diff --git a/src/main/java/net/tfminecraft/magic/gear/GearStationListener.java b/src/main/java/net/tfminecraft/magic/gear/GearStationListener.java index 20ef335..7a41907 100644 --- a/src/main/java/net/tfminecraft/magic/gear/GearStationListener.java +++ b/src/main/java/net/tfminecraft/magic/gear/GearStationListener.java @@ -16,7 +16,7 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.event.world.EntitiesLoadEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; @@ -92,8 +92,9 @@ public void onFurnitureBroken(FurnitureBreakEvent event) { } } + /** Paper loads a chunk's entities after the chunk, so station displays are settled only now. */ @EventHandler - public void onChunkLoad(ChunkLoadEvent event) { + public void onEntitiesLoad(EntitiesLoadEvent event) { GearStationStore.reconcile(event.getChunk()); } diff --git a/src/main/java/net/tfminecraft/magic/gear/GearStationStore.java b/src/main/java/net/tfminecraft/magic/gear/GearStationStore.java index 8cf6d77..6b5685e 100644 --- a/src/main/java/net/tfminecraft/magic/gear/GearStationStore.java +++ b/src/main/java/net/tfminecraft/magic/gear/GearStationStore.java @@ -340,14 +340,25 @@ private static Map readChargedRaw(Map row) { } /** - * When a chunk loads, a saved station with no furniture drops its weapon. A station - * that is still there keeps a single display, including one left behind in an - * unloaded chunk. + * Runs once a chunk's entities are loaded: Paper loads them after the chunk itself, so + * this is the first point where a station's displays can be seen. A saved station with + * no furniture drops its weapon. A station that is still there keeps a single display. + * Displays of stations that are gone, including untagged ones from older versions, are + * removed. */ public static void reconcile(Chunk chunk) { if (loading || chunk == null) { return; } + Map> found = new LinkedHashMap<>(); + for (Entity entity : chunk.getEntities()) { + if (entity instanceof ItemDisplay display) { + String owner = stationOf(display); + if (owner != null) { + found.computeIfAbsent(owner, ignored -> new ArrayList<>()).add(display); + } + } + } List keys = new ArrayList<>(); for (String stationKey : OCCUPIED.keySet()) { Location location = locationFromKey(stationKey); @@ -370,17 +381,94 @@ public static void reconcile(Chunk chunk) { abandon(location); continue; } - UUID displayId = ensureDisplay(location, occupancy.getItem(), occupancy.displayId); + UUID displayId = keepOne(location, occupancy, found.getOrDefault(stationKey, List.of())); if (!displayId.equals(occupancy.displayId)) { occupancy.displayId = displayId; changed = true; } } + found.forEach((stationKey, displays) -> { + if (!OCCUPIED.containsKey(stationKey) && !savedOccupied(stationKey)) { + removeLeftovers(stationKey, displays); + } + }); if (changed) { save(); } } + /** Keeps the station's saved display (or the first one found), removes extra copies, spawns one if none. */ + private static UUID keepOne(Location location, Occupancy occupancy, List displays) { + ItemDisplay keep = displays.isEmpty() ? null : displays.get(0); + for (ItemDisplay display : displays) { + if (display.getUniqueId().equals(occupancy.displayId)) { + keep = display; + } + } + if (keep == null) { + return spawnDisplay(location, occupancy.getItem()); + } + int extra = 0; + for (ItemDisplay display : displays) { + if (display != keep) { + display.remove(); + extra++; + } + } + if (extra > 0) { + Magic.plugin.getLogger().warning("[Magic] Removed " + extra + " extra displays at gear station " + key(location) + "."); + } + keep.setItemStack(occupancy.getItem()); + mark(keep, location); + return keep.getUniqueId(); + } + + /** + * A saved row still holds the station (held for review, not loaded yet, or its world was + * missing at startup). An unreadable store counts as held, so nothing is removed. + */ + private static boolean savedOccupied(String stationKey) { + try { + return property().occupied(stationKey); + } catch (IOException ex) { + warning(ex); + return true; + } + } + + /** Displays of a station that no longer exists. An abandoned station has already removed its own. */ + private static void removeLeftovers(String stationKey, List displays) { + int removed = 0; + for (ItemDisplay display : displays) { + if (display.isValid()) { + display.remove(); + removed++; + } + } + if (removed > 0) { + Magic.plugin.getLogger().warning("[Magic] Removed " + removed + " leftover displays at gear station " + + stationKey + " (no station there)."); + } + } + + /** + * The station a display belongs to: its tag, or for an untagged station display from an + * older version its position (1.15 above the block centre, no other plugin's data). + */ + private static String stationOf(ItemDisplay display) { + String marked = markOf(display); + if (marked != null) { + return marked; + } + if (!isGearDisplay(display) || !display.getPersistentDataContainer().isEmpty()) { + return null; + } + Location base = display.getLocation().subtract(0.5, 1.15, 0.5); + // Rounded, not floored: y + 1.15 - 1.15 can land just below a whole number. + Location block = new Location(base.getWorld(), Math.round(base.getX()), Math.round(base.getY()), Math.round(base.getZ())); + return base.distanceSquared(block) < 1.0E-4 ? key(block) : null; + } + /** * Occupied station whose block center is within {@code maxDistance} of {@code origin}. * 0.75 reaches a frame in this block and stops short of the next block's center. @@ -460,6 +548,11 @@ private static UUID ensureDisplay(Location location, ItemStack item, UUID savedD if (!world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) { location.getChunk().load(); } + if (!location.getChunk().isEntitiesLoaded()) { + // Existing displays can't be seen yet; spawning now would add a copy. The + // entities-load reconcile keeps or spawns the display. + return savedDisplay; + } ItemDisplay existing = displayOrNull(savedDisplay); if (existing == null) { existing = findTagged(location); diff --git a/src/test/java/net/tfminecraft/magic/GearStationLeftoverDisplayTest.java b/src/test/java/net/tfminecraft/magic/GearStationLeftoverDisplayTest.java new file mode 100644 index 0000000..feab478 --- /dev/null +++ b/src/test/java/net/tfminecraft/magic/GearStationLeftoverDisplayTest.java @@ -0,0 +1,193 @@ +package net.tfminecraft.magic; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; +import java.util.logging.*; +import net.tfminecraft.magic.gear.*; +import org.bukkit.*; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.persistence.PersistentDataType; +import org.junit.jupiter.api.*; + +/** Station displays are settled once a chunk's entities have loaded. */ +class GearStationLeftoverDisplayTest extends GearStationCoverageSupport { + final List logged = new ArrayList<>(); + Handler handler; + + @BeforeEach + void captureLog() { + handler = + new Handler() { + @Override + public void publish(LogRecord record) { + logged.add(record.getMessage()); + } + + @Override + public void flush() {} + + @Override + public void close() {} + }; + Magic.plugin.getLogger().addHandler(handler); + } + + @AfterEach + void releaseLog() { + Magic.plugin.getLogger().removeHandler(handler); + } + + static ItemStack gear() { + var weapon = item(); + tag(weapon, GearKeys.archetype(), PersistentDataType.STRING, "staff"); + return weapon; + } + + ItemDisplay display(Location at, ItemStack item, String stationTag) { + var display = at.getWorld().spawn(at, ItemDisplay.class); + display.setItemStack(item); + if (stationTag != null) { + display + .getPersistentDataContainer() + .set(GearKeys.stationDisplay(), PersistentDataType.STRING, stationTag); + } + return display; + } + + static Location above(Location station) { + return station.clone().add(.5, 1.15, .5); + } + + @Test + void displaysOfAStationThatIsGoneAreRemovedAndOtherDisplaysStay() throws Exception { + var location = station(); + var key = GearStationStore.key(location); + var stand = location.getWorld().spawn(above(location), ArmorStand.class); + var tagged = display(above(location), item(), key); + var legacy = display(above(location), gear(), null); + var pedestal = display(above(location), gear(), null); + pedestal + .getPersistentDataContainer() + .set(new NamespacedKey("interactiblefurniture", "furniture_display"), PersistentDataType.STRING, "x"); + var plain = display(above(location), item(), null); + var offset = display(location.clone().add(.45, 1.87, .45), gear(), null); + + GearStationStore.reconcile(location.getChunk()); + + assertFalse(tagged.isValid()); + assertFalse(legacy.isValid()); + assertTrue(stand.isValid()); + assertTrue(pedestal.isValid(), "another plugin's display is left alone"); + assertTrue(plain.isValid(), "not a mage weapon"); + assertTrue(offset.isValid(), "not at a station's display spot"); + assertTrue( + logged.contains("[Magic] Removed 2 leftover displays at gear station " + key + " (no station there)."), + logged.toString()); + } + + @Test + void aStationKeepsItsSavedDisplayAndLosesExtraCopies() throws Exception { + var location = station(); + var key = GearStationStore.key(location); + var occupancy = seed(location, item(), null, null); + var first = (ItemDisplay) Bukkit.getEntity(displayId(occupancy)); + var copy = display(above(location), item(), key); + var legacy = display(above(location), gear(), null); + var saved = display(above(location), item(), key); + setDisplayId(occupancy, saved.getUniqueId()); + + GearStationStore.reconcile(location.getChunk()); + + assertTrue(saved.isValid()); + assertFalse(first.isValid()); + assertFalse(copy.isValid()); + assertFalse(legacy.isValid()); + assertEquals(saved.getUniqueId(), displayId(occupancy)); + assertTrue(logged.contains("[Magic] Removed 3 extra displays at gear station " + key + "."), logged.toString()); + assertTrue(logged.stream().noneMatch(line -> line.contains("leftover")), logged.toString()); + } + + @Test + void aStationWithoutItsDisplayAdoptsAnOlderUntaggedOne() throws Exception { + var location = station(); + var key = GearStationStore.key(location); + var occupancy = seed(location, item(), null, null); + location.getWorld().getEntitiesByClass(ItemDisplay.class).forEach(Entity::remove); + var legacy = display(above(location), gear(), null); + + GearStationStore.reconcile(location.getChunk()); + + assertTrue(legacy.isValid()); + assertEquals(legacy.getUniqueId(), displayId(occupancy)); + assertEquals( + key, legacy.getPersistentDataContainer().get(GearKeys.stationDisplay(), PersistentDataType.STRING)); + assertEquals(occupancy.getItem(), legacy.getItemStack()); + assertTrue(logged.isEmpty(), logged.toString()); + assertTrue( + java.nio.file.Files.readString(temp.resolve("data/gear-stations.yml")) + .contains(legacy.getUniqueId().toString()), + "the adopted display is saved"); + } + + @Test + void aStationStillHeldInTheSavedFileKeepsItsDisplay() throws Exception { + var location = station(); + seed(location, item(), null, null); + occupied().clear(); // row not loaded (held, failed to load, or before startup load) + var display = + location.getWorld().getEntitiesByClass(ItemDisplay.class).stream() + .filter(Entity::isValid) + .findFirst() + .orElseThrow(); + + GearStationStore.reconcile(location.getChunk()); + + assertTrue(display.isValid()); + assertTrue(logged.isEmpty(), logged.toString()); + } + + @Test + void anUnreadableStoreRemovesNothing() throws Exception { + var location = station(); + var tagged = display(above(location), item(), GearStationStore.key(location)); + var file = temp.resolve("data/gear-stations.yml"); + java.nio.file.Files.createDirectories(file.getParent()); + java.nio.file.Files.writeString(file, "stations: [broken"); + + GearStationStore.reconcile(location.getChunk()); + + assertTrue(tagged.isValid()); + assertTrue(logged.stream().noneMatch(line -> line.contains("Removed")), logged.toString()); + } + + @Test + void anOldUntaggedDisplayIsFoundAtAHeightWhereFlooringWouldMissIt() throws Exception { + var location = station().clone(); + location.setY(15); + var legacy = display(above(location), gear(), null); + + GearStationStore.reconcile(location.getChunk()); + + assertFalse(legacy.isValid()); + assertTrue( + logged.contains( + "[Magic] Removed 1 leftover displays at gear station " + + GearStationStore.key(location) + + " (no station there)."), + logged.toString()); + } + + static UUID displayId(GearStationStore.Occupancy occupancy) throws Exception { + var field = GearStationStore.Occupancy.class.getDeclaredField("displayId"); + field.setAccessible(true); + return (UUID) field.get(occupancy); + } + + static void setDisplayId(GearStationStore.Occupancy occupancy, UUID id) throws Exception { + var field = GearStationStore.Occupancy.class.getDeclaredField("displayId"); + field.setAccessible(true); + field.set(occupancy, id); + } +} diff --git a/src/test/java/net/tfminecraft/magic/GearStationListenerCoverageTest.java b/src/test/java/net/tfminecraft/magic/GearStationListenerCoverageTest.java index 36d72eb..a844c46 100644 --- a/src/test/java/net/tfminecraft/magic/GearStationListenerCoverageTest.java +++ b/src/test/java/net/tfminecraft/magic/GearStationListenerCoverageTest.java @@ -16,7 +16,7 @@ import org.bukkit.entity.*; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.event.world.EntitiesLoadEvent; import org.bukkit.inventory.*; import org.bukkit.persistence.PersistentDataType; import org.junit.jupiter.api.*; @@ -155,7 +155,7 @@ void furnitureEventsRespectStationIdOccupancyAndRecentAbortGuard() throws Except listener.onFurnitureBreak(guarded); verify(guarded).setCancelled(true); assertFalse(aborts().containsKey("world,5,2,3")); - listener.onChunkLoad(new ChunkLoadEvent(loc.getChunk(), false)); + listener.onEntitiesLoad(new EntitiesLoadEvent(loc.getChunk(), java.util.List.of())); } @Test diff --git a/src/test/java/net/tfminecraft/magic/GearStationStoreCoverageTest.java b/src/test/java/net/tfminecraft/magic/GearStationStoreCoverageTest.java index c60f4d9..9aa7b3d 100644 --- a/src/test/java/net/tfminecraft/magic/GearStationStoreCoverageTest.java +++ b/src/test/java/net/tfminecraft/magic/GearStationStoreCoverageTest.java @@ -466,6 +466,20 @@ void displayBoundaryHandlesChunkLoadFailuresAndEmptyDisplays() throws Exception GearKeys.stationDisplay(), org.bukkit.persistence.PersistentDataType.STRING, GearStationStore.key(loc)); + var saved = UUID.randomUUID(); + clearInvocations(world); + assertEquals( + saved, + invoke( + GearStationStore.class, + "ensureDisplay", + new Class[] {Location.class, ItemStack.class, UUID.class}, + loc, + item(), + saved), + "entities not loaded yet: keep the saved id, spawn nothing"); + verify(world, never()).getNearbyEntities(any(Location.class), anyDouble(), anyDouble(), anyDouble()); + when(chunk.isEntitiesLoaded()).thenReturn(true); assertEquals( display.getUniqueId(), invoke(