Add crafter output pipes with a 3x3 recipe grid and vanilla craft.
Filtered outputs pull laid-out ingredients and trigger the crafter; empty grids still capture vanilla crafts. Planner indexing and inventory wakes no longer rescan every connection on the hot path. Co-authored-by: Cursor <cursoragent@cursor.com>
@@ -1,5 +1,8 @@
1
1
package nl.timfalken.containerpipes;
2
2
3
import org.bukkit.block.Block;
4
import org.bukkit.inventory.ItemStack;
5
3
6
import java.lang.reflect.*;
4
7
import java.util.*;
5
8
import java.util.concurrent.ConcurrentHashMap;
@@ -49,6 +52,15 @@ public final class AdvancedEndpointsPatch {
49
52
if (location == null) return false;
50
53
Object block = call(location, "getBlock");
51
54
if (!"CRAFTER".equals(materialName(block))) return false;
55
if (block instanceof Block bukkitBlock
56
&& CrafterPipeManager.isOrchestrated(bukkitBlock)) {
57
return false;
58
}
59
if (block instanceof Block bukkitBlock
60
&& sourceStack instanceof ItemStack itemStack
61
&& !CrafterPipeManager.allowsIncomingInsert(bukkitBlock, itemStack)) {
62
return false;
63
}
52
64
Object crafter = call(block, "getState");
53
65
54
66
int size = ((Number) call(inventory, "getSize")).intValue();
@@ -237,7 +249,6 @@ public final class AdvancedEndpointsPatch {
237
249
if (block == null) return;
238
250
239
251
String clickedType = materialName(block);
240
boolean crafter = "CRAFTER".equals(clickedType);
241
252
boolean destinationLiquid = isCauldronMaterial(clickedType);
242
253
243
254
Object held = call(event, "getItem");
@@ -265,7 +276,7 @@ public final class AdvancedEndpointsPatch {
265
276
return;
266
277
}
267
278
268
if (!crafter && !destinationLiquid) return;
279
if (!destinationLiquid) return;
269
280
270
281
Object blockFace = call(event, "getBlockFace");
271
282
LiquidConnection endpointConnection = destinationLiquid ? liquidConnectionAt(block, blockFace) : null;
@@ -273,13 +284,6 @@ public final class AdvancedEndpointsPatch {
273
284
// Liquid pipes have no filter UI. Shears are still allowed through
274
285
// so the plugin's normal shift+shears removal path remains intact.
275
286
if (!shears) call(event, "setCancelled", new Class<?>[]{boolean.class}, true);
276
return;
277
}
278
279
// A Crafter is destination-only. First-clicking it as a source is a
280
// silent no-op, except shears on an existing ordinary item endpoint.
281
if (crafter && !shears) {
282
call(event, "setCancelled", new Class<?>[]{boolean.class}, true);
283
287
}
284
288
}
285
289
@@ -1,5 +1,8 @@1
package nl.timfalken.containerpipes;1
package nl.timfalken.containerpipes;2
2
3
import org.bukkit.block.Block;4
import org.bukkit.inventory.ItemStack;5
3
import java.lang.reflect.*;6
import java.lang.reflect.*;4
import java.util.*;7
import java.util.*;5
import java.util.concurrent.ConcurrentHashMap;8
import java.util.concurrent.ConcurrentHashMap;@@ -49,6 +52,15 @@ public final class AdvancedEndpointsPatch {49
if (location == null) return false;52
if (location == null) return false;50
Object block = call(location, "getBlock");53
Object block = call(location, "getBlock");51
if (!"CRAFTER".equals(materialName(block))) return false;54
if (!"CRAFTER".equals(materialName(block))) return false;55
if (block instanceof Block bukkitBlock56
&& CrafterPipeManager.isOrchestrated(bukkitBlock)) {57
return false;58
}59
if (block instanceof Block bukkitBlock60
&& sourceStack instanceof ItemStack itemStack61
&& !CrafterPipeManager.allowsIncomingInsert(bukkitBlock, itemStack)) {62
return false;63
}52
Object crafter = call(block, "getState");64
Object crafter = call(block, "getState");53
65
54
int size = ((Number) call(inventory, "getSize")).intValue();66
int size = ((Number) call(inventory, "getSize")).intValue();@@ -237,7 +249,6 @@ public final class AdvancedEndpointsPatch {237
if (block == null) return;249
if (block == null) return;238
250
239
String clickedType = materialName(block);251
String clickedType = materialName(block);240
boolean crafter = "CRAFTER".equals(clickedType);241
boolean destinationLiquid = isCauldronMaterial(clickedType);252
boolean destinationLiquid = isCauldronMaterial(clickedType);242
253
243
Object held = call(event, "getItem");254
Object held = call(event, "getItem");@@ -265,7 +276,7 @@ public final class AdvancedEndpointsPatch {265
return;276
return;266
}277
}267
278
268
if (!crafter && !destinationLiquid) return;279
if (!destinationLiquid) return;269
280
270
Object blockFace = call(event, "getBlockFace");281
Object blockFace = call(event, "getBlockFace");271
LiquidConnection endpointConnection = destinationLiquid ? liquidConnectionAt(block, blockFace) : null;282
LiquidConnection endpointConnection = destinationLiquid ? liquidConnectionAt(block, blockFace) : null;@@ -273,13 +284,6 @@ public final class AdvancedEndpointsPatch {273
// Liquid pipes have no filter UI. Shears are still allowed through284
// Liquid pipes have no filter UI. Shears are still allowed through274
// so the plugin's normal shift+shears removal path remains intact.285
// so the plugin's normal shift+shears removal path remains intact.275
if (!shears) call(event, "setCancelled", new Class<?>[]{boolean.class}, true);286
if (!shears) call(event, "setCancelled", new Class<?>[]{boolean.class}, true);276
return;277
}278
279
// A Crafter is destination-only. First-clicking it as a source is a280
// silent no-op, except shears on an existing ordinary item endpoint.281
if (crafter && !shears) {282
call(event, "setCancelled", new Class<?>[]{boolean.class}, true);283
}287
}284
}288
}285
289
@@ -4,7 +4,10 @@ import org.bukkit.*;
4
4
import org.bukkit.block.*;
5
5
import org.bukkit.command.*;
6
6
import org.bukkit.configuration.file.FileConfiguration;
7
import org.bukkit.block.data.Lightable;
7
8
import org.bukkit.entity.BlockDisplay;
9
import org.bukkit.entity.Entity;
10
import org.bukkit.entity.HumanEntity;
8
11
import org.bukkit.entity.Interaction;
9
12
import org.bukkit.entity.Player;
10
13
import org.bukkit.event.*;
@@ -46,6 +49,8 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
46
49
private final Map<UUID, Long> lastInteractions = new HashMap<>();
47
50
private final AtomicLong nextId = new AtomicLong(1);
48
51
private final Map<Long, FilterHolder> openFilters = new HashMap<>();
52
private final Map<Long, BukkitTask> crafterLampFlashes = new HashMap<>();
53
private final Map<Long, Integer> lastTransferAnimTick = new HashMap<>();
49
54
private File dataFile;
50
55
private boolean connectionFileWritable = true;
51
56
private BukkitTask transferTask;
@@ -62,6 +67,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
62
67
Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);
63
68
getLogger().info("ContainerPipes 1.8.0 enabled with " + connections.size() + " connection(s).");
64
69
AdvancedEndpointsPatch.enable(this);
70
CrafterPipeManager.enable(this);
65
71
}
66
72
67
73
@Override public void onDisable() {
@@ -70,6 +76,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
70
76
saveConnectionsNow();
71
77
removeAllDisplays();
72
78
selections.clear();
79
CrafterPipeManager.disable();
73
80
AdvancedEndpointsPatch.disable(this);
74
81
}
75
82
@@ -103,10 +110,22 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
103
110
Material cost = pipeCostMaterial();
104
111
boolean holdingCost = cost != null && held != null && held.getType() == cost;
105
112
if (!emptyHand && !shears && !holdingCost) return;
113
114
Endpoint clicked = endpoint(block, face);
115
if (CrafterPipeManager.isCrafter(block)) {
116
Selection activeSelection = selections.get(player.getUniqueId());
117
if (shears) {
118
if (findByEndpoint(clicked) == null) return;
119
} else if (activeSelection == null) {
120
Connection existing = findByEndpoint(clicked);
121
if (existing == null && !CrafterPipeManager.isOutputFace(block, face)) return;
122
}
123
}
124
106
125
event.setCancelled(true);
107
126
108
127
if (shears) {
109
Connection existing = findByEndpoint(endpoint(block, face));
128
Connection existing = findByEndpoint(clicked);
110
129
if (existing != null) {
111
130
removeConnection(existing.id, true);
112
131
send(player, "disconnected");
@@ -117,7 +136,6 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
117
136
return;
118
137
}
119
138
120
Endpoint clicked = endpoint(block, face);
121
139
Selection selection = selections.remove(player.getUniqueId());
122
140
if (selection == null) {
123
141
Connection existing = findByEndpoint(clicked);
@@ -134,6 +152,12 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
134
152
Endpoint source = selection.endpoint;
135
153
if (!source.world.equals(clicked.world)) { send(player, "different-world"); return; }
136
154
if (source.equals(clicked)) { send(player, "selection-cancelled"); return; }
155
World sourceWorld = Bukkit.getWorld(source.world);
156
if (sourceWorld != null && CrafterPipeManager.isCrafter(sourceWorld.getBlockAt(source.x, source.y, source.z))
157
&& !CrafterPipeManager.isOutputFace(sourceWorld.getBlockAt(source.x, source.y, source.z), source.face)) {
158
send(player, "selection-cancelled");
159
return;
160
}
137
161
if (findByEndpoint(source) != null || findByEndpoint(clicked) != null) { send(player, "side-in-use"); return; }
138
162
int maxRange = Math.max(1, getConfig().getInt("maximum-connection-range", 32));
139
163
if (source.distanceSquared(clicked) > maxRange * maxRange) { send(player, "too-far"); return; }
@@ -259,6 +283,11 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
259
283
if (destination instanceof BrewerInventory) return true; // slot legality is decided live via Paper/NMS canPlaceItem
260
284
if (destination instanceof ChiseledBookshelfInventory) return HopperStyleEndpoints.isBookshelfBook(item);
261
285
if (destination instanceof JukeboxInventory) return item.hasData(io.papermc.paper.datacomponent.DataComponentTypes.JUKEBOX_PLAYABLE);
286
if (block.getType() == Material.CRAFTER) {
287
if (CrafterPipeManager.isOrchestrated(block)) {
288
return CrafterPipeManager.allowsIncomingInsert(block, item);
289
}
290
}
262
291
return true;
263
292
}
264
293
@@ -332,9 +361,10 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
332
361
float pointScale = point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;
333
362
if(!world.isChunkLoaded(loc.getBlockX()>>4,loc.getBlockZ()>>4)) continue;
334
363
BlockDisplay d=world.spawn(loc, BlockDisplay.class, bd->{
335
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());
364
bd.setBlock(sourceSegmentData(c, point.type()==1, pipeMaterial, filteredSourceMaterial));
336
365
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));
337
366
bd.setPersistent(false); bd.addScoreboardTag("containerpipes"); bd.addScoreboardTag("containerpipes:"+c.id);
367
if (point.type()==1) bd.addScoreboardTag("containerpipes-source:"+c.id);
338
368
bd.setViewRange(1.0f); bd.setShadowRadius(0); bd.setShadowStrength(0);
339
369
});
340
370
ids.add(d.getUniqueId());
@@ -412,6 +442,90 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
412
442
if (c != null) spawnMissingDisplaysInChunk(c, chunk);
413
443
}
414
444
}
445
private org.bukkit.block.data.BlockData sourceSegmentData(Connection c, boolean sourceEndpoint,
446
Material pipeMaterial, Material filteredSourceMaterial) {
447
if (!sourceEndpoint) return pipeMaterial.createBlockData();
448
if (CrafterPipeManager.isFilteredCrafterOutput(c.id)) {
449
Material lamp = Material.matchMaterial(getConfig().getString("filtered-crafter-source-material", "minecraft:redstone_lamp"));
450
if (lamp == null || !lamp.isBlock()) lamp = Material.REDSTONE_LAMP;
451
return lamp.createBlockData();
452
}
453
return (c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData();
454
}
455
456
boolean clearPipeFilterIfPresent(long id) {
457
Connection old = connections.get(id);
458
if (old == null || !old.hasFilter()) return false;
459
clearPipeFilter(id);
460
return true;
461
}
462
463
void clearPipeFilter(long id) {
464
Connection old = connections.get(id);
465
if (old == null || !old.hasFilter()) return;
466
FilterHolder holder = openFilters.remove(id);
467
if (holder != null && holder.inventory != null) {
468
for (HumanEntity viewer : List.copyOf(holder.inventory.getViewers())) viewer.closeInventory();
469
}
470
Connection replacement = new Connection(old.id, old.source, old.destination, old.path, List.of());
471
unregisterConnection(old);
472
registerConnection(replacement);
473
spawnDisplays(replacement);
474
saveConnections();
475
}
476
477
void playTransferAnimation(Object connection) {
478
if (!(connection instanceof Connection c)) return;
479
int now = Bukkit.getCurrentTick();
480
int cooldown = Math.max(0, getConfig().getInt("particles.transfer-animation-cooldown-ticks", 100));
481
Integer previous = lastTransferAnimTick.get(c.id);
482
if (previous != null && now - previous < cooldown) return;
483
lastTransferAnimTick.put(c.id, now);
484
animateTransfer(c);
485
}
486
487
void flashCrafterOutputLamp(long id) {
488
BukkitTask previous = crafterLampFlashes.remove(id);
489
if (previous != null) previous.cancel();
490
BlockDisplay sourceDisplay = findSourceDisplay(id);
491
if (sourceDisplay == null) return;
492
Lightable lit = (Lightable) Material.REDSTONE_LAMP.createBlockData();
493
lit.setLit(true);
494
sourceDisplay.setBlock(lit);
495
crafterLampFlashes.put(id, Bukkit.getScheduler().runTaskLater(this, () -> {
496
crafterLampFlashes.remove(id);
497
if (!sourceDisplay.isValid()) return;
498
Lightable unlit = (Lightable) Material.REDSTONE_LAMP.createBlockData();
499
unlit.setLit(false);
500
sourceDisplay.setBlock(unlit);
501
}, 8L));
502
}
503
504
private BlockDisplay findSourceDisplay(long id) {
505
String sourceTag = "containerpipes-source:" + id;
506
List<UUID> ids = displayIds.get(id);
507
if (ids != null) {
508
for (UUID uuid : ids) {
509
Entity entity = Bukkit.getEntity(uuid);
510
if (entity instanceof BlockDisplay display && display.getScoreboardTags().contains(sourceTag)) {
511
return display;
512
}
513
}
514
for (UUID uuid : ids) {
515
Entity entity = Bukkit.getEntity(uuid);
516
if (entity instanceof BlockDisplay display) return display;
517
}
518
}
519
Connection connection = connections.get(id);
520
if (connection == null) return null;
521
World world = Bukkit.getWorld(connection.source.world);
522
if (world == null) return null;
523
Location at = connection.source.attachmentCenter(world, endpointScale("source-endpoint-scale"));
524
for (Entity entity : world.getNearbyEntities(at, 0.75, 0.75, 0.75)) {
525
if (entity instanceof BlockDisplay display && display.getScoreboardTags().contains(sourceTag)) return display;
526
}
527
return null;
528
}
415
529
private void removeDisplays(long id){for(UUID uuid:displayIds.getOrDefault(id,List.of())){var e=Bukkit.getEntity(uuid);if(e!=null)e.remove();}displayIds.remove(id);}
416
530
private void removeAllDisplays(){for(long id:List.copyOf(displayIds.keySet()))removeDisplays(id);}
417
531
private void removeDisplaysInChunk(Chunk chunk){
@@ -437,9 +551,10 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
437
551
if((loc.getBlockX()>>4)!=chunk.getX() || (loc.getBlockZ()>>4)!=chunk.getZ()) continue;
438
552
float pointScale=point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;
439
553
BlockDisplay d=world.spawn(loc,BlockDisplay.class,bd->{
440
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());
554
bd.setBlock(sourceSegmentData(c, point.type()==1, pipeMaterial, filteredSourceMaterial));
441
555
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));
442
556
bd.setPersistent(false);bd.addScoreboardTag("containerpipes");bd.addScoreboardTag("containerpipes:"+c.id);
557
if (point.type()==1) bd.addScoreboardTag("containerpipes-source:"+c.id);
443
558
bd.setViewRange(1.0f);bd.setShadowRadius(0);bd.setShadowStrength(0);
444
559
});
445
560
ids.add(d.getUniqueId());
@@ -617,6 +732,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
617
732
for (BlockPos p : c.path) routeIndex.put(new WorldBlockPos(world, p), c.id);
618
733
for (ChunkKey key : c.chunkKeys()) connectionsByChunk.computeIfAbsent(key, ignored -> new HashSet<>()).add(c.id);
619
734
AdvancedEndpointsPatch.connectionChanged(this, c, true);
735
CrafterPipeManager.connectionChanged(this);
620
736
}
621
737
622
738
private void unregisterConnection(Connection c) {
@@ -632,6 +748,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
632
748
if (ids.isEmpty()) connectionsByChunk.remove(key);
633
749
}
634
750
AdvancedEndpointsPatch.connectionChanged(this, c, false);
751
CrafterPipeManager.connectionChanged(this);
635
752
}
636
753
637
754
private Set<Long> connectionIdsInChunk(Chunk chunk) {
@@ -688,6 +805,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
688
805
connectionFileWritable=false;
689
806
getLogger().warning(loaded+" verbinding(en) geladen; "+skipped+" ongeldige regel(s) overgeslagen. Bestand blijft ongewijzigd (herstelmodus).");
690
807
}
808
CrafterPipeManager.connectionChanged(this);
691
809
} catch(Exception e) {
692
810
connectionFileWritable=false;
693
811
getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingenbestand niet lezen; bestand blijft ongewijzigd",e);
@@ -791,15 +909,32 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
791
909
}
792
910
private long connectionIdFrom(Set<String> tags){for(String tag:tags)if(tag.startsWith("containerpipes-filter:"))try{return Long.parseLong(tag.substring(tag.indexOf(':')+1));}catch(Exception ignored){}return -1;}
793
911
private void openFilter(Player player,long id){
912
if (CrafterPipeManager.blocksFilter(id)) return;
794
913
Connection c=connections.get(id);if(c==null)return;
795
FilterHolder holder=new FilterHolder(id);Inventory inv=Bukkit.createInventory(holder,InventoryType.HOPPER,filterTitle(player,id));holder.inventory=inv;
796
for(int i=0;i<Math.min(5,c.filter.size());i++){ItemStack item=c.filter.get(i);if(item!=null)inv.setItem(i,item.clone());}
914
boolean craftingGrid = CrafterPipeManager.usesCraftingGrid(id) || crafterOutputPipe(c);
915
int size = craftingGrid ? 9 : 5;
916
FilterHolder holder=new FilterHolder(id, size);
917
Inventory inv = craftingGrid
918
? Bukkit.createInventory(holder, InventoryType.DISPENSER, crafterRecipeTitle(player, id))
919
: Bukkit.createInventory(holder, InventoryType.HOPPER, filterTitle(player, id));
920
holder.inventory=inv;
921
for(int i=0;i<Math.min(size,c.filter.size());i++){ItemStack item=c.filter.get(i);if(item!=null)inv.setItem(i,item.clone());}
797
922
openFilters.put(id,holder);player.openInventory(inv);
798
923
}
924
private boolean crafterOutputPipe(Connection c) {
925
World world = Bukkit.getWorld(c.source.world);
926
if (world == null || !world.isChunkLoaded(c.source.x >> 4, c.source.z >> 4)) return false;
927
return CrafterPipeManager.usesCraftingGrid(world.getBlockAt(c.source.x, c.source.y, c.source.z), c.source.face);
928
}
929
private String crafterRecipeTitle(Player player, long id) {
930
String title = getConfig().getString("crafter-recipe-title." + playerLanguage(player), null);
931
if (title == null) title = getConfig().getString("crafter-recipe-title.en", "Crafter recipe #{id}");
932
return title.replace("{id}", Long.toString(id));
933
}
799
934
@EventHandler public void onFilterClick(InventoryClickEvent event){
800
935
if(!(event.getInventory().getHolder() instanceof FilterHolder holder))return;
801
936
if(event.getRawSlot()<0)return;
802
if(event.getRawSlot()>=5){if(event.isShiftClick())event.setCancelled(true);return;}
937
if(event.getRawSlot()>=holder.size){if(event.isShiftClick())event.setCancelled(true);return;}
803
938
event.setCancelled(true);
804
939
ItemStack cursor=event.getCursor();
805
940
if(cursor==null||cursor.getType().isAir())event.getInventory().setItem(event.getRawSlot(),null);
@@ -809,15 +944,23 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
809
944
@EventHandler public void onFilterDrag(InventoryDragEvent event){if(event.getInventory().getHolder() instanceof FilterHolder)event.setCancelled(true);}
810
945
@EventHandler public void onFilterClose(InventoryCloseEvent event){if(event.getInventory().getHolder() instanceof FilterHolder holder)updateFilter(holder.connectionId,event.getInventory());}
811
946
private void updateFilterOriginal(long id, Inventory inv) {
947
if (CrafterPipeManager.blocksFilter(id)) {
948
Connection existing = connections.get(id);
949
if (existing != null && existing.hasFilter()) clearPipeFilter(id);
950
return;
951
}
812
952
Connection old = connections.get(id);
813
953
if (old == null) return;
814
ArrayList<ItemStack> f = new ArrayList<>(5);
815
for (int i = 0; i < 5; i++) {
954
int size = Math.max(inv.getSize(), CrafterPipeManager.usesCraftingGrid(id) || crafterOutputPipe(old) ? 9 : 5);
955
if (size != 5 && size != 9) size = inv.getSize() >= 9 ? 9 : 5;
956
ArrayList<ItemStack> f = new ArrayList<>(size);
957
boolean craftingGrid = size == 9;
958
for (int i = 0; i < size; i++) {
816
959
ItemStack x = inv.getItem(i);
817
960
if (x != null) {
818
961
x = x.clone();
819
962
x.setAmount(1);
820
if (!destinationCanEverAccept(old, x)) {
963
if (!craftingGrid && !destinationCanEverAccept(old, x)) {
821
964
x = null;
822
965
inv.setItem(i, null);
823
966
}
@@ -833,9 +976,35 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
833
976
private void updateFilter(long id, Inventory inv) {
834
977
TransferPolicyPatch.sanitizeFilterAndUpdate(this, id, inv);
835
978
}
836
private static String encodeFilter(List<ItemStack> filter){if(filter==null||filter.isEmpty())return "";ArrayList<String> parts=new ArrayList<>();for(int i=0;i<5;i++){ItemStack x=i<filter.size()?filter.get(i):null;parts.add(x==null||x.getType().isAir()?"-":Base64.getUrlEncoder().withoutPadding().encodeToString(x.serializeAsBytes()));}return String.join(";",parts);}
837
private static List<ItemStack> decodeFilter(String encoded){if(encoded==null||encoded.isBlank())return List.of();ArrayList<ItemStack> out=new ArrayList<>(5);String[] parts=encoded.split(";",-1);for(int i=0;i<5;i++){String part=i<parts.length?parts[i]:"-";try{out.add(part.equals("-")||part.isBlank()?null:ItemStack.deserializeBytes(Base64.getUrlDecoder().decode(part)));}catch(Exception e){out.add(null);}}return Collections.unmodifiableList(out);}
838
private static final class FilterHolder implements InventoryHolder{final long connectionId;Inventory inventory;FilterHolder(long id){connectionId=id;}public Inventory getInventory(){return inventory;}}
979
private static String encodeFilter(List<ItemStack> filter){
980
if(filter==null||filter.isEmpty())return "";
981
int slots = filter.size() >= 9 ? 9 : 5;
982
ArrayList<String> parts=new ArrayList<>(slots);
983
for(int i=0;i<slots;i++){
984
ItemStack x=i<filter.size()?filter.get(i):null;
985
parts.add(x==null||x.getType().isAir()?"-":Base64.getUrlEncoder().withoutPadding().encodeToString(x.serializeAsBytes()));
986
}
987
return String.join(";",parts);
988
}
989
private static List<ItemStack> decodeFilter(String encoded){
990
if(encoded==null||encoded.isBlank())return List.of();
991
String[] parts=encoded.split(";",-1);
992
int slots = parts.length >= 9 ? 9 : 5;
993
ArrayList<ItemStack> out=new ArrayList<>(slots);
994
for(int i=0;i<slots;i++){
995
String part=i<parts.length?parts[i]:"-";
996
try{out.add(part.equals("-")||part.isBlank()?null:ItemStack.deserializeBytes(Base64.getUrlDecoder().decode(part)));}
997
catch(Exception e){out.add(null);}
998
}
999
return Collections.unmodifiableList(out);
1000
}
1001
private static final class FilterHolder implements InventoryHolder{
1002
final long connectionId;
1003
final int size;
1004
Inventory inventory;
1005
FilterHolder(long id, int size){connectionId=id;this.size=size;}
1006
public Inventory getInventory(){return inventory;}
1007
}
839
1008
840
1009
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
841
1010
if(!sender.hasPermission("containerpipes.admin"))return true;
@@ -848,6 +1017,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,
848
1017
reloadConfig();
849
1018
startTasks();
850
1019
refreshLoadedDisplays();
1020
CrafterPipeManager.connectionChanged(this);
851
1021
sender.sendMessage(commandText(sender, "reloaded"));
852
1022
}
853
1023
case "refresh" -> {
@@ -4,7 +4,10 @@ import org.bukkit.*;4
import org.bukkit.block.*;4
import org.bukkit.block.*;5
import org.bukkit.command.*;5
import org.bukkit.command.*;6
import org.bukkit.configuration.file.FileConfiguration;6
import org.bukkit.configuration.file.FileConfiguration;7
import org.bukkit.block.data.Lightable;7
import org.bukkit.entity.BlockDisplay;8
import org.bukkit.entity.BlockDisplay;9
import org.bukkit.entity.Entity;10
import org.bukkit.entity.HumanEntity;8
import org.bukkit.entity.Interaction;11
import org.bukkit.entity.Interaction;9
import org.bukkit.entity.Player;12
import org.bukkit.entity.Player;10
import org.bukkit.event.*;13
import org.bukkit.event.*;@@ -46,6 +49,8 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,46
private final Map<UUID, Long> lastInteractions = new HashMap<>();49
private final Map<UUID, Long> lastInteractions = new HashMap<>();47
private final AtomicLong nextId = new AtomicLong(1);50
private final AtomicLong nextId = new AtomicLong(1);48
private final Map<Long, FilterHolder> openFilters = new HashMap<>();51
private final Map<Long, FilterHolder> openFilters = new HashMap<>();52
private final Map<Long, BukkitTask> crafterLampFlashes = new HashMap<>();53
private final Map<Long, Integer> lastTransferAnimTick = new HashMap<>();49
private File dataFile;54
private File dataFile;50
private boolean connectionFileWritable = true;55
private boolean connectionFileWritable = true;51
private BukkitTask transferTask;56
private BukkitTask transferTask;@@ -62,6 +67,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,62
Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);67
Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays);63
getLogger().info("ContainerPipes 1.8.0 enabled with " + connections.size() + " connection(s).");68
getLogger().info("ContainerPipes 1.8.0 enabled with " + connections.size() + " connection(s).");64
AdvancedEndpointsPatch.enable(this);69
AdvancedEndpointsPatch.enable(this);70
CrafterPipeManager.enable(this);65
}71
}66
72
67
@Override public void onDisable() {73
@Override public void onDisable() {@@ -70,6 +76,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,70
saveConnectionsNow();76
saveConnectionsNow();71
removeAllDisplays();77
removeAllDisplays();72
selections.clear();78
selections.clear();79
CrafterPipeManager.disable();73
AdvancedEndpointsPatch.disable(this);80
AdvancedEndpointsPatch.disable(this);74
}81
}75
82
@@ -103,10 +110,22 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,103
Material cost = pipeCostMaterial();110
Material cost = pipeCostMaterial();104
boolean holdingCost = cost != null && held != null && held.getType() == cost;111
boolean holdingCost = cost != null && held != null && held.getType() == cost;105
if (!emptyHand && !shears && !holdingCost) return;112
if (!emptyHand && !shears && !holdingCost) return;113
114
Endpoint clicked = endpoint(block, face);115
if (CrafterPipeManager.isCrafter(block)) {116
Selection activeSelection = selections.get(player.getUniqueId());117
if (shears) {118
if (findByEndpoint(clicked) == null) return;119
} else if (activeSelection == null) {120
Connection existing = findByEndpoint(clicked);121
if (existing == null && !CrafterPipeManager.isOutputFace(block, face)) return;122
}123
}124
106
event.setCancelled(true);125
event.setCancelled(true);107
126
108
if (shears) {127
if (shears) {109
Connection existing = findByEndpoint(endpoint(block, face));128
Connection existing = findByEndpoint(clicked);110
if (existing != null) {129
if (existing != null) {111
removeConnection(existing.id, true);130
removeConnection(existing.id, true);112
send(player, "disconnected");131
send(player, "disconnected");@@ -117,7 +136,6 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,117
return;136
return;118
}137
}119
138
120
Endpoint clicked = endpoint(block, face);121
Selection selection = selections.remove(player.getUniqueId());139
Selection selection = selections.remove(player.getUniqueId());122
if (selection == null) {140
if (selection == null) {123
Connection existing = findByEndpoint(clicked);141
Connection existing = findByEndpoint(clicked);@@ -134,6 +152,12 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,134
Endpoint source = selection.endpoint;152
Endpoint source = selection.endpoint;135
if (!source.world.equals(clicked.world)) { send(player, "different-world"); return; }153
if (!source.world.equals(clicked.world)) { send(player, "different-world"); return; }136
if (source.equals(clicked)) { send(player, "selection-cancelled"); return; }154
if (source.equals(clicked)) { send(player, "selection-cancelled"); return; }155
World sourceWorld = Bukkit.getWorld(source.world);156
if (sourceWorld != null && CrafterPipeManager.isCrafter(sourceWorld.getBlockAt(source.x, source.y, source.z))157
&& !CrafterPipeManager.isOutputFace(sourceWorld.getBlockAt(source.x, source.y, source.z), source.face)) {158
send(player, "selection-cancelled");159
return;160
}137
if (findByEndpoint(source) != null || findByEndpoint(clicked) != null) { send(player, "side-in-use"); return; }161
if (findByEndpoint(source) != null || findByEndpoint(clicked) != null) { send(player, "side-in-use"); return; }138
int maxRange = Math.max(1, getConfig().getInt("maximum-connection-range", 32));162
int maxRange = Math.max(1, getConfig().getInt("maximum-connection-range", 32));139
if (source.distanceSquared(clicked) > maxRange * maxRange) { send(player, "too-far"); return; }163
if (source.distanceSquared(clicked) > maxRange * maxRange) { send(player, "too-far"); return; }@@ -259,6 +283,11 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,259
if (destination instanceof BrewerInventory) return true; // slot legality is decided live via Paper/NMS canPlaceItem283
if (destination instanceof BrewerInventory) return true; // slot legality is decided live via Paper/NMS canPlaceItem260
if (destination instanceof ChiseledBookshelfInventory) return HopperStyleEndpoints.isBookshelfBook(item);284
if (destination instanceof ChiseledBookshelfInventory) return HopperStyleEndpoints.isBookshelfBook(item);261
if (destination instanceof JukeboxInventory) return item.hasData(io.papermc.paper.datacomponent.DataComponentTypes.JUKEBOX_PLAYABLE);285
if (destination instanceof JukeboxInventory) return item.hasData(io.papermc.paper.datacomponent.DataComponentTypes.JUKEBOX_PLAYABLE);286
if (block.getType() == Material.CRAFTER) {287
if (CrafterPipeManager.isOrchestrated(block)) {288
return CrafterPipeManager.allowsIncomingInsert(block, item);289
}290
}262
return true;291
return true;263
}292
}264
293
@@ -332,9 +361,10 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,332
float pointScale = point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;361
float pointScale = point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;333
if(!world.isChunkLoaded(loc.getBlockX()>>4,loc.getBlockZ()>>4)) continue;362
if(!world.isChunkLoaded(loc.getBlockX()>>4,loc.getBlockZ()>>4)) continue;334
BlockDisplay d=world.spawn(loc, BlockDisplay.class, bd->{363
BlockDisplay d=world.spawn(loc, BlockDisplay.class, bd->{335
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());364
bd.setBlock(sourceSegmentData(c, point.type()==1, pipeMaterial, filteredSourceMaterial));336
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));365
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));337
bd.setPersistent(false); bd.addScoreboardTag("containerpipes"); bd.addScoreboardTag("containerpipes:"+c.id);366
bd.setPersistent(false); bd.addScoreboardTag("containerpipes"); bd.addScoreboardTag("containerpipes:"+c.id);367
if (point.type()==1) bd.addScoreboardTag("containerpipes-source:"+c.id);338
bd.setViewRange(1.0f); bd.setShadowRadius(0); bd.setShadowStrength(0);368
bd.setViewRange(1.0f); bd.setShadowRadius(0); bd.setShadowStrength(0);339
});369
});340
ids.add(d.getUniqueId());370
ids.add(d.getUniqueId());@@ -412,6 +442,90 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,412
if (c != null) spawnMissingDisplaysInChunk(c, chunk);442
if (c != null) spawnMissingDisplaysInChunk(c, chunk);413
}443
}414
}444
}445
private org.bukkit.block.data.BlockData sourceSegmentData(Connection c, boolean sourceEndpoint,446
Material pipeMaterial, Material filteredSourceMaterial) {447
if (!sourceEndpoint) return pipeMaterial.createBlockData();448
if (CrafterPipeManager.isFilteredCrafterOutput(c.id)) {449
Material lamp = Material.matchMaterial(getConfig().getString("filtered-crafter-source-material", "minecraft:redstone_lamp"));450
if (lamp == null || !lamp.isBlock()) lamp = Material.REDSTONE_LAMP;451
return lamp.createBlockData();452
}453
return (c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData();454
}455
456
boolean clearPipeFilterIfPresent(long id) {457
Connection old = connections.get(id);458
if (old == null || !old.hasFilter()) return false;459
clearPipeFilter(id);460
return true;461
}462
463
void clearPipeFilter(long id) {464
Connection old = connections.get(id);465
if (old == null || !old.hasFilter()) return;466
FilterHolder holder = openFilters.remove(id);467
if (holder != null && holder.inventory != null) {468
for (HumanEntity viewer : List.copyOf(holder.inventory.getViewers())) viewer.closeInventory();469
}470
Connection replacement = new Connection(old.id, old.source, old.destination, old.path, List.of());471
unregisterConnection(old);472
registerConnection(replacement);473
spawnDisplays(replacement);474
saveConnections();475
}476
477
void playTransferAnimation(Object connection) {478
if (!(connection instanceof Connection c)) return;479
int now = Bukkit.getCurrentTick();480
int cooldown = Math.max(0, getConfig().getInt("particles.transfer-animation-cooldown-ticks", 100));481
Integer previous = lastTransferAnimTick.get(c.id);482
if (previous != null && now - previous < cooldown) return;483
lastTransferAnimTick.put(c.id, now);484
animateTransfer(c);485
}486
487
void flashCrafterOutputLamp(long id) {488
BukkitTask previous = crafterLampFlashes.remove(id);489
if (previous != null) previous.cancel();490
BlockDisplay sourceDisplay = findSourceDisplay(id);491
if (sourceDisplay == null) return;492
Lightable lit = (Lightable) Material.REDSTONE_LAMP.createBlockData();493
lit.setLit(true);494
sourceDisplay.setBlock(lit);495
crafterLampFlashes.put(id, Bukkit.getScheduler().runTaskLater(this, () -> {496
crafterLampFlashes.remove(id);497
if (!sourceDisplay.isValid()) return;498
Lightable unlit = (Lightable) Material.REDSTONE_LAMP.createBlockData();499
unlit.setLit(false);500
sourceDisplay.setBlock(unlit);501
}, 8L));502
}503
504
private BlockDisplay findSourceDisplay(long id) {505
String sourceTag = "containerpipes-source:" + id;506
List<UUID> ids = displayIds.get(id);507
if (ids != null) {508
for (UUID uuid : ids) {509
Entity entity = Bukkit.getEntity(uuid);510
if (entity instanceof BlockDisplay display && display.getScoreboardTags().contains(sourceTag)) {511
return display;512
}513
}514
for (UUID uuid : ids) {515
Entity entity = Bukkit.getEntity(uuid);516
if (entity instanceof BlockDisplay display) return display;517
}518
}519
Connection connection = connections.get(id);520
if (connection == null) return null;521
World world = Bukkit.getWorld(connection.source.world);522
if (world == null) return null;523
Location at = connection.source.attachmentCenter(world, endpointScale("source-endpoint-scale"));524
for (Entity entity : world.getNearbyEntities(at, 0.75, 0.75, 0.75)) {525
if (entity instanceof BlockDisplay display && display.getScoreboardTags().contains(sourceTag)) return display;526
}527
return null;528
}415
private void removeDisplays(long id){for(UUID uuid:displayIds.getOrDefault(id,List.of())){var e=Bukkit.getEntity(uuid);if(e!=null)e.remove();}displayIds.remove(id);}529
private void removeDisplays(long id){for(UUID uuid:displayIds.getOrDefault(id,List.of())){var e=Bukkit.getEntity(uuid);if(e!=null)e.remove();}displayIds.remove(id);}416
private void removeAllDisplays(){for(long id:List.copyOf(displayIds.keySet()))removeDisplays(id);}530
private void removeAllDisplays(){for(long id:List.copyOf(displayIds.keySet()))removeDisplays(id);}417
private void removeDisplaysInChunk(Chunk chunk){531
private void removeDisplaysInChunk(Chunk chunk){@@ -437,9 +551,10 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,437
if((loc.getBlockX()>>4)!=chunk.getX() || (loc.getBlockZ()>>4)!=chunk.getZ()) continue;551
if((loc.getBlockX()>>4)!=chunk.getX() || (loc.getBlockZ()>>4)!=chunk.getZ()) continue;438
float pointScale=point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;552
float pointScale=point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale;439
BlockDisplay d=world.spawn(loc,BlockDisplay.class,bd->{553
BlockDisplay d=world.spawn(loc,BlockDisplay.class,bd->{440
bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData());554
bd.setBlock(sourceSegmentData(c, point.type()==1, pipeMaterial, filteredSourceMaterial));441
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));555
bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f()));442
bd.setPersistent(false);bd.addScoreboardTag("containerpipes");bd.addScoreboardTag("containerpipes:"+c.id);556
bd.setPersistent(false);bd.addScoreboardTag("containerpipes");bd.addScoreboardTag("containerpipes:"+c.id);557
if (point.type()==1) bd.addScoreboardTag("containerpipes-source:"+c.id);443
bd.setViewRange(1.0f);bd.setShadowRadius(0);bd.setShadowStrength(0);558
bd.setViewRange(1.0f);bd.setShadowRadius(0);bd.setShadowStrength(0);444
});559
});445
ids.add(d.getUniqueId());560
ids.add(d.getUniqueId());@@ -617,6 +732,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,617
for (BlockPos p : c.path) routeIndex.put(new WorldBlockPos(world, p), c.id);732
for (BlockPos p : c.path) routeIndex.put(new WorldBlockPos(world, p), c.id);618
for (ChunkKey key : c.chunkKeys()) connectionsByChunk.computeIfAbsent(key, ignored -> new HashSet<>()).add(c.id);733
for (ChunkKey key : c.chunkKeys()) connectionsByChunk.computeIfAbsent(key, ignored -> new HashSet<>()).add(c.id);619
AdvancedEndpointsPatch.connectionChanged(this, c, true);734
AdvancedEndpointsPatch.connectionChanged(this, c, true);735
CrafterPipeManager.connectionChanged(this);620
}736
}621
737
622
private void unregisterConnection(Connection c) {738
private void unregisterConnection(Connection c) {@@ -632,6 +748,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,632
if (ids.isEmpty()) connectionsByChunk.remove(key);748
if (ids.isEmpty()) connectionsByChunk.remove(key);633
}749
}634
AdvancedEndpointsPatch.connectionChanged(this, c, false);750
AdvancedEndpointsPatch.connectionChanged(this, c, false);751
CrafterPipeManager.connectionChanged(this);635
}752
}636
753
637
private Set<Long> connectionIdsInChunk(Chunk chunk) {754
private Set<Long> connectionIdsInChunk(Chunk chunk) {@@ -688,6 +805,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,688
connectionFileWritable=false;805
connectionFileWritable=false;689
getLogger().warning(loaded+" verbinding(en) geladen; "+skipped+" ongeldige regel(s) overgeslagen. Bestand blijft ongewijzigd (herstelmodus).");806
getLogger().warning(loaded+" verbinding(en) geladen; "+skipped+" ongeldige regel(s) overgeslagen. Bestand blijft ongewijzigd (herstelmodus).");690
}807
}808
CrafterPipeManager.connectionChanged(this);691
} catch(Exception e) {809
} catch(Exception e) {692
connectionFileWritable=false;810
connectionFileWritable=false;693
getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingenbestand niet lezen; bestand blijft ongewijzigd",e);811
getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingenbestand niet lezen; bestand blijft ongewijzigd",e);@@ -791,15 +909,32 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,791
}909
}792
private long connectionIdFrom(Set<String> tags){for(String tag:tags)if(tag.startsWith("containerpipes-filter:"))try{return Long.parseLong(tag.substring(tag.indexOf(':')+1));}catch(Exception ignored){}return -1;}910
private long connectionIdFrom(Set<String> tags){for(String tag:tags)if(tag.startsWith("containerpipes-filter:"))try{return Long.parseLong(tag.substring(tag.indexOf(':')+1));}catch(Exception ignored){}return -1;}793
private void openFilter(Player player,long id){911
private void openFilter(Player player,long id){912
if (CrafterPipeManager.blocksFilter(id)) return;794
Connection c=connections.get(id);if(c==null)return;913
Connection c=connections.get(id);if(c==null)return;795
FilterHolder holder=new FilterHolder(id);Inventory inv=Bukkit.createInventory(holder,InventoryType.HOPPER,filterTitle(player,id));holder.inventory=inv;914
boolean craftingGrid = CrafterPipeManager.usesCraftingGrid(id) || crafterOutputPipe(c);796
for(int i=0;i<Math.min(5,c.filter.size());i++){ItemStack item=c.filter.get(i);if(item!=null)inv.setItem(i,item.clone());}915
int size = craftingGrid ? 9 : 5;916
FilterHolder holder=new FilterHolder(id, size);917
Inventory inv = craftingGrid918
? Bukkit.createInventory(holder, InventoryType.DISPENSER, crafterRecipeTitle(player, id))919
: Bukkit.createInventory(holder, InventoryType.HOPPER, filterTitle(player, id));920
holder.inventory=inv;921
for(int i=0;i<Math.min(size,c.filter.size());i++){ItemStack item=c.filter.get(i);if(item!=null)inv.setItem(i,item.clone());}797
openFilters.put(id,holder);player.openInventory(inv);922
openFilters.put(id,holder);player.openInventory(inv);798
}923
}924
private boolean crafterOutputPipe(Connection c) {925
World world = Bukkit.getWorld(c.source.world);926
if (world == null || !world.isChunkLoaded(c.source.x >> 4, c.source.z >> 4)) return false;927
return CrafterPipeManager.usesCraftingGrid(world.getBlockAt(c.source.x, c.source.y, c.source.z), c.source.face);928
}929
private String crafterRecipeTitle(Player player, long id) {930
String title = getConfig().getString("crafter-recipe-title." + playerLanguage(player), null);931
if (title == null) title = getConfig().getString("crafter-recipe-title.en", "Crafter recipe #{id}");932
return title.replace("{id}", Long.toString(id));933
}799
@EventHandler public void onFilterClick(InventoryClickEvent event){934
@EventHandler public void onFilterClick(InventoryClickEvent event){800
if(!(event.getInventory().getHolder() instanceof FilterHolder holder))return;935
if(!(event.getInventory().getHolder() instanceof FilterHolder holder))return;801
if(event.getRawSlot()<0)return;936
if(event.getRawSlot()<0)return;802
if(event.getRawSlot()>=5){if(event.isShiftClick())event.setCancelled(true);return;}937
if(event.getRawSlot()>=holder.size){if(event.isShiftClick())event.setCancelled(true);return;}803
event.setCancelled(true);938
event.setCancelled(true);804
ItemStack cursor=event.getCursor();939
ItemStack cursor=event.getCursor();805
if(cursor==null||cursor.getType().isAir())event.getInventory().setItem(event.getRawSlot(),null);940
if(cursor==null||cursor.getType().isAir())event.getInventory().setItem(event.getRawSlot(),null);@@ -809,15 +944,23 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,809
@EventHandler public void onFilterDrag(InventoryDragEvent event){if(event.getInventory().getHolder() instanceof FilterHolder)event.setCancelled(true);}944
@EventHandler public void onFilterDrag(InventoryDragEvent event){if(event.getInventory().getHolder() instanceof FilterHolder)event.setCancelled(true);}810
@EventHandler public void onFilterClose(InventoryCloseEvent event){if(event.getInventory().getHolder() instanceof FilterHolder holder)updateFilter(holder.connectionId,event.getInventory());}945
@EventHandler public void onFilterClose(InventoryCloseEvent event){if(event.getInventory().getHolder() instanceof FilterHolder holder)updateFilter(holder.connectionId,event.getInventory());}811
private void updateFilterOriginal(long id, Inventory inv) {946
private void updateFilterOriginal(long id, Inventory inv) {947
if (CrafterPipeManager.blocksFilter(id)) {948
Connection existing = connections.get(id);949
if (existing != null && existing.hasFilter()) clearPipeFilter(id);950
return;951
}812
Connection old = connections.get(id);952
Connection old = connections.get(id);813
if (old == null) return;953
if (old == null) return;814
ArrayList<ItemStack> f = new ArrayList<>(5);954
int size = Math.max(inv.getSize(), CrafterPipeManager.usesCraftingGrid(id) || crafterOutputPipe(old) ? 9 : 5);815
for (int i = 0; i < 5; i++) {955
if (size != 5 && size != 9) size = inv.getSize() >= 9 ? 9 : 5;956
ArrayList<ItemStack> f = new ArrayList<>(size);957
boolean craftingGrid = size == 9;958
for (int i = 0; i < size; i++) {816
ItemStack x = inv.getItem(i);959
ItemStack x = inv.getItem(i);817
if (x != null) {960
if (x != null) {818
x = x.clone();961
x = x.clone();819
x.setAmount(1);962
x.setAmount(1);820
if (!destinationCanEverAccept(old, x)) {963
if (!craftingGrid && !destinationCanEverAccept(old, x)) {821
x = null;964
x = null;822
inv.setItem(i, null);965
inv.setItem(i, null);823
}966
}@@ -833,9 +976,35 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,833
private void updateFilter(long id, Inventory inv) {976
private void updateFilter(long id, Inventory inv) {834
TransferPolicyPatch.sanitizeFilterAndUpdate(this, id, inv);977
TransferPolicyPatch.sanitizeFilterAndUpdate(this, id, inv);835
}978
}836
private static String encodeFilter(List<ItemStack> filter){if(filter==null||filter.isEmpty())return "";ArrayList<String> parts=new ArrayList<>();for(int i=0;i<5;i++){ItemStack x=i<filter.size()?filter.get(i):null;parts.add(x==null||x.getType().isAir()?"-":Base64.getUrlEncoder().withoutPadding().encodeToString(x.serializeAsBytes()));}return String.join(";",parts);}979
private static String encodeFilter(List<ItemStack> filter){837
private static List<ItemStack> decodeFilter(String encoded){if(encoded==null||encoded.isBlank())return List.of();ArrayList<ItemStack> out=new ArrayList<>(5);String[] parts=encoded.split(";",-1);for(int i=0;i<5;i++){String part=i<parts.length?parts[i]:"-";try{out.add(part.equals("-")||part.isBlank()?null:ItemStack.deserializeBytes(Base64.getUrlDecoder().decode(part)));}catch(Exception e){out.add(null);}}return Collections.unmodifiableList(out);}980
if(filter==null||filter.isEmpty())return "";838
private static final class FilterHolder implements InventoryHolder{final long connectionId;Inventory inventory;FilterHolder(long id){connectionId=id;}public Inventory getInventory(){return inventory;}}981
int slots = filter.size() >= 9 ? 9 : 5;982
ArrayList<String> parts=new ArrayList<>(slots);983
for(int i=0;i<slots;i++){984
ItemStack x=i<filter.size()?filter.get(i):null;985
parts.add(x==null||x.getType().isAir()?"-":Base64.getUrlEncoder().withoutPadding().encodeToString(x.serializeAsBytes()));986
}987
return String.join(";",parts);988
}989
private static List<ItemStack> decodeFilter(String encoded){990
if(encoded==null||encoded.isBlank())return List.of();991
String[] parts=encoded.split(";",-1);992
int slots = parts.length >= 9 ? 9 : 5;993
ArrayList<ItemStack> out=new ArrayList<>(slots);994
for(int i=0;i<slots;i++){995
String part=i<parts.length?parts[i]:"-";996
try{out.add(part.equals("-")||part.isBlank()?null:ItemStack.deserializeBytes(Base64.getUrlDecoder().decode(part)));}997
catch(Exception e){out.add(null);}998
}999
return Collections.unmodifiableList(out);1000
}1001
private static final class FilterHolder implements InventoryHolder{1002
final long connectionId;1003
final int size;1004
Inventory inventory;1005
FilterHolder(long id, int size){connectionId=id;this.size=size;}1006
public Inventory getInventory(){return inventory;}1007
}839
1008
840
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {1009
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {841
if(!sender.hasPermission("containerpipes.admin"))return true;1010
if(!sender.hasPermission("containerpipes.admin"))return true;@@ -848,6 +1017,7 @@ public final class ContainerPipesPlugin extends JavaPlugin implements Listener,848
reloadConfig();1017
reloadConfig();849
startTasks();1018
startTasks();850
refreshLoadedDisplays();1019
refreshLoadedDisplays();1020
CrafterPipeManager.connectionChanged(this);851
sender.sendMessage(commandText(sender, "reloaded"));1021
sender.sendMessage(commandText(sender, "reloaded"));852
}1022
}853
case "refresh" -> {1023
case "refresh" -> {@@ -0,0 +1,918 @@
1
package nl.timfalken.containerpipes;
2
3
import org.bukkit.Bukkit;
4
import org.bukkit.Material;
5
import org.bukkit.World;
6
import org.bukkit.block.Block;
7
import org.bukkit.block.BlockFace;
8
import org.bukkit.block.BlockState;
9
import org.bukkit.block.Crafter;
10
import org.bukkit.event.EventHandler;
11
import org.bukkit.event.EventPriority;
12
import org.bukkit.event.Listener;
13
import org.bukkit.event.block.CrafterCraftEvent;
14
import org.bukkit.inventory.Inventory;
15
import org.bukkit.inventory.ItemStack;
16
import org.bukkit.plugin.Plugin;
17
18
import java.lang.reflect.Field;
19
import java.lang.reflect.Method;
20
import 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
*/
28
public 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
}
@@ -0,0 +1,918 @@1
package nl.timfalken.containerpipes;2
3
import org.bukkit.Bukkit;4
import org.bukkit.Material;5
import org.bukkit.World;6
import org.bukkit.block.Block;7
import org.bukkit.block.BlockFace;8
import org.bukkit.block.BlockState;9
import org.bukkit.block.Crafter;10
import org.bukkit.event.EventHandler;11
import org.bukkit.event.EventPriority;12
import org.bukkit.event.Listener;13
import org.bukkit.event.block.CrafterCraftEvent;14
import org.bukkit.inventory.Inventory;15
import org.bukkit.inventory.ItemStack;16
import org.bukkit.plugin.Plugin;17
18
import java.lang.reflect.Field;19
import java.lang.reflect.Method;20
import java.util.*;21
22
/**23
* Crafter output pipes use a 3x3 recipe grid. Incoming pipes are slaved and24
* 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 crafter26
* fails and this network sleeps until an inventory/craft event wakes it.27
*/28
public 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 != null756
&& 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() == invWorld786
&& source.block.getX() == invX787
&& source.block.getY() == invY788
&& 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
}@@ -13,6 +13,7 @@ import org.bukkit.block.DoubleChest;
13
13
import org.bukkit.block.data.BlockData;
14
14
import org.bukkit.block.data.Directional;
15
15
import org.bukkit.configuration.file.FileConfiguration;
16
import org.bukkit.event.inventory.InventoryType;
16
17
import org.bukkit.inventory.BrewerInventory;
17
18
import org.bukkit.inventory.ChiseledBookshelfInventory;
18
19
import org.bukkit.inventory.DecoratedPotInventory;
@@ -48,6 +49,7 @@ public final class OptimizedTransferPlanner {
48
49
state.tick();
49
50
state.callPlugin("refreshSelectionParticles");
50
51
state.callPlugin("expireSelections");
52
CrafterPipeManager.tick(plugin);
51
53
} catch (Throwable t) {
52
54
log(plugin, "Direct transfer planner failed", t);
53
55
}
@@ -67,6 +69,15 @@ public final class OptimizedTransferPlanner {
67
69
* rebuild here preferable to allowing stale routing state for up to the
68
70
* periodic fingerprint interval.
69
71
*/
72
public static void invalidateBlock(Object plugin, Block block) {
73
if (plugin == null || block == null) return;
74
try {
75
State state = STATES.get(plugin);
76
if (state == null) return;
77
state.wakeBlock(block);
78
} catch (Throwable ignored) {}
79
}
80
70
81
public static void connectionChanged(Object plugin) {
71
82
try { STATES.computeIfAbsent(plugin, State::new).rebuild(true); }
72
83
catch (Throwable t) { log(plugin, "Connection topology refresh failed", t); }
@@ -277,6 +288,8 @@ public final class OptimizedTransferPlanner {
277
288
for (Object rawConnection : raw.values()) {
278
289
try {
279
290
ConnectionView connection = ConnectionView.read(rawConnection);
291
if (CrafterPipeManager.isSlavedIncoming(connection.id)
292
|| CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;
280
293
ContainerKey sourceKey = endpointKey(connection.source);
281
294
groups.computeIfAbsent(sourceKey, Group::new).connections.add(connection);
282
295
} catch (Throwable t) {
@@ -303,6 +316,7 @@ public final class OptimizedTransferPlanner {
303
316
void wakeInventory(Inventory inventory) {
304
317
ContainerKey key = inventoryKey(inventory);
305
318
if (key != null) invalidateAndWakeKey(key);
319
if (CrafterPipeManager.hasOrchestrators()) CrafterPipeManager.invalidateInventory(inventory);
306
320
}
307
321
308
322
void invalidateAndWakeKey(ContainerKey key) {
@@ -365,6 +379,7 @@ public final class OptimizedTransferPlanner {
365
379
// Dispenser/dropper/crafter: empty bucket ↔ water/lava/powder-snow
366
380
// bucket (and other dispense mutations) never open an inventory GUI.
367
381
"org.bukkit.event.block.BlockDispenseEvent",
382
"org.bukkit.event.block.CrafterCraftEvent",
368
383
"org.bukkit.event.world.ChunkLoadEvent",
369
384
"org.bukkit.event.world.ChunkUnloadEvent"
370
385
};
@@ -426,10 +441,14 @@ public final class OptimizedTransferPlanner {
426
441
wakeBlock(block);
427
442
wakeDispenseTarget(block);
428
443
}, 1L);
444
} else if (name.endsWith("CrafterCraftEvent")) {
445
Block block = (Block) call(event, "getBlock");
446
schedule(() -> wakeBlock(block), 1L);
429
447
} else if (name.endsWith("ChunkLoadEvent") || name.endsWith("ChunkUnloadEvent")) {
430
448
// Double-chest canonical identities can change as either half loads.
431
449
lastConnectionCount = -1;
432
450
for (Group group : groups.values()) active.add(group);
451
CrafterPipeManager.chunksChanged();
433
452
}
434
453
} catch (Throwable t) {
435
454
// A missed event must never stall the network permanently; emergency
@@ -446,6 +465,7 @@ public final class OptimizedTransferPlanner {
446
465
}
447
466
Inventory inventory = inventoryOf(block);
448
467
if (inventory != null) wakeInventory(inventory);
468
else if (CrafterPipeManager.hasOrchestrators()) CrafterPipeManager.invalidateBlock(block);
449
469
}
450
470
451
471
void wakeDispenseTarget(Block dispenser) {
@@ -484,6 +504,8 @@ public final class OptimizedTransferPlanner {
484
504
485
505
void rebuildCache() {
486
506
for (ConnectionView connection : connections) {
507
if (CrafterPipeManager.isSlavedIncoming(connection.id)) continue;
508
if (CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;
487
509
if (connection.filters.isEmpty()) unfiltered.add(connection);
488
510
else {
489
511
filtered.add(connection);
@@ -503,7 +525,8 @@ public final class OptimizedTransferPlanner {
503
525
}
504
526
Inventory source = inventoryAt(connections.get(0).source);
505
527
if (source == null || source instanceof FurnaceInventory || source instanceof BrewerInventory
506
|| source instanceof JukeboxInventory) {
528
|| source instanceof JukeboxInventory
529
|| source.getType() == InventoryType.CRAFTER) {
507
530
cycleBudget = null;
508
531
return;
509
532
}
@@ -589,6 +612,10 @@ public final class OptimizedTransferPlanner {
589
612
Inventory source = inventoryAt(connections.get(0).source);
590
613
if (source == null) return RunResult.NO_MOVE;
591
614
615
if (source.getType() == InventoryType.CRAFTER) {
616
return RunResult.NO_MOVE;
617
}
618
592
619
// Furnaces are special: only the output slot is a legal source.
593
620
if (source instanceof FurnaceInventory furnace) {
594
621
boolean moved = false;
@@ -821,13 +848,18 @@ public final class OptimizedTransferPlanner {
821
848
* restart the search from slot 0 so first-slot/merge preference stays correct.
822
849
*/
823
850
boolean insertOne(ItemStack source) {
824
// Crafters are destination-only and deliberately bypass the normal
825
// destination slot cache. Query their live disabled-slot state and
826
// use vanilla-equivalent hopper insertion ordering instead.
827
if (AdvancedEndpointsPatch.isCrafterInventory(inventory)) {
851
if (inventory.getType() == InventoryType.CRAFTER) {
852
Block block = inventory.getLocation() == null ? null : inventory.getLocation().getBlock();
853
if (CrafterPipeManager.hasOrchestrators()) {
854
if (block != null && CrafterPipeManager.isOrchestrated(block)) return false;
855
if (block != null && !CrafterPipeManager.allowsIncomingInsert(block, source)) return false;
856
}
828
857
return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);
829
858
}
830
859
860
// Crafters are destination-only and deliberately bypass the normal
861
// destination slot cache. Query their live disabled-slot state and
862
// use vanilla-equivalent hopper insertion ordering instead.
831
863
Boolean specialty = HopperStyleEndpoints.tryInsertOne(inventory, source);
832
864
if (specialty != null) return specialty;
833
865
@@ -1029,18 +1061,21 @@ public final class OptimizedTransferPlanner {
1029
1061
1030
1062
private static final class ConnectionView {
1031
1063
final Object raw;
1064
final long id;
1032
1065
final EndpointView source;
1033
1066
final EndpointView destination;
1034
1067
final EnumSet<Material> filters;
1035
1068
1036
ConnectionView(Object raw, EndpointView source, EndpointView destination, EnumSet<Material> filters) {
1069
ConnectionView(Object raw, long id, EndpointView source, EndpointView destination, EnumSet<Material> filters) {
1037
1070
this.raw = raw;
1071
this.id = id;
1038
1072
this.source = source;
1039
1073
this.destination = destination;
1040
1074
this.filters = filters;
1041
1075
}
1042
1076
1043
1077
static ConnectionView read(Object raw) throws Exception {
1078
long id = ((Number) call(raw, "id")).longValue();
1044
1079
Object source = call(raw, "source");
1045
1080
Object destination = call(raw, "destination");
1046
1081
EndpointView sourceView = endpoint(source);
@@ -1049,7 +1084,7 @@ public final class OptimizedTransferPlanner {
1049
1084
for (Object value : (List<?>) call(raw, "filter")) {
1050
1085
if (value instanceof ItemStack item && !item.getType().isAir()) filters.add(item.getType());
1051
1086
}
1052
return new ConnectionView(raw, sourceView, destinationView, filters);
1087
return new ConnectionView(raw, id, sourceView, destinationView, filters);
1053
1088
}
1054
1089
1055
1090
static EndpointView endpoint(Object endpoint) throws Exception {
@@ -13,6 +13,7 @@ import org.bukkit.block.DoubleChest;13
import org.bukkit.block.data.BlockData;13
import org.bukkit.block.data.BlockData;14
import org.bukkit.block.data.Directional;14
import org.bukkit.block.data.Directional;15
import org.bukkit.configuration.file.FileConfiguration;15
import org.bukkit.configuration.file.FileConfiguration;16
import org.bukkit.event.inventory.InventoryType;16
import org.bukkit.inventory.BrewerInventory;17
import org.bukkit.inventory.BrewerInventory;17
import org.bukkit.inventory.ChiseledBookshelfInventory;18
import org.bukkit.inventory.ChiseledBookshelfInventory;18
import org.bukkit.inventory.DecoratedPotInventory;19
import org.bukkit.inventory.DecoratedPotInventory;@@ -48,6 +49,7 @@ public final class OptimizedTransferPlanner {48
state.tick();49
state.tick();49
state.callPlugin("refreshSelectionParticles");50
state.callPlugin("refreshSelectionParticles");50
state.callPlugin("expireSelections");51
state.callPlugin("expireSelections");52
CrafterPipeManager.tick(plugin);51
} catch (Throwable t) {53
} catch (Throwable t) {52
log(plugin, "Direct transfer planner failed", t);54
log(plugin, "Direct transfer planner failed", t);53
}55
}@@ -67,6 +69,15 @@ public final class OptimizedTransferPlanner {67
* rebuild here preferable to allowing stale routing state for up to the69
* rebuild here preferable to allowing stale routing state for up to the68
* periodic fingerprint interval.70
* periodic fingerprint interval.69
*/71
*/72
public static void invalidateBlock(Object plugin, Block block) {73
if (plugin == null || block == null) return;74
try {75
State state = STATES.get(plugin);76
if (state == null) return;77
state.wakeBlock(block);78
} catch (Throwable ignored) {}79
}80
70
public static void connectionChanged(Object plugin) {81
public static void connectionChanged(Object plugin) {71
try { STATES.computeIfAbsent(plugin, State::new).rebuild(true); }82
try { STATES.computeIfAbsent(plugin, State::new).rebuild(true); }72
catch (Throwable t) { log(plugin, "Connection topology refresh failed", t); }83
catch (Throwable t) { log(plugin, "Connection topology refresh failed", t); }@@ -277,6 +288,8 @@ public final class OptimizedTransferPlanner {277
for (Object rawConnection : raw.values()) {288
for (Object rawConnection : raw.values()) {278
try {289
try {279
ConnectionView connection = ConnectionView.read(rawConnection);290
ConnectionView connection = ConnectionView.read(rawConnection);291
if (CrafterPipeManager.isSlavedIncoming(connection.id)292
|| CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;280
ContainerKey sourceKey = endpointKey(connection.source);293
ContainerKey sourceKey = endpointKey(connection.source);281
groups.computeIfAbsent(sourceKey, Group::new).connections.add(connection);294
groups.computeIfAbsent(sourceKey, Group::new).connections.add(connection);282
} catch (Throwable t) {295
} catch (Throwable t) {@@ -303,6 +316,7 @@ public final class OptimizedTransferPlanner {303
void wakeInventory(Inventory inventory) {316
void wakeInventory(Inventory inventory) {304
ContainerKey key = inventoryKey(inventory);317
ContainerKey key = inventoryKey(inventory);305
if (key != null) invalidateAndWakeKey(key);318
if (key != null) invalidateAndWakeKey(key);319
if (CrafterPipeManager.hasOrchestrators()) CrafterPipeManager.invalidateInventory(inventory);306
}320
}307
321
308
void invalidateAndWakeKey(ContainerKey key) {322
void invalidateAndWakeKey(ContainerKey key) {@@ -365,6 +379,7 @@ public final class OptimizedTransferPlanner {365
// Dispenser/dropper/crafter: empty bucket ↔ water/lava/powder-snow379
// Dispenser/dropper/crafter: empty bucket ↔ water/lava/powder-snow366
// bucket (and other dispense mutations) never open an inventory GUI.380
// bucket (and other dispense mutations) never open an inventory GUI.367
"org.bukkit.event.block.BlockDispenseEvent",381
"org.bukkit.event.block.BlockDispenseEvent",382
"org.bukkit.event.block.CrafterCraftEvent",368
"org.bukkit.event.world.ChunkLoadEvent",383
"org.bukkit.event.world.ChunkLoadEvent",369
"org.bukkit.event.world.ChunkUnloadEvent"384
"org.bukkit.event.world.ChunkUnloadEvent"370
};385
};@@ -426,10 +441,14 @@ public final class OptimizedTransferPlanner {426
wakeBlock(block);441
wakeBlock(block);427
wakeDispenseTarget(block);442
wakeDispenseTarget(block);428
}, 1L);443
}, 1L);444
} else if (name.endsWith("CrafterCraftEvent")) {445
Block block = (Block) call(event, "getBlock");446
schedule(() -> wakeBlock(block), 1L);429
} else if (name.endsWith("ChunkLoadEvent") || name.endsWith("ChunkUnloadEvent")) {447
} else if (name.endsWith("ChunkLoadEvent") || name.endsWith("ChunkUnloadEvent")) {430
// Double-chest canonical identities can change as either half loads.448
// Double-chest canonical identities can change as either half loads.431
lastConnectionCount = -1;449
lastConnectionCount = -1;432
for (Group group : groups.values()) active.add(group);450
for (Group group : groups.values()) active.add(group);451
CrafterPipeManager.chunksChanged();433
}452
}434
} catch (Throwable t) {453
} catch (Throwable t) {435
// A missed event must never stall the network permanently; emergency454
// A missed event must never stall the network permanently; emergency@@ -446,6 +465,7 @@ public final class OptimizedTransferPlanner {446
}465
}447
Inventory inventory = inventoryOf(block);466
Inventory inventory = inventoryOf(block);448
if (inventory != null) wakeInventory(inventory);467
if (inventory != null) wakeInventory(inventory);468
else if (CrafterPipeManager.hasOrchestrators()) CrafterPipeManager.invalidateBlock(block);449
}469
}450
470
451
void wakeDispenseTarget(Block dispenser) {471
void wakeDispenseTarget(Block dispenser) {@@ -484,6 +504,8 @@ public final class OptimizedTransferPlanner {484
504
485
void rebuildCache() {505
void rebuildCache() {486
for (ConnectionView connection : connections) {506
for (ConnectionView connection : connections) {507
if (CrafterPipeManager.isSlavedIncoming(connection.id)) continue;508
if (CrafterPipeManager.isFilteredCrafterOutput(connection.id)) continue;487
if (connection.filters.isEmpty()) unfiltered.add(connection);509
if (connection.filters.isEmpty()) unfiltered.add(connection);488
else {510
else {489
filtered.add(connection);511
filtered.add(connection);@@ -503,7 +525,8 @@ public final class OptimizedTransferPlanner {503
}525
}504
Inventory source = inventoryAt(connections.get(0).source);526
Inventory source = inventoryAt(connections.get(0).source);505
if (source == null || source instanceof FurnaceInventory || source instanceof BrewerInventory527
if (source == null || source instanceof FurnaceInventory || source instanceof BrewerInventory506
|| source instanceof JukeboxInventory) {528
|| source instanceof JukeboxInventory529
|| source.getType() == InventoryType.CRAFTER) {507
cycleBudget = null;530
cycleBudget = null;508
return;531
return;509
}532
}@@ -589,6 +612,10 @@ public final class OptimizedTransferPlanner {589
Inventory source = inventoryAt(connections.get(0).source);612
Inventory source = inventoryAt(connections.get(0).source);590
if (source == null) return RunResult.NO_MOVE;613
if (source == null) return RunResult.NO_MOVE;591
614
615
if (source.getType() == InventoryType.CRAFTER) {616
return RunResult.NO_MOVE;617
}618
592
// Furnaces are special: only the output slot is a legal source.619
// Furnaces are special: only the output slot is a legal source.593
if (source instanceof FurnaceInventory furnace) {620
if (source instanceof FurnaceInventory furnace) {594
boolean moved = false;621
boolean moved = false;@@ -821,13 +848,18 @@ public final class OptimizedTransferPlanner {821
* restart the search from slot 0 so first-slot/merge preference stays correct.848
* restart the search from slot 0 so first-slot/merge preference stays correct.822
*/849
*/823
boolean insertOne(ItemStack source) {850
boolean insertOne(ItemStack source) {824
// Crafters are destination-only and deliberately bypass the normal851
if (inventory.getType() == InventoryType.CRAFTER) {825
// destination slot cache. Query their live disabled-slot state and852
Block block = inventory.getLocation() == null ? null : inventory.getLocation().getBlock();826
// use vanilla-equivalent hopper insertion ordering instead.853
if (CrafterPipeManager.hasOrchestrators()) {827
if (AdvancedEndpointsPatch.isCrafterInventory(inventory)) {854
if (block != null && CrafterPipeManager.isOrchestrated(block)) return false;855
if (block != null && !CrafterPipeManager.allowsIncomingInsert(block, source)) return false;856
}828
return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);857
return AdvancedEndpointsPatch.insertOneCrafter(inventory, source);829
}858
}830
859
860
// Crafters are destination-only and deliberately bypass the normal861
// destination slot cache. Query their live disabled-slot state and862
// use vanilla-equivalent hopper insertion ordering instead.831
Boolean specialty = HopperStyleEndpoints.tryInsertOne(inventory, source);863
Boolean specialty = HopperStyleEndpoints.tryInsertOne(inventory, source);832
if (specialty != null) return specialty;864
if (specialty != null) return specialty;833
865
@@ -1029,18 +1061,21 @@ public final class OptimizedTransferPlanner {1029
1061
1030
private static final class ConnectionView {1062
private static final class ConnectionView {1031
final Object raw;1063
final Object raw;1064
final long id;1032
final EndpointView source;1065
final EndpointView source;1033
final EndpointView destination;1066
final EndpointView destination;1034
final EnumSet<Material> filters;1067
final EnumSet<Material> filters;1035
1068
1036
ConnectionView(Object raw, EndpointView source, EndpointView destination, EnumSet<Material> filters) {1069
ConnectionView(Object raw, long id, EndpointView source, EndpointView destination, EnumSet<Material> filters) {1037
this.raw = raw;1070
this.raw = raw;1071
this.id = id;1038
this.source = source;1072
this.source = source;1039
this.destination = destination;1073
this.destination = destination;1040
this.filters = filters;1074
this.filters = filters;1041
}1075
}1042
1076
1043
static ConnectionView read(Object raw) throws Exception {1077
static ConnectionView read(Object raw) throws Exception {1078
long id = ((Number) call(raw, "id")).longValue();1044
Object source = call(raw, "source");1079
Object source = call(raw, "source");1045
Object destination = call(raw, "destination");1080
Object destination = call(raw, "destination");1046
EndpointView sourceView = endpoint(source);1081
EndpointView sourceView = endpoint(source);@@ -1049,7 +1084,7 @@ public final class OptimizedTransferPlanner {1049
for (Object value : (List<?>) call(raw, "filter")) {1084
for (Object value : (List<?>) call(raw, "filter")) {1050
if (value instanceof ItemStack item && !item.getType().isAir()) filters.add(item.getType());1085
if (value instanceof ItemStack item && !item.getType().isAir()) filters.add(item.getType());1051
}1086
}1052
return new ConnectionView(raw, sourceView, destinationView, filters);1087
return new ConnectionView(raw, id, sourceView, destinationView, filters);1053
}1088
}1054
1089
1055
static EndpointView endpoint(Object endpoint) throws Exception {1090
static EndpointView endpoint(Object endpoint) throws Exception {@@ -72,8 +72,9 @@ public final class TransferPolicyPatch {
72
72
destInv=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},block);
73
73
}
74
74
}
75
if(destInv!=null && isA(destInv,"org.bukkit.inventory.FurnaceInventory")){
76
for(int i=0;i<5;i++){
75
int size=((Number)call(inventory,"getSize")).intValue();
76
if(destInv!=null && isA(destInv,"org.bukkit.inventory.FurnaceInventory") && size<=5){
77
for(int i=0;i<size;i++){
77
78
Object item=call(inventory,"getItem",new Class<?>[]{int.class},i);
78
79
if(!validItem(item))continue;
79
80
Object single=one(item);
@@ -72,8 +72,9 @@ public final class TransferPolicyPatch {72
destInv=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},block);72
destInv=invokePrivate(plugin,"inventoryOf",new Class<?>[]{classFor("org.bukkit.block.Block")},block);73
}73
}74
}74
}75
if(destInv!=null && isA(destInv,"org.bukkit.inventory.FurnaceInventory")){75
int size=((Number)call(inventory,"getSize")).intValue();76
for(int i=0;i<5;i++){76
if(destInv!=null && isA(destInv,"org.bukkit.inventory.FurnaceInventory") && size<=5){77
for(int i=0;i<size;i++){77
Object item=call(inventory,"getItem",new Class<?>[]{int.class},i);78
Object item=call(inventory,"getItem",new Class<?>[]{int.class},i);78
if(!validItem(item))continue;79
if(!validItem(item))continue;79
Object single=one(item);80
Object single=one(item);@@ -31,6 +31,9 @@ validation-interval-ticks: 400
31
31
# Source connector material while a filter is active.
32
32
filtered-source-material: minecraft:copper_block
33
33
34
# Source connector for a filtered crafter output pipe. Lights up while crafting.
35
filtered-crafter-source-material: minecraft:redstone_lamp
36
34
37
# Green feedback while a player is choosing the destination.
35
38
selection-particle-count: 12
36
39
selection-timeout-seconds: 30
@@ -44,6 +47,10 @@ filter-title:
44
47
nl: 'Buisfilter #{id}'
45
48
en: 'Pipe filter #{id}'
46
49
50
crafter-recipe-title:
51
nl: 'Crafter-recept #{id}'
52
en: 'Crafter recipe #{id}'
53
47
54
messages:
48
55
nl:
49
56
selected-source: '<green>Bronzijde gekozen. Shift-klik met lege hand op de bestemmingscontainer.</green>'
@@ -31,6 +31,9 @@ validation-interval-ticks: 40031
# Source connector material while a filter is active.31
# Source connector material while a filter is active.32
filtered-source-material: minecraft:copper_block32
filtered-source-material: minecraft:copper_block33
33
34
# Source connector for a filtered crafter output pipe. Lights up while crafting.35
filtered-crafter-source-material: minecraft:redstone_lamp36
34
# Green feedback while a player is choosing the destination.37
# Green feedback while a player is choosing the destination.35
selection-particle-count: 1238
selection-particle-count: 1236
selection-timeout-seconds: 3039
selection-timeout-seconds: 30@@ -44,6 +47,10 @@ filter-title:44
nl: 'Buisfilter #{id}'47
nl: 'Buisfilter #{id}'45
en: 'Pipe filter #{id}'48
en: 'Pipe filter #{id}'46
49
50
crafter-recipe-title:51
nl: 'Crafter-recept #{id}'52
en: 'Crafter recipe #{id}'53
47
messages:54
messages:48
nl:55
nl:49
selected-source: '<green>Bronzijde gekozen. Shift-klik met lege hand op de bestemmingscontainer.</green>'56
selected-source: '<green>Bronzijde gekozen. Shift-klik met lege hand op de bestemmingscontainer.</green>'