package nl.timfalken.chestpreview; import com.github.retrooper.packetevents.PacketEvents; import com.github.retrooper.packetevents.protocol.entity.data.EntityData; import com.github.retrooper.packetevents.protocol.entity.data.EntityDataTypes; import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes; import com.github.retrooper.packetevents.util.Quaternion4f; import com.github.retrooper.packetevents.util.Vector3f; import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities; import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata; import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport; import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity; import io.github.retrooper.packetevents.util.SpigotConversionUtil; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.entity.Entity; import org.bukkit.entity.ItemDisplay; import org.bukkit.entity.Player; import org.bukkit.inventory.FurnaceInventory; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.persistence.PersistentDataType; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; /** * Maintains logical previews and sends them as packet-only ItemDisplay entities. * No ItemDisplay is spawned into the Bukkit world by this version. */ final class PreviewManager { // Minecraft 26.2 metadata indices for Display / ItemDisplay entities. // Base Entity occupies 0..7, Display 8..22, ItemDisplay 23..24. private static final int META_ENTITY_FLAGS = 0; private static final int META_NO_GRAVITY = 5; private static final int META_SCALE = 12; private static final int META_LEFT_ROTATION = 13; private static final int META_RIGHT_ROTATION = 14; private static final int META_BILLBOARD = 15; private static final int META_ITEM = 23; private static final int META_ITEM_TRANSFORM = 24; private static final byte ENTITY_FLAG_GLOWING = 0x40; private static final byte BILLBOARD_FIXED = 0; private static final byte ITEM_TRANSFORM_GUI = 6; private static final byte ITEM_TRANSFORM_FIXED = 8; // Client-only IDs live far above normal server entity IDs to avoid collisions. private static final AtomicInteger NEXT_FAKE_ENTITY_ID = new AtomicInteger(2_000_000_000); private final ChestPreviewPlugin plugin; private final NamespacedKey legacyManagedKey; private final Map previews = new HashMap<>(); private final Queue scanQueue = new ArrayDeque<>(); private final Set queued = new HashSet<>(); private final Map> knownContainers = new HashMap<>(); PreviewManager(ChestPreviewPlugin plugin) { this.plugin = plugin; // Used only to remove persisted server-side displays left by ChestPreview <= 1.0.8. this.legacyManagedKey = new NamespacedKey("chestpreview", "managed"); } boolean isSupported(Block block) { return switch (block.getType()) { case CHEST -> plugin.getConfig().getBoolean("containers.chest", true); case TRAPPED_CHEST -> plugin.getConfig().getBoolean("containers.trapped-chest", true); case BARREL -> plugin.getConfig().getBoolean("containers.barrel", true); case FURNACE -> plugin.getConfig().getBoolean("output-containers.furnace", true); case BLAST_FURNACE -> plugin.getConfig().getBoolean("output-containers.blast-furnace", true); case SMOKER -> plugin.getConfig().getBoolean("output-containers.smoker", true); default -> false; }; } void refresh(Block block) { if (!isSupported(block)) { removeForPhysicalBlock(BlockKey.of(block)); return; } ContainerTarget target = ContainerTarget.fromBlock(block); if (target != null) refresh(target); } void refresh(ContainerTarget target) { rememberTarget(target); ItemStack selected = selectItem(target); BlockKey key = target.key(); if (selected == null) { destroyPreview(key); return; } Location location = target.displayLocation( plugin.getConfig().getDouble("display.forward-offset", 0.515), plugin.getConfig().getDouble("display.vertical-offset", 0.42), plugin.getConfig().getDouble("display.sideways-offset", 0.0), plugin.getConfig().getDouble("display.rotation.yaw", 0.0), plugin.getConfig().getDouble("display.rotation.pitch", 0.0)); ItemStack shown = selected.clone(); shown.setAmount(1); VisualSpec visual = visualSpec(shown.getType()); PreviewState state = previews.get(key); boolean newlyCreated = false; boolean moved = false; boolean metadataChanged = false; if (state == null) { state = new PreviewState( NEXT_FAKE_ENTITY_ID.getAndDecrement(), UUID.randomUUID(), copyLocation(location), shown, visual); previews.put(key, state); newlyCreated = true; } else { moved = !sameLocation(state.location, location); metadataChanged = !sameItem(state.item, shown) || !state.visual.equals(visual); state.location = copyLocation(location); state.item = shown; state.visual = visual; } syncViewers(key, state, newlyCreated, moved, metadataChanged); } private ItemStack selectItem(ContainerTarget target) { Inventory inventory = target.inventory(); if (inventory instanceof FurnaceInventory furnaceInventory) { ItemStack result = furnaceInventory.getResult(); if (usable(result)) return result; ItemStack input = furnaceInventory.getSmelting(); return usable(input) ? input : null; } ItemStack[] contents = inventory.getStorageContents(); int usableCount = 0; for (ItemStack item : contents) { if (usable(item)) usableCount++; } if (usableCount == 0) return null; int selectedIndex = ThreadLocalRandom.current().nextInt(usableCount); for (ItemStack item : contents) { if (!usable(item)) continue; if (selectedIndex-- == 0) return item; } return null; } private static boolean usable(ItemStack item) { return item != null && item.getType() != Material.AIR && item.getAmount() > 0; } private VisualSpec visualSpec(Material material) { float scale = (float) plugin.getConfig().getDouble("display.scale", 0.40); float roll = radians(plugin.getConfig().getDouble("display.rotation.roll", 0.0)); boolean block = material.isBlock(); float modelYaw = block ? 0.0f : radians(180.0); float modelPitch = 0.0f; if (material.name().endsWith("_STAIRS")) { modelYaw = radians(plugin.getConfig().getDouble("display.block-rotation.stairs-yaw", 0.0)); modelPitch = radians(plugin.getConfig().getDouble("display.block-rotation.stairs-pitch", 0.0)); } else if (block) { modelYaw = radians(plugin.getConfig().getDouble("display.block-rotation.default-yaw", 0.0)); modelPitch = radians(plugin.getConfig().getDouble("display.block-rotation.default-pitch", 0.0)); } byte transform = block ? ITEM_TRANSFORM_FIXED : ITEM_TRANSFORM_GUI; boolean glowing = plugin.getConfig().getBoolean("display.glowing", false); return new VisualSpec(scale, modelPitch, modelYaw, roll, transform, glowing); } private void syncViewers(BlockKey key, PreviewState state, boolean newlyCreated, boolean moved, boolean metadataChanged) { Set stillVisible = new HashSet<>(); for (Player player : Bukkit.getOnlinePlayers()) { if (!shouldView(player, state.location)) continue; UUID playerId = player.getUniqueId(); stillVisible.add(playerId); if (state.viewers.add(playerId)) { sendSpawn(player, state); } else { if (moved) sendTeleport(player, state); if (metadataChanged || newlyCreated) sendMetadata(player, state); } } Iterator iterator = state.viewers.iterator(); while (iterator.hasNext()) { UUID viewerId = iterator.next(); if (stillVisible.contains(viewerId)) continue; Player viewer = Bukkit.getPlayer(viewerId); if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId); iterator.remove(); } } private boolean shouldView(Player player, Location location) { if (location.getWorld() == null || !player.getWorld().getUID().equals(location.getWorld().getUID())) return false; int radius = Math.max(0, plugin.getConfig().getInt("cycling.player-chunk-radius", 4)); int playerChunkX = player.getLocation().getChunk().getX(); int playerChunkZ = player.getLocation().getChunk().getZ(); int previewChunkX = ((int) Math.floor(location.getX())) >> 4; int previewChunkZ = ((int) Math.floor(location.getZ())) >> 4; return Math.abs(playerChunkX - previewChunkX) <= radius && Math.abs(playerChunkZ - previewChunkZ) <= radius; } private void sendSpawn(Player player, PreviewState state) { WrapperPlayServerSpawnEntity spawn = new WrapperPlayServerSpawnEntity( state.entityId, state.entityUuid, EntityTypes.ITEM_DISPLAY, SpigotConversionUtil.fromBukkitLocation(state.location), state.location.getYaw(), 0, null); PacketEvents.getAPI().getPlayerManager().sendPacket(player, spawn); sendMetadata(player, state); } private void sendMetadata(Player player, PreviewState state) { List> data = new ArrayList<>(8); byte flags = state.visual.glowing ? ENTITY_FLAG_GLOWING : 0; data.add(new EntityData<>(META_ENTITY_FLAGS, EntityDataTypes.BYTE, flags)); data.add(new EntityData<>(META_NO_GRAVITY, EntityDataTypes.BOOLEAN, true)); data.add(new EntityData<>(META_SCALE, EntityDataTypes.VECTOR3F, new Vector3f(state.visual.scale, state.visual.scale, state.visual.scale))); data.add(new EntityData<>(META_LEFT_ROTATION, EntityDataTypes.QUATERNION, quaternionXYZ(state.visual.pitch, state.visual.yaw, state.visual.roll))); data.add(new EntityData<>(META_RIGHT_ROTATION, EntityDataTypes.QUATERNION, new Quaternion4f(0.0f, 0.0f, 0.0f, 1.0f))); data.add(new EntityData<>(META_BILLBOARD, EntityDataTypes.BYTE, BILLBOARD_FIXED)); data.add(new EntityData<>(META_ITEM, EntityDataTypes.ITEMSTACK, SpigotConversionUtil.fromBukkitItemStack(state.item))); data.add(new EntityData<>(META_ITEM_TRANSFORM, EntityDataTypes.BYTE, state.visual.itemTransform)); PacketEvents.getAPI().getPlayerManager().sendPacket( player, new WrapperPlayServerEntityMetadata(state.entityId, data)); } private void sendTeleport(Player player, PreviewState state) { PacketEvents.getAPI().getPlayerManager().sendPacket( player, new WrapperPlayServerEntityTeleport( state.entityId, SpigotConversionUtil.fromBukkitLocation(state.location), false)); } private void sendDestroy(Player player, int entityId) { PacketEvents.getAPI().getPlayerManager().sendPacket( player, new WrapperPlayServerDestroyEntities(entityId)); } private void destroyPreview(BlockKey key) { PreviewState state = previews.remove(key); if (state == null) return; for (UUID viewerId : new HashSet<>(state.viewers)) { Player viewer = Bukkit.getPlayer(viewerId); if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId); } state.viewers.clear(); } private void pruneViewers() { for (PreviewState state : previews.values()) { Iterator iterator = state.viewers.iterator(); while (iterator.hasNext()) { UUID viewerId = iterator.next(); Player viewer = Bukkit.getPlayer(viewerId); if (viewer != null && viewer.isOnline() && shouldView(viewer, state.location)) continue; if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId); iterator.remove(); } } } /** * Register containers once when a chunk is discovered. Legacy Bukkit ItemDisplays from * ChestPreview <= 1.0.8 are removed as a migration step, but no new Bukkit entity is spawned. */ void discoverChunk(Chunk chunk) { cleanupLegacyDisplays(chunk); registerContainersInChunk(chunk, true); } void rebuildChunk(Chunk chunk) { int chunkX = chunk.getX(); int chunkZ = chunk.getZ(); World world = chunk.getWorld(); ChunkKey chunkKey = ChunkKey.of(chunk); cleanupLegacyDisplays(chunk); List toDestroy = new ArrayList<>(); for (BlockKey key : previews.keySet()) { if (isInChunk(key, world, chunkX, chunkZ)) toDestroy.add(key); } for (BlockKey key : toDestroy) destroyPreview(key); scanQueue.removeIf(key -> isInChunk(key, world, chunkX, chunkZ)); queued.removeIf(key -> isInChunk(key, world, chunkX, chunkZ)); knownContainers.remove(chunkKey); registerContainersInChunk(chunk, true); } void forgetChunk(Chunk chunk) { ChunkKey chunkKey = ChunkKey.of(chunk); Set forgotten = knownContainers.remove(chunkKey); if (forgotten == null) return; for (BlockKey key : forgotten) { destroyPreview(key); queued.remove(key); } scanQueue.removeIf(forgotten::contains); } private void cleanupLegacyDisplays(Chunk chunk) { for (Entity entity : chunk.getEntities()) { if (!(entity instanceof ItemDisplay display)) continue; if (display.getPersistentDataContainer().has(legacyManagedKey, PersistentDataType.BYTE)) { display.remove(); } } } private void registerContainersInChunk(Chunk chunk, boolean enqueueForRefresh) { for (BlockState state : chunk.getTileEntities()) { Block block = state.getBlock(); if (!isSupported(block)) continue; ContainerTarget target = ContainerTarget.fromBlock(block); if (target == null) continue; rememberTarget(target); if (enqueueForRefresh) enqueue(target.key()); } } private void rememberTarget(ContainerTarget target) { BlockKey key = target.key(); knownContainers.computeIfAbsent(ChunkKey.of(key), ignored -> new HashSet<>()).add(key); } private void forgetKnownKey(BlockKey key) { Set keys = knownContainers.get(ChunkKey.of(key)); if (keys == null) return; keys.remove(key); if (keys.isEmpty()) knownContainers.remove(ChunkKey.of(key)); } private static boolean isInChunk(BlockKey key, World world, int chunkX, int chunkZ) { return key.worldId().equals(world.getUID()) && (key.x() >> 4) == chunkX && (key.z() >> 4) == chunkZ; } void enqueue(BlockKey key) { if (queued.add(key)) scanQueue.offer(key); } void enqueue(Block block) { if (!isSupported(block)) return; ContainerTarget target = ContainerTarget.fromBlock(block); if (target == null) return; rememberTarget(target); enqueue(target.key()); } void processScanBatch() { int maximum = Math.max(1, plugin.getConfig().getInt("updates.containers-per-batch", 5)); for (int i = 0; i < maximum; i++) { BlockKey key = scanQueue.poll(); if (key == null) return; queued.remove(key); World world = Bukkit.getWorld(key.worldId()); if (world == null || !world.isChunkLoaded(key.x() >> 4, key.z() >> 4)) continue; refresh(world.getBlockAt(key.x(), key.y(), key.z())); } } /** * Every interval, already-known containers near players are visited. If cycling is enabled, * the preview item is reselected. The same pass also creates/removes client-only viewers as * players enter or leave the configured four-chunk radius. No chunk tile-entity scan occurs. */ void cycleNearbyContainers() { int radius = Math.max(0, plugin.getConfig().getInt("cycling.player-chunk-radius", 4)); boolean cycling = plugin.getConfig().getBoolean("cycling.enabled", true); Set targets = new HashSet<>(); Set visitedChunks = new HashSet<>(); for (Player player : Bukkit.getOnlinePlayers()) { Chunk center = player.getLocation().getChunk(); World world = player.getWorld(); for (int dx = -radius; dx <= radius; dx++) { for (int dz = -radius; dz <= radius; dz++) { int chunkX = center.getX() + dx; int chunkZ = center.getZ() + dz; if (!world.isChunkLoaded(chunkX, chunkZ)) continue; ChunkKey chunkKey = new ChunkKey(world.getUID(), chunkX, chunkZ); if (!visitedChunks.add(chunkKey)) continue; Set known = knownContainers.get(chunkKey); if (known != null) targets.addAll(known); } } } for (BlockKey key : targets) { World world = Bukkit.getWorld(key.worldId()); if (world == null || !world.isChunkLoaded(key.x() >> 4, key.z() >> 4)) continue; Block block = world.getBlockAt(key.x(), key.y(), key.z()); if (!isSupported(block)) { removeForPhysicalBlock(key); continue; } if (cycling || !previews.containsKey(key)) { refresh(block); } else { PreviewState state = previews.get(key); if (state != null) syncViewers(key, state, false, false, false); } } pruneViewers(); } void enqueueLoadedChunks() { for (World world : Bukkit.getWorlds()) { for (Chunk chunk : world.getLoadedChunks()) discoverChunk(chunk); } } void cleanupAll() { destroyAllPacketDisplays(); scanQueue.clear(); queued.clear(); knownContainers.clear(); for (World world : Bukkit.getWorlds()) { for (Chunk chunk : world.getLoadedChunks()) cleanupLegacyDisplays(chunk); } } void shutdown() { destroyAllPacketDisplays(); scanQueue.clear(); queued.clear(); knownContainers.clear(); } private void destroyAllPacketDisplays() { for (PreviewState state : previews.values()) { for (UUID viewerId : new HashSet<>(state.viewers)) { Player viewer = Bukkit.getPlayer(viewerId); if (viewer != null && viewer.isOnline()) sendDestroy(viewer, state.entityId); } state.viewers.clear(); } previews.clear(); } void removeForPhysicalBlock(BlockKey physical) { Block block = physical.getBlock(); if (block != null && isSupported(block)) { ContainerTarget target = ContainerTarget.fromBlock(block); if (target != null) { forgetKnownKey(target.key()); destroyPreview(target.key()); } } forgetKnownKey(physical); destroyPreview(physical); } private static Location copyLocation(Location source) { return new Location(source.getWorld(), source.getX(), source.getY(), source.getZ(), source.getYaw(), source.getPitch()); } private static boolean sameLocation(Location a, Location b) { if (a.getWorld() == null || b.getWorld() == null) return false; return a.getWorld().getUID().equals(b.getWorld().getUID()) && Double.compare(a.getX(), b.getX()) == 0 && Double.compare(a.getY(), b.getY()) == 0 && Double.compare(a.getZ(), b.getZ()) == 0 && Float.compare(a.getYaw(), b.getYaw()) == 0 && Float.compare(a.getPitch(), b.getPitch()) == 0; } private static boolean sameItem(ItemStack a, ItemStack b) { return a.getAmount() == b.getAmount() && a.isSimilar(b); } private static float radians(double degrees) { return (float) Math.toRadians(degrees); } /** Equivalent to JOML Quaternionf().rotateXYZ(x, y, z) used by 1.0.8. */ private static Quaternion4f quaternionXYZ(float x, float y, float z) { float sx = (float) Math.sin(x * 0.5f); float cx = (float) Math.cos(x * 0.5f); float sy = (float) Math.sin(y * 0.5f); float cy = (float) Math.cos(y * 0.5f); float sz = (float) Math.sin(z * 0.5f); float cz = (float) Math.cos(z * 0.5f); float qx = sx * cy * cz + cx * sy * sz; float qy = cx * sy * cz - sx * cy * sz; float qz = cx * cy * sz + sx * sy * cz; float qw = cx * cy * cz - sx * sy * sz; return new Quaternion4f(qx, qy, qz, qw); } private static final class PreviewState { private final int entityId; private final UUID entityUuid; private final Set viewers = new HashSet<>(); private Location location; private ItemStack item; private VisualSpec visual; private PreviewState(int entityId, UUID entityUuid, Location location, ItemStack item, VisualSpec visual) { this.entityId = entityId; this.entityUuid = entityUuid; this.location = location; this.item = item; this.visual = visual; } } private record VisualSpec(float scale, float pitch, float yaw, float roll, byte itemTransform, boolean glowing) {} private record ChunkKey(UUID worldId, int x, int z) { static ChunkKey of(Chunk chunk) { return new ChunkKey(chunk.getWorld().getUID(), chunk.getX(), chunk.getZ()); } static ChunkKey of(BlockKey key) { return new ChunkKey(key.worldId(), key.x() >> 4, key.z() >> 4); } } }