Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/main/java/net/tfminecraft/dowsing/Cache.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,17 @@ public class Cache {

public static double efficiencyLossType;
public static double efficiencyLossPM;

/** Producing nodes' chunks are loaded only around drops and inputs; false keeps them loaded all the time. */
public static boolean timedNodeChunks = true;
/** Minutes before a drop that a node's chunk starts loading in the background. */
public static int nodeChunkLeadMinutes = 1;
/** Minutes before an input that a node's chunk is loaded, so hoppers can fill the barrel first. */
public static int nodeChunkInputLeadMinutes = 5;
/** Minutes a node's chunk stays loaded after a drop or an input, so hoppers can move the output. */
public static int nodeChunkDrainMinutes = 5;
/** How often the drain window is extended while the node's hopper still holds items. */
public static int nodeChunkMaxExtensions = 3;
/** Chunks kept force-loaded all the time ("world x z" in block coordinates), so a world keeps ticking. */
public static java.util.List<String> keepActiveChunks = java.util.List.of();
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,12 @@ public void loadConfig(File configFile) {
Cache.maxEfficiencyPerMember = config.getDouble("max-efficiency-per-member", 25.0);
Cache.efficiencyLossType = config.getDouble("efficiency-loss-type", 40.0);
Cache.efficiencyLossPM = config.getDouble("efficiency-loss-pm", 5.0);

Cache.timedNodeChunks = !"always".equalsIgnoreCase(config.getString("node-chunks.mode", "timed"));
Cache.nodeChunkLeadMinutes = Math.max(0, config.getInt("node-chunks.lead-minutes", 1));
Cache.nodeChunkInputLeadMinutes = Math.max(0, config.getInt("node-chunks.input-lead-minutes", 5));
Cache.nodeChunkDrainMinutes = Math.max(1, config.getInt("node-chunks.drain-minutes", 5));
Cache.nodeChunkMaxExtensions = Math.max(0, config.getInt("node-chunks.max-drain-extensions", 3));
Cache.keepActiveChunks = java.util.List.copyOf(config.getStringList("node-chunks.keep-active"));
}
}
146 changes: 142 additions & 4 deletions src/main/java/net/tfminecraft/dowsing/managers/NodeManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -289,11 +289,13 @@ public void run()
if(!new ItemDropper().dropItems(n)) continue;
n.setTimeLeft(n.getModifiedTime());
n.setInputCounter(0);
startDrain(n);
}
n.tickCycle();
if(n.getCycleTime().equals(Cache.cycleLength)) {
n.setCycleTime(0);
n.input();
startDrain(n);
}
if(!n.getIsActive()) continue;
n.tick();
Expand Down Expand Up @@ -344,8 +346,12 @@ static NodeChunk at(Location loc) {
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
* Keeps a producing node's chunk force-loaded while it works, so it produces and its hopper runs with
* nobody near. With timed chunks (the default) that is only around its drops and inputs: the chunk loads
* in the background a little before, and stays for the drain time after (longer while the node's hopper
* still holds items); "always" keeps it the whole time. Configured keep-active chunks stay forced so their
* world keeps ticking while nobody is online. Lets go of the chunk once no node in it needs it: switched
* off, unowned, in a held realm, or between a timed node's events. 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
Expand All @@ -356,9 +362,23 @@ static NodeChunk at(Location loc) {
*/
static void holdNodeChunks() {
if(!SimpleFactionsApi.ready()) return;
advanceDrains();
if(!startCleared) {
// Drain windows do not survive a restart: every producing node gets one on the first pass, so
// output a restart left in its hopper is still moved (and the window extends while it is not).
for(Node n : nodes) {
try {
if(producing(n)) startDrain(n);
} catch(RuntimeException ex) {
// Handled like any node that cannot be checked, in the loop below.
}
}
}
Set<NodeChunk> wanted = new HashSet<>();
Set<NodeChunk> soon = new HashSet<>();
Set<NodeChunk> unknown = new HashSet<>();
Set<NodeChunk> idle = new HashSet<>(heldChunks);
wanted.addAll(keepActiveChunks());
boolean lookupFailed = false;
for(Node n : nodes) {
NodeChunk chunk;
Expand All @@ -371,16 +391,23 @@ static void holdNodeChunks() {
}
if(chunk == null) continue;
try {
if(producing(n)) wanted.add(chunk);
// With timed chunks a producing node needs its chunk only around a drop or an input.
if(producing(n) && needsChunkNow(n)) wanted.add(chunk);
else if(producing(n) && needsChunkSoon(n)) soon.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);
}
}
soon.removeAll(wanted);
idle.removeAll(wanted);
idle.removeAll(soon);
idle.removeAll(unknown);
upcoming.clear();
upcoming.addAll(wanted);
upcoming.addAll(soon);
Set<NodeChunk> next = new HashSet<>();
if(lookupFailed) {
// A node whose chunk is unknown may be in any of them: nothing is let go this pass. Held
Expand All @@ -397,6 +424,16 @@ static void holdNodeChunks() {
// 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 : soon) {
// Loaded in the background ahead of a drop or input, so the pass never waits for the disk.
try {
if(chunk.loaded()) setForced(chunk, true);
else preload(chunk);
} catch(RuntimeException ex) {
logChunkFailure("Failed to load node chunk " + chunk.x() + ", " + chunk.z(), ex);
}
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);
Expand All @@ -409,10 +446,108 @@ static void holdNodeChunks() {
if(!lookupFailed) startCleared = true;
}

private static void logChunkFailure(String message, RuntimeException ex) {
private static void logChunkFailure(String message, Throwable ex) {
DowsingMain.plugin.getLogger().log(java.util.logging.Level.SEVERE, message, ex);
}

/** Chunks wanted or about to be wanted this pass; a background load finishing later only holds these. */
private static final Set<NodeChunk> upcoming = new HashSet<>();
/** Chunks with a background load still running. */
private static final Set<NodeChunk> loading = new HashSet<>();
/** Per node: minutes its chunk stays held after a drop or input, and the extensions used. */
private static final Map<java.util.UUID, int[]> drains = new HashMap<>();

/** True when the node drops, takes inputs or is draining this pass, or chunks are not timed. */
static boolean needsChunkNow(Node n) {
if(!Cache.timedNodeChunks) return true;
if(n.getTimeLeft() <= 0 || drains.containsKey(n.getId())) return true;
return Cache.cycleLength != null && n.getCycleTime() + 1 >= Cache.cycleLength;
}

/** True when a drop or an input comes within its lead time, so the chunk loads in the background. */
static boolean needsChunkSoon(Node n) {
if(n.getTimeLeft() <= Cache.nodeChunkLeadMinutes) return true;
return Cache.cycleLength != null && Cache.cycleLength - n.getCycleTime() <= Cache.nodeChunkInputLeadMinutes + 1;
}

/** Keeps a node's chunk held for the drain time after it dropped items or took inputs. */
static void startDrain(Node n) {
if(Cache.timedNodeChunks) drains.put(n.getId(), new int[] {Cache.nodeChunkDrainMinutes, 0});
}

/**
* Counts down each node's drain time, once per pass. When it runs out while the node's hopper still
* holds items it is extended, up to the configured number of times; removed nodes are forgotten.
*/
static void advanceDrains() {
Set<java.util.UUID> present = new HashSet<>();
Map<java.util.UUID, Node> byId = new HashMap<>();
for(Node n : nodes) {
present.add(n.getId());
byId.put(n.getId(), n);
}
drains.keySet().retainAll(present);
java.util.Iterator<Map.Entry<java.util.UUID, int[]>> it = drains.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<java.util.UUID, int[]> e = it.next();
int[] d = e.getValue();
if(--d[0] > 0) continue;
if(d[1] < Cache.nodeChunkMaxExtensions && hopperHoldsItems(byId.get(e.getKey()))) {
d[0] = Cache.nodeChunkDrainMinutes;
d[1]++;
} else {
it.remove();
}
}
}

/** Whether the hopper on top of the node still holds items; false when its chunk is not loaded. */
static boolean hopperHoldsItems(Node n) {
try {
NodeChunk chunk = NodeChunk.of(n);
if(chunk == null || !chunk.loaded()) return false;
Block block = n.getLoc().clone().add(0, 1, 0).getBlock();
if(block.getType() != Material.HOPPER) return false;
return !((org.bukkit.block.Hopper) block.getState(false)).getInventory().isEmpty();
} catch(RuntimeException ex) {
logChunkFailure("Failed to check node " + n.getId() + "'s hopper", ex);
return false;
}
}

/** Loads a chunk without blocking the server thread and holds it once loaded, if still needed then. */
static void preload(NodeChunk chunk) {
if(!loading.add(chunk)) return;
try {
chunk.world().getChunkAtAsync(chunk.x(), chunk.z()).whenComplete((loaded, ex) ->
Bukkit.getScheduler().runTask(DowsingMain.plugin, () -> {
loading.remove(chunk);
if(ex != null) logChunkFailure("Failed to load node chunk " + chunk.x() + ", " + chunk.z(), ex);
// Not held when no node needs it any more, or a removed node's chunk was let go meanwhile.
else if(upcoming.contains(chunk) && heldChunks.contains(chunk)) setForced(chunk, true);
}));
} catch(RuntimeException ex) {
loading.remove(chunk);
logChunkFailure("Failed to load node chunk " + chunk.x() + ", " + chunk.z(), ex);
}
}

/** The configured always-loaded chunks whose world exists; a malformed entry is skipped. */
static Set<NodeChunk> keepActiveChunks() {
Set<NodeChunk> chunks = new HashSet<>();
for(String entry : Cache.keepActiveChunks) {
String[] p = entry.trim().split("\\s+");
World w = p.length == 3 ? Bukkit.getWorld(p[0]) : null;
if(w == null) continue;
try {
chunks.add(new NodeChunk(w, Integer.parseInt(p[1]) >> 4, Integer.parseInt(p[2]) >> 4));
} catch(NumberFormatException ex) {
// Skipped like an unknown world.
}
}
return chunks;
}

/** 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 {
Expand Down Expand Up @@ -447,6 +582,9 @@ public static void releaseChunkOf(Node removed) {
static void forgetHeldChunks() {
heldChunks.clear();
startCleared = false;
upcoming.clear();
loading.clear();
drains.clear();
}

/** Every 30 s: resync node benefits when a node's guild or realm changed without a node event. */
Expand Down
19 changes: 18 additions & 1 deletion src/main/resources/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,21 @@ min-members-for-node: 1
efficiency-growth-per-member: 0.1
max-efficiency-per-member: 25.0
efficiency-loss-type: 40.0
efficiency-loss-pm: 0.0
efficiency-loss-pm: 0.0

# How a producing node's chunk is kept loaded.
# timed: only around its drops and inputs. It loads in the background lead-minutes before a drop
# (input-lead-minutes before an input, so hoppers can fill the barrel), and stays drain-minutes
# after, extended up to max-drain-extensions times while the node's hopper still holds items.
# always: every producing node's chunk stays loaded (Dowsing 3.4 behaviour). A loaded chunk keeps every
# chunk a player loads within 13 chunks of it in memory until the restart.
node-chunks:
mode: timed
lead-minutes: 1
input-lead-minutes: 5
drain-minutes: 5
max-drain-extensions: 3
# Chunks kept force-loaded all the time, "world x z" in block coordinates, so the world keeps ticking
# while nobody is online (pick a spot no player goes). After removing an entry, unload it with
# /forceload remove.
keep-active: []
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,21 @@ void configurationLoadsAllRuntimeSettings() throws Exception {
assertEquals(0.6, Cache.refundPercentage); assertEquals(4, Cache.minMembersForNode);
assertEquals(0.2, Cache.efficiencyGrowthPerMember); assertEquals(30, Cache.maxEfficiencyPerMember);
assertEquals(25, Cache.efficiencyLossType); assertEquals(3, Cache.efficiencyLossPM);
assertTrue(Cache.timedNodeChunks); assertEquals(1, Cache.nodeChunkLeadMinutes);
assertEquals(5, Cache.nodeChunkInputLeadMinutes); assertEquals(5, Cache.nodeChunkDrainMinutes);
assertEquals(3, Cache.nodeChunkMaxExtensions); assertTrue(Cache.keepActiveChunks.isEmpty());
new ConfigLoader().loadConfig(file("chunks.yml", """
node-chunks:
mode: ALWAYS
lead-minutes: -2
input-lead-minutes: 8
drain-minutes: 0
max-drain-extensions: -1
keep-active: ["TFMC_Map 6000 6000"]
"""));
assertFalse(Cache.timedNodeChunks); assertEquals(0, Cache.nodeChunkLeadMinutes);
assertEquals(8, Cache.nodeChunkInputLeadMinutes); assertEquals(1, Cache.nodeChunkDrainMinutes);
assertEquals(0, Cache.nodeChunkMaxExtensions); assertEquals(List.of("TFMC_Map 6000 6000"), Cache.keepActiveChunks);
}

@Test
Expand Down
Loading