PLayer data now loaded async on player join

This commit is contained in:
Jules 2021-07-25 15:06:07 +02:00
parent 4da75c0864
commit 9cbc951fad
13 changed files with 1226 additions and 1115 deletions

12
pom.xml
View File

@ -172,7 +172,7 @@
<!-- Local repo -->
<dependency>
<groupId>net.Indyuce.mmocore.lib</groupId>
<groupId>com.bekvon.bukkit.residence</groupId>
<artifactId>Residence</artifactId>
<version>4.8.7.2</version>
<scope>system</scope>
@ -180,7 +180,7 @@
</dependency>
<dependency>
<groupId>net.Indyuce.mmocore.lib</groupId>
<groupId>com.Zrips.CMI</groupId>
<artifactId>CMI</artifactId>
<version>8.6.5.0</version>
<scope>system</scope>
@ -188,7 +188,7 @@
</dependency>
<dependency>
<groupId>net.Indyuce.mmocore.lib</groupId>
<groupId>com.sainttx.holograms</groupId>
<artifactId>Holograms</artifactId>
<version>2.9.1</version>
<scope>system</scope>
@ -196,7 +196,7 @@
</dependency>
<dependency>
<groupId>net.Indyuce.mmocore.lib</groupId>
<groupId>com.gmail.filoghost</groupId>
<artifactId>HolographicDisplays</artifactId>
<version>2.4.6</version>
<scope>system</scope>
@ -204,7 +204,7 @@
</dependency>
<dependency>
<groupId>net.Indyuce.mmocore.lib</groupId>
<groupId>net.citizensnpcs</groupId>
<artifactId>Citizens</artifactId>
<version>2.0.25</version>
<scope>system</scope>
@ -212,7 +212,7 @@
</dependency>
<dependency>
<groupId>net.Indyuce.mmocore.lib</groupId>
<groupId>me.vagdedes.spartan</groupId>
<artifactId>SpartanAPI</artifactId>
<version>1.0</version>
<scope>system</scope>

View File

@ -225,7 +225,7 @@ public class MMOCore extends LuminePlugin {
}
/*
* resource regeneration. must check if entity is dead otherwise regen will make
* Resource regeneration. Must check if entity is dead otherwise regen will make
* the 'respawn' button glitched plus HURT entity effect bug
*/
new BukkitRunnable() {
@ -240,7 +240,7 @@ public class MMOCore extends LuminePlugin {
}.runTaskTimer(MMOCore.plugin, 100, 20);
/*
* clean active loot chests every 5 minutes. cannot register this runnable in
* Clean active loot chests every 5 minutes. Cannot register this runnable in
* the loot chest manager because it is instanced when the plugin loads
*/
new BukkitRunnable() {
@ -255,7 +255,7 @@ public class MMOCore extends LuminePlugin {
* Stamina Addon...This should prevent a couple error reports produced by people
* not reading the installation guide...
*/
if (Bukkit.getPluginManager().getPlugin("MMOItemsMana") != null) {
if (Bukkit.getPluginManager().getPlugin("MMOMana") != null) {
getLogger().log(Level.SEVERE, ChatColor.DARK_RED + "MMOCore is not meant to be used with MMOItems ManaAndStamina");
getLogger().log(Level.SEVERE, ChatColor.DARK_RED + "Please read the installation guide!");
Bukkit.broadcastMessage(ChatColor.DARK_RED + "[MMOCore] MMOCore is not meant to be used with MMOItems ManaAndStamina");
@ -297,20 +297,16 @@ public class MMOCore extends LuminePlugin {
Bukkit.getPluginManager().registerEvents(new PlayerCollectStats(), this);
/*
* initialize player data from all online players. this is very important to do
* Initialize player data from all online players. This is very important to do
* that after registering all the professses otherwise the player datas can't
* recognize what profess the player has and professes will be lost
*/
Bukkit.getOnlinePlayers().forEach(player -> dataProvider.getDataManager().setup(player.getUniqueId()));
/*
* load guild data after loading player data
*/
// load guild data after loading player data
dataProvider.getGuildManager().load();
/*
* commands
*/
// Command
try {
final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");

View File

@ -0,0 +1,27 @@
package net.Indyuce.mmocore.api.event;
import net.Indyuce.mmocore.api.player.PlayerData;
import org.bukkit.event.HandlerList;
public class AsyncPlayerDataLoadEvent extends PlayerDataEvent {
private static final HandlerList handlers = new HandlerList();
/**
* Called when a player data is being loaded into the game.
* This event is called async.
*
* @param playerData Player data being loaded
*/
public AsyncPlayerDataLoadEvent(PlayerData playerData) {
super(playerData);
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@ -1,15 +1,29 @@
package net.Indyuce.mmocore.api.event;
import net.Indyuce.mmocore.api.player.PlayerData;
import net.Indyuce.mmocore.api.player.attribute.PlayerAttribute;
import org.bukkit.event.HandlerList;
public class PlayerAttributeUseEvent extends PlayerDataEvent {
private static final HandlerList handlers = new HandlerList();
public PlayerAttributeUseEvent(PlayerData playerData) {
private final PlayerAttribute attribute;
/**
* Called when a player increases an attribute using the attribute viewer GUI
*
* @param playerData PLayer increasing his attribute
* @param attribute Attribute being increased
*/
public PlayerAttributeUseEvent(PlayerData playerData, PlayerAttribute attribute) {
super(playerData);
this.attribute = attribute;
}
public PlayerAttribute getAttribute() {
return attribute;
}
@Override
public HandlerList getHandlers() {

View File

@ -1,14 +1,20 @@
package net.Indyuce.mmocore.api.event;
import org.bukkit.event.HandlerList;
import net.Indyuce.mmocore.api.player.PlayerData;
import org.bukkit.event.HandlerList;
public class PlayerCombatEvent extends PlayerDataEvent {
private static final HandlerList handlers = new HandlerList();
private final boolean enter;
/**
* Called when a player either enters or leaves combat
* by dealing damage to, or being hit by another entity
*
* @param playerData Player interacting
* @param enter If the player is entering combt
*/
public PlayerCombatEvent(PlayerData playerData, boolean enter) {
super(playerData);

View File

@ -1,12 +1,20 @@
package net.Indyuce.mmocore.api.event;
import net.Indyuce.mmocore.api.player.PlayerData;
import org.bukkit.event.HandlerList;
import net.Indyuce.mmocore.api.player.PlayerData;
/**
* @deprecated Use {@link AsyncPlayerDataLoadEvent} instead
*/
@Deprecated
public class PlayerDataLoadEvent extends PlayerDataEvent {
private static final HandlerList handlers = new HandlerList();
/**
* Called when a player data is being loaded into the game.
*
* @param playerData Player data being loaded
*/
public PlayerDataLoadEvent(PlayerData playerData) {
super(playerData);
}

View File

@ -1,24 +1,28 @@
package net.Indyuce.mmocore.api.event;
import org.bukkit.event.HandlerList;
import net.Indyuce.mmocore.api.player.PlayerData;
import net.Indyuce.mmocore.api.skill.Skill.SkillInfo;
import net.Indyuce.mmocore.api.skill.SkillResult;
import org.bukkit.event.HandlerList;
public class PlayerPostCastSkillEvent extends PlayerDataEvent {
private static final HandlerList handlers = new HandlerList();
private final SkillInfo skill;
private final SkillResult result;
private final boolean successful;
public PlayerPostCastSkillEvent(PlayerData playerData, SkillInfo skill, SkillResult result, boolean successful) {
/**
* Called right after a player casts a skill.
*
* @param playerData Player casting the skill
* @param skill Skill being cast
* @param result SKill casting result
*/
public PlayerPostCastSkillEvent(PlayerData playerData, SkillInfo skill, SkillResult result) {
super(playerData);
this.skill = skill;
this.result = result;
this.successful = successful;
}
public SkillInfo getCast() {
@ -30,7 +34,7 @@ public class PlayerPostCastSkillEvent extends PlayerDataEvent {
}
public boolean wasSuccessful() {
return successful;
return result.isSuccessful();
}
@Override

View File

@ -1,10 +1,9 @@
package net.Indyuce.mmocore.api.event;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import net.Indyuce.mmocore.api.player.PlayerData;
import net.Indyuce.mmocore.api.skill.Skill.SkillInfo;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
public class PlayerPreCastSkillEvent extends PlayerDataEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
@ -13,6 +12,13 @@ public class PlayerPreCastSkillEvent extends PlayerDataEvent implements Cancella
private boolean cancelled;
/**
* Called right before a player casts a skill. This occurs before
* checking for mana, stamina costs and ability cooldown.
*
* @param playerData Player casting the skill
* @param skill Skill being cast
*/
public PlayerPreCastSkillEvent(PlayerData playerData, SkillInfo skill) {
super(playerData);

View File

@ -1,5 +1,7 @@
package net.Indyuce.mmocore.api.loot;
import net.Indyuce.mmocore.MMOCore;
import net.Indyuce.mmocore.manager.SoundManager;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Particle;
@ -9,9 +11,6 @@ import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import net.Indyuce.mmocore.MMOCore;
import net.Indyuce.mmocore.manager.SoundManager;
public class LootChest {
private final ChestTier tier;
private final LootChestRegion region;
@ -19,10 +18,12 @@ public class LootChest {
private final BukkitRunnable effectRunnable;
private final long date = System.currentTimeMillis();
/*
* instance generated when a loot chest is placed (as a bukkit block), and
* used to save the data of the block which has been replaced (can replace
* non-solid blocks)
/**
* Called when a loot chest is placed as a Bukkit block, and used
* to save the data of the block which has been replaced.
* <p>
* A placed drop chest may only replace non solid blocks like grass
* or levels..
*/
public LootChest(ChestTier tier, LootChestRegion region, Block block) {
this.tier = tier;
@ -54,11 +55,13 @@ public class LootChest {
return System.currentTimeMillis() - date > MMOCore.plugin.configManager.lootChestExpireTime;
}
/**
* @param player If a player just the chest. It's set to false
* when a loot chest expires or when MMOCore disables.
*/
public void unregister(boolean player) {
/*
* if a player is responsible of closing the chest, close it with sound
*/
// If a player is responsible of closing the chest, close it with sound
if (player) {
MMOCore.plugin.soundManager.play(block.loc.getBlock(), SoundManager.SoundEvent.CLOSE_LOOT_CHEST);
block.loc.getWorld().spawnParticle(Particle.CRIT, block.loc.clone().add(.5, .5, .5), 16, 0, 0, 0, .5);
@ -66,7 +69,7 @@ public class LootChest {
}
/*
* must clean block inventory before replacing block otherwise loots fly
* Must clean block inventory before replacing block otherwise loots fly
* off and accumulate on the ground (+during dev phase)
*/
else

View File

@ -43,18 +43,18 @@ import java.util.logging.Level;
public class PlayerData extends OfflinePlayerData {
/*
* is updated everytime the player joins the server. it is kept when the
* player is offline so the plugin can use #isOnline to check if the player
* is online
/**
* Corresponds to the MythicLib player data. It is used to keep
* track of the Player instance corresponding to that player data,
* as well as other things like the last time the player logged in/out
*/
private final MMOPlayerData mmoData;
/*
* 'profess' can be null, you need to retrieve the player class using the
* getProfess() method which should never return null if the plugin is
* configured right
/**
* Can be null, the {@link #getProfess()} method will return the
* player class, or the default one if this field is null.
*/
@Nullable
private PlayerClass profess;
private int level, experience, classPoints, skillPoints, attributePoints, attributeReallocationPoints;// skillReallocationPoints,
private double mana, stamina, stellium;
@ -74,14 +74,16 @@ public class PlayerData extends OfflinePlayerData {
private long lastWaypoint, lastFriendRequest, actionBarTimeOut, lastLootChest;
/*
* NON-FINAL player data stuff made public to facilitate field change
*/
// NON-FINAL player data stuff made public to facilitate field change
public int skillGuiDisplayOffset;
public SkillCasting skillCasting;
public boolean nocd;
public CombatRunnable combat;
/**
* Player data is stored in the data map before it's actually fully loaded
* so that external plugins don't necessarily have to listen to the PlayerDataLoadEvent.
*/
private boolean fullyLoaded = false;
public PlayerData(MMOPlayerData mmoData) {
@ -92,8 +94,8 @@ public class PlayerData extends OfflinePlayerData {
this.questData = new PlayerQuests(this);
}
/*
* update all references after /mmocore reload so there can be garbage
/**
* Update all references after /mmocore reload so there can be garbage
* collection with old plugin objects like class or skill instances.
*/
public void update() {
@ -175,8 +177,8 @@ public class PlayerData extends OfflinePlayerData {
return skillPoints;
}
/*
* returns level up needed in order to level up
/**
* @return Experience needed in order to reach next level
*/
public int getLevelUpExperience() {
return getProfess().getExpCurve().getExperience(getLevel() + 1);
@ -206,10 +208,6 @@ public class PlayerData extends OfflinePlayerData {
return guild != null;
}
// public boolean isOnline() {
// return player.isOnline();
// }
public void setLevel(int level) {
this.level = Math.max(1, level);
getStats().updateStats();
@ -232,14 +230,17 @@ public class PlayerData extends OfflinePlayerData {
refreshVanillaExp();
}
/**
* Class experience can be displayed on the player's exp bar.
* This updates the exp bar to display the player class level and exp.
*/
public void refreshVanillaExp() {
if (MMOCore.plugin.configManager.overrideVanillaExp) {
if (!isOnline())
if (!isOnline() || !MMOCore.plugin.configManager.overrideVanillaExp)
return;
getPlayer().setLevel(getLevel());
getPlayer().setExp(Math.max(0, Math.min(1, (float) experience / (float) getLevelUpExperience())));
}
}
// public void setSkillReallocationPoints(int value) {
// skillReallocationPoints = Math.max(0, value);
@ -301,10 +302,12 @@ public class PlayerData extends OfflinePlayerData {
return Math.max(0, lastWaypoint + 5000 - System.currentTimeMillis());
}
/*
* handles the per-player loot chest cooldown. that is to reduce the risk of
* spawning multiple chests in a row around the same player which could
* break the gameplay
/**
* Handles the per-player loot chest cooldown system. That is to
* reduce the rik of spawning multiple loot chests around the same
* player in a row, which could be game breaking.
*
* @return If a random chest can spawn around that player
*/
public boolean canSpawnLootChest() {
return lastLootChest + MMOCore.plugin.configManager.lootChestPlayerCooldown < System.currentTimeMillis();
@ -371,18 +374,18 @@ public class PlayerData extends OfflinePlayerData {
}
public void warp(Waypoint waypoint) {
if (!isOnline())
return;
/*
* this cooldown is only used internally to make sure the player is not
* spamming waypoints. there is no need to reset it when resetting the
* This cooldown is only used internally to make sure the player is not
* spamming waypoints. There is no need to reset it when resetting the
* player waypoints data
*/
lastWaypoint = System.currentTimeMillis();
giveStellium(-waypoint.getStelliumCost());
if (!isOnline())
return;
new BukkitRunnable() {
final int x = getPlayer().getLocation().getBlockX();
final int y = getPlayer().getLocation().getBlockY();
@ -424,6 +427,12 @@ public class PlayerData extends OfflinePlayerData {
return getProfess().getMaxLevel() > 0 && getLevel() >= getProfess().getMaxLevel();
}
/**
* Gives experience without displaying an EXP hologram around the player
*
* @param value Experience to give the player
* @param source How the player earned experience
*/
public void giveExperience(int value, EXPSource source) {
giveExperience(value, source, null);
}
@ -442,9 +451,7 @@ public class PlayerData extends OfflinePlayerData {
return;
}
/*
* Handle experience hologram
*/
// Experience hologram
if (hologramLocation != null && isOnline() && MMOCore.plugin.hasHolograms())
MMOCore.plugin.hologramSupport.displayIndicator(hologramLocation.add(.5, 1.5, .5),
MMOCore.plugin.configManager.getSimpleMessage("exp-hologram", "exp", "" + value).message(), getPlayer());
@ -459,6 +466,7 @@ public class PlayerData extends OfflinePlayerData {
experience += event.getExperience();
// Calculate the player's next level
int oldLevel = level, needed;
while (experience >= (needed = getLevelUpExperience())) {
@ -577,14 +585,18 @@ public class PlayerData extends OfflinePlayerData {
return skillCasting != null;
}
/*
* returns if the action bar is not being used to display anything else and
* if the general info action bar can be displayed
/**
* @return If the action bar is not being used to display anything else
* i.e if the "general info" action bar can be displayed
*/
public boolean canSeeActionBar() {
return actionBarTimeOut < System.currentTimeMillis();
}
/**
* @param timeOut Delay during which the general info action bar
* will not be displayed to the player
*/
public void setActionBarTimeOut(long timeOut) {
actionBarTimeOut = System.currentTimeMillis() + (timeOut * 50);
}
@ -592,6 +604,7 @@ public class PlayerData extends OfflinePlayerData {
public void displayActionBar(String message) {
if (!isOnline())
return;
setActionBarTimeOut(MMOCore.plugin.actionBarManager.getTimeOut());
getPlayer().spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message));
}
@ -635,11 +648,15 @@ public class PlayerData extends OfflinePlayerData {
return getProfess().hasSkill(skill.getId()) && hasSkillUnlocked(getProfess().getSkill(skill.getId()));
}
/*
* (bug fix) any skill, when the player has the right level is instantly
/**
* Checks for the player's level and compares it to the skill unlock level.
* <p>
* Any skill, when the player has the right level is instantly
* unlocked, therefore one must NOT check if the player has unlocked the
* skill by checking if the skills map contains the skill id as key. this
* skill by checking if the skills map contains the skill id as key. This
* only checks if the player has spent any skill point.
*
* @return If the player unlocked the skill
*/
public boolean hasSkillUnlocked(SkillInfo info) {
return getLevel() >= info.getUnlockLevel();
@ -711,6 +728,13 @@ public class PlayerData extends OfflinePlayerData {
return combat != null;
}
/**
* Loops through all the subclasses available to the player and
* checks if they could potentially upgrade to one of these
*
* @return If the player can change its current class to
* a subclass
*/
public boolean canChooseSubclass() {
for (Subclass subclass : getProfess().getSubclasses())
if (getLevel() >= subclass.getLevel())
@ -718,6 +742,10 @@ public class PlayerData extends OfflinePlayerData {
return false;
}
/**
* Everytime a player does a combat action, like taking
* or dealing damage to an entity, this method is called.
*/
public void updateCombat() {
if (isInCombat())
combat.update();
@ -736,12 +764,10 @@ public class PlayerData extends OfflinePlayerData {
if (preEvent.isCancelled())
return new SkillResult(this, skill, CancelReason.OTHER);
/*
* skill, mana stamina aand cooldown requirements are all calculated in
* the SkillResult instances. this cast(SkillResult) method only applies
* cooldown, reduces mana and/or stamina and send messages
*/
// Check for mana/stamina/cooldown and cast skill
SkillResult cast = skill.getSkill().whenCast(this, skill);
// Send failure messages
if (!cast.isSuccessful()) {
if (!skill.getSkill().isPassive() && isOnline()) {
if (cast.getCancelReason() == CancelReason.LOCKED)
@ -757,11 +783,12 @@ public class PlayerData extends OfflinePlayerData {
MMOCore.plugin.configManager.getSimpleMessage("casting.on-cooldown").send(getPlayer());
}
PlayerPostCastSkillEvent postEvent = new PlayerPostCastSkillEvent(this, skill, cast, false);
PlayerPostCastSkillEvent postEvent = new PlayerPostCastSkillEvent(this, skill, cast);
Bukkit.getPluginManager().callEvent(postEvent);
return cast;
}
// Apply cooldown, mana and stamina costs
if (!nocd) {
double flatCooldownReduction = Math.max(0, Math.min(1, getStats().getStat(StatType.COOLDOWN_REDUCTION) / 100));
flatCooldownReduction *= flatCooldownReduction > 0 ? skill.getModifier("cooldown", getSkillLevel(skill.getSkill())) * 1000 : 0;
@ -771,7 +798,7 @@ public class PlayerData extends OfflinePlayerData {
giveStamina(-cast.getStaminaCost());
}
PlayerPostCastSkillEvent postEvent = new PlayerPostCastSkillEvent(this, skill, cast, true);
PlayerPostCastSkillEvent postEvent = new PlayerPostCastSkillEvent(this, skill, cast);
Bukkit.getPluginManager().callEvent(postEvent);
return cast;
}

View File

@ -42,7 +42,7 @@ public class AttributeView extends EditableInventory {
}
public GeneratedInventory newInventory(PlayerData data) {
return new SkillViewerInventory(data, this);
return new AttributeViewerInventory(data, this);
}
public static class AttributeItem extends InventoryPlaceholderItem {
@ -74,8 +74,8 @@ public class AttributeView extends EditableInventory {
}
}
public class SkillViewerInventory extends GeneratedInventory {
public SkillViewerInventory(PlayerData playerData, EditableInventory editable) {
public class AttributeViewerInventory extends GeneratedInventory {
public AttributeViewerInventory(PlayerData playerData, EditableInventory editable) {
super(playerData, editable);
}
@ -130,7 +130,7 @@ public class AttributeView extends EditableInventory {
MMOCore.plugin.configManager.getSimpleMessage("attribute-level-up", "attribute", attribute.getName(), "level", "" + ins.getBase()).send(player);
MMOCore.plugin.soundManager.play(getPlayer(), SoundManager.SoundEvent.LEVEL_ATTRIBUTE);
PlayerAttributeUseEvent playerAttributeUseEvent = new PlayerAttributeUseEvent(playerData);
PlayerAttributeUseEvent playerAttributeUseEvent = new PlayerAttributeUseEvent(playerData, attribute);
Bukkit.getServer().getPluginManager().callEvent(playerAttributeUseEvent);
open();

View File

@ -1,6 +1,11 @@
package net.Indyuce.mmocore.listener;
import net.Indyuce.mmocore.MMOCore;
import net.Indyuce.mmocore.api.event.PlayerRegenResourceEvent;
import net.Indyuce.mmocore.api.player.PlayerData;
import net.Indyuce.mmocore.api.player.profess.resource.PlayerResource;
import net.Indyuce.mmocore.gui.api.PluginInventory;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
@ -12,52 +17,35 @@ import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import net.Indyuce.mmocore.MMOCore;
import net.Indyuce.mmocore.api.event.PlayerRegenResourceEvent;
import net.Indyuce.mmocore.api.player.PlayerData;
import net.Indyuce.mmocore.api.player.profess.resource.PlayerResource;
import net.Indyuce.mmocore.gui.api.PluginInventory;
import org.bukkit.scheduler.BukkitRunnable;
public class PlayerListener implements Listener {
/*
We load our player data.
*/
// Player data loading
@EventHandler(priority = EventPriority.NORMAL)
public void playerLoadingEvent(PlayerJoinEvent e) {
new BukkitRunnable() {
@Override
public void run() {
MMOCore.plugin.dataProvider.getDataManager().setup(e.getPlayer().getUniqueId());
}
}.runTaskAsynchronously(MMOCore.plugin);
public void playerLoadingEvent(PlayerJoinEvent event) {
MMOCore.plugin.dataProvider.getDataManager().setup(event.getPlayer().getUniqueId());
}
/*
* custom inventories register
*/
// Register custom inventory clicks
@EventHandler
public void b(InventoryClickEvent event) {
if (event.getInventory().getHolder() instanceof PluginInventory)
((PluginInventory) event.getInventory().getHolder()).whenClicked(event);
}
// Register custom inventory close effect
@EventHandler
public void c(InventoryCloseEvent event) {
if (event.getInventory().getHolder() instanceof PluginInventory)
((PluginInventory) event.getInventory().getHolder()).whenClosed(event);
}
/*
* updates the player's combat log data every time he hits an entity, or
* gets hit by an entity or a projectile sent by another entity. updates
* this stuff on LOW level so other plugins can check if the player just
* entered combat
/**
* Updates the player's combat log data every time he hits an entity, or
* gets hit by an entity or a projectile sent by another entity
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void d(EntityDamageByEntityEvent event) {
@ -81,16 +69,7 @@ public class PlayerListener implements Listener {
MMOCore.plugin.dataProvider.getDataManager().remove(playerData);
}
/*
* reset skill data when leaving combat
*/
// @EventHandler
// public void f(PlayerCombatEvent event) {
// if (!event.entersCombat())
// event.getData().getSkillData().resetData();
// }
/*
/**
* Warning: this really is not the best way to interface with MMOCore
* generation. Use instead PlayerRegenResourceEvent to be able to access
* directly the PlayerData without an extra map lookup.

View File

@ -1,17 +1,18 @@
package net.Indyuce.mmocore.manager.data;
import java.util.*;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.ConfigurationSection;
import io.lumine.mythic.lib.api.player.MMOPlayerData;
import net.Indyuce.mmocore.MMOCore;
import net.Indyuce.mmocore.api.event.AsyncPlayerDataLoadEvent;
import net.Indyuce.mmocore.api.event.PlayerDataLoadEvent;
import net.Indyuce.mmocore.api.player.OfflinePlayerData;
import net.Indyuce.mmocore.api.player.PlayerData;
import io.lumine.mythic.lib.api.player.MMOPlayerData;
import org.bukkit.scheduler.BukkitRunnable;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull;
import java.util.*;
public abstract class PlayerDataManager {
private final static Map<UUID, PlayerData> data = Collections.synchronizedMap(new HashMap<>());
@ -22,38 +23,68 @@ public abstract class PlayerDataManager {
return get(player.getUniqueId());
}
/**
* Gets the player data, or throws an exception if not found.
* The player data should be loaded when the player logs in
* so it's really bad practice to setup the player data if it's not loaded.
*
* @param uuid Player UUID
* @return Player data, if it's loaded
*/
public PlayerData get(UUID uuid) {
return data.getOrDefault(uuid, setup(uuid));
Validate.isTrue(data.containsKey(uuid), "Player data is not loaded");
return data.get(uuid);
}
public void remove(UUID uuid) {
data.remove(uuid);
}
/**
* Offline player data is used to handle processes like friend removal
* which can still occur if one of the two players is offline.
* <p>
* Unlike {@link #get(UUID)} this method never returns a null instance
*
* @param uuid Player unique id
* @return Offline player data
*/
@NotNull
public abstract OfflinePlayerData getOffline(UUID uuid);
/**
* Called when a player logs in, loading the player data inside the map.
* <p>
* For YAML configs or SQL databases, data is loaded as not to overload
* the main thread with SQL requests. Therefore, the player data returned
* by that method, when the player joined for the first time, is not
* fully loaded YET.
*
* @param uniqueId Player UUID
* @return The loaded player data.
*/
public PlayerData setup(UUID uniqueId) {
return data.compute(uniqueId, (uuid, searchData) -> {
if (searchData == null) {
PlayerData playerData = new PlayerData(MMOPlayerData.get(uniqueId));
loadData(playerData);
playerData.getStats().updateStats();
// We call the player data load event. TODO: Convert this event to async.
new BukkitRunnable() {
@Override
public void run() {
Bukkit.getPluginManager().callEvent(new PlayerDataLoadEvent(playerData));
}
}.runTask(MMOCore.plugin);
return playerData;
} else return searchData;
// Load player data if it does not exist
if (!data.containsKey(uniqueId)) {
PlayerData newData = new PlayerData(MMOPlayerData.get(uniqueId));
// Schedule async data loading
Bukkit.getScheduler().runTaskAsynchronously(MMOCore.plugin, () -> {
loadData(newData);
newData.getStats().updateStats();
Bukkit.getPluginManager().callEvent(new AsyncPlayerDataLoadEvent(newData));
Bukkit.getScheduler().runTask(MMOCore.plugin, () -> Bukkit.getPluginManager().callEvent(new PlayerDataLoadEvent(newData)));
});
// Update data map
data.put(uniqueId, newData);
return newData;
}
return data.get(uniqueId);
}
public DefaultPlayerData getDefaultData() {
return defaultData;
@ -71,8 +102,18 @@ public abstract class PlayerDataManager {
return data.values();
}
/**
* Called when player data must be loaded from database or config.
*
* @param data Player data to load
*/
public abstract void loadData(PlayerData data);
/**
* Called when player data must be saved in configs or database.
*
* @param data Player data to save
*/
public abstract void saveData(PlayerData data);
public abstract void remove(PlayerData data);