Delete src/main/java/pers/xanadu/enderdragon/manager directory

This commit is contained in:
Xanadu13
2023-08-25 21:50:57 +08:00
committed by GitHub
parent 5b64f739ee
commit 3e926fd36d
9 changed files with 0 additions and 1547 deletions
@@ -1,25 +0,0 @@
package pers.xanadu.enderdragon.manager;
import pers.xanadu.enderdragon.util.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class DamageManager {
public static final ConcurrentHashMap<UUID, ConcurrentHashMap<String,Double>> data = new ConcurrentHashMap<>();
public static List<Pair<String,Double>> getDamageList(UUID uuid){
ConcurrentHashMap<String,Double> mp = data.get(uuid);
List<Pair<String,Double>> list = new ArrayList<>();
if(mp == null) return list;
mp.forEach((k,v)->list.add(new Pair<>(k,v)));
return list;
}
public static <T> int sortByDamage(Pair<T, Double> p1, Pair<T, Double> p2){
if(p2.second>p1.second) return 1;
if(p2.second.equals(p1.second)) return 0;
return -1;
}
}
@@ -1,463 +0,0 @@
package pers.xanadu.enderdragon.manager;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.boss.DragonBattle;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.*;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scoreboard.Team;
import pers.xanadu.enderdragon.config.Config;
import pers.xanadu.enderdragon.config.Lang;
import pers.xanadu.enderdragon.reward.RewardDist;
import pers.xanadu.enderdragon.util.MyDragon;
import pers.xanadu.enderdragon.util.Version;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import static pers.xanadu.enderdragon.EnderDragon.*;
public class DragonManager {
public static ArrayList<MyDragon> dragons = new ArrayList<>();
public static HashMap<String, MyDragon> mp = new HashMap<>();
public static List<String> dragon_names = new ArrayList<>();
private static int sum = 0;
private static final int[][] nxt = {{3,0},{0,3},{-3,0},{0,-3}};
private Method DragonBattle_e;
private Method getX;
private Method getY;
private Method getZ;
public static void reload(){
new BukkitRunnable(){
@Override
public void run(){
dragons.clear();
mp.clear();
dragon_names.clear();
sum = 0;
if(Config.dragon_setting_file == null){
Lang.error("\"dragon_setting_file\" in config.yml is empty!");
Lang.warn("Plugin will use the default config...");
Config.dragon_setting_file = new ArrayList<>();
Config.dragon_setting_file.add("default:5");
Config.dragon_setting_file.add("special:5");
}
for(String str : Config.dragon_setting_file){
String[] s = str.split(":");
if(s.length != 2){
Lang.error("\"dragon_setting_file\" in config.yml error! Key: " + str);
continue;
}
String path = "setting/" + s[0] + ".yml";
int edge = -1;
try {
edge = Integer.parseInt(s[1]);
} catch (NumberFormatException ignored){}
if(edge < 0) {
Lang.error("\"dragon_setting_file\" in config.yml error! Key: " + str);
continue;
}
File file = new File(plugin.getDataFolder(),path);
if(!file.exists()) {
try{
plugin.saveResource("setting/"+file.getName(),false);
file = new File(plugin.getDataFolder(),path);
}catch (Exception ignored){
Lang.error("Not Found setting/" + s[0] + ".yml ,skipped it.");
continue;
}
}
FileConfiguration fc = YamlConfiguration.loadConfiguration(file);
readSettingFile(fc,edge);
}
dragons.sort((o1, o2) -> o2.priority - o1.priority);
RewardManager.reload();
}
}.runTaskAsynchronously(plugin);
}
public static MyDragon judge(){
if(Config.special_dragon_jude_mode.equalsIgnoreCase("weight")){
int cnt = 0, random = ThreadLocalRandom.current().nextInt(0, sum);
for(MyDragon cur : dragons){
if(cnt <= random && cnt + cur.edge > random){
return cur;
}
cnt += cur.edge;
}
}
else if(Config.special_dragon_jude_mode.equalsIgnoreCase("pc")){
Iterator<MyDragon> it = dragons.iterator();
MyDragon cur = null;
while (it.hasNext()){
cur = it.next();
boolean judge = cur.spawn_chance > ThreadLocalRandom.current().nextDouble(100);
if(judge) return cur;
}
return cur;
}
else if(Config.special_dragon_jude_mode.equalsIgnoreCase("edge")){
int cnt = 0, random = ThreadLocalRandom.current().nextInt(0, sum);
for(MyDragon cur : dragons){
if(cnt <= random && cnt + cur.edge > random){
return cur;
}
cnt += cur.edge;
}
Lang.error("\"edge\" in \"special_dragon_jude_mode\" of config.yml is deprecated!Please use \"weight\" instead.");
}
return null;
}
public static void setSpecialKey(Entity e, String key){
e.addScoreboardTag(key);
}
public static String getSpecialKey(Entity e){
for(MyDragon a : dragons){
if(e.getScoreboardTags().contains(a.unique_name)) return a.unique_name;
}
return null;
}
public static void readSettingFile(FileConfiguration f,int edge){
MyDragon myDragon = new MyDragon();
myDragon.unique_name = f.getString("unique_name","default");
if(mp.containsKey(myDragon.unique_name)){
Lang.error("The unique_name conflict! Key: "+myDragon.unique_name);
return;
}
myDragon.icon = ItemManager.readFromBukkit(f,"icon");
myDragon.display_name = f.getString("display_name","Special Dragon");
myDragon.drop_gui = f.getString("drop_gui");
myDragon.edge = edge;
myDragon.priority = f.getInt("priority",1);
myDragon.spawn_chance = f.getDouble("spawn_chance",0);
myDragon.max_health = f.getInt("max_health",200);
myDragon.spawn_health = f.getInt("spawn_health",200);
myDragon.exp_drop = f.getInt("exp_drop",500);
myDragon.dragon_egg_spawn_delay = f.getInt("dragon_egg_spawn.delay",410);
myDragon.dragon_egg_spawn_x = f.getInt("dragon_egg_spawn.x",0);
myDragon.dragon_egg_spawn_y = f.getInt("dragon_egg_spawn.y",70);
myDragon.dragon_egg_spawn_z = f.getInt("dragon_egg_spawn.z",0);
myDragon.dragon_egg_spawn_chance = f.getDouble("dragon_egg_spawn.chance",0);
myDragon.attack_damage_modify = f.getDouble("attack_damage_modify",0);
//myDragon.move_speed_modify = f.getDouble("move_speed_modify",0);
myDragon.armor_modify = f.getDouble("armor_modify",0);
myDragon.armor_toughness_modify = f.getDouble("armor_toughness_modify",0);
myDragon.crystal_heal_speed = f.getDouble("crystal_heal_speed",2.0);
myDragon.suck_blood_enable = f.getBoolean("suck_blood.enable",true);
myDragon.suck_blood_rate = f.getDouble("suck_blood.rate",50) / 100d;
myDragon.suck_blood_base_amount = f.getDouble("suck_blood.base_amount",1);
myDragon.suck_blood_only_player = f.getBoolean("suck_blood.only_player",true);
List<String> stringList = f.getStringList("attack_potion_effect");
List<PotionEffect> potions = new ArrayList<>();
for(String string : stringList){
String[] s = string.split(" ");
if(s.length != 3) continue;
PotionEffectType type = PotionEffectType.getByName(s[0].toUpperCase());
if(type == null){
Lang.error("Unknown potion type: " + s[0]);
continue;
}
int duration = -1;
try {
duration = Integer.parseInt(s[1]);
} catch (NumberFormatException ex){
Lang.error("Wrong number format: " + s[1]);
}
if(duration == -1) continue;
int level = -1;
try {
level = Integer.parseInt(s[2]);
} catch (NumberFormatException ex){
Lang.error("Wrong number format: " + s[2]);
}
if(level == -1) continue;
PotionEffect potionEffect = new PotionEffect(type,duration*20,level-1);
potions.add(potionEffect);
}
myDragon.attack_potion_effect = potions;
myDragon.spawn_cmd = f.getStringList("spawn_cmd");
myDragon.death_cmd = f.getStringList("death_cmd");
myDragon.spawn_broadcast_msg = f.getStringList("spawn_broadcast_msg");
myDragon.death_broadcast_msg = f.getStringList("death_broadcast_msg");
myDragon.msg_to_killer = f.getStringList("msg_to_killer");
myDragon.glow_color = f.getString("glow_color","random");
myDragon.bossbar_color = f.getString("bossbar.color","WHITE");
myDragon.bossbar_style = f.getString("bossbar.style","SOLID");
myDragon.effect_cloud_original_radius = f.getDouble("effect_cloud.original_radius",3);
myDragon.effect_cloud_expand_speed = f.getDouble("effect_cloud.expand_speed",0.1333333);
myDragon.effect_cloud_duration = f.getInt("effect_cloud.duration",60);
String effect_cloud_color = f.getString("effect_cloud.color","none");
String[] s0 = effect_cloud_color.split(":");
if(s0.length != 3) myDragon.effect_cloud_color_R = -1;
else{
try{
myDragon.effect_cloud_color_R = Integer.parseInt(s0[0]);
myDragon.effect_cloud_color_G = Integer.parseInt(s0[1]);
myDragon.effect_cloud_color_B = Integer.parseInt(s0[2]);
}
catch (NumberFormatException e){
Lang.error("Wrong effect_cloud_color format!");
myDragon.effect_cloud_color_R = -1;
}
}
List<String> stringList2 = f.getStringList("effect_cloud.potion");
List<PotionEffect> effectCloudPotions = new ArrayList<>();
for(String string : stringList2){
String[] s = string.split(" ");
if(s.length != 3) continue;
PotionEffectType type = PotionEffectType.getByName(s[0].toUpperCase());
if(type == null){
Lang.error("Unknown potion type: " + s[0]);
continue;
}
int duration = -1;
try {
duration = Integer.parseInt(s[1]);
} catch (NumberFormatException ex){
Lang.error("Wrong number format: " + s[1]);
}
if(duration == -1) continue;
int level = -1;
try {
level = Integer.parseInt(s[2]);
} catch (NumberFormatException ex){
Lang.error("Wrong number format: " + s[2]);
}
if(level == -1) continue;
PotionEffect potionEffect = new PotionEffect(type,duration*20,level-1);
effectCloudPotions.add(potionEffect);
}
myDragon.effect_cloud_potion = effectCloudPotions;
myDragon.reward_dist = RewardDist.parse(f.getConfigurationSection("reward_dist"));
dragons.add(myDragon);
mp.put(myDragon.unique_name,myDragon);
dragon_names.add(myDragon.unique_name);
sum += edge;
}
public static void disable(){
dragons.clear();
mp.clear();
dragon_names.clear();
}
public static void setAttribute(EnderDragon dragon, Attribute attribute, double amount){
AttributeInstance instance = dragon.getAttribute(attribute);
assert instance != null;
instance.setBaseValue(amount);
}
public static void modifyAttribute(EnderDragon dragon, Attribute attribute, double amount){
AttributeInstance instance = dragon.getAttribute(attribute);
assert instance != null;
instance.addModifier(new AttributeModifier("EnderDragon",amount,AttributeModifier.Operation.ADD_NUMBER));
}
public void initiateRespawn(Player p){
DragonRespawnResult res = initiateRespawn(p.getWorld());
if(res == DragonRespawnResult.success) Lang.broadcastMSG(Lang.dragon_auto_respawn);
else Lang.sendFeedback(p,"§c"+res.getMessage());
}
public void initiateRespawn(CommandSender sender, String world_name){
DragonRespawnResult res = initiateRespawn(Bukkit.getWorld(world_name));
if(res == DragonRespawnResult.success) Lang.broadcastMSG(Lang.dragon_auto_respawn);
else Lang.sendFeedback(sender,"§c"+res.getMessage());
}
public void initiateRespawn(String world_name){
DragonRespawnResult res = initiateRespawn(Bukkit.getWorld(world_name));
if(res == DragonRespawnResult.success) Lang.broadcastMSG(Lang.dragon_auto_respawn);
else Lang.error(res.getMessage());
}
public boolean canRespawn(String world_name){
return canRespawn(Bukkit.getWorld(world_name));
}
public boolean canRespawn(World world){
if(world == null) return false;
if(world.getEnvironment() != World.Environment.THE_END) return false;
if(Version.mcMainVersion >= 16){//executes 1e5 times within 27ms
DragonBattle battle = world.getEnderDragonBattle();
if(battle == null) return false;
if(battle.getEnderDragon() != null) return false;
if(battle.getRespawnPhase() != DragonBattle.RespawnPhase.NONE) return false;
Location cen = battle.getEndPortalLocation();
if(cen == null) {
battle.initiateRespawn();
cen = battle.getEndPortalLocation();
if(cen == null){
return false;
}
}
return true;
}
try {//executes 1e5 times within 76ms
Object battle = getInstance().getNMSManager().getEnderDragonBattle(world);
if(battle == null) return false;
Field k = battle.getClass().getDeclaredField("k");
k.setAccessible(true);
Object isAlive = k.get(battle);
if(!((boolean) isAlive)) return false;
Field p = battle.getClass().getDeclaredField("p");
p.setAccessible(true);
Object phase = p.get(battle);
if(phase != null) return false;
Field field = battle.getClass().getDeclaredField("o");
field.setAccessible(true);
Object BlockPosition = field.get(battle);
if(BlockPosition == null){
if (this.DragonBattle_e == null) this.DragonBattle_e = battle.getClass().getMethod("e");
this.DragonBattle_e.invoke(battle);
BlockPosition = field.get(battle);
if(BlockPosition == null) return false;
}
return true;
} catch (ReflectiveOperationException e) {
return false;
}
}
public boolean isRespawnRunning(World world){
if(world == null) return false;
if(world.getEnvironment() != World.Environment.THE_END) return false;
if(Version.mcMainVersion >= 16){
DragonBattle battle = world.getEnderDragonBattle();
assert battle != null;
return battle.getRespawnPhase() != DragonBattle.RespawnPhase.NONE;
}
try {
Object battle = getInstance().getNMSManager().getEnderDragonBattle(world);
assert battle != null;
Field p = battle.getClass().getDeclaredField("p");
p.setAccessible(true);
Object phase = p.get(battle);
return phase != null;
} catch (ReflectiveOperationException e) {
e.printStackTrace();
return false;
}
}
public void refresh_respawn(World world){
if(world == null) return;
if(world.getEnvironment() != World.Environment.THE_END) return;
if(Version.mcMainVersion >= 16){
DragonBattle battle = world.getEnderDragonBattle();
assert battle != null;
battle.initiateRespawn();
return;
}
try {
Object battle = getInstance().getNMSManager().getEnderDragonBattle(world);
assert battle != null;
if (this.DragonBattle_e == null) this.DragonBattle_e = battle.getClass().getMethod("e");
this.DragonBattle_e.invoke(battle);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
private DragonRespawnResult initiateRespawn(World world){
if(world == null) return DragonRespawnResult.world_not_found;
if(world.getEnvironment() != World.Environment.THE_END) return DragonRespawnResult.world_wrong_env;
if(Version.mcMainVersion >= 16){
DragonBattle battle = world.getEnderDragonBattle();
assert battle != null;
if(battle.getEnderDragon() != null) return DragonRespawnResult.dragon_has_existed;
if(battle.getRespawnPhase() != DragonBattle.RespawnPhase.NONE) return DragonRespawnResult.respawn_has_started;
Location cen = battle.getEndPortalLocation();
if(cen == null) {
battle.initiateRespawn();
cen = battle.getEndPortalLocation();
if(cen == null){
return DragonRespawnResult.world_unloaded;//也可尝试chunk.load()
}
}
placeEndCrystals(world,cen);
battle.initiateRespawn();
return DragonRespawnResult.success;
}
try {
Object battle = getInstance().getNMSManager().getEnderDragonBattle(world);
assert battle != null;
Field k = battle.getClass().getDeclaredField("k");
k.setAccessible(true);
Object isAlive = k.get(battle);
if(!((boolean) isAlive)) return DragonRespawnResult.dragon_has_existed;
Field p = battle.getClass().getDeclaredField("p");
p.setAccessible(true);
Object phase = p.get(battle);
if(phase != null) return DragonRespawnResult.respawn_has_started;
Field field = battle.getClass().getDeclaredField("o");
field.setAccessible(true);
Object BlockPosition = field.get(battle);
if(BlockPosition == null){
if (this.DragonBattle_e == null) this.DragonBattle_e = battle.getClass().getMethod("e");
this.DragonBattle_e.invoke(battle);
BlockPosition = field.get(battle);
if(BlockPosition == null) return DragonRespawnResult.world_unloaded;
}
if(this.getX == null) this.getX = BlockPosition.getClass().getMethod("getX");
if(this.getY == null) this.getY = BlockPosition.getClass().getMethod("getY");
if(this.getZ == null) this.getZ = BlockPosition.getClass().getMethod("getZ");
Location loc = new Location(world,(int)getX.invoke(BlockPosition),(int)this.getY.invoke(BlockPosition),(int)this.getZ.invoke(BlockPosition));
placeEndCrystals(world, loc);
if (this.DragonBattle_e == null) this.DragonBattle_e = battle.getClass().getMethod("e");
this.DragonBattle_e.invoke(battle);
return DragonRespawnResult.success;
} catch (ReflectiveOperationException e) {
return DragonRespawnResult.version_not_support;
}
}
private void placeEndCrystals(World world, Location cen){
cen.add(0.5,1,0.5);
for(int i = 0; i < 4; i++){
EnderCrystal crystal = (EnderCrystal) world.spawnEntity(cen.clone().add(nxt[i][0],0,nxt[i][1]), EntityType.ENDER_CRYSTAL);
if(Config.auto_respawn_invulnerable) crystal.setInvulnerable(true);
crystal.setShowingBottom(false);
}
}
public enum DragonRespawnResult{
success,
world_not_found,
world_unloaded,
world_wrong_env,
respawn_has_started,
dragon_has_existed,
version_not_support;
public String getMessage(){
switch (this){
case success: return "Success";
case world_not_found: return "Can't find this world!";
case world_unloaded: return "The world_the_end is unloaded.";
case world_wrong_env: return "Respawn only can be called in the End.";
case respawn_has_started: return "The respawning has already started.";
case dragon_has_existed: return "There is already a dragon here.";
case version_not_support: return "Your server version (" + Version.getVersion() + ") is not supported!";
default: return "Unknown error!";
}
}
}
}
// try {
// Object WorldServer = getInstance().getNMSManager().getWorldServer(world);
// Field Z = WorldServer.getClass().getDeclaredField("Z");
// Z.setAccessible(true);
// Object edb = Z.get(WorldServer);
// Class<?> edb_clazz = Class.forName("net.minecraft.world.level.dimension.end.EnderDragonBattle");
// Method a = edb_clazz.getMethod("a");
// a.invoke(edb);
// Field y = edb_clazz.getDeclaredField("y");
// y.setAccessible(true);
// Object bp = y.get(edb);
// if(bp == null) Bukkit.broadcastMessage("123");
// }catch (ReflectiveOperationException e){
// e.printStackTrace();
// }
@@ -1,76 +0,0 @@
package pers.xanadu.enderdragon.manager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import pers.xanadu.enderdragon.util.Version;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
public class GlowManager {
public static Set<Scoreboard> handled = new HashSet<>();
public static void reload(){
handled.clear();
}
public static void setScoreBoard(Player p){
Scoreboard board = p.getScoreboard();
if(handled.contains(board)) return;
ChatColor[] colors = ChatColor.values();
for(ChatColor color : colors){
String name = "ed-"+color.name();
if(board.getTeam(name)==null) board.registerNewTeam(name);
Team team = board.getTeam(name);
assert team != null;
if(Version.mcMainVersion >= 13) team.setColor(color);
else team.setPrefix(color.toString());
}
handled.add(board);
}
public static void addUUID(String uuid,String color){
Set<Team> teams = new HashSet<>();
Bukkit.getOnlinePlayers().forEach(player -> {
GlowManager.setScoreBoard(player);
Team team = player.getScoreboard().getTeam("ed-"+color.toUpperCase());
teams.add(team);
});
teams.forEach(team->{
team.addEntry(uuid);
});
}
public static void setGlowingColor(Entity entity, ChatColor color){
Set<Team> teams = new HashSet<>();
Bukkit.getOnlinePlayers().forEach(player -> {
GlowManager.setScoreBoard(player);
Team team = player.getScoreboard().getTeam("ed-"+color.name());
teams.add(team);
});
teams.forEach(team->{
team.addEntry(entity.getUniqueId().toString());
entity.setGlowing(true);
});
}
public static ChatColor getGlowColor(String str){
ChatColor chatColor;
if(str.equals("RANDOM")) chatColor = randomColor();
else chatColor = ChatColor.valueOf(str);
return chatColor;
}
public static ChatColor getGlowColor(GlowColor glowColor){
if(glowColor == GlowColor.NONE) return null;
if(glowColor == GlowColor.RANDOM) return randomColor();
return ChatColor.valueOf(glowColor.name());
}
public static ChatColor randomColor(){
return ChatColor.values()[ThreadLocalRandom.current().nextInt(16)];
}
public enum GlowColor{
AQUA,BLACK,BLUE,DARK_AQUA,DARK_BLUE,DARK_GRAY,DARK_GREEN,DARK_PURPLE,DARK_RED,GOLD,GRAY,GREEN,LIGHT_PURPLE,RED,WHITE,YELLOW,
NONE,RANDOM
}
}
@@ -1,76 +0,0 @@
package pers.xanadu.enderdragon.manager;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import pers.xanadu.enderdragon.config.Lang;
import pers.xanadu.enderdragon.gui.GUIWrapper;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import static pers.xanadu.enderdragon.EnderDragon.plugin;
public class GuiManager {
private static HashMap<String, GUIWrapper> f = new HashMap<>();
public static void loadGui(){
new BukkitRunnable(){
@Override
public void run(){
File folder = new File(plugin.getDataFolder(),"gui");
if(!folder.exists()) return;
File[] files = folder.listFiles();
if(files == null) return;
for(File file : files){
if(!file.getName().endsWith(".yml")) continue;
Lang.info(Lang.plugin_read_file + file.getName());
FileConfiguration fileConfiguration = YamlConfiguration.loadConfiguration(file);
Iterator it = fileConfiguration.getKeys(false).iterator();
while (it.hasNext()){
String name = (String) it.next();
ConfigurationSection section = fileConfiguration.getConfigurationSection(name);
GUIWrapper guiWrapper = new GUIWrapper(section);
f.put(name, guiWrapper);
}
}
}
}.runTaskAsynchronously(plugin);
}
public static void disable(){
f.clear();
}
public static void openGui(Player player, String name, boolean editor) {
if (!f.containsKey(name)) {
Lang.sendFeedback(player,Lang.gui_not_found);
return;
}
player.openInventory(new GUIWrapper(f.get(name),name,editor).current());
}
public static void openGui(Player player,String style,String key, boolean editor){
if (!f.containsKey(style)) {
Lang.sendFeedback(player,Lang.gui_not_found);
return;
}
player.openInventory(new GUIWrapper(f.get(style),key,editor).current());
}
@Deprecated
public static void openGui(Player player, String name) {
if (!f.containsKey(name)) {
Lang.sendFeedback(player,Lang.gui_not_found);
return;
}
player.openInventory(new GUIWrapper(f.get(name),name,false).current());
}
@Deprecated
public static void openGui(Player player,String style,String key){
if (!f.containsKey(style)) {
Lang.sendFeedback(player,Lang.gui_not_found);
return;
}
player.openInventory(new GUIWrapper(f.get(style),key,false).current());
}
}
@@ -1,426 +0,0 @@
package pers.xanadu.enderdragon.manager;
import org.bukkit.Material;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.Repairable;
import org.bukkit.persistence.PersistentDataContainer;
import pers.xanadu.enderdragon.EnderDragon;
import pers.xanadu.enderdragon.config.Config;
import pers.xanadu.enderdragon.reward.Reward;
import pers.xanadu.enderdragon.reward.Chance;
import pers.xanadu.enderdragon.util.Version;
import java.util.*;
public class ItemManager {
public static String write(Reward reward){
Chance chance = reward.getChance();
return write(reward.getItem(),chance.getValue(),chance.getStr(),reward.getName());
}
public static String write(ItemStack item,double value,String str,String name){
YamlConfiguration yaml = new YamlConfiguration();
if(name == null){
ItemMeta meta = item.getItemMeta();
if(meta != null) {
String displayName = meta.getDisplayName();
if("".equals(displayName) || displayName == null){
name = item.getType().name().toLowerCase() + "(" + TaskManager.getCurrentTimeWithSpecialFormat() + ")";
}
else name = meta.getDisplayName();
}
else name = item.getType().name().toLowerCase() + "(" + TaskManager.getCurrentTimeWithSpecialFormat() + ")";
}
ConfigurationSection section = yaml.createSection(name);
switch(Config.item_format_data){
case "nbt" : {
section.set("data_type","nbt");
section.set("data",EnderDragon.getInstance().getNMSManager().getNBT(item));
break;
}
case "advanced" : {
section.set("data_type","advanced");
ConfigurationSection section_data = section.createSection("data");
//type
String type = item.getType().name();
section_data.set("type",type);
if("AIR".equals(type)) break;
//amount
int amount = item.getAmount();
section_data.set("amount",amount);
//damage
int damage = item.getDurability();
if(damage != 0) section_data.set("damage",damage);
ItemMeta meta = item.getItemMeta();
if(meta == null) break;
//DisplayName
String display_name = meta.getDisplayName();
if(!"".equals(display_name)) section_data.set("display_name",display_name);
//LocalizedName
if(meta.hasLocalizedName()){
section_data.set("localized_name",meta.getLocalizedName());
}
//lore
List<String> lores = meta.getLore();
if(lores != null) section_data.set("lore",lores);
//Enchantments
if(meta.hasEnchants()){
ConfigurationSection enchants = section_data.createSection("enchants");
Map<Enchantment,Integer> mp = meta.getEnchants();
mp.forEach((enchantment,level) -> enchants.set(enchantment.getName(),level));
}
if(Version.mcMainVersion>=14 || "v1_13_R2".equals(Version.getVersion())){
//AttributeModifiers
if(meta.hasAttributeModifiers()){
ConfigurationSection attributes = section_data.createSection("AttributeModifiers");
meta.getAttributeModifiers().forEach((attribute,modifier)->{
attributes.set(attribute.name(),modifier);
});
}
}
if(Version.mcMainVersion>=14){
//CustomModelData
if(meta.hasCustomModelData()) {
section_data.set("CustomModelData",meta.getCustomModelData());//int
}
//PersistentDataContainer
PersistentDataContainer dataContainer = meta.getPersistentDataContainer();
if(!dataContainer.isEmpty()){
ConfigurationSection dataContainer_section = section_data.createSection("PersistentDataContainer");
String cpd = EnderDragon.getInstance().getNMSManager().PDCtoString(dataContainer);
dataContainer_section.set("data_type","nbt");
dataContainer_section.set("data",cpd);
}
}
//RepairCost
if(meta instanceof Repairable){
Repairable repairable = (Repairable) meta;
section_data.set("RepairCost",repairable.getRepairCost());
}
//ItemFlags
Set<ItemFlag> flags = meta.getItemFlags();
if(!flags.isEmpty()){
List<String> list = new ArrayList<>();
flags.forEach(flag ->{
list.add(flag.name());
});
section_data.set("ItemFlags",list);
}
//Unbreakable
section_data.set("unbreakable",meta.isUnbreakable());
//internal
Object cpd = EnderDragon.getInstance().getNMSManager().getCPD(item);
Map<String,Object> mp = EnderDragon.getInstance().getNMSManager().cpdToMap(cpd);
if(mp.containsKey("tag")){
cpd = mp.get("tag");
mp = EnderDragon.getInstance().getNMSManager().cpdToMap(cpd);
mp.remove("Damage");
if(mp.containsKey("display")){
Object display = mp.get("display");
Map<String,Object> display_mp = EnderDragon.getInstance().getNMSManager().cpdToMap(display);
display_mp.remove("Name");
display_mp.remove("LocName");
display_mp.remove("Lore");
Object new_display = EnderDragon.getInstance().getNMSManager().getNBTTagCompound(display_mp);
mp.put("display",new_display);
}
//mp.remove("display");//Name, LocName, Lore, color
mp.remove("Enchantments");
mp.remove("AttributeModifiers");
mp.remove("CustomModelData");
mp.remove("PublicBukkitValues");//PersistentDataContainer
mp.remove("RepairCost");
mp.remove("HideFlags");//ItemFlags
mp.remove("Unbreakable");
//CanDestroy, CanPlaceOn
Object new_cpd = EnderDragon.getInstance().getNMSManager().getNBTTagCompound(mp);
ConfigurationSection internal = section_data.createSection("internal");
internal.set("data_type","nbt");
internal.set("data",new_cpd.toString());
}
// Map<String,Object> mp = EnderDragon.getInstance().getNMSManager().getUnhandledTags(meta);
// if(mp != null){
// ConfigurationSection internal = section_data.createSection("internal");
// saveUnhandledTags(internal,mp);
// }
break;
}
default : {
section.set("data_type","default");
section.set("data", item);
}
}
section.set("drop_chance.value",value);
section.set("drop_chance.format",str);
return yaml.saveToString();
}
public static Reward readAsReward(ConfigurationSection section){
Set<String> strings = section.getKeys(false);
String name = strings.iterator().next();
ConfigurationSection section0 = section.getConfigurationSection(name);
if(section0 == null) return null;
String data_type = section0.getString("data_type");
//data_type may be null
ItemStack item;
if("nbt".equals(data_type)) item = readFromNBT(section0,"data");
else if("advanced".equals(data_type)) item = readFromAdvData(section0, "data");
else item = readFromBukkit(section0,"data");
double d0 = section0.getDouble("drop_chance.value");
String str = section0.getString("drop_chance.format");
return new Reward(item,new Chance(d0, str));
}
public static ItemStack readFromAdvData(ConfigurationSection section, String path){
ConfigurationSection data = section.getConfigurationSection(path);
if(data == null) return new ItemStack(Material.AIR);
String type = data.getString("type");
if(type == null || "AIR".equals(type)) return new ItemStack(Material.AIR);
int amount = data.getInt("amount");
Material material = Material.getMaterial(type);
if(material == null) return new ItemStack(Material.AIR);
ItemStack item = new ItemStack(material,amount);
//internal
if(data.contains("internal")){
ConfigurationSection internal_section = data.getConfigurationSection("internal");
if(internal_section!=null){
if("nbt".equals(internal_section.getString("data_type"))){
String nbt = internal_section.getString("data");
Object cpd = EnderDragon.getInstance().getNMSManager().getCPD(nbt);
Map<String,Object> mp_tag = new HashMap<>();
mp_tag.put("tag",cpd);
Object full_cpd = EnderDragon.getInstance().getNMSManager().getNBTTagCompound(mp_tag);
item = EnderDragon.getInstance().getNMSManager().mergeItemCPD(item,full_cpd);
}
// else{
// Map<String,Object> mp = getUnhandledTags(internal_section);
// EnderDragon.getInstance().getNMSManager().setUnhandledTags(meta,mp);
// }
// Map<String,Object> mp = new HashMap<>();
// internal_section.getKeys(false).forEach(key->{
// Object obj = internal_section.get(key);//obj instanceof String
// Object nbt_base = EnderDragon.getInstance().getNMSItemManager().readAsNBTBase((String) obj);
// mp.put(key,nbt_base);
// });
// Map<String,Object> mp = getUnhandledTags(internal_section);
// NBTTagCompound cpd = getNBTTagCompound(mp);
// net.minecraft.world.item.ItemStack ei = CraftItemStack.asNMSCopy(item);
// ei.c(cpd);
// item = CraftItemStack.asBukkitCopy(ei);
//EnderDragon.getInstance().getNMSManager().setUnhandledTags(meta,mp);
}
}
//damage
if(data.contains("damage")){
int damage = data.getInt("damage");
item.setDurability((short) damage);
}
ItemMeta meta = item.getItemMeta();
if(meta == null) return item;
//DisplayName
String display_name = data.getString("display_name");
if(display_name != null) meta.setDisplayName(display_name);
//LocalizedName
if(data.contains("localized_name")){
String LocalizedName = data.getString("localized_name");
if(LocalizedName != null) meta.setLocalizedName(LocalizedName);
}
//lore
if(data.contains("lore")){
List<String> lores = data.getStringList("lore");
if(!lores.isEmpty()) meta.setLore(lores);
}
//Enchantments
if(data.contains("enchants")){
ConfigurationSection enchants = data.getConfigurationSection("enchants");
if(enchants != null){
//Map<Enchantment,Integer> mp = new HashMap<>();
enchants.getKeys(false).forEach(key->{
Enchantment enchantment = Enchantment.getByName(key);
int level = enchants.getInt(key);
if(enchantment != null && level>0){
meta.addEnchant(enchantment,level,true);
}
});
}
}
//CustomModelData
if(data.contains("CustomModelData")){
int CustomModelData = data.getInt("CustomModelData");
meta.setCustomModelData(CustomModelData);
}
//AttributeModifiers
if(data.contains("AttributeModifiers")){
ConfigurationSection attributes = data.getConfigurationSection("AttributeModifiers");
if(attributes != null){
attributes.getKeys(false).forEach(name->{
Attribute attribute = Attribute.valueOf(name);
AttributeModifier modifier = (AttributeModifier) attributes.get(name);
if(modifier != null){
meta.addAttributeModifier(attribute,modifier);
}
});
}
}
//RepairCost
if(data.contains("RepairCost")){
int cost = data.getInt("RepairCost");
if(meta instanceof Repairable){
((Repairable)meta).setRepairCost(cost);
}
}
//ItemFlags
if(data.contains("ItemFlags")){
List<String> names = data.getStringList("ItemFlags");
names.forEach(name->meta.addItemFlags(ItemFlag.valueOf(name)));
}
//Unbreakable
if(data.contains("unbreakable") && data.getBoolean("unbreakable")) meta.setUnbreakable(true);
//PersistentDataContainer
if(data.contains("PersistentDataContainer")){
ConfigurationSection dataContainer_section = data.getConfigurationSection("PersistentDataContainer");
if(dataContainer_section != null){
if("nbt".equals(dataContainer_section.getString("data_type"))){
String nbt = dataContainer_section.getString("data");
Object cpd = EnderDragon.getInstance().getNMSManager().getCPD(nbt);
PersistentDataContainer container = meta.getPersistentDataContainer();
EnderDragon.getInstance().getNMSManager().setPersistentDataContainer(container, cpd);
}
}
}
item.setItemMeta(meta);
return item;
}
public static ItemStack readFromNBT(ConfigurationSection section, String path){
String nbt = section.getString(path);
if (nbt == null) return new ItemStack(Material.AIR);
return EnderDragon.getInstance().getNMSItemManager().readAsItem(nbt);
}
public static ItemStack readFromBukkit(ConfigurationSection section, String path){
String nbt = section.getString(path);
if (nbt == null) return new ItemStack(Material.AIR);
return section.getItemStack(path);
}
public static ItemStack readFromString(String str){
YamlConfiguration yml = new YamlConfiguration();
yml.set("test",str);
return yml.getItemStack("test");
}
public static void addLoreFront(ItemStack item, String lore){
ItemMeta meta = item.getItemMeta();
if(meta != null) {
List<String> lores = meta.getLore();
if (lores != null) {
lores.add(0,lore);
meta.setLore(lores);
}
else {
meta.setLore(Collections.singletonList(lore));
}
item.setItemMeta(meta);
}
}
public static void addLoreBack(ItemStack item, String lore){
ItemMeta meta = item.getItemMeta();
if(meta != null) {
List<String> lores = meta.getLore();
if (lores != null) {
lores.add(lore);
meta.setLore(lores);
}
else {
meta.setLore(Collections.singletonList(lore));
}
item.setItemMeta(meta);
}
}
public static boolean isEmpty(ItemStack item){
if(item == null) return true;
if(item.getType() == Material.AIR) return true;
return false;
}
private static void saveUnhandledTags(ConfigurationSection section, Map<String,Object> mp){
mp.forEach((k,v)->{
//Bukkit.broadcastMessage(k+": "+v.getClass().toString());
if(v instanceof Map){
saveUnhandledTags(section.createSection(k), (Map<String, Object>) v);
}
else section.set(k,v.toString());
});
}
/**
private static void saveUnhandledTags(ConfigurationSection section, Map<String,Object> mp){
mp.forEach((k,v)->{
Object obj = v;
//Bukkit.broadcastMessage(obj.getClass().toString());
try{
obj = EnderDragon.getInstance().getNMSItemManager().parseNBT(v);
}catch (Throwable ignored){
}
if(obj instanceof Map){
saveUnhandledTags(section.createSection(k), (Map<String, Object>) obj);
}
else section.set(k,obj);
});
}**/
private static Map<String, Object> getUnhandledTags(ConfigurationSection section){
Map<String,Object> res = new HashMap<>();
section.getKeys(false).forEach(key->{
Object obj = section.get(key);
if(obj instanceof ConfigurationSection){
ConfigurationSection subSection = section.getConfigurationSection(key);
if(subSection != null){
obj = getUnhandledTags(subSection);
// Object mp = getUnhandledTags(subSection);
// Bukkit.getLogger().info(mp.getClass().toString());
// try{
// obj = EnderDragon.getInstance().getNMSItemManager().getNBTBase(mp);
// }catch (Throwable throwable){
//
// }
}
}
else obj = EnderDragon.getInstance().getNMSManager().getCPD((String) obj);
//else obj = EnderDragon.getInstance().getNMSItemManager().readAsNBTBase((String) obj);
res.put(key,obj);
});
return res;
}
// private static Object dfs(ConfigurationSection section){
// section.getKeys(false).forEach(key->{
// Object obj = section.get(key);
// if(obj instanceof ConfigurationSection){
// ConfigurationSection subSection = section.getConfigurationSection(key);
// if(subSection != null) obj = dfs(subSection);
// }
// else obj = EnderDragon.getInstance().getNMSItemManager().readAsNBTBase((String) obj);
//
// });
// return
// }
// //internal
// Map<String,Object> mp = EnderDragon.getInstance().getNMSManager().getUnhandledTags(meta);
// if(mp != null){
// ConfigurationSection internal = section_data.createSection("internal");
// mp.forEach((k,v)->{
// Object obj = EnderDragon.getInstance().getNMSItemManager().parseNBT(v);
//
// if(obj instanceof Map) obj = obj.toString();
// else if(obj instanceof List) obj = obj.toString();
//
// internal.set(k,obj);
// });
// }
}
@@ -1,117 +0,0 @@
package pers.xanadu.enderdragon.manager;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import pers.xanadu.enderdragon.config.Lang;
import pers.xanadu.enderdragon.reward.Reward;
import pers.xanadu.enderdragon.reward.Chance;
import pers.xanadu.enderdragon.util.MyDragon;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import static pers.xanadu.enderdragon.EnderDragon.*;
public class RewardManager {
public static void reload(){
for(MyDragon dragon : DragonManager.dragons){
dragon.datum.clear();
File file = getRewardFile(dragon.unique_name);
if(file == null) return;
FileConfiguration data = YamlConfiguration.loadConfiguration(file);
String path = "list";
List<String> list = data.getStringList(path);
// if list == null ?
for(String str : list){
YamlConfiguration yml = new YamlConfiguration();
try{
yml.loadFromString(str);
Reward reward = ItemManager.readAsReward(yml);
dragon.datum.add(reward);
}catch (InvalidConfigurationException e){
Lang.error(Lang.plugin_item_read_error + str);
}
}
}
}
public static void addItem(String key,Reward reward){
addItem(key,reward.getItem(),reward.getChance());
}
public static void addItem(String key, ItemStack item, Chance chance){
MyDragon dragon = DragonManager.mp.get(key);
if(dragon == null) return;
File file = getRewardFile(dragon.unique_name);
if(file == null) return;
FileConfiguration data = YamlConfiguration.loadConfiguration(file);
String path = "list";
List<String> list = data.getStringList(path);
Reward reward = new Reward(item,chance);
list.add(reward.toString());
data.set(path,list);
try {
data.save(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
dragon.datum.add(reward);
}
public static void clearItem(String key){
MyDragon dragon = DragonManager.mp.get(key);
if(dragon == null) return;
File file = getRewardFile(dragon.unique_name);
if(file == null) return;
FileConfiguration data = YamlConfiguration.loadConfiguration(file);
String path = "list";
data.set(path,"");
try {
data.save(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
dragon.datum.clear();
}
public static boolean removeItem(String key,int idx){
MyDragon dragon = DragonManager.mp.get(key);
if(dragon == null) return false;
File file = getRewardFile(dragon.unique_name);
if(file == null) return false;
FileConfiguration data = YamlConfiguration.loadConfiguration(file);
String path = "list";
List<String> list = data.getStringList(path);
try{
list.remove(idx);
data.set(path,list);
data.save(file);
dragon.datum.remove(idx);
return true;
}catch (IndexOutOfBoundsException e){
Lang.error("Index out of bound!");
}catch (IOException e) {
throw new RuntimeException(e);
}
return false;
}
private static File getRewardFile(String key){
String file_path = "reward/" + key + ".yml";
File file = new File(plugin.getDataFolder(),file_path);
if(!file.exists()) {
try{
YamlConfiguration yml = new YamlConfiguration();
yml.set("version","2.1.0");
yml.set("list","");
yml.save(file);
}catch (IOException e){
Lang.error("Not Found "+file_path+" ,skipped it.");
return null;
}
}
return new File(plugin.getDataFolder(),file_path);
}
}
@@ -1,93 +0,0 @@
package pers.xanadu.enderdragon.manager;
import pers.xanadu.enderdragon.config.Config;
import pers.xanadu.enderdragon.config.Lang;
import pers.xanadu.enderdragon.task.type.*;
import pers.xanadu.enderdragon.task.Task;
import pers.xanadu.enderdragon.task.TaskType;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import static pers.xanadu.enderdragon.EnderDragon.*;
public class TaskManager {
private static final DateTimeFormatter RoundTimeFormat_hm = DateTimeFormatter.ofPattern("HH:mm");
private static final DateTimeFormatter RoundTimeFormat_all = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
public static String path = "auto_respawn.next_respawn_time";
public static Task task = null;
public static Task parse(String string){
String[] str = string.split(":",2);
TaskType taskType = TaskType.getByName(str[0]);
switch (taskType){
case minute : {
return new Minute(TaskType.minute,str[1]);
}
case hour : {
return new Hour(TaskType.hour,str[1]);
}
case day : {
return new Day(TaskType.day,str[1]);
}
case week : {
return new Week(TaskType.week,str[1]);
}
case month : {
return new Month(TaskType.month,str[1]);
}
case year : {
return new Year(TaskType.year,str[1]);
}
default : {
return null;
}
}
}
public static void reload(){
task = parse(Config.auto_respawn_respawn_time);
}
public static LocalTime getRoundTime(String str){
try {
return LocalTime.parse(str, RoundTimeFormat_hm);
}catch (DateTimeParseException e){
Lang.error("\"respawn_time\" in config.yml error!The format of time should be HH:mm.");
}
return null;
}
public static String getRoundTimeStr(LocalDateTime time){
return time.format(RoundTimeFormat_all);
}
public static LocalDateTime getLocalDateTime(String str){
if(isValidTime(str)) return LocalDateTime.parse(str, RoundTimeFormat_all);
return null;
}
public static boolean isValidTime(String str){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try{
df.parse(str);
} catch (ParseException e) {
Lang.error("\"next_respawn_time\" in data.yml error!The format of time should be HH:mm.");
return false;
}
return true;
}
public static void saveFile(LocalDateTime nextTime){
data.set(TaskManager.path,getRoundTimeStr(nextTime));
try{
data.save(dataF);
}catch (IOException ex){
Lang.error(Lang.plugin_file_save_error.replaceAll("\\{file_name}",dataF.getName()));
}
}
public static String getCurrentTimeWithSpecialFormat(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HHmmss");//这里的∶是特殊字符
return df.format(new Date());
}
}
@@ -1,75 +0,0 @@
package pers.xanadu.enderdragon.manager;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import pers.xanadu.enderdragon.config.Lang;
import pers.xanadu.enderdragon.task.DragonRespawnTimer;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import static pers.xanadu.enderdragon.EnderDragon.plugin;
public class TimerManager {
private static final HashMap<String, DragonRespawnTimer> mp = new HashMap<>();
public static void enable(){
File file = new File(plugin.getDataFolder(),"respawn_cd.yml");
if(file.exists()){
FileConfiguration fc = YamlConfiguration.loadConfiguration(file);
ConfigurationSection section = fc.getConfigurationSection("respawn_cd");
if(section == null) return;
section.getKeys(false).forEach(name->{
int set_time = section.getInt(name+".setTime");
int rest_time = section.getInt(name+".remainTime");
if(set_time>0){
boolean run = section.getBoolean(name+".isRunning");
DragonRespawnTimer timer = new DragonRespawnTimer(name,set_time,rest_time);
if(run) timer.run();
TimerManager.mp.put(name,timer);
}
});
}
}
public static void save(){
YamlConfiguration yml = new YamlConfiguration();
mp.forEach((k,v)->{
ConfigurationSection section = yml.createSection("respawn_cd."+k);
if(v.getRestTime()>0){
//section.set("world_name",k);
section.set("setTime",v.getSetTime());
section.set("remainTime",v.getRestTime());
section.set("isRunning",v.isRunning());
}
});
try{
yml.save(new File(plugin.getDataFolder(),"respawn_cd.yml"));
}catch (IOException e){
Lang.error("Failed to save respawn_cd.yml!");
}
}
public static void startTimer(String world_name){
DragonRespawnTimer timer = mp.get(world_name);
if(timer != null){
timer.run();
}
}
public static void setTimer(String world_name, DragonRespawnTimer timer){
DragonRespawnTimer timer_old = mp.get(world_name);
if(timer_old != null) timer_old.del();
mp.put(world_name,timer);
}
public static DragonRespawnTimer getTimer(String world_name){
return mp.get(world_name);
}
public static void removeTimer(String world_name){
DragonRespawnTimer timer_old = mp.get(world_name);
if(timer_old != null) timer_old.del();
mp.remove(world_name);
}
public static void removeAll(){
mp.values().forEach(DragonRespawnTimer::del);
mp.clear();
}
}
@@ -1,196 +0,0 @@
package pers.xanadu.enderdragon.manager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Entity;
import pers.xanadu.enderdragon.config.Lang;
import pers.xanadu.enderdragon.util.Version;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static java.lang.Math.sqrt;
import static pers.xanadu.enderdragon.EnderDragon.getInstance;
import static pers.xanadu.enderdragon.util.MathUtil.*;
public class WorldManager {
public static final List<String> worlds = new ArrayList<>();
private Field dimension;
private Field world_provider;
private Method getDimensionID;
public static void reload(){
worlds.clear();
Bukkit.getWorlds().forEach(world -> worlds.add(world.getName()));
}
public static Collection<EnderDragon> getExplosionDragon(float power, Location loc){
World world = loc.getWorld();
if(world == null) return Collections.EMPTY_LIST;
return getExplosionDragon(loc.getWorld(),power,loc.getX()+0.5d,loc.getY()+0.5d,loc.getZ()+0.5d);
}
public static Collection<EnderDragon> getExplosionDragon(World world,float power,double x,double y,double z){
float f = power * 2.0F;
int x1 = floor(x - (double)f - 1.0);
int x2 = floor(x + (double)f + 1.0);
int y1 = floor(y - (double)f - 1.0);
int y2 = floor(y + (double)f + 1.0);
int z1 = floor(z - (double)f - 1.0);
int z2 = floor(z + (double)f + 1.0);
// Collection<Entity> list = world.getNearbyEntities(new BoundingBox(x1, y1, z1, x2, y2, z2));
Location cen = new Location(world,(x1+x2)/2d,(y1+y2)/2d,(z1+z2)/2d);
double rx = (x2-x1)/2d;
double ry = (y2-y1)/2d;
double rz = (z2-z1)/2d;
Collection<Entity> list = world.getNearbyEntities(cen,rx,ry,rz);
List<EnderDragon> res = new ArrayList<>();
for (Entity entity : list) {
if(entity instanceof EnderDragon){
double d0 = sqrt(c(entity,x, y, z)) / f;
if (d0 <= 1.0) {
Location loc = entity.getLocation();
double dx = loc.getX() - x;
double dy = loc.getY() + 6.8d - y;
double dz = loc.getZ() - z;
double d1 = sqrt(dx * dx + dy * dy + dz * dz);
if (d1 != 0.0) {
res.add((EnderDragon) entity);
}
}
}
}
return res;
}
// public static float a(Vector endPos, Entity entity) {
// BoundingBox bb = entity.getBoundingBox();
// double d0 = 1.0 / ((bb.getMaxX() - bb.getMinX()) * 2.0 + 1.0);
// double d1 = 1.0 / ((bb.getMaxY() - bb.getMinY()) * 2.0 + 1.0);
// double d2 = 1.0 / ((bb.getMaxZ() - bb.getMinZ()) * 2.0 + 1.0);
// double d3 = (1.0 - Math.floor(1.0 / d0) * d0) / 2.0;
// double d4 = (1.0 - Math.floor(1.0 / d2) * d2) / 2.0;
// if (d0 >= 0.0 && d1 >= 0.0 && d2 >= 0.0) {
// int i = 0;
// int j = 0;
//
// for(float f = 0.0F; f <= 1.0F; f = (float)((double)f + d0)) {
// for(float f1 = 0.0F; f1 <= 1.0F; f1 = (float)((double)f1 + d1)) {
// for(float f2 = 0.0F; f2 <= 1.0F; f2 = (float)((double)f2 + d2)) {
// double d5 = d(f, bb.getMinX(), bb.getMaxX());
// double d6 = d(f1, bb.getMinY(), bb.getMaxY());
// double d7 = d(f2, bb.getMinZ(), bb.getMaxZ());
// //Vec3D vec3d1 = new Vec3D(d5 + d3, d6, d7 + d4);
// Location start = new Location(entity.getWorld(),d5 + d3, d6, d7 + d4);
// Vector dir = new Vector(endPos.getX()-start.getX(),endPos.getY()-start.getY(),endPos.getZ()-start.getZ());
// double maxDistance = dir.length();
// RayTraceResult result = entity.getWorld().rayTraceBlocks(start,dir,maxDistance, FluidCollisionMode.NEVER,false);
// if(result == null) ++i;
//// if (entity.getWorld().rayTrace(new RayTrace(vec3d1, endPos, RayTrace.BlockCollisionOption.OUTLINE, RayTrace.FluidCollisionOption.NONE, entity)).getType() == MovingObjectPosition.EnumMovingObjectType.MISS) {
//// ++i;
//// }
// ++j;
// }
// }
// }
// return (float)i / (float)j;
// } else {
// return 0.0F;
// }
// }
public void fixWorldEnvironment(){
Bukkit.getWorlds().forEach(world -> {
try{
if(isTheEnd(world)) getInstance().getNMSManager().setEnvironment(world, World.Environment.THE_END);
}catch(ReflectiveOperationException e){
e.printStackTrace();
}
});
}
private boolean isTheEnd(World world) throws ReflectiveOperationException {
String version = Version.getVersion();
switch (version) {
case "v1_12_R1" :
case "v1_13_R1" : {
Object world_server = getInstance().getNMSManager().getWorldServer(world);
if(dimension == null) dimension = world_server.getClass().getDeclaredField("dimension");
int dimen = (int) dimension.get(world_server);
return dimen == 1;
}
case "v1_13_R2" : {
Object world_server = getInstance().getNMSManager().getWorldServer(world);
if(dimension == null) dimension = world_server.getClass().getField("dimension");
Object DimensionManager = dimension.get(world_server);
if(getDimensionID == null) getDimensionID = DimensionManager.getClass().getMethod("getDimensionID");
int dimen = (int) getDimensionID.invoke(DimensionManager);
return dimen == 1;
}
case "v1_14_R1" :
case "v1_15_R1" : {
Object world_server = getInstance().getNMSManager().getWorldServer(world);
if(world_provider == null) world_provider = world_server.getClass().getField("worldProvider");
Object worldProvider = world_provider.get(world_server);
if(dimension == null) dimension = getInstance().getNMSManager().getWorldProviderClass().getDeclaredField("f");
dimension.setAccessible(true);
Object DimensionManager = dimension.get(worldProvider);
if(getDimensionID == null) getDimensionID = DimensionManager.getClass().getMethod("getDimensionID");
int dimen = (int) getDimensionID.invoke(DimensionManager);
return dimen == 1;
}
case "v1_16_R1" :
case "v1_16_R2" :
case "v1_16_R3" :
case "v1_17_R1" : {
Object world_server = getInstance().getNMSManager().getWorldServer(world);
if(getDimensionID == null) getDimensionID = getInstance().getNMSManager().getWorldClass().getMethod("getDimensionKey");
Object world_type = getDimensionID.invoke(world_server);
return world_type.toString().contains("minecraft:the_end");
}
default : {
if(Version.mcMainVersion < 12){
Lang.warn("Your server version (" + version + ") is not supported!");
return false;
}
Object world_server = getInstance().getNMSManager().getWorldServer(world);
if(getDimensionID == null) getDimensionID = world_server.getClass().getMethod("getTypeKey");
Object world_type = getDimensionID.invoke(world_server);
return world_type.toString().contains("minecraft:the_end");
}
}
/*
try{
//>=1.18 建议使用WorldServer::getTypeKey
Object world_server = getInstance().getNMSManager().getWorldServer(world);
Class<?> World_Class = Class.forName("net.minecraft.server."+ Version.getVersion()+".World");//<=1.16.5
Object world_type = World_Class.getDeclaredMethod("getDimensionKey").invoke(world_server);//<=1.17.1
String string_type = world_type.toString();
Bukkit.broadcastMessage(string_type);
Class<?> ResourceKey_Class = Class.forName("net.minecraft.server."+Version.getVersion()+".ResourceKey");
Object ResourceKey = ResourceKey_Class.cast(world_type);
Object MinecraftKey = ResourceKey_Class.getDeclaredMethod("a").invoke(ResourceKey);
Class<?> MinecraftKey_Class = Class.forName("net.minecraft.server."+Version.getVersion()+".MinecraftKey");
String string_type2 = (String) MinecraftKey_Class.getDeclaredMethod("getKey").invoke(MinecraftKey);
Bukkit.broadcastMessage(string_type2);
// Object world_c = getCraftWorld(world);
// Object envi = CraftWorldClass.getDeclaredMethod("getEnvironment").invoke(world_c);
// World.Environment environment = (World.Environment) envi;
// Bukkit.broadcastMessage(environment.toString());
}catch (ReflectiveOperationException e){
e.printStackTrace();
}
*/
}
}