mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
Add studio bridge server for the Iris Studio app
- Serve world, tiles, hover, regions, players and events over a loopback HTTP bridge - Draw biome, region and river tiles with the Swing map's renderer - Add /iris std app to open the studio on a world - Add studioApp and electron studio settings - Close the bridges when the studio service stops
This commit is contained in:
1 parent
564dcdcc72
commit
86ce2856e8
13 files changed
+1375
-3
No files matched your search
@@ -21,6 +21,10 @@ package art.arcane.iris.command;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.studio.bridge.StudioBridge;
|
||||
import art.arcane.iris.studio.bridge.StudioBridges;
|
||||
import art.arcane.iris.studio.bridge.StudioWindow;
|
||||
import art.arcane.iris.studio.map.MapWindow;
|
||||
import art.arcane.iris.studio.map.PaletteExplorerStart;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
@@ -436,6 +440,28 @@ public class CommandStudio implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
|
||||
}
|
||||
|
||||
@Director(description = "Open the Iris Studio app on a world", descriptionKey = "iris.director.commandstudio.director.render_world_map_external_gui", aliases = "app")
|
||||
public void studioApp(
|
||||
@Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
if (!IrisToolbelt.isIrisWorld(world)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
|
||||
return;
|
||||
}
|
||||
UUID openerId = sender().isPlayer() ? player().getUniqueId() : null;
|
||||
PlatformChunkGenerator generator = IrisToolbelt.access(world);
|
||||
try {
|
||||
StudioBridge bridge = StudioBridges.open(world.getName(), generator::getEngine, openerId);
|
||||
if (!StudioWindow.show(bridge)) {
|
||||
IrisLogging.info("Iris Studio link for %s: %s", world.getName(), bridge.link());
|
||||
}
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
|
||||
} catch (IOException error) {
|
||||
IrisLogging.warn("Could not open the studio bridge: %s", error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// The map opens where the player stands when they are in that world, otherwise at the world origin.
|
||||
private PaletteExplorerStart mapStartIn(World world, Player opener, UUID openerId) {
|
||||
Location center = opener != null && opener.getWorld().equals(world) ? opener.getLocation() : null;
|
||||
|
||||
@@ -404,6 +404,8 @@ public class IrisSettings {
|
||||
public boolean disableTimeAndWeather = true;
|
||||
public boolean entitySpawning = true;
|
||||
public boolean autoStartDefaultStudio = false;
|
||||
public String studioApp = "";
|
||||
public String electron = "electron";
|
||||
}
|
||||
|
||||
@Data
|
||||
|
||||
@@ -42,6 +42,7 @@ import art.arcane.iris.pack.PackValidationRegistry;
|
||||
import art.arcane.iris.pack.PackValidationCache;
|
||||
import art.arcane.iris.pack.PackValidationResult;
|
||||
import art.arcane.iris.pack.PackValidator;
|
||||
import art.arcane.iris.studio.bridge.StudioBridges;
|
||||
import art.arcane.iris.studio.workspace.IrisProject;
|
||||
import art.arcane.iris.studio.workspace.IrisPackageCompiler;
|
||||
import art.arcane.iris.studio.workspace.IrisCodeWorkspace;
|
||||
@@ -161,6 +162,7 @@ public class StudioSVC implements IrisService {
|
||||
@Override
|
||||
public void onDisable() {
|
||||
quiesceDownloadsForShutdown();
|
||||
StudioBridges.closeAll();
|
||||
IrisLogging.debug("Studio Mode Active: Closing Projects");
|
||||
boolean stopping = IrisToolbelt.isServerStopping();
|
||||
LinkedHashSet<String> worldNamesToDelete = new LinkedHashSet<>(TransientWorldCleanupSupport.collectTransientStudioWorldNames(IrisWorldStorage.levelRoot()));
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.OperatingSystemMXBean;
|
||||
|
||||
/**
|
||||
* What the server asks of its machine: CPU counted like {@code top}, where 100 is one thread kept busy, and the Java
|
||||
* heap in use.
|
||||
*
|
||||
* @param cpuPercent the process's CPU use with 100 per busy thread, or null when the JVM cannot tell
|
||||
* @param threads the threads the server's CPU has, so the studio can show the most {@code cpuPercent} can reach
|
||||
* @param heapUsedBytes the Java heap in use
|
||||
* @param heapMaxBytes the most the Java heap can grow to
|
||||
*/
|
||||
record ServerUsage(Double cpuPercent, int threads, long heapUsedBytes, long heapMaxBytes) {
|
||||
private static final double PERCENT_PER_THREAD = 100D;
|
||||
|
||||
static ServerUsage sample() {
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
|
||||
return of(processCpuLoad(system), runtime.availableProcessors(), runtime.totalMemory() - runtime.freeMemory(), runtime.maxMemory());
|
||||
}
|
||||
|
||||
/** @param processCpuLoad the share of every core the process uses, or below zero when unknown */
|
||||
static ServerUsage of(double processCpuLoad, int threads, long heapUsedBytes, long heapMaxBytes) {
|
||||
Double cpuPercent = processCpuLoad < 0D ? null : processCpuLoad * threads * PERCENT_PER_THREAD;
|
||||
return new ServerUsage(cpuPercent, threads, heapUsedBytes, heapMaxBytes);
|
||||
}
|
||||
|
||||
private static double processCpuLoad(OperatingSystemMXBean system) {
|
||||
return system instanceof com.sun.management.OperatingSystemMXBean hotspot ? hotspot.getProcessCpuLoad() : -1D;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.studio.map.StudioHover;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import art.arcane.iris.studio.view.GuiMarker;
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
/**
|
||||
* An Iris Studio app's connection to one world: HTTP on the loopback interface, on a free port, each request carrying
|
||||
* the bridge's token as {@code Authorization: Bearer <token>}. JSON for the world, hovers and players; tiles in
|
||||
* {@link StudioTile}; {@code /v1/events} streams {@link StudioEvents}. Requests run on a small pool of daemon threads,
|
||||
* so a busy studio cannot hold up the server.
|
||||
*/
|
||||
public final class StudioBridge implements AutoCloseable {
|
||||
private static final String API = "/v1/";
|
||||
private static final int TOKEN_BYTES = 24;
|
||||
private static final int DEFAULT_TILE_SIZE = 128;
|
||||
private static final int LARGEST_TILE_SIZE = 512;
|
||||
private static final double SMALLEST_BLOCKS_PER_PIXEL = 1D / 16D;
|
||||
private static final double LARGEST_BLOCKS_PER_PIXEL = 4_096D;
|
||||
private static final long DROPPED_TILE_KEPT_MINUTES = 10;
|
||||
private static final long ENTITY_WAIT_MILLIS = 3_000L;
|
||||
private static final String VIEW_BIOMES = "biomes";
|
||||
private static final String VIEW_REGIONS = "regions";
|
||||
private static final String VIEW_RIVERS = "rivers";
|
||||
static final int STATUS_OK = 200;
|
||||
static final int STATUS_NO_CONTENT = 204;
|
||||
static final int STATUS_BAD_REQUEST = 400;
|
||||
static final int STATUS_UNAUTHORIZED = 401;
|
||||
static final int STATUS_NOT_FOUND = 404;
|
||||
static final int STATUS_METHOD_NOT_ALLOWED = 405;
|
||||
static final int STATUS_SERVER_ERROR = 500;
|
||||
static final int STATUS_UNAVAILABLE = 503;
|
||||
|
||||
private static final List<ViewInfo> VIEWS = List.of(
|
||||
new ViewInfo(VIEW_BIOMES, "Biomes", "The biome at each spot, in the biome's colour", "WORLD", "World"),
|
||||
new ViewInfo(VIEW_REGIONS, "Regions", "The region each spot belongs to", "WORLD", "World"),
|
||||
new ViewInfo(VIEW_RIVERS, "Rivers", "Streams, rivers, falls, ponds, lakes, sea inlets, grottos and cave pools from the hydrology",
|
||||
"WORLD", "World"));
|
||||
|
||||
private final StudioWorld world;
|
||||
private final String token;
|
||||
private final Gson gson = new GsonBuilder().serializeNulls().create();
|
||||
private final HttpServer server;
|
||||
private final int port;
|
||||
private final ExecutorService workers;
|
||||
private final ScheduledExecutorService ticker;
|
||||
private final StudioEvents events;
|
||||
private final Runnable hotloadHook;
|
||||
private final Cache<String, AtomicBoolean> droppedTiles = Caffeine.newBuilder().expireAfterWrite(DROPPED_TILE_KEPT_MINUTES, TimeUnit.MINUTES).build();
|
||||
private volatile boolean closed;
|
||||
|
||||
private StudioBridge(StudioWorld world) throws IOException {
|
||||
this.world = world;
|
||||
this.token = newToken();
|
||||
this.events = new StudioEvents(world, gson);
|
||||
this.server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
|
||||
this.port = server.getAddress().getPort();
|
||||
this.workers = Executors.newFixedThreadPool(workerCount(), daemonThreads("Iris Studio Bridge"));
|
||||
this.ticker = Executors.newSingleThreadScheduledExecutor(daemonThreads("Iris Studio Events"));
|
||||
this.hotloadHook = events::hotloaded;
|
||||
server.setExecutor(workers);
|
||||
server.createContext(API, this::handle);
|
||||
}
|
||||
|
||||
static StudioBridge start(StudioWorld world) throws IOException {
|
||||
StudioBridge bridge = new StudioBridge(world);
|
||||
bridge.server.start();
|
||||
bridge.ticker.scheduleWithFixedDelay(bridge::pollEvents, 0L, StudioEvents.POLL_INTERVAL_MILLIS, TimeUnit.MILLISECONDS);
|
||||
GuiHost.get().registerHotloadHook(bridge.hotloadHook);
|
||||
return bridge;
|
||||
}
|
||||
|
||||
public String worldName() {
|
||||
return world.name();
|
||||
}
|
||||
|
||||
public int port() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public String token() {
|
||||
return token;
|
||||
}
|
||||
|
||||
/** What the studio app opens to connect. */
|
||||
public String link() {
|
||||
return "iris-studio://127.0.0.1:" + port() + "/?token=" + token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
GuiHost.get().unregisterHotloadHook(hotloadHook);
|
||||
ticker.shutdownNow();
|
||||
events.closeAll();
|
||||
server.stop(0);
|
||||
workers.shutdownNow();
|
||||
}
|
||||
|
||||
private void pollEvents() {
|
||||
try {
|
||||
events.poll();
|
||||
} catch (Throwable error) {
|
||||
IrisLogging.debug("Studio events failed: " + error);
|
||||
}
|
||||
}
|
||||
|
||||
private void handle(HttpExchange exchange) throws IOException {
|
||||
try {
|
||||
allowAnyOrigin(exchange.getResponseHeaders());
|
||||
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
||||
exchange.sendResponseHeaders(STATUS_NO_CONTENT, -1);
|
||||
exchange.close();
|
||||
return;
|
||||
}
|
||||
if (!isAuthorized(exchange)) {
|
||||
throw new RequestError(STATUS_UNAUTHORIZED, "Missing or wrong token");
|
||||
}
|
||||
route(exchange);
|
||||
} catch (RequestError error) {
|
||||
sendJson(exchange, error.status, new ErrorBody(error.getMessage()));
|
||||
} catch (CancellationException stopped) {
|
||||
sendJson(exchange, STATUS_UNAVAILABLE, new ErrorBody("The world stopped"));
|
||||
} catch (IOException clientHungUp) {
|
||||
exchange.close();
|
||||
} catch (Throwable error) {
|
||||
IrisLogging.reportError("Studio bridge request " + exchange.getRequestURI().getPath(), error);
|
||||
sendJson(exchange, STATUS_SERVER_ERROR, new ErrorBody(String.valueOf(error.getMessage())));
|
||||
}
|
||||
}
|
||||
|
||||
private void route(HttpExchange exchange) throws IOException {
|
||||
String endpoint = exchange.getRequestURI().getPath().substring(API.length());
|
||||
Query query = Query.of(exchange.getRequestURI());
|
||||
switch (endpoint) {
|
||||
case "world" -> sendJson(exchange, STATUS_OK, worldInfo(get(exchange)));
|
||||
case "tile" -> sendBytes(exchange, "application/octet-stream", tile(get(exchange), query));
|
||||
case "tile-cancel" -> cancelTile(exchange, query);
|
||||
case "hover" -> sendJson(exchange, STATUS_OK, hover(get(exchange).engine(), query));
|
||||
case "picks" -> sendJson(exchange, STATUS_OK, new PickInspection("", List.of()));
|
||||
case "regions" -> sendJson(exchange, STATUS_OK, StudioHover.previewableRegions(get(exchange).engine()));
|
||||
case "entities" -> sendJson(exchange, STATUS_OK, entities(get(exchange)));
|
||||
case "scenes", "patterns", "noise-sources", "saved-worlds" -> sendJson(exchange, STATUS_OK, List.of());
|
||||
case "events" -> streamEvents(exchange);
|
||||
case "teleport" -> teleport(exchange, query);
|
||||
case "open" -> throw new RequestError(STATUS_NOT_FOUND, "Opening a pack file from the studio is not available in Iris v4");
|
||||
default -> throw new RequestError(STATUS_NOT_FOUND, "No such endpoint: " + endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private StudioWorld.Session get(HttpExchange exchange) {
|
||||
requireMethod(exchange, "GET");
|
||||
return runningSession();
|
||||
}
|
||||
|
||||
private StudioWorld.Session post(HttpExchange exchange) {
|
||||
requireMethod(exchange, "POST");
|
||||
return runningSession();
|
||||
}
|
||||
|
||||
private StudioWorld.Session runningSession() {
|
||||
StudioWorld.Session session = world.session();
|
||||
if (session == null) {
|
||||
throw new RequestError(STATUS_UNAVAILABLE, "The world " + world.name() + " has no running engine");
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
private static void requireMethod(HttpExchange exchange, String method) {
|
||||
if (!method.equals(exchange.getRequestMethod())) {
|
||||
throw new RequestError(STATUS_METHOD_NOT_ALLOWED, "Use " + method);
|
||||
}
|
||||
}
|
||||
|
||||
private WorldInfo worldInfo(StudioWorld.Session session) {
|
||||
Engine engine = session.engine();
|
||||
return new WorldInfo(
|
||||
world.name(),
|
||||
engine.getDimension().getLoadKey(),
|
||||
engine.getDimension().getName(),
|
||||
Long.toString(engine.getWorld().getRawWorldSeed()),
|
||||
engine.getMinHeight(),
|
||||
engine.getHeight(),
|
||||
engine.getDimension().getFluidHeight(),
|
||||
DEFAULT_TILE_SIZE,
|
||||
session.overlay() != null,
|
||||
session.tiles().hydrologyEnabled(),
|
||||
VIEWS
|
||||
);
|
||||
}
|
||||
|
||||
private static String viewOf(Query query) {
|
||||
String view = query.text("view");
|
||||
if (VIEWS.stream().noneMatch(known -> known.id().equals(view))) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "Unknown view: " + view);
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
private static String previewOf(Query query) {
|
||||
if (!query.has("preview")) {
|
||||
return null;
|
||||
}
|
||||
if (!VIEW_REGIONS.equals(viewOf(query))) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "Only the region view previews a region");
|
||||
}
|
||||
return query.text("preview");
|
||||
}
|
||||
|
||||
private static StudioHover.Hover hover(Engine engine, Query query) {
|
||||
String view = viewOf(query);
|
||||
String preview = previewOf(query);
|
||||
if (preview != null && engine.getData().getRegionLoader().load(preview) == null) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "This world has no region " + preview);
|
||||
}
|
||||
return StudioHover.sample(engine, query.number("x"), query.number("z"), preview, !VIEW_REGIONS.equals(view) || preview != null);
|
||||
}
|
||||
|
||||
private byte[] tile(StudioWorld.Session session, Query query) {
|
||||
Engine engine = session.engine();
|
||||
String view = viewOf(query);
|
||||
String preview = previewOf(query);
|
||||
int size = query.whole("size", DEFAULT_TILE_SIZE);
|
||||
double blocksPerPixel = query.number("scale");
|
||||
if (size < 1 || size > LARGEST_TILE_SIZE) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "A tile is 1 to " + LARGEST_TILE_SIZE + " pixels");
|
||||
}
|
||||
if (!(blocksPerPixel >= SMALLEST_BLOCKS_PER_PIXEL && blocksPerPixel <= LARGEST_BLOCKS_PER_PIXEL)) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "The scale is " + SMALLEST_BLOCKS_PER_PIXEL + " to " + LARGEST_BLOCKS_PER_PIXEL + " blocks per pixel");
|
||||
}
|
||||
double tileBlocks = size * blocksPerPixel;
|
||||
double startX = query.whole("x", 0) * tileBlocks;
|
||||
double startZ = query.whole("z", 0) * tileBlocks;
|
||||
AtomicBoolean dropped = query.has("request") ? droppedFlagOf(query.text("request")) : new AtomicBoolean();
|
||||
BooleanSupplier cancelled = () -> dropped.get() || closed || engine.isClosing() || engine.isClosed();
|
||||
StudioTile tile = VIEW_RIVERS.equals(view)
|
||||
? session.tiles().rivers(startX, startZ, blocksPerPixel, size, cancelled)
|
||||
: session.tiles().biomesOrRegions(view, preview, startX, startZ, blocksPerPixel, size, query.flag("heights"), cancelled);
|
||||
return tile.encode(gson);
|
||||
}
|
||||
|
||||
private void cancelTile(HttpExchange exchange, Query query) throws IOException {
|
||||
requireMethod(exchange, "POST");
|
||||
droppedFlagOf(query.text("request")).set(true);
|
||||
sendJson(exchange, STATUS_OK, new MessageBody(null));
|
||||
}
|
||||
|
||||
private AtomicBoolean droppedFlagOf(String requestId) {
|
||||
return droppedTiles.get(requestId, id -> new AtomicBoolean());
|
||||
}
|
||||
|
||||
private List<GuiMarker> entities(StudioWorld.Session session) {
|
||||
if (session.overlay() == null) {
|
||||
return List.of();
|
||||
}
|
||||
CompletableFuture<List<GuiMarker>> found = new CompletableFuture<>();
|
||||
session.overlay().requestEntities(found::complete);
|
||||
try {
|
||||
return found.get(ENTITY_WAIT_MILLIS, TimeUnit.MILLISECONDS);
|
||||
} catch (TimeoutException slow) {
|
||||
throw new RequestError(STATUS_UNAVAILABLE, "The server did not list its entities in time");
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new CancellationException("Bridge closing");
|
||||
} catch (ExecutionException failed) {
|
||||
throw new IllegalStateException(failed.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
private void teleport(HttpExchange exchange, Query query) throws IOException {
|
||||
StudioWorld.Session session = post(exchange);
|
||||
if (session.overlay() == null) {
|
||||
throw new RequestError(STATUS_NOT_FOUND, "This server cannot do that from the studio");
|
||||
}
|
||||
session.overlay().teleport(query.number("x"), query.number("z"));
|
||||
sendJson(exchange, STATUS_OK, new MessageBody(null));
|
||||
}
|
||||
|
||||
private void streamEvents(HttpExchange exchange) throws IOException {
|
||||
requireMethod(exchange, "GET");
|
||||
Headers headers = exchange.getResponseHeaders();
|
||||
headers.set("Content-Type", "text/event-stream; charset=utf-8");
|
||||
headers.set("Cache-Control", "no-cache");
|
||||
exchange.sendResponseHeaders(STATUS_OK, 0);
|
||||
OutputStream body = exchange.getResponseBody();
|
||||
body.flush();
|
||||
events.listen(body);
|
||||
}
|
||||
|
||||
private boolean isAuthorized(HttpExchange exchange) {
|
||||
String header = exchange.getRequestHeaders().getFirst("Authorization");
|
||||
String expected = "Bearer " + token;
|
||||
return header != null && MessageDigest.isEqual(
|
||||
header.getBytes(StandardCharsets.UTF_8), expected.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static void allowAnyOrigin(Headers headers) {
|
||||
headers.set("Access-Control-Allow-Origin", "*");
|
||||
headers.set("Access-Control-Allow-Headers", "Authorization");
|
||||
headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
}
|
||||
|
||||
private void sendJson(HttpExchange exchange, int status, Object body) throws IOException {
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
|
||||
send(exchange, status, gson.toJson(body).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static void sendBytes(HttpExchange exchange, String contentType, byte[] body) throws IOException {
|
||||
exchange.getResponseHeaders().set("Content-Type", contentType);
|
||||
send(exchange, STATUS_OK, body);
|
||||
}
|
||||
|
||||
private static void send(HttpExchange exchange, int status, byte[] body) throws IOException {
|
||||
try (exchange) {
|
||||
exchange.sendResponseHeaders(status, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
}
|
||||
}
|
||||
|
||||
private static String newToken() {
|
||||
byte[] bytes = new byte[TOKEN_BYTES];
|
||||
new SecureRandom().nextBytes(bytes);
|
||||
return HexFormat.of().formatHex(bytes);
|
||||
}
|
||||
|
||||
private static int workerCount() {
|
||||
return Math.max(2, Runtime.getRuntime().availableProcessors() / 2);
|
||||
}
|
||||
|
||||
private static ThreadFactory daemonThreads(String name) {
|
||||
AtomicInteger count = new AtomicInteger();
|
||||
return task -> {
|
||||
Thread thread = new Thread(task, name + " " + count.incrementAndGet());
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
};
|
||||
}
|
||||
|
||||
static final class RequestError extends RuntimeException {
|
||||
final int status;
|
||||
|
||||
RequestError(int status, String message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/** A request's query parameters; a missing or malformed one is a bad request. */
|
||||
record Query(Map<String, String> values) {
|
||||
static Query of(URI uri) {
|
||||
Map<String, String> values = new HashMap<>();
|
||||
String raw = uri.getRawQuery();
|
||||
if (raw != null) {
|
||||
for (String pair : raw.split("&")) {
|
||||
int equals = pair.indexOf('=');
|
||||
String name = equals < 0 ? pair : pair.substring(0, equals);
|
||||
String value = equals < 0 ? "" : pair.substring(equals + 1);
|
||||
values.put(decode(name), decode(value));
|
||||
}
|
||||
}
|
||||
return new Query(values);
|
||||
}
|
||||
|
||||
private static String decode(String text) {
|
||||
return URLDecoder.decode(text, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
String text(String name) {
|
||||
String value = values.get(name);
|
||||
if (value == null) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "Missing " + name);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
double number(String name) {
|
||||
try {
|
||||
double value = Double.parseDouble(text(name));
|
||||
if (!Double.isFinite(value)) {
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
return value;
|
||||
} catch (NumberFormatException malformed) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, name + " must be a number");
|
||||
}
|
||||
}
|
||||
|
||||
int whole(String name, int fallback) {
|
||||
if (!values.containsKey(name)) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(values.get(name));
|
||||
} catch (NumberFormatException malformed) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, name + " must be a whole number");
|
||||
}
|
||||
}
|
||||
|
||||
boolean has(String name) {
|
||||
return values.containsKey(name);
|
||||
}
|
||||
|
||||
boolean flag(String name) {
|
||||
String value = values.get(name);
|
||||
return "1".equals(value) || "true".equals(value);
|
||||
}
|
||||
}
|
||||
|
||||
private record ErrorBody(String error) {
|
||||
}
|
||||
|
||||
private record MessageBody(String message) {
|
||||
}
|
||||
|
||||
private record PickInspection(String detail, List<Object> sections) {
|
||||
}
|
||||
|
||||
/** @param seed as text, as JavaScript numbers cannot hold every long */
|
||||
private record WorldInfo(String world, String dimension, String dimensionName, String seed, int minY, int height,
|
||||
int fluidHeight, int tileSize, boolean hasPlayers, boolean hydrology, List<ViewInfo> views) {
|
||||
}
|
||||
|
||||
private record ViewInfo(String id, String label, String description, String group, String groupLabel) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The open bridges, one per world. Each is announced in a connection file under {@code ~/.iris/studio/bridges}, which
|
||||
* a studio app on the same machine lists to connect without a pasted link; the file goes when the bridge closes.
|
||||
*/
|
||||
public final class StudioBridges {
|
||||
private static final Path CONNECTION_FOLDER = Path.of(System.getProperty("user.home"), ".iris", "studio", "bridges");
|
||||
private static final String OWNER_ONLY = "rw-------";
|
||||
private static final Map<String, StudioBridge> OPEN = new ConcurrentHashMap<>();
|
||||
|
||||
private StudioBridges() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The bridge to {@code worldName}, started when it has none yet.
|
||||
*
|
||||
* @param engines the world's engine now, or null while it has none
|
||||
* @param openerId the player the studio's teleports move, or null for the console
|
||||
*/
|
||||
public static synchronized StudioBridge open(String worldName, Supplier<Engine> engines, UUID openerId) throws IOException {
|
||||
StudioBridge open = OPEN.get(worldName);
|
||||
if (open != null) {
|
||||
return open;
|
||||
}
|
||||
StudioBridge bridge = StudioBridge.start(new StudioWorld(worldName, engines, openerId));
|
||||
OPEN.put(worldName, bridge);
|
||||
announce(bridge);
|
||||
return bridge;
|
||||
}
|
||||
|
||||
public static synchronized void closeAll() {
|
||||
StudioWindow.closeAll();
|
||||
for (StudioBridge bridge : OPEN.values()) {
|
||||
bridge.close();
|
||||
withdraw(bridge);
|
||||
}
|
||||
OPEN.clear();
|
||||
}
|
||||
|
||||
private static void announce(StudioBridge bridge) {
|
||||
try {
|
||||
Files.createDirectories(CONNECTION_FOLDER);
|
||||
Path file = connectionFile(bridge);
|
||||
Connection connection = new Connection(bridge.worldName(), bridge.port(), bridge.token(), bridge.link(),
|
||||
ProcessHandle.current().pid(), System.currentTimeMillis());
|
||||
Files.deleteIfExists(file);
|
||||
createReadableByOwnerOnly(file);
|
||||
Files.writeString(file, new Gson().toJson(connection), StandardCharsets.UTF_8);
|
||||
} catch (IOException error) {
|
||||
IrisLogging.warn("Could not write the studio connection file: %s", error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// The file holds the token, so other users of the machine must not read it, not even before it is written.
|
||||
private static void createReadableByOwnerOnly(Path file) throws IOException {
|
||||
if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
|
||||
Files.createFile(file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(OWNER_ONLY)));
|
||||
return;
|
||||
}
|
||||
Files.createFile(file);
|
||||
}
|
||||
|
||||
private static void withdraw(StudioBridge bridge) {
|
||||
try {
|
||||
Files.deleteIfExists(connectionFile(bridge));
|
||||
} catch (IOException error) {
|
||||
IrisLogging.debug("Could not remove the studio connection file: " + error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static Path connectionFile(StudioBridge bridge) {
|
||||
return CONNECTION_FOLDER.resolve(bridge.port() + ".json");
|
||||
}
|
||||
|
||||
/** @param pid the server's process, so the studio can skip files a crashed server left */
|
||||
private record Connection(String world, int port, String token, String link, long pid, long startedMillis) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.studio.view.GuiMarker;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* Server-sent events to every connected studio: {@code players} when a player moves, {@code world} when the world's
|
||||
* engine changes (a hotload), {@code usage} with the server's CPU and heap every second, and a comment now and then so
|
||||
* a dead connection is noticed. A studio that stops
|
||||
* reading is dropped.
|
||||
*/
|
||||
final class StudioEvents {
|
||||
private static final byte[] KEEP_ALIVE = ": alive\n\n".getBytes(StandardCharsets.UTF_8);
|
||||
static final long POLL_INTERVAL_MILLIS = 250L;
|
||||
private static final long KEEP_ALIVE_INTERVAL_MILLIS = 10_000L;
|
||||
private static final long USAGE_INTERVAL_MILLIS = 1_000L;
|
||||
|
||||
private final StudioWorld world;
|
||||
private final Gson gson;
|
||||
private final List<OutputStream> listeners = new CopyOnWriteArrayList<>();
|
||||
/** Listeners not yet told the world's state. */
|
||||
private final List<OutputStream> joining = new CopyOnWriteArrayList<>();
|
||||
private final AtomicBoolean listenerJoined = new AtomicBoolean();
|
||||
private final AtomicBoolean usageWanted = new AtomicBoolean();
|
||||
private final AtomicBoolean hotloaded = new AtomicBoolean();
|
||||
private List<GuiMarker> lastPlayers;
|
||||
private Engine lastEngine;
|
||||
private long lastSentMillis;
|
||||
private long lastUsageMillis;
|
||||
|
||||
StudioEvents(StudioWorld world, Gson gson) {
|
||||
this.world = world;
|
||||
this.gson = gson;
|
||||
}
|
||||
|
||||
void listen(OutputStream stream) {
|
||||
listeners.add(stream);
|
||||
joining.add(stream);
|
||||
listenerJoined.set(true);
|
||||
usageWanted.set(true);
|
||||
}
|
||||
|
||||
/** The pack was hotloaded; the engine may be the same, its streams are not. */
|
||||
void hotloaded() {
|
||||
hotloaded.set(true);
|
||||
}
|
||||
|
||||
/** Sends what changed since the last poll; called every {@link #POLL_INTERVAL_MILLIS} from one thread. */
|
||||
void poll() {
|
||||
if (listeners.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
StudioWorld.Session session = world.session();
|
||||
Engine engine = session == null ? null : session.engine();
|
||||
List<OutputStream> joined = List.copyOf(joining);
|
||||
if (engine != lastEngine || hotloaded.getAndSet(false)) {
|
||||
lastEngine = engine;
|
||||
send("world", new WorldChange(engine != null));
|
||||
} else {
|
||||
greet(joined, engine != null);
|
||||
}
|
||||
joining.removeAll(joined);
|
||||
List<GuiMarker> players = session == null || session.overlay() == null ? List.of() : session.overlay().players();
|
||||
if (listenerJoined.getAndSet(false) || !Objects.equals(players, lastPlayers)) {
|
||||
lastPlayers = players;
|
||||
send("players", players);
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
if (usageWanted.getAndSet(false) || now - lastUsageMillis >= USAGE_INTERVAL_MILLIS) {
|
||||
lastUsageMillis = now;
|
||||
send("usage", ServerUsage.sample());
|
||||
}
|
||||
if (now - lastSentMillis > KEEP_ALIVE_INTERVAL_MILLIS) {
|
||||
sendToAll(KEEP_ALIVE);
|
||||
}
|
||||
}
|
||||
|
||||
void closeAll() {
|
||||
for (OutputStream listener : listeners) {
|
||||
closeQuietly(listener);
|
||||
}
|
||||
listeners.clear();
|
||||
joining.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells studios that just connected what state the world is in, them alone. A studio takes its first world event as
|
||||
* the state it connected to, so without one of its own it would take the next hotload for it and not redraw.
|
||||
*/
|
||||
private void greet(List<OutputStream> joined, boolean running) {
|
||||
if (joined.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
byte[] message = eventOf("world", new WorldChange(running));
|
||||
for (OutputStream listener : joined) {
|
||||
sendTo(listener, message);
|
||||
}
|
||||
}
|
||||
|
||||
private void send(String event, Object data) {
|
||||
sendToAll(eventOf(event, data));
|
||||
}
|
||||
|
||||
private byte[] eventOf(String event, Object data) {
|
||||
return ("event: " + event + "\ndata: " + gson.toJson(data) + "\n\n").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private void sendToAll(byte[] message) {
|
||||
lastSentMillis = System.currentTimeMillis();
|
||||
for (OutputStream listener : listeners) {
|
||||
sendTo(listener, message);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendTo(OutputStream listener, byte[] message) {
|
||||
try {
|
||||
listener.write(message);
|
||||
listener.flush();
|
||||
} catch (IOException gone) {
|
||||
listeners.remove(listener);
|
||||
joining.remove(listener);
|
||||
closeQuietly(listener);
|
||||
}
|
||||
}
|
||||
|
||||
private static void closeQuietly(OutputStream stream) {
|
||||
try {
|
||||
stream.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
/** @param running whether the world has an engine again; the studio redraws either way */
|
||||
private record WorldChange(boolean running) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A square of the map as the Iris Studio app reads it, little endian:
|
||||
* <pre>
|
||||
* u32 header length | header, UTF-8 JSON | padding to 4 bytes
|
||||
* i16 subjects[grid²] | padding to 4 | i16 regions[grid²] | padding to 4 | f32 heights[grid²], when the header says so
|
||||
* </pre>
|
||||
* The grids hold {@code (size + 2)²} cells row by row: the tile's pixels inside a ring of the neighbouring tiles' edge
|
||||
* pixels, so edges and slopes continue across tiles. Subjects and regions index the header's labels.
|
||||
*
|
||||
* @param subjectKind BIOME, REGION or WATER: what the subjects are
|
||||
* @param heights null when the tile carries none
|
||||
*/
|
||||
record StudioTile(int size, double blocksPerPixel, String subjectKind, List<Label> labels, short[] subjects, short[] regions,
|
||||
float[] heights) {
|
||||
static final short NO_LABEL = -1;
|
||||
private static final int ALIGNMENT_BYTES = 4;
|
||||
|
||||
/** @param color 0xRRGGBB */
|
||||
record Label(String kind, String key, String name, int color) {
|
||||
}
|
||||
|
||||
byte[] encode(Gson gson) {
|
||||
byte[] header = gson.toJson(new Header(size, blocksPerPixel, subjectKind, labels, heights != null, false))
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
int cells = (size + 2) * (size + 2);
|
||||
int length = aligned(Integer.BYTES + header.length) + aligned(cells * Short.BYTES) * 2
|
||||
+ (heights == null ? 0 : cells * Float.BYTES);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(header.length).put(header);
|
||||
buffer.position(aligned(buffer.position()));
|
||||
putShorts(buffer, subjects);
|
||||
putShorts(buffer, regions);
|
||||
if (heights != null) {
|
||||
buffer.asFloatBuffer().put(heights);
|
||||
}
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
private static void putShorts(ByteBuffer buffer, short[] grid) {
|
||||
buffer.asShortBuffer().put(grid);
|
||||
buffer.position(aligned(buffer.position() + grid.length * Short.BYTES));
|
||||
}
|
||||
|
||||
private static int aligned(int bytes) {
|
||||
return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
|
||||
}
|
||||
|
||||
private record Header(int size, double blocksPerPixel, String subjectKind, List<Label> labels, boolean heights,
|
||||
boolean pickNoise) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.studio.map.RiverKey;
|
||||
import art.arcane.iris.studio.map.components.MapLabels;
|
||||
import art.arcane.iris.studio.map.components.MapLayer;
|
||||
import art.arcane.iris.studio.map.components.MapTile;
|
||||
import art.arcane.iris.studio.map.components.MapTileRenderer;
|
||||
import art.arcane.iris.studio.map.components.PickDisplay;
|
||||
import art.arcane.iris.studio.map.components.TileType;
|
||||
import art.arcane.iris.studio.render.IrisRenderer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
/** Draws the studio app's map views with the renderer the Swing map uses, one tile at a time. */
|
||||
final class StudioTiles {
|
||||
private static final int RGB = 0xFFFFFF;
|
||||
private static final short DRY = 0;
|
||||
private static final String DRY_KEY = "dry";
|
||||
private static final int DRY_COLOR = 0x1C1F26;
|
||||
private static final int MAX_FINISH_ATTEMPTS = 200;
|
||||
private static final long FINISH_WAIT_MILLIS = 50L;
|
||||
|
||||
private final Engine engine;
|
||||
private final MapTileRenderer renderer;
|
||||
private final IrisRenderer waterRenderer;
|
||||
private final List<StudioTile.Label> waterLabels;
|
||||
private final Map<Integer, Short> waterLabelByColor;
|
||||
|
||||
StudioTiles(Engine engine, MapTileRenderer renderer) {
|
||||
this.engine = engine;
|
||||
this.renderer = renderer;
|
||||
this.waterRenderer = new IrisRenderer(engine);
|
||||
List<StudioTile.Label> labels = new ArrayList<>();
|
||||
labels.add(new StudioTile.Label("WATER", DRY_KEY, "No water", DRY_COLOR));
|
||||
Map<Integer, Short> byColor = new HashMap<>();
|
||||
for (RiverKey.Row row : RiverKey.rows()) {
|
||||
byColor.put(row.color() & RGB, (short) labels.size());
|
||||
labels.add(new StudioTile.Label("WATER", row.label(), row.label(), row.color() & RGB));
|
||||
}
|
||||
this.waterLabels = List.copyOf(labels);
|
||||
this.waterLabelByColor = Map.copyOf(byColor);
|
||||
}
|
||||
|
||||
boolean hydrologyEnabled() {
|
||||
var runtime = engine.getComplex().getHydrologyRuntime();
|
||||
return runtime != null && runtime.enabled();
|
||||
}
|
||||
|
||||
StudioTile biomesOrRegions(String view, String previewRegion, double startX, double startZ, double blocksPerPixel, int size,
|
||||
boolean withHeights, BooleanSupplier cancelled) {
|
||||
MapLayer layer = layerOf(view, previewRegion);
|
||||
MapTileRenderer.TileRender render = renderer.prepareTile(startX, startZ, blocksPerPixel, size, layer, withHeights);
|
||||
MapTile tile = render.render(cancelled);
|
||||
for (int attempt = 0; !render.complete() && attempt < MAX_FINISH_ATTEMPTS; attempt++) {
|
||||
pause(cancelled);
|
||||
tile = render.render(cancelled);
|
||||
}
|
||||
return wire(tile, blocksPerPixel, withHeights && tile.hasHeights());
|
||||
}
|
||||
|
||||
StudioTile rivers(double startX, double startZ, double blocksPerPixel, int size, BooleanSupplier cancelled) {
|
||||
int grid = size + 2;
|
||||
short[] subjects = new short[grid * grid];
|
||||
Arrays.fill(subjects, DRY);
|
||||
if (hydrologyEnabled()) {
|
||||
IrisRenderer.WaterTile water = waterRenderer.prepareStudioWater(startX - blocksPerPixel, startZ - blocksPerPixel, blocksPerPixel, grid);
|
||||
int[] colors = water.render(null, false, cancelled);
|
||||
for (int attempt = 0; !water.complete() && attempt < MAX_FINISH_ATTEMPTS; attempt++) {
|
||||
pause(cancelled);
|
||||
colors = water.render(null, false, cancelled);
|
||||
}
|
||||
for (int cell = 0; cell < colors.length; cell++) {
|
||||
subjects[cell] = waterLabelByColor.getOrDefault(colors[cell] & RGB, DRY);
|
||||
}
|
||||
}
|
||||
return new StudioTile(size, blocksPerPixel, "WATER", waterLabels, subjects, subjects, null);
|
||||
}
|
||||
|
||||
private static MapLayer layerOf(String view, String previewRegion) {
|
||||
if ("regions".equals(view)) {
|
||||
return previewRegion == null ? MapLayer.regions(PickDisplay.PICKS) : MapLayer.regionPreview(previewRegion, PickDisplay.PICKS);
|
||||
}
|
||||
return MapLayer.biomes(PickDisplay.PICKS, false);
|
||||
}
|
||||
|
||||
private StudioTile wire(MapTile tile, double blocksPerPixel, boolean withHeights) {
|
||||
int size = tile.size();
|
||||
int grid = size + 2;
|
||||
Labelling labelling = new Labelling();
|
||||
short[] subjects = new short[grid * grid];
|
||||
short[] regions = new short[grid * grid];
|
||||
float[] heights = withHeights ? new float[grid * grid] : null;
|
||||
for (int z = -1; z <= size; z++) {
|
||||
for (int x = -1; x <= size; x++) {
|
||||
int cell = (z + 1) * grid + x + 1;
|
||||
subjects[cell] = labelling.indexOf(tile.labels(), tile.subjectAt(x, z));
|
||||
regions[cell] = labelling.indexOf(tile.labels(), tile.regionAt(x, z));
|
||||
if (heights != null) {
|
||||
heights[cell] = (float) tile.heightAt(x, z);
|
||||
}
|
||||
}
|
||||
}
|
||||
List<StudioTile.Label> labels = labelling.labels(renderer);
|
||||
return new StudioTile(size, blocksPerPixel, tile.subjectKind().name(), labels, subjects, regions, heights);
|
||||
}
|
||||
|
||||
private static void pause(BooleanSupplier cancelled) {
|
||||
if (cancelled.getAsBoolean()) {
|
||||
throw new CancellationException("Tile dropped");
|
||||
}
|
||||
try {
|
||||
Thread.sleep(FINISH_WAIT_MILLIS);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new CancellationException("Tile interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
/** Renumbers the labels a tile uses from 0, so its header lists only those. */
|
||||
private static final class Labelling {
|
||||
private final Map<Short, Short> indexByLabelId = new HashMap<>();
|
||||
private final List<Short> usedLabelIds = new ArrayList<>();
|
||||
|
||||
short indexOf(MapLabels labels, short labelId) {
|
||||
if (labelId == MapLabels.NONE || labels.label(labelId) == null) {
|
||||
return StudioTile.NO_LABEL;
|
||||
}
|
||||
return indexByLabelId.computeIfAbsent(labelId, id -> {
|
||||
usedLabelIds.add(id);
|
||||
return (short) (usedLabelIds.size() - 1);
|
||||
});
|
||||
}
|
||||
|
||||
List<StudioTile.Label> labels(MapTileRenderer renderer) {
|
||||
List<StudioTile.Label> labels = new ArrayList<>();
|
||||
for (short id : usedLabelIds) {
|
||||
MapLabels.Label label = renderer.labels().label(id);
|
||||
labels.add(new StudioTile.Label(label.kind().name(), label.key(), label.name(),
|
||||
renderer.legendColor(label, TileType.BIOME) & RGB));
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Opens the Iris Studio window on a bridge, from the app folder the studio settings name. The app keeps one window:
|
||||
* a second start hands its link to the open window and exits. Windows the server started close when it stops, as
|
||||
* their bridges go with it.
|
||||
*/
|
||||
public final class StudioWindow {
|
||||
private static final Path LOG_FILE = Path.of(System.getProperty("user.home"), ".iris", "studio", "window.log");
|
||||
private static final String DEFAULT_ELECTRON = "electron";
|
||||
private static final String BUILT_MAIN = "out/main/index.js";
|
||||
/** Set by terminals that are Electron apps themselves; left in, Electron would start as plain Node with no window. */
|
||||
private static final String RUN_AS_PLAIN_NODE = "ELECTRON_RUN_AS_NODE";
|
||||
private static final List<Process> STARTED = new ArrayList<>();
|
||||
|
||||
private StudioWindow() {
|
||||
}
|
||||
|
||||
/** False when no app is set or it could not start, so the caller's printed link is the only way in. */
|
||||
public static synchronized boolean show(StudioBridge bridge) {
|
||||
IrisSettings.IrisSettingsStudio settings = IrisSettings.get().getStudio();
|
||||
String appFolder = settings.getStudioApp();
|
||||
if (appFolder == null || appFolder.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
Path app = Path.of(appFolder);
|
||||
if (!Files.isRegularFile(app.resolve(BUILT_MAIN))) {
|
||||
IrisLogging.warn("Iris Studio is not built in %s; run npm run build there.", app);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
STARTED.removeIf(process -> !process.isAlive());
|
||||
STARTED.add(start(electronBinary(settings), app, bridge.link()));
|
||||
return true;
|
||||
} catch (IOException error) {
|
||||
IrisLogging.warn("Could not open Iris Studio: %s", error.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized void closeAll() {
|
||||
STARTED.forEach(Process::destroy);
|
||||
STARTED.clear();
|
||||
}
|
||||
|
||||
private static Process start(String electron, Path app, String link) throws IOException {
|
||||
Files.createDirectories(LOG_FILE.getParent());
|
||||
ProcessBuilder builder = new ProcessBuilder(electron, app.toString(), link)
|
||||
.redirectErrorStream(true)
|
||||
.redirectOutput(ProcessBuilder.Redirect.to(LOG_FILE.toFile()));
|
||||
builder.environment().remove(RUN_AS_PLAIN_NODE);
|
||||
return builder.start();
|
||||
}
|
||||
|
||||
private static String electronBinary(IrisSettings.IrisSettingsStudio settings) {
|
||||
String electron = settings.getElectron();
|
||||
return electron == null || electron.isBlank() ? DEFAULT_ELECTRON : electron;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.studio.map.components.MapTileRenderer;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import art.arcane.iris.studio.view.GuiOverlay;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The world a bridge shows. Its engine is asked for again whenever the one in use closes, as a hotload or a restart of
|
||||
* the world does, so a bridge outlives them.
|
||||
*/
|
||||
final class StudioWorld {
|
||||
private final String name;
|
||||
private final Supplier<Engine> engines;
|
||||
private final UUID openerId;
|
||||
private Session session;
|
||||
|
||||
/**
|
||||
* @param engines the world's engine now; null while it has none
|
||||
* @param openerId the player the studio teleports, or null when the console opened it
|
||||
*/
|
||||
StudioWorld(String name, Supplier<Engine> engines, UUID openerId) {
|
||||
this.name = Objects.requireNonNull(name, "name");
|
||||
this.engines = Objects.requireNonNull(engines, "engines");
|
||||
this.openerId = openerId;
|
||||
}
|
||||
|
||||
String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/** The world's engine and what the bridge draws it with; null while the world has no running engine. */
|
||||
synchronized Session session() {
|
||||
if (session != null && isRunning(session.engine())) {
|
||||
return session;
|
||||
}
|
||||
Engine engine = engines.get();
|
||||
session = isRunning(engine)
|
||||
? new Session(engine, new StudioTiles(engine, new MapTileRenderer(engine)), GuiHost.get().overlayFor(engine, openerId))
|
||||
: null;
|
||||
return session;
|
||||
}
|
||||
|
||||
private static boolean isRunning(Engine engine) {
|
||||
return engine != null && !engine.isClosed() && !engine.isClosing() && engine.getComplex() != null;
|
||||
}
|
||||
|
||||
/** @param overlay the server's players and teleports; null on a platform without one */
|
||||
record Session(Engine engine, StudioTiles tiles, GuiOverlay overlay) {
|
||||
}
|
||||
}
|
||||
@@ -30,16 +30,16 @@ import java.util.Map;
|
||||
/**
|
||||
* What the colours of the river view stand for, one row per colour, so features drawn alike share a row.
|
||||
*/
|
||||
final class RiverKey {
|
||||
public final class RiverKey {
|
||||
private static final List<Row> ROWS = buildRows();
|
||||
|
||||
private RiverKey() {
|
||||
}
|
||||
|
||||
record Row(int color, String label) {
|
||||
public record Row(int color, String label) {
|
||||
}
|
||||
|
||||
static List<Row> rows() {
|
||||
public static List<Row> rows() {
|
||||
return ROWS;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.map;
|
||||
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.terrain.IrisRegion;
|
||||
import art.arcane.iris.pack.loading.IrisRegistrant;
|
||||
import art.arcane.iris.studio.map.MapHoverProbe.Details;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** What the Iris Studio app's hover card shows about one spot, from the same probe the Swing map's card uses. */
|
||||
public final class StudioHover {
|
||||
private static final int RGB = 0xFFFFFF;
|
||||
|
||||
private StudioHover() {
|
||||
}
|
||||
|
||||
/** @param previewRegionKey the region the region view previews everywhere, or null for the world as it is */
|
||||
public static Hover sample(Engine engine, double worldX, double worldZ, String previewRegionKey, boolean explainsBiome) {
|
||||
Details details = MapHoverProbe.sample(engine, worldX, worldZ, previewRegionKey, explainsBiome);
|
||||
return new Hover(
|
||||
details.worldX(),
|
||||
details.worldZ(),
|
||||
label(engine, details.surfaceBiome()),
|
||||
label(engine, details.caveBiome()),
|
||||
label(engine, details.region()),
|
||||
details.vanillaBiome(),
|
||||
details.height(),
|
||||
details.fluidHeight(),
|
||||
details.slopeDegrees(),
|
||||
packPath(engine, details.surfaceBiome()),
|
||||
packPath(engine, details.region()),
|
||||
steps(details.pickPath())
|
||||
);
|
||||
}
|
||||
|
||||
/** The regions the world picks biomes for, which the region view can preview. */
|
||||
public static List<Label> previewableRegions(Engine engine) {
|
||||
return engine.getComplex().noisePickedRegions().stream().map(region -> label(engine, region)).toList();
|
||||
}
|
||||
|
||||
private static Label label(Engine engine, IrisBiome biome) {
|
||||
if (biome == null) {
|
||||
return null;
|
||||
}
|
||||
NoisePickSpread.Option option = PickMeasuring.biomeOption(engine, biome);
|
||||
return new Label("BIOME", option.key(), option.name(), option.color() & RGB);
|
||||
}
|
||||
|
||||
private static Label label(Engine engine, IrisRegion region) {
|
||||
if (region == null) {
|
||||
return null;
|
||||
}
|
||||
NoisePickSpread.Option option = PickMeasuring.regionOption(engine, region);
|
||||
return new Label("REGION", option.key(), option.name(), option.color() & RGB);
|
||||
}
|
||||
|
||||
private static Label label(String kind, NoisePickSpread.Option option) {
|
||||
return new Label(kind, option.key(), option.name(), option.color() & RGB);
|
||||
}
|
||||
|
||||
private static List<Step> steps(List<MapHoverProbe.PickStep> path) {
|
||||
List<Step> steps = new ArrayList<>();
|
||||
String previous = null;
|
||||
for (MapHoverProbe.PickStep step : path) {
|
||||
boolean regionStep = step.kind() == MapHoverProbe.StepKind.REGION_NOISE || step.kind() == MapHoverProbe.StepKind.PREVIEWED_REGION;
|
||||
String kind = regionStep ? "REGION" : "BIOME";
|
||||
List<Band> bands = step.bands().stream()
|
||||
.map(band -> new Band(label(kind, band.option()), band.fromNoise(), band.toNoise()))
|
||||
.toList();
|
||||
steps.add(new Step(wireKind(step.kind()), label(kind, step.picked()), step.detail(),
|
||||
step.kind() == MapHoverProbe.StepKind.CHILD ? previous : null,
|
||||
Double.isNaN(step.noise()) ? null : step.noise(), bands));
|
||||
previous = step.picked().name();
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
|
||||
private static String wireKind(MapHoverProbe.StepKind kind) {
|
||||
return switch (kind) {
|
||||
case REGION_NOISE -> "REGION";
|
||||
case PREVIEWED_REGION -> "PREVIEW";
|
||||
case BIOME_NOISE -> "BIOME";
|
||||
case CHILD -> "CHILD";
|
||||
};
|
||||
}
|
||||
|
||||
private static String packPath(Engine engine, IrisRegistrant registrant) {
|
||||
if (registrant == null || registrant.getLoadFile() == null || engine.getData() == null) {
|
||||
return null;
|
||||
}
|
||||
Path pack = engine.getData().getDataFolder().toPath().toAbsolutePath();
|
||||
Path file = registrant.getLoadFile().toPath().toAbsolutePath();
|
||||
return file.startsWith(pack) ? pack.relativize(file).toString().replace('\\', '/') : null;
|
||||
}
|
||||
|
||||
public record Label(String kind, String key, String name, int color) {
|
||||
}
|
||||
|
||||
public record Band(Label option, double from, double to) {
|
||||
}
|
||||
|
||||
public record Step(String kind, Label picked, String list, String replaced, Double noise, List<Band> bands) {
|
||||
}
|
||||
|
||||
public record Hover(double worldX, double worldZ, Label biome, Label caveBiome, Label region, String vanillaBiome,
|
||||
double height, double fluidHeight, double slopeDegrees, String biomeFile, String regionFile,
|
||||
List<Step> pickPath) {
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user