Serve the studio map over a local bridge

/iris studio map now starts a bridge for the world instead of the Swing
map: HTTP on 127.0.0.1, a free port and a per-bridge token, with the
world, tiles, hover, entities, teleport and open-in-editor, and server-sent
events for players and hotloads. A connection file under
~/.iris/studio/bridges lets a studio app on the same machine find it.
Works on headless servers. Bridges close with the plugin or mod.
This commit is contained in:
piexel committed 2026-11-05 23:26:38 +01:00
1 parent 60ba7e644c
commit a375d3b2f0
31 files changed
+1104 -15

No files matched your search

@@ -23,8 +23,10 @@ import art.arcane.iris.platform.bukkit.BukkitPlatform;
import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.gui.ImageMapStudioGUI; import art.arcane.iris.core.gui.ImageMapStudioGUI;
import art.arcane.iris.core.gui.NoiseExplorerGUI; import art.arcane.iris.core.gui.NoiseExplorerGUI;
import art.arcane.iris.core.gui.VisionGUI;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.localization.IrisMessages;
import art.arcane.iris.core.studio.bridge.StudioBridge;
import art.arcane.iris.core.studio.bridge.StudioBridges;
import art.arcane.iris.core.project.IrisProject; import art.arcane.iris.core.project.IrisProject;
import art.arcane.iris.core.project.IrisCodeWorkspace; import art.arcane.iris.core.project.IrisCodeWorkspace;
import art.arcane.iris.core.localization.RuntimeUiMessages; import art.arcane.iris.core.localization.RuntimeUiMessages;
@@ -402,16 +404,20 @@ public class CommandStudio implements DirectorExecutor {
@Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true) @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 World world
) { ) {
if (noGUI()) return;
if (!IrisToolbelt.isIrisWorld(world)) { if (!IrisToolbelt.isIrisWorld(world)) {
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD)); sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
return; return;
} }
UUID openerId = sender().isPlayer() ? player().getUniqueId() : null; UUID openerId = sender().isPlayer() ? player().getUniqueId() : null;
VisionGUI.launch(IrisToolbelt.access(world).getEngine(), openerId); PlatformChunkGenerator generator = IrisToolbelt.access(world);
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP)); try {
StudioBridge bridge = StudioBridges.open(world.getName(), generator::getEngine, openerId);
sender().sendMessage(IrisLanguage.text(IrisMessages.STUDIO_MAP_READY,
MessageArgument.untrusted("world", world.getName()), MessageArgument.untrusted("link", bridge.link())));
} catch (IOException error) {
sender().sendMessage(IrisLanguage.text(IrisMessages.STUDIO_MAP_FAILED, MessageArgument.untrusted("value", String.valueOf(error.getMessage()))));
}
} }
@Director(description = "Package a dimension into a compressed format", descriptionKey = "iris.director.commandstudio.director.package_dimension_into_compressed_format", aliases = "package") @Director(description = "Package a dimension into a compressed format", descriptionKey = "iris.director.commandstudio.director.package_dimension_into_compressed_format", aliases = "package")
@@ -20,6 +20,7 @@ package art.arcane.iris.modded;
import art.arcane.iris.core.gui.GuiHost; import art.arcane.iris.core.gui.GuiHost;
import art.arcane.iris.core.localization.IrisLanguage; import art.arcane.iris.core.localization.IrisLanguage;
import art.arcane.iris.core.studio.bridge.StudioBridges;
import art.arcane.iris.engine.data.cache.AtomicCacheFailureReporting; import art.arcane.iris.engine.data.cache.AtomicCacheFailureReporting;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.EngineEffectsProvider; import art.arcane.iris.engine.framework.EngineEffectsProvider;
@@ -174,6 +175,7 @@ public final class ModdedEngineBootstrap {
failure = runStopStage(failure, "object undo", ModdedObjectUndo::clearAll); failure = runStopStage(failure, "object undo", ModdedObjectUndo::clearAll);
failure = runStopStage(failure, "wand service", ModdedWandService::clearAll); failure = runStopStage(failure, "wand service", ModdedWandService::clearAll);
failure = runStopStage(failure, "block break handler", ModdedBlockBreakHandler::clear); failure = runStopStage(failure, "block break handler", ModdedBlockBreakHandler::clear);
failure = runStopStage(failure, "studio bridges", StudioBridges::closeAll);
failure = runStopStage(failure, "studio commands", ModdedStudioCommands::clear); failure = runStopStage(failure, "studio commands", ModdedStudioCommands::clear);
failure = runStopStage(failure, "gui host", ModdedGuiHost::clear); failure = runStopStage(failure, "gui host", ModdedGuiHost::clear);
failure = runStopStage(failure, "services", () -> services().disableAll()); failure = runStopStage(failure, "services", () -> services().disableAll());
@@ -23,8 +23,10 @@ import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.core.gui.GuiHost; import art.arcane.iris.core.gui.GuiHost;
import art.arcane.iris.core.gui.ImageMapStudioGUI; import art.arcane.iris.core.gui.ImageMapStudioGUI;
import art.arcane.iris.core.gui.NoiseExplorerGUI; import art.arcane.iris.core.gui.NoiseExplorerGUI;
import art.arcane.iris.core.gui.VisionGUI;
import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisData;
import art.arcane.iris.core.localization.IrisMessages;
import art.arcane.iris.core.studio.bridge.StudioBridge;
import art.arcane.iris.core.studio.bridge.StudioBridges;
import art.arcane.iris.core.project.IrisProjectCopier; import art.arcane.iris.core.project.IrisProjectCopier;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.dimension.IrisDimension;
@@ -241,15 +243,28 @@ public final class ModdedStudioCommands {
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_STAND_IRIS_STUDIO)); IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_STAND_IRIS_STUDIO));
return 0; return 0;
} }
if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) { ServerPlayer player = source.getPlayer();
IrisModdedCommands.fail(source, guiUnavailableMessage()); UUID openerId = player == null ? null : player.getUUID();
MinecraftServer server = source.getServer();
String worldName = level.dimension().identifier().toString();
try {
StudioBridge bridge = StudioBridges.open(worldName, () -> boundEngine(server, level, openerId), openerId);
IrisModdedCommands.ok(source, IrisLanguage.plain(IrisMessages.STUDIO_MAP_READY,
MessageArgument.untrusted("world", worldName), MessageArgument.untrusted("link", bridge.link())));
return 1;
} catch (IOException error) {
IrisModdedCommands.fail(source, IrisLanguage.plain(IrisMessages.STUDIO_MAP_FAILED, MessageArgument.untrusted("value", String.valueOf(error.getMessage()))));
return 0; return 0;
} }
ServerPlayer player = source.getPlayer(); }
ModdedGuiHost.bindContext(source.getServer(), level, engine, player == null ? null : player.getUUID());
VisionGUI.launch(engine, player == null ? null : player.getUUID()); /** The level's engine now, bound so the studio's players and teleports find its level. */
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_VISION_MAP_ON_SERVER_DISPLAY, MessageArgument.untrusted("value", level.dimension().identifier()))); private static Engine boundEngine(MinecraftServer server, ServerLevel level, UUID openerId) {
return 1; Engine engine = IrisModdedCommands.engineFor(level);
if (engine != null) {
ModdedGuiHost.bindContext(server, level, engine, openerId);
}
return engine;
} }
private static int imageMap(CommandSourceStack source) { private static int imageMap(CommandSourceStack source) {
@@ -38,6 +38,8 @@ public final class IrisMessages {
public static final TextKey COMMAND_IRIS_WORLD_REQUIRED = text("iris.command.iris_world_required"); public static final TextKey COMMAND_IRIS_WORLD_REQUIRED = text("iris.command.iris_world_required");
public static final TextKey COMMAND_RELOAD_SUCCESS = text("iris.command.reload.success"); public static final TextKey COMMAND_RELOAD_SUCCESS = text("iris.command.reload.success");
public static final TextKey COMMAND_RELOAD_FAILED = text("iris.command.reload.failed"); public static final TextKey COMMAND_RELOAD_FAILED = text("iris.command.reload.failed");
public static final TextKey STUDIO_MAP_READY = text("iris.studio.map_ready");
public static final TextKey STUDIO_MAP_FAILED = text("iris.studio.map_failed");
public static final TextKey MODDED_HELP_UNKNOWN_SECTION = text("iris.modded.help.unknown_section"); public static final TextKey MODDED_HELP_UNKNOWN_SECTION = text("iris.modded.help.unknown_section");
public static final TextKey MODDED_HELP_BACK_HOVER = text("iris.modded.help.back_hover"); public static final TextKey MODDED_HELP_BACK_HOVER = text("iris.modded.help.back_hover");
public static final TextKey MODDED_HELP_COMMAND_PARAMETER = text("iris.modded.help.command_parameter"); public static final TextKey MODDED_HELP_COMMAND_PARAMETER = text("iris.modded.help.command_parameter");
@@ -18,6 +18,7 @@
package art.arcane.iris.core.service; package art.arcane.iris.core.service;
import art.arcane.iris.core.studio.bridge.StudioBridges;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.spi.IrisServices; import art.arcane.iris.spi.IrisServices;
import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.IrisSettings;
@@ -118,6 +119,7 @@ public class StudioSVC implements IrisService {
@Override @Override
public void onDisable() { public void onDisable() {
StudioBridges.closeAll();
quiesceDownloadsForShutdown(); quiesceDownloadsForShutdown();
IrisLogging.debug("Studio Mode Active: Closing Projects"); IrisLogging.debug("Studio Mode Active: Closing Projects");
boolean stopping = IrisToolbelt.isServerStopping(); boolean stopping = IrisToolbelt.isServerStopping();
@@ -0,0 +1,78 @@
/*
* 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.core.studio.bridge;
import art.arcane.iris.core.studio.map.MapLabel;
import art.arcane.iris.core.studio.map.MapTile;
import com.google.gson.Gson;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* A {@link MapTile} as the studio 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 header holds the size, the scale, the subject kind and the labels the grids index. Every array starts on a
* multiple of 4 bytes, so the studio views them in place.
*/
final class MapTileEncoding {
private static final int ALIGNMENT_BYTES = 4;
private MapTileEncoding() {
}
static byte[] encode(MapTile tile, Gson gson) {
boolean hasHeights = tile.heights() != null;
byte[] header = gson.toJson(new Header(tile.size(), tile.blocksPerPixel(), tile.subjectKind(), tile.labels(), hasHeights))
.getBytes(StandardCharsets.UTF_8);
int cells = tile.gridSize() * tile.gridSize();
int length = aligned(Integer.BYTES + header.length)
+ aligned(cells * Short.BYTES) * 2
+ (hasHeights ? cells * Float.BYTES : 0);
ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(header.length).put(header);
align(buffer);
buffer.asShortBuffer().put(tile.subjects());
buffer.position(buffer.position() + cells * Short.BYTES);
align(buffer);
buffer.asShortBuffer().put(tile.regions());
buffer.position(buffer.position() + cells * Short.BYTES);
align(buffer);
if (hasHeights) {
buffer.asFloatBuffer().put(tile.heights());
}
return buffer.array();
}
private static int aligned(int bytes) {
return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
}
private static void align(ByteBuffer buffer) {
buffer.position(aligned(buffer.position()));
}
private record Header(int size, double blocksPerPixel, MapLabel.Kind subjectKind, List<MapLabel> labels, boolean heights) {
}
}
@@ -0,0 +1,426 @@
/*
* 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.core.studio.bridge;
import art.arcane.iris.core.gui.GuiHost;
import art.arcane.iris.core.gui.GuiMarker;
import art.arcane.iris.core.studio.map.MapHover;
import art.arcane.iris.core.studio.map.MapTile;
import art.arcane.iris.core.studio.map.MapView;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.render.RenderType;
import art.arcane.iris.spi.IrisLogging;
import com.google.gson.Gson;
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.Arrays;
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.AtomicInteger;
/**
* A 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 MapTileEncoding}; {@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 = 256;
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 = 1024D;
private static final long ENTITY_WAIT_MILLIS = 3_000L;
private static final int STATUS_OK = 200;
private static final int STATUS_NO_CONTENT = 204;
private static final int STATUS_BAD_REQUEST = 400;
private static final int STATUS_UNAUTHORIZED = 401;
private static final int STATUS_NOT_FOUND = 404;
private static final int STATUS_METHOD_NOT_ALLOWED = 405;
private static final int STATUS_SERVER_ERROR = 500;
private static final int STATUS_UNAVAILABLE = 503;
private final StudioWorld world;
private final String token;
private final Gson gson = new Gson();
private final HttpServer server;
private final ExecutorService workers;
private final ScheduledExecutorService ticker;
private final StudioEvents events;
private final Runnable hotloadHook;
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.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 server.getAddress().getPort();
}
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 (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 "hover" -> sendJson(exchange, STATUS_OK, MapHover.sample(get(exchange).engine(), query.number("x"), query.number("z")));
case "entities" -> sendJson(exchange, STATUS_OK, entities(get(exchange)));
case "events" -> streamEvents(exchange);
case "teleport" -> teleport(exchange, query);
case "open" -> openInEditor(exchange, query);
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();
List<ViewInfo> views = Arrays.stream(MapView.values())
.map(view -> new ViewInfo(view.id(), view.label(), view.description(), view.group().name(), view.group().label()))
.toList();
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,
views
);
}
private byte[] tile(StudioWorld.Session session, Query query) {
MapView view = MapView.byId(query.text("view"))
.orElseThrow(() -> new RequestError(STATUS_BAD_REQUEST, "Unknown view: " + query.text("view")));
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;
Engine engine = session.engine();
MapTile tile = session.renderer().render(view, query.whole("x", 0) * tileBlocks, query.whole("z", 0) * tileBlocks,
blocksPerPixel, size, query.flag("heights"), () -> closed || engine.isClosing() || engine.isClosed());
return MapTileEncoding.encode(tile, gson);
}
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);
requireOverlay(session);
session.overlay().teleport(query.number("x"), query.number("z"));
sendJson(exchange, STATUS_OK, new MessageBody(null));
}
private void openInEditor(HttpExchange exchange, Query query) throws IOException {
StudioWorld.Session session = post(exchange);
requireOverlay(session);
MapView view = MapView.byId(query.text("view")).orElse(MapView.BIOMES);
RenderType type = view == MapView.REGIONS ? RenderType.REGION : RenderType.BIOME;
sendJson(exchange, STATUS_OK, new MessageBody(session.overlay().openInEditor(query.number("x"), query.number("z"), type)));
}
private static void requireOverlay(StudioWorld.Session session) {
if (session.overlay() == null) {
throw new RequestError(STATUS_NOT_FOUND, "This server cannot do that from the studio");
}
}
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;
};
}
private static final class RequestError extends RuntimeException {
private final int status;
private RequestError(int status, String message) {
super(message);
this.status = status;
}
}
/** A request's query parameters; a missing or malformed one is a bad request. */
private 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 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) {
}
/** @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, List<ViewInfo> views) {
}
private record ViewInfo(String id, String label, String description, String group, String groupLabel) {
}
}
@@ -0,0 +1,110 @@
/*
* 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.core.studio.bridge;
import art.arcane.iris.engine.framework.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() {
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,122 @@
/*
* 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.core.studio.bridge;
import art.arcane.iris.core.gui.GuiMarker;
import art.arcane.iris.engine.framework.Engine;
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), 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 final StudioWorld world;
private final Gson gson;
private final List<OutputStream> listeners = new CopyOnWriteArrayList<>();
private final AtomicBoolean listenerJoined = new AtomicBoolean();
private final AtomicBoolean hotloaded = new AtomicBoolean();
private List<GuiMarker> lastPlayers;
private Engine lastEngine;
private long lastSentMillis;
StudioEvents(StudioWorld world, Gson gson) {
this.world = world;
this.gson = gson;
}
void listen(OutputStream stream) {
listeners.add(stream);
listenerJoined.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();
if (engine != lastEngine || hotloaded.getAndSet(false)) {
lastEngine = engine;
send("world", new WorldChange(engine != null));
}
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);
}
if (System.currentTimeMillis() - lastSentMillis > KEEP_ALIVE_INTERVAL_MILLIS) {
sendToAll(KEEP_ALIVE);
}
}
void closeAll() {
for (OutputStream listener : listeners) {
closeQuietly(listener);
}
listeners.clear();
}
private void send(String event, Object data) {
sendToAll(("event: " + event + "\ndata: " + gson.toJson(data) + "\n\n").getBytes(StandardCharsets.UTF_8));
}
private void sendToAll(byte[] message) {
lastSentMillis = System.currentTimeMillis();
for (OutputStream listener : listeners) {
try {
listener.write(message);
listener.flush();
} catch (IOException gone) {
listeners.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,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.core.studio.bridge;
import art.arcane.iris.core.gui.GuiHost;
import art.arcane.iris.core.gui.GuiOverlay;
import art.arcane.iris.core.studio.map.MapTileRenderer;
import art.arcane.iris.engine.framework.Engine;
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 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, MapTileRenderer renderer, GuiOverlay overlay) {
}
}
@@ -18,6 +18,7 @@
package art.arcane.iris.core.studio.map; package art.arcane.iris.core.studio.map;
import art.arcane.iris.core.loader.IrisRegistrant;
import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.render.RenderType; import art.arcane.iris.engine.framework.render.RenderType;
@@ -26,15 +27,19 @@ import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.spi.PlatformBiome; import art.arcane.iris.spi.PlatformBiome;
import java.nio.file.Path;
/** /**
* What the map knows about the column under the cursor. * What the map knows about the column under the cursor.
* *
* @param biome the base biome, as the biome view shows it; null where the stream has none, as for the others * @param biome the base biome, as the biome view shows it; null where the stream has none, as for the others
* @param vanillaBiome the platform biome the column gets, such as {@code minecraft:plains} * @param vanillaBiome the platform biome the column gets, such as {@code minecraft:plains}
* @param slopeDegrees how steep the terrain is, 0 for flat * @param slopeDegrees how steep the terrain is, 0 for flat
* @param biomeFile the biome's file within the pack, such as {@code biomes/plains/meadow.json}; null when unknown
*/ */
public record MapHover(double worldX, double worldZ, MapLabel biome, MapLabel caveBiome, MapLabel region, public record MapHover(double worldX, double worldZ, MapLabel biome, MapLabel caveBiome, MapLabel region,
String vanillaBiome, double height, double fluidHeight, double slopeDegrees) { String vanillaBiome, double height, double fluidHeight, double slopeDegrees,
String biomeFile, String regionFile) {
// IrisComplex measures slope as the height change over this many blocks. // IrisComplex measures slope as the height change over this many blocks.
private static final double SLOPE_STREAM_RANGE_BLOCKS = 3D; private static final double SLOPE_STREAM_RANGE_BLOCKS = 3D;
@@ -55,7 +60,18 @@ public record MapHover(double worldX, double worldZ, MapLabel biome, MapLabel ca
vanillaBiome == null ? null : vanillaBiome.key(), vanillaBiome == null ? null : vanillaBiome.key(),
complex.getHeightStream().getDouble(worldX, worldZ), complex.getHeightStream().getDouble(worldX, worldZ),
dimension == null ? 0D : dimension.getFluidHeight(), dimension == null ? 0D : dimension.getFluidHeight(),
Math.toDegrees(Math.atan(slope / SLOPE_STREAM_RANGE_BLOCKS)) Math.toDegrees(Math.atan(slope / SLOPE_STREAM_RANGE_BLOCKS)),
packPath(engine, biome),
packPath(engine, region)
); );
} }
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;
}
} }
@@ -29,6 +29,8 @@
"iris.command.unknown": "Unbekannter Iris-Befehl", "iris.command.unknown": "Unbekannter Iris-Befehl",
"iris.command.player_only": "Dieser Befehl kann nur von Spielern verwendet werden.", "iris.command.player_only": "Dieser Befehl kann nur von Spielern verwendet werden.",
"iris.command.iris_world_required": "Diese Dimension wurde nicht von Iris generiert.", "iris.command.iris_world_required": "Diese Dimension wurde nicht von Iris generiert.",
"iris.studio.map_ready": "Studio-Karte für {world}: {link}",
"iris.studio.map_failed": "Die Studio-Karte konnte nicht gestartet werden: {value}",
"iris.command.reload.success": "Einstellungen und Sprache {locale} wurden neu geladen.", "iris.command.reload.success": "Einstellungen und Sprache {locale} wurden neu geladen.",
"iris.command.reload.failed": "Die Einstellungen wurden neu geladen, aber die Sprache {locale} wurde abgelehnt; {activeLocale} bleibt aktiv.", "iris.command.reload.failed": "Die Einstellungen wurden neu geladen, aber die Sprache {locale} wurde abgelehnt; {activeLocale} bleibt aktiv.",
"iris.modded.help.unknown_section": "Unbekannter Iris-Hilfeabschnitt: {section}", "iris.modded.help.unknown_section": "Unbekannter Iris-Hilfeabschnitt: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Comando de Iris desconocido", "iris.command.unknown": "Comando de Iris desconocido",
"iris.command.player_only": "Este comando solo puede ser utilizado por jugadores.", "iris.command.player_only": "Este comando solo puede ser utilizado por jugadores.",
"iris.command.iris_world_required": "Esta dimensión no fue generada por Iris.", "iris.command.iris_world_required": "Esta dimensión no fue generada por Iris.",
"iris.studio.map_ready": "Mapa de Studio para {world}: {link}",
"iris.studio.map_failed": "No se pudo iniciar el mapa de Studio: {value}",
"iris.command.reload.success": "Se recargaron la configuración y el idioma {locale}.", "iris.command.reload.success": "Se recargaron la configuración y el idioma {locale}.",
"iris.command.reload.failed": "Se recargó la configuración, pero se rechazó el idioma {locale}; se seguirá usando {activeLocale}.", "iris.command.reload.failed": "Se recargó la configuración, pero se rechazó el idioma {locale}; se seguirá usando {activeLocale}.",
"iris.modded.help.unknown_section": "Sección de ayuda de Iris desconocida: {section}", "iris.modded.help.unknown_section": "Sección de ayuda de Iris desconocida: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Tuntematon Iris-komento", "iris.command.unknown": "Tuntematon Iris-komento",
"iris.command.player_only": "Vain pelaajat voivat käyttää tätä komentoa.", "iris.command.player_only": "Vain pelaajat voivat käyttää tätä komentoa.",
"iris.command.iris_world_required": "Iris ei ole luonut tätä ulottuvuutta.", "iris.command.iris_world_required": "Iris ei ole luonut tätä ulottuvuutta.",
"iris.studio.map_ready": "Studio-kartta maailmalle {world}: {link}",
"iris.studio.map_failed": "Studio-kartan käynnistys epäonnistui: {value}",
"iris.command.reload.success": "Asetukset ja kieli {locale} ladattiin uudelleen.", "iris.command.reload.success": "Asetukset ja kieli {locale} ladattiin uudelleen.",
"iris.command.reload.failed": "Asetukset ladattiin uudelleen, mutta kieli {locale} hylättiin; jatketaan kielen {activeLocale} käyttöä.", "iris.command.reload.failed": "Asetukset ladattiin uudelleen, mutta kieli {locale} hylättiin; jatketaan kielen {activeLocale} käyttöä.",
"iris.modded.help.unknown_section": "Tuntematon Iris Tukiosa: {section}", "iris.modded.help.unknown_section": "Tuntematon Iris Tukiosa: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Commande Iris inconnue", "iris.command.unknown": "Commande Iris inconnue",
"iris.command.player_only": "Cette commande ne peut être utilisée que par les joueurs.", "iris.command.player_only": "Cette commande ne peut être utilisée que par les joueurs.",
"iris.command.iris_world_required": "Cette dimension n'a pas été générée par Iris.", "iris.command.iris_world_required": "Cette dimension n'a pas été générée par Iris.",
"iris.studio.map_ready": "Carte Studio pour {world} : {link}",
"iris.studio.map_failed": "Impossible de démarrer la carte Studio : {value}",
"iris.command.reload.success": "Les paramètres et la langue {locale} ont été rechargés.", "iris.command.reload.success": "Les paramètres et la langue {locale} ont été rechargés.",
"iris.command.reload.failed": "Les paramètres ont été rechargés, mais la langue {locale} a été refusée ; la langue {activeLocale} reste utilisée.", "iris.command.reload.failed": "Les paramètres ont été rechargés, mais la langue {locale} a été refusée ; la langue {activeLocale} reste utilisée.",
"iris.modded.help.unknown_section": "Section d'aide Iris inconnue : {section}", "iris.modded.help.unknown_section": "Section d'aide Iris inconnue : {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "פקודת Iris לא מוכרת", "iris.command.unknown": "פקודת Iris לא מוכרת",
"iris.command.player_only": "רק שחקנים יכולים להשתמש בפקודה זו.", "iris.command.player_only": "רק שחקנים יכולים להשתמש בפקודה זו.",
"iris.command.iris_world_required": "ממד זה לא נוצר על ידי Iris.", "iris.command.iris_world_required": "ממד זה לא נוצר על ידי Iris.",
"iris.studio.map_ready": "מפת Studio עבור {world}: {link}",
"iris.studio.map_failed": "לא ניתן להפעיל את מפת ה-Studio: {value}",
"iris.command.reload.success": "ההגדרות והשפה {locale} נטענו מחדש.", "iris.command.reload.success": "ההגדרות והשפה {locale} נטענו מחדש.",
"iris.command.reload.failed": "ההגדרות נטענו מחדש, אך השפה {locale} נדחתה; ממשיכים עם {activeLocale}.", "iris.command.reload.failed": "ההגדרות נטענו מחדש, אך השפה {locale} נדחתה; ממשיכים עם {activeLocale}.",
"iris.modded.help.unknown_section": "לא ידוע Iris עזרה סעיף: {section}", "iris.modded.help.unknown_section": "לא ידוע Iris עזרה סעיף: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Comando Iris sconosciuto", "iris.command.unknown": "Comando Iris sconosciuto",
"iris.command.player_only": "Questo comando può essere usato solo dai giocatori.", "iris.command.player_only": "Questo comando può essere usato solo dai giocatori.",
"iris.command.iris_world_required": "Questa dimensione non è stata generata da Iris.", "iris.command.iris_world_required": "Questa dimensione non è stata generata da Iris.",
"iris.studio.map_ready": "Mappa di Studio per {world}: {link}",
"iris.studio.map_failed": "Impossibile avviare la mappa di Studio: {value}",
"iris.command.reload.success": "Le impostazioni e la lingua {locale} sono state ricaricate.", "iris.command.reload.success": "Le impostazioni e la lingua {locale} sono state ricaricate.",
"iris.command.reload.failed": "Le impostazioni sono state ricaricate, ma la lingua {locale} è stata rifiutata; si continuerà a usare {activeLocale}.", "iris.command.reload.failed": "Le impostazioni sono state ricaricate, ma la lingua {locale} è stata rifiutata; si continuerà a usare {activeLocale}.",
"iris.modded.help.unknown_section": "Sezione della guida Iris sconosciuta: {section}", "iris.modded.help.unknown_section": "Sezione della guida Iris sconosciuta: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "不明な Iris コマンドです", "iris.command.unknown": "不明な Iris コマンドです",
"iris.command.player_only": "このコマンドはプレイヤーのみ使用できます。", "iris.command.player_only": "このコマンドはプレイヤーのみ使用できます。",
"iris.command.iris_world_required": "このディメンションは Iris によって生成されていません。", "iris.command.iris_world_required": "このディメンションは Iris によって生成されていません。",
"iris.studio.map_ready": "{world} の Studio マップ: {link}",
"iris.studio.map_failed": "Studio マップを開始できませんでした: {value}",
"iris.command.reload.success": "設定と言語 {locale} を再読み込みしました。", "iris.command.reload.success": "設定と言語 {locale} を再読み込みしました。",
"iris.command.reload.failed": "設定は再読み込みされましたが、言語 {locale} は拒否されました。引き続き {activeLocale} を使用します。", "iris.command.reload.failed": "設定は再読み込みされましたが、言語 {locale} は拒否されました。引き続き {activeLocale} を使用します。",
"iris.modded.help.unknown_section": "不明な Iris ヘルプセクション: {section}", "iris.modded.help.unknown_section": "不明な Iris ヘルプセクション: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "알 수 없는 Iris 명령어", "iris.command.unknown": "알 수 없는 Iris 명령어",
"iris.command.player_only": "이 명령어는 플레이어만 사용할 수 있습니다.", "iris.command.player_only": "이 명령어는 플레이어만 사용할 수 있습니다.",
"iris.command.iris_world_required": "이 차원은 Iris가 생성하지 않았습니다.", "iris.command.iris_world_required": "이 차원은 Iris가 생성하지 않았습니다.",
"iris.studio.map_ready": "{world}의 Studio 지도: {link}",
"iris.studio.map_failed": "Studio 지도를 시작할 수 없습니다: {value}",
"iris.command.reload.success": "설정과 {locale} 언어를 다시 불러왔습니다.", "iris.command.reload.success": "설정과 {locale} 언어를 다시 불러왔습니다.",
"iris.command.reload.failed": "설정은 다시 불러왔지만 {locale} 언어가 거부되어 {activeLocale}을 계속 사용합니다.", "iris.command.reload.failed": "설정은 다시 불러왔지만 {locale} 언어가 거부되어 {activeLocale}을 계속 사용합니다.",
"iris.modded.help.unknown_section": "알 수 없는 Iris 도움말 섹션: {section}", "iris.modded.help.unknown_section": "알 수 없는 Iris 도움말 섹션: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Nežinoma Iris komanda", "iris.command.unknown": "Nežinoma Iris komanda",
"iris.command.player_only": "Šią komandą gali naudoti tik žaidėjai.", "iris.command.player_only": "Šią komandą gali naudoti tik žaidėjai.",
"iris.command.iris_world_required": "Šio matmens nesugeneravo Iris.", "iris.command.iris_world_required": "Šio matmens nesugeneravo Iris.",
"iris.studio.map_ready": "Studio žemėlapis pasauliui {world}: {link}",
"iris.studio.map_failed": "Nepavyko paleisti Studio žemėlapio: {value}",
"iris.command.reload.success": "Nustatymai ir kalba {locale} įkelti iš naujo.", "iris.command.reload.success": "Nustatymai ir kalba {locale} įkelti iš naujo.",
"iris.command.reload.failed": "Nustatymai įkelti iš naujo, tačiau kalba {locale} atmesta; toliau naudojama {activeLocale}.", "iris.command.reload.failed": "Nustatymai įkelti iš naujo, tačiau kalba {locale} atmesta; toliau naudojama {activeLocale}.",
"iris.modded.help.unknown_section": "Nežinoma Iris pagalbos skyrius: {section}", "iris.modded.help.unknown_section": "Nežinoma Iris pagalbos skyrius: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Onbekende Iris-opdracht", "iris.command.unknown": "Onbekende Iris-opdracht",
"iris.command.player_only": "Deze opdracht kan alleen door spelers worden gebruikt.", "iris.command.player_only": "Deze opdracht kan alleen door spelers worden gebruikt.",
"iris.command.iris_world_required": "Deze dimensie is niet door Iris gegenereerd.", "iris.command.iris_world_required": "Deze dimensie is niet door Iris gegenereerd.",
"iris.studio.map_ready": "Studio-kaart voor {world}: {link}",
"iris.studio.map_failed": "Kan de Studio-kaart niet starten: {value}",
"iris.command.reload.success": "De instellingen en taal {locale} zijn opnieuw geladen.", "iris.command.reload.success": "De instellingen en taal {locale} zijn opnieuw geladen.",
"iris.command.reload.failed": "De instellingen zijn opnieuw geladen, maar taal {locale} is geweigerd; {activeLocale} blijft actief.", "iris.command.reload.failed": "De instellingen zijn opnieuw geladen, maar taal {locale} is geweigerd; {activeLocale} blijft actief.",
"iris.modded.help.unknown_section": "Onbekend Iris help sectie: {section}", "iris.modded.help.unknown_section": "Onbekend Iris help sectie: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Nieznane polecenie Iris", "iris.command.unknown": "Nieznane polecenie Iris",
"iris.command.player_only": "Tego polecenia mogą używać tylko gracze.", "iris.command.player_only": "Tego polecenia mogą używać tylko gracze.",
"iris.command.iris_world_required": "Ten wymiar nie został wygenerowany przez Iris.", "iris.command.iris_world_required": "Ten wymiar nie został wygenerowany przez Iris.",
"iris.studio.map_ready": "Mapa Studio dla {world}: {link}",
"iris.studio.map_failed": "Nie udało się uruchomić mapy Studio: {value}",
"iris.command.reload.success": "Ustawienia i język {locale} zostały ponownie wczytane.", "iris.command.reload.success": "Ustawienia i język {locale} zostały ponownie wczytane.",
"iris.command.reload.failed": "Ustawienia zostały ponownie wczytane, ale język {locale} został odrzucony; nadal używany jest {activeLocale}.", "iris.command.reload.failed": "Ustawienia zostały ponownie wczytane, ale język {locale} został odrzucony; nadal używany jest {activeLocale}.",
"iris.modded.help.unknown_section": "Nieznany Iris sekcja pomocnicza: {section}", "iris.modded.help.unknown_section": "Nieznany Iris sekcja pomocnicza: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Comando Iris desconhecido", "iris.command.unknown": "Comando Iris desconhecido",
"iris.command.player_only": "Este comando só pode ser utilizado por jogadores.", "iris.command.player_only": "Este comando só pode ser utilizado por jogadores.",
"iris.command.iris_world_required": "Esta dimensão não foi gerada pelo Iris.", "iris.command.iris_world_required": "Esta dimensão não foi gerada pelo Iris.",
"iris.studio.map_ready": "Mapa do Studio para {world}: {link}",
"iris.studio.map_failed": "Não foi possível iniciar o mapa do Studio: {value}",
"iris.command.reload.success": "As definições e o idioma {locale} foram recarregados.", "iris.command.reload.success": "As definições e o idioma {locale} foram recarregados.",
"iris.command.reload.failed": "As definições foram recarregadas, mas o idioma {locale} foi rejeitado; será mantido {activeLocale}.", "iris.command.reload.failed": "As definições foram recarregadas, mas o idioma {locale} foi rejeitado; será mantido {activeLocale}.",
"iris.modded.help.unknown_section": "Desconhecido Iris secção de ajuda: {section}", "iris.modded.help.unknown_section": "Desconhecido Iris secção de ajuda: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Неизвестная команда Iris", "iris.command.unknown": "Неизвестная команда Iris",
"iris.command.player_only": "Эту команду могут использовать только игроки.", "iris.command.player_only": "Эту команду могут использовать только игроки.",
"iris.command.iris_world_required": "Это измерение не было создано Iris.", "iris.command.iris_world_required": "Это измерение не было создано Iris.",
"iris.studio.map_ready": "Карта Studio для {world}: {link}",
"iris.studio.map_failed": "Не удалось запустить карту Studio: {value}",
"iris.command.reload.success": "Настройки и язык {locale} были перезагружены.", "iris.command.reload.success": "Настройки и язык {locale} были перезагружены.",
"iris.command.reload.failed": "Настройки были перезагружены, но язык {locale} был отклонён; продолжает использоваться {activeLocale}.", "iris.command.reload.failed": "Настройки были перезагружены, но язык {locale} был отклонён; продолжает использоваться {activeLocale}.",
"iris.modded.help.unknown_section": "неизвестный Iris Раздел помощи: {section}", "iris.modded.help.unknown_section": "неизвестный Iris Раздел помощи: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Bilinmeyen Iris komutu", "iris.command.unknown": "Bilinmeyen Iris komutu",
"iris.command.player_only": "Bu komutu yalnızca oyuncular kullanabilir.", "iris.command.player_only": "Bu komutu yalnızca oyuncular kullanabilir.",
"iris.command.iris_world_required": "Bu boyut Iris tarafından oluşturulmadı.", "iris.command.iris_world_required": "Bu boyut Iris tarafından oluşturulmadı.",
"iris.studio.map_ready": "{world} için Studio haritası: {link}",
"iris.studio.map_failed": "Studio haritası başlatılamadı: {value}",
"iris.command.reload.success": "Ayarlar ve {locale} dili yeniden yüklendi.", "iris.command.reload.success": "Ayarlar ve {locale} dili yeniden yüklendi.",
"iris.command.reload.failed": "Ayarlar yeniden yüklendi, ancak {locale} dili reddedildi; {activeLocale} kullanılmaya devam ediliyor.", "iris.command.reload.failed": "Ayarlar yeniden yüklendi, ancak {locale} dili reddedildi; {activeLocale} kullanılmaya devam ediliyor.",
"iris.modded.help.unknown_section": "Bilinmeyen Iris Yardım bölümü: {section}", "iris.modded.help.unknown_section": "Bilinmeyen Iris Yardım bölümü: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "Lệnh Iris không xác định", "iris.command.unknown": "Lệnh Iris không xác định",
"iris.command.player_only": "Chỉ người chơi mới có thể sử dụng lệnh này.", "iris.command.player_only": "Chỉ người chơi mới có thể sử dụng lệnh này.",
"iris.command.iris_world_required": "Chiều không gian này không được Iris tạo ra.", "iris.command.iris_world_required": "Chiều không gian này không được Iris tạo ra.",
"iris.studio.map_ready": "Bản đồ Studio cho {world}: {link}",
"iris.studio.map_failed": "Không thể khởi động bản đồ Studio: {value}",
"iris.command.reload.success": "Đã tải lại cài đặt và ngôn ngữ {locale}.", "iris.command.reload.success": "Đã tải lại cài đặt và ngôn ngữ {locale}.",
"iris.command.reload.failed": "Đã tải lại cài đặt, nhưng ngôn ngữ {locale} bị từ chối; tiếp tục sử dụng {activeLocale}.", "iris.command.reload.failed": "Đã tải lại cài đặt, nhưng ngôn ngữ {locale} bị từ chối; tiếp tục sử dụng {activeLocale}.",
"iris.modded.help.unknown_section": "Không rõ Iris Phần trợ giúp: {section}", "iris.modded.help.unknown_section": "Không rõ Iris Phần trợ giúp: {section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "未知的 Iris 命令。", "iris.command.unknown": "未知的 Iris 命令。",
"iris.command.player_only": "此命令只能由玩家执行。", "iris.command.player_only": "此命令只能由玩家执行。",
"iris.command.iris_world_required": "此维度不是由 Iris 生成的。", "iris.command.iris_world_required": "此维度不是由 Iris 生成的。",
"iris.studio.map_ready": "{world} 的 Studio 地图:{link}",
"iris.studio.map_failed": "无法启动 Studio 地图:{value}",
"iris.command.reload.success": "设置和语言 {locale} 已重新加载。", "iris.command.reload.success": "设置和语言 {locale} 已重新加载。",
"iris.command.reload.failed": "设置已重新加载,但语言 {locale} 验证失败;继续使用 {activeLocale}。", "iris.command.reload.failed": "设置已重新加载,但语言 {locale} 验证失败;继续使用 {activeLocale}。",
"iris.modded.help.unknown_section": "未知的 Iris 帮助章节:{section}", "iris.modded.help.unknown_section": "未知的 Iris 帮助章节:{section}",
@@ -29,6 +29,8 @@
"iris.command.unknown": "未知的 Iris 命令。", "iris.command.unknown": "未知的 Iris 命令。",
"iris.command.player_only": "此命令只能由玩家執行。", "iris.command.player_only": "此命令只能由玩家執行。",
"iris.command.iris_world_required": "此維度不是由 Iris 生成的。", "iris.command.iris_world_required": "此維度不是由 Iris 生成的。",
"iris.studio.map_ready": "{world} 的 Studio 地圖:{link}",
"iris.studio.map_failed": "無法啟動 Studio 地圖:{value}",
"iris.command.reload.success": "設定和語言 {locale} 已重新載入。", "iris.command.reload.success": "設定和語言 {locale} 已重新載入。",
"iris.command.reload.failed": "設定已重新載入,但語言 {locale} 驗證失敗;繼續使用 {activeLocale}。", "iris.command.reload.failed": "設定已重新載入,但語言 {locale} 驗證失敗;繼續使用 {activeLocale}。",
"iris.modded.help.unknown_section": "未知的 Iris 說明章節:{section}", "iris.modded.help.unknown_section": "未知的 Iris 說明章節:{section}",
@@ -5,6 +5,8 @@
"iris.command.unknown": "Unknown Iris command", "iris.command.unknown": "Unknown Iris command",
"iris.command.player_only": "This command can only be used by players.", "iris.command.player_only": "This command can only be used by players.",
"iris.command.iris_world_required": "This dimension is not generated by Iris.", "iris.command.iris_world_required": "This dimension is not generated by Iris.",
"iris.studio.map_ready": "Studio map for {world}: {link}",
"iris.studio.map_failed": "Could not start the studio map: {value}",
"iris.command.reload.success": "Hotloaded settings and locale {locale}.", "iris.command.reload.success": "Hotloaded settings and locale {locale}.",
"iris.command.reload.failed": "Settings were reloaded, but locale {locale} was rejected; continuing with {activeLocale}.", "iris.command.reload.failed": "Settings were reloaded, but locale {locale} was rejected; continuing with {activeLocale}.",
"iris.modded.help.unknown_section": "Unknown Iris help section: {section}", "iris.modded.help.unknown_section": "Unknown Iris help section: {section}",
@@ -0,0 +1,195 @@
package art.arcane.iris.core.studio.bridge;
import art.arcane.iris.engine.IrisComplex;
import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.render.RenderType;
import art.arcane.iris.engine.object.world.IrisWorld;
import art.arcane.iris.engine.object.world.biome.IrisBiome;
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
import art.arcane.iris.engine.object.world.region.IrisRegion;
import art.arcane.iris.spi.PlatformBiome;
import art.arcane.iris.util.project.stream.ProceduralStream;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** A bridge to a world of plains in one region, flat at height 70, asked over real HTTP. */
public class StudioBridgeTest {
private static final Duration WAIT = Duration.ofSeconds(5);
private final HttpClient http = HttpClient.newBuilder().connectTimeout(WAIT).build();
private final AtomicReference<Engine> running = new AtomicReference<>();
private StudioBridge bridge;
@Before
@SuppressWarnings("unchecked")
public void openABridge() throws Exception {
Engine engine = mock(Engine.class);
IrisComplex complex = mock(IrisComplex.class);
IrisBiome plains = mock(IrisBiome.class);
when(plains.getLoadKey()).thenReturn("plains");
when(plains.getName()).thenReturn("Plains");
when(plains.getColor(eq(engine), any(RenderType.class))).thenReturn(java.awt.Color.GREEN);
IrisRegion region = mock(IrisRegion.class);
when(region.getLoadKey()).thenReturn("temperate");
when(region.getName()).thenReturn("Temperate");
when(region.getColor(complex, RenderType.REGION)).thenReturn(java.awt.Color.BLUE);
ProceduralStream<IrisBiome> biomes = mock(ProceduralStream.class);
when(biomes.get(anyDouble(), anyDouble())).thenReturn(plains);
ProceduralStream<IrisRegion> regions = mock(ProceduralStream.class);
when(regions.get(anyDouble(), anyDouble())).thenReturn(region);
ProceduralStream<Double> heights = mock(ProceduralStream.class);
when(heights.getDouble(anyDouble(), anyDouble())).thenReturn(70D);
ProceduralStream<PlatformBiome> vanilla = mock(ProceduralStream.class);
when(complex.getBaseBiomeStream()).thenReturn(biomes);
when(complex.getCaveBiomeStream()).thenReturn(biomes);
when(complex.getRegionStream()).thenReturn(regions);
when(complex.getHeightStream()).thenReturn(heights);
when(complex.getSlopeStream()).thenReturn(heights);
when(complex.getTrueBiomeDerivativeStream()).thenReturn(vanilla);
IrisDimension dimension = mock(IrisDimension.class);
when(dimension.getLoadKey()).thenReturn("overworld");
when(dimension.getName()).thenReturn("Overworld");
when(dimension.getFluidHeight()).thenReturn(63);
IrisWorld world = mock(IrisWorld.class);
when(world.getRawWorldSeed()).thenReturn(Long.MAX_VALUE);
when(engine.getComplex()).thenReturn(complex);
when(engine.getDimension()).thenReturn(dimension);
when(engine.getWorld()).thenReturn(world);
when(engine.getMinHeight()).thenReturn(-64);
when(engine.getHeight()).thenReturn(384);
running.set(engine);
bridge = StudioBridge.start(new StudioWorld("world_iris", running::get, null));
}
@After
public void closeTheBridge() {
bridge.close();
}
@Test
public void aRequestWithoutTheTokenIsRefused() throws Exception {
HttpResponse<String> response = http.send(HttpRequest.newBuilder(uri("world")).timeout(WAIT).build(),
HttpResponse.BodyHandlers.ofString());
assertEquals(401, response.statusCode());
}
@Test
public void theWorldListsItsHeightsAndViews() throws Exception {
JsonObject world = json(get("world"));
assertEquals("world_iris", world.get("world").getAsString());
assertEquals("overworld", world.get("dimension").getAsString());
assertEquals(Long.toString(Long.MAX_VALUE), world.get("seed").getAsString());
assertEquals(-64, world.get("minY").getAsInt());
assertEquals(384, world.get("height").getAsInt());
assertEquals(63, world.get("fluidHeight").getAsInt());
assertEquals("biomes", world.getAsJsonArray("views").get(0).getAsJsonObject().get("id").getAsString());
}
@Test
public void aTileIsItsHeaderThenAlignedGrids() throws Exception {
HttpResponse<byte[]> response = http.send(authorized("tile?view=biomes&x=-1&z=2&scale=2&size=8&heights=1"),
HttpResponse.BodyHandlers.ofByteArray());
ByteBuffer body = ByteBuffer.wrap(response.body()).order(ByteOrder.LITTLE_ENDIAN);
int headerLength = body.getInt();
JsonObject header = JsonParser.parseString(new String(response.body(), 4, headerLength, StandardCharsets.UTF_8)).getAsJsonObject();
int cells = 10 * 10;
int subjects = (4 + headerLength + 3) / 4 * 4;
int regions = subjects + cells * 2;
int heights = regions + cells * 2;
assertEquals(200, response.statusCode());
assertEquals(8, header.get("size").getAsInt());
assertTrue(header.get("heights").getAsBoolean());
assertEquals(heights + cells * 4, response.body().length);
String subjectKey = header.getAsJsonArray("labels").get(body.getShort(subjects)).getAsJsonObject().get("key").getAsString();
String regionKey = header.getAsJsonArray("labels").get(body.getShort(regions)).getAsJsonObject().get("key").getAsString();
assertEquals("plains", subjectKey);
assertEquals("temperate", regionKey);
assertEquals(70F, body.getFloat(heights), 1e-4F);
}
@Test
public void aBadTileRequestSaysWhatIsWrong() throws Exception {
HttpResponse<String> unknownView = http.send(authorized("tile?view=nothing&scale=1"), HttpResponse.BodyHandlers.ofString());
HttpResponse<String> hugeScale = http.send(authorized("tile?view=biomes&scale=1e9"), HttpResponse.BodyHandlers.ofString());
assertEquals(400, unknownView.statusCode());
assertTrue(unknownView.body().contains("Unknown view"));
assertEquals(400, hugeScale.statusCode());
}
@Test
public void theHoverDescribesTheColumn() throws Exception {
JsonObject hover = json(get("hover?x=5&z=-3"));
assertEquals("plains", hover.getAsJsonObject("biome").get("key").getAsString());
assertEquals("temperate", hover.getAsJsonObject("region").get("key").getAsString());
assertEquals(70D, hover.get("height").getAsDouble(), 0D);
}
@Test
public void aWorldWithoutAnEngineIsUnavailableUntilItHasOneAgain() throws Exception {
Engine engine = running.getAndSet(null);
assertEquals(503, get("world").statusCode());
running.set(engine);
assertEquals(200, get("world").statusCode());
}
@Test
public void aNewListenerHearsThePlayersRightAway() throws Exception {
HttpResponse<InputStream> events = http.send(authorized("events"), HttpResponse.BodyHandlers.ofInputStream());
try (BufferedReader lines = new BufferedReader(new InputStreamReader(events.body(), StandardCharsets.UTF_8))) {
String line;
do {
line = lines.readLine();
} while (line != null && !line.equals("event: players"));
assertEquals("event: players", line);
assertEquals("data: []", lines.readLine());
}
}
private HttpResponse<String> get(String endpoint) throws Exception {
return http.send(authorized(endpoint), HttpResponse.BodyHandlers.ofString());
}
private HttpRequest authorized(String endpoint) {
return HttpRequest.newBuilder(uri(endpoint)).timeout(WAIT).header("Authorization", "Bearer " + bridge.token()).build();
}
private URI uri(String endpoint) {
return URI.create("http://127.0.0.1:" + bridge.port() + "/v1/" + endpoint);
}
private static JsonObject json(HttpResponse<String> response) {
assertEquals(response.body(), 200, response.statusCode());
return JsonParser.parseString(response.body()).getAsJsonObject();
}
}
@@ -136,6 +136,10 @@ public class MapTileRendererTest {
IrisDimension dimension = mock(IrisDimension.class); IrisDimension dimension = mock(IrisDimension.class);
when(dimension.getFluidHeight()).thenReturn(63); when(dimension.getFluidHeight()).thenReturn(63);
when(engine.getDimension()).thenReturn(dimension); when(engine.getDimension()).thenReturn(dimension);
art.arcane.iris.core.loader.IrisData pack = mock(art.arcane.iris.core.loader.IrisData.class);
when(pack.getDataFolder()).thenReturn(new java.io.File("/packs/overworld"));
when(engine.getData()).thenReturn(pack);
when(desert.getLoadFile()).thenReturn(new java.io.File("/packs/overworld/biomes/desert.json"));
MapHover hover = MapHover.sample(engine, 10D, 0D); MapHover hover = MapHover.sample(engine, 10D, 0D);
@@ -146,6 +150,8 @@ public class MapTileRendererTest {
assertEquals(complex.getHeightStream().getDouble(10D, 0D), hover.height(), 1e-9); assertEquals(complex.getHeightStream().getDouble(10D, 0D), hover.height(), 1e-9);
assertEquals(63D, hover.fluidHeight(), 0D); assertEquals(63D, hover.fluidHeight(), 0D);
assertEquals(45D, hover.slopeDegrees(), 1e-9); assertEquals(45D, hover.slopeDegrees(), 1e-9);
assertEquals("biomes/desert.json", hover.biomeFile());
assertNull("a region without a file has no path", hover.regionFile());
} }
@Test @Test