diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java index e805134e9..9429021b6 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java @@ -19,6 +19,8 @@ package art.arcane.iris.core.studio.bridge; import art.arcane.iris.core.gui.GuiHost; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; import art.arcane.iris.core.link.CustomBlockLook; import art.arcane.iris.core.link.CustomBlockSource; import art.arcane.iris.spi.IrisServices; @@ -89,6 +91,7 @@ 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; @@ -110,6 +113,7 @@ public final class StudioBridge implements AutoCloseable { private static final int LARGEST_BODY_BYTES = 4 * 1024 * 1024; 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; // Each pixel reads the chunk it lands in, so a saved world is shown no farther out than a pixel per chunk. private static final int LARGEST_SAVED_BLOCKS_PER_PIXEL = 16; // A palette is picked block by block, so far out a column stands for the blocks around it; past this it says little. @@ -139,6 +143,9 @@ public final class StudioBridge implements AutoCloseable { private final ScheduledExecutorService ticker; private final StudioEvents events; private final Runnable hotloadHook; + // Whether the studio stopped waiting for each tile, by the id it gave the request. A cancel can arrive before its tile + // does, so each is kept a while rather than for its tile alone. + private final Cache droppedTiles = Caffeine.newBuilder().expireAfterWrite(DROPPED_TILE_KEPT_MINUTES, TimeUnit.MINUTES).build(); private volatile boolean closed; private StudioBridge(StudioWorld world) throws IOException { @@ -234,6 +241,7 @@ 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-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)); case "regions" -> sendJson(exchange, STATUS_OK, regions(get(exchange).engine())); @@ -601,7 +609,8 @@ public final class StudioBridge implements AutoCloseable { double tileBlocks = size * blocksPerPixel; double startX = query.whole("x", 0) * tileBlocks; double startZ = query.whole("z", 0) * tileBlocks; - BooleanSupplier cancelled = () -> closed || engine.isClosing() || engine.isClosed(); + AtomicBoolean dropped = query.has("request") ? droppedFlagOf(query.text("request")) : new AtomicBoolean(); + BooleanSupplier cancelled = () -> dropped.get() || closed || engine.isClosing() || engine.isClosed(); MapTile tile = session.renderer().render(layer, startX, startZ, blocksPerPixel, size, tileExtras(query), cancelled); if (query.has("blocks")) { tile = withBlocks(session, tile, startX, startZ, blockSource(query), cancelled); @@ -609,6 +618,17 @@ public final class StudioBridge implements AutoCloseable { return MapTileEncoding.encode(tile, gson, StudioBridge::pluginLookOf); } + // 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"); + 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 static MapTile withBlocks(StudioWorld.Session session, MapTile tile, double startX, double startZ, BlockSource source, BooleanSupplier cancelled) { try { diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/BlockSource.java b/core/src/main/java/art/arcane/iris/core/studio/map/BlockSource.java index eba9a35ea..43af9feee 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/BlockSource.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/BlockSource.java @@ -23,8 +23,11 @@ import java.util.Optional; /** Where a tile's blocks come from. */ public enum BlockSource { - /** The chunks generated in memory: what the world would hold, at a block a pixel or finer. */ - GENERATED("generated", 1D); + /** + * The chunks generated in memory: what the world would hold, at any scale. A tile generates every chunk its pixels + * fall in, so one coarser than a chunk a pixel costs a chunk for each pixel, up to about a minute's work. + */ + GENERATED("generated", 4_096D); private final String id; private final double largestBlocksPerPixel; diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java index c67bfe768..ae953dce9 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java @@ -25,6 +25,15 @@ import java.util.Arrays; 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. + * + * @throws java.util.concurrent.CancellationException as soon as the grid's request is cancelled + */ + default void prepare(TileGrid grid) { + } + /** * The top of one column. * diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java b/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java index f21b937b5..adbad9c77 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java @@ -35,25 +35,44 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; +import java.util.concurrent.PriorityBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +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 * columns hold what the world would, trees and structures included, and nothing is placed in the world. Generating * plans the chunk's surroundings in the world's mantle, as generating it in the world would. A chunk is generated once - * and its top kept; asked for from several bridge threads at once. + * and its top kept; asked for from several bridge threads at once. A tile's chunks are generated side by side on threads + * of their own, which end once the studio has asked for none for a while. */ final class GeneratedChunks implements ColumnTops { private static final int CHUNK_SHIFT = 4; private static final int BLOCKS_ACROSS = 1 << CHUNK_SHIFT; private static final int CHUNK_MASK = BLOCKS_ACROSS - 1; - // A chunk's top is about 5 KB, and each block raised over its ground adds a height and a shared key. + // A chunk's top is about 5 KB, and each block raised over its ground adds a height and a shared key. A view with + // blocks out to the horizon holds tens of thousands of chunks. private static final int CHUNK_TOP_BYTES = 5 * 1024; private static final int RAISED_BLOCK_BYTES = Short.BYTES + Integer.BYTES; - private static final long MOST_BYTES_KEPT = 64L * 1024 * 1024; + private static final long MOST_BYTES_KEPT = 512L * 1024 * 1024; private static final String LEASE_NAME = "studio_block_preview"; + // Half the cores, as the bridge does, so a studio filling its view leaves the server room to run. + private static final int GENERATING_THREADS = Math.max(2, Runtime.getRuntime().availableProcessors() / 2); + private static final long IDLE_THREAD_SECONDS = 30; + private static final long CANCEL_CHECK_MILLIS = 250; + private static final ThreadPoolExecutor GENERATORS = idleEndingThreads(); private final Engine engine; private final LoadingCache tops; @@ -73,6 +92,93 @@ 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. + @Override + public void prepare(TileGrid grid) { + List> 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); + } + } + } + try { + for (Future chunk : generating) { + awaitUnlessCancelled(chunk, grid.cancelled()); + } + } catch (CancellationException cancelled) { + generating.forEach(chunk -> chunk.cancel(false)); + throw cancelled; + } + } + + private void generateUnlessCancelled(long key, BooleanSupplier cancelled) { + if (!cancelled.getAsBoolean()) { + tops.get(key); + } + } + + private static void awaitUnlessCancelled(Future chunk, BooleanSupplier cancelled) { + while (true) { + MapTileRenderer.checkCancelled(cancelled); + try { + chunk.get(CANCEL_CHECK_MILLIS, TimeUnit.MILLISECONDS); + return; + } catch (TimeoutException stillGenerating) { + // checked for cancelling again + } catch (ExecutionException failed) { + return; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new CancellationException("Map tile render interrupted"); + } + } + } + + // 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. + */ + private static final class ChunkTask extends FutureTask implements Comparable { + private static final AtomicLong ASKED = new AtomicLong(); + private final double blocksPerColumn; + private final long asked = ASKED.getAndIncrement(); + + ChunkTask(Runnable generation, double blocksPerColumn) { + super(generation, null); + this.blocksPerColumn = blocksPerColumn; + } + + @Override + public int compareTo(ChunkTask other) { + int byFineness = Double.compare(blocksPerColumn, other.blocksPerColumn); + return byFineness != 0 ? byFineness : Long.compare(asked, other.asked); + } + } + + private static ThreadPoolExecutor idleEndingThreads() { + ThreadPoolExecutor threads = new ThreadPoolExecutor(GENERATING_THREADS, GENERATING_THREADS, IDLE_THREAD_SECONDS, TimeUnit.SECONDS, + new PriorityBlockingQueue<>(), runnable -> { + Thread thread = new Thread(runnable, "Iris Studio Chunks"); + thread.setDaemon(true); + return thread; + }); + threads.allowCoreThreadTimeOut(true); + return threads; + } + private ChunkTop generate(long key) throws Exception { int chunkX = (int) (key >> Integer.SIZE); int chunkZ = (int) key; diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java index f78594a05..b8e043518 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java @@ -88,6 +88,7 @@ public final class MapTileRenderer { } TileGrid grid = new TileGrid(tile.gridSize(), startX - step, startZ - step, step, cancelled); ColumnTops tops = topsOf(source); + tops.prepare(grid); int cells = grid.size() * grid.size(); short[] ground = new short[cells]; short[] cover = new short[cells]; diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index 5a1b4aa98..5e08d1ab7 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -141,11 +141,19 @@ export class BridgeClient { }) if (request.blocks !== null) { query.set('blocks', request.blocks) + this.cancelOnAbort(query, signal) } const response = await this.fetch(`tile?${query}`, { signal }) return decodeTile(await response.arrayBuffer()) } + // A tile with blocks can keep the server generating chunks for a minute; dropping the request alone would not stop it. + private cancelOnAbort(query: URLSearchParams, signal: AbortSignal): void { + const request = crypto.randomUUID() + query.set('request', request) + signal.addEventListener('abort', () => void this.fetch(`tile-cancel?${new URLSearchParams({ request })}`, { method: 'POST' }).catch(() => {}), { once: true }) + } + /** The scene views the pack's modules show, such as its objects. */ sceneViews(): Promise { return this.json('scenes') diff --git a/studio/src/renderer/src/map/MapController.ts b/studio/src/renderer/src/map/MapController.ts index d04724349..fc7050740 100644 --- a/studio/src/renderer/src/map/MapController.ts +++ b/studio/src/renderer/src/map/MapController.ts @@ -147,7 +147,7 @@ export class MapController { /** Whether the map is zoomed in far enough for its tiles to carry blocks. */ showsBlocks(): boolean { - return hasBlocksAt(BLOCK_SOURCE, this.renderScale()) + return hasBlocksAt(this.renderScale()) } // Heights are the costly part of a tile, so they are only asked for when something draws with them: the relief, and diff --git a/studio/src/renderer/src/map/TileStore.ts b/studio/src/renderer/src/map/TileStore.ts index 687d7b114..21a19c0c3 100644 --- a/studio/src/renderer/src/map/TileStore.ts +++ b/studio/src/renderer/src/map/TileStore.ts @@ -80,8 +80,13 @@ export class TileStore { /** Fetches the tiles the view shows, in the order given, and gives up on the ones it no longer shows. */ want(addresses: TileAddress[], layer: Layer): void { - this.wanted = addresses - .map((address) => ({ key: this.key(address, layer), address, layer })) + this.wantEach(addresses.map((address) => ({ address, layer }))) + } + + /** As {@link want}, each tile of its own layer. */ + wantEach(tiles: { address: TileAddress; layer: Layer }[]): void { + this.wanted = tiles + .map(({ address, layer }) => ({ key: this.key(address, layer), address, layer })) .filter((entry) => !this.tiles.has(entry.key) && !this.failed.has(entry.key)) const stillWanted = new Set(this.wanted.map((entry) => entry.key)) for (const [key, controller] of this.inFlight) { diff --git a/studio/src/renderer/src/map/mapTileSource.ts b/studio/src/renderer/src/map/mapTileSource.ts index 2a8c453c7..ffbbae921 100644 --- a/studio/src/renderer/src/map/mapTileSource.ts +++ b/studio/src/renderer/src/map/mapTileSource.ts @@ -17,21 +17,28 @@ export interface TileLayer { revision: number } -/** The coarsest tiles a block source is asked for; coarser ones come without blocks. */ -const MOST_BLOCKS_PER_PIXEL: Record = { generated: 1 } +/** + * The coarsest tiles the map asks for blocks; coarser ones come without. Every chunk under a tile is generated for its + * blocks, so a map zoomed out over a few screens would keep the server busy for minutes. + */ +const MAP_MOST_BLOCKS_PER_PIXEL = 1 const TEXTURED_BLOCKS_PER_PIXEL = 1 -/** Whether tiles this coarse carry blocks from {@code source}. */ -export function hasBlocksAt(source: BlockSource, blocksPerPixel: number): boolean { - return blocksPerPixel <= MOST_BLOCKS_PER_PIXEL[source] +/** Whether the map's tiles this coarse carry blocks. */ +export function hasBlocksAt(blocksPerPixel: number): boolean { + return blocksPerPixel <= MAP_MOST_BLOCKS_PER_PIXEL } -/** The world map's tiles: the engine's streams, drawn in the map's styles, their blocks painted with {@code art}. */ -export function mapTileSource(client: BridgeClient, tileSize: number, art: BlockArt): TileSource { +/** + * The world map's tiles: the engine's streams, drawn in the map's styles, their blocks painted with {@code art}. + * + * @param mostBlocksPerPixel the coarsest tiles that carry blocks; at most the 8 the server generates them for + */ +export function mapTileSource(client: BridgeClient, tileSize: number, art: BlockArt, mostBlocksPerPixel = MAP_MOST_BLOCKS_PER_PIXEL): TileSource { return { layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise, layer.blocks ?? ''].join('/'), fetch: async (address, layer, signal) => { - const blocks = layer.blocks !== null && hasBlocksAt(layer.blocks, address.blocksPerPixel) ? layer.blocks : null + const blocks = layer.blocks !== null && address.blocksPerPixel <= mostBlocksPerPixel ? layer.blocks : null const tile = await client.tile({ ...layer, ...address, size: tileSize, blocks }, signal) if (tile.blocks !== null) { await art.paint(tile.blocks, address.blocksPerPixel === TEXTURED_BLOCKS_PER_PIXEL) diff --git a/studio/src/renderer/src/scene/mapTerrain.test.ts b/studio/src/renderer/src/scene/mapTerrain.test.ts new file mode 100644 index 000000000..48dbfc179 --- /dev/null +++ b/studio/src/renderer/src/scene/mapTerrain.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest' +import type { MapTile, TileBlocks } from '../bridge/types' +import { MapTerrain } from './mapTerrain' + +const SIZE = 2 +const CELLS = (SIZE + 2) ** 2 +const GROUND_Y = 64 +const LEAF_Y = 70 +const STONE = 0x808080 +const LEAVES = 0x00ff00 +// The tile's first column, past the ring of its neighbours' cells. +const FIRST_CELL = SIZE + 2 + 1 + +// A tile of stone at one height, with a leaf raised over its first column. +function tileWithALeaf(): MapTile { + const raisedStart = new Int32Array(CELLS + 1) + raisedStart.fill(1, FIRST_CELL + 1) + const blocks: TileBlocks = { + names: ['stone', 'leaves'], + ground: new Int16Array(CELLS), + cover: new Int16Array(CELLS).fill(-1), + raisedStart, + raisedY: Int16Array.of(LEAF_Y), + raised: Int16Array.of(1), + colors: [STONE, LEAVES], + looks: [], + covers: [] + } + return { + size: SIZE, + blocksPerPixel: 1, + subjectKind: 'BIOME', + labels: [], + subjects: new Int16Array(CELLS), + regions: new Int16Array(CELLS), + heights: new Float32Array(CELLS).fill(GROUND_Y), + pickNoise: null, + blocks + } +} + +function terrainAt(level: number): MapTerrain { + return new MapTerrain(tileWithALeaf(), { tileX: 0, tileZ: 0, level }, 'blocks', 0) +} + +describe('map terrain', () => { + it('stands raised blocks on columns a block wide, over the ground they stand on', () => { + const terrain = terrainAt(0) + + expect(terrain.groundAt(0, 0)).toBe(GROUND_Y) + expect(terrain.colorAt(0, 0)).toBe(STONE) + expect(terrain.raisedAt(0, 0)).toEqual([{ y: LEAF_Y, color: LEAVES, look: null }]) + }) + + it('takes the highest raised block as the top of a column wider than a block', () => { + const terrain = terrainAt(3) + + expect(terrain.groundAt(0, 0)).toBe(LEAF_Y) + expect(terrain.colorAt(0, 0)).toBe(LEAVES) + expect(terrain.raisedAt(0, 0)).toEqual([]) + expect(terrain.groundAt(1, 0)).toBe(GROUND_Y) + }) +}) diff --git a/studio/src/renderer/src/scene/mapTerrain.ts b/studio/src/renderer/src/scene/mapTerrain.ts index 80f31f603..72ae9a671 100644 --- a/studio/src/renderer/src/scene/mapTerrain.ts +++ b/studio/src/renderer/src/scene/mapTerrain.ts @@ -13,7 +13,8 @@ const UNLABELLED_COLOR = 0x5a5f6b /** * One map tile with heights as a surface, a column to a pixel, without the ring the tile carries for its neighbours; the * sea fills up to fluid height. Coloured by blocks, a tile that carries them shows their colours, and their textures - * where it has their looks; one too coarse to carry them keeps its biomes' colours. + * where it has their looks; one too coarse to carry them keeps its biomes' colours. Blocks raised over the ground stand + * as blocks on columns a block wide, and are the top of wider ones. */ export class MapTerrain implements TerrainSurface { readonly columns: number @@ -37,7 +38,8 @@ export class MapTerrain implements TerrainSurface { } groundAt(column: number, row: number): number { - return Math.floor(this.heightAt(column, row)) + const highestRaised = this.highestFoldedRaisedAt(column, row) + return highestRaised === null ? Math.floor(this.heightAt(column, row)) : this.tile.blocks!.raisedY[highestRaised] } waterAt(column: number, row: number): number | null { @@ -45,12 +47,12 @@ export class MapTerrain implements TerrainSurface { } lookAt(column: number, row: number): BlockLook | null { - const ground = this.groundBlockAt(column, row) - return ground === NO_BLOCK ? null : (this.tile.blocks!.looks[ground] ?? null) + const top = this.topBlockAt(column, row) + return top === NO_BLOCK ? null : (this.tile.blocks!.looks[top] ?? null) } coverAt(column: number, row: number): CoverLook | null { - if (this.groundBlockAt(column, row) === NO_BLOCK) { + if (this.groundBlockAt(column, row) === NO_BLOCK || this.highestFoldedRaisedAt(column, row) !== null) { return null } const cover = this.tile.blocks!.cover[this.cellAt(column, row)] @@ -59,7 +61,7 @@ export class MapTerrain implements TerrainSurface { raisedAt(column: number, row: number): readonly RaisedBlock[] { const blocks = this.coloring === 'blocks' ? this.tile.blocks : null - if (blocks === null) { + if (blocks === null || this.foldsRaisedBlocks()) { return [] } const cell = this.cellAt(column, row) @@ -75,14 +77,35 @@ export class MapTerrain implements TerrainSurface { if (this.coloring === 'height') { return heightColor(this.heightAt(column, row), this.fluidHeight) } - const ground = this.groundBlockAt(column, row) - if (ground !== NO_BLOCK) { - return this.tile.blocks!.colors[ground] + const top = this.topBlockAt(column, row) + if (top !== NO_BLOCK) { + return this.tile.blocks!.colors[top] } const index = this.coloring === 'regions' ? this.tile.regions[this.cellAt(column, row)] : this.tile.subjects[this.cellAt(column, row)] return index === NO_LABEL ? UNLABELLED_COLOR : this.tile.labels[index].color } + // A block raised on a column wider than a block would stand as a slab as wide as the column, so such columns take + // their highest raised block as their top, as a forest seen from afar is its canopy. + private foldsRaisedBlocks(): boolean { + return this.blocksPerColumn > 1 + } + + /** Where the column's highest raised block lies in the tile's raised blocks, where the column takes it as its top. */ + private highestFoldedRaisedAt(column: number, row: number): number | null { + if (!this.foldsRaisedBlocks() || this.groundBlockAt(column, row) === NO_BLOCK) { + return null + } + const cell = this.cellAt(column, row) + const { raisedStart } = this.tile.blocks! + return raisedStart[cell] < raisedStart[cell + 1] ? raisedStart[cell] : null + } + + private topBlockAt(column: number, row: number): number { + const highestRaised = this.highestFoldedRaisedAt(column, row) + return highestRaised === null ? this.groundBlockAt(column, row) : this.tile.blocks!.raised[highestRaised] + } + private groundBlockAt(column: number, row: number): number { return this.coloring === 'blocks' && this.tile.blocks !== null ? this.tile.blocks.ground[this.cellAt(column, row)] : NO_BLOCK } diff --git a/studio/src/renderer/src/scene/terrainCover.test.ts b/studio/src/renderer/src/scene/terrainCover.test.ts index 8cda11ac5..15de63d97 100644 --- a/studio/src/renderer/src/scene/terrainCover.test.ts +++ b/studio/src/renderer/src/scene/terrainCover.test.ts @@ -54,6 +54,33 @@ describe('terrain cover', () => { expect(Math.min(...wanted.map((tile) => tile.level))).toBeLessThan(wanted[0].level) }) + it('draws a quick stand-in only where no truer tile of any level is known', () => { + const sight = sightFrom(2000) + const backdrop = planCover(sight, nothingReady, COARSEST_LEVEL).wanted[0] + const quickEverywhere = (): TileState => 'quick' + const trueBackdrop = (tile: TerrainTile): TileState => (tileKey(tile) === tileKey(backdrop) ? 'fresh' : 'quick') + + const quickOnly = planCover(sight, quickEverywhere, COARSEST_LEVEL).draws + const withTrueBackdrop = planCover(sight, trueBackdrop, COARSEST_LEVEL).draws + + expect(quickOnly.length).toBeGreaterThan(0) + expectEverySpotDrawnOnce(quickOnly) + expect(withTrueBackdrop.some((draw) => tileKey(draw.tile) === tileKey(backdrop))).toBe(true) + expect(withTrueBackdrop.some((draw) => isInside(draw.tile, backdrop))).toBe(false) + }) + + it('keeps the true ground drawn from closer up, however much finer, until its coarser tile is as true', () => { + const sight = sightFrom(3000) + const nearGround = { level: 0, tileX: 0, tileZ: 0 } + const known = (tile: TerrainTile): TileState => (tileKey(tile) === tileKey(nearGround) ? 'fresh' : 'quick') + const knownInside = (tile: TerrainTile): TerrainTile[] => (isInside(nearGround, tile) ? [nearGround] : []) + + const { draws } = planCover(sight, known, COARSEST_LEVEL, knownInside) + + expect(draws.some((draw) => tileKey(draw.tile) === tileKey(nearGround))).toBe(true) + expect(drawnOver(draws, 5.5, 5.5)).toBe(1) + }) + it('wants nothing once every tile it needs is sampled', () => { expect(planCover(sightFrom(2000), everythingReady, COARSEST_LEVEL).wanted).toEqual([]) }) @@ -65,10 +92,10 @@ describe('terrain cover', () => { expect(Math.min(...far.map((draw) => draw.tile.level))).toBeGreaterThanOrEqual(3) }) - it('never asks for more than a backdrop, a preview and detail of 64 tiles each', () => { + it('never asks for more than a backdrop, a preview and detail of 192 tiles each', () => { for (const height of [60, 600, 6000, 600_000]) { const { wanted } = planCover(sightFrom(height), nothingReady, COARSEST_LEVEL) - expect(wanted.length).toBeLessThanOrEqual(3 * 64) + expect(wanted.length).toBeLessThanOrEqual(3 * 192) } }) diff --git a/studio/src/renderer/src/scene/terrainCover.ts b/studio/src/renderer/src/scene/terrainCover.ts index 33aab93c5..1bc7584de 100644 --- a/studio/src/renderer/src/scene/terrainCover.ts +++ b/studio/src/renderer/src/scene/terrainCover.ts @@ -11,8 +11,11 @@ import { type TerrainTile } from './terrainTiles' -/** What is known of a tile: its ground, ground left over from before the layer changed that stands in until it is sampled anew, or nothing. */ -export type TileState = 'none' | 'standIn' | 'fresh' +/** + * What is known of a tile: its ground; ground left over from before the layer changed that stands in until it is + * sampled anew; only a quick, rougher stand-in, drawn where nothing truer of any level is known; or nothing. + */ +export type TileState = 'none' | 'quick' | 'standIn' | 'fresh' export interface DrawnTile { tile: TerrainTile @@ -26,11 +29,12 @@ export interface Cover { wanted: TerrainTile[] } -// A column is drawn at most this many pixels wide, as wider ones show their blockiness; coarser ones only where there are too many. -const MOST_COLUMN_PIXELS = 1 -// A little above one, as tiles in sight stick out past the view's edges; beyond it, columns only add faces no one can tell apart. -const MOST_COLUMNS_PER_PIXEL = 1.25 -const MOST_TILES_IN_SIGHT = 64 +// Tuned for looks over speed. A column is drawn at most half a pixel wide, so blocks, trees and their textures go on +// well past where a column shrinks to a pixel; coarser ones only where there would be too many tiles. +const MOST_COLUMN_PIXELS = 0.5 +// Columns finer than a pixel still show what stands on them, such as trees, so the view takes several to a pixel. +const MOST_COLUMNS_PER_PIXEL = 4 +const MOST_TILES_IN_SIGHT = 192 // The backdrop reaches to the horizon, where a few coarse tiles do; the rest of the tiles go to ground that is near. const MOST_BACKDROP_TILES = 16 const DETAIL_MARGIN = 0.15 @@ -48,16 +52,26 @@ type StateOf = (tile: TerrainTile) => TileState * sampled the nearest sampled tile of a coarser level stands in, with holes where finer tiles are ready, and detail * left over from before zooming out stands in for the coarser tile that is not sampled yet. * + * Quick stand-ins are drawn only where no truer tile of any level is known, so ground once sampled stays in sight until + * what replaces it is as true. + * * @param coarsestLevel the coarsest level the source can sample + * @param knownInside the tiles finer than a tile, inside it, whose ground is known, however much finer; where not + * given, the ones up to a couple of levels finer that {@code stateOf} knows */ -export function planCover(sight: CameraSight, stateOf: StateOf, coarsestLevel: number): Cover { +export function planCover(sight: CameraSight, stateOf: StateOf, coarsestLevel: number, knownInside?: (tile: TerrainTile) => TerrainTile[]): Cover { const backdropLevel = backdropLevelFor(sight, coarsestLevel) const finestLevel = Math.max(0, backdropLevel - MOST_LEVELS_FINER) const backdrop = sight.tilesAt(backdropLevel, BACKDROP_MARGIN).sort(nearestFirst(sight)).slice(0, MOST_BACKDROP_TILES) const detail = detailTiles(sight, backdrop, finestLevel) - const ready = candidatesOf(backdrop, detail, backdropLevel, finestLevel, stateOf).filter((tile) => stateOf(tile) !== 'none') + const isTrue = (tile: TerrainTile): boolean => stateOf(tile) === 'fresh' || stateOf(tile) === 'standIn' + const leftOverInside = knownInside ?? ((tile: TerrainTile) => finerLeftOver(tile, finestLevel, stateOf, MOST_LEVELS_FINER_LEFT_OVER)) + const candidates = candidatesOf(backdrop, detail, backdropLevel, isTrue, (tile) => leftOverInside(tile).filter((finer) => finer.level >= finestLevel && isTrue(finer))) + const ready = candidates.filter(isTrue) + const quickFill = candidates.filter((tile) => stateOf(tile) === 'quick' && !ready.some((truer) => isInside(tile, truer))) + const drawn = [...ready, ...quickFill] return { - draws: ready.map((tile) => ({ tile, holes: ready.filter((finer) => isInside(finer, tile)).map((finer) => columnsUnder(tile, finer)) })), + draws: drawn.map((tile) => ({ tile, holes: drawn.filter((finer) => isInside(finer, tile)).map((finer) => columnsUnder(tile, finer)) })), wanted: wantedInOrder(sight, backdrop, detail, backdropLevel, stateOf) } } @@ -95,19 +109,30 @@ function detailTiles(sight: CameraSight, backdrop: TerrainTile[], finestLevel: n } // Everything that may be drawn for the view: the backdrop, the detail and the levels between that happen to be there, -// and, where detail is missing, finer tiles left over from before. None is finer than a backdrop tile can be cut a hole for. -function candidatesOf(backdrop: TerrainTile[], detail: TerrainTile[], backdropLevel: number, finestLevel: number, stateOf: StateOf): TerrainTile[] { +// and, where a tile's true ground is missing, finer tiles left over from before. None is finer than a backdrop tile can +// be cut a hole for. +function candidatesOf( + backdrop: TerrainTile[], + detail: TerrainTile[], + backdropLevel: number, + isTrue: (tile: TerrainTile) => boolean, + leftOverInside: (tile: TerrainTile) => TerrainTile[] +): TerrainTile[] { const candidates = new Map() const add = (tile: TerrainTile): void => void candidates.set(tileKey(tile), tile) + const addLeftOverWhereMissing = (tile: TerrainTile): void => { + if (!isTrue(tile)) { + leftOverInside(tile).forEach(add) + } + } backdrop.forEach(add) + backdrop.forEach(addLeftOverWhereMissing) for (const tile of detail) { add(tile) for (let level = tile.level + 1; level <= backdropLevel; level++) { add(ancestorAt(tile, level)) } - if (stateOf(tile) === 'none') { - finerLeftOver(tile, finestLevel, stateOf, MOST_LEVELS_FINER_LEFT_OVER).forEach(add) - } + addLeftOverWhereMissing(tile) } return [...candidates.values()] } diff --git a/studio/src/renderer/src/scene/terrainStream.test.ts b/studio/src/renderer/src/scene/terrainStream.test.ts index bf4631edb..ccf49feba 100644 --- a/studio/src/renderer/src/scene/terrainStream.test.ts +++ b/studio/src/renderer/src/scene/terrainStream.test.ts @@ -36,20 +36,26 @@ const flatStyle: TerrainStyle = { topY: 128 } -function setUp(coarsestLevel = COARSEST_LEVEL): { +function setUp( + coarsestLevel = COARSEST_LEVEL, + quickLayerOf?: (layer: FlatLayer) => FlatLayer | null +): { stream: TerrainStream camera: PerspectiveCamera moved(): void requested: number[] + requestedLayers: string[] pendingCounts: number[] stopFollowing: () => void } { const requested: number[] = [] + const requestedLayers: string[] = [] const pendingCounts: number[] = [] const source: TileSource = { layerKey: (layer) => layer.name, fetch: async (address, layer) => { requested.push(address.blocksPerPixel) + requestedLayers.push(layer.name) await layer.gate return { height: layer.height } }, @@ -58,6 +64,7 @@ function setUp(coarsestLevel = COARSEST_LEVEL): { const stream = new TerrainStream({ source, coarsestLevel, + quickLayerOf, focus: focusAround(0, 0, 0, 128), onPending: (pending) => pendingCounts.push(pending), onError: (message) => { @@ -77,7 +84,7 @@ function setUp(coarsestLevel = COARSEST_LEVEL): { redraw: vi.fn() } const stopFollowing = stream.content.follow!(link) - return { stream, camera, moved: () => listeners.forEach((listener) => listener()), requested, pendingCounts, stopFollowing } + return { stream, camera, moved: () => listeners.forEach((listener) => listener()), requested, requestedLayers, pendingCounts, stopFollowing } } async function settle(): Promise { @@ -127,6 +134,25 @@ describe('terrain stream', () => { expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(91, 3) }) + it('draws the quick stand-in of a slow layer at once, and asks for the slow tiles finest first', async () => { + let release = (): void => {} + const slow: FlatLayer = { name: 'slow', height: 90, gate: new Promise((resolve) => (release = resolve)) } + const quick: FlatLayer = { name: 'quick', height: 70, gate: open } + const { stream, requested, requestedLayers } = setUp(COARSEST_LEVEL, (layer) => (layer === slow ? quick : null)) + stream.restyle(flatStyle) + stream.showLayer(slow) + await settle() + const ray = new Ray(new Vector3(10, 300, 10), new Vector3(0, -1, 0)) + expect(requestedLayers[0]).toBe('quick') + expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(71, 3) + const slowScales = requested.filter((_, at) => requestedLayers[at] === 'slow') + expect(slowScales.length).toBeGreaterThan(0) + expect(slowScales).toEqual([...slowScales].sort((first, second) => first - second)) + release() + await settle() + expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(91, 3) + }) + it('draws the tiles again in another style without asking for them again', async () => { const { stream, requested } = setUp() stream.restyle(flatStyle) diff --git a/studio/src/renderer/src/scene/terrainStream.ts b/studio/src/renderer/src/scene/terrainStream.ts index f4982e9a0..47db9bf25 100644 --- a/studio/src/renderer/src/scene/terrainStream.ts +++ b/studio/src/renderer/src/scene/terrainStream.ts @@ -1,5 +1,6 @@ import { Box3, Group, Vector3 } from 'three' import { TileStore, type TileSource } from '../map/TileStore' +import type { TileAddress } from '../map/viewport' import type { CameraLink, ViewportContent } from '../studio/SceneViewport' import { CameraSight } from './cameraSight' import type { ColumnField } from './columnField' @@ -7,7 +8,7 @@ import { groundInView, type GroundInView } from './groundInView' import { marchOntoSurface } from './surfaceMarch' import { planCover, type Cover, type DrawnTile, type TileState } from './terrainCover' import { buildTerrainMesh, type TerrainMesh, type TerrainSurface } from './terrainMesh' -import { addressOf, tileContaining, tileKey, type TerrainTile } from './terrainTiles' +import { addressOf, isInside, tileContaining, tileKey, type TerrainTile } from './terrainTiles' /** How the tiles of a source look as ground, and how low and high that ground can reach. */ export interface TerrainStyle { @@ -22,6 +23,11 @@ export interface TerrainStreamOptions { coarsestLevel: number /** The box the camera frames when the terrain is first shown; ground is looked for between its heights until tiles show where it really stands. */ focus: Box3 + /** + * A layer whose tiles arrive quickly, drawn where the layer's own have not arrived yet, or null for none; a layer + * whose tiles are slow to sample, such as one with generated blocks, so never leaves ground missing for long. + */ + quickLayerOf?(layer: Layer): Layer | null /** Told how many tiles are still on their way, whenever that changes. */ onPending(pending: number): void onError(message: string): void @@ -148,31 +154,54 @@ export class TerrainStream { } const sight = new CameraSight(this.camera.view(), this.lowestGround, this.highestGround) const layer = this.layer - const cover = planCover(sight, (tile) => this.stateOf(tile, layer), this.options.coarsestLevel) - this.store.want(cover.wanted.map(addressOf), layer) - this.draw(cover, layer, this.style) + const quick = this.options.quickLayerOf?.(layer) ?? null + const stateOf = (tile: TerrainTile): TileState => this.stateOf(tile, layer, quick) + const knownInside = (tile: TerrainTile): TerrainTile[] => this.drawnInside(tile) + const cover = planCover(sight, stateOf, this.options.coarsestLevel, knownInside) + this.store.wantEach(this.wantedOf(cover.wanted, layer, quick)) + this.draw(cover, layer, quick, this.style) this.reportPending() this.sightListeners.forEach((listener) => listener()) } - private stateOf(tile: TerrainTile, layer: Layer): TileState { + // Quick tiles come first, so the view fills at once. The slow ones go finest first: the ground near the camera, whose + // blocks show the most, is not kept waiting behind the horizon's tiles, which each take far longer. + private wantedOf(tiles: TerrainTile[], layer: Layer, quick: Layer | null): { address: TileAddress; layer: Layer }[] { + if (quick === null) { + return tiles.map((tile) => ({ address: addressOf(tile), layer })) + } + const quickOnes = tiles.filter((tile) => !this.store.has(addressOf(tile), quick)).map((tile) => ({ address: addressOf(tile), layer: quick })) + const finestFirst = [...tiles].sort((first, second) => first.level - second.level) + return [...quickOnes, ...finestFirst.map((tile) => ({ address: addressOf(tile), layer }))] + } + + private stateOf(tile: TerrainTile, layer: Layer, quick: Layer | null): TileState { if (this.store.has(addressOf(tile), layer)) { return 'fresh' } - return this.standIns.has(tileKey(tile)) ? 'standIn' : 'none' + if (this.standIns.has(tileKey(tile))) { + return 'standIn' + } + return quick !== null && this.store.has(addressOf(tile), quick) ? 'quick' : 'none' } - private dataOf(tile: TerrainTile, layer: Layer): Tile | null { + private dataOf(tile: TerrainTile, layer: Layer, quick: Layer | null): Tile | null { const key = tileKey(tile) const fresh = this.store.get(addressOf(tile), layer) if (fresh !== null) { this.standIns.delete(key) return fresh } - return this.standIns.get(key) ?? null + const quickTile = quick === null ? null : this.store.get(addressOf(tile), quick) + return this.standIns.get(key) ?? quickTile ?? null } - private draw(cover: Cover, layer: Layer, style: TerrainStyle): void { + // What is drawn now is what the view has; the planner keeps it, however fine, until a tile as true replaces it. + private drawnInside(tile: TerrainTile): TerrainTile[] { + return [...this.drawn.values()].map((drawn) => drawn.tile).filter((finer) => isInside(finer, tile)) + } + + private draw(cover: Cover, layer: Layer, quick: Layer | null, style: TerrainStyle): void { const deadline = performance.now() + MESH_BUILD_BUDGET_MILLISECONDS const stillDrawn = new Set() let behind = false @@ -180,7 +209,7 @@ export class TerrainStream { for (const draw of [...cover.draws].sort((first, second) => first.tile.level - second.tile.level)) { const key = tileKey(draw.tile) stillDrawn.add(key) - const data = this.dataOf(draw.tile, layer) + const data = this.dataOf(draw.tile, layer, quick) if (data === null || this.isCurrent(this.drawn.get(key), data, draw)) { continue } diff --git a/studio/src/renderer/src/studio/WorldStudio3D.tsx b/studio/src/renderer/src/studio/WorldStudio3D.tsx index f35b451f3..c27255940 100644 --- a/studio/src/renderer/src/studio/WorldStudio3D.tsx +++ b/studio/src/renderer/src/studio/WorldStudio3D.tsx @@ -22,6 +22,15 @@ const NUMBER = new Intl.NumberFormat('en-US') const COARSEST_LEVEL = 12 const BLOCKS_ABOVE_FLUID_IN_FOCUS = 96 const BLOCKS_BELOW_FLUID_IN_FOCUS = 32 +// Every level carries blocks, out to the horizon: a coarse tile generates a chunk for each of its columns, a minute or +// so of the server's time, and the ground already sampled stays in sight meanwhile. +const MOST_BLOCKS_PER_COLUMN = 2 ** COARSEST_LEVEL + +// Tiles with generated blocks take seconds to minutes each. The same tiles without them stand in, but only on ground +// where no tile with blocks of any level is known yet. +function withoutBlocks(layer: TileLayer): TileLayer | null { + return layer.blocks === null ? null : { ...layer, blocks: null } +} interface WorldStudio3DProps { title: string @@ -43,7 +52,7 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS const centre = useMemo(() => centreOf(mapArea), [mapArea]) const art = useMemo(() => blockArt(client, true), [client]) useEffect(() => () => art.dispose(), [art]) - const source = useMemo(() => mapTileSource(client, TILE_COLUMNS, art), [client, art]) + const source = useMemo(() => mapTileSource(client, TILE_COLUMNS, art, MOST_BLOCKS_PER_COLUMN), [client, art]) const focus = useMemo( () => focusAround(centre.x, centre.z, world.fluidHeight - BLOCKS_BELOW_FLUID_IN_FOCUS, world.fluidHeight + BLOCKS_ABOVE_FLUID_IN_FOCUS), [centre, world.fluidHeight] @@ -61,7 +70,7 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS }), [coloring, world.fluidHeight, world.minY, world.height, art] ) - const { content, pending, stream } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell) + const { content, pending, stream } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell, withoutBlocks) const sampling = useLongPending(pending) const ground = useGroundInView(stream) const heightShares = useMemo(() => heightBandShares(ground?.heights ?? [], world.fluidHeight), [ground, world.fluidHeight]) @@ -92,7 +101,7 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS Height - + Blocks diff --git a/studio/src/renderer/src/studio/useTerrainStream.ts b/studio/src/renderer/src/studio/useTerrainStream.ts index 5c4430773..6a33911d8 100644 --- a/studio/src/renderer/src/studio/useTerrainStream.ts +++ b/studio/src/renderer/src/studio/useTerrainStream.ts @@ -7,7 +7,8 @@ import type { ViewportContent } from './SceneViewport' /** * Endless terrain around {@code focus} for a viewport: the tiles of {@code layer} drawn in {@code style}, where the - * camera looks. A new layer keeps the ground drawn until its tiles arrive; a new source or focus starts again. + * camera looks. A new layer keeps the ground drawn until its tiles arrive; a new source or focus starts again. Where + * {@code quickLayerOf} gives a quicker layer, its tiles stand in until the layer's own arrive. * * @return what to show, or null before there is any, and how many tiles are still on their way */ @@ -17,7 +18,8 @@ export function useTerrainStream( focus: Box3, layer: Layer | null, style: TerrainStyle | null, - tell: (message: string) => void + tell: (message: string) => void, + quickLayerOf?: (layer: Layer) => Layer | null ): { content: ViewportContent | null; pending: number; stream: TerrainStream | null } { const [stream, setStream] = useState | null>(null) const [pending, setPending] = useState(0) @@ -25,14 +27,14 @@ export function useTerrainStream( latestTell.current = tell useEffect(() => { - const created = new TerrainStream({ source, coarsestLevel, focus, onPending: setPending, onError: (message) => latestTell.current(message) }) + const created = new TerrainStream({ source, coarsestLevel, focus, quickLayerOf, onPending: setPending, onError: (message) => latestTell.current(message) }) setStream(created) return () => { created.dispose() setStream(null) setPending(0) } - }, [source, coarsestLevel, focus]) + }, [source, coarsestLevel, focus, quickLayerOf]) useEffect(() => { if (layer !== null) { stream?.showLayer(layer)