BlueGit

timfa containerpipes

Files

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

CrafterPipeManager.java

CrafterPipeManager.java 28.8 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 deliver recipe
24 * ingredients through the normal transfer planner; this class only coordinates
25 * slot locks, recipe-aware insertion, and triggering the vanilla crafter.
26 */
27public final class CrafterPipeManager implements Listener {
28 private CrafterPipeManager() {}
29
30 private static Plugin plugin;
31 private static final Map<CrafterPos, Network> networks = new HashMap<>();
32 private static final Map<Long, Network> outgoingIndex = new HashMap<>();
33 private static final Map<CrafterPos, Integer> appliedSlotMask = new HashMap<>();
34 private static final Set<Long> incomingToOrchestrated = new HashSet<>();
35 private static final Set<Long> craftingGridIds = new HashSet<>();
36 private static final Map<String, Method> methodCache = new HashMap<>();
37 private static boolean applying;
38 private static boolean dirty;
39 private static boolean scheduled;
40 private static boolean needsRetry;
41 private static int orchestratorCount;
42 private static int idleAfter = 3;
43 private static int sleepProbe = 200;
44
45 record CrafterPos(UUID world, int x, int y, int z) {
46 static CrafterPos of(Block block) {
47 return new CrafterPos(block.getWorld().getUID(), block.getX(), block.getY(), block.getZ());
48 }
49 }
50
51 static final class PipeRef {
52 final long id;
53 final Object raw;
54 final Block sourceBlock;
55 final Block destBlock;
56
57 PipeRef(long id, Object raw, Block sourceBlock, Block destBlock) {
58 this.id = id;
59 this.raw = raw;
60 this.sourceBlock = sourceBlock;
61 this.destBlock = destBlock;
62 }
63 }
64
65 static final class Network {
66 final CrafterPos pos;
67 PipeRef outgoing;
68 PipeRef orchestrator;
69 final List<PipeRef> incoming = new ArrayList<>();
70 final ItemStack[] recipe = new ItemStack[9];
71 int recipeMask;
72 boolean sleeping;
73 int failed;
74 int sleepUntil;
75 boolean attemptingCraft;
76 boolean craftSucceeded;
77
78 Network(CrafterPos pos) { this.pos = pos; }
79
80 void setRecipe(List<ItemStack> filters) {
81 recipeMask = 0;
82 Arrays.fill(recipe, null);
83 if (filters == null || filters.size() != 9) return;
84 for (int slot = 0; slot < 9; slot++) {
85 ItemStack item = filters.get(slot);
86 if (!validItem(item)) continue;
87 ItemStack one = item.clone();
88 one.setAmount(1);
89 recipe[slot] = one;
90 recipeMask |= 1 << slot;
91 }
92 }
93
94 void wake() {
95 sleeping = false;
96 failed = 0;
97 sleepUntil = 0;
98 }
99 }
100
101 public static void enable(Plugin owner) {
102 plugin = owner;
103 rebuild(owner);
104 Bukkit.getPluginManager().registerEvents(new CrafterPipeManager(), owner);
105 }
106
107 public static void disable() {
108 networks.clear();
109 outgoingIndex.clear();
110 appliedSlotMask.clear();
111 incomingToOrchestrated.clear();
112 craftingGridIds.clear();
113 methodCache.clear();
114 orchestratorCount = 0;
115 dirty = false;
116 scheduled = false;
117 needsRetry = false;
118 plugin = null;
119 }
120
121 public static void rebuild(Object owner) {
122 if (applying) return;
123 applying = true;
124 try {
125 networks.clear();
126 outgoingIndex.clear();
127 incomingToOrchestrated.clear();
128 craftingGridIds.clear();
129 orchestratorCount = 0;
130 needsRetry = false;
131 try {
132 Field field = owner.getClass().getDeclaredField("connections");
133 field.setAccessible(true);
134 @SuppressWarnings("unchecked")
135 Map<Long, Object> connections = (Map<Long, Object>) field.get(owner);
136 for (Object connection : connections.values()) indexConnection(connection);
137 if (stripIncomingFilters(owner)) {
138 networks.clear();
139 outgoingIndex.clear();
140 needsRetry = false;
141 for (Object connection : connections.values()) indexConnection(connection);
142 }
143 } catch (Throwable ignored) {}
144 networks.values().removeIf(network -> network.outgoing == null);
145 for (Network network : networks.values()) {
146 craftingGridIds.add(network.outgoing.id);
147 outgoingIndex.put(network.outgoing.id, network);
148 if (network.orchestrator != null) {
149 orchestratorCount++;
150 for (PipeRef incoming : network.incoming) incomingToOrchestrated.add(incoming.id);
151 }
152 applySlotLocksNow(network);
153 }
154 dirty = false;
155 } finally {
156 applying = false;
157 }
158 }
159
160 public static void connectionChanged(Object owner) {
161 dirty = true;
162 scheduleRebuild(owner);
163 }
164
165 public static void chunksChanged() {
166 if (!needsRetry || plugin == null) return;
167 dirty = true;
168 scheduleRebuild(plugin);
169 }
170
171 public static boolean hasOrchestrators() {
172 return orchestratorCount > 0;
173 }
174
175 /** Material filter for incoming pipes whose destination is an orchestrated crafter. */
176 public static EnumSet<Material> recipeMaterials(Block crafterBlock) {
177 Network network = networkAt(crafterBlock);
178 if (network == null || network.orchestrator == null) return null;
179 EnumSet<Material> materials = EnumSet.noneOf(Material.class);
180 for (ItemStack template : network.recipe) {
181 if (template != null) materials.add(template.getType());
182 }
183 return materials.isEmpty() ? null : materials;
184 }
185
186 public static boolean insertRecipeItem(Inventory inventory, Block block, ItemStack source) {
187 if (!validItem(source) || inventory == null || block == null) return false;
188 Network network = networkAt(block);
189 if (network == null || network.orchestrator == null) {
190 return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
191 }
192 if (!allowsIncomingInsert(block, source)) return false;
193
194 ItemStack one = source.clone();
195 one.setAmount(1);
196 Crafter crafter = liveCrafter(block);
197 int maxStack = Math.min(one.getMaxStackSize(), inventory.getMaxStackSize());
198
199 for (int slot = 0; slot < 9; slot++) {
200 ItemStack template = network.recipe[slot];
201 if (template == null || !one.isSimilar(template)) continue;
202 if (crafter != null && crafter.isSlotDisabled(slot)) continue;
203 ItemStack existing = inventory.getItem(slot);
204 if (validItem(existing)) continue;
205 ItemStack actual = inventory.getItem(slot);
206 if (validItem(actual)) continue;
207 inventory.setItem(slot, one.clone());
208 return true;
209 }
210
211 int bestSlot = -1;
212 int bestAmount = Integer.MAX_VALUE;
213 for (int slot = 0; slot < 9; slot++) {
214 ItemStack template = network.recipe[slot];
215 if (template == null || !one.isSimilar(template)) continue;
216 if (crafter != null && crafter.isSlotDisabled(slot)) continue;
217 ItemStack existing = inventory.getItem(slot);
218 if (!validItem(existing) || !existing.isSimilar(one)) continue;
219 if (existing.getAmount() >= Math.min(existing.getMaxStackSize(), maxStack)) continue;
220 if (existing.getAmount() < bestAmount) {
221 bestAmount = existing.getAmount();
222 bestSlot = slot;
223 }
224 }
225 if (bestSlot < 0) return false;
226 ItemStack existing = inventory.getItem(bestSlot);
227 if (!validItem(existing) || existing.getAmount() != bestAmount || !existing.isSimilar(one)) return false;
228 ItemStack merged = existing.clone();
229 merged.setAmount(existing.getAmount() + 1);
230 inventory.setItem(bestSlot, merged);
231 return true;
232 }
233
234 private static void scheduleRebuild(Object owner) {
235 Plugin p = plugin != null ? plugin : owner instanceof Plugin pl ? pl : null;
236 if (p == null || scheduled) return;
237 scheduled = true;
238 Bukkit.getScheduler().runTask(p, () -> {
239 scheduled = false;
240 Object target = plugin != null ? plugin : owner;
241 if (dirty) rebuild(target);
242 });
243 }
244
245 public static void invalidateBlock(Block block) {
246 if (block == null || orchestratorCount == 0) return;
247 Network network = networkAt(block);
248 if (network != null && network.orchestrator != null) network.wake();
249 }
250
251 public static void invalidateInventory(Inventory inventory) {
252 if (inventory == null || orchestratorCount == 0) return;
253 try {
254 var location = inventory.getLocation();
255 if (location != null && location.getWorld() != null) invalidateBlock(location.getBlock());
256 } catch (Throwable ignored) {}
257 }
258
259 public static boolean isSlavedIncoming(long connectionId) {
260 return incomingToOrchestrated.contains(connectionId);
261 }
262
263 public static boolean isFilteredCrafterOutput(long connectionId) {
264 Network network = outgoingIndex.get(connectionId);
265 return network != null && network.orchestrator != null;
266 }
267
268 public static boolean isFilteredCrafterOutput(Block sourceBlock, BlockFace face, boolean hasFilter) {
269 return hasFilter && isOutputFace(sourceBlock, face);
270 }
271
272 public static boolean usesCraftingGrid(long connectionId) {
273 return craftingGridIds.contains(connectionId);
274 }
275
276 public static boolean usesCraftingGrid(Block sourceBlock, BlockFace face) {
277 return isOutputFace(sourceBlock, face);
278 }
279
280 public static boolean blocksFilter(long connectionId) {
281 return incomingToOrchestrated.contains(connectionId);
282 }
283
284 public static boolean isCrafter(Block block) {
285 return block != null && block.getType() == Material.CRAFTER;
286 }
287
288 public static BlockFace outputFace(Block block) {
289 if (!isCrafter(block)) return null;
290 if (!(block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data)) return BlockFace.NORTH;
291 String name = data.getOrientation().name();
292 int underscore = name.indexOf('_');
293 if (underscore <= 0) return BlockFace.NORTH;
294 return parseFace(name.substring(0, underscore));
295 }
296
297 public static boolean isOutputFace(Block block, BlockFace face) {
298 BlockFace output = outputFace(block);
299 return output != null && output == face;
300 }
301
302 public static boolean isOrchestrated(Block block) {
303 if (!isCrafter(block)) return false;
304 Network network = networks.get(CrafterPos.of(block));
305 return network != null && network.orchestrator != null;
306 }
307
308 public static boolean allowsIncomingInsert(Block crafterBlock, ItemStack stack) {
309 if (!validItem(stack)) return false;
310 Network network = networkAt(crafterBlock);
311 if (network == null || network.orchestrator == null) return true;
312 for (ItemStack template : network.recipe) {
313 if (template != null && stack.isSimilar(template)) return true;
314 }
315 return false;
316 }
317
318 public static void tick(Object owner) {
319 if (dirty) rebuild(owner);
320 if (orchestratorCount == 0) return;
321 reloadPerf(owner);
322 int now = Bukkit.getCurrentTick();
323 for (Network network : networks.values()) {
324 if (network.orchestrator == null) continue;
325 if (network.sleeping && now < network.sleepUntil) continue;
326 try {
327 RunResult result = tryCraft(owner, network);
328 if (result == RunResult.MOVED) {
329 network.sleeping = false;
330 network.failed = 0;
331 } else if (result == RunResult.CRAFT_FAILED) {
332 network.sleeping = true;
333 network.sleepUntil = now + sleepProbe;
334 } else if (++network.failed >= idleAfter) {
335 network.sleeping = true;
336 network.sleepUntil = now + sleepProbe;
337 }
338 } catch (Throwable t) {
339 if (plugin != null) plugin.getLogger().warning("Crafter orchestration failed: " + t);
340 network.sleeping = true;
341 network.sleepUntil = now + sleepProbe;
342 }
343 }
344 }
345
346 @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
347 public void onCrafterCraft(CrafterCraftEvent event) {
348 if (plugin == null) return;
349 Block block = event.getBlock();
350 if (block.getType() != Material.CRAFTER) return;
351
352 Network network = networks.get(CrafterPos.of(block));
353 if (network == null || network.outgoing == null) return;
354
355 ItemStack result = event.getResult();
356 if (!validItem(result)) return;
357
358 boolean routed = routeOutgoing(plugin, network.outgoing, result.clone());
359 if (network.attemptingCraft) {
360 if (!routed) {
361 event.setCancelled(true);
362 return;
363 }
364 network.craftSucceeded = true;
365 } else if (!routed) {
366 return;
367 }
368
369 if (network.orchestrator != null) {
370 playTransferEffects(network);
371 flashOutputLamp(plugin, network.outgoing.id);
372 } else {
373 playTransferAnimation(plugin, network.outgoing);
374 }
375 event.setCancelled(true);
376 event.setResult(new ItemStack(Material.AIR));
377 if (network.outgoing.destBlock != null) {
378 OptimizedTransferPlanner.invalidateBlock(plugin, network.outgoing.destBlock);
379 }
380 OptimizedTransferPlanner.invalidateBlock(plugin, block);
381 }
382
383 private enum RunResult { MOVED, NO_MOVE, CRAFT_FAILED }
384
385 private static RunResult tryCraft(Object owner, Network network) {
386 World world = Bukkit.getWorld(network.pos.world);
387 if (world == null || !world.isChunkLoaded(network.pos.x >> 4, network.pos.z >> 4)) return RunResult.NO_MOVE;
388
389 Block block = world.getBlockAt(network.pos.x, network.pos.y, network.pos.z);
390 if (block.getType() != Material.CRAFTER) return RunResult.NO_MOVE;
391 if (isBusy(block)) return RunResult.NO_MOVE;
392
393 if (!Objects.equals(appliedSlotMask.get(network.pos), network.recipeMask)) {
394 applySlotLocksNow(network);
395 }
396
397 Inventory crafterInv = HopperStyleEndpoints.inventoryOf(block);
398 if (crafterInv == null) return RunResult.NO_MOVE;
399
400 ItemStack[] grid = readGrid(crafterInv);
401 if (hasJunk(grid, network.recipe)) return RunResult.CRAFT_FAILED;
402 if (!gridMatchesRecipe(grid, network.recipe)) return RunResult.NO_MOVE;
403
404 return triggerCraft(owner, network, block) ? RunResult.MOVED : RunResult.CRAFT_FAILED;
405 }
406
407 private static ItemStack[] readGrid(Inventory inventory) {
408 ItemStack[] storage = inventory.getStorageContents();
409 ItemStack[] grid = new ItemStack[9];
410 int limit = Math.min(9, storage.length);
411 for (int slot = 0; slot < limit; slot++) {
412 ItemStack item = storage[slot];
413 grid[slot] = validItem(item) ? item.clone() : null;
414 }
415 return grid;
416 }
417
418 private static boolean hasJunk(ItemStack[] grid, ItemStack[] recipe) {
419 for (int slot = 0; slot < 9; slot++) {
420 ItemStack want = recipe[slot];
421 ItemStack have = grid[slot];
422 if (want == null) {
423 if (validItem(have)) return true;
424 } else if (validItem(have) && !have.isSimilar(want)) {
425 return true;
426 }
427 }
428 return false;
429 }
430
431 private static boolean gridMatchesRecipe(ItemStack[] grid, ItemStack[] recipe) {
432 if (grid == null) return false;
433 for (int slot = 0; slot < 9; slot++) {
434 ItemStack want = recipe[slot];
435 ItemStack have = grid[slot];
436 if (want == null) {
437 if (validItem(have)) return false;
438 } else if (!validItem(have) || !have.isSimilar(want)) {
439 return false;
440 }
441 }
442 return true;
443 }
444
445 private static boolean triggerCraft(Object owner, Network network, Block block) {
446 network.attemptingCraft = true;
447 network.craftSucceeded = false;
448 try {
449 if (block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data) {
450 data.setTriggered(true);
451 block.setBlockData(data, false);
452 }
453 block.tick();
454 if (block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data) {
455 data.setTriggered(false);
456 block.setBlockData(data, false);
457 }
458 return network.craftSucceeded;
459 } catch (Throwable ignored) {
460 return false;
461 } finally {
462 network.attemptingCraft = false;
463 if (network.outgoing != null && network.outgoing.destBlock != null) {
464 OptimizedTransferPlanner.invalidateBlock(owner, network.outgoing.destBlock);
465 }
466 }
467 }
468
469 private static boolean isBusy(Block block) {
470 try {
471 if (block.getBlockData() instanceof org.bukkit.block.data.type.Crafter data && data.isCrafting()) {
472 return true;
473 }
474 Crafter crafter = liveCrafter(block);
475 return crafter != null && crafter.getCraftingTicks() > 0;
476 } catch (Throwable ignored) {
477 return false;
478 }
479 }
480
481 private static boolean routeOutgoing(Object owner, PipeRef outgoing, ItemStack item) {
482 try {
483 if (!validItem(item) || outgoing == null) return false;
484 Block destBlock = outgoing.destBlock;
485 if (destBlock == null || destBlock.getWorld() == null) return false;
486 if (!destBlock.getWorld().isChunkLoaded(destBlock.getX() >> 4, destBlock.getZ() >> 4)) return false;
487 Inventory destInv = HopperStyleEndpoints.inventoryOf(destBlock);
488 if (destInv == null) return false;
489
490 if (AdvancedEndpointsPatch.isCrafterInventory(destInv)) {
491 if (!insertIntoCrafter(destInv, item)) return false;
492 } else if (HopperStyleEndpoints.isComposter(destBlock)) {
493 if (item.getAmount() != 1 || !HopperStyleEndpoints.insertComposter(destBlock, item)) return false;
494 } else {
495 Boolean specialty = HopperStyleEndpoints.tryInsertOne(destInv, item);
496 if (specialty != null) {
497 if (item.getAmount() != 1 || !specialty) return false;
498 } else if (!insertStack(destInv, item)) {
499 return false;
500 }
501 }
502 return true;
503 } catch (Throwable ignored) {
504 return false;
505 }
506 }
507
508 private static boolean insertIntoCrafter(Inventory inventory, ItemStack source) {
509 int amount = source.getAmount();
510 for (int i = 0; i < amount; i++) {
511 ItemStack one = source.clone();
512 one.setAmount(1);
513 if (!AdvancedEndpointsPatch.insertOneCrafter(inventory, one)) return false;
514 }
515 return amount > 0;
516 }
517
518 private static boolean insertStack(Inventory inventory, ItemStack source) {
519 if (!validItem(source)) return false;
520 int amount = source.getAmount();
521 if (!canFit(inventory, source, amount)) return false;
522 for (int i = 0; i < amount; i++) {
523 if (!insertOne(inventory, source)) return false;
524 }
525 return true;
526 }
527
528 private static boolean canFit(Inventory inventory, ItemStack source, int amount) {
529 int remaining = amount;
530 int max = Math.min(source.getMaxStackSize(), inventory.getMaxStackSize());
531 ItemStack[] storage = inventory.getStorageContents();
532 for (ItemStack existing : storage) {
533 if (existing != null && !existing.getType().isAir() && existing.isSimilar(source)) {
534 remaining -= Math.max(0, Math.min(max, existing.getMaxStackSize()) - existing.getAmount());
535 if (remaining <= 0) return true;
536 }
537 }
538 for (ItemStack existing : storage) {
539 if (existing == null || existing.getType().isAir()) {
540 remaining -= max;
541 if (remaining <= 0) return true;
542 }
543 }
544 return remaining <= 0;
545 }
546
547 private static boolean insertOne(Inventory inventory, ItemStack source) {
548 ItemStack one = source.clone();
549 one.setAmount(1);
550 ItemStack[] storage = inventory.getStorageContents();
551 for (int slot = 0; slot < storage.length; slot++) {
552 ItemStack existing = storage[slot];
553 if (existing != null && !existing.getType().isAir() && existing.isSimilar(one)
554 && existing.getAmount() < existing.getMaxStackSize()) {
555 ItemStack merged = existing.clone();
556 merged.setAmount(existing.getAmount() + 1);
557 inventory.setItem(slot, merged);
558 return true;
559 }
560 }
561 for (int slot = 0; slot < storage.length; slot++) {
562 ItemStack existing = storage[slot];
563 if (existing == null || existing.getType().isAir()) {
564 inventory.setItem(slot, one.clone());
565 return true;
566 }
567 }
568 return false;
569 }
570
571 private static Network networkAt(Block block) {
572 if (block == null || block.getType() != Material.CRAFTER) return null;
573 return networks.get(CrafterPos.of(block));
574 }
575
576 private static void applySlotLocksNow(Network network) {
577 World world = Bukkit.getWorld(network.pos.world);
578 if (world == null || !world.isChunkLoaded(network.pos.x >> 4, network.pos.z >> 4)) return;
579 Block block = world.getBlockAt(network.pos.x, network.pos.y, network.pos.z);
580 if (block.getType() != Material.CRAFTER) return;
581 Crafter crafter = liveCrafter(block);
582 if (crafter == null) return;
583 int mask = network.orchestrator == null ? 0x1FF : network.recipeMask;
584 if (network.orchestrator == null && !appliedSlotMask.containsKey(network.pos)) return;
585 applySlotLocks(network.pos, crafter, mask);
586 if (network.orchestrator == null) appliedSlotMask.remove(network.pos);
587 }
588
589 private static void applySlotLocks(CrafterPos pos, Crafter crafter, int mask) {
590 if (Objects.equals(appliedSlotMask.get(pos), mask)) return;
591 for (int slot = 0; slot < 9; slot++) {
592 crafter.setSlotDisabled(slot, (mask & (1 << slot)) == 0);
593 }
594 appliedSlotMask.put(pos, mask);
595 try { crafter.update(true, false); } catch (Throwable ignored) {}
596 }
597
598 private static Crafter liveCrafter(Block block) {
599 try {
600 BlockState state = block.getState(false);
601 if (state instanceof Crafter crafter) return crafter;
602 } catch (Throwable ignored) {}
603 return block.getState() instanceof Crafter crafter ? crafter : null;
604 }
605
606 private static void playTransferAnimation(Object owner, PipeRef pipe) {
607 if (pipe == null || !(owner instanceof ContainerPipesPlugin pipes)) return;
608 pipes.playTransferAnimation(pipe.raw);
609 }
610
611 private static void flashOutputLamp(Object owner, long connectionId) {
612 if (owner instanceof ContainerPipesPlugin pipes) pipes.flashCrafterOutputLamp(connectionId);
613 }
614
615 private static void playTransferEffects(Network network) {
616 if (!(plugin instanceof ContainerPipesPlugin pipes)) return;
617 if (network.outgoing != null) pipes.playTransferAnimation(network.outgoing.raw);
618 for (PipeRef incoming : network.incoming) pipes.playTransferAnimation(incoming.raw);
619 }
620
621 private static boolean stripIncomingFilters(Object owner) {
622 if (!(owner instanceof ContainerPipesPlugin pipes)) return false;
623 boolean stripped = false;
624 for (Network network : networks.values()) {
625 if (network.orchestrator == null) continue;
626 for (PipeRef incoming : network.incoming) {
627 if (pipes.clearPipeFilterIfPresent(incoming.id)) stripped = true;
628 }
629 }
630 return stripped;
631 }
632
633 private static void indexConnection(Object connection) {
634 try {
635 long id = ((Number) invoke(connection, "id")).longValue();
636 Object source = invoke(connection, "source");
637 Object destination = invoke(connection, "destination");
638 UUID world = (UUID) invoke(source, "world");
639 int sx = (int) invoke(source, "x");
640 int sy = (int) invoke(source, "y");
641 int sz = (int) invoke(source, "z");
642 String sourceFace = String.valueOf(invoke(source, "face"));
643 int dx = (int) invoke(destination, "x");
644 int dy = (int) invoke(destination, "y");
645 int dz = (int) invoke(destination, "z");
646
647 World w = Bukkit.getWorld(world);
648 if (w == null) return;
649
650 boolean sourceLoaded = w.isChunkLoaded(sx >> 4, sz >> 4);
651 boolean destLoaded = w.isChunkLoaded(dx >> 4, dz >> 4);
652 if (!sourceLoaded || !destLoaded) needsRetry = true;
653
654 Block sourceBlock = sourceLoaded ? w.getBlockAt(sx, sy, sz) : null;
655 Block destBlock = destLoaded ? w.getBlockAt(dx, dy, dz) : null;
656 PipeRef ref = new PipeRef(id, connection, sourceBlock, destBlock);
657
658 if (sourceBlock != null && sourceBlock.getType() == Material.CRAFTER) {
659 BlockFace output = outputFace(sourceBlock);
660 if (output != null && output.name().equals(sourceFace)) {
661 Network network = networks.computeIfAbsent(CrafterPos.of(sourceBlock), Network::new);
662 network.outgoing = ref;
663 network.setRecipe(readFilters(connection));
664 if (network.recipeMask != 0) network.orchestrator = ref;
665 }
666 }
667
668 if (destBlock != null && destBlock.getType() == Material.CRAFTER) {
669 Network network = networks.computeIfAbsent(CrafterPos.of(destBlock), Network::new);
670 network.incoming.add(ref);
671 }
672 } catch (Throwable ignored) {}
673 }
674
675 private static void reloadPerf(Object owner) {
676 Plugin configOwner = owner instanceof Plugin p ? p : plugin;
677 if (configOwner == null) return;
678 idleAfter = Math.max(1, configOwner.getConfig().getInt("performance.idle-after-failed-attempts", 3));
679 sleepProbe = Math.max(1, configOwner.getConfig().getInt("performance.sleeping-probe-interval-ticks", 200));
680 }
681
682 private static List<ItemStack> readFilters(Object connection) throws Exception {
683 List<ItemStack> filters = new ArrayList<>();
684 for (Object value : (List<?>) invoke(connection, "filter")) {
685 if (value instanceof ItemStack item && validItem(item)) filters.add(item.clone());
686 else filters.add(null);
687 }
688 return filters;
689 }
690
691 private static boolean validItem(ItemStack item) {
692 return item != null && !item.getType().isAir() && item.getAmount() > 0;
693 }
694
695 private static BlockFace parseFace(String name) {
696 try {
697 return BlockFace.valueOf(name.toUpperCase(Locale.ROOT));
698 } catch (IllegalArgumentException ignored) {
699 return null;
700 }
701 }
702
703 private static Object invoke(Object target, String name, Object... args) throws Exception {
704 Class<?> type = target.getClass();
705 String key = type.getName() + '#' + name + '#' + args.length;
706 Method method = methodCache.get(key);
707 if (method == null) {
708 method = findMethod(type, name, args.length);
709 if (method == null) throw new NoSuchMethodException(name);
710 method.setAccessible(true);
711 methodCache.put(key, method);
712 }
713 return method.invoke(target, args);
714 }
715
716 private static Method findMethod(Class<?> type, String name, int parameterCount) {
717 for (Method candidate : type.getMethods()) {
718 if (candidate.getName().equals(name) && candidate.getParameterCount() == parameterCount) return candidate;
719 }
720 for (Method candidate : type.getDeclaredMethods()) {
721 if (candidate.getName().equals(name) && candidate.getParameterCount() == parameterCount) return candidate;
722 }
723 return null;
724 }
725}