Skip to content

Commit

Permalink
Improve move event listener/player cache a bit (#6910)
Browse files Browse the repository at this point in the history
* Improve move event listener/player cache a bit

* Comments
  • Loading branch information
Warriorrrr authored Aug 8, 2023
1 parent b399583 commit c65e311
Show file tree
Hide file tree
Showing 10 changed files with 65 additions and 94 deletions.
18 changes: 4 additions & 14 deletions Towny/src/main/java/com/palmergames/bukkit/towny/Towny.java
Original file line number Diff line number Diff line change
Expand Up @@ -602,10 +602,10 @@ public PlayerCache newCache(Player player) {

TownyWorld world = TownyAPI.getInstance().getTownyWorld(player.getWorld());
if (world == null) {
TownyMessaging.sendErrorMsg(player, "Could not create permission cache for this world (" + player.getWorld().getName() + ".");
return null;
TownyMessaging.sendErrorMsg(player, "Could not create permission cache for unregistered world (" + player.getWorld().getName() + ").");
return null;
}
PlayerCache cache = new PlayerCache(world, player);
PlayerCache cache = new PlayerCache(player);
playerCache.put(player.getUniqueId(), cache);
return cache;

Expand Down Expand Up @@ -635,17 +635,7 @@ public void deleteCache(UUID uuid) {
* @return the current (or new) cache for this player.
*/
public PlayerCache getCache(Player player) {

PlayerCache cache = playerCache.get(player.getUniqueId());

if (cache == null) {
cache = newCache(player);

if (cache != null)
cache.setLastTownBlock(WorldCoord.parseWorldCoord(player));
}

return cache;
return playerCache.computeIfAbsent(player.getUniqueId(), k -> newCache(player));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public static void generateAndSend(Towny plugin, Player player, int lineHeight)
return;
}

Coord pos = Coord.parseCoord(plugin.getCache(player).getLastLocation());
WorldCoord pos = WorldCoord.parseWorldCoord(player.getLocation());
final Translator translator = Translator.locale(player);

// Generate Map
Expand Down Expand Up @@ -278,7 +278,7 @@ else if (townblock.isOutpost())
for (Component component : map)
Towny.getAdventure().player(player).sendMessage(component);

TownBlock townblock = TownyAPI.getInstance().getTownBlock(plugin.getCache(player).getLastLocation());
TownBlock townblock = pos.getTownBlockOrNull();
TownyMessaging.sendMsg(player, translator.of("status_towny_map_town_line",
(townblock != null && townblock.hasTown() ? townblock.getTownOrNull() : translator.of("status_no_town")),
(townblock != null && townblock.hasResident() ? townblock.getResidentOrNull() : translator.of("status_no_town"))));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@ public void parsePlotSetOutpost(Player player, Resident resident, TownBlock town

Town town = townBlock.getTownOrNull();
TownyWorld townyWorld = townBlock.getWorld();
Coord key = Coord.parseCoord(plugin.getCache(player).getLastLocation());
Coord key = Coord.parseCoord(player.getLocation());

if (OutpostUtil.OutpostTests(town, resident, townyWorld, key, resident.isAdmin(), true)) {
// Test if they can pay.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3654,7 +3654,7 @@ public static void parseTownClaimCommand(Player player, String[] split) throws T
Town town = getTownFromResidentOrThrow(resident);

// Allow a bankrupt town to claim a single plot.
if (town.isBankrupt() && town.getTownBlocks().size() != 0)
if (town.isBankrupt() && !town.getTownBlocks().isEmpty())
throw new TownyException(Translatable.of("msg_err_bankrupt_town_cannot_claim"));

final TownyWorld world = TownyAPI.getInstance().getTownyWorld(player.getWorld());
Expand All @@ -3668,7 +3668,7 @@ public static void parseTownClaimCommand(Player player, String[] split) throws T
List<WorldCoord> selection;
boolean outpost = false;
boolean isAdmin = resident.isAdmin();
Coord key = Coord.parseCoord(plugin.getCache(player).getLastLocation());
WorldCoord key = WorldCoord.parseWorldCoord(player);

/*
* Make initial selection of WorldCoord(s)
Expand All @@ -3683,12 +3683,12 @@ public static void parseTownClaimCommand(Player player, String[] split) throws T
// Run various tests required by configuration/permissions through Util.
OutpostUtil.OutpostTests(town, resident, world, key, isAdmin, false);

if (!TownyAPI.getInstance().isWilderness(plugin.getCache(player).getLastLocation()))
if (key.hasTownBlock())
throw new TownyException(Translatable.of("msg_already_claimed_1", key));

// Select a single WorldCoord using the AreaSelectionUtil.
selection = new ArrayList<>();
selection.add(new WorldCoord(world.getName(), key));
selection.add(key);
outpost = true;

} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1976,16 +1976,10 @@ private void adminSetPlot(CommandSender sender, String[] split) throws TownyExce
TownyMessaging.sendMsg(player, Translatable.of("changed_plot_town", newTown.getName()));
} else {
Town town = getTownOrThrow(split[1]);
TownyWorld world = TownyAPI.getInstance().getTownyWorld(player.getWorld());
Coord key = Coord.parseCoord(plugin.getCache(player).getLastLocation());
List<WorldCoord> selection;
if (split.length == 2)
selection = AreaSelectionUtil.selectWorldCoordArea(town, new WorldCoord(world.getName(), key), new String[0], true);
else {
String[] newSplit = StringMgmt.remFirstArg(split);
newSplit = StringMgmt.remFirstArg(newSplit);
selection = AreaSelectionUtil.selectWorldCoordArea(town, new WorldCoord(world.getName(), key), newSplit, true);
}
WorldCoord key = WorldCoord.parseWorldCoord(player);
String[] newSplit = StringMgmt.remArgs(split, 2);
List<WorldCoord> selection = AreaSelectionUtil.selectWorldCoordArea(town, key, newSplit, true);

TownyMessaging.sendDebugMsg("Admin Initiated townClaim: Pre-Filter Selection ["+selection.size()+"] " + Arrays.toString(selection.toArray(new WorldCoord[0])));
selection = AreaSelectionUtil.filterOutTownOwnedBlocks(selection);
TownyMessaging.sendDebugMsg("Admin Initiated townClaim: Post-Filter Selection ["+selection.size()+"] " + Arrays.toString(selection.toArray(new WorldCoord[0])));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ public class TownyPlayerListener implements Listener {
private CommandList blockedWarCommands;
private CommandList ownPlotLimitedCommands;

private int teleportWarmupTime = TownySettings.getTeleportWarmupTime();
private boolean isMovementCancellingWarmup = TownySettings.isMovementCancellingSpawnWarmup();

private static final MethodHandle GET_RESPAWN_FLAGS;

static {
Expand All @@ -130,6 +133,11 @@ public TownyPlayerListener(Towny plugin) {
this.plugin = plugin;
loadBlockedCommandLists();
TownySettings.addReloadListener(NamespacedKey.fromString("blocked-commands", plugin), config -> loadBlockedCommandLists());

TownySettings.addReloadListener(NamespacedKey.fromString("teleport-warmups", plugin), () -> {
this.teleportWarmupTime = TownySettings.getTeleportWarmupTime();
this.isMovementCancellingWarmup = TownySettings.isMovementCancellingSpawnWarmup();
});
}

@EventHandler(priority = EventPriority.NORMAL)
Expand Down Expand Up @@ -722,52 +730,37 @@ public void onPlayerMove(PlayerMoveEvent event) {
return;
}

Player player = event.getPlayer();
Location to = event.getTo();
Location from = event.getFrom();

/*
* Abort if we havn't really moved
* Abort if we haven't really moved
*/
if (event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockZ() == event.getTo().getBlockZ() && event.getFrom().getBlockY() == event.getTo().getBlockY()) {
if (from.getBlockX() == to.getBlockX() && from.getBlockZ() == to.getBlockZ() && from.getBlockY() == to.getBlockY()) {
return;
}

TownyUniverse townyUniverse = TownyUniverse.getInstance();
Player player = event.getPlayer();
Location to = event.getTo();
Location from;
PlayerCache cache = plugin.getCache(player);
Resident resident = townyUniverse.getResident(player.getUniqueId());

if (resident != null
&& TownySettings.getTeleportWarmupTime() > 0
&& TownySettings.isMovementCancellingSpawnWarmup()
&& resident.hasRequestedTeleport()
&& !townyUniverse.getPermissionSource().isTownyAdmin(player)
&& TeleportWarmupTimerTask.abortTeleportRequest(resident)) {
TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_teleport_cancelled"));
if (this.teleportWarmupTime > 0 && this.isMovementCancellingWarmup) {
final Resident resident = TownyAPI.getInstance().getResident(player);

if (resident != null && resident.hasRequestedTeleport() && !resident.isAdmin() && TeleportWarmupTimerTask.abortTeleportRequest(resident))
TownyMessaging.sendErrorMsg(player, Translatable.of("msg_err_teleport_cancelled"));
}

try {
from = cache.getLastLocation();
} catch (NullPointerException e) {
from = event.getFrom();
}

if (WorldCoord.cellChanged(from, to)) {

TownyWorld fromWorld = TownyAPI.getInstance().getTownyWorld(from.getWorld());
TownyWorld toWorld = TownyAPI.getInstance().getTownyWorld(to.getWorld());
if (fromWorld == null || toWorld == null) {
TownyMessaging.sendErrorMsg(player, Translatable.of("not_registered"));
cache.setLastLocation(to);
return;
}
WorldCoord fromCoord = new WorldCoord(fromWorld.getName(), fromWorld.getUUID(), Coord.parseCoord(from));
WorldCoord toCoord = new WorldCoord(toWorld.getName(), fromWorld.getUUID(), Coord.parseCoord(to));
WorldCoord fromCoord = WorldCoord.parseWorldCoord(from);
WorldCoord toCoord = WorldCoord.parseWorldCoord(to);

onPlayerMoveChunk(player, fromCoord, toCoord, from, to, event);
onPlayerMoveChunk(player, fromCoord, toCoord, event);
}

// Update the cached players current location
cache.setLastLocation(to);
}

@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
Expand Down Expand Up @@ -900,10 +893,11 @@ public void onPlayerFishEvent(PlayerFishEvent event) {
/*
* PlayerMoveEvent that can fire the PlayerChangePlotEvent
*/
public void onPlayerMoveChunk(Player player, WorldCoord from, WorldCoord to, Location fromLoc, Location toLoc, PlayerMoveEvent moveEvent) {
private void onPlayerMoveChunk(Player player, WorldCoord from, WorldCoord to, PlayerMoveEvent moveEvent) {

plugin.getCache(player).setLastLocation(toLoc);
plugin.getCache(player).updateCoord(to);
final PlayerCache cache = plugin.getCacheOrNull(player.getUniqueId());
if (cache != null)
cache.resetAndUpdate(to);

PlayerChangePlotEvent event = new PlayerChangePlotEvent(player, from, to, moveEvent);
BukkitTools.fireEvent(event);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

import com.palmergames.bukkit.towny.object.TownyPermission.ActionType;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class PlayerCache {

Expand All @@ -18,17 +20,11 @@ public class PlayerCache {

private WorldCoord lastWorldCoord;
private String blockErrMsg;
private Location lastLocation;
private final UUID playerUUID;

public PlayerCache(TownyWorld world, Player player) {

this(new WorldCoord(world.getName(), Coord.parseCoord(player)));
this.lastLocation = player.getLocation();
}

public PlayerCache(@NotNull WorldCoord worldCoord) {

this.setLastTownBlock(worldCoord);
public PlayerCache(Player player) {
this.lastWorldCoord = WorldCoord.parseWorldCoord(player);
this.playerUUID = player.getUniqueId();
}

/**
Expand Down Expand Up @@ -207,16 +203,23 @@ public boolean hasBlockErrMsg() {
return blockErrMsg != null;
}

/**
* Deprecated as of 0.99.5.9, location caching is no longer used.
*/
@Deprecated
public void setLastLocation(Location lastLocation) {

this.lastLocation = lastLocation.clone();
}

/**
* @deprecated Deprecated as of 0.99.5.9, location caching is no longer used.
*/
@Deprecated
public Location getLastLocation() throws NullPointerException {
final Player player = Bukkit.getServer().getPlayer(this.playerUUID);
if (player == null)
throw new NullPointerException(); // adhere to the throws contract

if (lastLocation == null)
throw new NullPointerException();
else
return lastLocation;
return player.getLocation();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

Expand Down Expand Up @@ -87,7 +88,8 @@ public static void requestTeleport(@NotNull Resident resident, @NotNull Location
* @param resident The resident to abort the request for.
* @return Whether the resident had an active teleport request.
*/
public static boolean abortTeleportRequest(Resident resident) {
@Contract("null -> false")
public static boolean abortTeleportRequest(@Nullable Resident resident) {
if (resident == null)
return false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,9 @@ public static PlayerCache getCache(Player player) {
*/
public static boolean getCachePermission(Player player, Location location, Material material, ActionType action) {

WorldCoord worldCoord;
final WorldCoord worldCoord = WorldCoord.parseWorldCoord(location);

try {
// Test required for portalCreateEvent in WorldListener, player hasn't changed worlds yet.
if (player.getWorld().equals(location.getWorld()))
worldCoord = new WorldCoord(player.getWorld().getName(), Coord.parseCoord(location));
else
worldCoord = new WorldCoord(location.getWorld().getName(), Coord.parseCoord(location));
PlayerCache cache = plugin.getCache(player);
cache.updateCoord(worldCoord);

Expand All @@ -82,13 +77,6 @@ public static boolean getCachePermission(Player player, Location location, Mater

} catch (NullPointerException e) {
// New or old cache permission was null, update it

// Test required for portalCreateEvent in WorldListener, player hasn't changed worlds yet.
if (location.getWorld().equals(player.getWorld()))
worldCoord = new WorldCoord(player.getWorld().getName(), Coord.parseCoord(location));
else
worldCoord = new WorldCoord(location.getWorld().getName(), Coord.parseCoord(location));

TownBlockStatus status = cacheStatus(player, worldCoord, fetchTownBlockStatus(player, worldCoord));
triggerCacheCreate(player, location, worldCoord, status, material, action);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -432,12 +432,12 @@ private static CompletableFuture<Location> getSpawnLoc(Player player, Town town,
else if (town != null && town.hasSpawn())
return town.getSpawnOrNull();
else
return plugin.getCache(player).getLastLocation().getWorld().getSpawnLocation();
return player.getWorld().getSpawnLocation();
});
} else if (town != null && town.hasSpawn())
yield CompletableFuture.completedFuture(town.getSpawnOrNull());
else
yield CompletableFuture.completedFuture(plugin.getCache(player).getLastLocation().getWorld().getSpawnLocation());
yield CompletableFuture.completedFuture(player.getWorld().getSpawnLocation());
case TOWN:
if (outpost)
yield CompletableFuture.completedFuture(getOutpostSpawnLocation(town, split));
Expand Down

0 comments on commit c65e311

Please sign in to comment.