diff --git a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java index 0ffa8cd..d4aae5a 100644 --- a/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java +++ b/src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java @@ -4,6 +4,7 @@ import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; @@ -16,6 +17,7 @@ import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.Sound; +import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; @@ -277,15 +279,12 @@ public void run() { if (!DowsingMain.plugin.nodesReady()) return; validate(); + // Failures are handled per node and per chunk inside, so production below always runs. + holdNodeChunks(); for(Node n : nodes) { try { - if(!n.getIsActive()) continue; - if(!n.hasGuild()) continue; - // A held realm's nodes pause until it is taken on. - if(Node.held(n.getGuild())) continue; - if(n.getLoc().getChunk().isForceLoaded() == false) { - n.getLoc().getChunk().setForceLoaded(true); - } + // Switched-off and unowned nodes wait, and a held realm's nodes pause until it is taken on. + if(!producing(n)) continue; if(n.getTimeLeft() <= 0) { if(!new ItemDropper().dropItems(n)) continue; n.setTimeLeft(n.getModifiedTime()); @@ -319,6 +318,137 @@ public void run() } }.runTaskTimer(DowsingMain.plugin, 0L, 1200L); } + /** Whether a node produces this pass: switched on, owned, and not in a held realm. */ + static boolean producing(Node n) { + if(!n.getIsActive() || !n.hasGuild()) return false; + return !Node.held(n.getGuild()); + } + + /** A world chunk that holds a node. */ + record NodeChunk(World world, int x, int z) { + static NodeChunk of(Node n) { + return at(n.getLoc()); + } + static NodeChunk at(Location loc) { + if(loc == null || loc.getWorld() == null) return null; + return new NodeChunk(loc.getWorld(), loc.getBlockX() >> 4, loc.getBlockZ() >> 4); + } + boolean loaded() { return world.isChunkLoaded(x, z); } + boolean forced() { return world.isChunkForceLoaded(x, z); } + void force(boolean on) { world.setChunkForceLoaded(x, z, on); } + } + + /** The chunks the passes of this start force-loaded for producing nodes. */ + private static final Set heldChunks = new HashSet<>(); + /** Whether this start has let go of the idle node chunks an earlier start left force-loaded. */ + private static boolean startCleared = false; + + /** + * Keeps a producing node's chunk force-loaded, so it produces and its hopper runs with nobody near, + * and lets go of the chunk once no node in it produces: switched off, unowned or in a held realm. A + * removed node's chunk is let go when it breaks ({@link #releaseChunkOf}). A forced chunk never unloads + * and keeps every chunk a player loads within 13 chunks of it in memory, so an idle node's chunk must + * not stay forced. The force flag (not a plugin ticket) is kept on purpose: like before, it keeps the + * world ticking hoppers while nobody is online. It is saved with the world, so the first pass of each + * start lets go of the chunk of every idle node Dowsing loaded, including those Dowsing 3.4 and older + * never let go; spots of nodes removed before this version are not known and need a manual check. + * Later passes only touch chunks this start forced. Waits for SimpleFactions, which says who owns a node. + */ + static void holdNodeChunks() { + if(!SimpleFactionsApi.ready()) return; + Set wanted = new HashSet<>(); + Set unknown = new HashSet<>(); + Set idle = new HashSet<>(heldChunks); + boolean lookupFailed = false; + for(Node n : nodes) { + NodeChunk chunk; + try { + chunk = NodeChunk.of(n); + } catch(RuntimeException ex) { + logChunkFailure("Failed to find node " + n.getId() + "'s chunk", ex); + lookupFailed = true; + continue; + } + if(chunk == null) continue; + try { + if(producing(n)) wanted.add(chunk); + else if(!startCleared) idle.add(chunk); + } catch(RuntimeException ex) { + // Not known whether it produces: its chunk keeps what it had and is not let go. + logChunkFailure("Failed to check node " + n.getId() + " for chunk loading", ex); + unknown.add(chunk); + } + } + idle.removeAll(wanted); + idle.removeAll(unknown); + Set next = new HashSet<>(); + if(lookupFailed) { + // A node whose chunk is unknown may be in any of them: nothing is let go this pass. Held + // chunks stay tracked, and the first pass's clean-up waits for a pass that knows every chunk. + for(NodeChunk chunk : idle) { + if(heldChunks.contains(chunk)) next.add(chunk); + } + idle.clear(); + } + // On the first pass a chunk that could not be handled is tracked anyway, so a later pass can still + // let go of a flag an earlier start left on it. + boolean keepAll = !startCleared; + for(NodeChunk chunk : wanted) { + // A held chunk that could not be checked stays held, so it is still let go once idle. + if(setForced(chunk, true) || keepAll || heldChunks.contains(chunk)) next.add(chunk); + } + for(NodeChunk chunk : idle) { + // Kept when it could not be let go, so the next pass tries again. + if(!setForced(chunk, false)) next.add(chunk); + } + for(NodeChunk chunk : unknown) { + if(keepAll || heldChunks.contains(chunk)) next.add(chunk); + } + heldChunks.clear(); + heldChunks.addAll(next); + if(!lookupFailed) startCleared = true; + } + + private static void logChunkFailure(String message, RuntimeException ex) { + DowsingMain.plugin.getLogger().log(java.util.logging.Level.SEVERE, message, ex); + } + + /** Sets one chunk's force flag; a failing chunk is logged and does not stop the others. */ + private static boolean setForced(NodeChunk chunk, boolean on) { + try { + if(chunk.forced() != on) chunk.force(on); + return true; + } catch(RuntimeException ex) { + DowsingMain.plugin.getLogger().log(java.util.logging.Level.SEVERE, + "Failed to " + (on ? "hold" : "let go of") + " node chunk " + chunk.x() + ", " + chunk.z(), ex); + return false; + } + } + + /** + * Lets go of a removed node's chunk right away, unless another producing node is in it, so the saved + * force flag cannot outlive the node when the server stops before the next pass. + */ + public static void releaseChunkOf(Node removed) { + NodeChunk chunk = NodeChunk.of(removed); + if(chunk == null) return; + for(Node n : nodes) { + if(n != removed && chunk.equals(NodeChunk.of(n)) && producing(n)) return; + } + // Only a chunk Dowsing holds, or any node chunk before the first pass has cleared them; a staff + // force-load made later on an idle node's chunk is left alone. + if(!heldChunks.contains(chunk) && startCleared) return; + // Tracked until it is let go, so a failed release is tried again by the next pass. + if(setForced(chunk, false)) heldChunks.remove(chunk); + else heldChunks.add(chunk); + } + + /** Forgets what this start held and cleared, for tests. */ + static void forgetHeldChunks() { + heldChunks.clear(); + startCleared = false; + } + /** Every 30 s: resync node benefits when a node's guild or realm changed without a node event. */ public void realmCycle(){ new BukkitRunnable() @@ -376,9 +506,18 @@ public void validate() { if (!SimpleFactionsApi.ready()) return; for(int i = 0; i delivered = new HashMap<>(); + int spilled = deliverToHopper(hopper.getSnapshotInventory(), items, result, loc, delivered); + if(!hopper.update(false, false)) { + // The hopper went away in the meantime: what was meant for it goes on top instead. + for(Map.Entry entry : delivered.entrySet()) { + dropLoose(loc, items.get(entry.getKey()), entry.getValue()); + } + } if(spilled > 0) warnSpill(n, above, spilled); } else { for(Map.Entry entry : result.entrySet()) { @@ -108,7 +118,8 @@ public boolean dropItems(Node n) { * Fills the hopper with what fits and spills the rest on top of it, where the hopper * can still pull it in as it drains. Returns how many items spilled. */ - private int deliverToHopper(Inventory inventory, Map items, Map result, Location loc) { + private int deliverToHopper(Inventory inventory, Map items, Map result, Location loc, + Map deliveredByKey) { int delivered = 0; int spilled = 0; for(Map.Entry entry : result.entrySet()) { @@ -120,6 +131,7 @@ private int deliverToHopper(Inventory inventory, Map items, M } dropLoose(loc, items.get(entry.getKey()), left); delivered += entry.getValue() - left; + if(entry.getValue() > left) deliveredByKey.put(entry.getKey(), entry.getValue() - left); spilled += left; } if(delivered > 0) loc.getWorld().playSound(loc, Sound.ENTITY_ITEM_PICKUP, 0.5f, 1f); diff --git a/src/main/java/net/tfminecraft/dowsing/utils/NodeEngine.java b/src/main/java/net/tfminecraft/dowsing/utils/NodeEngine.java index ed1c53f..a11601f 100644 --- a/src/main/java/net/tfminecraft/dowsing/utils/NodeEngine.java +++ b/src/main/java/net/tfminecraft/dowsing/utils/NodeEngine.java @@ -127,7 +127,9 @@ public void takeInputs(Node n) { l.add(0,-1,0); Block block = l.getBlock(); Barrel b = (Barrel) block.getState(); - Inventory i = b.getInventory(); + // Taken from the snapshot and written back, which marks the chunk changed. Changing the live + // stacks did not, so the inputs were back in the barrel after the chunk unloaded or a restart. + Inventory i = b.getSnapshotInventory(); HashMap inputs = new HashMap<>(); for(NodeSlot slot : n.getCurrentType().getSlots()) { for(String s : slot.getActivePm().getInputs()) { @@ -148,6 +150,7 @@ public void takeInputs(Node n) { for(String key : inputs.keySet()) { take(n, key, inputs.get(key), i); } + b.update(false, false); } public void take(Node n, String path, Integer amount, Inventory i) { for(ItemStack item : i.getContents()) { diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java index 88ed2a1..6cf1b29 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerCyclesTest.java @@ -13,6 +13,7 @@ import org.bukkit.Bukkit; import org.bukkit.Location; +import org.bukkit.World; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.entity.Entity; @@ -36,6 +37,7 @@ import net.tfminecraft.dowsing.objects.NodeType; import net.tfminecraft.dowsing.utils.ItemDropper; import net.tfminecraft.dowsing.utils.NodeEngine; +import net.tfminecraft.simplefactions.api.SimpleFactionsApi; import net.tfminecraft.simplefactions.guild.Guild; import net.tfminecraft.simplefactions.managers.FactionManager; import net.tfminecraft.simplefactions.objects.Faction; @@ -159,7 +161,226 @@ void aHeldRealmsNodesPauseInsteadOfProducing() { try (Cycles cycles = new Cycles(); var droppers = mockConstruction(ItemDropper.class)) { f.manager.start(); cycles.tasks.get(1200L).run(); verify(held, never()).tickCycle(); verify(held, never()).tick(); assertTrue(droppers.constructed().isEmpty()); - verify(f.chunk, never()).setForceLoaded(true); + verify(f.world, never()).setChunkForceLoaded(0, 0, true); + } + } + + @Test + void anIdleNodesChunkIsLetGoAndForcedAgainOnceItProduces() { + Node node = f.node; NodeManager.nodes.add(node); + // Switched off before a restart: the saved force flag is let go on the first pass. + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(false); when(node.getIsActive()).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, true); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world, times(1)).setChunkForceLoaded(0, 0, true); + when(node.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world, times(2)).setChunkForceLoaded(0, 0, false); + } + + @Test + void afterTheFirstPassOnlyChunksThisStartForcedAreLetGo() { + Node idle = f.nodeAt(new Location(f.world, 40, 64, -20)); NodeManager.nodes.add(idle); + NodeManager.holdNodeChunks(); + // Forced later by someone else, such as staff: Dowsing leaves it alone. + when(f.world.isChunkForceLoaded(2, -2)).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world, never()).setChunkForceLoaded(2, -2, false); + } + + @Test + void aBrokenNodesChunkIsLetGoAtOnceUnlessAnotherProducingNodeIsInIt() { + Node producing = f.nodeAt(f.location), removed = f.nodeAt(f.location); + when(producing.getIsActive()).thenReturn(true); when(removed.getIsActive()).thenReturn(true); + Node alone = f.nodeAt(new Location(f.world, 40, 64, -20)); when(alone.getIsActive()).thenReturn(true); + NodeManager.nodes.addAll(List.of(producing, removed, alone)); + when(f.world.isChunkForceLoaded(anyInt(), anyInt())).thenReturn(true); + NodeManager.releaseChunkOf(removed); + verify(f.world, never()).setChunkForceLoaded(0, 0, false); + NodeManager.releaseChunkOf(alone); + verify(f.world).setChunkForceLoaded(2, -2, false); + NodeManager.releaseChunkOf(f.nodeAt(new Location(null, 1, 2, 3))); + } + + @Test + void heldRealmAndUnownedNodesLetTheirChunksGo() { + World other = mock(World.class); + Node held = f.nodeAt(f.location), unowned = f.nodeAt(new Location(other, 20, 64, 20)); + when(held.getIsActive()).thenReturn(true); when(f.guild.isHeld()).thenReturn(true); + when(unowned.getIsActive()).thenReturn(true); when(unowned.hasGuild()).thenReturn(false); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); when(other.isChunkForceLoaded(1, 1)).thenReturn(true); + NodeManager.nodes.addAll(List.of(held, unowned)); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); verify(other).setChunkForceLoaded(1, 1, false); + verify(f.world, never()).setChunkForceLoaded(0, 0, true); + } + + @Test + void chunkLoadingWaitsForSimpleFactionsAndSkipsNodesWithoutAWorld() { + Node noWorld = f.nodeAt(new Location(null, 1, 2, 3)), noLocation = f.nodeAt(f.location); + when(noWorld.getIsActive()).thenReturn(true); when(noLocation.getLoc()).thenReturn(null); + NodeManager.nodes.addAll(List.of(f.node, noWorld, noLocation)); + when(f.node.getIsActive()).thenReturn(true); + net.tfminecraft.dowsing.testsupport.FactionFixture.api.when(SimpleFactionsApi::ready).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world, never()).isChunkForceLoaded(anyInt(), anyInt()); + net.tfminecraft.dowsing.testsupport.FactionFixture.api.when(SimpleFactionsApi::ready).thenReturn(true); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, true); + } + + @Test + void aChunkLoadingFailureIsLoggedAndNodesStillProduce() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); when(node.getTimeLeft()).thenReturn(10); when(node.getCycleTime()).thenReturn(1); + NodeManager.nodes.add(node); + when(f.world.isChunkForceLoaded(0, 0)).thenThrow(new IllegalStateException("world gone")); + try (Cycles cycles = new Cycles()) { + f.manager.start(); cycles.tasks.get(1200L).run(); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to hold node chunk 0, 0"), any(IllegalStateException.class)); + verify(node).tick(); + } + } + + @Test + void aNodeThatCannotBeCheckedKeepsItsChunkAndTheOthersGoOn() { + Node broken = f.nodeAt(f.location), other = f.nodeAt(new Location(f.world, 40, 64, -20)); + when(broken.getIsActive()).thenReturn(true); NodeManager.nodes.add(broken); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, true); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + when(broken.hasGuild()).thenThrow(new IllegalStateException("guild lookup failed")); + when(other.getIsActive()).thenReturn(true); NodeManager.nodes.add(other); + try (Cycles cycles = new Cycles()) { + f.manager.start(); cycles.tasks.get(1200L).run(); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("for chunk loading"), any(IllegalStateException.class)); + verify(f.world).setChunkForceLoaded(2, -2, true); + verify(f.world, never()).setChunkForceLoaded(0, 0, false); + } + // A node whose location cannot be read is skipped and logged. + Node lost = f.nodeAt(f.location); when(lost.getLoc()).thenThrow(new IllegalStateException("no location")); NodeManager.nodes.add(lost); + NodeManager.holdNodeChunks(); NodeManager.nodes.remove(lost); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to find node"), any(IllegalStateException.class)); + // Still tracked: once it can be checked again and is idle, it is let go. + doReturn(true).when(broken).hasGuild(); when(broken.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + } + + @Test + void aFirstPassFailureStillLetsALaterPassClearAnOldFlag() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + when(node.hasGuild()).thenThrow(new IllegalStateException("guild lookup failed")); + NodeManager.holdNodeChunks(); + verify(f.world, never()).setChunkForceLoaded(0, 0, false); + doReturn(true).when(node).hasGuild(); when(node.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + } + + @Test + void noHeldChunkIsLetGoInAPassWhereANodesLocationCannotBeRead() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + NodeManager.holdNodeChunks(); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + when(node.getLoc()).thenThrow(new IllegalStateException("no location")); + NodeManager.holdNodeChunks(); + verify(f.world, never()).setChunkForceLoaded(0, 0, false); + // Still tracked: once the location reads again and the node is idle, it is let go. + doReturn(f.location).when(node).getLoc(); when(node.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + } + + @Test + void aFirstPassWithAnUnreadableLocationLetsNothingGoAndCleansUpLater() { + Node producing = f.nodeAt(f.location), idle = f.nodeAt(f.location); + when(producing.getIsActive()).thenReturn(true); + when(producing.getLoc()).thenThrow(new IllegalStateException("no location")); + NodeManager.nodes.addAll(List.of(producing, idle)); + when(f.world.isChunkForceLoaded(0, 0)).thenReturn(true); + // The idle node shares the chunk of the node whose location cannot be read: not let go. + NodeManager.holdNodeChunks(); + verify(f.world, never()).setChunkForceLoaded(0, 0, false); + // The first-pass clean-up still runs once every location reads. + doReturn(f.location).when(producing).getLoc(); when(producing.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + } + + @Test + void aNodeThatFailsValidationDoesNotStopTheOthers() { + Node lost = f.nodeAt(f.location), invalid = f.nodeAt(f.location); + when(lost.getLoc()).thenThrow(new IllegalStateException("no location")); + NodeManager.nodes.addAll(List.of(lost, invalid)); + when(f.worldBlock.getType()).thenReturn(Material.AIR); + f.manager.validate(); + verify(invalid).breakNode(); assertFalse(NodeManager.nodes.contains(invalid)); assertTrue(NodeManager.nodes.contains(lost)); + verify(f.logger).log(eq(java.util.logging.Level.SEVERE), contains("Failed to validate node"), any(IllegalStateException.class)); + } + + @Test + void aHeldChunkWhoseCheckFailsStaysTrackedAndIsLetGoLater() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + NodeManager.holdNodeChunks(); + when(f.world.isChunkForceLoaded(0, 0)).thenThrow(new IllegalStateException("bad chunk")); + NodeManager.holdNodeChunks(); + doReturn(true).when(f.world).isChunkForceLoaded(0, 0); when(node.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + } + + @Test + void aFailedReleaseOfABrokenNodesChunkIsRetriedByTheNextPass() { + Node node = f.node; when(node.getIsActive()).thenReturn(true); NodeManager.nodes.add(node); + NodeManager.holdNodeChunks(); + when(f.world.isChunkForceLoaded(0, 0)).thenThrow(new IllegalStateException("bad chunk")); + NodeManager.releaseChunkOf(node); NodeManager.nodes.remove(node); + doReturn(true).when(f.world).isChunkForceLoaded(0, 0); + NodeManager.holdNodeChunks(); + verify(f.world).setChunkForceLoaded(0, 0, false); + } + + @Test + void aChunkThatFailsIsRetriedAndDoesNotStopTheOthers() { + Node first = f.nodeAt(f.location), second = f.nodeAt(new Location(f.world, 40, 64, -20)); + when(first.getIsActive()).thenReturn(true); when(second.getIsActive()).thenReturn(true); + NodeManager.nodes.addAll(List.of(first, second)); + when(f.world.isChunkForceLoaded(0, 0)).thenThrow(new IllegalStateException("bad chunk")); + NodeManager.holdNodeChunks(); NodeManager.holdNodeChunks(); + verify(f.world, atLeastOnce()).setChunkForceLoaded(2, -2, true); + verify(f.world, times(2)).isChunkForceLoaded(0, 0); + // A chunk that cannot be let go stays known and is tried again. + clearInvocations(f.world); + when(f.world.isChunkForceLoaded(2, -2)).thenThrow(new IllegalStateException("bad chunk")); + when(second.getIsActive()).thenReturn(false); + NodeManager.holdNodeChunks(); NodeManager.holdNodeChunks(); + verify(f.world, times(2)).isChunkForceLoaded(2, -2); + verify(f.logger, atLeastOnce()).log(eq(java.util.logging.Level.SEVERE), contains("Failed to let go of node chunk 2, -2"), any(IllegalStateException.class)); + } + + @Test + void aBrokenIdleNodeLeavesAStaffForceLoadAloneAfterTheFirstPass() { + Node idle = f.nodeAt(new Location(f.world, 40, 64, -20)); NodeManager.nodes.add(idle); + NodeManager.holdNodeChunks(); + when(f.world.isChunkForceLoaded(2, -2)).thenReturn(true); + NodeManager.releaseChunkOf(idle); + verify(f.world, never()).setChunkForceLoaded(2, -2, false); + } + + @Test + void aPassNeverLoadsAnIdleNodesChunkToValidateIt() { + Node node = f.node; NodeManager.nodes.add(node); + when(f.world.isChunkLoaded(0, 0)).thenReturn(false); + try (Cycles cycles = new Cycles()) { + f.manager.start(); cycles.tasks.get(1200L).run(); + verify(f.world, never()).getBlockAt(any(Location.class)); verify(node, never()).breakNode(); + assertTrue(NodeManager.nodes.contains(node)); } } @@ -341,7 +562,7 @@ void productionCycleCompletesRealNodeOutputThenConsumesTheNextInputBatch() { doAnswer(inv -> { node.setInputCounter(node.getInputCounter() + 1); return null; }).when(engine).takeInputs(node); })) { f.manager.start(); cycles.tasks.get(1200L).run(); - verify(f.chunk).setForceLoaded(true); verify(droppers.constructed().getFirst()).dropItems(node); + verify(f.world).setChunkForceLoaded(0, 0, true); verify(droppers.constructed().getFirst()).dropItems(node); assertEquals(29, node.getTimeLeft()); assertEquals(0, node.getCycleTime()); assertEquals(1, node.getInputCounter()); verify(engines.constructed().getFirst()).takeInputs(node); assertTrue(node.getIsActive()); } @@ -411,8 +632,8 @@ void failedOutputKeepsTheCyclePendingAndExceptionsDoNotStopOtherNodes() { @Test void inputFailureStopsTickingAndSuccessfulTicksUpdateMatchingOpenMenusOnly() { - Node node = f.node; when(node.getIsActive()).thenReturn(true, false); when(node.getTimeLeft()).thenReturn(10); - when(node.getCycleTime()).thenReturn(60); NodeManager.nodes.add(node); when(f.chunk.isForceLoaded()).thenReturn(true); + Node node = f.node; when(node.getIsActive()).thenReturn(true, true, false); when(node.getTimeLeft()).thenReturn(10); + when(node.getCycleTime()).thenReturn(60); NodeManager.nodes.add(node); try (Cycles cycles = new Cycles()) { f.manager.start(); cycles.tasks.get(1200L).run(); verify(node).input(); verify(node, never()).tick(); when(node.getIsActive()).thenReturn(true); when(node.getCycleTime()).thenReturn(1); diff --git a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java index 487a829..8aa59f2 100644 --- a/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java +++ b/src/test/java/net/tfminecraft/dowsing/managers/NodeManagerEventsTest.java @@ -525,7 +525,7 @@ static final class Fixture implements AutoCloseable { return true; }); when(DowsingMain.plugin.getName()).thenReturn("Dowsing"); when(DowsingMain.plugin.isEnabled()).thenReturn(true); - NodeManager.nodes = new ArrayList<>(); NodeManager.extraCapacityByGuild = new HashMap<>(); + NodeManager.nodes = new ArrayList<>(); NodeManager.extraCapacityByGuild = new HashMap<>(); NodeManager.forgetHeldChunks(); Cache.extraCapacity = false; Cache.naturalYieldEnabled = false; Cache.cycleLength = 60; Cache.membersPerCapacity = 2; Cache.maxMemberCapacity = 5; Cache.minMembersForNode = 1; Cache.efficiencyLossPM = 5; Cache.efficiencyLossType = 40; Cache.refundPercentage = 0.8; @@ -533,7 +533,7 @@ static final class Fixture implements AutoCloseable { when(guild.getId()).thenReturn("guild"); when(guild.getLeader()).thenReturn("Leader"); when(guild.getMembers()).thenReturn(List.of("Leader", "Member")); when(guild.getBank()).thenReturn(bank); when(bank.getWealth()).thenReturn(1000.0); when(player.getName()).thenReturn("Leader"); when(player.getLocation()).thenReturn(location); - when(world.getChunkAt(any(Location.class))).thenReturn(chunk); + when(world.getChunkAt(any(Location.class))).thenReturn(chunk); when(world.isChunkLoaded(anyInt(), anyInt())).thenReturn(true); when(world.getBlockAt(anyInt(), anyInt(), anyInt())).thenReturn(worldBlock); when(world.getBlockAt(any(Location.class))).thenReturn(worldBlock); when(worldBlock.getLocation()).thenReturn(location); when(worldBlock.getWorld()).thenReturn(world); when(worldBlock.getType()).thenReturn(Material.BARRIER); Biome biome = mock(Biome.class); when(biome.toString()).thenReturn("PLAINS"); when(worldBlock.getBiome()).thenReturn(biome); @@ -589,7 +589,7 @@ ItemStack item(String label) { } @Override public void close() throws Exception { inventories.close(); toggles.close(); types.close(); methods.close(); blocks.close(); factions.close(); MockBukkit.unmock(); - DowsingMain.plugin = previousPlugin; NodeManager.nodes = previousNodes; NodeManager.extraCapacityByGuild = previousCapacity; + DowsingMain.plugin = previousPlugin; NodeManager.nodes = previousNodes; NodeManager.extraCapacityByGuild = previousCapacity; NodeManager.forgetHeldChunks(); net.tfminecraft.simplefactions.Cache.maxExtraNodeCapacity = previousMaxCapacity; for (var entry : previousCache.entrySet()) entry.getKey().set(null, entry.getValue()); } diff --git a/src/test/java/net/tfminecraft/dowsing/objects/NodeProductionTest.java b/src/test/java/net/tfminecraft/dowsing/objects/NodeProductionTest.java index 843b71d..7a91c91 100644 --- a/src/test/java/net/tfminecraft/dowsing/objects/NodeProductionTest.java +++ b/src/test/java/net/tfminecraft/dowsing/objects/NodeProductionTest.java @@ -210,6 +210,19 @@ void breakingAVanillaNodeClearsTheBlockAndReturnsItsItemAtTheBlockCenter() { } } + @Test + void breakingANodeStillReturnsItsItemWhenLettingGoOfItsChunkFails() { + Node node = f.node(); + Node neighbour = mock(Node.class); when(neighbour.getLoc()).thenReturn(f.location); + when(neighbour.getIsActive()).thenThrow(new IllegalStateException("guild lookup failed")); + net.tfminecraft.dowsing.managers.NodeManager.nodes.add(neighbour); + try (var droppers = mockConstruction(ItemDropper.class)) { + assertDoesNotThrow(node::breakNode); + verify(f.worldBlock).setType(Material.AIR); + verify(droppers.constructed().getFirst()).dropItem(new Location(f.world, 2.5, 64, 3.5), "v.IRON_BLOCK", false); + } + } + @Test void breakingANodeReturnsItsHeldOutputItemsOnlyOnce() { Node node = f.node(); node.setPendingResult(Map.of("v.STONE", 2)); diff --git a/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java b/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java index 50e9d97..92286fe 100644 --- a/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java +++ b/src/test/java/net/tfminecraft/dowsing/utils/ItemDropperTest.java @@ -165,6 +165,8 @@ void outputGoesToTheHopperAboveTheNodeInsteadOfTheGround() { assertTrue(new ItemDropper(path -> template, message -> fail(message)).dropItems(node)); verify(delivered).setAmount(3); verify(inventory).addItem(delivered); + // Written back through the snapshot so the chunk is saved with the output in it. + verify(lastHopper).update(false, false); verify(lastHopper, never()).getInventory(); verify(world, never()).dropItem(any(Location.class), any(ItemStack.class)); verify(world).playSound(new Location(world, 4.5, 62, 7.5), Sound.ENTITY_ITEM_PICKUP, 0.5f, 1f); verify(node).setLastResult(Map.of("v.STONE", 3)); verify(node).update(); @@ -289,6 +291,24 @@ void pendingAmountsAboveOneStackAreDeliveredAsOneTransaction() { verify(node).setPendingResult(null); verify(node).setLastResult(Map.of("v.STONE", 130)); } + @Test + void outputMeantForAHopperThatWentAwayIsDroppedOnTopInstead() { + World world = mock(World.class); + Node node = nodeAt(new Location(world, 4, 60, 7), Map.of("v.STONE", 1.0), 3); + Inventory inventory = hopperAbove(world); + when(inventory.addItem(any(ItemStack.class))).thenReturn(new HashMap<>()); + when(lastHopper.update(false, false)).thenReturn(false); + ItemStack template = mock(ItemStack.class); when(template.getMaxStackSize()).thenReturn(64); + ItemStack delivered = mock(ItemStack.class); when(template.clone()).thenReturn(delivered); + Item dropped = mock(Item.class); when(world.dropItem(any(Location.class), any(ItemStack.class))).thenReturn(dropped); + assertTrue(new ItemDropper(path -> template, message -> fail(message)).dropItems(node)); + verify(world).dropItem(new Location(world, 4.5, 62, 7.5), delivered); + verify(delivered, atLeastOnce()).setAmount(3); + verify(node).setLastResult(Map.of("v.STONE", 3)); + } + + private Hopper lastHopper; + private Inventory hopperAbove(World world) { Block block = mock(Block.class); Hopper hopper = mock(Hopper.class); @@ -297,7 +317,9 @@ private Inventory hopperAbove(World world) { when(block.getType()).thenReturn(Material.HOPPER); when(block.getState()).thenReturn(hopper); when(block.getX()).thenReturn(4); when(block.getY()).thenReturn(61); when(block.getZ()).thenReturn(7); - when(hopper.getInventory()).thenReturn(inventory); + when(hopper.getSnapshotInventory()).thenReturn(inventory); + when(hopper.update(false, false)).thenReturn(true); + lastHopper = hopper; return inventory; } diff --git a/src/test/java/net/tfminecraft/dowsing/utils/NodeEngineTest.java b/src/test/java/net/tfminecraft/dowsing/utils/NodeEngineTest.java index dfa4a3f..05283af 100644 --- a/src/test/java/net/tfminecraft/dowsing/utils/NodeEngineTest.java +++ b/src/test/java/net/tfminecraft/dowsing/utils/NodeEngineTest.java @@ -39,6 +39,7 @@ class NodeEngineTest { World world; Block below, above; Inventory inventory; + Barrel barrel; AtomicInteger inputs; @BeforeEach void setUp() { @@ -49,7 +50,7 @@ class NodeEngineTest { when(node.getMultiplier()).thenReturn(2); inputs = new AtomicInteger(2); when(node.getInputCounter()).thenAnswer(inv -> inputs.get()); doAnswer(inv -> { inputs.set(inv.getArgument(0)); return null; }).when(node).setInputCounter(anyInt()); when(world.getBlockAt(any(Location.class))).thenAnswer(inv -> ((Location) inv.getArgument(0)).getBlockY() == 63 ? below : above); - when(below.getType()).thenReturn(Material.BARREL); when(below.getState()).thenReturn(barrel); when(barrel.getInventory()).thenReturn(inventory); + when(below.getType()).thenReturn(Material.BARREL); when(below.getState()).thenReturn(barrel); when(barrel.getInventory()).thenReturn(inventory); when(barrel.getSnapshotInventory()).thenReturn(inventory); this.barrel = barrel; when(above.getType()).thenReturn(Material.HOPPER); tlibs = mockStatic(TLibs.class); ItemAPI api = mock(ItemAPI.class); ItemChecker checker = mock(ItemChecker.class); tlibs.when(TLibs::getItemAPI).thenReturn(api); when(api.getChecker()).thenReturn(checker); @@ -89,6 +90,8 @@ void takingInputsConsumesExactlyOneAggregatedBatchAndLeavesUnrelatedItems() { inventory.setItem(2, new ItemStack(Material.COAL, 3)); inventory.setItem(3, new ItemStack(Material.DIAMOND, 4)); engine.takeInputs(node); assertEquals(3, inputs.get()); assertEquals(3, count(Material.STONE)); assertEquals(1, count(Material.COAL)); assertEquals(4, count(Material.DIAMOND)); + // Taken from the snapshot and written back, so the chunk is saved without the inputs. + verify(barrel).getSnapshotInventory(); verify(barrel).update(false, false); engine.take(node, "v.EMERALD", 1, inventory); assertEquals(4, count(Material.DIAMOND)); engine.take(node, "v.STONE", 100, inventory); assertEquals(0, count(Material.STONE)); }