Keep the studio responsive while block tiles generate

Block tiles held the bridge's few request threads while their chunks
generated, and coarse tiles pushed their own chunks out of the cache
before reading them. Each tile now reads its columns as its chunks
generate and coarse tiles keep none; block tiles wait on threads of
their own; the studio gives quick and slow tiles separate request
slots.

The planner now keeps any stored tile with blocks in sight, not only
drawn ones, and draws columns no finer than a pixel again: at half a
pixel a forest view held twelve million triangles. The atlas gets
mipmaps down to a pixel a picture, so far textures fade to the flat
colour of coarser ground.
This commit is contained in:
piexel committed 2026-11-12 08:00:33 +01:00
1 parent e759edadfe
commit 93d6ffe70e
11 files changed
+281 -65

No files matched your search

@@ -140,6 +140,7 @@ public final class StudioBridge implements AutoCloseable {
private final HttpServer server;
private final int port;
private final ExecutorService workers;
private final ExecutorService blockTileWaiters;
private final ScheduledExecutorService ticker;
private final StudioEvents events;
private final Runnable hotloadHook;
@@ -155,6 +156,7 @@ public final class StudioBridge implements AutoCloseable {
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.blockTileWaiters = Executors.newCachedThreadPool(daemonThreads("Iris Studio Block Tiles"));
this.ticker = Executors.newSingleThreadScheduledExecutor(daemonThreads("Iris Studio Events"));
this.hotloadHook = events::hotloaded;
server.setExecutor(workers);
@@ -197,6 +199,7 @@ public final class StudioBridge implements AutoCloseable {
events.closeAll();
server.stop(0);
workers.shutdownNow();
blockTileWaiters.shutdownNow();
}
private void pollEvents() {
@@ -208,7 +211,7 @@ public final class StudioBridge implements AutoCloseable {
}
private void handle(HttpExchange exchange) throws IOException {
try {
answer(exchange, () -> {
allowAnyOrigin(exchange.getResponseHeaders());
if ("OPTIONS".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(STATUS_NO_CONTENT, -1);
@@ -219,6 +222,16 @@ public final class StudioBridge implements AutoCloseable {
throw new RequestError(STATUS_UNAUTHORIZED, "Missing or wrong token");
}
route(exchange);
});
}
private interface Answer {
void run() throws IOException;
}
private void answer(HttpExchange exchange, Answer answer) throws IOException {
try {
answer.run();
} catch (RequestError error) {
sendJson(exchange, error.status, new ErrorBody(error.getMessage()));
} catch (CancellationException stopped) {
@@ -240,7 +253,13 @@ public final class StudioBridge implements AutoCloseable {
}
switch (endpoint) {
case "world" -> sendJson(exchange, STATUS_OK, worldInfo(get(exchange)));
case "tile" -> sendBytes(exchange, "application/octet-stream", tile(get(exchange), query));
case "tile" -> {
if (query.has("blocks")) {
answerAside(exchange, () -> sendBytes(exchange, "application/octet-stream", tile(get(exchange), query)));
} else {
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, picks(get(exchange).engine(), query));
@@ -618,6 +637,18 @@ public final class StudioBridge implements AutoCloseable {
return MapTileEncoding.encode(tile, gson, StudioBridge::pluginLookOf);
}
// A tile with blocks waits a minute or more on chunks generated on threads of their own; waiting on the bridge's
// few threads, a handful of them would leave none for the studio's other requests.
private void answerAside(HttpExchange exchange, Answer answer) {
blockTileWaiters.execute(() -> {
try {
answer(exchange, answer);
} catch (IOException clientHungUp) {
exchange.close();
}
});
}
// A tile with blocks may generate thousands of chunks, so one the studio stopped waiting for is let go of.
private void cancelTile(HttpExchange exchange, Query query) throws IOException {
requireMethod(exchange, "POST");
@@ -26,12 +26,13 @@ interface ColumnTops {
ColumnTop at(int worldX, int worldZ);
/**
* Readies the tops of the grid's columns at once, so asking for them one by one after is quick. Nothing to do for a
* source whose tops are quick to find.
* The tops of the grid's columns found at once, so asking for them one by one after is quick; this source itself
* where its tops are quick to find.
*
* @throws java.util.concurrent.CancellationException as soon as the grid's request is cancelled
*/
default void prepare(TileGrid grid) {
default ColumnTops prepared(TileGrid grid) {
return this;
}
/**
@@ -29,6 +29,10 @@ import art.arcane.iris.util.project.context.IrisContext;
import art.arcane.iris.util.project.hunk.Hunk;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.longs.LongList;
import it.unimi.dsi.fastutil.shorts.ShortArrayList;
import java.util.ArrayList;
@@ -36,6 +40,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@@ -47,9 +52,7 @@ import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BooleanSupplier;
import java.util.function.IntBinaryOperator;
import java.util.function.IntToDoubleFunction;
import java.util.function.UnaryOperator;
import java.util.stream.IntStream;
/**
* The tops of chunks generated for the studio alone: each chunk runs through the world's own stages into memory, so its
@@ -92,33 +95,78 @@ final class GeneratedChunks implements ColumnTops {
return chunk.columns[(worldZ & CHUNK_MASK) * BLOCKS_ACROSS + (worldX & CHUNK_MASK)];
}
// A chunk that fails to generate is left for at() to fail on, as it would without this.
// The tile reads each of its columns as soon as its chunk is generated, so it holds them whatever the cache lets go
// of meanwhile. A tile with several columns to a chunk keeps the chunk for the finer tiles that follow; a coarser one
// reads one column of each chunk and keeps none, as thousands of them would only push the near ground out. A chunk
// that fails to generate is left for at() to fail on.
@Override
public void prepare(TileGrid grid) {
public ColumnTops prepared(TileGrid grid) {
boolean keepsChunks = grid.step() < BLOCKS_ACROSS;
Long2ObjectMap<LongList> columnsByChunk = columnsByChunkOf(grid);
Map<Long, ColumnTop> found = new ConcurrentHashMap<>();
List<Future<?>> generating = new ArrayList<>();
for (int chunkZ : chunksAlong(grid, grid::worldZ)) {
for (int chunkX : chunksAlong(grid, grid::worldX)) {
long key = keyOf(chunkX, chunkZ);
if (tops.getIfPresent(key) == null) {
ChunkTask chunk = new ChunkTask(() -> generateUnlessCancelled(key, grid.cancelled()), grid.step());
GENERATORS.execute(chunk);
generating.add(chunk);
}
for (Long2ObjectMap.Entry<LongList> chunk : columnsByChunk.long2ObjectEntrySet()) {
long key = chunk.getLongKey();
ChunkTop known = tops.getIfPresent(key);
if (known != null) {
readColumns(known, chunk.getValue(), found);
continue;
}
ChunkTask task = new ChunkTask(() -> readGenerated(key, keepsChunks, chunk.getValue(), found, grid.cancelled()), grid.step());
GENERATORS.execute(task);
generating.add(task);
}
try {
for (Future<?> chunk : generating) {
awaitUnlessCancelled(chunk, grid.cancelled());
for (Future<?> task : generating) {
awaitUnlessCancelled(task, grid.cancelled());
}
} catch (CancellationException cancelled) {
generating.forEach(chunk -> chunk.cancel(false));
generating.forEach(task -> task.cancel(false));
throw cancelled;
}
return (worldX, worldZ) -> {
ColumnTop column = found.get(keyOf(worldX, worldZ));
return column != null ? column : at(worldX, worldZ);
};
}
private static Long2ObjectMap<LongList> columnsByChunkOf(TileGrid grid) {
Long2ObjectMap<LongList> columnsByChunk = new Long2ObjectOpenHashMap<>();
for (int gridZ = 0; gridZ < grid.size(); gridZ++) {
int worldZ = (int) Math.floor(grid.worldZ(gridZ));
for (int gridX = 0; gridX < grid.size(); gridX++) {
int worldX = (int) Math.floor(grid.worldX(gridX));
long chunk = keyOf(worldX >> CHUNK_SHIFT, worldZ >> CHUNK_SHIFT);
columnsByChunk.computeIfAbsent(chunk, ignored -> new LongArrayList()).add(keyOf(worldX, worldZ));
}
}
return columnsByChunk;
}
private void readGenerated(long key, boolean keepsChunk, LongList columns, Map<Long, ColumnTop> found, BooleanSupplier cancelled) {
if (cancelled.getAsBoolean()) {
return;
}
readColumns(keepsChunk ? tops.get(key) : topWithoutKeeping(key), columns, found);
}
private ChunkTop topWithoutKeeping(long key) {
ChunkTop known = tops.getIfPresent(key);
if (known != null) {
return known;
}
try {
return generate(key);
} catch (Exception failed) {
throw new CompletionException(failed);
}
}
private void generateUnlessCancelled(long key, BooleanSupplier cancelled) {
if (!cancelled.getAsBoolean()) {
tops.get(key);
private static void readColumns(ChunkTop chunk, LongList columns, Map<Long, ColumnTop> found) {
for (long column : columns) {
int worldX = (int) (column >> Integer.SIZE);
int worldZ = (int) column;
found.put(column, chunk.columns[(worldZ & CHUNK_MASK) * BLOCKS_ACROSS + (worldX & CHUNK_MASK)]);
}
}
@@ -139,14 +187,6 @@ final class GeneratedChunks implements ColumnTops {
}
}
// The distinct chunks the grid's columns fall in along one axis, in order.
private static int[] chunksAlong(TileGrid grid, IntToDoubleFunction worldAt) {
return IntStream.range(0, grid.size())
.map(cell -> (int) Math.floor(worldAt.applyAsDouble(cell)) >> CHUNK_SHIFT)
.distinct()
.toArray();
}
/**
* One chunk to generate for a tile. The chunks of finer tiles go first, then those asked for first: a tile far out
* spreads over thousands of chunks, and the ground near the camera, in finer tiles, is not kept waiting behind it.
@@ -87,8 +87,7 @@ public final class MapTileRenderer {
+ " blocks per pixel or finer");
}
TileGrid grid = new TileGrid(tile.gridSize(), startX - step, startZ - step, step, cancelled);
ColumnTops tops = topsOf(source);
tops.prepare(grid);
ColumnTops tops = topsOf(source).prepared(grid);
int cells = grid.size() * grid.size();
short[] ground = new short[cells];
short[] cover = new short[cells];