Files
src
build.gradle
README.md
settings.gradle
Code
6 497
src/main/java/com/kodari/billboards/ImageBillboards.java
package com.kodari.billboards;
import com.cryptomorin.xseries.XMaterial;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.MapMeta;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
public final class ImageBillboards extends JavaPlugin implements Listener, CommandExecutor, TabCompleter {
private final Map<String, Board> boards = new LinkedHashMap<>();
private final Map<UUID, Session> sessions = new HashMap<>();
private final Map<String, List<BufferedImage>> cache = new LinkedHashMap<>(16, 0.75f, true);
private final AtomicLong generation = new AtomicLong();
private ExecutorService worker;
private File images;
private File storage;
private NamespacedKey frameKey;
private NamespacedKey toolKey;
private volatile List<String> imageNames = Collections.emptyList();
private long cachedBytes;
@Override public void onEnable() {
saveDefaultConfig();
images = new File(getDataFolder(), "images");
if (!images.isDirectory() && !images.mkdirs()) getLogger().warning("Could not create images directory");
storage = new File(getDataFolder(), "billboards.yml");
frameKey = new NamespacedKey(this, "billboard");
toolKey = new NamespacedKey(this, "tool");
worker = Executors.newSingleThreadExecutor(r -> { Thread t = new Thread(r, "Billboard-image-worker"); t.setDaemon(true); return t; });
Bukkit.getPluginManager().registerEvents(this, this);
getCommand("billboard").setExecutor(this);
getCommand("billboard").setTabCompleter(this);
load();
scan();
for (Board board : boards.values()) render(board);
}
@Override public void onDisable() {
generation.incrementAndGet();
if (worker != null) worker.shutdownNow();
save();
synchronized (cache) { cache.clear(); cachedBytes = 0; }
}
private String color(String text) { return ChatColor.translateAlternateColorCodes('&', text); }
private void msg(CommandSender sender, String text) { sender.sendMessage(color(getConfig().getString("messages.prefix", "&8[&bBillboards&8] &7") + text)); }
private boolean allowed(CommandSender sender, String permission) {
if (sender.hasPermission(permission) || sender.hasPermission("imagebillboards.admin")) return true;
msg(sender, getConfig().getString("messages.no-permission", "&cYou do not have permission.")); return false;
}
private boolean viewer(CommandSender s) {
return s.hasPermission("imagebillboards.admin") || s.hasPermission("imagebillboards.create") || s.hasPermission("imagebillboards.edit") || s.hasPermission("imagebillboards.remove") || s.hasPermission("imagebillboards.reload");
}
private int limit(String key, int fallback) { return Math.max(1, getConfig().getInt("limits." + key, fallback)); }
private boolean validSize(int w, int h) {
return w > 0 && h > 0 && w <= limit("max-width-tiles", 16) && h <= limit("max-height-tiles", 16) && (long) w * h <= limit("max-tiles-per-billboard", 128);
}
private static final class Board {
String id, image, world;
int x, y, z, width, height;
BlockFace face;
boolean stretch;
long revision;
final List<UUID> frames = new ArrayList<>();
}
private static final class Session {
String image, moving;
}
private static final class Editor implements InventoryHolder {
final String id;
Inventory inventory;
Editor(String id) { this.id = id; }
@Override public Inventory getInventory() { return inventory; }
}
private void load() {
YamlConfiguration yaml = YamlConfiguration.loadConfiguration(storage);
ConfigurationSection root = yaml.getConfigurationSection("billboards");
if (root == null) return;
for (String id : root.getKeys(false)) {
try {
ConfigurationSection s = root.getConfigurationSection(id);
if (s == null) continue;
Board b = new Board(); b.id = id; b.image = s.getString("image"); b.world = s.getString("world");
b.x = s.getInt("x"); b.y = s.getInt("y"); b.z = s.getInt("z"); b.width = s.getInt("width"); b.height = s.getInt("height");
b.face = BlockFace.valueOf(s.getString("face", "NORTH")); b.stretch = s.getBoolean("stretch");
if (b.image == null || b.world == null || !horizontal(b.face) || !validSize(b.width, b.height)) throw new IllegalArgumentException("invalid fields or dimensions");
for (String uuid : s.getStringList("frames")) try { b.frames.add(UUID.fromString(uuid)); } catch (IllegalArgumentException ignored) { }
boards.put(id, b);
} catch (RuntimeException ex) { getLogger().warning("Skipping billboard " + id + ": " + ex.getMessage()); }
}
}
private void save() {
YamlConfiguration yaml = new YamlConfiguration();
for (Board b : boards.values()) {
String p = "billboards." + b.id + ".";
yaml.set(p + "image", b.image); yaml.set(p + "world", b.world); yaml.set(p + "x", b.x); yaml.set(p + "y", b.y); yaml.set(p + "z", b.z);
yaml.set(p + "width", b.width); yaml.set(p + "height", b.height); yaml.set(p + "face", b.face.name()); yaml.set(p + "stretch", b.stretch);
List<String> ids = new ArrayList<>(); for (UUID uuid : b.frames) ids.add(uuid.toString()); yaml.set(p + "frames", ids);
}
try { yaml.save(storage); } catch (IOException ex) { getLogger().severe("Could not save billboards: " + ex.getMessage()); }
}
private void scan() {
worker.execute(() -> {
File[] files = images.listFiles(f -> f.isFile() && supported(f.getName()));
List<String> names = new ArrayList<>();
if (files != null) for (File f : files) names.add(f.getName());
names.sort(String.CASE_INSENSITIVE_ORDER); imageNames = Collections.unmodifiableList(names);
});
}
private boolean supported(String name) {
String n = name.toLowerCase(Locale.ROOT); return n.endsWith(".png") || n.endsWith(".jpg") || n.endsWith(".jpeg") || n.endsWith(".webp");
}
private File imageFile(String name) throws IOException {
File file = new File(images, name).getCanonicalFile();
if (!file.getParentFile().equals(images.getCanonicalFile()) || !supported(name) || !file.isFile()) throw new IOException("Image not found: " + name);
return file;
}
private List<BufferedImage> process(String name, int w, int h, boolean stretch, int maxW, int maxH, long maxPixels, long maxBytes, String scaling, long cacheLimit) throws IOException {
File file = imageFile(name);
long fileSize = Files.size(file.toPath());
if (fileSize > maxBytes) throw new IOException("Image exceeds file-size limit");
String key = name + "|" + file.lastModified() + "|" + fileSize + "|" + w + "|" + h + "|" + stretch + "|" + scaling;
synchronized (cache) { List<BufferedImage> hit = cache.get(key); if (hit != null) return hit; }
BufferedImage source;
try (ImageInputStream in = ImageIO.createImageInputStream(file)) {
if (in == null) throw new IOException("Cannot open image");
Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if (!readers.hasNext()) throw new IOException("No decoder for this image format");
ImageReader reader = readers.next();
try {
reader.setInput(in, true, true);
int iw = reader.getWidth(0), ih = reader.getHeight(0);
if (iw <= 0 || ih <= 0 || iw > maxW || ih > maxH || (long) iw * ih > maxPixels) throw new IOException("Image exceeds dimension or pixel limits");
source = reader.read(0);
} finally { reader.dispose(); }
}
if (source == null) throw new IOException("Image decode failed");
int tw = w * 128, th = h * 128;
int dw = tw, dh = th;
if (!stretch) { double factor = Math.min((double) tw / source.getWidth(), (double) th / source.getHeight()); dw = Math.max(1, (int) Math.round(source.getWidth() * factor)); dh = Math.max(1, (int) Math.round(source.getHeight() * factor)); }
BufferedImage scaled = new BufferedImage(tw, th, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = scaled.createGraphics();
Object interpolation = scaling.equalsIgnoreCase("NEAREST") ? RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR : scaling.equalsIgnoreCase("BILINEAR") ? RenderingHints.VALUE_INTERPOLATION_BILINEAR : RenderingHints.VALUE_INTERPOLATION_BICUBIC;
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);