BlueGit

timfa containerpipes

Files

containerpipes / src / main / java / nl / timfalken / containerpipes / CrafterPipeManager.java

CrafterPipeManager.java

CrafterPipeManager.java 36.4 KiB Download Raw
1package nl.timfalken.containerpipes;
2
3import org.bukkit.Bukkit;
4import org.bukkit.Material;
5import org.bukkit.World;
6import org.bukkit.block.Block;
7import org.bukkit.block.BlockFace;
8import org.bukkit.block.BlockState;
9import org.bukkit.block.Crafter;
10import org.bukkit.event.EventHandler;
11import org.bukkit.event.EventPriority;
12import org.bukkit.event.Listener;
13import org.bukkit.event.block.CrafterCraftEvent;
14import org.bukkit.inventory.Inventory;
15import org.bukkit.inventory.ItemStack;
16import org.bukkit.plugin.Plugin;
17
18import java.lang.reflect.Field;
19import java.lang.reflect.Method;
20import java.util.*;
21
22/**
23 * Crafter output pipes use a 3x3 recipe grid. Incoming pipes are slaved and
24 * supply those exact ingredients; the vanilla crafter is then told to craft.
25 * No recipe lookup or result preview — if the layout is wrong, the crafter
26 * fails and this network sleeps until an inventory/craft event wakes it.
27 */
28public final class CrafterPipeManager implements Listener {
29 private CrafterPipeManager() {}
30
31 private static Plugin plugin;
32 private static final Map<CrafterPos, Network> networks = new HashMap<>();
33 private static final Map<Long, Network> outgoingIndex = new HashMap<>();
34 private static final Map<CrafterPos, Integer> appliedSlotMask = new HashMap<>();
35 private static final Set<Long> slavedIncomingIds = new HashSet<>();
36 private static final Set<Long> craftingGridIds = new HashSet<>();
37 private static final Map<String, Method> methodCache = new HashMap<>();
38 private static boolean applying;
39 private static boolean dirty;
40 private static boolean scheduled;
41 private static boolean needsRetry;
42 private static int orchestratorCount;
43 private static Network running;
44 private static int idleAfter = 3;
45 private static int sleepProbe = 200;
46
47 record CrafterPos(UUID world, int x, int y, int z) {
48 static CrafterPos of(Block block) {
49 return new CrafterPos(block.getWorld().getUID(), block.getX(), block.getY(), block.getZ());
50 }
51 }
52
53 static final class PipeRef {
54 final long id;
55 final Object raw;
56 final Block sourceBlock;
57 final Block destBlock;
58
59 PipeRef(long id, Object raw, Block sourceBlock, Block destBlock) {
60 this.id = id;
61 this.raw = raw;
62 this.sourceBlock = sourceBlock;
63 this.destBlock = destBlock;
64 }
65 }
66
67 static final class SourceCache {
68 final Block block;
69 final List<PipeRef> pipes = new ArrayList<>();
70 ItemStack[] contents;
71 boolean dirty = true;
72
73 SourceCache(Block block) { this.block = block; }
74
75 void refresh() {
76 if (!dirty && contents != null) return;
77 World world = block.getWorld();
78 if (world == null || !world.isChunkLoaded(block.getX() >> 4, block.getZ() >> 4)) {
79 contents = new ItemStack[0];
80 dirty = false;
81 return;
82 }
83 Inventory inventory = HopperStyleEndpoints.inventoryOf(block);
84 contents = inventory == null ? new ItemStack[0] : cloneContents(inventory.getStorageContents());
85 dirty = false;
86 }
87
88 Inventory liveInventory() {
89 World world = block.getWorld();
90 if (world == null || !world.isChunkLoaded(block.getX() >> 4, block.getZ() >> 4)) return null;
91 return HopperStyleEndpoints.inventoryOf(block);
92 }
93 }
94
95 static final class Network {
96 final CrafterPos pos;
97 PipeRef outgoing;
98 PipeRef orchestrator;
99 final List<PipeRef> incoming = new ArrayList<>();
100 final List<SourceCache> sources = new ArrayList<>();
101 final ItemStack[] recipe = new ItemStack[9];
102 int recipeMask;
103 ItemStack[] crafterCache;
104 boolean crafterDirty = true;
105 boolean sleeping;
106 int failed;
107 int sleepUntil;
108 boolean attemptingCraft;
109 boolean craftSucceeded;
110
111 Network(CrafterPos pos) { this.pos = pos; }
112
113 void setRecipe(List<ItemStack> filters) {
114 recipeMask = 0;
115 Arrays.fill(recipe, null);
116 if (filters == null || filters.size() != 9) return;
117 for (int slot = 0; slot < 9; slot++) {
118 ItemStack item = filters.get(slot);
119 if (!validItem(item)) continue;
120 ItemStack one = item.clone();
121 one.setAmount(1);
122 recipe[slot] = one;
123 recipeMask |= 1 << slot;
124 }
125 }
126
127 void wake() {
128 sleeping = false;
129 failed = 0;
130 sleepUntil = 0;
131 crafterDirty = true;
132 for (SourceCache source : sources) source.dirty = true;
133 }
134
135 void sleepUntil(int tick) {
136 sleeping = true;
137 sleepUntil = tick;
138 }
139 }
140
141 public static void enable(Plugin owner) {
142 plugin = owner;
143 rebuild(owner);
144 Bukkit.getPluginManager().registerEvents(new CrafterPipeManager(), owner);
145 }
146
147 public static void disable() {
148 networks.clear();
149 outgoingIndex.clear();
150 appliedSlotMask.clear();
151 slavedIncomingIds.clear();
152 craftingGridIds.clear();
153 methodCache.clear();
154 orchestratorCount = 0;
155 dirty = false;
156 scheduled = false;
157 needsRetry = false;
158 plugin = null;
159 }
160
161 public static void rebuild(Object owner) {
162 if (applying) return;
163 applying = true;
164 try {
165 networks.clear();
166 outgoingIndex.clear();
167 slavedIncomingIds.clear();
168 craftingGridIds.clear();
169 orchestratorCount = 0;
170 needsRetry = false;
171 try {
172 Field field = owner.getClass().getDeclaredField("connections");
173 field.setAccessible(true);
174 @SuppressWarnings("unchecked")
175 Map<Long, Object> connections = (Map<Long, Object>) field.get(owner);
176 for (Object connection : connections.values()) indexConnection(connection);
177 if (stripIncomingFilters(owner)) {
178 networks.clear();
179 outgoingIndex.clear();
180 needsRetry = false;
181 for (Object connection : connections.values()) indexConnection(connection);
182 }
183 } catch (Throwable ignored) {}
184 networks.values().removeIf(network -> network.outgoing == null);
185 for (Network network : networks.values()) {
186 craftingGridIds.add(network.outgoing.id);
187 outgoingIndex.put(network.outgoing.id, network);
188 if (network.orchestrator != null) {
189 orchestratorCount++;
190 for (PipeRef incoming : network.incoming) slavedIncomingIds.add(incoming.id);
191 indexSources(network);
192 }
193 applySlotLocksNow(network);
194 }
195 dirty = false;
196 } finally {
197 applying = false;
198 }
199 }
200
201 public static void connectionChanged(Object owner) {
202 dirty = true;
203 scheduleRebuild(owner);
204 }
205
206 public static void chunksChanged() {
207 if (!needsRetry || plugin == null) return;
208 dirty = true;
209 scheduleRebuild(plugin);
210 }
211
212 public static boolean hasOrchestrators() {
213 return orchestratorCount > 0;
214 }
215
216 private static void scheduleRebuild(Object owner) {
217 Plugin p = plugin != null ? plugin : owner instanceof Plugin pl ? pl : null;
218 if (p == null || scheduled) return;
219 scheduled = true;
220 Bukkit.getScheduler().runTask(p, () -> {
221 scheduled = false;
222 Object target = plugin != null ? plugin : owner;
223 if (dirty) rebuild(target);
224 });
225 }
226
227 public static void invalidateBlock(Block block) {
228 if (block == null || orchestratorCount == 0) return;
229 Inventory inventory = HopperStyleEndpoints.inventoryOf(block);
230 wakeMatching(block, inventory);
231 }
232
233 public static void invalidateInventory(Inventory inventory) {
234 if (inventory == null || orchestratorCount == 0) return;
235 Block block = null;
236 try {
237 var location = inventory.getLocation();
238 if (location != null && location.getWorld() != null) block = location.getBlock();
239 } catch (Throwable ignored) {}
240 wakeMatching(block, inventory);
241 }
242
243 public static boolean isSlavedIncoming(long connectionId) {
244 return slavedIncomingIds.contains(connectionId);
245 }
246
247 public static boolean isFilteredCrafterOutput(long connectionId) {
248 Network network = outgoingIndex.get(connectionId);
249 return network != null && network.orchestrator != null;
250 }
251
252 public static boolean isFilteredCrafterOutput(Block sourceBlock, BlockFace face, boolean hasFilter) {
253 return hasFilter && isOutputFace(sourceBlock, face);
254 }
255
256 public static boolean usesCraftingGrid(long connectionId) {
257 return craftingGridIds.contains(connectionId);
258 }
259
260 public static boolean usesCraftingGrid(Block sourceBlock, BlockFace face) {
261 return isOutputFace(sourceBlock, face);
262 }
263
264 public static boolean blocksFilter(long connectionId) {
265 return slavedIncomingIds.contains(connectionId);
266 }
267
268 public static boolean isCrafter(Block block) {
269 return block != null && block.getType() == Material.CRAFTER;
270 }
271
272 /** Minecraft orientation is {@code <dispense>_<top>}; the first token is the output face. */
273 public static BlockFace outputFace(Block block) {
274 if (!isCrafter(block)) return null;
275 if (!(block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data)) return BlockFace.NORTH;
276 String name = data.getOrientation().name();
277 int underscore = name.indexOf('_');
278 if (underscore <= 0) return BlockFace.NORTH;
279 return parseFace(name.substring(0, underscore));
280 }
281
282 public static boolean isOutputFace(Block block, BlockFace face) {
283 BlockFace output = outputFace(block);
284 return output != null && output == face;
285 }
286
287 public static boolean isOrchestrated(Block block) {
288 if (!isCrafter(block)) return false;
289 Network network = networks.get(CrafterPos.of(block));
290 return network != null && network.orchestrator != null;
291 }
292
293 public static boolean allowsIncomingInsert(Block crafterBlock, ItemStack stack) {
294 if (!validItem(stack)) return false;
295 Network network = networks.get(CrafterPos.of(crafterBlock));
296 if (network == null || network.orchestrator == null) return true;
297 for (ItemStack template : network.recipe) {
298 if (template != null && stack.isSimilar(template)) return true;
299 }
300 return false;
301 }
302
303 public static void tick(Object owner) {
304 if (dirty) rebuild(owner);
305 if (orchestratorCount == 0) return;
306 reloadPerf(owner);
307 int now = Bukkit.getCurrentTick();
308 for (Network network : networks.values()) {
309 if (network.orchestrator == null) continue;
310 if (network.sleeping && now < network.sleepUntil) continue;
311 try {
312 RunResult result = orchestrate(owner, network);
313 if (result == RunResult.MOVED || result == RunResult.STALE) {
314 network.sleeping = false;
315 network.failed = 0;
316 } else if (result == RunResult.CRAFT_FAILED) {
317 network.sleepUntil(now + sleepProbe);
318 } else if (++network.failed >= idleAfter) {
319 network.sleepUntil(now + sleepProbe);
320 }
321 } catch (Throwable t) {
322 if (plugin != null) plugin.getLogger().warning("Crafter orchestration failed: " + t);
323 network.crafterDirty = true;
324 for (SourceCache source : network.sources) source.dirty = true;
325 network.sleepUntil(now + sleepProbe);
326 }
327 }
328 }
329
330 @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
331 public void onCrafterCraft(CrafterCraftEvent event) {
332 if (plugin == null) return;
333 Block block = event.getBlock();
334 if (block.getType() != Material.CRAFTER) return;
335
336 Network network = networks.get(CrafterPos.of(block));
337 if (network == null || network.outgoing == null) return;
338
339 ItemStack result = event.getResult();
340 if (!validItem(result)) return;
341
342 boolean routed = routeOutgoing(plugin, network.outgoing, result.clone());
343 if (network.attemptingCraft) {
344 if (!routed) {
345 event.setCancelled(true);
346 return;
347 }
348 network.craftSucceeded = true;
349 } else if (!routed) {
350 return;
351 }
352
353 if (network.orchestrator != null) {
354 playTransferEffects(network);
355 flashOutputLamp(plugin, network.outgoing.id);
356 } else {
357 playTransferAnimation(plugin, network.outgoing);
358 }
359 event.setCancelled(true);
360 event.setResult(new ItemStack(Material.AIR));
361 network.crafterDirty = true;
362 if (network.outgoing.destBlock != null) {
363 OptimizedTransferPlanner.invalidateBlock(plugin, network.outgoing.destBlock);
364 }
365 OptimizedTransferPlanner.invalidateBlock(plugin, block);
366 }
367
368 private enum RunResult { MOVED, NO_MOVE, STALE, CRAFT_FAILED }
369
370 private static RunResult orchestrate(Object owner, Network network) {
371 World world = Bukkit.getWorld(network.pos.world);
372 if (world == null || !world.isChunkLoaded(network.pos.x >> 4, network.pos.z >> 4)) return RunResult.NO_MOVE;
373
374 Block block = world.getBlockAt(network.pos.x, network.pos.y, network.pos.z);
375 if (block.getType() != Material.CRAFTER) return RunResult.NO_MOVE;
376 if (isBusy(block)) return RunResult.NO_MOVE;
377
378 running = network;
379 try {
380 if (!Objects.equals(appliedSlotMask.get(network.pos), network.recipeMask)) {
381 applySlotLocksNow(network);
382 }
383
384 Inventory crafterInv = HopperStyleEndpoints.inventoryOf(block);
385 if (crafterInv == null) return RunResult.NO_MOVE;
386 refreshCrafterCache(network, crafterInv);
387
388 if (gridMatchesRecipe(network.crafterCache, network.recipe)) {
389 return triggerCraft(owner, network, block) ? RunResult.MOVED : RunResult.CRAFT_FAILED;
390 }
391 if (!gridEmpty(network.crafterCache)) return RunResult.CRAFT_FAILED;
392
393 for (SourceCache source : network.sources) source.refresh();
394 Pull[] pulls = planPulls(network.sources, network.recipe);
395 if (pulls == null) return RunResult.NO_MOVE;
396
397 List<Take> takes = new ArrayList<>(9);
398 ItemStack[] placed = new ItemStack[9];
399 for (int slot = 0; slot < 9; slot++) {
400 Pull pull = pulls[slot];
401 if (pull == null) continue;
402 Inventory live = pull.source.liveInventory();
403 if (live == null) {
404 restoreTakes(takes);
405 return RunResult.NO_MOVE;
406 }
407 ItemStack expected = pull.source.contents[pull.invSlot];
408 if (!slotMatches(live, pull.invSlot, expected)) {
409 pull.source.dirty = true;
410 restoreTakes(takes);
411 return RunResult.STALE;
412 }
413 ItemStack before = takeOne(live, pull.invSlot, network.recipe[slot]);
414 if (before == null) {
415 pull.source.dirty = true;
416 restoreTakes(takes);
417 return RunResult.STALE;
418 }
419 takes.add(new Take(live, pull.invSlot, before, pull.source, expected));
420 decrementCache(pull.source, pull.invSlot);
421 ItemStack one = before.clone();
422 one.setAmount(1);
423 placed[slot] = one;
424 }
425
426 writeGrid(crafterInv, placed);
427 network.crafterCache = cloneContents(placed);
428 network.crafterDirty = false;
429 for (SourceCache source : network.sources) {
430 if (!source.dirty) OptimizedTransferPlanner.invalidateBlock(owner, source.block);
431 }
432
433 return triggerCraft(owner, network, block) ? RunResult.MOVED : RunResult.CRAFT_FAILED;
434 } finally {
435 running = null;
436 }
437 }
438
439 private static boolean triggerCraft(Object owner, Network network, Block block) {
440 network.attemptingCraft = true;
441 network.craftSucceeded = false;
442 try {
443 if (block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data) {
444 data.setTriggered(true);
445 block.setBlockData(data, false);
446 }
447 block.tick();
448 if (block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data) {
449 data.setTriggered(false);
450 block.setBlockData(data, false);
451 }
452 return network.craftSucceeded;
453 } catch (Throwable ignored) {
454 return false;
455 } finally {
456 network.attemptingCraft = false;
457 network.crafterDirty = true;
458 if (network.outgoing != null && network.outgoing.destBlock != null) {
459 OptimizedTransferPlanner.invalidateBlock(owner, network.outgoing.destBlock);
460 }
461 }
462 }
463
464 private static boolean isBusy(Block block) {
465 try {
466 if (block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data && data.isCrafting()) {
467 return true;
468 }
469 Crafter crafter = liveCrafter(block);
470 return crafter != null && crafter.getCraftingTicks() > 0;
471 } catch (Throwable ignored) {
472 return false;
473 }
474 }
475
476 private static void refreshCrafterCache(Network network, Inventory inventory) {
477 if (!network.crafterDirty && network.crafterCache != null) return;
478 ItemStack[] storage = inventory.getStorageContents();
479 ItemStack[] grid = new ItemStack[9];
480 int limit = Math.min(9, storage.length);
481 for (int slot = 0; slot < limit; slot++) {
482 ItemStack item = storage[slot];
483 grid[slot] = validItem(item) ? item.clone() : null;
484 }
485 network.crafterCache = grid;
486 network.crafterDirty = false;
487 }
488
489 private static boolean gridEmpty(ItemStack[] grid) {
490 if (grid == null) return true;
491 for (ItemStack item : grid) {
492 if (validItem(item)) return false;
493 }
494 return true;
495 }
496
497 private static boolean gridMatchesRecipe(ItemStack[] grid, ItemStack[] recipe) {
498 if (grid == null) return false;
499 for (int slot = 0; slot < 9; slot++) {
500 ItemStack want = recipe[slot];
501 ItemStack have = slot < grid.length ? grid[slot] : null;
502 if (want == null) {
503 if (validItem(have)) return false;
504 } else if (!validItem(have) || !have.isSimilar(want)) {
505 return false;
506 }
507 }
508 return true;
509 }
510
511 private static boolean routeOutgoing(Object owner, PipeRef outgoing, ItemStack item) {
512 try {
513 if (!validItem(item) || outgoing == null) return false;
514 Block destBlock = outgoing.destBlock;
515 if (destBlock == null || destBlock.getWorld() == null) return false;
516 if (!destBlock.getWorld().isChunkLoaded(destBlock.getX() >> 4, destBlock.getZ() >> 4)) return false;
517 Inventory destInv = HopperStyleEndpoints.inventoryOf(destBlock);
518 if (destInv == null) return false;
519
520 if (AdvancedEndpointsPatch.isCrafterInventory(destInv)) {
521 if (!insertIntoCrafter(destInv, item)) return false;
522 } else if (HopperStyleEndpoints.isComposter(destBlock)) {
523 if (item.getAmount() != 1 || !HopperStyleEndpoints.insertComposter(destBlock, item)) return false;
524 } else {
525 Boolean specialty = HopperStyleEndpoints.tryInsertOne(destInv, item);
526 if (specialty != null) {
527 if (item.getAmount() != 1 || !specialty) return false;
528 } else if (!insertStack(destInv, item)) {
529 return false;
530 }
531 }
532 return true;
533 } catch (Throwable ignored) {
534 return false;
535 }
536 }
537
538 private static boolean insertIntoCrafter(Inventory inventory, ItemStack source) {
539 int amount = source.getAmount();
540 for (int i = 0; i < amount; i++) {
541 ItemStack one = source.clone();
542 one.setAmount(1);
543 if (!AdvancedEndpointsPatch.insertOneCrafter(inventory, one)) return false;
544 }
545 return amount > 0;
546 }
547
548 private static boolean insertStack(Inventory inventory, ItemStack source) {
549 if (!validItem(source)) return false;
550 int amount = source.getAmount();
551 if (!canFit(inventory, source, amount)) return false;
552 for (int i = 0; i < amount; i++) {
553 if (!insertOne(inventory, source)) return false;
554 }
555 return true;
556 }
557
558 private static boolean canFit(Inventory inventory, ItemStack source, int amount) {
559 int remaining = amount;
560 int max = Math.min(source.getMaxStackSize(), inventory.getMaxStackSize());
561 ItemStack[] storage = inventory.getStorageContents();
562 for (ItemStack existing : storage) {
563 if (existing != null && !existing.getType().isAir() && existing.isSimilar(source)) {
564 remaining -= Math.max(0, Math.min(max, existing.getMaxStackSize()) - existing.getAmount());
565 if (remaining <= 0) return true;
566 }
567 }
568 for (ItemStack existing : storage) {
569 if (existing == null || existing.getType().isAir()) {
570 remaining -= max;
571 if (remaining <= 0) return true;
572 }
573 }
574 return remaining <= 0;
575 }
576
577 private static boolean insertOne(Inventory inventory, ItemStack source) {
578 ItemStack one = source.clone();
579 one.setAmount(1);
580 ItemStack[] storage = inventory.getStorageContents();
581 for (int slot = 0; slot < storage.length; slot++) {
582 ItemStack existing = storage[slot];
583 if (existing != null && !existing.getType().isAir() && existing.isSimilar(one)
584 && existing.getAmount() < existing.getMaxStackSize()) {
585 ItemStack merged = existing.clone();
586 merged.setAmount(existing.getAmount() + 1);
587 inventory.setItem(slot, merged);
588 return true;
589 }
590 }
591 for (int slot = 0; slot < storage.length; slot++) {
592 ItemStack existing = storage[slot];
593 if (existing == null || existing.getType().isAir()) {
594 inventory.setItem(slot, one.clone());
595 return true;
596 }
597 }
598 return false;
599 }
600
601 private static void applySlotLocksNow(Network network) {
602 World world = Bukkit.getWorld(network.pos.world);
603 if (world == null || !world.isChunkLoaded(network.pos.x >> 4, network.pos.z >> 4)) return;
604 Block block = world.getBlockAt(network.pos.x, network.pos.y, network.pos.z);
605 if (block.getType() != Material.CRAFTER) return;
606 Crafter crafter = liveCrafter(block);
607 if (crafter == null) return;
608 int mask = network.orchestrator == null ? 0x1FF : network.recipeMask;
609 if (network.orchestrator == null && !appliedSlotMask.containsKey(network.pos)) return;
610 applySlotLocks(network.pos, crafter, mask);
611 if (network.orchestrator == null) appliedSlotMask.remove(network.pos);
612 }
613
614 private static void applySlotLocks(CrafterPos pos, Crafter crafter, int mask) {
615 if (Objects.equals(appliedSlotMask.get(pos), mask)) return;
616 for (int slot = 0; slot < 9; slot++) {
617 crafter.setSlotDisabled(slot, (mask & (1 << slot)) == 0);
618 }
619 appliedSlotMask.put(pos, mask);
620 try { crafter.update(true, false); } catch (Throwable ignored) {}
621 }
622
623 private static Pull[] planPulls(List<SourceCache> sources, ItemStack[] recipe) {
624 Pull[] pulls = new Pull[9];
625 int needed = 0;
626 int[][] reserved = new int[sources.size()][];
627 for (int i = 0; i < sources.size(); i++) {
628 ItemStack[] contents = sources.get(i).contents;
629 reserved[i] = new int[contents == null ? 0 : contents.length];
630 }
631 for (int slot = 0; slot < 9; slot++) {
632 ItemStack template = recipe[slot];
633 if (template == null) continue;
634 needed++;
635 Pull pull = null;
636 for (int s = 0; s < sources.size(); s++) {
637 SourceCache source = sources.get(s);
638 ItemStack[] contents = source.contents;
639 if (contents == null) continue;
640 for (int invSlot = 0; invSlot < contents.length; invSlot++) {
641 ItemStack stack = contents[invSlot];
642 if (!validItem(stack) || !stack.isSimilar(template)) continue;
643 if (stack.getAmount() <= reserved[s][invSlot]) continue;
644 reserved[s][invSlot]++;
645 pull = new Pull(source, invSlot);
646 break;
647 }
648 if (pull != null) break;
649 }
650 if (pull == null) return null;
651 pulls[slot] = pull;
652 }
653 return needed == 0 ? null : pulls;
654 }
655
656 private static boolean slotMatches(Inventory inventory, int slot, ItemStack expected) {
657 ItemStack actual = inventory.getItem(slot);
658 if (expected == null || expected.getType().isAir()) {
659 return actual == null || actual.getType().isAir();
660 }
661 if (actual == null || actual.getType().isAir()) return false;
662 return expected.getAmount() == actual.getAmount() && expected.isSimilar(actual);
663 }
664
665 private static ItemStack takeOne(Inventory inventory, int slot, ItemStack template) {
666 ItemStack have = inventory.getItem(slot);
667 if (!validItem(have) || (template != null && !have.isSimilar(template))) return null;
668 ItemStack before = have.clone();
669 if (have.getAmount() <= 1) inventory.setItem(slot, null);
670 else {
671 ItemStack reduced = have.clone();
672 reduced.setAmount(have.getAmount() - 1);
673 inventory.setItem(slot, reduced);
674 }
675 return before;
676 }
677
678 private static void decrementCache(SourceCache source, int slot) {
679 if (source.contents == null || slot < 0 || slot >= source.contents.length) return;
680 ItemStack have = source.contents[slot];
681 if (!validItem(have)) return;
682 if (have.getAmount() <= 1) source.contents[slot] = null;
683 else {
684 ItemStack reduced = have.clone();
685 reduced.setAmount(have.getAmount() - 1);
686 source.contents[slot] = reduced;
687 }
688 }
689
690 private static void restoreTakes(List<Take> takes) {
691 for (int i = takes.size() - 1; i >= 0; i--) {
692 Take take = takes.get(i);
693 take.inventory.setItem(take.slot, take.before);
694 if (take.source.contents != null && take.slot < take.source.contents.length) {
695 take.source.contents[take.slot] = take.cachedBefore == null ? null : take.cachedBefore.clone();
696 }
697 }
698 }
699
700 private static void writeGrid(Inventory inventory, ItemStack[] placed) {
701 int limit = Math.min(9, inventory.getSize());
702 for (int slot = 0; slot < limit; slot++) {
703 ItemStack item = placed[slot];
704 inventory.setItem(slot, validItem(item) ? item.clone() : null);
705 }
706 }
707
708 private static ItemStack[] cloneContents(ItemStack[] input) {
709 ItemStack[] copy = new ItemStack[input.length];
710 for (int i = 0; i < input.length; i++) copy[i] = input[i] == null ? null : input[i].clone();
711 return copy;
712 }
713
714 private record Pull(SourceCache source, int invSlot) {}
715
716 private record Take(Inventory inventory, int slot, ItemStack before, SourceCache source, ItemStack cachedBefore) {}
717
718 private static Crafter liveCrafter(Block block) {
719 try {
720 BlockState state = block.getState(false);
721 if (state instanceof Crafter crafter) return crafter;
722 } catch (Throwable ignored) {}
723 return block.getState() instanceof Crafter crafter ? crafter : null;
724 }
725
726 private static void playTransferAnimation(Object owner, PipeRef pipe) {
727 if (pipe == null || !(owner instanceof ContainerPipesPlugin pipes)) return;
728 pipes.playTransferAnimation(pipe.raw);
729 }
730
731 private static void flashOutputLamp(Object owner, long connectionId) {
732 if (owner instanceof ContainerPipesPlugin pipes) pipes.flashCrafterOutputLamp(connectionId);
733 }
734
735 private static void playTransferEffects(Network network) {
736 if (!(plugin instanceof ContainerPipesPlugin pipes)) return;
737 if (network.outgoing != null) pipes.playTransferAnimation(network.outgoing.raw);
738 for (SourceCache source : network.sources) {
739 for (PipeRef incoming : source.pipes) pipes.playTransferAnimation(incoming.raw);
740 }
741 }
742
743 private static void wakeMatching(Block block, Inventory inventory) {
744 CrafterPos pos = block == null ? null : CrafterPos.of(block);
745 for (Network network : networks.values()) {
746 if (network.orchestrator == null) continue;
747 if (network == running) {
748 network.crafterDirty = true;
749 continue;
750 }
751 if (pos != null && network.pos.equals(pos)) {
752 network.wake();
753 continue;
754 }
755 if (pos != null && network.outgoing != null && network.outgoing.destBlock != null
756 && CrafterPos.of(network.outgoing.destBlock).equals(pos)) {
757 network.wake();
758 continue;
759 }
760 if (matchesSource(network, block, inventory)) network.wake();
761 }
762 }
763
764 private static boolean matchesSource(Network network, Block block, Inventory inventory) {
765 Integer invX = null, invY = null, invZ = null;
766 World invWorld = null;
767 if (inventory != null) {
768 try {
769 var location = inventory.getLocation();
770 if (location != null && location.getWorld() != null) {
771 invWorld = location.getWorld();
772 invX = location.getBlockX();
773 invY = location.getBlockY();
774 invZ = location.getBlockZ();
775 }
776 } catch (Throwable ignored) {}
777 }
778 for (SourceCache source : network.sources) {
779 if (block != null && source.block.getWorld() == block.getWorld()
780 && source.block.getX() == block.getX()
781 && source.block.getY() == block.getY()
782 && source.block.getZ() == block.getZ()) {
783 return true;
784 }
785 if (invWorld != null && source.block.getWorld() == invWorld
786 && source.block.getX() == invX
787 && source.block.getY() == invY
788 && source.block.getZ() == invZ) {
789 return true;
790 }
791 }
792 return false;
793 }
794
795 private static void indexSources(Network network) {
796 network.sources.clear();
797 Map<String, SourceCache> byBlock = new LinkedHashMap<>();
798 for (PipeRef incoming : network.incoming) {
799 Block block = incoming.sourceBlock;
800 if (block == null) continue;
801 String key = block.getWorld().getUID() + ":" + block.getX() + "," + block.getY() + "," + block.getZ();
802 SourceCache cache = byBlock.get(key);
803 if (cache == null) {
804 cache = new SourceCache(block);
805 byBlock.put(key, cache);
806 }
807 cache.pipes.add(incoming);
808 }
809 network.sources.addAll(byBlock.values());
810 network.crafterDirty = true;
811 network.wake();
812 }
813
814 private static boolean stripIncomingFilters(Object owner) {
815 if (!(owner instanceof ContainerPipesPlugin pipes)) return false;
816 boolean stripped = false;
817 for (Network network : networks.values()) {
818 if (network.orchestrator == null) continue;
819 for (PipeRef incoming : network.incoming) {
820 if (pipes.clearPipeFilterIfPresent(incoming.id)) stripped = true;
821 }
822 }
823 return stripped;
824 }
825
826 private static void indexConnection(Object connection) {
827 try {
828 long id = ((Number) invoke(connection, "id")).longValue();
829 Object source = invoke(connection, "source");
830 Object destination = invoke(connection, "destination");
831 UUID world = (UUID) invoke(source, "world");
832 int sx = (int) invoke(source, "x");
833 int sy = (int) invoke(source, "y");
834 int sz = (int) invoke(source, "z");
835 String sourceFace = String.valueOf(invoke(source, "face"));
836 int dx = (int) invoke(destination, "x");
837 int dy = (int) invoke(destination, "y");
838 int dz = (int) invoke(destination, "z");
839
840 World w = Bukkit.getWorld(world);
841 if (w == null) return;
842
843 boolean sourceLoaded = w.isChunkLoaded(sx >> 4, sz >> 4);
844 boolean destLoaded = w.isChunkLoaded(dx >> 4, dz >> 4);
845 if (!sourceLoaded || !destLoaded) needsRetry = true;
846
847 Block sourceBlock = sourceLoaded ? w.getBlockAt(sx, sy, sz) : null;
848 Block destBlock = destLoaded ? w.getBlockAt(dx, dy, dz) : null;
849 PipeRef ref = new PipeRef(id, connection, sourceBlock, destBlock);
850
851 if (sourceBlock != null && sourceBlock.getType() == Material.CRAFTER) {
852 BlockFace output = outputFace(sourceBlock);
853 if (output != null && output.name().equals(sourceFace)) {
854 Network network = networks.computeIfAbsent(CrafterPos.of(sourceBlock), Network::new);
855 network.outgoing = ref;
856 network.setRecipe(readFilters(connection));
857 if (network.recipeMask != 0) network.orchestrator = ref;
858 }
859 }
860
861 if (destBlock != null && destBlock.getType() == Material.CRAFTER) {
862 Network network = networks.computeIfAbsent(CrafterPos.of(destBlock), Network::new);
863 network.incoming.add(ref);
864 }
865 } catch (Throwable ignored) {}
866 }
867
868 private static void reloadPerf(Object owner) {
869 Plugin configOwner = owner instanceof Plugin p ? p : plugin;
870 if (configOwner == null) return;
871 idleAfter = Math.max(1, configOwner.getConfig().getInt("performance.idle-after-failed-attempts", 3));
872 sleepProbe = Math.max(1, configOwner.getConfig().getInt("performance.sleeping-probe-interval-ticks", 200));
873 }
874
875 private static List<ItemStack> readFilters(Object connection) throws Exception {
876 List<ItemStack> filters = new ArrayList<>();
877 for (Object value : (List<?>) invoke(connection, "filter")) {
878 if (value instanceof ItemStack item && validItem(item)) filters.add(item.clone());
879 else filters.add(null);
880 }
881 return filters;
882 }
883
884 private static boolean validItem(ItemStack item) {
885 return item != null && !item.getType().isAir() && item.getAmount() > 0;
886 }
887
888 private static BlockFace parseFace(String name) {
889 try {
890 return BlockFace.valueOf(name.toUpperCase(Locale.ROOT));
891 } catch (IllegalArgumentException ignored) {
892 return null;
893 }
894 }
895
896 private static Object invoke(Object target, String name, Object... args) throws Exception {
897 Class<?> type = target.getClass();
898 String key = type.getName() + '#' + name + '#' + args.length;
899 Method method = methodCache.get(key);
900 if (method == null) {
901 method = findMethod(type, name, args.length);
902 if (method == null) throw new NoSuchMethodException(name);
903 method.setAccessible(true);
904 methodCache.put(key, method);
905 }
906 return method.invoke(target, args);
907 }
908
909 private static Method findMethod(Class<?> type, String name, int parameterCount) {
910 for (Method candidate : type.getMethods()) {
911 if (candidate.getName().equals(name) && candidate.getParameterCount() == parameterCount) return candidate;
912 }
913 for (Method candidate : type.getDeclaredMethods()) {
914 if (candidate.getName().equals(name) && candidate.getParameterCount() == parameterCount) return candidate;
915 }
916 return null;
917 }
918}