| 1 | package nl.timfalken.containerpipes; |
| 2 | |
| 3 | import org.bukkit.*; |
| 4 | import org.bukkit.block.*; |
| 5 | import org.bukkit.command.*; |
| 6 | import org.bukkit.configuration.file.FileConfiguration; |
| 7 | import org.bukkit.entity.BlockDisplay; |
| 8 | import org.bukkit.entity.Interaction; |
| 9 | import org.bukkit.entity.Player; |
| 10 | import org.bukkit.event.*; |
| 11 | import org.bukkit.event.block.*; |
| 12 | import org.bukkit.event.player.PlayerInteractEvent; |
| 13 | import org.bukkit.event.player.PlayerInteractAtEntityEvent; |
| 14 | import org.bukkit.event.inventory.InventoryClickEvent; |
| 15 | import org.bukkit.event.inventory.InventoryDragEvent; |
| 16 | import org.bukkit.event.inventory.InventoryCloseEvent; |
| 17 | import org.bukkit.event.world.*; |
| 18 | import org.bukkit.inventory.*; |
| 19 | import org.bukkit.event.inventory.InventoryType; |
| 20 | import org.bukkit.inventory.EquipmentSlot; |
| 21 | import org.bukkit.plugin.java.JavaPlugin; |
| 22 | import org.bukkit.scheduler.BukkitTask; |
| 23 | import org.bukkit.util.Transformation; |
| 24 | import org.joml.AxisAngle4f; |
| 25 | import org.joml.Vector3f; |
| 26 | |
| 27 | import java.io.*; |
| 28 | import java.nio.charset.StandardCharsets; |
| 29 | import java.nio.file.Files; |
| 30 | import java.util.*; |
| 31 | import java.util.concurrent.atomic.AtomicLong; |
| 32 | import java.util.Base64; |
| 33 | |
| 34 | public final class ContainerPipesPlugin extends JavaPlugin implements Listener, CommandExecutor { |
| 35 | private final Map<Long, Connection> connections = new LinkedHashMap<>(); |
| 36 | private final Map<UUID, Selection> selections = new HashMap<>(); |
| 37 | private final Map<Long, List<UUID>> displayIds = new HashMap<>(); |
| 38 | private final Map<UUID, Long> lastInteractions = new HashMap<>(); |
| 39 | private final AtomicLong nextId = new AtomicLong(1); |
| 40 | private final Map<Long, FilterHolder> openFilters = new HashMap<>(); |
| 41 | private File dataFile; |
| 42 | private BukkitTask transferTask; |
| 43 | private BukkitTask validationTask; |
| 44 | |
| 45 | @Override public void onEnable() { |
| 46 | saveDefaultConfig(); |
| 47 | dataFile = new File(getDataFolder(), "connections.tsv"); |
| 48 | getServer().getPluginManager().registerEvents(this, this); |
| 49 | Objects.requireNonNull(getCommand("containerpipes")).setExecutor(this); |
| 50 | cleanupTaggedDisplays(); |
| 51 | loadConnections(); |
| 52 | startTasks(); |
| 53 | Bukkit.getScheduler().runTask(this, this::refreshLoadedDisplays); |
| 54 | getLogger().info("ContainerPipes 1.1.0 actief met " + connections.size() + " verbinding(en)."); |
| 55 | } |
| 56 | |
| 57 | @Override public void onDisable() { |
| 58 | if (transferTask != null) transferTask.cancel(); |
| 59 | if (validationTask != null) validationTask.cancel(); |
| 60 | saveConnections(); |
| 61 | removeAllDisplays(); |
| 62 | selections.clear(); |
| 63 | } |
| 64 | |
| 65 | private void startTasks() { |
| 66 | if (transferTask != null) transferTask.cancel(); |
| 67 | if (validationTask != null) validationTask.cancel(); |
| 68 | long transfer = Math.max(1, getConfig().getLong("transfer-interval-ticks", 10)); |
| 69 | long validate = Math.max(1, getConfig().getLong("validation-interval-ticks", 20)); |
| 70 | transferTask = Bukkit.getScheduler().runTaskTimer(this, () -> { |
| 71 | for (Connection c : List.copyOf(connections.values())) transferOne(c); |
| 72 | refreshSelectionParticles(); |
| 73 | expireSelections(); |
| 74 | }, transfer, transfer); |
| 75 | validationTask = Bukkit.getScheduler().runTaskTimer(this, this::validateConnections, validate, validate); |
| 76 | } |
| 77 | |
| 78 | @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) |
| 79 | public void onInteract(PlayerInteractEvent event) { |
| 80 | if (event.getHand() != EquipmentSlot.HAND) return; |
| 81 | if (event.getAction() != Action.RIGHT_CLICK_BLOCK || !event.getPlayer().isSneaking()) return; |
| 82 | Player player = event.getPlayer(); |
| 83 | long now = System.currentTimeMillis(); |
| 84 | long debounceMillis = Math.max(0, getConfig().getLong("interaction-debounce-millis", 100)); |
| 85 | Long previous = lastInteractions.put(player.getUniqueId(), now); |
| 86 | if (previous != null && now - previous < debounceMillis) return; |
| 87 | Block block = event.getClickedBlock(); |
| 88 | BlockFace face = event.getBlockFace(); |
| 89 | if (block == null || !isAllowedContainer(block)) return; |
| 90 | if (!player.hasPermission("containerpipes.use")) return; |
| 91 | |
| 92 | ItemStack held = event.getItem(); |
| 93 | boolean emptyHand = held == null || held.getType().isAir(); |
| 94 | boolean shears = held != null && held.getType() == Material.SHEARS; |
| 95 | if (!emptyHand && !shears) return; |
| 96 | event.setCancelled(true); |
| 97 | |
| 98 | if (shears) { |
| 99 | Connection existing = findByEndpoint(endpoint(block, face)); |
| 100 | if (existing != null) { |
| 101 | removeConnection(existing.id, true); |
| 102 | send(player, "messages.disconnected"); |
| 103 | } else { |
| 104 | selections.remove(player.getUniqueId()); |
| 105 | send(player, "messages.selection-cancelled"); |
| 106 | } |
| 107 | return; |
| 108 | } |
| 109 | |
| 110 | Endpoint clicked = endpoint(block, face); |
| 111 | Selection selection = selections.remove(player.getUniqueId()); |
| 112 | if (selection == null) { |
| 113 | if (findByEndpoint(clicked) != null) { send(player, "messages.side-in-use"); return; } |
| 114 | selections.put(player.getUniqueId(), new Selection(clicked, System.currentTimeMillis())); |
| 115 | spawnSelectionParticles(player, clicked); |
| 116 | send(player, "messages.selected-source"); |
| 117 | return; |
| 118 | } |
| 119 | |
| 120 | Endpoint source = selection.endpoint; |
| 121 | if (!source.world.equals(clicked.world)) { send(player, "messages.different-world"); return; } |
| 122 | if (source.equals(clicked)) { send(player, "messages.selection-cancelled"); return; } |
| 123 | if (findByEndpoint(source) != null || findByEndpoint(clicked) != null) { send(player, "messages.side-in-use"); return; } |
| 124 | int maxRange = Math.max(1, getConfig().getInt("maximum-connection-range", 32)); |
| 125 | if (source.distanceSquared(clicked) > maxRange * maxRange) { send(player, "messages.too-far"); return; } |
| 126 | |
| 127 | World world = Bukkit.getWorld(source.world); |
| 128 | if (world == null) return; |
| 129 | BlockPos start = source.outside(); |
| 130 | BlockPos goal = clicked.outside(); |
| 131 | Set<BlockPos> occupied = occupiedPipeBlocks(); |
| 132 | List<BlockPos> route = findRoute(world, start, goal, maxRange, occupied); |
| 133 | if (route == null) { send(player, "messages.no-route"); return; } |
| 134 | |
| 135 | long id = nextId.getAndIncrement(); |
| 136 | Connection c = new Connection(id, source, clicked, route, List.of()); |
| 137 | connections.put(id, c); |
| 138 | saveConnections(); |
| 139 | spawnDisplays(c); |
| 140 | send(player, "messages.connected"); |
| 141 | } |
| 142 | |
| 143 | @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) |
| 144 | public void onBlockPlace(BlockPlaceEvent event) { |
| 145 | if (isPipeRouteBlock(BlockPos.of(event.getBlockPlaced()))) { |
| 146 | event.setCancelled(true); |
| 147 | send(event.getPlayer(), "messages.pipe-blocked"); |
| 148 | } |
| 149 | } |
| 150 | @EventHandler(ignoreCancelled = true) |
| 151 | public void onBlockBreak(BlockBreakEvent event) { |
| 152 | Block b = event.getBlock(); |
| 153 | for (Connection c : List.copyOf(connections.values())) { |
| 154 | if (c.source.isBlock(b) || c.destination.isBlock(b)) removeConnection(c.id, true); |
| 155 | } |
| 156 | } |
| 157 | @EventHandler public void onChunkLoad(ChunkLoadEvent event) { |
| 158 | Bukkit.getScheduler().runTask(this, () -> refreshChunk(event.getChunk())); |
| 159 | } |
| 160 | @EventHandler public void onChunkUnload(ChunkUnloadEvent event) { removeDisplaysInChunk(event.getChunk()); } |
| 161 | |
| 162 | private void validateConnections() { |
| 163 | for (Connection c : List.copyOf(connections.values())) { |
| 164 | World world = Bukkit.getWorld(c.source.world); |
| 165 | if (world == null) continue; |
| 166 | if (!isEndpointContainer(c.source) || !isEndpointContainer(c.destination)) { removeConnection(c.id, true); continue; } |
| 167 | |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | private boolean isEndpointContainer(Endpoint e) { |
| 172 | World w = Bukkit.getWorld(e.world); |
| 173 | return w != null && (!w.isChunkLoaded(e.x >> 4, e.z >> 4) || isAllowedContainer(w.getBlockAt(e.x,e.y,e.z))); |
| 174 | } |
| 175 | |
| 176 | private void transferOne(Connection c) { |
| 177 | World world = Bukkit.getWorld(c.source.world); |
| 178 | if (world == null || !world.isChunkLoaded(c.source.x >> 4, c.source.z >> 4) || !world.isChunkLoaded(c.destination.x >> 4, c.destination.z >> 4)) return; |
| 179 | Block sourceBlock = world.getBlockAt(c.source.x,c.source.y,c.source.z); |
| 180 | Block destBlock = world.getBlockAt(c.destination.x,c.destination.y,c.destination.z); |
| 181 | Inventory source = inventoryOf(sourceBlock); |
| 182 | Inventory dest = inventoryOf(destBlock); |
| 183 | if (source == null || dest == null) return; |
| 184 | |
| 185 | if (source instanceof FurnaceInventory furnace) { |
| 186 | ItemStack out = furnace.getResult(); |
| 187 | if (out != null && !out.getType().isAir() && matchesFilter(c, one(out)) && tryInsert(dest, one(out))) { |
| 188 | decrementFurnaceResult(furnace); |
| 189 | animateTransfer(c); |
| 190 | } |
| 191 | return; |
| 192 | } |
| 193 | |
| 194 | ItemStack[] contents = source.getStorageContents(); |
| 195 | for (int slot = 0; slot < contents.length; slot++) { |
| 196 | ItemStack stack = contents[slot]; |
| 197 | if (stack == null || stack.getType().isAir() || stack.getAmount() <= 0) continue; |
| 198 | ItemStack single = one(stack); |
| 199 | if (!matchesFilter(c, single)) continue; |
| 200 | if (tryInsert(dest, single)) { |
| 201 | decrement(source, slot, stack); |
| 202 | animateTransfer(c); |
| 203 | return; |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | private boolean tryInsert(Inventory dest, ItemStack single) { |
| 209 | if (dest instanceof FurnaceInventory furnace) { |
| 210 | boolean smelt = furnace.canSmelt(single); |
| 211 | boolean fuel = furnace.isFuel(single); |
| 212 | if (smelt && canMerge(furnace.getSmelting(), single, dest.getMaxStackSize())) { furnace.setSmelting(merged(furnace.getSmelting(), single)); return true; } |
| 213 | if (fuel && canMerge(furnace.getFuel(), single, dest.getMaxStackSize())) { furnace.setFuel(merged(furnace.getFuel(), single)); return true; } |
| 214 | return false; |
| 215 | } |
| 216 | ItemStack[] storage = dest.getStorageContents(); |
| 217 | for (int i=0;i<storage.length;i++) { |
| 218 | ItemStack existing = storage[i]; |
| 219 | if (existing != null && existing.isSimilar(single) && existing.getAmount() < Math.min(existing.getMaxStackSize(), dest.getMaxStackSize())) { |
| 220 | existing.setAmount(existing.getAmount()+1); dest.setItem(i, existing); return true; |
| 221 | } |
| 222 | } |
| 223 | for (int i=0;i<storage.length;i++) if (storage[i] == null || storage[i].getType().isAir()) { dest.setItem(i, single); return true; } |
| 224 | return false; |
| 225 | } |
| 226 | |
| 227 | private static boolean canMerge(ItemStack existing, ItemStack add, int inventoryMax) { |
| 228 | return existing == null || existing.getType().isAir() || (existing.isSimilar(add) && existing.getAmount() < Math.min(existing.getMaxStackSize(), inventoryMax)); |
| 229 | } |
| 230 | private static ItemStack merged(ItemStack existing, ItemStack add) { |
| 231 | if (existing == null || existing.getType().isAir()) return add.clone(); |
| 232 | ItemStack result = existing.clone(); result.setAmount(existing.getAmount()+1); return result; |
| 233 | } |
| 234 | private static ItemStack one(ItemStack source) { ItemStack x=source.clone(); x.setAmount(1); return x; } |
| 235 | private static void decrement(Inventory inv, int slot, ItemStack stack) { if (stack.getAmount() <= 1) inv.setItem(slot, null); else { stack.setAmount(stack.getAmount()-1); inv.setItem(slot, stack); } } |
| 236 | private static void decrementFurnaceResult(FurnaceInventory inv) { ItemStack s=inv.getResult(); if(s==null)return; if(s.getAmount()<=1)inv.setResult(null); else {s.setAmount(s.getAmount()-1);inv.setResult(s);} } |
| 237 | |
| 238 | private Inventory inventoryOf(Block block) { |
| 239 | BlockState state = block.getState(); |
| 240 | if (state instanceof Chest chest) return chest.getInventory(); |
| 241 | if (state instanceof Container container) return container.getInventory(); |
| 242 | return null; |
| 243 | } |
| 244 | |
| 245 | private boolean isAllowedContainer(Block block) { |
| 246 | String n = block.getType().name(); |
| 247 | if (n.equals("CHEST") || n.equals("TRAPPED_CHEST") || n.equals("BARREL") || n.equals("DROPPER") || n.equals("HOPPER") || n.equals("FURNACE") || n.equals("BLAST_FURNACE") || n.equals("SMOKER") || n.equals("DISPENSER")) return true; |
| 248 | return n.endsWith("COPPER_CHEST") && block.getState() instanceof Container; |
| 249 | } |
| 250 | |
| 251 | private Endpoint endpoint(Block b, BlockFace face) { return new Endpoint(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ(), face); } |
| 252 | private Connection findByEndpoint(Endpoint e) { for(Connection c:connections.values()) if(c.source.equals(e)||c.destination.equals(e)) return c; return null; } |
| 253 | |
| 254 | private List<BlockPos> findRoute(World world, BlockPos start, BlockPos goal, int range, Set<BlockPos> occupied) { |
| 255 | if (!isRouteSpace(world.getBlockAt(start.x,start.y,start.z), true) || !isRouteSpace(world.getBlockAt(goal.x,goal.y,goal.z), true)) return null; |
| 256 | record Node(BlockPos pos, int g, int f) {} |
| 257 | PriorityQueue<Node> open = new PriorityQueue<>(Comparator.comparingInt(Node::f)); |
| 258 | Map<BlockPos,Integer> g = new HashMap<>(); |
| 259 | Map<BlockPos,BlockPos> prev = new HashMap<>(); |
| 260 | open.add(new Node(start,0,start.manhattan(goal))); g.put(start,0); |
| 261 | int visited=0, limit=Math.max(4096, range*range*range*4); |
| 262 | while(!open.isEmpty() && visited++<limit) { |
| 263 | Node n=open.poll(); if(n.g()!=g.getOrDefault(n.pos(),Integer.MAX_VALUE)) continue; |
| 264 | if(n.pos().equals(goal)) return reconstruct(prev, goal); |
| 265 | for(BlockPos q:n.pos().neighbors()) { |
| 266 | if(q.y<world.getMinHeight() || q.y>=world.getMaxHeight()) continue; |
| 267 | if(Math.abs(q.x-start.x)>range || Math.abs(q.y-start.y)>range || Math.abs(q.z-start.z)>range) continue; |
| 268 | if(!q.equals(goal) && occupied.contains(q)) continue; |
| 269 | if(!isRouteSpace(world.getBlockAt(q.x,q.y,q.z), q.equals(goal))) continue; |
| 270 | int ng=n.g()+1; |
| 271 | if(ng<g.getOrDefault(q,Integer.MAX_VALUE)) { g.put(q,ng); prev.put(q,n.pos()); open.add(new Node(q,ng,ng+q.manhattan(goal))); } |
| 272 | } |
| 273 | } |
| 274 | return null; |
| 275 | } |
| 276 | private static List<BlockPos> reconstruct(Map<BlockPos,BlockPos> prev, BlockPos goal) { ArrayList<BlockPos> out=new ArrayList<>(); for(BlockPos p=goal;p!=null;p=prev.get(p))out.add(p); Collections.reverse(out); return out; } |
| 277 | private boolean isRouteSpace(Block block, boolean endpointOutside) { return block.getType().isAir(); } |
| 278 | private Set<BlockPos> occupiedPipeBlocks() { Set<BlockPos>s=new HashSet<>(); for(Connection c:connections.values())s.addAll(c.path); return s; } |
| 279 | |
| 280 | private void spawnDisplays(Connection c) { |
| 281 | removeDisplays(c.id); |
| 282 | World world=Bukkit.getWorld(c.source.world); if(world==null)return; |
| 283 | Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block")); |
| 284 | if(material==null || !material.isBlock()) material=Material.IRON_BLOCK; |
| 285 | final Material pipeMaterial = material; |
| 286 | Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block")); |
| 287 | if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK; |
| 288 | final Material filteredSourceMaterial=filteredMaterial; |
| 289 | double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0)); |
| 290 | float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0))); |
| 291 | float sourceEndpointScale=endpointScale("source-endpoint-scale"); |
| 292 | float destinationEndpointScale=endpointScale("destination-endpoint-scale"); |
| 293 | List<UUID> ids=new ArrayList<>(); |
| 294 | List<DisplayPoint> points=polylinePoints(c, spacing); |
| 295 | for(DisplayPoint point:points) { |
| 296 | Location loc = point.location(); |
| 297 | float pointScale = point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale; |
| 298 | if(!world.isChunkLoaded(loc.getBlockX()>>4,loc.getBlockZ()>>4)) continue; |
| 299 | BlockDisplay d=world.spawn(loc, BlockDisplay.class, bd->{ |
| 300 | bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData()); |
| 301 | bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f())); |
| 302 | bd.setPersistent(false); bd.addScoreboardTag("containerpipes"); bd.addScoreboardTag("containerpipes:"+c.id); |
| 303 | bd.setViewRange(1.0f); bd.setShadowRadius(0); bd.setShadowStrength(0); |
| 304 | }); |
| 305 | ids.add(d.getUniqueId()); |
| 306 | Interaction hit=world.spawn(loc, Interaction.class, interaction->{ |
| 307 | interaction.setInteractionWidth(Math.max(0.28f, pointScale)); |
| 308 | interaction.setInteractionHeight(Math.max(0.28f, pointScale)); |
| 309 | interaction.setResponsive(true); |
| 310 | interaction.setPersistent(false); |
| 311 | interaction.addScoreboardTag("containerpipes"); |
| 312 | interaction.addScoreboardTag("containerpipes-filter:"+c.id); |
| 313 | }); |
| 314 | ids.add(hit.getUniqueId()); |
| 315 | } |
| 316 | displayIds.put(c.id,ids); |
| 317 | } |
| 318 | |
| 319 | private List<DisplayPoint> polylinePoints(Connection c,double spacing) { |
| 320 | World w=Bukkit.getWorld(c.source.world); if(w==null)return List.of(); |
| 321 | float sourceEndpointScale=endpointScale("source-endpoint-scale"); |
| 322 | float destinationEndpointScale=endpointScale("destination-endpoint-scale"); |
| 323 | ArrayList<Location> centers=new ArrayList<>(); |
| 324 | Location sourceFace=c.source.attachmentCenter(w, sourceEndpointScale); centers.add(sourceFace); |
| 325 | for(BlockPos p:c.path) centers.add(new Location(w,p.x+0.5,p.y+0.5,p.z+0.5)); |
| 326 | centers.add(c.destination.attachmentCenter(w, destinationEndpointScale)); |
| 327 | ArrayList<Location> raw=new ArrayList<>(); |
| 328 | for(int i=0;i<centers.size()-1;i++) { |
| 329 | Location a=centers.get(i),b=centers.get(i+1); double dist=a.distance(b); int steps=Math.max(1,(int)Math.ceil(dist/spacing)); |
| 330 | for(int j=(i==0?0:1);j<=steps;j++) { double t=(double)j/steps; raw.add(new Location(w,a.getX()+(b.getX()-a.getX())*t,a.getY()+(b.getY()-a.getY())*t,a.getZ()+(b.getZ()-a.getZ())*t)); } |
| 331 | } |
| 332 | ArrayList<DisplayPoint> out=new ArrayList<>(raw.size()); |
| 333 | for(int i=0;i<raw.size();i++) out.add(new DisplayPoint(raw.get(i), i==0 ? 1 : i==raw.size()-1 ? 2 : 0)); |
| 334 | return out; |
| 335 | } |
| 336 | |
| 337 | private void spawnSelectionParticles(Player p, Endpoint e) { |
| 338 | World w=Bukkit.getWorld(e.world); if(w==null)return; Location l=e.faceCenter(w); |
| 339 | int count=Math.max(1,getConfig().getInt("selection-particle-count",12)); |
| 340 | w.spawnParticle(Particle.HAPPY_VILLAGER,l,count,0.18,0.18,0.18,0); |
| 341 | } |
| 342 | private void refreshSelectionParticles() { |
| 343 | for (Map.Entry<UUID, Selection> entry : selections.entrySet()) { |
| 344 | Player player = Bukkit.getPlayer(entry.getKey()); |
| 345 | if (player != null && player.isOnline()) spawnSelectionParticles(player, entry.getValue().endpoint); |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | private void animateTransfer(Connection c) { |
| 350 | World world = Bukkit.getWorld(c.source.world); |
| 351 | if (world == null) return; |
| 352 | List<DisplayPoint> displayPoints = polylinePoints(c, Math.max(0.1, getConfig().getDouble("transfer-particle-spacing", 0.25))); |
| 353 | if (displayPoints.isEmpty()) return; |
| 354 | int stepTicks = Math.max(1, getConfig().getInt("transfer-particle-step-ticks", 1)); |
| 355 | int pointsPerStep = Math.max(1, getConfig().getInt("transfer-particle-points-per-step", 2)); |
| 356 | BukkitTask[] task = new BukkitTask[1]; |
| 357 | int[] index = {0}; |
| 358 | task[0] = Bukkit.getScheduler().runTaskTimer(this, () -> { |
| 359 | if (index[0] >= displayPoints.size()) { |
| 360 | task[0].cancel(); |
| 361 | return; |
| 362 | } |
| 363 | for (int i = 0; i < pointsPerStep && index[0] < displayPoints.size(); i++, index[0]++) { |
| 364 | Location location = displayPoints.get(index[0]).location(); |
| 365 | if (world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) { |
| 366 | world.spawnParticle(Particle.END_ROD, location, 1, 0, 0, 0, 0); |
| 367 | } |
| 368 | } |
| 369 | }, 0L, stepTicks); |
| 370 | } |
| 371 | private void expireSelections(){long max=Math.max(1,getConfig().getLong("selection-timeout-seconds",30))*1000; long now=System.currentTimeMillis(); selections.entrySet().removeIf(e->now-e.getValue().createdAt>max);} |
| 372 | |
| 373 | private void refreshLoadedDisplays(){for(Connection c:connections.values())spawnDisplays(c);} |
| 374 | private void refreshChunk(Chunk chunk){for(Connection c:connections.values())if(c.touchesChunk(chunk))spawnMissingDisplaysInChunk(c, chunk);} |
| 375 | 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);} |
| 376 | private void removeAllDisplays(){for(long id:List.copyOf(displayIds.keySet()))removeDisplays(id);} |
| 377 | private void removeDisplaysInChunk(Chunk chunk){ |
| 378 | Set<UUID> removed=new HashSet<>(); |
| 379 | for(var e:chunk.getEntities()) if(e.getScoreboardTags().contains("containerpipes")){removed.add(e.getUniqueId());e.remove();} |
| 380 | if(!removed.isEmpty()) for(var entry:displayIds.entrySet()) entry.getValue().removeIf(removed::contains); |
| 381 | } |
| 382 | private void spawnMissingDisplaysInChunk(Connection c, Chunk chunk) { |
| 383 | World world=Bukkit.getWorld(c.source.world); if(world==null)return; |
| 384 | Material material=Material.matchMaterial(getConfig().getString("pipe-material","minecraft:iron_block")); |
| 385 | if(material==null || !material.isBlock()) material=Material.IRON_BLOCK; |
| 386 | final Material pipeMaterial=material; |
| 387 | Material filteredMaterial=Material.matchMaterial(getConfig().getString("filtered-source-material","minecraft:copper_block")); |
| 388 | if(filteredMaterial==null || !filteredMaterial.isBlock()) filteredMaterial=Material.COPPER_BLOCK; |
| 389 | final Material filteredSourceMaterial=filteredMaterial; |
| 390 | double spacing=Math.max(0.1,getConfig().getDouble("segment-spacing",1.0/3.0)); |
| 391 | float scale=(float)Math.max(0.05,Math.min(1.0,getConfig().getDouble("pipe-scale",1.0/3.0))); |
| 392 | float sourceEndpointScale=endpointScale("source-endpoint-scale"); |
| 393 | float destinationEndpointScale=endpointScale("destination-endpoint-scale"); |
| 394 | List<UUID> ids=displayIds.computeIfAbsent(c.id,k->new ArrayList<>()); |
| 395 | for(DisplayPoint point:polylinePoints(c,spacing)) { |
| 396 | Location loc=point.location(); |
| 397 | if((loc.getBlockX()>>4)!=chunk.getX() || (loc.getBlockZ()>>4)!=chunk.getZ()) continue; |
| 398 | float pointScale=point.type()==1 ? sourceEndpointScale : point.type()==2 ? destinationEndpointScale : scale; |
| 399 | BlockDisplay d=world.spawn(loc,BlockDisplay.class,bd->{ |
| 400 | bd.setBlock((point.type()==1 && c.hasFilter() ? filteredSourceMaterial : pipeMaterial).createBlockData()); |
| 401 | bd.setTransformation(new Transformation(new Vector3f(-pointScale/2f,-pointScale/2f,-pointScale/2f),new AxisAngle4f(),new Vector3f(pointScale,pointScale,pointScale),new AxisAngle4f())); |
| 402 | bd.setPersistent(false);bd.addScoreboardTag("containerpipes");bd.addScoreboardTag("containerpipes:"+c.id); |
| 403 | bd.setViewRange(1.0f);bd.setShadowRadius(0);bd.setShadowStrength(0); |
| 404 | }); |
| 405 | ids.add(d.getUniqueId()); |
| 406 | Interaction hit=world.spawn(loc,Interaction.class,interaction->{ |
| 407 | interaction.setInteractionWidth(Math.max(0.28f,pointScale)); |
| 408 | interaction.setInteractionHeight(Math.max(0.28f,pointScale)); |
| 409 | interaction.setResponsive(true);interaction.setPersistent(false); |
| 410 | interaction.addScoreboardTag("containerpipes");interaction.addScoreboardTag("containerpipes-filter:"+c.id); |
| 411 | }); |
| 412 | ids.add(hit.getUniqueId()); |
| 413 | } |
| 414 | } |
| 415 | private void cleanupTaggedDisplays(){for(World w:Bukkit.getWorlds())for(var e:w.getEntities())if(e.getScoreboardTags().contains("containerpipes"))e.remove();} |
| 416 | |
| 417 | private void removeConnection(long id,boolean save){connections.remove(id);removeDisplays(id);if(save)saveConnections();} |
| 418 | |
| 419 | private void saveConnections(){ |
| 420 | try {getDataFolder().mkdirs(); StringBuilder s=new StringBuilder("# ContainerPipes 1.1.0\n"); for(Connection c:connections.values())s.append(c.serialize()).append('\n'); Files.writeString(dataFile.toPath(),s.toString(),StandardCharsets.UTF_8);} catch(Exception e){getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingen niet opslaan",e);} |
| 421 | } |
| 422 | private void loadConnections(){ |
| 423 | connections.clear(); |
| 424 | nextId.set(1); |
| 425 | if(!dataFile.exists())return; |
| 426 | int loaded=0; |
| 427 | int skipped=0; |
| 428 | try { |
| 429 | List<String> lines=Files.readAllLines(dataFile.toPath(),StandardCharsets.UTF_8); |
| 430 | for(int i=0;i<lines.size();i++) { |
| 431 | String line=lines.get(i).trim(); |
| 432 | if(line.isEmpty()||line.startsWith("#"))continue; |
| 433 | try { |
| 434 | Connection c=Connection.parse(line); |
| 435 | connections.put(c.id,c); |
| 436 | nextId.set(Math.max(nextId.get(),c.id+1)); |
| 437 | loaded++; |
| 438 | } catch(Exception entryError) { |
| 439 | skipped++; |
| 440 | getLogger().warning("Ongeldige verbinding overgeslagen op regel "+(i+1)+": "+entryError.getMessage()); |
| 441 | } |
| 442 | } |
| 443 | if(skipped>0)getLogger().warning(loaded+" verbinding(en) geladen; "+skipped+" ongeldige regel(s) overgeslagen."); |
| 444 | } catch(Exception e) { |
| 445 | getLogger().log(java.util.logging.Level.SEVERE,"Kon verbindingenbestand niet lezen",e); |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | private float endpointScale(String key) { |
| 450 | double legacy=getConfig().getDouble("endpoint-scale",0.40); |
| 451 | return (float)Math.max(0.05,Math.min(1.0,getConfig().getDouble(key,legacy))); |
| 452 | } |
| 453 | |
| 454 | private void send(Player p,String key){p.sendMessage(legacyMessage(getConfig().getString(key,"")));} |
| 455 | private String legacyMessage(String input){ |
| 456 | if(input==null)return ""; |
| 457 | return input.replace("<green>","§a").replace("</green>","") |
| 458 | .replace("<yellow>","§e").replace("</yellow>","") |
| 459 | .replace("<red>","§c").replace("</red>","") |
| 460 | .replace("<gray>","§7").replace("</gray>","") |
| 461 | .replace("<white>","§f").replace("</white>","") |
| 462 | .replace("<bold>","§l").replace("</bold>","§r") |
| 463 | .replace("<reset>","§r"); |
| 464 | } |
| 465 | |
| 466 | |
| 467 | private boolean isPipeRouteBlock(BlockPos pos){for(Connection c:connections.values())if(c.path.contains(pos))return true;return false;} |
| 468 | private boolean matchesFilter(Connection c, ItemStack item){if(!c.hasFilter())return true;for(ItemStack f:c.filter)if(f!=null&&!f.getType().isAir()&&f.isSimilar(item))return true;return false;} |
| 469 | |
| 470 | @EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true) |
| 471 | public void onPipeInteract(PlayerInteractAtEntityEvent event){ |
| 472 | if(event.getHand()!=EquipmentSlot.HAND || !event.getPlayer().isSneaking())return; |
| 473 | ItemStack held=event.getPlayer().getInventory().getItemInMainHand(); |
| 474 | if(held!=null&&!held.getType().isAir())return; |
| 475 | long id=connectionIdFrom(event.getRightClicked().getScoreboardTags()); |
| 476 | if(id<0||!connections.containsKey(id))return; |
| 477 | event.setCancelled(true);openFilter(event.getPlayer(),id); |
| 478 | } |
| 479 | 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;} |
| 480 | private void openFilter(Player player,long id){ |
| 481 | Connection c=connections.get(id);if(c==null)return; |
| 482 | FilterHolder holder=new FilterHolder(id);Inventory inv=Bukkit.createInventory(holder,InventoryType.HOPPER,"Buisfilter #"+id);holder.inventory=inv; |
| 483 | 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());} |
| 484 | openFilters.put(id,holder);player.openInventory(inv); |
| 485 | } |
| 486 | @EventHandler public void onFilterClick(InventoryClickEvent event){ |
| 487 | if(!(event.getInventory().getHolder() instanceof FilterHolder holder))return; |
| 488 | if(event.getRawSlot()<0)return; |
| 489 | if(event.getRawSlot()>=5){if(event.isShiftClick())event.setCancelled(true);return;} |
| 490 | event.setCancelled(true); |
| 491 | ItemStack cursor=event.getCursor(); |
| 492 | if(cursor==null||cursor.getType().isAir())event.getInventory().setItem(event.getRawSlot(),null); |
| 493 | else{ItemStack copy=cursor.clone();copy.setAmount(1);event.getInventory().setItem(event.getRawSlot(),copy);} |
| 494 | updateFilter(holder.connectionId,event.getInventory()); |
| 495 | } |
| 496 | @EventHandler public void onFilterDrag(InventoryDragEvent event){if(event.getInventory().getHolder() instanceof FilterHolder)event.setCancelled(true);} |
| 497 | @EventHandler public void onFilterClose(InventoryCloseEvent event){if(event.getInventory().getHolder() instanceof FilterHolder holder)updateFilter(holder.connectionId,event.getInventory());} |
| 498 | private void updateFilter(long id,Inventory inv){Connection old=connections.get(id);if(old==null)return;ArrayList<ItemStack> f=new ArrayList<>(5);for(int i=0;i<5;i++){ItemStack x=inv.getItem(i);if(x!=null){x=x.clone();x.setAmount(1);}f.add(x);}connections.put(id,new Connection(old.id,old.source,old.destination,old.path,Collections.unmodifiableList(f)));saveConnections();spawnDisplays(connections.get(id));} |
| 499 | 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);} |
| 500 | 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);} |
| 501 | private static final class FilterHolder implements InventoryHolder{final long connectionId;Inventory inventory;FilterHolder(long id){connectionId=id;}public Inventory getInventory(){return inventory;}} |
| 502 | |
| 503 | @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { |
| 504 | if(!sender.hasPermission("containerpipes.admin"))return true; |
| 505 | String sub=args.length==0?"status":args[0].toLowerCase(Locale.ROOT); |
| 506 | switch(sub){ |
| 507 | case "status"->sender.sendMessage("ContainerPipes: "+connections.size()+" verbinding(en), "+displayIds.values().stream().mapToInt(List::size).sum()+" displaysegmenten."); |
| 508 | case "reload"->{reloadConfig();startTasks();refreshLoadedDisplays();sender.sendMessage("ContainerPipes herladen.");} |
| 509 | case "refresh"->{cleanupTaggedDisplays();displayIds.clear();refreshLoadedDisplays();sender.sendMessage("Alle geladen buizen vernieuwd.");} |
| 510 | default->sender.sendMessage("Gebruik: /containerpipes <status|reload|refresh>"); |
| 511 | } return true; |
| 512 | } |
| 513 | |
| 514 | private record Selection(Endpoint endpoint,long createdAt){} |
| 515 | private record DisplayPoint(Location location, int type){} |
| 516 | private record BlockPos(int x,int y,int z){ |
| 517 | static BlockPos of(Block b){return new BlockPos(b.getX(),b.getY(),b.getZ());} |
| 518 | List<BlockPos> neighbors(){return List.of(new BlockPos(x+1,y,z),new BlockPos(x-1,y,z),new BlockPos(x,y+1,z),new BlockPos(x,y-1,z),new BlockPos(x,y,z+1),new BlockPos(x,y,z-1));} |
| 519 | int manhattan(BlockPos o){return Math.abs(x-o.x)+Math.abs(y-o.y)+Math.abs(z-o.z);} |
| 520 | String encode(){return x+","+y+","+z;} static BlockPos decode(String s){String[]p=s.split(",");return new BlockPos(Integer.parseInt(p[0]),Integer.parseInt(p[1]),Integer.parseInt(p[2]));} |
| 521 | } |
| 522 | private record Endpoint(UUID world,int x,int y,int z,BlockFace face){ |
| 523 | BlockPos outside(){return new BlockPos(x+face.getModX(),y+face.getModY(),z+face.getModZ());} |
| 524 | boolean isBlock(Block b){return b.getWorld().getUID().equals(world)&&b.getX()==x&&b.getY()==y&&b.getZ()==z;} |
| 525 | double distanceSquared(Endpoint o){double dx=x-o.x,dy=y-o.y,dz=z-o.z;return dx*dx+dy*dy+dz*dz;} |
| 526 | Location faceCenter(World w){return new Location(w,x+0.5+face.getModX()*0.51,y+0.5+face.getModY()*0.51,z+0.5+face.getModZ()*0.51);} |
| 527 | Location attachmentCenter(World w,float scale){double offset=0.5+(scale/2.0);return new Location(w,x+0.5+face.getModX()*offset,y+0.5+face.getModY()*offset,z+0.5+face.getModZ()*offset);} |
| 528 | String encode(){return world+","+x+","+y+","+z+","+face.name();} |
| 529 | static Endpoint decode(String s){String[]p=s.split(",");return new Endpoint(UUID.fromString(p[0]),Integer.parseInt(p[1]),Integer.parseInt(p[2]),Integer.parseInt(p[3]),BlockFace.valueOf(p[4]));} |
| 530 | } |
| 531 | private record Connection(long id,Endpoint source,Endpoint destination,List<BlockPos> path,List<ItemStack> filter){ |
| 532 | boolean hasFilter(){return filter.stream().anyMatch(i->i!=null&&!i.getType().isAir());} |
| 533 | String serialize(){return id+"\t"+source.encode()+"\t"+destination.encode()+"\t"+path.stream().map(BlockPos::encode).reduce((a,b)->a+";"+b).orElse("")+"\t"+encodeFilter(filter);} |
| 534 | static Connection parse(String line){String[]p=line.split("\\t",5);List<BlockPos>path=p.length<4||p[3].isBlank()?List.of():Arrays.stream(p[3].split(";")).map(BlockPos::decode).toList();List<ItemStack> filter=p.length<5?List.of():decodeFilter(p[4]);return new Connection(Long.parseLong(p[0]),Endpoint.decode(p[1]),Endpoint.decode(p[2]),path,filter);} |
| 535 | boolean touchesChunk(Chunk c){if(!c.getWorld().getUID().equals(source.world))return false;int cx=c.getX(),cz=c.getZ();if((source.x>>4)==cx&&(source.z>>4)==cz)return true;if((destination.x>>4)==cx&&(destination.z>>4)==cz)return true;for(BlockPos p:path)if((p.x>>4)==cx&&(p.z>>4)==cz)return true;return false;} |
| 536 | } |
| 537 | } |