SkillUtils.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package com.gmail.nossr50.util.skills;
  2. import com.gmail.nossr50.config.AdvancedConfig;
  3. import com.gmail.nossr50.config.Config;
  4. import com.gmail.nossr50.config.HiddenConfig;
  5. import com.gmail.nossr50.datatypes.experience.XPGainReason;
  6. import com.gmail.nossr50.datatypes.experience.XPGainSource;
  7. import com.gmail.nossr50.datatypes.interactions.NotificationType;
  8. import com.gmail.nossr50.datatypes.player.McMMOPlayer;
  9. import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
  10. import com.gmail.nossr50.datatypes.skills.SubSkillType;
  11. import com.gmail.nossr50.datatypes.skills.SuperAbilityType;
  12. import com.gmail.nossr50.events.skills.secondaryabilities.SubSkillEvent;
  13. import com.gmail.nossr50.locale.LocaleLoader;
  14. import com.gmail.nossr50.mcMMO;
  15. import com.gmail.nossr50.util.EventUtils;
  16. import com.gmail.nossr50.util.ItemUtils;
  17. import com.gmail.nossr50.util.Misc;
  18. import com.gmail.nossr50.util.Permissions;
  19. import com.gmail.nossr50.util.compat.layers.persistentdata.AbstractPersistentDataLayer;
  20. import com.gmail.nossr50.util.player.NotificationManager;
  21. import com.gmail.nossr50.util.player.UserManager;
  22. import com.gmail.nossr50.util.random.*;
  23. import com.gmail.nossr50.util.text.StringUtils;
  24. import org.bukkit.Bukkit;
  25. import org.bukkit.Location;
  26. import org.bukkit.Material;
  27. import org.bukkit.enchantments.Enchantment;
  28. import org.bukkit.entity.Player;
  29. import org.bukkit.inventory.ItemStack;
  30. import org.bukkit.inventory.Recipe;
  31. import org.bukkit.inventory.ShapedRecipe;
  32. import org.bukkit.inventory.ShapelessRecipe;
  33. import org.bukkit.inventory.meta.ItemMeta;
  34. import org.bukkit.potion.PotionEffect;
  35. import org.bukkit.potion.PotionEffectType;
  36. import org.jetbrains.annotations.NotNull;
  37. import org.jetbrains.annotations.Nullable;
  38. import java.util.Iterator;
  39. public final class SkillUtils {
  40. /**
  41. * This is a static utility class, therefore we don't want any instances of
  42. * this class. Making the constructor private prevents accidents like that.
  43. */
  44. private SkillUtils() {}
  45. public static void applyXpGain(McMMOPlayer mcMMOPlayer, PrimarySkillType skill, float xp, XPGainReason xpGainReason) {
  46. mcMMOPlayer.beginXpGain(skill, xp, xpGainReason, XPGainSource.SELF);
  47. }
  48. public static void applyXpGain(McMMOPlayer mcMMOPlayer, PrimarySkillType skill, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) {
  49. mcMMOPlayer.beginXpGain(skill, xp, xpGainReason, xpGainSource);
  50. }
  51. /*
  52. * Skill Stat Calculations
  53. */
  54. public static String[] calculateLengthDisplayValues(Player player, float skillValue, PrimarySkillType skill) {
  55. int maxLength = skill.getAbility().getMaxLength();
  56. int abilityLengthVar = AdvancedConfig.getInstance().getAbilityLength();
  57. int abilityLengthCap = AdvancedConfig.getInstance().getAbilityLengthCap();
  58. int length;
  59. if(abilityLengthCap > 0)
  60. {
  61. length = (int) Math.min(abilityLengthCap, 2 + (skillValue / abilityLengthVar));
  62. } else {
  63. length = 2 + (int) (skillValue / abilityLengthVar);
  64. }
  65. int enduranceLength = PerksUtils.handleActivationPerks(player, length, maxLength);
  66. if (maxLength != 0) {
  67. length = Math.min(length, maxLength);
  68. }
  69. return new String[] { String.valueOf(length), String.valueOf(enduranceLength) };
  70. }
  71. /*
  72. * Others
  73. */
  74. public static int handleFoodSkills(Player player, int eventFoodLevel, SubSkillType subSkillType) {
  75. int curRank = RankUtils.getRank(player, subSkillType);
  76. int currentFoodLevel = player.getFoodLevel();
  77. int foodChange = eventFoodLevel - currentFoodLevel;
  78. foodChange+=curRank;
  79. return currentFoodLevel + foodChange;
  80. }
  81. /**
  82. * Calculate the time remaining until the cooldown expires.
  83. *
  84. * @param deactivatedTimeStamp Time of deactivation
  85. * @param cooldown The length of the cooldown
  86. * @param player The Player to check for cooldown perks
  87. *
  88. * @return the number of seconds remaining before the cooldown expires
  89. */
  90. public static int calculateTimeLeft(long deactivatedTimeStamp, int cooldown, Player player) {
  91. return (int) (((deactivatedTimeStamp + (PerksUtils.handleCooldownPerks(player, cooldown) * Misc.TIME_CONVERSION_FACTOR)) - System.currentTimeMillis()) / Misc.TIME_CONVERSION_FACTOR);
  92. }
  93. /**
  94. * Check if the cooldown has expired.
  95. * This does NOT account for cooldown perks!
  96. *
  97. * @param deactivatedTimeStamp Time of deactivation in seconds
  98. * @param cooldown The length of the cooldown in seconds
  99. *
  100. * @return true if the cooldown is expired
  101. */
  102. public static boolean cooldownExpired(long deactivatedTimeStamp, int cooldown) {
  103. return System.currentTimeMillis() >= (deactivatedTimeStamp + cooldown) * Misc.TIME_CONVERSION_FACTOR;
  104. }
  105. /**
  106. * Checks if the given string represents a valid skill
  107. *
  108. * @param skillName The name of the skill to check
  109. * @return true if this is a valid skill, false otherwise
  110. */
  111. public static boolean isSkill(String skillName) {
  112. return Config.getInstance().getLocale().equalsIgnoreCase("en_US") ? PrimarySkillType.getSkill(skillName) != null : isLocalizedSkill(skillName);
  113. }
  114. public static void sendSkillMessage(Player player, NotificationType notificationType, String key) {
  115. Location location = player.getLocation();
  116. for (Player otherPlayer : player.getWorld().getPlayers()) {
  117. if (otherPlayer != player && Misc.isNear(location, otherPlayer.getLocation(), Misc.SKILL_MESSAGE_MAX_SENDING_DISTANCE)) {
  118. NotificationManager.sendNearbyPlayersInformation(otherPlayer, notificationType, key, player.getName());
  119. }
  120. }
  121. }
  122. public static void handleAbilitySpeedIncrease(Player player) {
  123. if (HiddenConfig.getInstance().useEnchantmentBuffs()) {
  124. ItemStack heldItem = player.getInventory().getItemInMainHand();
  125. if(heldItem == null)
  126. return;
  127. if (!ItemUtils.canBeSuperAbilityDigBoosted(heldItem)) {
  128. return;
  129. }
  130. int originalDigSpeed = heldItem.getEnchantmentLevel(Enchantment.DIG_SPEED);
  131. //Add dig speed
  132. //Lore no longer gets added, no point to it afaik
  133. //ItemUtils.addAbilityLore(heldItem); //lore can be a secondary failsafe for 1.13 and below
  134. ItemUtils.addDigSpeedToItem(heldItem, heldItem.getEnchantmentLevel(Enchantment.DIG_SPEED));
  135. //1.13.2+ will have persistent metadata for this item
  136. AbstractPersistentDataLayer compatLayer = mcMMO.getCompatibilityManager().getPersistentDataLayer();
  137. compatLayer.setSuperAbilityBoostedItem(heldItem, originalDigSpeed);
  138. }
  139. else {
  140. int duration = 0;
  141. int amplifier = 0;
  142. if (player.hasPotionEffect(PotionEffectType.FAST_DIGGING)) {
  143. for (PotionEffect effect : player.getActivePotionEffects()) {
  144. if (effect.getType() == PotionEffectType.FAST_DIGGING) {
  145. duration = effect.getDuration();
  146. amplifier = effect.getAmplifier();
  147. break;
  148. }
  149. }
  150. }
  151. McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
  152. //Not Loaded
  153. if(mcMMOPlayer == null)
  154. return;
  155. PrimarySkillType skill = mcMMOPlayer.getAbilityMode(SuperAbilityType.SUPER_BREAKER) ? PrimarySkillType.MINING : PrimarySkillType.EXCAVATION;
  156. int abilityLengthVar = AdvancedConfig.getInstance().getAbilityLength();
  157. int abilityLengthCap = AdvancedConfig.getInstance().getAbilityLengthCap();
  158. int ticks;
  159. if(abilityLengthCap > 0)
  160. {
  161. ticks = PerksUtils.handleActivationPerks(player, Math.min(abilityLengthCap, 2 + (mcMMOPlayer.getSkillLevel(skill) / abilityLengthVar)),
  162. skill.getAbility().getMaxLength()) * Misc.TICK_CONVERSION_FACTOR;
  163. } else {
  164. ticks = PerksUtils.handleActivationPerks(player, 2 + ((mcMMOPlayer.getSkillLevel(skill)) / abilityLengthVar),
  165. skill.getAbility().getMaxLength()) * Misc.TICK_CONVERSION_FACTOR;
  166. }
  167. PotionEffect abilityBuff = new PotionEffect(PotionEffectType.FAST_DIGGING, duration + ticks, amplifier + 10);
  168. player.addPotionEffect(abilityBuff, true);
  169. }
  170. }
  171. public static void removeAbilityBoostsFromInventory(@NotNull Player player) {
  172. for (ItemStack itemStack : player.getInventory().getContents()) {
  173. removeAbilityBuff(itemStack);
  174. }
  175. }
  176. public static void removeAbilityBuff(@Nullable ItemStack itemStack) {
  177. if(itemStack == null)
  178. return;
  179. if(!ItemUtils.canBeSuperAbilityDigBoosted(itemStack))
  180. return;
  181. //1.13.2+ will have persistent metadata for this itemStack
  182. AbstractPersistentDataLayer compatLayer = mcMMO.getCompatibilityManager().getPersistentDataLayer();
  183. if(compatLayer.isLegacyAbilityTool(itemStack)) {
  184. ItemMeta itemMeta = itemStack.getItemMeta();
  185. // This is safe to call without prior checks.
  186. itemMeta.removeEnchant(Enchantment.DIG_SPEED);
  187. itemStack.setItemMeta(itemMeta);
  188. ItemUtils.removeAbilityLore(itemStack);
  189. }
  190. if(compatLayer.isSuperAbilityBoosted(itemStack)) {
  191. compatLayer.removeBonusDigSpeedOnSuperAbilityTool(itemStack);
  192. }
  193. }
  194. public static void handleDurabilityChange(ItemStack itemStack, int durabilityModifier) {
  195. handleDurabilityChange(itemStack, durabilityModifier, 1.0);
  196. }
  197. /**
  198. * Modify the durability of an ItemStack.
  199. *
  200. * @param itemStack The ItemStack which durability should be modified
  201. * @param durabilityModifier the amount to modify the durability by
  202. * @param maxDamageModifier the amount to adjust the max damage by
  203. */
  204. public static void handleDurabilityChange(ItemStack itemStack, double durabilityModifier, double maxDamageModifier) {
  205. if(itemStack.getItemMeta() != null && itemStack.getItemMeta().isUnbreakable()) {
  206. return;
  207. }
  208. Material type = itemStack.getType();
  209. short maxDurability = mcMMO.getRepairableManager().isRepairable(type) ? mcMMO.getRepairableManager().getRepairable(type).getMaximumDurability() : type.getMaxDurability();
  210. durabilityModifier = (int) Math.min(durabilityModifier / (itemStack.getEnchantmentLevel(Enchantment.DURABILITY) + 1), maxDurability * maxDamageModifier);
  211. itemStack.setDurability((short) Math.min(itemStack.getDurability() + durabilityModifier, maxDurability));
  212. }
  213. private static boolean isLocalizedSkill(String skillName) {
  214. for (PrimarySkillType skill : PrimarySkillType.values()) {
  215. if (skillName.equalsIgnoreCase(LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".SkillName"))) {
  216. return true;
  217. }
  218. }
  219. return false;
  220. }
  221. @Nullable
  222. public static Material getRepairAndSalvageItem(@NotNull ItemStack inHand) {
  223. if (ItemUtils.isDiamondTool(inHand) || ItemUtils.isDiamondArmor(inHand)) {
  224. return Material.DIAMOND;
  225. }
  226. else if (ItemUtils.isGoldTool(inHand) || ItemUtils.isGoldArmor(inHand)) {
  227. return Material.GOLD_INGOT;
  228. }
  229. else if (ItemUtils.isIronTool(inHand) || ItemUtils.isIronArmor(inHand)) {
  230. return Material.IRON_INGOT;
  231. }
  232. else if (ItemUtils.isStoneTool(inHand)) {
  233. return Material.COBBLESTONE;
  234. }
  235. else if (ItemUtils.isWoodTool(inHand)) {
  236. return Material.OAK_WOOD;
  237. }
  238. else if (ItemUtils.isLeatherArmor(inHand)) {
  239. return Material.LEATHER;
  240. }
  241. else if (ItemUtils.isStringTool(inHand)) {
  242. return Material.STRING;
  243. }
  244. else {
  245. return null;
  246. }
  247. }
  248. public static int getRepairAndSalvageQuantities(ItemStack item) {
  249. return getRepairAndSalvageQuantities(item.getType(), getRepairAndSalvageItem(item));
  250. }
  251. public static int getRepairAndSalvageQuantities(Material itemMaterial, Material recipeMaterial) {
  252. int quantity = 0;
  253. if(mcMMO.getMaterialMapStore().isNetheriteTool(itemMaterial) || mcMMO.getMaterialMapStore().isNetheriteArmor(itemMaterial)) {
  254. //One netherite bar requires 4 netherite scraps
  255. return 4;
  256. }
  257. for(Iterator<? extends Recipe> recipeIterator = Bukkit.getServer().recipeIterator(); recipeIterator.hasNext();) {
  258. Recipe bukkitRecipe = recipeIterator.next();
  259. if(bukkitRecipe.getResult().getType() != itemMaterial)
  260. continue;
  261. if(bukkitRecipe instanceof ShapelessRecipe) {
  262. for (ItemStack ingredient : ((ShapelessRecipe) bukkitRecipe).getIngredientList()) {
  263. if (ingredient != null
  264. && (recipeMaterial == null || ingredient.getType() == recipeMaterial)
  265. && (ingredient.getType() == recipeMaterial)) {
  266. quantity += ingredient.getAmount();
  267. }
  268. }
  269. } else if(bukkitRecipe instanceof ShapedRecipe) {
  270. for (ItemStack ingredient : ((ShapedRecipe) bukkitRecipe).getIngredientMap().values()) {
  271. if (ingredient != null
  272. && (recipeMaterial == null || ingredient.getType() == recipeMaterial)
  273. && (ingredient.getType() == recipeMaterial)) {
  274. quantity += ingredient.getAmount();
  275. }
  276. }
  277. }
  278. }
  279. return quantity;
  280. }
  281. /**
  282. * This is one of several Skill RNG check methods
  283. * This helper method is for specific {@link SubSkillType}, which help mcMMO understand where the RNG values used in our calculations come from from this {@link SubSkillType}
  284. *
  285. * 1) Determine where the RNG values come from for the passed {@link SubSkillType}
  286. * NOTE: In the config file, there are values which are static and which are more dynamic, this is currently a bit hardcoded and will need to be updated manually
  287. *
  288. * 2) Determine whether or not to use Lucky multiplier and influence the outcome
  289. *
  290. * 3) Creates a {@link Probability} and pipes it to {@link RandomChanceUtil} which processes the result and returns it
  291. *
  292. * This also calls a {@link SubSkillEvent} which can be cancelled, if it is cancelled this will return false
  293. * The outcome of the probability can also be modified by this event that is called
  294. *
  295. * @param subSkillType target subskill
  296. * @param player target player, can be null (null players are given odds equivalent to a player with no levels or luck)
  297. * @return true if the Skill RNG succeeds, false if it fails
  298. */
  299. public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, @NotNull Player player) {
  300. //Process probability
  301. Probability probability = getSubSkillProbability(subSkillType, player);
  302. //Send out event
  303. SubSkillEvent subSkillEvent = EventUtils.callSubSkillEvent(player, subSkillType);
  304. if(subSkillEvent.isCancelled()) {
  305. return false; //Event got cancelled so this doesn't succeed
  306. }
  307. //Result modifier
  308. double resultModifier = subSkillEvent.getResultModifier();
  309. //Mutate probability
  310. if(resultModifier != 1.0D)
  311. probability = ProbabilityFactory.ofPercentageValue(probability.getValue() * resultModifier);
  312. //Luck
  313. boolean isLucky = Permissions.lucky(player, subSkillType.getParentSkill());
  314. if(isLucky) {
  315. return RandomChanceUtil.processProbability(probability, RandomChanceUtil.LUCKY_MODIFIER);
  316. } else {
  317. return RandomChanceUtil.processProbability(probability);
  318. }
  319. }
  320. /**
  321. * This is one of several Skill RNG check methods
  322. * This helper method is specific to static value RNG, which can be influenced by a player's Luck
  323. *
  324. * @param primarySkillType the related primary skill
  325. * @param player the target player, can be null (null players have the worst odds)
  326. * @param probabilityPercentage the probability of this player succeeding in "percentage" format (0-100 inclusive)
  327. * @return true if the RNG succeeds, false if it fails
  328. */
  329. public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, @Nullable Player player, double probabilityPercentage) {
  330. //Grab a probability converted from a "percentage" value
  331. Probability probability = ProbabilityFactory.ofPercentageValue(probabilityPercentage);
  332. return isStaticSkillRNGSuccessful(primarySkillType, player, probability);
  333. }
  334. /**
  335. * This is one of several Skill RNG check methods
  336. * This helper method is specific to static value RNG, which can be influenced by a player's Luck
  337. *
  338. * @param primarySkillType the related primary skill
  339. * @param player the target player, can be null (null players have the worst odds)
  340. * @param probability the probability of this player succeeding
  341. * @return true if the RNG succeeds, false if it fails
  342. */
  343. public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, @Nullable Player player, @NotNull Probability probability) {
  344. boolean isLucky = player != null && Permissions.lucky(player, primarySkillType);
  345. if(isLucky) {
  346. return RandomChanceUtil.processProbability(probability, RandomChanceUtil.LUCKY_MODIFIER);
  347. } else {
  348. return RandomChanceUtil.processProbability(probability);
  349. }
  350. }
  351. /**
  352. * Skills activate without RNG, this allows other plugins to prevent that activation
  353. * @param subSkillType target subskill
  354. * @param player target player
  355. * @return true if the skill succeeds (wasn't cancelled by any other plugin)
  356. */
  357. public static boolean isNonRNGSkillActivationSuccessful(@NotNull SubSkillType subSkillType, @NotNull Player player) {
  358. return !EventUtils.callSubSkillEvent(player, subSkillType).isCancelled();
  359. }
  360. /**
  361. * Grab the {@link Probability} for a specific {@link SubSkillType} for a specific {@link Player}
  362. *
  363. * @param subSkillType target subskill
  364. * @param player target player
  365. * @return the Probability of this skill succeeding
  366. * @throws InvalidStaticChance when a skill that does not have a hard coded static chance and it is asked for
  367. * @throws RuntimeException
  368. */
  369. public static @NotNull Probability getSubSkillProbability(@NotNull SubSkillType subSkillType, @Nullable Player player) {
  370. SkillProbabilityType skillProbabilityType = SkillProbabilityType.DYNAMIC_CONFIGURABLE;
  371. if(subSkillType == SubSkillType.TAMING_FAST_FOOD_SERVICE || subSkillType == SubSkillType.AXES_ARMOR_IMPACT || subSkillType == SubSkillType.AXES_GREATER_IMPACT)
  372. skillProbabilityType = SkillProbabilityType.STATIC_CONFIGURABLE;
  373. return ProbabilityFactory.ofSubSkill(player, subSkillType, skillProbabilityType);
  374. }
  375. public static @NotNull String[] getRNGDisplayValues(@NotNull Player player, @NotNull SubSkillType subSkill) {
  376. double firstValue = RandomChanceUtil.chanceOfSuccessPercentage(player, subSkill, false);
  377. double secondValue = RandomChanceUtil.chanceOfSuccessPercentage(player, subSkill, true);
  378. return new String[]{RandomChanceUtil.percent.format(firstValue), RandomChanceUtil.percent.format(secondValue)};
  379. }
  380. public static @NotNull String[] getRNGDisplayValues(@NotNull Probability probability) {
  381. double firstValue = RandomChanceUtil.chanceOfSuccessPercentage(probability, false);
  382. double secondValue = RandomChanceUtil.chanceOfSuccessPercentage(probability, true);
  383. return new String[]{RandomChanceUtil.percent.format(firstValue), RandomChanceUtil.percent.format(secondValue)};
  384. }
  385. }