From ef06546721cb265ab7c330e462e68016bd257554 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Wed, 17 Mar 2021 14:35:24 -0700 Subject: [PATCH] More work on gutting out the new skill system & reducing compiler errors --- .../java/com/gmail/nossr50/config/Config.java | 16 +- .../config/experience/ExperienceConfig.java | 10 +- .../database/AbstractDatabaseManager.java | 37 - .../nossr50/database/DatabaseManager.java | 5 +- .../database/FlatFileDatabaseManager.java | 796 ++++++++---------- .../nossr50/database/SQLDatabaseManager.java | 52 +- .../OfflineExperienceProcessor.java | 4 +- .../experience/OnlineExperienceProcessor.java | 192 ++--- .../datatypes/player/AbstractMMOPlayer.java | 15 +- .../datatypes/player/CooldownManager.java | 4 +- .../datatypes/player/MMODataBuilder.java | 49 +- .../datatypes/player/MMODataSnapshot.java | 13 +- .../nossr50/datatypes/player/McMMOPlayer.java | 17 +- ...MMOPlayerDataImpl.java => PlayerData.java} | 112 +-- .../datatypes/player/PlayerProfile.java | 30 +- .../nossr50/datatypes/skills/CoreSkills.java | 48 +- .../datatypes/skills/SkillRegisterImpl.java | 20 +- .../commands/MctopCommandAsyncTask.java | 11 +- .../commands/MctopCommandDisplayTask.java | 17 +- .../skills/ExperienceBarHideTask.java | 10 +- .../nossr50/skills/child/FamilyTree.java | 10 +- .../com/gmail/nossr50/util/Permissions.java | 4 +- .../util/experience/ExperienceBarWrapper.java | 24 +- .../experience/MMOExperienceBarManager.java | 101 +-- .../util/input/SuperSkillManagerImpl.java | 6 +- .../util/player/NotificationManager.java | 6 +- .../nossr50/util/player/PlayerLevelUtils.java | 6 +- .../util/text/TextComponentFactory.java | 4 +- 28 files changed, 697 insertions(+), 922 deletions(-) delete mode 100644 src/main/java/com/gmail/nossr50/database/AbstractDatabaseManager.java rename src/main/java/com/gmail/nossr50/datatypes/player/{MMOPlayerDataImpl.java => PlayerData.java} (77%) diff --git a/src/main/java/com/gmail/nossr50/config/Config.java b/src/main/java/com/gmail/nossr50/config/Config.java index f5aeff15e..0131ceff3 100644 --- a/src/main/java/com/gmail/nossr50/config/Config.java +++ b/src/main/java/com/gmail/nossr50/config/Config.java @@ -355,10 +355,10 @@ public class Config extends AutoUpdateConfigLoader { /* Hardcore Mode */ @Deprecated public boolean getHardcoreStatLossEnabled(PrimarySkillType primarySkillType) { return config.getBoolean("Hardcore.Death_Stat_Loss.Enabled." + StringUtils.getCapitalized(primarySkillType.toString()), false); } - public boolean getHardcoreStatLossEnabled(@NotNull RootSkill rootSkill) { return config.getBoolean("Hardcore.Death_Stat_Loss.Enabled." + rootSkill.getRawSkillName(), false); } + public boolean getHardcoreStatLossEnabled(@NotNull PrimarySkillType primarySkillType) { return config.getBoolean("Hardcore.Death_Stat_Loss.Enabled." + primarySkillType.getRawSkillName(), false); } @Deprecated public void setHardcoreStatLossEnabled(PrimarySkillType primarySkillType, boolean enabled) { config.set("Hardcore.Death_Stat_Loss.Enabled." + StringUtils.getCapitalized(primarySkillType.toString()), enabled); } - public void setHardcoreStatLossEnabled(@NotNull RootSkill rootSkill, boolean enabled) { config.set("Hardcore.Death_Stat_Loss.Enabled." + rootSkill.getRawSkillName(), enabled); } + public void setHardcoreStatLossEnabled(@NotNull PrimarySkillType primarySkillType, boolean enabled) { config.set("Hardcore.Death_Stat_Loss.Enabled." + primarySkillType.getRawSkillName(), enabled); } public double getHardcoreDeathStatPenaltyPercentage() { return config.getDouble("Hardcore.Death_Stat_Loss.Penalty_Percentage", 75.0D); } public void setHardcoreDeathStatPenaltyPercentage(double value) { config.set("Hardcore.Death_Stat_Loss.Penalty_Percentage", value); } @@ -367,10 +367,10 @@ public class Config extends AutoUpdateConfigLoader { @Deprecated public boolean getHardcoreVampirismEnabled(PrimarySkillType primarySkillType) { return config.getBoolean("Hardcore.Vampirism.Enabled." + StringUtils.getCapitalized(primarySkillType.toString()), false); } - public boolean getHardcoreVampirismEnabled(@NotNull RootSkill rootSkill) { return config.getBoolean("Hardcore.Vampirism.Enabled." + rootSkill.getRawSkillName(), false); } + public boolean getHardcoreVampirismEnabled(@NotNull PrimarySkillType primarySkillType) { return config.getBoolean("Hardcore.Vampirism.Enabled." + primarySkillType.getRawSkillName(), false); } @Deprecated public void setHardcoreVampirismEnabled(PrimarySkillType primarySkillType, boolean enabled) { config.set("Hardcore.Vampirism.Enabled." + StringUtils.getCapitalized(primarySkillType.toString()), enabled); } - public void setHardcoreVampirismEnabled(@NotNull RootSkill rootSkill, boolean enabled) { config.set("Hardcore.Vampirism.Enabled." + rootSkill.getRawSkillName(), enabled); } + public void setHardcoreVampirismEnabled(@NotNull PrimarySkillType primarySkillType, boolean enabled) { config.set("Hardcore.Vampirism.Enabled." + primarySkillType.getRawSkillName(), enabled); } public double getHardcoreVampirismStatLeechPercentage() { return config.getDouble("Hardcore.Vampirism.Leech_Percentage", 5.0D); } public void setHardcoreVampirismStatLeechPercentage(double value) { config.set("Hardcore.Vampirism.Leech_Percentage", value); } @@ -562,9 +562,9 @@ public class Config extends AutoUpdateConfigLoader { return (cap <= 0) ? Integer.MAX_VALUE : cap; } - public int getLevelCap(@NotNull RootSkill rootSkill) { + public int getLevelCap(@NotNull PrimarySkillType primarySkillType) { - int cap = config.getInt("Skills." + StringUtils.getCapitalized(rootSkill.getRawSkillName()) + ".Level_Cap", 0); + int cap = config.getInt("Skills." + StringUtils.getCapitalized(primarySkillType.getRawSkillName()) + ".Level_Cap", 0); return (cap <= 0) ? Integer.MAX_VALUE : cap; } @@ -584,10 +584,10 @@ public class Config extends AutoUpdateConfigLoader { /* PVP & PVE Settings */ @Deprecated public boolean getPVPEnabled(PrimarySkillType skill) { return config.getBoolean("Skills." + StringUtils.getCapitalized(skill.toString()) + ".Enabled_For_PVP", true); } - public boolean getPVPEnabled(RootSkill skill) { return config.getBoolean("Skills." + skill.getRawSkillName() + ".Enabled_For_PVP", true); } + public boolean getPVPEnabled(PrimarySkillType skill) { return config.getBoolean("Skills." + skill.getRawSkillName() + ".Enabled_For_PVP", true); } @Deprecated public boolean getPVEEnabled(PrimarySkillType skill) { return config.getBoolean("Skills." + StringUtils.getCapitalized(skill.toString()) + ".Enabled_For_PVE", true); } - public boolean getPVEEnabled(RootSkill skill) { return config.getBoolean("Skills." + skill.getRawSkillName() + ".Enabled_For_PVE", true); } + public boolean getPVEEnabled(PrimarySkillType skill) { return config.getBoolean("Skills." + skill.getRawSkillName() + ".Enabled_For_PVE", true); } //public float getMasterVolume() { return (float) config.getDouble("Sounds.MasterVolume", 1.0); } diff --git a/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java b/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java index e2eeb2199..9c6513979 100644 --- a/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java +++ b/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java @@ -331,11 +331,11 @@ public class ExperienceConfig extends AutoUpdateConfigLoader { public boolean getAddExtraDetails() { return config.getBoolean("Experience_Bars.ThisMayCauseLag.AlwaysUpdateTitlesWhenXPIsGained.ExtraDetails", false);} public boolean isExperienceBarsEnabled() { return config.getBoolean("Experience_Bars.Enable", true); } public boolean isExperienceBarEnabled(PrimarySkillType primarySkillType) { return config.getBoolean("Experience_Bars."+StringUtils.getCapitalized(primarySkillType.toString())+".Enable", true);} - public boolean isExperienceBarEnabled(@NotNull RootSkill rootSkill) { return config.getBoolean("Experience_Bars."+StringUtils.getCapitalized(rootSkill.getRawSkillName())+".Enable", true);} + public boolean isExperienceBarEnabled(@NotNull PrimarySkillType primarySkillType) { return config.getBoolean("Experience_Bars."+StringUtils.getCapitalized(primarySkillType.getRawSkillName())+".Enable", true);} - public BarColor getExperienceBarColor(@NotNull RootSkill rootSkill) + public BarColor getExperienceBarColor(@NotNull PrimarySkillType primarySkillType) { - String colorValueFromConfig = config.getString("Experience_Bars."+StringUtils.getCapitalized(rootSkill.getRawSkillName())+".Color"); + String colorValueFromConfig = config.getString("Experience_Bars."+StringUtils.getCapitalized(primarySkillType.getRawSkillName())+".Color"); for(BarColor barColor : BarColor.values()) { @@ -374,8 +374,8 @@ public class ExperienceConfig extends AutoUpdateConfigLoader { return BarStyle.SOLID; } - public BarStyle getExperienceBarStyle(@NotNull RootSkill rootSkill) { - String colorValueFromConfig = config.getString("Experience_Bars."+StringUtils.getCapitalized(rootSkill.getRawSkillName())+".BarStyle"); + public BarStyle getExperienceBarStyle(@NotNull PrimarySkillType primarySkillType) { + String colorValueFromConfig = config.getString("Experience_Bars."+StringUtils.getCapitalized(primarySkillType.getRawSkillName())+".BarStyle"); for(BarStyle barStyle : BarStyle.values()) { diff --git a/src/main/java/com/gmail/nossr50/database/AbstractDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/AbstractDatabaseManager.java deleted file mode 100644 index 46bbc7254..000000000 --- a/src/main/java/com/gmail/nossr50/database/AbstractDatabaseManager.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.gmail.nossr50.database; - -import com.gmail.nossr50.datatypes.player.MMODataBuilder; -import com.gmail.nossr50.datatypes.player.PlayerProfile; -import com.gmail.nossr50.mcMMO; -import com.neetgames.mcmmo.exceptions.ProfileRetrievalException; -import org.apache.commons.lang.NullArgumentException; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public abstract class AbstractDatabaseManager implements DatabaseManager { - @Override - public @Nullable PlayerProfile initPlayerProfile(@NotNull Player player) throws Exception { - //First we attempt to load the player data - try { - PlayerProfile playerProfile = queryPlayerDataByUUID(player.getUniqueId(), player.getName()); - if(playerProfile != null) { - return playerProfile; - } - //If we fail to load the player data due to either missing data for the player or corrupted/invalid data, we create a new profile for this player - } catch (ProfileRetrievalException | NullArgumentException e) { - mcMMO.p.getLogger().info("Making new player data in DB for user name:"+player.getName().toString()+", uuid:" + player.getUniqueId().toString()); - //Add data for this player into DB with default values - //TODO: have this use the PersistentPlayerData object created below to initialize defaults - insertNewUser(player.getName(), player.getUniqueId()); - //Construct player data object - MMODataBuilder MMODataBuilder = new MMODataBuilder(); - //Return player profile - return new PlayerProfile(MMODataBuilder.buildNewPlayerData(player.getUniqueId(), player.getName())); - } catch (Exception e) { - e.printStackTrace(); - } - - return null; //Some critical failure happened - } -} diff --git a/src/main/java/com/gmail/nossr50/database/DatabaseManager.java b/src/main/java/com/gmail/nossr50/database/DatabaseManager.java index 7b6fc41cd..1c6f3ef3a 100644 --- a/src/main/java/com/gmail/nossr50/database/DatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/DatabaseManager.java @@ -6,6 +6,7 @@ import com.gmail.nossr50.datatypes.database.DatabaseType; import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.neetgames.mcmmo.player.MMOPlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -49,10 +50,10 @@ public interface DatabaseManager { /** * Save a user to the database. * - * @param profile The profile of the player to save + * @param mmoPlayer The player to save * @return true if successful, false on failure */ - boolean saveUser(PlayerProfile profile); + boolean saveUser(@NotNull MMOPlayer mmoPlayer); /** * Retrieve leaderboard info. diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java index 9590ed714..86e598ab0 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java @@ -13,15 +13,11 @@ import com.gmail.nossr50.runnables.database.UUIDUpdateAsyncTask; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.experience.MMOExperienceBarManager; import com.gmail.nossr50.util.skills.SkillUtils; -import com.gmail.nossr50.util.text.StringUtils; import com.google.common.collect.ImmutableMap; -import com.neetgames.mcmmo.MobHealthBarType; import com.neetgames.mcmmo.UniqueDataType; -import com.neetgames.mcmmo.exceptions.ProfileRetrievalException; -import com.neetgames.mcmmo.player.MMOPlayerData; -import com.neetgames.mcmmo.skill.RootSkill; +import com.neetgames.mcmmo.exceptions.InvalidSkillException; +import com.neetgames.mcmmo.player.MMOPlayer; import com.neetgames.mcmmo.skill.SkillBossBarState; -import org.apache.commons.lang.NullArgumentException; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -30,10 +26,10 @@ import org.jetbrains.annotations.Nullable; import java.io.*; import java.util.*; -public final class FlatFileDatabaseManager extends AbstractDatabaseManager { +public final class FlatFileDatabaseManager implements DatabaseManager { public static final String FLATFILE_SPLIT_CHARACTER_REGEX = ":"; - public static final String NULL_VALUE = NULL_VALUE; - private final HashMap> playerStatHash = new HashMap<>(); + public static final String NULL_VALUE = "NULL"; + private final HashMap> playerStatHash = new HashMap<>(); private final List powerLevels = new ArrayList<>(); private long lastUpdate = 0; @@ -254,13 +250,21 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { return worked; } - public boolean saveUser(@NotNull MMODataSnapshot dataSnapshot) { + @Override + public void cleanupUser(UUID uuid) { + //Not used in FlatFile + } + + + public boolean saveUser(@NotNull MMOPlayer mmoPlayer) { + PlayerData mmoPlayerData = mmoPlayer.getPlayerData(); String playerName = dataSnapshot.getPlayerName(); UUID uuid = dataSnapshot.getPlayerUUID(); BufferedReader in = null; FileWriter out = null; String usersFilePath = mcMMO.getUsersFilePath(); + boolean corruptDataFound = false; synchronized (fileWritingLock) { try { @@ -272,14 +276,38 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { boolean wroteUser = false; // While not at the end of the file while ((line = in.readLine()) != null) { - // Read the line in and copy it to the output if it's not the player we want to edit - String[] character = line.split(":"); - if (!character[FlatFileMappings.UUID_INDEX].equalsIgnoreCase(uuid.toString()) && !character[FlatFileMappings.USERNAME].equalsIgnoreCase(playerName)) { - writer.append(line).append("\r\n"); + //Check for incomplete or corrupted data + if(!line.contains(":")) { + + if(!corruptDataFound) { + mcMMO.p.getLogger().severe("mcMMO found some unexpected or corrupted data in mcmmo.users and is removing it, it is possible some data has been lost."); + corruptDataFound = true; + } + + continue; } - else { - // Otherwise write the new player information - writeUserToLine(dataSnapshot, playerName, uuid, writer); + + String[] splitData = line.split(":"); + + //This would be rare, but check the splitData for having enough entries to contain a username + if(splitData.length < USERNAME) { //UUID have been in mcMMO DB for a very long time so any user without + //Something is wrong if we don't have enough split data to have an entry for a username + + if(!corruptDataFound) { + mcMMO.p.getLogger().severe("mcMMO found some unexpected or corrupted data in mcmmo.users and is removing it, it is possible some data has been lost."); + corruptDataFound = true; + } + + continue; + } + + if (!(uuid != null + && splitData[FlatFileMappings.UUID_INDEX].equalsIgnoreCase(uuid.toString())) + && !splitData[FlatFileMappings.USERNAME].equalsIgnoreCase(playerName)) { + writer.append(line).append("\r\n"); //Not the user so write it to file and move on + } else { + //User found + writeUserToLine(profile, playerName, uuid, writer); wroteUser = true; } } @@ -287,9 +315,8 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { /* * If we couldn't find the user in the DB we need to add him */ - if(!wroteUser) - { - writeUserToLine(dataSnapshot, playerName, uuid, writer); + if(!wroteUser) { + writeUserToLine(profile, playerName, uuid, writer); } // Write the new file @@ -322,7 +349,7 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { } } - private void writeUserToLine(@NotNull MMODataSnapshot mmoDataSnapshot, @NotNull String playerName, @NotNull UUID uuid, @NotNull StringBuilder writer) { + private void writeUserToLine(@NotNull MMODataSnapshot mmoDataSnapshot, @NotNull String playerName, @Nullable UUID uuid, @NotNull StringBuilder writer) { ImmutableMap primarySkillLevelMap = mmoDataSnapshot.getSkillLevelValues(); ImmutableMap primarySkillExperienceValueMap = mmoDataSnapshot.getSkillExperienceValues(); @@ -369,7 +396,7 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { writer.append(primarySkillLevelMap.get(PrimarySkillType.ALCHEMY)).append(":"); writer.append(primarySkillExperienceValueMap.get(PrimarySkillType.ALCHEMY)).append(":"); - writer.append(uuid != null ? uuid.toString() : NULL_VALUE).append(":"); + writer.append(uuid != null ? uuid.toString() : NULL_VALUE).append(":"); //Can be NULL writer.append(mmoDataSnapshot.getScoreboardTipsShown()).append(":"); writer.append(mmoDataSnapshot.getUniqueData(UniqueDataType.CHIMAERA_WING_DATS)).append(":"); @@ -430,8 +457,13 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { writer.append("\r\n"); } - @Override - public @NotNull List readLeaderboard(@NotNull RootSkill skill, int pageNumber, int statsPerPage) { + public @NotNull List readLeaderboard(@NotNull PrimarySkillType skill, int pageNumber, int statsPerPage) { + //Fix for a plugin that people are using that is throwing SQL errors + if(skill != null && skill.isChildSkill()) { + mcMMO.p.getLogger().severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); + throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); + } + updateLeaderboards(); List statsList = skill == null ? powerLevels : playerStatHash.get(skill); int fromIndex = (Math.max(pageNumber, 1) - 1) * statsPerPage; @@ -439,17 +471,13 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { return statsList.subList(Math.min(fromIndex, statsList.size()), Math.min(fromIndex + statsPerPage, statsList.size())); } - @Override - public @NotNull Map readRank(@NotNull String playerName) { + public Map readRank(String playerName) { updateLeaderboards(); Map skills = new HashMap<>(); - for (RootSkill rootSkill : PrimarySkillType.getImmutableCoreRootSkillSet()) { - if(PrimarySkillType.isChildSkill(rootSkill)) - continue; - - skills.put(rootSkill, getPlayerRank(playerName, playerStatHash.get(rootSkill))); + for (PrimarySkillType skill : PrimarySkillType.NON_CHILD_SKILLS) { + skills.put(skill, getPlayerRank(playerName, playerStatHash.get(skill))); } skills.put(null, getPlayerRank(playerName, powerLevels)); @@ -457,8 +485,12 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { return skills; } - @Override - public void newUser(@NotNull String playerName, @NotNull UUID uuid) { + public @NotNull PlayerProfile newUser(@NotNull Player player) { + newUser(player.getName(), player.getUniqueId()); + return new PlayerProfile(player.getName(), player.getUniqueId(), true); + } + + public void newUser(String playerName, UUID uuid) { BufferedWriter out = null; synchronized (fileWritingLock) { try { @@ -565,121 +597,131 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { } } - @Override - public @Nullable MMOPlayerData queryPlayerByName(@NotNull String playerName) throws ProfileRetrievalException { - BufferedReader bufferedReader = null; + public @NotNull PlayerProfile loadPlayerProfile(@NotNull String playerName) { + return loadPlayerByName(playerName); + } + + public @NotNull PlayerProfile loadPlayerProfile(@NotNull UUID uuid, @Nullable String playerName) { + return loadPlayerByUUID(uuid, playerName); + } + + private @NotNull PlayerProfile loadPlayerByUUID(@NotNull UUID uuid, @Nullable String playerName) { + BufferedReader in = null; String usersFilePath = mcMMO.getUsersFilePath(); //Retrieve player synchronized (fileWritingLock) { try { // Open the user file - bufferedReader = new BufferedReader(new FileReader(usersFilePath)); - String currentLine; + in = new BufferedReader(new FileReader(usersFilePath)); + String line; - while ((currentLine = bufferedReader.readLine()) != null) { - // Split the data which is stored as a string with : as break points - String[] stringDataArray = currentLine.split(FLATFILE_SPLIT_CHARACTER_REGEX); + while ((line = in.readLine()) != null) { + // Find if the line contains the player we want. + String[] rawSplitData = line.split(":"); - //Search for matching name - if (!stringDataArray[FlatFileMappings.USERNAME].equalsIgnoreCase(playerName)) { + /* Don't read corrupt data */ + if(rawSplitData.length < (FlatFileMappings.UUID_INDEX + 1)) { continue; } - //We found our player, load the data - return loadFromLine(stringDataArray); - } - - throw new ProfileRetrievalException("Couldn't find a matching player in the database! Using name matching - " + playerName); - } - catch (Exception e) { - e.printStackTrace(); - } - - //Cleanup resource leaks - finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); + /* Does this entry have a UUID? */ + if (rawSplitData[FlatFileMappings.UUID_INDEX].equalsIgnoreCase("NULL") + || rawSplitData[FlatFileMappings.UUID_INDEX].isEmpty() + || rawSplitData[FlatFileMappings.UUID_INDEX].equalsIgnoreCase("")) { + continue; //No UUID entry found for this data in the DB, go to next entry } - catch (IOException e) { + + // Compare provided UUID to DB + if (!rawSplitData[FlatFileMappings.UUID_INDEX].equalsIgnoreCase(uuid.toString())) { + continue; //Doesn't match, go to the next entry + } + + /* + * UUID Matched! + * Making it this far means the current data line is considered a match + */ + + + /* Check for nickname changes and update since we are here anyways */ + if (!rawSplitData[FlatFileMappings.USERNAME].equalsIgnoreCase(playerName)) { + //mcMMO.p.getLogger().info("Name updated for player: " + rawSplitData[FlatFileMappings.USERNAME] + " => " + playerName); + rawSplitData[FlatFileMappings.USERNAME] = playerName; + } + + return loadFromLine(rawSplitData); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + // I have no idea why it's necessary to inline tryClose() here, but it removes + // a resource leak warning, and I'm trusting the compiler on this one. + if (in != null) { + try { + in.close(); + } catch (IOException e) { // Ignore } } } } - //Theoretically this statement should never be reached - mcMMO.p.getLogger().severe("Critical failure in execution of loading player from DB, contact the devs!"); - return null; + /* + * No match was found in the file + */ + + return grabUnloadedProfile(uuid, playerName); //Create an empty new profile and return } - public @Nullable MMOPlayerData queryPlayerDataByPlayer(@NotNull Player player) throws ProfileRetrievalException, NullArgumentException { - return queryPlayerDataByUUID(player.getUniqueId(), player.getName()); - } - - /** - * Queries by UUID will always have the current player name included as this method only gets executed when players join the server - * The name will be used to update player names in the DB if the name has changed - * There exists scenarios where players can share the same name in the DB, there is no code to account for this currently - * @param uuid uuid to match - * @param playerName used to overwrite playername values in the database if an existing value that is not equal to this one is found - * @return the player profile if retrieved successfully, otherwise null - * @throws ProfileRetrievalException - * @throws NullArgumentException - */ - public @Nullable MMOPlayerData queryPlayerDataByUUID(@NotNull UUID uuid, @NotNull String playerName) throws ProfileRetrievalException, NullArgumentException { - BufferedReader bufferedReader = null; + private @NotNull PlayerProfile loadPlayerByName(@NotNull String playerName) { + BufferedReader in = null; String usersFilePath = mcMMO.getUsersFilePath(); - //Retrieve player synchronized (fileWritingLock) { try { // Open the user file - bufferedReader = new BufferedReader(new FileReader(usersFilePath)); - String currentLine; + in = new BufferedReader(new FileReader(usersFilePath)); + String line; - while ((currentLine = bufferedReader.readLine()) != null) { - // Split the data which is stored as a string with : as break points - String[] stringDataArray = currentLine.split(FLATFILE_SPLIT_CHARACTER_REGEX); + while ((line = in.readLine()) != null) { + // Find if the line contains the player we want. + String[] rawSplitData = line.split(":"); - //Search for matching UUID - if (!stringDataArray[FlatFileMappings.UUID_INDEX].equalsIgnoreCase(uuid.toString())) { + /* Don't read corrupt data */ + if(rawSplitData.length < (USERNAME + 1)) { continue; } - //If the player has changed their name, we need to update it too - if (!stringDataArray[FlatFileMappings.USERNAME].equalsIgnoreCase(playerName)) { - mcMMO.p.getLogger().info("Name change detected: " + stringDataArray[FlatFileMappings.USERNAME] + " => " + playerName); - stringDataArray[FlatFileMappings.USERNAME] = playerName; + //If we couldn't find anyone + if(playerName.equalsIgnoreCase(rawSplitData[FlatFileMappings.USERNAME])) { + return loadFromLine(rawSplitData); } - - //We found our player, load the data - return loadFromLine(stringDataArray); } - - throw new ProfileRetrievalException("Couldn't find a matching player in the database! - "+playerName+", "+uuid.toString()); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); - } - - //Cleanup resource leaks - finally { - if (bufferedReader != null) { + } finally { + // I have no idea why it's necessary to inline tryClose() here, but it removes + // a resource leak warning, and I'm trusting the compiler on this one. + if (in != null) { try { - bufferedReader.close(); - } - catch (IOException e) { + in.close(); + } catch (IOException e) { // Ignore } } } } - //Theoretically this statement should never be reached - mcMMO.p.getLogger().severe("Critical failure in execution of loading player from DB, contact the devs!"); - return null; + //Return a new blank profile + return new PlayerProfile(playerName, null); + } + + private @NotNull PlayerProfile grabUnloadedProfile(@NotNull UUID uuid, @Nullable String playerName) { + if(playerName == null) { + playerName = ""; //No name for you boy! + } + + return new PlayerProfile(playerName, uuid); } public void convertUsers(@NotNull DatabaseManager destination) { @@ -695,14 +737,10 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { String line; while ((line = in.readLine()) != null) { - String[] stringDataSplit = line.split(":"); + String[] character = line.split(":"); try { - MMOPlayerData mmoPlayerData = loadFromLine(stringDataSplit); - if(mmoPlayerData == null) - continue; - - destination.saveUser(mcMMO.getUserManager().createPlayerDataSnapshot(mmoPlayerData)); + destination.saveUser(loadFromLine(character)); } catch (Exception e) { e.printStackTrace(); @@ -727,7 +765,127 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { } } - public @NotNull List getStoredUsers() { + public boolean saveUserUUID(String userName, UUID uuid) { + boolean worked = false; + + int i = 0; + BufferedReader in = null; + FileWriter out = null; + String usersFilePath = mcMMO.getUsersFilePath(); + + synchronized (fileWritingLock) { + try { + in = new BufferedReader(new FileReader(usersFilePath)); + StringBuilder writer = new StringBuilder(); + String line; + + while ((line = in.readLine()) != null) { + String[] character = line.split(":"); + if (!worked && character[FlatFileMappings.USERNAME].equalsIgnoreCase(userName)) { + if (character.length < 42) { + mcMMO.p.getLogger().severe("Could not update UUID for " + userName + "!"); + mcMMO.p.getLogger().severe("Database entry is invalid."); + continue; + } + + line = line.replace(character[FlatFileMappings.UUID_INDEX], uuid.toString()); + worked = true; + } + + i++; + writer.append(line).append("\r\n"); + } + + out = new FileWriter(usersFilePath); // Write out the new file + out.write(writer.toString()); + } + catch (Exception e) { + mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); + } + finally { + mcMMO.p.getLogger().info(i + " entries written while saving UUID for " + userName); + if (in != null) { + try { + in.close(); + } + catch (IOException e) { + // Ignore + } + } + if (out != null) { + try { + out.close(); + } + catch (IOException e) { + // Ignore + } + } + } + } + + return worked; + } + + public boolean saveUserUUIDs(Map fetchedUUIDs) { + BufferedReader in = null; + FileWriter out = null; + String usersFilePath = mcMMO.getUsersFilePath(); + int i = 0; + + synchronized (fileWritingLock) { + try { + in = new BufferedReader(new FileReader(usersFilePath)); + StringBuilder writer = new StringBuilder(); + String line; + + while (((line = in.readLine()) != null)) { + String[] character = line.split(":"); + if (!fetchedUUIDs.isEmpty() && fetchedUUIDs.containsKey(character[FlatFileMappings.USERNAME])) { + if (character.length < 42) { + mcMMO.p.getLogger().severe("Could not update UUID for " + character[FlatFileMappings.USERNAME] + "!"); + mcMMO.p.getLogger().severe("Database entry is invalid."); + continue; + } + + character[FlatFileMappings.UUID_INDEX] = fetchedUUIDs.remove(character[FlatFileMappings.USERNAME]).toString(); + line = org.apache.commons.lang.StringUtils.join(character, ":") + ":"; + } + + i++; + writer.append(line).append("\r\n"); + } + + out = new FileWriter(usersFilePath); // Write out the new file + out.write(writer.toString()); + } + catch (Exception e) { + mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); + } + finally { + mcMMO.p.getLogger().info(i + " entries written while saving UUID batch"); + if (in != null) { + try { + in.close(); + } + catch (IOException e) { + // Ignore + } + } + if (out != null) { + try { + out.close(); + } + catch (IOException e) { + // Ignore + } + } + } + } + + return true; + } + + public List getStoredUsers() { ArrayList users = new ArrayList<>(); BufferedReader in = null; String usersFilePath = mcMMO.getUsersFilePath(); @@ -867,12 +1025,16 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { playerStatHash.put(PrimarySkillType.TAMING, taming); playerStatHash.put(PrimarySkillType.FISHING, fishing); playerStatHash.put(PrimarySkillType.ALCHEMY, alchemy); + playerStatHash.put(PrimarySkillType.TRIDENTS, alchemy); + playerStatHash.put(PrimarySkillType.CROSSBOWS, alchemy); } /** * Checks that the file is present and valid */ private void checkStructure() { + boolean corruptDataFound = false; + if (usersFile.exists()) { BufferedReader in = null; FileWriter out = null; @@ -880,6 +1042,7 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { synchronized (fileWritingLock) { try { + in = new BufferedReader(new FileReader(usersFilePath)); StringBuilder writer = new StringBuilder(); String line; @@ -892,303 +1055,62 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { continue; } - // Length checks depend on last stringDataArray being ':' + // Length checks depend on last rawSplitData being ':' if (line.charAt(line.length() - 1) != ':') { line = line.concat(":"); } - boolean updated = false; - String[] stringDataArray = line.split(":"); - int originalLength = stringDataArray.length; + + String[] rawSplitData = line.split(":"); + + //Not enough data found to be considered a user reliably (NOTE: not foolproof) + if(rawSplitData.length < (FlatFileMappings.UUID_INDEX + 1)) { + if(!corruptDataFound) { + mcMMO.p.getLogger().severe("Some corrupt data was found in mcmmo.users and has been repaired, it is possible that some player data has been lost in this process."); + corruptDataFound = true; + } + + if(rawSplitData.length >= 10 //The value here is kind of arbitrary, it shouldn't be too low to avoid false positives, but also we aren't really going to correctly identify when player data has been corrupted or not with 100% accuracy ever + && rawSplitData[0] != null && !rawSplitData[0].isEmpty()) { + if(rawSplitData[0].length() <= 16 && rawSplitData[0].length() >= 3) { + mcMMO.p.getLogger().severe("Not enough data found to recover corrupted player data for user: "+rawSplitData[0]); + } + } + //This user may have had a name so declare it + + continue; + } // Prevent the same username from being present multiple times - if (!usernames.add(stringDataArray[FlatFileMappings.USERNAME])) { - stringDataArray[FlatFileMappings.USERNAME] = "_INVALID_OLD_USERNAME_'"; - updated = true; - if (stringDataArray.length < FlatFileMappings.UUID_INDEX + 1 || stringDataArray[FlatFileMappings.UUID_INDEX].equals(NULL_VALUE)) { + if (!usernames.add(rawSplitData[FlatFileMappings.USERNAME])) { + //TODO: Check if the commented out code was even necessary + rawSplitData[FlatFileMappings.USERNAME] = "_INVALID_OLD_USERNAME_'"; + if (rawSplitData.length < FlatFileMappings.UUID_INDEX + 1 || rawSplitData[FlatFileMappings.UUID_INDEX].equals("NULL")) { + mcMMO.p.getLogger().severe("Fixing duplicate player names found in mcmmo.users"); continue; } } - - if (stringDataArray.length < 33) { - // Before Version 1.0 - Drop - mcMMO.p.getLogger().warning("Dropping malformed or before version 1.0 line from database - " + line); - continue; - } - - String oldVersion = null; - - if (stringDataArray.length > 33 && !stringDataArray[33].isEmpty()) { - // Removal of Spout Support - // Version 1.4.07-dev2 - // commit 7bac0e2ca5143bce84dc160617fed97f0b1cb968 - stringDataArray[33] = ""; - oldVersion = "1.4.07"; - updated = true; - } - - if (stringDataArray.length <= 33) { - // Introduction of HUDType - // Version 1.1.06 - // commit 78f79213cdd7190cd11ae54526f3b4ea42078e8a - stringDataArray = Arrays.copyOf(stringDataArray, stringDataArray.length + 1); - stringDataArray[stringDataArray.length - 1] = ""; - oldVersion = "1.1.06"; - updated = true; - } - - if (stringDataArray.length <= 35) { - // Introduction of Fishing - // Version 1.2.00 - // commit a814b57311bc7734661109f0e77fc8bab3a0bd29 - stringDataArray = Arrays.copyOf(stringDataArray, stringDataArray.length + 2); - stringDataArray[stringDataArray.length - 1] = "0"; - stringDataArray[stringDataArray.length - 2] = "0"; - if (oldVersion == null) { - oldVersion = "1.2.00"; - } - updated = true; - } - if (stringDataArray.length <= 36) { - // Introduction of Blast Mining cooldowns - // Version 1.3.00-dev - // commit fadbaf429d6b4764b8f1ad0efaa524a090e82ef5 - stringDataArray = Arrays.copyOf(stringDataArray, stringDataArray.length + 1); - stringDataArray[stringDataArray.length - 1] = "0"; - if (oldVersion == null) { - oldVersion = "1.3.00"; - } - updated = true; - } - if (stringDataArray.length <= 37) { - // Making old-purge work with flatfile - // Version 1.4.00-dev - // commmit 3f6c07ba6aaf44e388cc3b882cac3d8f51d0ac28 - // XXX Cannot create an OfflinePlayer at startup, use 0 and fix in purge - stringDataArray = Arrays.copyOf(stringDataArray, stringDataArray.length + 1); - stringDataArray[stringDataArray.length - 1] = "0"; - if (oldVersion == null) { - oldVersion = "1.4.00"; - } - updated = true; - } - if (stringDataArray.length <= 38) { - // Addition of mob healthbars - // Version 1.4.06 - // commit da29185b7dc7e0d992754bba555576d48fa08aa6 - stringDataArray = Arrays.copyOf(stringDataArray, stringDataArray.length + 1); - stringDataArray[stringDataArray.length - 1] = Config.getInstance().getMobHealthbarDefault().toString(); - if (oldVersion == null) { - oldVersion = "1.4.06"; - } - updated = true; - } - if (stringDataArray.length <= 39) { - // Addition of Alchemy - // Version 1.4.08 - stringDataArray = Arrays.copyOf(stringDataArray, stringDataArray.length + 2); - stringDataArray[stringDataArray.length - 1] = "0"; - stringDataArray[stringDataArray.length - 2] = "0"; - if (oldVersion == null) { - oldVersion = "1.4.08"; - } - updated = true; - } - if (stringDataArray.length <= 41) { - // Addition of UUIDs - // Version 1.5.01 - // Add a value because otherwise it gets removed - stringDataArray = Arrays.copyOf(stringDataArray, stringDataArray.length + 1); - stringDataArray[stringDataArray.length - 1] = NULL_VALUE; - if (oldVersion == null) { - oldVersion = "1.5.01"; - } - updated = true; - } - if (stringDataArray.length <= 42) { - // Addition of scoreboard tips auto disable - // Version 1.5.02 - stringDataArray = Arrays.copyOf(stringDataArray, stringDataArray.length + 1); - stringDataArray[stringDataArray.length - 1] = "0"; - - if (oldVersion == null) { - oldVersion = "1.5.02"; - } - updated = true; - } - - if(stringDataArray.length <= 43) { - // Addition of Chimaera wing DATS - stringDataArray = Arrays.copyOf(stringDataArray, stringDataArray.length + 1); - stringDataArray[stringDataArray.length - 1] = "0"; - - if (oldVersion == null) { - oldVersion = "2.1.133"; - } - updated = true; - } - - if(stringDataArray.length <= FlatFileMappings.LENGTH_OF_SPLIT_DATA_ARRAY) { - - if (oldVersion == null) { - oldVersion = "2.1.134"; - } - - stringDataArray = Arrays.copyOf(stringDataArray, FlatFileMappings.LENGTH_OF_SPLIT_DATA_ARRAY); // new array size - - /* - public static int SKILLS_TRIDENTS = 44; - public static int EXP_TRIDENTS = 45; - public static int SKILLS_CROSSBOWS = 46; - public static int EXP_CROSSBOWS = 47; - public static int BARSTATE_ACROBATICS = 48; - public static int BARSTATE_ALCHEMY = 49; - public static int BARSTATE_ARCHERY = 50; - public static int BARSTATE_AXES = 51; - public static int BARSTATE_EXCAVATION = 52; - public static int BARSTATE_FISHING = 53; - public static int BARSTATE_HERBALISM = 54; - public static int BARSTATE_MINING = 55; - public static int BARSTATE_REPAIR = 56; - public static int BARSTATE_SALVAGE = 57; - public static int BARSTATE_SMELTING = 58; - public static int BARSTATE_SWORDS = 59; - public static int BARSTATE_TAMING = 60; - public static int BARSTATE_UNARMED = 61; - public static int BARSTATE_WOODCUTTING = 62; - public static int BARSTATE_TRIDENTS = 63; - public static int BARSTATE_CROSSBOWS = 64; - */ - - stringDataArray[FlatFileMappings.SKILLS_TRIDENTS] = "0"; //trident skill lvl - stringDataArray[FlatFileMappings.EXP_TRIDENTS] = "0"; //trident xp value - stringDataArray[FlatFileMappings.SKILLS_CROSSBOWS] = "0"; //xbow skill lvl - stringDataArray[FlatFileMappings.EXP_CROSSBOWS] = "0"; //xbow xp lvl - - //Barstates 48-64 - stringDataArray[FlatFileMappings.BARSTATE_ACROBATICS] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_ALCHEMY] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_ARCHERY] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_AXES] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_EXCAVATION] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_FISHING] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_HERBALISM] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_MINING] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_REPAIR] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_SALVAGE] = "DISABLED"; //Child skills - stringDataArray[FlatFileMappings.BARSTATE_SMELTING] = "DISABLED"; //Child skills - stringDataArray[FlatFileMappings.BARSTATE_SWORDS] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_TAMING] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_UNARMED] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_WOODCUTTING] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_TRIDENTS] = "NORMAL"; - stringDataArray[FlatFileMappings.BARSTATE_CROSSBOWS] = "NORMAL"; - - stringDataArray[FlatFileMappings.COOLDOWN_ARCHERY_SUPER_1] = "0"; - stringDataArray[FlatFileMappings.COOLDOWN_CROSSBOWS_SUPER_1] = "0"; - stringDataArray[FlatFileMappings.COOLDOWN_TRIDENTS_SUPER_1] = "0"; - - stringDataArray[FlatFileMappings.CHATSPY_TOGGLE] = "0"; - stringDataArray[FlatFileMappings.LEADERBOARD_IGNORED] = "0"; - - //This part is a bit odd because lastlogin already has a place in the index but it was unused - stringDataArray[FlatFileMappings.LAST_LOGIN] = "0"; - - updated = true; - } - - //TODO: If new skills are added this needs to be rewritten - if (Config.getInstance().getTruncateSkills()) { - for (RootSkill rootSkill : PrimarySkillType.getImmutableCoreRootSkillSet()) { - if(PrimarySkillType.isChildSkill(rootSkill)) - continue; - - int index = getSkillIndex(rootSkill); - if (index >= stringDataArray.length) { - continue; - } - int cap = Config.getInstance().getLevelCap(rootSkill); - if (Integer.parseInt(stringDataArray[index]) > cap) { - mcMMO.p.getLogger().warning("Truncating " + rootSkill.getRawSkillName() + " to configured max level for player " + stringDataArray[FlatFileMappings.USERNAME]); - stringDataArray[index] = cap + ""; - updated = true; - } - } - } - - boolean corrupted = false; - - //TODO: Update this corruption code, its super out of date - //TODO: Update this corruption code, its super out of date - //TODO: Update this corruption code, its super out of date - //TODO: Update this corruption code, its super out of date - //TODO: Update this corruption code, its super out of date - //TODO: Update this corruption code, its super out of date - //TODO: Update this corruption code, its super out of date - //TODO: Update this corruption code, its super out of date - //TODO: Update this corruption code, its super out of dated - - for (int i = 0; i < stringDataArray.length; i++) { - //Sigh... this code - if (stringDataArray[i].isEmpty() && !(i == 2 || i == 3 || i == 23 || i == 33 || i == 41)) { - mcMMO.p.getLogger().info("Player data at index "+i+" appears to be empty, possible corruption of data has occurred."); - corrupted = true; - if (i == 37) { - stringDataArray[i] = String.valueOf(System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR); - } - else if (i == 38) { - stringDataArray[i] = Config.getInstance().getMobHealthbarDefault().toString(); - } - else { - stringDataArray[i] = "0"; - } - } - - if (StringUtils.isInt(stringDataArray[i]) && i == 38) { - corrupted = true; - stringDataArray[i] = Config.getInstance().getMobHealthbarDefault().toString(); - } - - if (!StringUtils.isInt(stringDataArray[i]) && !(i == 0 || i == 2 || i == 3 || i == 23 || i == 33 || i == 38 || i == 41)) { - corrupted = true; - stringDataArray[i] = "0"; - } - } - - if (corrupted) { - mcMMO.p.getLogger().info("Updating corrupted database line for player " + stringDataArray[FlatFileMappings.USERNAME]); - } - - if (oldVersion != null) { - mcMMO.p.getLogger().info("Updating database line from before version " + oldVersion + " for player " + stringDataArray[FlatFileMappings.USERNAME]); - } - - updated |= corrupted; - updated |= oldVersion != null; - - if (Config.getInstance().getTruncateSkills()) { - Map skillsMap = getSkillMapFromLine(stringDataArray); - for (RootSkill rootSkill : PrimarySkillType.getNonChildSkills()) { - int cap = Config.getInstance().getLevelCap(rootSkill); - if (skillsMap.get(rootSkill) > cap) { - updated = true; - } - } - } - - if (updated) { - line = org.apache.commons.lang.StringUtils.join(stringDataArray, ":") + ":"; - } - // Prevent the same player from being present multiple times - if (stringDataArray.length == originalLength //If the length changed then the schema was expanded - && (!stringDataArray[FlatFileMappings.UUID_INDEX].isEmpty() - && !stringDataArray[FlatFileMappings.UUID_INDEX].equals(NULL_VALUE) - && !players.add(stringDataArray[FlatFileMappings.UUID_INDEX]))) { + if (rawSplitData.length >= (FlatFileMappings.UUID_INDEX + 1) //TODO: Test this condition + && (!rawSplitData[FlatFileMappings.UUID_INDEX].isEmpty() + && !rawSplitData[FlatFileMappings.UUID_INDEX].equals("NULL") && !players.add(rawSplitData[FlatFileMappings.UUID_INDEX]))) { + + mcMMO.p.getLogger().severe("Removing duplicate player data from mcmmo.users"); + mcMMO.p.getLogger().info("Duplicate Data: "+line); continue; } - writer.append(line).append("\r\n"); + //Correctly size the data (null entries for missing values) + if(line.length() < FlatFileMappings.LENGTH_OF_SPLIT_DATA_ARRAY) { //TODO: Test this condition + String[] correctSizeSplitData = Arrays.copyOf(rawSplitData, FlatFileMappings.LENGTH_OF_SPLIT_DATA_ARRAY); + line = org.apache.commons.lang.StringUtils.join(correctSizeSplitData, ":") + ":"; + rawSplitData = line.split(":"); + PlayerProfile temporaryProfile = loadFromLine(rawSplitData); + writeUserToLine(temporaryProfile, rawSplitData[FlatFileMappings.USERNAME], temporaryProfile.getUniqueId(), writer); + } else { + writer.append(line).append("\r\n"); + } + } // Write the new file @@ -1204,7 +1126,7 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { in.close(); } catch (IOException e) { - // Ignore + e.printStackTrace(); } } if (out != null) { @@ -1212,26 +1134,22 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { out.close(); } catch (IOException e) { - // Ignore + e.printStackTrace(); } } } } - mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_FISHING); - mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_BLAST_MINING_COOLDOWN); - mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_SQL_INDEXES); - mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_MOB_HEALTHBARS); -// mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.DROP_SQL_PARTY_NAMES); - mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.DROP_SPOUT); - mcMMO.getUpgradeManager().setUpgradeCompleted(UpgradeType.ADD_ALCHEMY); + if(corruptDataFound) + mcMMO.p.getLogger().info("Corrupt data was found and removed, everything should be working fine. It is possible some player data was lost."); + return; } usersFile.getParentFile().mkdir(); try { - mcMMO.p.getLogger().info("Creating mcmmo.users file..."); + mcMMO.p.debug("Creating mcmmo.users file..."); new File(mcMMO.getUsersFilePath()).createNewFile(); } catch (IOException e) { @@ -1269,7 +1187,7 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { } } - private @Nullable MMOPlayerData loadFromLine(@NotNull String[] dataStrSplit) { + private @Nullable PlayerData loadFromLine(@NotNull String[] dataStrSplit) { MMODataBuilder playerDataBuilder = new MMODataBuilder(); String username = dataStrSplit[FlatFileMappings.USERNAME]; @@ -1325,8 +1243,7 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { playerUUID = UUID.fromString(dataStrSplit[FlatFileMappings.UUID_INDEX]); } catch (Exception e) { - mcMMO.p.getLogger().severe("UUID not found for data entry, skipping entry"); - return null; + playerUUID = null; } try { @@ -1366,7 +1283,7 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { xpBarStateMap = MMOExperienceBarManager.generateDefaultBarStateMap(); } - MMOPlayerData mmoPlayerData; + PlayerData mmoPlayerData; try { //Set Player Data @@ -1489,57 +1406,4 @@ public final class FlatFileDatabaseManager extends AbstractDatabaseManager { @Override public void onDisable() { } - - public void resetMobHealthSettings() { - BufferedReader in = null; - FileWriter out = null; - String usersFilePath = mcMMO.getUsersFilePath(); - - synchronized (fileWritingLock) { - try { - in = new BufferedReader(new FileReader(usersFilePath)); - StringBuilder writer = new StringBuilder(); - String line; - - while ((line = in.readLine()) != null) { - // Remove empty lines from the file - if (line.isEmpty()) { - continue; - } - String[] character = line.split(":"); - - character[FlatFileMappings.HEALTHBAR] = Config.getInstance().getMobHealthbarDefault().toString(); - - line = org.apache.commons.lang.StringUtils.join(character, ":") + ":"; - - writer.append(line).append("\r\n"); - } - - // Write the new file - out = new FileWriter(usersFilePath); - out.write(writer.toString()); - } - catch (IOException e) { - mcMMO.p.getLogger().severe("Exception while reading " + usersFilePath + " (Are you sure you formatted it correctly?)" + e.toString()); - } - finally { - if (in != null) { - try { - in.close(); - } - catch (IOException e) { - // Ignore - } - } - if (out != null) { - try { - out.close(); - } - catch (IOException e) { - // Ignore - } - } - } - } - } } diff --git a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java index 2f26533b1..51b286587 100644 --- a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.database.DatabaseType; import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.database.UpgradeType; import com.gmail.nossr50.datatypes.player.*; -import com.gmail.nossr50.datatypes.skills.CoreSkills; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.mcMMO; @@ -15,12 +14,7 @@ import com.gmail.nossr50.util.skills.SkillUtils; import com.neetgames.mcmmo.MobHealthBarType; import com.neetgames.mcmmo.UniqueDataType; import com.neetgames.mcmmo.exceptions.InvalidSkillException; -import com.neetgames.mcmmo.exceptions.ProfileRetrievalException; -import com.neetgames.mcmmo.player.MMOPlayerData; -import com.neetgames.mcmmo.skill.RootSkill; import com.neetgames.mcmmo.skill.SkillBossBarState; -import com.neetgames.mcmmo.skill.SuperSkill; -import org.apache.commons.lang.NullArgumentException; import org.apache.tomcat.jdbc.pool.DataSource; import org.apache.tomcat.jdbc.pool.PoolProperties; import org.bukkit.entity.Player; @@ -32,7 +26,7 @@ import java.sql.*; import java.util.*; import java.util.concurrent.locks.ReentrantLock; -public final class SQLDatabaseManager extends AbstractDatabaseManager { +public final class SQLDatabaseManager implements DatabaseManager { private static final String ALL_QUERY_VERSION = "total"; public static final String MOBHEALTHBAR_VARCHAR = "VARCHAR(50)"; public static final String UUID_VARCHAR = "VARCHAR(36)"; @@ -281,8 +275,8 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { statement.setInt(14, dataSnapshot.getSkillLevel(PrimarySkillType.TRIDENTS)); statement.setInt(15, dataSnapshot.getSkillLevel(PrimarySkillType.CROSSBOWS)); int total = 0; - for (RootSkill rootSkill : PrimarySkillType.getNonChildSkills()) - total += dataSnapshot.getSkillLevel(rootSkill); + for (PrimarySkillType primarySkillType : PrimarySkillType.getNonChildSkills()) + total += dataSnapshot.getSkillLevel(primarySkillType); statement.setInt(16, total); statement.setInt(17, id); success &= (statement.executeUpdate() != 0); @@ -414,17 +408,17 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { return success; } - public @NotNull List readLeaderboard(@Nullable RootSkill rootSkill, int pageNumber, int statsPerPage) throws InvalidSkillException { + public @NotNull List readLeaderboard(@Nullable PrimarySkillType primarySkillType, int pageNumber, int statsPerPage) throws InvalidSkillException { List stats = new ArrayList<>(); //Fix for a plugin that people are using that is throwing SQL errors - if(rootSkill != null && PrimarySkillType.isChildSkill(rootSkill)) { + if(primarySkillType != null && PrimarySkillType.isChildSkill(primarySkillType)) { mcMMO.p.getLogger().severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); } - String query = rootSkill == null ? ALL_QUERY_VERSION : rootSkill.getRawSkillName().toLowerCase(Locale.ENGLISH); + String query = primarySkillType == null ? ALL_QUERY_VERSION : primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH); ResultSet resultSet = null; PreparedStatement statement = null; Connection connection = null; @@ -469,8 +463,8 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { try { connection = getConnection(PoolIdentifier.MISC); - for (RootSkill rootSkill : PrimarySkillType.getNonChildSkills()) { - String skillName = rootSkill.getRawSkillName().toLowerCase(Locale.ENGLISH); + for (PrimarySkillType primarySkillType : PrimarySkillType.getNonChildSkills()) { + String skillName = primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH); // Get count of all users with higher skill level than player String sql = "SELECT COUNT(*) AS 'rank' FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " + "AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " + @@ -497,7 +491,7 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { while (resultSet.next()) { if (resultSet.getString("user").equalsIgnoreCase(playerName)) { - skills.put(rootSkill, rank + resultSet.getRow()); + skills.put(primarySkillType, rank + resultSet.getRow()); break; } } @@ -639,7 +633,7 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { public @NotNull PlayerProfile loadPlayerProfile(@NotNull UUID uuid, @Nullable String playerName) { return loadPlayerFromDB(uuid, playerName); @Override - public @Nullable MMOPlayerData queryPlayerDataByPlayer(@NotNull Player player) throws ProfileRetrievalException, NullArgumentException { + public @Nullable PlayerData queryPlayerDataByPlayer(@NotNull Player player) throws ProfileRetrievalException, NullArgumentException { return loadPlayerProfile(player, player.getName(), player.getUniqueId()); } @@ -648,11 +642,11 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { throw new RuntimeException("Error looking up player, both UUID and playerName are null and one must not be."); } @Override - public @Nullable MMOPlayerData queryPlayerDataByUUID(@NotNull UUID uuid, @NotNull String playerName) throws ProfileRetrievalException, NullArgumentException { + public @Nullable PlayerData queryPlayerDataByUUID(@NotNull UUID uuid, @NotNull String playerName) throws ProfileRetrievalException, NullArgumentException { return loadPlayerProfile(null, playerName, uuid); } - private @Nullable MMOPlayerData loadPlayerProfile(@Nullable Player player, @NotNull String playerName, @Nullable UUID playerUUID) { + private @Nullable PlayerData loadPlayerProfile(@Nullable Player player, @NotNull String playerName, @Nullable UUID playerUUID) { PreparedStatement statement = null; Connection connection = null; ResultSet resultSet = null; @@ -675,7 +669,7 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { if (resultSet.next()) { try { - MMOPlayerData mmoPlayerData = loadFromResult(playerName, resultSet); + PlayerData mmoPlayerData = loadFromResult(playerName, resultSet); String name = resultSet.getString(42); // TODO: Magic Number, make sure it stays updated resultSet.close(); statement.close(); @@ -741,7 +735,7 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { resultSet = statement.executeQuery(); resultSet.next(); //TODO: Optimize, probably needless to make a snapshot here, brain tired - MMOPlayerData mmoPlayerData = loadFromResult(playerName, resultSet); + PlayerData mmoPlayerData = loadFromResult(playerName, resultSet); MMODataSnapshot mmoDataSnapshot = mcMMO.getUserManager().createPlayerDataSnapshot(mmoPlayerData); destination.saveUser(mmoDataSnapshot); resultSet.close(); @@ -1057,12 +1051,12 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { } if (Config.getInstance().getTruncateSkills()) { - for (RootSkill rootSkill : PrimarySkillType.getNonChildSkills()) { - int cap = Config.getInstance().getLevelCap(rootSkill); + for (PrimarySkillType primarySkillType : PrimarySkillType.getNonChildSkills()) { + int cap = Config.getInstance().getLevelCap(primarySkillType); if (cap != Integer.MAX_VALUE) { statement = connection.prepareStatement("UPDATE `" + tablePrefix + "skills` SET `" - + rootSkill.getRawSkillName().toLowerCase(Locale.ENGLISH) + "` = " + cap + " WHERE `" - + rootSkill.getRawSkillName().toLowerCase(Locale.ENGLISH) + "` > " + cap); + + primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH) + "` = " + cap + " WHERE `" + + primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH) + "` > " + cap); statement.executeUpdate(); tryClose(statement); } @@ -1226,13 +1220,13 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { } } - private @Nullable MMOPlayerData loadFromResult(@NotNull String playerName, @NotNull ResultSet result) throws SQLException { + private @Nullable PlayerData loadFromResult(@NotNull String playerName, @NotNull ResultSet result) throws SQLException { MMODataBuilder MMODataBuilder = new MMODataBuilder(); Map skills = new HashMap<>(); // Skill & Level Map skillsXp = new HashMap<>(); // Skill & XP - Map skillsDATS = new HashMap<>(); // Ability & Cooldown + Map skillsDATS = new HashMap<>(); // Ability & Cooldown Map uniqueData = new EnumMap(UniqueDataType.class); //Chimaera wing cooldown and other misc info - Map xpBarStateMap = new HashMap(); + Map xpBarStateMap = new HashMap(); MobHealthBarType mobHealthbarType; UUID uuid; @@ -1500,8 +1494,8 @@ public final class SQLDatabaseManager extends AbstractDatabaseManager { if (resultSet.getRow() != PrimarySkillType.getNonChildSkills().size()) { mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases"); - for (RootSkill rootSkill : PrimarySkillType.getNonChildSkills()) { - String skill_name = rootSkill.getRawSkillName().toLowerCase(Locale.ENGLISH); + for (PrimarySkillType primarySkillType : PrimarySkillType.getNonChildSkills()) { + String skill_name = primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH); try { statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_" + skill_name + "` (`" + skill_name + "`) USING BTREE"); diff --git a/src/main/java/com/gmail/nossr50/datatypes/experience/OfflineExperienceProcessor.java b/src/main/java/com/gmail/nossr50/datatypes/experience/OfflineExperienceProcessor.java index a7d3fc2aa..0eccb57bc 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/experience/OfflineExperienceProcessor.java +++ b/src/main/java/com/gmail/nossr50/datatypes/experience/OfflineExperienceProcessor.java @@ -1,6 +1,8 @@ package com.gmail.nossr50.datatypes.experience; import com.neetgames.mcmmo.experience.ExperienceHandler; - +//TODO: T&C Write implementation, this should be the exact same way OnlineExperienceProcessor handles stuff but without sending player messages or sounds and stuff like that +//TODO: Is this needed? Maybe just make OnlineExperienceProcessor handle both in a clean way public class OfflineExperienceProcessor { + } diff --git a/src/main/java/com/gmail/nossr50/datatypes/experience/OnlineExperienceProcessor.java b/src/main/java/com/gmail/nossr50/datatypes/experience/OnlineExperienceProcessor.java index 2dd398cb3..5e0ddaccc 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/experience/OnlineExperienceProcessor.java +++ b/src/main/java/com/gmail/nossr50/datatypes/experience/OnlineExperienceProcessor.java @@ -2,6 +2,8 @@ package com.gmail.nossr50.datatypes.experience; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.config.experience.ExperienceConfig; +import com.gmail.nossr50.datatypes.player.PlayerData; +import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.neetgames.mcmmo.party.Party; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; @@ -29,83 +31,75 @@ public class OnlineExperienceProcessor { private boolean isUsingUnarmed = false; - private final @NotNull MMOPlayerData mmoPlayerData; + private final @NotNull PlayerData mmoPlayerData; private final @NotNull MMOPlayer mmoPlayer; private final @NotNull Player playerRef; public OnlineExperienceProcessor(@NotNull MMOPlayer mmoPlayer, @NotNull Player playerRef) { this.mmoPlayer = mmoPlayer; this.playerRef = playerRef; - this.mmoPlayerData = mmoPlayer.getMMOPlayerData(); + this.mmoPlayerData = mmoPlayer.getMMOPlayerDataImpl(); } - @Override public int getPowerLevel() { int powerLevel = 0; - Map rootSkillLevelMap = mmoPlayerData.getDirtySkillLevelMap().unwrapMap(); + Map primarySkillTypeLevelMap = mmoPlayerData.getDirtySkillLevelMap().unwrapMap(); - for (RootSkill rootSkill : rootSkillLevelMap.keySet()) { - powerLevel += rootSkillLevelMap.get(rootSkill); + for (PrimarySkillType primarySkillType : primarySkillTypeLevelMap.keySet()) { + powerLevel += primarySkillTypeLevelMap.get(primarySkillType); } return powerLevel; } - @Override - public float getSkillXpLevelRaw(@NotNull RootSkill rootSkill) { - return mmoPlayerData.getSkillsExperienceMap().get(rootSkill); + public float getSkillXpLevelRaw(@NotNull PrimarySkillType primarySkillType) { + return mmoPlayerData.getSkillsExperienceMap().get(primarySkillType); } - @Override - public int getSkillXpValue(@NotNull RootSkill rootSkill) { - if(PrimarySkillType.isChildSkill(rootSkill)) { + public int getSkillXpValue(@NotNull PrimarySkillType primarySkillType) { + if(PrimarySkillType.isChildSkill(primarySkillType)) { return 0; } - return (int) Math.floor(getSkillXpLevelRaw(rootSkill)); + return (int) Math.floor(getSkillXpLevelRaw(primarySkillType)); } - @Override - public void setSkillXpValue(@NotNull RootSkill rootSkill, float xpLevel) { - if (PrimarySkillType.isChildSkill(rootSkill)) { + public void setSkillXpValue(@NotNull PrimarySkillType primarySkillType, float xpLevel) { + if (PrimarySkillType.isChildSkill(primarySkillType)) { return; } - mmoPlayerData.getSkillsExperienceMap().put(rootSkill, xpLevel); + mmoPlayerData.getSkillsExperienceMap().put(primarySkillType, xpLevel); } - @Override - public float levelUp(@NotNull RootSkill rootSkill) { - float xpRemoved = getExperienceToNextLevel(rootSkill); + public float levelUp(@NotNull PrimarySkillType primarySkillType) { + float xpRemoved = getExperienceToNextLevel(primarySkillType); - setSkillLevel(rootSkill, getSkillLevel(rootSkill) + 1); - setSkillXpValue(rootSkill, getSkillXpValue(rootSkill) - xpRemoved); + setSkillLevel(primarySkillType, getSkillLevel(primarySkillType) + 1); + setSkillXpValue(primarySkillType, getSkillXpValue(primarySkillType) - xpRemoved); return xpRemoved; } - @Override - public boolean hasReachedLevelCap(@NotNull RootSkill rootSkill) { + public boolean hasReachedLevelCap(@NotNull PrimarySkillType primarySkillType) { if(hasReachedPowerLevelCap()) return true; - return getSkillLevel(rootSkill) >= Config.getInstance().getLevelCap(rootSkill); + return getSkillLevel(primarySkillType) >= Config.getInstance().getLevelCap(primarySkillType); } - @Override public boolean hasReachedPowerLevelCap() { return this.getPowerLevel() >= Config.getInstance().getPowerLevelCap(); } - @Override - public void beginXpGain(@NotNull RootSkill rootSkill, float xp, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) { + public void beginXpGain(@NotNull PrimarySkillType primarySkillType, float xp, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) { if (xp <= 0.0) { return; } - if (PrimarySkillType.isChildSkill(rootSkill)) { - Set parentSkills = FamilyTree.getParentSkills(rootSkill); + if (PrimarySkillType.isChildSkill(primarySkillType)) { + Set parentSkills = FamilyTree.getParentSkills(primarySkillType); float splitXp = xp / parentSkills.size(); for (RootSkill parentSkill : parentSkills) { @@ -118,49 +112,45 @@ public class OnlineExperienceProcessor { //TODO: The logic here is so stupid... rewrite later // Return if the experience has been shared - if (mmoPlayer.getParty() != null && ShareHandler.handleXpShare(xp, mmoPlayer, mmoPlayer.getParty(), rootSkill, ShareHandler.getSharedXpGainReason(xpGainReason))) { + if (mmoPlayer.getParty() != null && ShareHandler.handleXpShare(xp, mmoPlayer, mmoPlayer.getParty(), primarySkillType, ShareHandler.getSharedXpGainReason(xpGainReason))) { return; } - beginUnsharedXpGain(rootSkill, xp, xpGainReason, xpGainSource); + beginUnsharedXpGain(primarySkillType, xp, xpGainReason, xpGainSource); } - @Override - public void beginUnsharedXpGain(@NotNull RootSkill rootSkill, float xp, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) { + public void beginUnsharedXpGain(@NotNull PrimarySkillType primarySkillType, float xp, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) { if(Misc.adaptPlayer(mmoPlayer).getGameMode() == GameMode.CREATIVE) return; - ExperienceUtils.applyXpGain(mmoPlayer, rootSkill, modifyXpGain(rootSkill, xp), xpGainReason, xpGainSource); + ExperienceUtils.applyXpGain(mmoPlayer, primarySkillType, modifyXpGain(primarySkillType, xp), xpGainReason, xpGainSource); Party party = mmoPlayer.getParty(); if (party != null) { if (!Config.getInstance().getPartyXpNearMembersNeeded() || !mcMMO.getPartyManager().getNearMembers(mmoPlayer).isEmpty()) { - party.getPartyExperienceManager().applyXpGain(modifyXpGain(rootSkill, xp)); + party.getPartyExperienceManager().applyXpGain(modifyXpGain(primarySkillType, xp)); } } } - @Override - public int getSkillLevel(@NotNull RootSkill rootSkill) { - return PrimarySkillType.isChildSkill(rootSkill) ? getChildSkillLevel(rootSkill) : getSkillLevel(rootSkill); + public int getSkillLevel(@NotNull PrimarySkillType primarySkillType) { + return PrimarySkillType.isChildSkill(primarySkillType) ? getChildSkillLevel(primarySkillType) : getSkillLevel(primarySkillType); } - @Override - public int getExperienceToNextLevel(@NotNull RootSkill rootSkill) { - if(PrimarySkillType.isChildSkill(rootSkill)) { + public int getExperienceToNextLevel(@NotNull PrimarySkillType primarySkillType) { + if(PrimarySkillType.isChildSkill(primarySkillType)) { return 0; } - int level = (ExperienceConfig.getInstance().getCumulativeCurveEnabled()) ? getPowerLevel() : getSkillLevel(rootSkill); + int level = (ExperienceConfig.getInstance().getCumulativeCurveEnabled()) ? getPowerLevel() : getSkillLevel(primarySkillType); FormulaType formulaType = ExperienceConfig.getInstance().getFormulaType(); return mcMMO.getFormulaManager().getXPtoNextLevel(level, formulaType); } - @Override - public int getChildSkillLevel(@NotNull RootSkill rootSkill) { - Set parents = FamilyTree.getParentSkills(rootSkill); + public int getChildSkillLevel(@NotNull PrimarySkillType primarySkillType) { + Set parents = FamilyTree.getParentSkills(primarySkillType); int sum = 0; for (RootSkill parentIdentity : parents) { @@ -170,8 +160,7 @@ public class OnlineExperienceProcessor { return sum / parents.size(); } - @Override - public void removeXp(@NotNull RootSkill skill, int xp) { + public void removeXp(@NotNull PrimarySkillType skill, int xp) { if (skill.isChildSkill()) { return; } @@ -179,8 +168,7 @@ public class OnlineExperienceProcessor { setSkillXpValue(skill, getSkillXpValue(skill) - xp); } - @Override - public void removeXp(RootSkill skill, float xp) { + public void removeXp(PrimarySkillType skill, float xp) { if (skill.isChildSkill()) { return; } @@ -188,9 +176,8 @@ public class OnlineExperienceProcessor { setSkillXpValue(skill, getSkillXpValue(skill) - xp); } - @Override - public void setSkillLevel(@NotNull RootSkill rootSkill, int level) { - if (rootSkill.isChildSkill()) { + public void setSkillLevel(@NotNull PrimarySkillType primarySkillType, int level) { + if (primarySkillType.isChildSkill()) { return; } @@ -198,19 +185,17 @@ public class OnlineExperienceProcessor { if(level < 0) level = 0; - setSkillLevel(rootSkill, level); - setSkillXpValue(rootSkill, 0F); + setSkillLevel(primarySkillType, level); + setSkillXpValue(primarySkillType, 0F); } - @Override - public void addLevels(@NotNull RootSkill rootSkill, int levels) { - setSkillLevel(rootSkill, getSkillLevel(rootSkill) + levels); + public void addLevels(@NotNull PrimarySkillType primarySkillType, int levels) { + setSkillLevel(primarySkillType, getSkillLevel(primarySkillType) + levels); } - @Override - public void addXp(@NotNull RootSkill rootSkill, float xp) { - if (rootSkill.isChildSkill()) { - Set parentSkills = FamilyTree.getParents(rootSkill); + public void addXp(@NotNull PrimarySkillType primarySkillType, float xp) { + if (primarySkillType.isChildSkill()) { + Set parentSkills = FamilyTree.getParents(primarySkillType); float dividedXP = (xp / parentSkills.size()); for (RootSkill parentSkill : parentSkills) { @@ -218,28 +203,25 @@ public class OnlineExperienceProcessor { } } else { - setSkillXpValue(rootSkill, getSkillXpValue(rootSkill) + xp); + setSkillXpValue(primarySkillType, getSkillXpValue(primarySkillType) + xp); } } - @Override - public float getRegisteredXpGain(@NotNull RootSkill rootSkill) { + public float getRegisteredXpGain(@NotNull PrimarySkillType primarySkillType) { float xp = 0F; - if (get(rootSkill) != null) { //?? - xp = rollingSkillsXp.get(rootSkill); + if (get(primarySkillType) != null) { //?? + xp = rollingSkillsXp.get(primarySkillType); } return xp; } - @Override - public void registerXpGain(@NotNull RootSkill rootSkill, float xp) { - gainedSkillsXp.add(new SkillXpGain(rootSkill, xp)); - rollingSkillsXp.put(rootSkill, getRegisteredXpGain(rootSkill) + xp); + public void registerXpGain(@NotNull PrimarySkillType primarySkillType, float xp) { + gainedSkillsXp.add(new SkillXpGain(primarySkillType, xp)); + rollingSkillsXp.put(primarySkillType, getRegisteredXpGain(primarySkillType) + xp); } - @Override public void purgeExpiredXpGains() { SkillXpGain gain; while ((gain = gainedSkillsXp.poll()) != null) { @@ -247,44 +229,40 @@ public class OnlineExperienceProcessor { } } - @Override - private float modifyXpGain(@NotNull RootSkill rootSkill, float xp) { - if ((rootSkill.getMaxLevel() <= getSkillLevel(rootSkill)) || (Config.getInstance().getPowerLevelCap() <= getPowerLevel())) { + private float modifyXpGain(@NotNull PrimarySkillType primarySkillType, float xp) { + if ((primarySkillType.getMaxLevel() <= getSkillLevel(primarySkillType)) || (Config.getInstance().getPowerLevelCap() <= getPowerLevel())) { return 0; } - xp = (float) (xp / rootSkill.getXpModifier() * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()); + xp = (float) (xp / primarySkillType.getXpModifier() * ExperienceConfig.getInstance().getExperienceGainsGlobalMultiplier()); - return PerksUtils.handleXpPerks(Misc.adaptPlayer(mmoPlayer), xp, rootSkill); + return PerksUtils.handleXpPerks(Misc.adaptPlayer(mmoPlayer), xp, primarySkillType); } - @Override - public double getProgressInCurrentSkillLevel(@NotNull RootSkill rootSkill) throws UnknownSkillException + public double getProgressInCurrentSkillLevel(@NotNull PrimarySkillType primarySkillType) throws UnknownSkillException { - if(PrimarySkillType.isChildSkill(rootSkill)) { + if(PrimarySkillType.isChildSkill(primarySkillType)) { return 1.0D; } - double currentXP = getSkillXpValue(rootSkill); - double maxXP = getExperienceToNextLevel(rootSkill); + double currentXP = getSkillXpValue(primarySkillType); + double maxXP = getExperienceToNextLevel(primarySkillType); return (currentXP / maxXP); } - @Override public void setUsingUnarmed(boolean bool) { isUsingUnarmed = bool; } - @Override - public void applyXpGain(@NotNull RootSkill rootSkill, float xp, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) { + public void applyXpGain(@NotNull PrimarySkillType primarySkillType, float xp, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) { //Only check for permissions if the player is online, otherwise just assume a command is being executed by an admin or some other means and add the XP - if (!Permissions.skillEnabled(mmoPlayer.getPlayer(), PrimarySkillType.getSkill(rootSkill))) { + if (!Permissions.skillEnabled(mmoPlayer.getPlayer(), PrimarySkillType.getSkill(primarySkillType))) { return; } - if (PrimarySkillType.isChildSkill(rootSkill)) { - Set parentSkills = FamilyTree.getParentSkills(rootSkill); + if (PrimarySkillType.isChildSkill(primarySkillType)) { + Set parentSkills = FamilyTree.getParentSkills(primarySkillType); for (RootSkill parentSkill : parentSkills) { applyXpGain(parentSkill, xp / parentSkills.size(), xpGainReason, xpGainSource); @@ -293,16 +271,15 @@ public class OnlineExperienceProcessor { return; } - if (!EventUtils.handleXpGainEvent(Misc.adaptPlayer(mmoPlayer), rootSkill, xp, xpGainReason)) { + if (!EventUtils.handleXpGainEvent(Misc.adaptPlayer(mmoPlayer), primarySkillType, xp, xpGainReason)) { return; } - setUsingUnarmed(rootSkill == PrimarySkillType.UNARMED); - updateLevelStats(rootSkill, xpGainReason, xpGainSource); + setUsingUnarmed(primarySkillType == PrimarySkillType.UNARMED); + updateLevelStats(primarySkillType, xpGainReason, xpGainSource); } - @Override - public void processPostXpEvent(@NotNull RootSkill rootSkill, @NotNull XPGainSource xpGainSource) + public void processPostXpEvent(@NotNull PrimarySkillType primarySkillType, @NotNull XPGainSource xpGainSource) { /* * Everything in this method requires an online player, so if they aren't online we don't waste our time @@ -313,8 +290,8 @@ public class OnlineExperienceProcessor { //Check if they've reached the power level cap just now if(hasReachedPowerLevelCap()) { NotificationManager.sendPlayerInformationChatOnly(Misc.adaptPlayer(mmoPlayer), "LevelCap.PowerLevel", String.valueOf(Config.getInstance().getPowerLevelCap())); - } else if(hasReachedLevelCap(rootSkill)) { - NotificationManager.sendPlayerInformationChatOnly(Misc.adaptPlayer(mmoPlayer), "LevelCap.Skill", String.valueOf(Config.getInstance().getLevelCap(rootSkill)), rootSkill.getRawSkillName()); + } else if(hasReachedLevelCap(primarySkillType)) { + NotificationManager.sendPlayerInformationChatOnly(Misc.adaptPlayer(mmoPlayer), "LevelCap.Skill", String.valueOf(Config.getInstance().getLevelCap(primarySkillType)), primarySkillType.getRawSkillName()); } //Updates from Party sources @@ -325,33 +302,32 @@ public class OnlineExperienceProcessor { if(xpGainSource == XPGainSource.PASSIVE && !ExperienceConfig.getInstance().isPassiveGainsExperienceBarsEnabled()) return; - mmoPlayer.updateXPBar(rootSkill); + mmoPlayer.updateXPBar(primarySkillType); } - @Override - public void updateLevelStats(@NotNull RootSkill rootSkill, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) { - if(hasReachedLevelCap(rootSkill)) + public void updateLevelStats(@NotNull PrimarySkillType primarySkillType, @NotNull XPGainReason xpGainReason, @NotNull XPGainSource xpGainSource) { + if(hasReachedLevelCap(primarySkillType)) return; - if (getSkillXpLevelRaw(rootSkill) < getExperienceToNextLevel(rootSkill)) { - processPostXpEvent(rootSkill, xpGainSource); + if (getSkillXpLevelRaw(primarySkillType) < getExperienceToNextLevel(primarySkillType)) { + processPostXpEvent(primarySkillType, xpGainSource); return; } int levelsGained = 0; float xpRemoved = 0; - while (getSkillXpLevelRaw(rootSkill) >= getExperienceToNextLevel(rootSkill)) { - if (hasReachedLevelCap(rootSkill)) { - setSkillXpValue(rootSkill, 0); + while (getSkillXpLevelRaw(primarySkillType) >= getExperienceToNextLevel(primarySkillType)) { + if (hasReachedLevelCap(primarySkillType)) { + setSkillXpValue(primarySkillType, 0); break; } - xpRemoved += levelUp(rootSkill); + xpRemoved += levelUp(primarySkillType); levelsGained++; } - if (EventUtils.tryLevelChangeEvent(Misc.adaptPlayer(mmoPlayer), rootSkill, levelsGained, xpRemoved, true, xpGainReason)) { + if (EventUtils.tryLevelChangeEvent(Misc.adaptPlayer(mmoPlayer), primarySkillType, levelsGained, xpRemoved, true, xpGainReason)) { return; } @@ -363,9 +339,9 @@ public class OnlineExperienceProcessor { * Check to see if the player unlocked any new skills */ - NotificationManager.sendPlayerLevelUpNotification(mmoPlayer, rootSkill, levelsGained, getSkillLevel(rootSkill)); + NotificationManager.sendPlayerLevelUpNotification(mmoPlayer, primarySkillType, levelsGained, getSkillLevel(primarySkillType)); //UPDATE XP BARS - processPostXpEvent(rootSkill, xpGainSource); + processPostXpEvent(primarySkillType, xpGainSource); } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/AbstractMMOPlayer.java b/src/main/java/com/gmail/nossr50/datatypes/player/AbstractMMOPlayer.java index 5b2ed3b87..246111b06 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/AbstractMMOPlayer.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/AbstractMMOPlayer.java @@ -2,18 +2,17 @@ package com.gmail.nossr50.datatypes.player; import com.gmail.nossr50.datatypes.experience.OfflineExperienceProcessor; import com.gmail.nossr50.datatypes.experience.OnlineExperienceProcessor; -import com.neetgames.mcmmo.experience.ExperienceHandler; +import com.neetgames.mcmmo.experience.ExperienceProcessor; import com.neetgames.mcmmo.player.MMOPlayer; -import com.neetgames.mcmmo.player.MMOPlayerData; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; public abstract class AbstractMMOPlayer implements MMOPlayer { /* All of the persistent data for a player that gets saved and loaded from DB */ - protected final @NotNull MMOPlayerData mmoPlayerData; //All persistent data is kept here + protected final @NotNull PlayerData mmoPlayerData; //All persistent data is kept here /* Managers */ - protected final @NotNull ExperienceHandler experienceHandler; + protected final @NotNull ExperienceProcessor experienceProcessor; protected final @NotNull CooldownManager cooldownManager; /** @@ -22,9 +21,9 @@ public abstract class AbstractMMOPlayer implements MMOPlayer { * * @param mmoPlayerData player data */ - public AbstractMMOPlayer(@NotNull Player player, @NotNull MMOPlayerDataImpl mmoPlayerData) { + public AbstractMMOPlayer(@NotNull Player player, @NotNull PlayerData mmoPlayerData) { this.mmoPlayerData = mmoPlayerData; - this.experienceHandler = new OnlineExperienceProcessor(mmoPlayerData); + this.experienceProcessor = new OnlineExperienceProcessor(mmoPlayerData); this.cooldownManager = new CooldownManager(mmoPlayerData); } @@ -33,9 +32,9 @@ public abstract class AbstractMMOPlayer implements MMOPlayer { * * @param mmoPlayerData player data */ - public AbstractMMOPlayer(@NotNull MMOPlayerDataImpl mmoPlayerData) { + public AbstractMMOPlayer(@NotNull PlayerData mmoPlayerData) { this.mmoPlayerData = mmoPlayerData; - this.experienceHandler = new OfflineExperienceProcessor(mmoPlayerData); + this.experienceProcessor = new OfflineExperienceProcessor(mmoPlayerData); this.cooldownManager = new CooldownManager(mmoPlayerData); } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/CooldownManager.java b/src/main/java/com/gmail/nossr50/datatypes/player/CooldownManager.java index a44702287..f46656a5f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/CooldownManager.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/CooldownManager.java @@ -8,9 +8,9 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class CooldownManager { - private final @NotNull MMOPlayerDataImpl playerDataRef; + private final @NotNull PlayerData playerDataRef; - public CooldownManager(@NotNull MMOPlayerDataImpl playerDataRef) { + public CooldownManager(@NotNull PlayerData playerDataRef) { this.playerDataRef = playerDataRef; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/MMODataBuilder.java b/src/main/java/com/gmail/nossr50/datatypes/player/MMODataBuilder.java index e3e52fc84..dbf0ea078 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/MMODataBuilder.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/MMODataBuilder.java @@ -1,13 +1,11 @@ package com.gmail.nossr50.datatypes.player; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.experience.MMOExperienceBarManager; import com.neetgames.mcmmo.UniqueDataType; -import com.neetgames.mcmmo.player.MMOPlayerData; -import com.neetgames.mcmmo.skill.RootSkill; import com.neetgames.mcmmo.skill.SkillBossBarState; -import com.neetgames.mcmmo.skill.SuperSkill; import org.apache.commons.lang.NullArgumentException; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; @@ -29,9 +27,9 @@ public class MMODataBuilder { /* Skill Data */ private @Nullable Map skillLevelValues; private @Nullable Map skillExperienceValues; - private @Nullable Map abilityDeactivationTimestamps; // Ability & Cooldown + private @Nullable Map abilityDeactivationTimestamps; // Ability & Cooldown private @Nullable Map uniquePlayerData; //Misc data that doesn't fit into other categories (chimaera wing, etc..) - private @Nullable Map barStateMap; + private @Nullable Map barStateMap; /* Special Flags */ private boolean partyChatSpying; @@ -40,28 +38,28 @@ public class MMODataBuilder { /* Scoreboards */ private int scoreboardTipsShown; - public @NotNull MMOPlayerData buildNewPlayerData(@NotNull Player player) { + public @NotNull PlayerData buildNewPlayerData(@NotNull Player player) { /* * New Profile with default values */ return buildNewPlayerData(player.getUniqueId(), player.getName()); } - public @Nullable MMOPlayerData buildNewPlayerData(@NotNull OfflinePlayer offlinePlayer) { + public @Nullable PlayerData buildNewPlayerData(@NotNull OfflinePlayer offlinePlayer) { if(offlinePlayer.getName() != null) return buildNewPlayerData(offlinePlayer.getUniqueId(), offlinePlayer.getName()); else return null; } - public @NotNull MMOPlayerData buildNewPlayerData(@NotNull UUID playerUUID, @NotNull String playerName) { + public @NotNull PlayerData buildNewPlayerData(@NotNull UUID playerUUID, @NotNull String playerName) { /* * New Profile with default values */ - return new MMOPlayerDataImpl(playerUUID, playerName); + return new PlayerData(playerUUID, playerName); } - public @NotNull MMOPlayerData build() throws Exception { + public @NotNull PlayerData build() throws Exception { if(playerUUID == null) throw new NullArgumentException("playerUUID"); @@ -93,19 +91,22 @@ public class MMODataBuilder { validateBarStateMapEntries(barStateMap); - return new MMOPlayerDataImpl(playerUUID, playerName, partyChatSpying, skillLevelValues, skillExperienceValues, abilityDeactivationTimestamps, uniquePlayerData, barStateMap, scoreboardTipsShown, lastLogin, leaderBoardExemption); + return new PlayerData(playerUUID, playerName, partyChatSpying, skillLevelValues, skillExperienceValues, abilityDeactivationTimestamps, uniquePlayerData, barStateMap, scoreboardTipsShown, lastLogin, leaderBoardExemption); } - private void validateBarStateMapEntries(@NotNull Map map) { - Map barMapDefaults = MMOExperienceBarManager.generateDefaultBarStateMap(); + private void validateBarStateMapEntries(@NotNull Map map) { + Map barMapDefaults = MMOExperienceBarManager.generateDefaultBarStateMap(); - for(RootSkill key : mcMMO.p.getSkillRegister().getRootSkills()) { + for(PrimarySkillType key : PrimarySkillType.values()) { map.putIfAbsent(key, barMapDefaults.get(key)); } } private void validateExperienceValueMapEntries(@NotNull Map map) { - for(RootSkill key : mcMMO.p.getSkillRegister().getRootSkills()) { + for(PrimarySkillType key : PrimarySkillType.values()) { + if(key.isChildSkill()) + continue; + map.putIfAbsent(key, 0F); if(map.get(key) < 0F) { @@ -126,8 +127,8 @@ public class MMODataBuilder { } } - private void validateAbilityCooldownMapEntries(@NotNull Map map) { - for(SuperSkill key : mcMMO.p.getSkillRegister().getSuperSkills()) { + private void validateAbilityCooldownMapEntries(@NotNull Map map) { + for(SuperAbilityType key : SuperAbilityType.values()) { map.putIfAbsent(key, 0); if(map.get(key) < 0) { @@ -138,7 +139,11 @@ public class MMODataBuilder { } private void validateSkillLevelMapEntries(@NotNull Map map) { - for(RootSkill key : mcMMO.p.getSkillRegister().getRootSkills()) { + for(PrimarySkillType key : PrimarySkillType.values()) { + + if(key.isChildSkill()) + continue; + map.putIfAbsent(key, 0); if(map.get(key) < 0) { @@ -193,11 +198,11 @@ public class MMODataBuilder { return this; } - public @Nullable Map getAbilityDeactivationTimestamps() { + public @Nullable Map getAbilityDeactivationTimestamps() { return abilityDeactivationTimestamps; } - public @NotNull MMODataBuilder setAbilityDeactivationTimestamps(@NotNull Map abilityDeactivationTimestamps) { + public @NotNull MMODataBuilder setAbilityDeactivationTimestamps(@NotNull Map abilityDeactivationTimestamps) { this.abilityDeactivationTimestamps = abilityDeactivationTimestamps; return this; } @@ -211,11 +216,11 @@ public class MMODataBuilder { return this; } - public @Nullable Map getBarStateMap() { + public @Nullable Map getBarStateMap() { return barStateMap; } - public @NotNull MMODataBuilder setBarStateMap(@NotNull Map barStateMap) { + public @NotNull MMODataBuilder setBarStateMap(@NotNull Map barStateMap) { this.barStateMap = barStateMap; return this; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/MMODataSnapshot.java b/src/main/java/com/gmail/nossr50/datatypes/player/MMODataSnapshot.java index 234aa09d8..2c6dd3f4f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/MMODataSnapshot.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/MMODataSnapshot.java @@ -3,9 +3,8 @@ package com.gmail.nossr50.datatypes.player; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.google.common.collect.ImmutableMap; -import com.neetgames.mcmmo.MobHealthBarType; import com.neetgames.mcmmo.UniqueDataType; -import com.neetgames.mcmmo.player.MMOPlayerData; +import com.neetgames.mcmmo.player.MMOPlayerDataImpl; import com.neetgames.mcmmo.skill.RootSkill; import com.neetgames.mcmmo.skill.SkillBossBarState; import com.neetgames.mcmmo.skill.SuperSkill; @@ -36,7 +35,7 @@ public class MMODataSnapshot { private final int scoreboardTipsShown; - public MMODataSnapshot(@NotNull MMOPlayerData mmoPlayerData) { + public MMODataSnapshot(@NotNull PlayerData mmoPlayerData) { playerName = mmoPlayerData.getPlayerName(); playerUUID = mmoPlayerData.getPlayerUUID(); lastLogin = mmoPlayerData.getLastLogin(); @@ -94,12 +93,12 @@ public class MMODataSnapshot { return scoreboardTipsShown; } - public int getSkillLevel(@NotNull RootSkill rootSkill) { - return skillLevelValues.getOrDefault(rootSkill, 0); + public int getSkillLevel(@NotNull PrimarySkillType primarySkillType) { + return skillLevelValues.getOrDefault(primarySkillType, 0); } - public int getSkillXpLevel(@NotNull RootSkill rootSkill) { - return (skillExperienceValues.getOrDefault(rootSkill, 0F)).intValue(); + public int getSkillXpLevel(@NotNull PrimarySkillType primarySkillType) { + return (skillExperienceValues.getOrDefault(primarySkillType, 0F)).intValue(); } public long getAbilityDATS(@NotNull SuperAbilityType superAbilityType) { diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java index b01150ab4..65ff2e010 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.config.ChatConfig; import com.gmail.nossr50.config.WorldBlacklist; import com.gmail.nossr50.datatypes.chat.ChatChannel; import com.gmail.nossr50.datatypes.skills.CoreRootSkill; -import com.gmail.nossr50.datatypes.skills.CoreSkills; import com.neetgames.mcmmo.party.Party; import com.gmail.nossr50.party.PartyTeleportRecord; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; @@ -34,10 +33,7 @@ import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.experience.MMOExperienceBarManager; import com.gmail.nossr50.util.input.AbilityActivationProcessor; import com.gmail.nossr50.util.input.SuperSkillManagerImpl; -import com.neetgames.mcmmo.player.MMOPlayerData; import com.neetgames.mcmmo.player.OnlineMMOPlayer; -import com.neetgames.mcmmo.player.SuperSkillManager; -import com.neetgames.mcmmo.skill.RootSkill; import net.kyori.adventure.identity.Identified; import net.kyori.adventure.identity.Identity; import org.bukkit.Location; @@ -58,7 +54,7 @@ public class McMMOPlayer extends PlayerProfile implements OnlineMMOPlayer, Ident //Used in our chat systems for chat messages private final @NotNull PlayerAuthor playerAuthor; - private final @NotNull Map skillManagers = new HashMap<>(); + private final @NotNull Map skillManagers = new HashMap<>(); private final @NotNull MMOExperienceBarManager experienceBarManager; private @Nullable PartyTeleportRecord ptpRecord; @@ -93,7 +89,7 @@ public class McMMOPlayer extends PlayerProfile implements OnlineMMOPlayer, Ident * New * Player */ - super(new MMOPlayerDataImpl(player.getUniqueId(), player.getName())); + super(new PlayerData(player.getUniqueId(), player.getName())); UUID uuid = player.getUniqueId(); identity = Identity.identity(uuid); @@ -126,7 +122,7 @@ public class McMMOPlayer extends PlayerProfile implements OnlineMMOPlayer, Ident * @param player target player * @param mmoPlayerData existing player data */ - public McMMOPlayer(@NotNull Player player, @NotNull MMOPlayerData mmoPlayerData) { + public McMMOPlayer(@NotNull Player player, @NotNull PlayerData mmoPlayerData) { /* * Existing * Player @@ -587,8 +583,8 @@ public class McMMOPlayer extends PlayerProfile implements OnlineMMOPlayer, Ident } @Override - public void updateXPBar(@NotNull RootSkill rootSkill) { - experienceBarManager.updateExperienceBar(rootSkill, mcMMO.p); + public void updateXPBar(@NotNull PrimarySkillType primarySkillType) { + experienceBarManager.updateExperienceBar(primarySkillType, mcMMO.p); } @Override @@ -603,8 +599,7 @@ public class McMMOPlayer extends PlayerProfile implements OnlineMMOPlayer, Ident return playerPartyRef; } - @Override - public @NotNull SuperSkillManager getSuperSkillManager() { + public @NotNull SuperSkillManagerImpl getSuperSkillManager() { return superSkillManagerImpl; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/MMOPlayerDataImpl.java b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerData.java similarity index 77% rename from src/main/java/com/gmail/nossr50/datatypes/player/MMOPlayerDataImpl.java rename to src/main/java/com/gmail/nossr50/datatypes/player/PlayerData.java index dfb465c36..feed6a655 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/MMOPlayerDataImpl.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerData.java @@ -1,17 +1,16 @@ package com.gmail.nossr50.datatypes.player; import com.gmail.nossr50.config.AdvancedConfig; -import com.gmail.nossr50.datatypes.skills.CoreSkills; +import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.datatypes.validation.NonNullRule; import com.gmail.nossr50.datatypes.validation.PositiveIntegerRule; import com.gmail.nossr50.datatypes.validation.Validator; -import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.experience.MMOExperienceBarManager; import com.google.common.collect.ImmutableMap; import com.neetgames.mcmmo.UniqueDataType; import com.neetgames.mcmmo.exceptions.UnexpectedValueException; import com.neetgames.mcmmo.skill.*; -import com.neetgames.mcmmo.player.MMOPlayerData; import com.neetgames.neetlib.dirtydata.DirtyData; import com.neetgames.neetlib.dirtydata.DirtyMap; import com.neetgames.neetlib.mutableprimitives.MutableBoolean; @@ -25,7 +24,7 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; -public class MMOPlayerDataImpl implements MMOPlayerData { +public class PlayerData { private final @NotNull MutableBoolean dirtyFlag; //Dirty values in this class will change this flag as needed @@ -39,9 +38,9 @@ public class MMOPlayerDataImpl implements MMOPlayerData { /* Skill Data */ private final @NotNull DirtyMap skillLevelValues; private final @NotNull DirtyMap skillExperienceValues; - private final @NotNull DirtyMap abilityDeactivationTimestamps; // Ability & Cooldown + private final @NotNull DirtyMap abilityDeactivationTimestamps; // Ability & Cooldown private final @NotNull DirtyMap uniquePlayerData; //Misc data that doesn't fit into other categories (chimaera wing, etc..) - private final @NotNull DirtyMap barStateMap; + private final @NotNull DirtyMap barStateMap; /* Special Flags */ private final @NotNull DirtyData partyChatSpying; @@ -58,7 +57,7 @@ public class MMOPlayerDataImpl implements MMOPlayerData { * @param playerName target player's name * @throws NullArgumentException thrown when never null arguments are null */ - public MMOPlayerDataImpl(@NotNull UUID playerUUID, @NotNull String playerName) throws NullArgumentException { + public PlayerData(@NotNull UUID playerUUID, @NotNull String playerName) throws NullArgumentException { /* * New Data */ @@ -73,15 +72,19 @@ public class MMOPlayerDataImpl implements MMOPlayerData { this.scoreboardTipsShown = new DirtyData<>(new MutableInteger(0), dirtyFlag); - for(SuperSkill superSkill : mcMMO.p.getSkillRegister().getSuperSkills()) { + for(SuperAbilityType superSkill : SuperAbilityType.values()) { abilityDeactivationTimestamps.put(superSkill, 0); } //Core skills //TODO: Don't store values for disabled skills - for(RootSkill rootSkill : PrimarySkillType.getCoreRootSkills()) { - skillLevelValues.put(rootSkill, AdvancedConfig.getInstance().getStartingLevel()); - skillExperienceValues.put(rootSkill, 0F); + for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { + + if(primarySkillType.isChildSkill()) + continue; + + skillLevelValues.put(primarySkillType, AdvancedConfig.getInstance().getStartingLevel()); + skillExperienceValues.put(primarySkillType, 0F); } //Unique Player Data @@ -109,17 +112,17 @@ public class MMOPlayerDataImpl implements MMOPlayerData { * @param lastLogin target player's last login * @param leaderBoardExclusion target player's leaderboard exemption status */ - public MMOPlayerDataImpl(@NotNull UUID playerUUID, - @NotNull String playerName, - boolean partyChatSpying, - @NotNull Map skillLevelValues, - @NotNull Map skillExperienceValues, - @NotNull Map abilityDeactivationTimestamps, - @NotNull Map uniquePlayerData, - @NotNull Map barStateMap, - int scoreboardTipsShown, - long lastLogin, - boolean leaderBoardExclusion) throws Exception { + public PlayerData(@NotNull UUID playerUUID, + @NotNull String playerName, + boolean partyChatSpying, + @NotNull Map skillLevelValues, + @NotNull Map skillExperienceValues, + @NotNull Map abilityDeactivationTimestamps, + @NotNull Map uniquePlayerData, + @NotNull Map barStateMap, + int scoreboardTipsShown, + long lastLogin, + boolean leaderBoardExclusion) throws Exception { /* * Skills Data @@ -156,15 +159,18 @@ public class MMOPlayerDataImpl implements MMOPlayerData { * @throws UnexpectedValueException when values are outside of expected norms * @throws Exception when values are outside of expected norms */ - private void validateRootSkillMap(Map map) throws UnexpectedValueException, Exception { + private void validateRootSkillMap(Map map) throws UnexpectedValueException, Exception { //TODO: Check for missing/unregistered Validator validator = new Validator<>(); validator.addRule(new PositiveIntegerRule<>()); validator.addRule(new NonNullRule<>()); - for(RootSkill rootSkill : mcMMO.p.getSkillRegister().getRootSkills()) { - validator.validate(map.get(rootSkill)); + for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { + if(primarySkillType.isChildSkill()) + continue; + + validator.validate(map.get(primarySkillType)); } } @@ -175,56 +181,49 @@ public class MMOPlayerDataImpl implements MMOPlayerData { * @throws UnexpectedValueException when values are outside of expected norms * @throws Exception when values are outside of expected norms */ - private void validateSuperSkillMap(Map map) throws UnexpectedValueException, Exception { + private void validateSuperSkillMap(Map map) throws UnexpectedValueException, Exception { //TODO: Check for missing/unregistered Validator validator = new Validator<>(); validator.addRule(new PositiveIntegerRule<>()); validator.addRule(new NonNullRule<>()); - for(SuperSkill superSkill : mcMMO.p.getSkillRegister().getSuperSkills()) { + for(SuperAbilityType superSkill : SuperAbilityType.values()) { validator.validate(map.get(superSkill)); } } - @Override - public void setSkillLevel(@NotNull RootSkill rootSkill, int i) { - skillLevelValues.put(rootSkill, i); + + public void setSkillLevel(@NotNull PrimarySkillType primarySkillType, int i) { + skillLevelValues.put(primarySkillType, i); } - @Override - public int getSkillLevel(@NotNull RootSkill rootSkill) { + + public int getSkillLevel(@NotNull PrimarySkillType primarySkillType) { return 0; } - @Override public boolean isDirtyProfile() { return dirtyFlag.getImmutableCopy(); } - @Override public void resetDirtyFlag() { dirtyFlag.setBoolean(false); } - @Override public @NotNull String getPlayerName() { return playerName.getData().getImmutableCopy(); } - @Override public @NotNull UUID getPlayerUUID() { return playerUUID; } - @Override public boolean isPartyChatSpying() { return partyChatSpying.getData().getImmutableCopy(); } - @Override public void togglePartyChatSpying() { partyChatSpying.getData().setBoolean(!partyChatSpying.getData().getImmutableCopy()); } - @Override public void setPartyChatSpying(boolean bool) { this.partyChatSpying.getData().setBoolean(bool); } @@ -233,124 +232,101 @@ public class MMOPlayerDataImpl implements MMOPlayerData { * Scoreboards */ - @Override public int getScoreboardTipsShown() { return scoreboardTipsShown.getData(false).getImmutableCopy(); } - @Override public void setScoreboardTipsShown(int newValue) { scoreboardTipsShown.getData(true).setInt(newValue); } - @Override public int getChimaeraWingDATS() { return uniquePlayerData.get((UniqueDataType.CHIMAERA_WING_DATS)); } - @Override public void setChimaeraWingDATS(int DATS) { uniquePlayerData.put(UniqueDataType.CHIMAERA_WING_DATS, DATS); } - @Override public void setUniqueData(@NotNull UniqueDataType uniqueDataType, int newData) { uniquePlayerData.put(uniqueDataType, newData); } - @Override + public long getUniqueData(@NotNull UniqueDataType uniqueDataType) { return uniquePlayerData.get(uniqueDataType); } - @Override - public long getAbilityDATS(@NotNull SuperSkill superSkill) { + public long getAbilityDATS(@NotNull SuperAbilityType superSkill) { return abilityDeactivationTimestamps.get(superSkill); } - public void setAbilityDATS(@NotNull SuperSkill superSkill, long DATS) { + public void setAbilityDATS(@NotNull SuperAbilityType superSkill, long DATS) { abilityDeactivationTimestamps.put(superSkill, (int) (DATS * .001D)); } - @Override public void resetCooldowns() { abilityDeactivationTimestamps.replaceAll((a, v) -> 0); } - @Override - public @NotNull Map getBarStateMap() { + public @NotNull Map getBarStateMap() { return barStateMap; } - @Override - public @NotNull DirtyMap getDirtyBarStateMap() { + public @NotNull DirtyMap getDirtyBarStateMap() { return barStateMap; } - @Override public @NotNull DirtyMap getDirtySkillLevelMap() { return skillLevelValues; } - @Override public @NotNull DirtyMap getDirtyExperienceValueMap() { return skillExperienceValues; } - @Override public @NotNull DirtyData getDirtyPartyChatSpying() { return partyChatSpying; } - @Override public @NotNull Map getSkillLevelsMap() { return skillLevelValues; } - @Override public @NotNull Map getSkillsExperienceMap() { return skillExperienceValues; } - @Override - public @NotNull Map getAbilityDeactivationTimestamps() { + public @NotNull Map getAbilityDeactivationTimestamps() { return abilityDeactivationTimestamps; } - @Override public @NotNull Map getUniquePlayerData() { return uniquePlayerData; } - @Override public void setDirtyProfile() { this.dirtyFlag.setBoolean(true); } - @Override public long getLastLogin() { return lastLogin.getData().getImmutableCopy(); } - @Override public void setLastLogin(long newValue) { lastLogin.getData().setLong(newValue); } - @Override public boolean isLeaderBoardExcluded() { return leaderBoardExclusion.getData().getImmutableCopy(); } - @Override public void setLeaderBoardExclusion(boolean bool) { leaderBoardExclusion.getData(true).setBoolean(bool); } - @Override public @NotNull ImmutableMap copyPrimarySkillLevelsMap() { return ImmutableMap.copyOf(getSkillLevelsMap()); } - @Override public @NotNull ImmutableMap copyPrimarySkillExperienceValuesMap() { return ImmutableMap.copyOf(getSkillsExperienceMap()); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java index 75afea112..0dccad113 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java @@ -1,9 +1,7 @@ package com.gmail.nossr50.datatypes.player; +import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.neetgames.mcmmo.exceptions.UnknownSkillException; -import com.neetgames.mcmmo.experience.ExperienceHandler; -import com.neetgames.mcmmo.player.MMOPlayerData; -import com.neetgames.mcmmo.skill.RootSkill; import org.jetbrains.annotations.NotNull; import java.util.UUID; @@ -11,12 +9,12 @@ import java.util.UUID; public class PlayerProfile extends AbstractMMOPlayer { /** - * Initialize an {@link PlayerProfile} for {@link MMOPlayerDataImpl} + * Initialize an {@link PlayerProfile} for {@link PlayerData} * This will be used for existing data * * @param mmoPlayerData target persistent player data */ - public PlayerProfile(@NotNull MMOPlayerData mmoPlayerData) { + public PlayerProfile(@NotNull PlayerData mmoPlayerData) { super(mmoPlayerData); } @@ -32,27 +30,27 @@ public class PlayerProfile extends AbstractMMOPlayer { @Override public int getPowerLevel() { - return experienceHandler.getPowerLevel(); + return experienceProcessor.getPowerLevel(); } @Override - public int getSkillLevel(@NotNull RootSkill rootSkill) throws UnknownSkillException { - return experienceHandler.getSkillLevel(rootSkill); + public int getSkillLevel(@NotNull PrimarySkillType primarySkillType) throws UnknownSkillException { + return experienceProcessor.getSkillLevel(primarySkillType); } @Override - public int getSkillExperience(@NotNull RootSkill rootSkill) throws UnknownSkillException { - return experienceHandler.getSkillXpValue(rootSkill); + public int getSkillExperience(@NotNull PrimarySkillType primarySkillType) throws UnknownSkillException { + return experienceProcessor.getSkillXpValue(primarySkillType); } @Override - public int getExperienceToNextLevel(@NotNull RootSkill rootSkill) throws UnknownSkillException { - return experienceHandler.getExperienceToNextLevel(rootSkill); + public int getExperienceToNextLevel(@NotNull PrimarySkillType primarySkillType) throws UnknownSkillException { + return experienceProcessor.getExperienceToNextLevel(primarySkillType); } @Override - public double getProgressInCurrentSkillLevel(@NotNull RootSkill rootSkill) throws UnknownSkillException { - return experienceHandler.getProgressInCurrentSkillLevel(rootSkill); + public double getProgressInCurrentSkillLevel(@NotNull PrimarySkillType primarySkillType) throws UnknownSkillException { + return experienceProcessor.getProgressInCurrentSkillLevel(primarySkillType); } @Override @@ -62,11 +60,11 @@ public class PlayerProfile extends AbstractMMOPlayer { @Override public @NotNull ExperienceHandler getExperienceHandler() { - return experienceHandler; + return experienceProcessor; } @Override - public @NotNull MMOPlayerData getMMOPlayerData() { + public @NotNull PlayerData getMMOPlayerDataImpl() { return mmoPlayerData; } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/CoreSkills.java b/src/main/java/com/gmail/nossr50/datatypes/skills/CoreSkills.java index 482c54b4c..2ea0a4b51 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/CoreSkills.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/CoreSkills.java @@ -107,7 +107,7 @@ // private static final @NotNull HackySkillMappings hackySkillMappings = new HackySkillMappings(); // // static { -// HashSet rootSkillSet = new HashSet<>(); +// HashSet primarySkillTypeSet = new HashSet<>(); // HashSet childSkillSet = new HashSet<>(); // HashSet subSkillSet = new HashSet<>(); // HashSet superSkillSet = new HashSet<>(); @@ -167,25 +167,25 @@ // childSkillSet.add(SMELTING); // childSkillSet.add(SALVAGE); // -// rootSkillSet.add(ACROBATICS); -// rootSkillSet.add(ALCHEMY); -// rootSkillSet.add(ARCHERY); -// rootSkillSet.add(AXES); -// rootSkillSet.add(EXCAVATION); -// rootSkillSet.add(FISHING); -// rootSkillSet.add(HERBALISM); -// rootSkillSet.add(MINING); -// rootSkillSet.add(REPAIR); -// rootSkillSet.add(SALVAGE); -// rootSkillSet.add(SMELTING); -// rootSkillSet.add(SWORDS); -// rootSkillSet.add(TAMING); -// rootSkillSet.add(UNARMED); -// rootSkillSet.add(WOODCUTTING); -// rootSkillSet.add(TRIDENTS); -// rootSkillSet.add(CROSSBOWS); +// primarySkillTypeSet.add(ACROBATICS); +// primarySkillTypeSet.add(ALCHEMY); +// primarySkillTypeSet.add(ARCHERY); +// primarySkillTypeSet.add(AXES); +// primarySkillTypeSet.add(EXCAVATION); +// primarySkillTypeSet.add(FISHING); +// primarySkillTypeSet.add(HERBALISM); +// primarySkillTypeSet.add(MINING); +// primarySkillTypeSet.add(REPAIR); +// primarySkillTypeSet.add(SALVAGE); +// primarySkillTypeSet.add(SMELTING); +// primarySkillTypeSet.add(SWORDS); +// primarySkillTypeSet.add(TAMING); +// primarySkillTypeSet.add(UNARMED); +// primarySkillTypeSet.add(WOODCUTTING); +// primarySkillTypeSet.add(TRIDENTS); +// primarySkillTypeSet.add(CROSSBOWS); // -// CORE_ROOT_SKILLS = ImmutableSet.copyOf(rootSkillSet); +// CORE_ROOT_SKILLS = ImmutableSet.copyOf(primarySkillTypeSet); // CORE_CHILD_SKILLS = ImmutableSet.copyOf(childSkillSet); // CORE_NON_CHILD_SKILLS = ImmutableSet.copyOf(generateNonChildSkillSet()); // CORE_SUB_SKILLS = ImmutableSet.copyOf(subSkillSet); @@ -242,11 +242,11 @@ // // /** // * Whether or not a skill is considered a child skill -// * @param rootSkill target skill +// * @param primarySkillType target skill // * @return true if the skill identity belongs to a core "child" root skill // */ -// public static boolean isChildSkill(@NotNull RootSkill rootSkill) { -// return CORE_CHILD_SKILLS.contains(rootSkill); +// public static boolean isChildSkill(@NotNull PrimarySkillType primarySkillType) { +// return CORE_CHILD_SKILLS.contains(primarySkillType); // } // // @Deprecated @@ -259,12 +259,12 @@ // } // // @Deprecated -// public static @NotNull PrimarySkillType getSkill(@NotNull RootSkill rootSkill) { +// public static @NotNull PrimarySkillType getSkill(@NotNull PrimarySkillType primarySkillType) { // if(!hackySkillMappings.init) { // hackySkillMappings.initMappings(); // } // -// return hackySkillMappings.rootToPrimaryMap.get(rootSkill); +// return hackySkillMappings.rootToPrimaryMap.get(primarySkillType); // } // // @Deprecated diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SkillRegisterImpl.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SkillRegisterImpl.java index b01ad25d0..b4a81051d 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SkillRegisterImpl.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SkillRegisterImpl.java @@ -24,14 +24,14 @@ // private final @NotNull Set registeredSkills; // private final @NotNull Set superSkills; // private final @NotNull Set rankedSkills; -// private final @NotNull Set rootSkills; //Can include not-official root skills +// private final @NotNull Set primarySkillTypes; //Can include not-official root skills // private final @NotNull Set coreRootSkills; //Only includes official root skills // private final @NotNull Set coreSkills; //Only includes official core skills // // public SkillRegisterImpl() { // skillNameMap = new HashMap<>(); // registeredSkills = new HashSet<>(); -// rootSkills = new HashSet<>(); +// primarySkillTypes = new HashSet<>(); // superSkills = new HashSet<>(); // rankedSkills = new HashSet<>(); // coreRootSkills = new HashSet<>(); @@ -72,7 +72,7 @@ // // @Override // public @NotNull Set getRootSkills() { -// return rootSkills; +// return primarySkillTypes; // } // // @Override @@ -117,7 +117,7 @@ // } // // if(skill instanceof RootSkill) { -// rootSkills.remove(skill); +// primarySkillTypes.remove(skill); // } // // if (skill instanceof SuperSkill) { @@ -149,7 +149,7 @@ // } // // if(skill instanceof RootSkill) { -// rootSkills.add((RootSkill) skill); +// primarySkillTypes.add((RootSkill) skill); // } // // if (skill instanceof SuperSkill) { @@ -194,11 +194,11 @@ // * @see SkillIdentity#getFullyQualifiedName() // */ // public @Nullable RootSkill matchRootSkill(@NotNull String skillName) { -// for (RootSkill rootSkill : rootSkills) { -// if (rootSkill.getSkillIdentity().getFullyQualifiedName().equalsIgnoreCase(skillName) -// || skillName.equalsIgnoreCase(LocaleLoader.getString(StringUtils.getCapitalized(rootSkill.getRawSkillName()) + ".SkillName")) -// || rootSkill.getRawSkillName().equalsIgnoreCase(skillName)) { -// return rootSkill; +// for (PrimarySkillType primarySkillType : primarySkillTypes) { +// if (primarySkillType.getSkillIdentity().getFullyQualifiedName().equalsIgnoreCase(skillName) +// || skillName.equalsIgnoreCase(LocaleLoader.getString(StringUtils.getCapitalized(primarySkillType.getRawSkillName()) + ".SkillName")) +// || primarySkillType.getRawSkillName().equalsIgnoreCase(skillName)) { +// return primarySkillType; // } // } // diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandAsyncTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandAsyncTask.java index 09e12c851..1bfc19324 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandAsyncTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandAsyncTask.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.runnables.commands; import com.gmail.nossr50.datatypes.database.PlayerStat; +import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.mcMMO; import com.neetgames.mcmmo.skill.RootSkill; import org.apache.commons.lang.Validate; @@ -14,11 +15,11 @@ import java.util.List; public class MctopCommandAsyncTask extends BukkitRunnable { private final @NotNull CommandSender sender; - private final @Nullable RootSkill rootSkill; + private final @Nullable PrimarySkillType primarySkillType; private final int page; private final boolean useBoard, useChat; - public MctopCommandAsyncTask(int page, @Nullable RootSkill rootSkill, @NotNull CommandSender sender, boolean useBoard, boolean useChat) { + public MctopCommandAsyncTask(int page, @Nullable PrimarySkillType primarySkillType, @NotNull CommandSender sender, boolean useBoard, boolean useChat) { Validate.isTrue(useBoard || useChat, "Attempted to start a rank retrieval with both board and chat off"); Validate.notNull(sender, "Attempted to start a rank retrieval with no recipient"); @@ -27,7 +28,7 @@ public class MctopCommandAsyncTask extends BukkitRunnable { } this.page = page; - this.rootSkill = rootSkill; + this.primarySkillType = primarySkillType; this.sender = sender; this.useBoard = useBoard; this.useChat = useChat; @@ -35,8 +36,8 @@ public class MctopCommandAsyncTask extends BukkitRunnable { @Override public void run() { - final List userStats = mcMMO.getDatabaseManager().readLeaderboard(rootSkill, page, 10); + final List userStats = mcMMO.getDatabaseManager().readLeaderboard(primarySkillType, page, 10); - new MctopCommandDisplayTask(userStats, page, rootSkill, sender, useBoard, useChat).runTaskLater(mcMMO.p, 1); + new MctopCommandDisplayTask(userStats, page, primarySkillType, sender, useBoard, useChat).runTaskLater(mcMMO.p, 1); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java index cf7d0636e..6c923464e 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java @@ -3,6 +3,7 @@ package com.gmail.nossr50.runnables.commands; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.skills.CoreSkills; +import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.scoreboards.ScoreboardManager; @@ -22,14 +23,14 @@ import java.util.List; public class MctopCommandDisplayTask extends BukkitRunnable { private final List userStats; private final CommandSender sender; - private final @Nullable RootSkill rootSkill; + private final @Nullable PrimarySkillType primarySkillType; private final int page; private final boolean useBoard, useChat; - MctopCommandDisplayTask(@NotNull List userStats, int page, @Nullable RootSkill rootSkill, @NotNull CommandSender sender, boolean useBoard, boolean useChat) { + MctopCommandDisplayTask(@NotNull List userStats, int page, @Nullable PrimarySkillType primarySkillType, @NotNull CommandSender sender, boolean useBoard, boolean useChat) { this.userStats = userStats; this.page = page; - this.rootSkill = rootSkill; + this.primarySkillType = primarySkillType; this.sender = sender; this.useBoard = useBoard; this.useChat = useChat; @@ -53,7 +54,7 @@ public class MctopCommandDisplayTask extends BukkitRunnable { } private void displayChat() { - if (rootSkill == null) { + if (primarySkillType == null) { if(sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard")); } @@ -63,10 +64,10 @@ public class MctopCommandDisplayTask extends BukkitRunnable { } else { if(sender instanceof Player) { - sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", skill.getName())); + sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", primarySkillType.getName())); } else { - sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.Skill.Leaderboard", skill.getName()))); + sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.Skill.Leaderboard", primarySkillType.getName()))); } } @@ -88,11 +89,11 @@ public class MctopCommandDisplayTask extends BukkitRunnable { } private void displayBoard() { - if (rootSkill == null) { + if (primarySkillType == null) { ScoreboardManager.showTopPowerScoreboard((Player) sender, page, userStats); } else { - ScoreboardManager.showTopScoreboard((Player) sender, PrimarySkillType.getSkill(rootSkill), page, userStats); + ScoreboardManager.showTopScoreboard((Player) sender, primarySkillType, page, userStats); } } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java index 8ff09f917..349dbfd6f 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java @@ -7,13 +7,13 @@ import org.bukkit.scheduler.BukkitRunnable; public class ExperienceBarHideTask extends BukkitRunnable { public final OnlineMMOPlayer mmoPlayer; - public final RootSkill rootSkill; + public final PrimarySkillType primarySkillType; public final MMOExperienceBarManager MMOExperienceBarManagerRef; - public ExperienceBarHideTask(MMOExperienceBarManager MMOExperienceBarManagerRef, OnlineMMOPlayer mmoPlayer, RootSkill rootSkill) { + public ExperienceBarHideTask(MMOExperienceBarManager MMOExperienceBarManagerRef, OnlineMMOPlayer mmoPlayer, PrimarySkillType primarySkillType) { this.MMOExperienceBarManagerRef = MMOExperienceBarManagerRef; this.mmoPlayer = mmoPlayer; - this.rootSkill = rootSkill; + this.primarySkillType = primarySkillType; } /** @@ -32,7 +32,7 @@ public class ExperienceBarHideTask extends BukkitRunnable { if(MMOExperienceBarManagerRef == null || mmoPlayer == null) return; - MMOExperienceBarManagerRef.hideExperienceBar(rootSkill); - MMOExperienceBarManagerRef.clearTask(rootSkill); + MMOExperienceBarManagerRef.hideExperienceBar(primarySkillType); + MMOExperienceBarManagerRef.clearTask(primarySkillType); } } diff --git a/src/main/java/com/gmail/nossr50/skills/child/FamilyTree.java b/src/main/java/com/gmail/nossr50/skills/child/FamilyTree.java index 14ae9ca9f..9e8acbbde 100644 --- a/src/main/java/com/gmail/nossr50/skills/child/FamilyTree.java +++ b/src/main/java/com/gmail/nossr50/skills/child/FamilyTree.java @@ -18,8 +18,8 @@ public class FamilyTree { private static @Nullable Set smeltingParents; private static @Nullable Set salvageParents; - public static @NotNull Set getParentSkills(@NotNull RootSkill rootSkill) throws UnknownSkillException { - if(PrimarySkillType.isChildSkill(rootSkill)) { + public static @NotNull Set getParentSkills(@NotNull PrimarySkillType primarySkillType) throws UnknownSkillException { + if(PrimarySkillType.isChildSkill(primarySkillType)) { if(smeltingParents == null || salvageParents == null) { smeltingParents = new HashSet<>(); salvageParents = new HashSet<>(); @@ -31,12 +31,12 @@ public class FamilyTree { salvageParents.add(PrimarySkillType.REPAIR); } - if(rootSkill.equals(PrimarySkillType.SALVAGE)) { + if(primarySkillType.equals(PrimarySkillType.SALVAGE)) { return salvageParents; - } else if (rootSkill.equals(PrimarySkillType.SMELTING)) { + } else if (primarySkillType.equals(PrimarySkillType.SMELTING)) { return smeltingParents; } else { - mcMMO.p.getLogger().severe("root skill argument is not a child skill! " + rootSkill.toString()); + mcMMO.p.getLogger().severe("root skill argument is not a child skill! " + primarySkillType.toString()); throw new UnknownSkillException(); } diff --git a/src/main/java/com/gmail/nossr50/util/Permissions.java b/src/main/java/com/gmail/nossr50/util/Permissions.java index 5c516a522..124535948 100644 --- a/src/main/java/com/gmail/nossr50/util/Permissions.java +++ b/src/main/java/com/gmail/nossr50/util/Permissions.java @@ -118,7 +118,7 @@ public final class Permissions { public static boolean hasSalvageEnchantBypassPerk(Permissible permissible) { return permissible.hasPermission("mcmmo.perks.bypass.salvageenchant"); } public static boolean lucky(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.lucky." + skill.toString().toLowerCase(Locale.ENGLISH)); } - public static boolean lucky(Permissible permissible, RootSkill rootSkill) { return permissible.hasPermission("mcmmo.perks.lucky." + rootSkill.getRawSkillName().toLowerCase(Locale.ENGLISH)); } + public static boolean lucky(Permissible permissible, PrimarySkillType primarySkillType) { return permissible.hasPermission("mcmmo.perks.lucky." + primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH)); } /* XP PERKS */ public static boolean quadrupleXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.quadruple." + skill.toString().toLowerCase(Locale.ENGLISH)); } @@ -145,7 +145,7 @@ public final class Permissions { @Deprecated public static boolean skillEnabled(Permissible permissible, PrimarySkillType skill) {return permissible.hasPermission("mcmmo.skills." + skill.toString().toLowerCase(Locale.ENGLISH)); } - public static boolean skillEnabled(@NotNull Permissible permissible, @NotNull RootSkill rootSkill) {return permissible.hasPermission("mcmmo.skills." + rootSkill.getRawSkillName().toLowerCase(Locale.ENGLISH)); } + public static boolean skillEnabled(@NotNull Permissible permissible, @NotNull PrimarySkillType primarySkillType) {return permissible.hasPermission("mcmmo.skills." + primarySkillType.getRawSkillName().toLowerCase(Locale.ENGLISH)); } public static boolean vanillaXpBoost(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.ability." + skill.toString().toLowerCase(Locale.ENGLISH) + ".vanillaxpboost"); } public static boolean isSubSkillEnabled(Permissible permissible, SubSkillType subSkillType) { return permissible.hasPermission(subSkillType.getPermissionNodeAddress()); } public static boolean isSubSkillEnabled(Permissible permissible, AbstractSubSkill abstractSubSkill) { return permissible.hasPermission(abstractSubSkill.getPermissionNode()); } diff --git a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java index cd82c02eb..ba0e6be79 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java @@ -22,7 +22,7 @@ import java.util.List; */ public class ExperienceBarWrapper { - private final @NotNull RootSkill rootSkill; //Primary Skill + private final @NotNull PrimarySkillType primarySkillType; //Primary Skill private @NotNull BossBar bossBar; protected final @NotNull McMMOPlayer mmoPlayer; private int lastLevelUpdated; @@ -33,14 +33,14 @@ public class ExperienceBarWrapper { protected String niceSkillName; protected String title; - public ExperienceBarWrapper(@NotNull RootSkill rootSkill, @NotNull McMMOPlayer mmoPlayer) { + public ExperienceBarWrapper(@NotNull PrimarySkillType primarySkillType, @NotNull McMMOPlayer mmoPlayer) { this.mmoPlayer = mmoPlayer; - this.rootSkill = rootSkill; + this.primarySkillType = primarySkillType; title = ""; lastLevelUpdated = 0; //These vars are stored to help reduce operations involving strings - niceSkillName = StringUtils.getCapitalized(rootSkill.toString()); + niceSkillName = StringUtils.getCapitalized(primarySkillType.toString()); //Create the bar initBar(); @@ -59,7 +59,7 @@ public class ExperienceBarWrapper { private String getTitleTemplate() { //If they are using extra details - if(ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mmoPlayer, rootSkill)) { + if(ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mmoPlayer, primarySkillType)) { return LocaleLoader.getString("XPBar.Template.EarlyGameBoost"); } else if(ExperienceConfig.getInstance().getAddExtraDetails()) return LocaleLoader.getString("XPBar.Complex.Template", LocaleLoader.getString("XPBar."+niceSkillName, getLevel()), getCurrentXP(), getMaxXP(), getPowerLevel(), getPercentageOfLevel()); @@ -68,16 +68,16 @@ public class ExperienceBarWrapper { } private int getLevel() { - return mmoPlayer.getSkillLevel(rootSkill); + return mmoPlayer.getSkillLevel(primarySkillType); } private int getCurrentXP() { - return mmoPlayer.getSkillExperience(rootSkill); + return mmoPlayer.getSkillExperience(primarySkillType); } private int getMaxXP() { - return mmoPlayer.getExperienceToNextLevel(rootSkill); + return mmoPlayer.getExperienceToNextLevel(primarySkillType); } private int getPowerLevel() { return mmoPlayer.getPowerLevel(); } - private int getPercentageOfLevel() { return (int) (mmoPlayer.getProgressInCurrentSkillLevel(rootSkill) * 100); } + private int getPercentageOfLevel() { return (int) (mmoPlayer.getProgressInCurrentSkillLevel(primarySkillType) * 100); } public String getTitle() { return bossBar.getTitle(); @@ -114,10 +114,10 @@ public class ExperienceBarWrapper { bossBar.setProgress(v); //Check player level - if(ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mmoPlayer, rootSkill)) { + if(ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mmoPlayer, primarySkillType)) { setColor(BarColor.YELLOW); } else { - setColor(ExperienceConfig.getInstance().getExperienceBarColor(rootSkill)); + setColor(ExperienceConfig.getInstance().getExperienceBarColor(primarySkillType)); } //Every time progress updates we need to check for a title update @@ -157,7 +157,7 @@ public class ExperienceBarWrapper { private void createBossBar() { - bossBar = Bukkit.getServer().createBossBar(title, ExperienceConfig.getInstance().getExperienceBarColor(rootSkill), ExperienceConfig.getInstance().getExperienceBarStyle(rootSkill)); + bossBar = Bukkit.getServer().createBossBar(title, ExperienceConfig.getInstance().getExperienceBarColor(primarySkillType), ExperienceConfig.getInstance().getExperienceBarStyle(primarySkillType)); bossBar.addPlayer(mmoPlayer.getPlayer()); } } diff --git a/src/main/java/com/gmail/nossr50/util/experience/MMOExperienceBarManager.java b/src/main/java/com/gmail/nossr50/util/experience/MMOExperienceBarManager.java index 6dd0497f9..fbf03e60d 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/MMOExperienceBarManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/MMOExperienceBarManager.java @@ -2,6 +2,7 @@ package com.gmail.nossr50.util.experience; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.datatypes.skills.CoreSkills; import com.gmail.nossr50.mcMMO; @@ -23,12 +24,12 @@ public class MMOExperienceBarManager { int delaySeconds = 3; - private @NotNull final Map barStateMapRef; + private @NotNull final Map barStateMapRef; - private @NotNull final Map experienceBars; - private @NotNull final Map experienceBarHideTaskHashMap; + private @NotNull final Map experienceBars; + private @NotNull final Map experienceBarHideTaskHashMap; - public MMOExperienceBarManager(@NotNull McMMOPlayer mmoPlayer, @NotNull Map barStateMapRef) + public MMOExperienceBarManager(@NotNull McMMOPlayer mmoPlayer, @NotNull Map barStateMapRef) { this.mmoPlayer = mmoPlayer; this.barStateMapRef = barStateMapRef; @@ -45,8 +46,8 @@ public class MMOExperienceBarManager { } private void syncBarStates() { - for(Map.Entry entry : barStateMapRef.entrySet()) { - RootSkill key = entry.getKey(); + for(Map.Entry entry : barStateMapRef.entrySet()) { + PrimarySkillType key = entry.getKey(); SkillBossBarState barState = entry.getValue(); switch(barState) { @@ -64,130 +65,130 @@ public class MMOExperienceBarManager { barStateMapRef.putAll(generateDefaultBarStateMap()); } - public void updateExperienceBar(@NotNull RootSkill rootSkill, @NotNull Plugin plugin) + public void updateExperienceBar(@NotNull PrimarySkillType primarySkillType, @NotNull Plugin plugin) { - if(isBarDisabled(rootSkill)) + if(isBarDisabled(primarySkillType)) return; //Init Bar - if(experienceBars.get(rootSkill) == null) - experienceBars.put(rootSkill, new ExperienceBarWrapper(rootSkill, mmoPlayer)); + if(experienceBars.get(primarySkillType) == null) + experienceBars.put(primarySkillType, new ExperienceBarWrapper(primarySkillType, mmoPlayer)); //Get Bar - ExperienceBarWrapper experienceBarWrapper = experienceBars.get(rootSkill); + ExperienceBarWrapper experienceBarWrapper = experienceBars.get(primarySkillType); //Update Progress - experienceBarWrapper.setProgress(mmoPlayer.getExperienceHandler().getProgressInCurrentSkillLevel(rootSkill)); + experienceBarWrapper.setProgress(mmoPlayer.getExperienceHandler().getProgressInCurrentSkillLevel(primarySkillType)); //Show Bar experienceBarWrapper.showExperienceBar(); //Setup Hide Bar Task - if(experienceBarHideTaskHashMap.get(rootSkill) != null) + if(experienceBarHideTaskHashMap.get(primarySkillType) != null) { - experienceBarHideTaskHashMap.get(rootSkill).cancel(); + experienceBarHideTaskHashMap.get(primarySkillType).cancel(); } - scheduleHideTask(rootSkill, plugin); + scheduleHideTask(primarySkillType, plugin); } - private boolean isBarDisabled(@NotNull RootSkill rootSkill) { - return barStateMapRef.get(rootSkill) == SkillBossBarState.DISABLED + private boolean isBarDisabled(@NotNull PrimarySkillType primarySkillType) { + return barStateMapRef.get(primarySkillType) == SkillBossBarState.DISABLED //Config checks || !ExperienceConfig.getInstance().isExperienceBarsEnabled() - || !ExperienceConfig.getInstance().isExperienceBarEnabled(rootSkill); + || !ExperienceConfig.getInstance().isExperienceBarEnabled(primarySkillType); } - private boolean isBarAlwaysVisible(@NotNull RootSkill rootSkill) { - return barStateMapRef.get(rootSkill) == SkillBossBarState.ALWAYS_ON; + private boolean isBarAlwaysVisible(@NotNull PrimarySkillType primarySkillType) { + return barStateMapRef.get(primarySkillType) == SkillBossBarState.ALWAYS_ON; } - private void scheduleHideTask(@NotNull RootSkill rootSkill, @NotNull Plugin plugin) { - if(isBarAlwaysVisible(rootSkill)) + private void scheduleHideTask(@NotNull PrimarySkillType primarySkillType, @NotNull Plugin plugin) { + if(isBarAlwaysVisible(primarySkillType)) return; - ExperienceBarHideTask experienceBarHideTask = new ExperienceBarHideTask(this, mmoPlayer, rootSkill); + ExperienceBarHideTask experienceBarHideTask = new ExperienceBarHideTask(this, mmoPlayer, primarySkillType); experienceBarHideTask.runTaskLater(plugin, 20 * delaySeconds); - experienceBarHideTaskHashMap.put(rootSkill, experienceBarHideTask); + experienceBarHideTaskHashMap.put(primarySkillType, experienceBarHideTask); } - public void hideExperienceBar(@NotNull RootSkill rootSkill) + public void hideExperienceBar(@NotNull PrimarySkillType primarySkillType) { - if(experienceBars.containsKey(rootSkill)) - experienceBars.get(rootSkill).hideExperienceBar(); + if(experienceBars.containsKey(primarySkillType)) + experienceBars.get(primarySkillType).hideExperienceBar(); } - public void clearTask(@NotNull RootSkill rootSkill) + public void clearTask(@NotNull PrimarySkillType primarySkillType) { - experienceBarHideTaskHashMap.remove(rootSkill); + experienceBarHideTaskHashMap.remove(primarySkillType); } public void disableAllBars() { - for(RootSkill rootSkill : mcMMO.p.getSkillRegister().getRootSkills()) { - xpBarSettingToggle(SkillBossBarSetting.HIDE, rootSkill); + for(PrimarySkillType primarySkillType : mcMMO.p.getSkillRegister().getRootSkills()) { + xpBarSettingToggle(SkillBossBarSetting.HIDE, primarySkillType); } NotificationManager.sendPlayerInformationChatOnlyPrefixed(Misc.adaptPlayer(mmoPlayer), "Commands.XPBar.DisableAll"); } - public void xpBarSettingToggle(@NotNull SkillBossBarSetting skillBossBarSetting, @NotNull RootSkill rootSkill) { + public void xpBarSettingToggle(@NotNull SkillBossBarSetting skillBossBarSetting, @NotNull PrimarySkillType primarySkillType) { switch(skillBossBarSetting) { case SHOW: - barStateMapRef.put(rootSkill, SkillBossBarState.ALWAYS_ON); + barStateMapRef.put(primarySkillType, SkillBossBarState.ALWAYS_ON); //Remove lingering tasks - if(experienceBarHideTaskHashMap.containsKey(rootSkill)) { - experienceBarHideTaskHashMap.get(rootSkill).cancel(); + if(experienceBarHideTaskHashMap.containsKey(primarySkillType)) { + experienceBarHideTaskHashMap.get(primarySkillType).cancel(); } - updateExperienceBar(rootSkill, mcMMO.p); + updateExperienceBar(primarySkillType, mcMMO.p); break; case HIDE: - barStateMapRef.put(rootSkill, SkillBossBarState.DISABLED); + barStateMapRef.put(primarySkillType, SkillBossBarState.DISABLED); //Remove lingering tasks - if(experienceBarHideTaskHashMap.containsKey(rootSkill)) { - experienceBarHideTaskHashMap.get(rootSkill).cancel(); + if(experienceBarHideTaskHashMap.containsKey(primarySkillType)) { + experienceBarHideTaskHashMap.get(primarySkillType).cancel(); } - hideExperienceBar(rootSkill); + hideExperienceBar(primarySkillType); break; case RESET: resetBarSettings(); break; } - informPlayer(skillBossBarSetting, rootSkill); + informPlayer(skillBossBarSetting, primarySkillType); } private void resetBarSettings() { barStateMapRef.putAll(generateDefaultBarStateMap()); } - private void informPlayer(@NotNull SkillBossBarSetting settingTarget, @NotNull RootSkill rootSkill) { + private void informPlayer(@NotNull SkillBossBarSetting settingTarget, @NotNull PrimarySkillType primarySkillType) { //Inform player of setting change if(settingTarget != SkillBossBarSetting.RESET) { - NotificationManager.sendPlayerInformationChatOnlyPrefixed(Misc.adaptPlayer(mmoPlayer), "Commands.XPBar.SettingChanged", rootSkill.getRawSkillName(), settingTarget.toString()); + NotificationManager.sendPlayerInformationChatOnlyPrefixed(Misc.adaptPlayer(mmoPlayer), "Commands.XPBar.SettingChanged", primarySkillType.getName(), settingTarget.toString()); } else { NotificationManager.sendPlayerInformationChatOnlyPrefixed(Misc.adaptPlayer(mmoPlayer), "Commands.XPBar.Reset"); } } - public static @NotNull Map generateDefaultBarStateMap() { - HashMap barStateMap = new HashMap<>(); + public static @NotNull Map generateDefaultBarStateMap() { + HashMap barStateMap = new HashMap<>(); setBarStateDefaults(barStateMap); return barStateMap; } - public static void setBarStateDefaults(@NotNull Map barStateHashMap) { - for(RootSkill rootSkill : PrimarySkillType.getCoreRootSkills()) { + public static void setBarStateDefaults(@NotNull Map barStateHashMap) { + for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(PrimarySkillType.isChildSkill(rootSkill)) { - barStateHashMap.put(rootSkill, SkillBossBarState.DISABLED); + if(!primarySkillType.isChildSkill()) { + barStateHashMap.put(primarySkillType, SkillBossBarState.DISABLED); } else { - barStateHashMap.put(rootSkill, SkillBossBarState.NORMAL); + barStateHashMap.put(primarySkillType, SkillBossBarState.NORMAL); } } } diff --git a/src/main/java/com/gmail/nossr50/util/input/SuperSkillManagerImpl.java b/src/main/java/com/gmail/nossr50/util/input/SuperSkillManagerImpl.java index 9835ec751..e99d144ca 100644 --- a/src/main/java/com/gmail/nossr50/util/input/SuperSkillManagerImpl.java +++ b/src/main/java/com/gmail/nossr50/util/input/SuperSkillManagerImpl.java @@ -4,7 +4,7 @@ import com.gmail.nossr50.config.AdvancedConfig; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.player.McMMOPlayer; -import com.neetgames.mcmmo.player.MMOPlayerData; +import com.neetgames.mcmmo.player.MMOPlayerDataImpl; import com.gmail.nossr50.datatypes.skills.AbilityToolType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; @@ -38,9 +38,9 @@ public class SuperSkillManagerImpl implements SuperSkillManager { private boolean abilityActivationPermission = true; private final Map toolMode = new HashMap<>(); - private final MMOPlayerData mmoPlayerData; + private final MMOPlayerDataImpl mmoPlayerData; - public SuperSkillManagerImpl(@NotNull McMMOPlayer mmoPlayer, @NotNull MMOPlayerData mmoPlayerData) { + public SuperSkillManagerImpl(@NotNull McMMOPlayer mmoPlayer, @NotNull MMOPlayerDataImpl mmoPlayerData) { this.mmoPlayer = mmoPlayer; this.mmoPlayerData = mmoPlayerData; this.player = Misc.adaptPlayer(mmoPlayer); diff --git a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java index 3b62192b7..bd630a535 100644 --- a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java @@ -160,17 +160,17 @@ public class NotificationManager { /** * Handles sending level up notifications to a mmoPlayer * @param mmoPlayer target mmoPlayer - * @param rootSkill skill that leveled up + * @param primarySkillType skill that leveled up * @param newLevel new level of that skill */ - public static void sendPlayerLevelUpNotification(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull RootSkill rootSkill, int levelsGained, int newLevel) + public static void sendPlayerLevelUpNotification(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType, int levelsGained, int newLevel) { if(!mmoPlayer.hasSkillChatNotifications()) return; McMMOMessageType destination = AdvancedConfig.getInstance().doesNotificationUseActionBar(NotificationType.LEVEL_UP_MESSAGE) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM; - Component levelUpTextComponent = TextComponentFactory.getNotificationLevelUpTextComponent(PrimarySkillType.getSkill(rootSkill), levelsGained, newLevel); + Component levelUpTextComponent = TextComponentFactory.getNotificationLevelUpTextComponent(PrimarySkillType.getSkill(primarySkillType), levelsGained, newLevel); McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(Misc.adaptPlayer(mmoPlayer), NotificationType.LEVEL_UP_MESSAGE, destination, levelUpTextComponent); sendNotification(Misc.adaptPlayer(mmoPlayer), customEvent); diff --git a/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java b/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java index 1dda27bda..f37573a9b 100644 --- a/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java +++ b/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java @@ -11,10 +11,10 @@ public class PlayerLevelUtils { * Check if a player is currently qualifying for the early game boosted XP * Will return false only if a player is above the boost level cutoff, it does not check config settings to see if the early game boost is on * @param mmoPlayer target player - * @param rootSkill target skill + * @param primarySkillType target skill * @return if the player would qualify for the XP boost if its enabled */ - public static boolean qualifiesForEarlyGameBoost(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull RootSkill rootSkill) { - return mmoPlayer.getSkillLevel(rootSkill) < 1; + public static boolean qualifiesForEarlyGameBoost(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType) { + return mmoPlayer.getSkillLevel(primarySkillType) < 1; } } diff --git a/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java b/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java index dcb24c672..5683d5e0b 100644 --- a/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java +++ b/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java @@ -488,8 +488,8 @@ public class TextComponentFactory { componentBuilder.append(Component.newline()); } - public static void getSubSkillTextComponents(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull List textComponents, @NotNull RootSkill rootSkill) { - return getSubSkillTextComponents(mmoPlayer, textComponents, PrimarySkillType.getSkill(rootSkill)); + public static void getSubSkillTextComponents(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull List textComponents, @NotNull PrimarySkillType primarySkillType) { + return getSubSkillTextComponents(mmoPlayer, textComponents, PrimarySkillType.getSkill(primarySkillType)); } public static void getSubSkillTextComponents(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull List textComponents, @NotNull PrimarySkillType parentSkill) {