mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
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:
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];
|
||||
|
||||
@@ -14,6 +14,8 @@ export interface TileSource<Tile, Layer, Style> {
|
||||
|
||||
interface StoredTile<Tile> {
|
||||
tile: Tile
|
||||
address: TileAddress
|
||||
layerKey: string
|
||||
bytes: number
|
||||
lastUsed: number
|
||||
picture: HTMLCanvasElement | null
|
||||
@@ -30,12 +32,13 @@ const CACHE_BYTES = 256 * 1024 * 1024
|
||||
*/
|
||||
export class TileStore<Tile, Layer, Style> {
|
||||
private readonly tiles = new Map<string, StoredTile<Tile>>()
|
||||
private readonly inFlight = new Map<string, AbortController>()
|
||||
private readonly inFlight = new Map<string, { controller: AbortController; layerKey: string }>()
|
||||
/** Asked for again only after a refresh, which changes every key, so a broken tile is not fetched on every frame. */
|
||||
private readonly failed = new Set<string>()
|
||||
private wanted: { key: string; address: TileAddress; layer: Layer }[] = []
|
||||
private storedBytes = 0
|
||||
private useClock = 0
|
||||
private changes = 0
|
||||
|
||||
constructor(
|
||||
private readonly source: TileSource<Tile, Layer, Style>,
|
||||
@@ -62,6 +65,17 @@ export class TileStore<Tile, Layer, Style> {
|
||||
return this.tiles.has(this.key(address, layer))
|
||||
}
|
||||
|
||||
/** Where the layer's tiles that have arrived lie; asking does not count as using them. */
|
||||
addressesOf(layer: Layer): TileAddress[] {
|
||||
const layerKey = this.source.layerKey(layer)
|
||||
return [...this.tiles.values()].filter((stored) => stored.layerKey === layerKey).map((stored) => stored.address)
|
||||
}
|
||||
|
||||
/** Changes whenever a tile arrives or is let go, so what is worked out from the stored tiles is worked out again. */
|
||||
get version(): number {
|
||||
return this.changes
|
||||
}
|
||||
|
||||
/** The tile drawn in {@code style}; restyled only when the style changed since it was last drawn. */
|
||||
picture(address: TileAddress, layer: Layer, style: Style): HTMLCanvasElement | null {
|
||||
const stored = this.tiles.get(this.key(address, layer))
|
||||
@@ -89,9 +103,9 @@ export class TileStore<Tile, Layer, Style> {
|
||||
.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) {
|
||||
for (const [key, request] of this.inFlight) {
|
||||
if (!stillWanted.has(key)) {
|
||||
controller.abort()
|
||||
request.controller.abort()
|
||||
this.inFlight.delete(key)
|
||||
}
|
||||
}
|
||||
@@ -104,33 +118,40 @@ export class TileStore<Tile, Layer, Style> {
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
for (const controller of this.inFlight.values()) {
|
||||
controller.abort()
|
||||
for (const request of this.inFlight.values()) {
|
||||
request.controller.abort()
|
||||
}
|
||||
this.inFlight.clear()
|
||||
this.failed.clear()
|
||||
this.tiles.clear()
|
||||
this.wanted = []
|
||||
this.storedBytes = 0
|
||||
this.changes++
|
||||
}
|
||||
|
||||
// Each layer has its own requests in flight, so tiles of a slow layer, which take a minute, never hold up a quick one's.
|
||||
private startRequests(): void {
|
||||
const inFlightByLayer = new Map<string, number>()
|
||||
for (const { layerKey } of this.inFlight.values()) {
|
||||
inFlightByLayer.set(layerKey, (inFlightByLayer.get(layerKey) ?? 0) + 1)
|
||||
}
|
||||
for (const entry of this.wanted) {
|
||||
if (this.inFlight.size >= MAXIMUM_IN_FLIGHT) {
|
||||
return
|
||||
}
|
||||
if (!this.inFlight.has(entry.key)) {
|
||||
this.fetchTile(entry.key, entry.address, entry.layer)
|
||||
const layerKey = this.source.layerKey(entry.layer)
|
||||
const inFlight = inFlightByLayer.get(layerKey) ?? 0
|
||||
if (this.inFlight.has(entry.key) || inFlight >= MAXIMUM_IN_FLIGHT) {
|
||||
continue
|
||||
}
|
||||
inFlightByLayer.set(layerKey, inFlight + 1)
|
||||
this.fetchTile(entry.key, layerKey, entry.address, entry.layer)
|
||||
}
|
||||
}
|
||||
|
||||
private fetchTile(key: string, address: TileAddress, layer: Layer): void {
|
||||
private fetchTile(key: string, layerKey: string, address: TileAddress, layer: Layer): void {
|
||||
const controller = new AbortController()
|
||||
this.inFlight.set(key, controller)
|
||||
this.inFlight.set(key, { controller, layerKey })
|
||||
this.source
|
||||
.fetch(address, layer, controller.signal)
|
||||
.then((tile) => this.store(key, tile))
|
||||
.then((tile) => this.store(key, address, layer, tile))
|
||||
.catch((error: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
this.failed.add(key)
|
||||
@@ -138,7 +159,7 @@ export class TileStore<Tile, Layer, Style> {
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (this.inFlight.get(key) === controller) {
|
||||
if (this.inFlight.get(key)?.controller === controller) {
|
||||
this.inFlight.delete(key)
|
||||
}
|
||||
this.wanted = this.wanted.filter((entry) => entry.key !== key)
|
||||
@@ -147,10 +168,11 @@ export class TileStore<Tile, Layer, Style> {
|
||||
})
|
||||
}
|
||||
|
||||
private store(key: string, tile: Tile): void {
|
||||
private store(key: string, address: TileAddress, layer: Layer, tile: Tile): void {
|
||||
const bytes = this.source.bytesOf(tile)
|
||||
this.tiles.set(key, { tile, bytes, lastUsed: ++this.useClock, picture: null, pictureStyle: '' })
|
||||
this.tiles.set(key, { tile, address, layerKey: this.source.layerKey(layer), bytes, lastUsed: ++this.useClock, picture: null, pictureStyle: '' })
|
||||
this.storedBytes += bytes
|
||||
this.changes++
|
||||
this.evictOldest()
|
||||
}
|
||||
|
||||
@@ -165,6 +187,7 @@ export class TileStore<Tile, Layer, Style> {
|
||||
}
|
||||
this.tiles.delete(key)
|
||||
this.storedBytes -= stored.bytes
|
||||
this.changes++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CanvasTexture, NearestFilter, type Texture } from 'three'
|
||||
import { CanvasTexture, NearestFilter, NearestMipmapLinearFilter, type Texture } from 'three'
|
||||
import { averageColor } from './blockColors'
|
||||
import { texturePath, type ImageSource } from './textureAtlas'
|
||||
|
||||
@@ -65,16 +65,21 @@ export class TerrainAtlas implements TerrainPictures, PictureSource {
|
||||
|
||||
private readonly drawing: CanvasRenderingContext2D
|
||||
private readonly cutoutDrawing: CanvasRenderingContext2D
|
||||
/** The texture halved again and again, down to a pixel a picture. */
|
||||
private readonly smallerDrawings: CanvasRenderingContext2D[]
|
||||
private readonly cells = new Map<string, Promise<UvCell | null>>()
|
||||
private used = PLAIN_CELL + 1
|
||||
|
||||
constructor(private readonly images: ImageSource) {
|
||||
;[this.drawing, this.texture] = sheet()
|
||||
;[this.cutoutDrawing, this.cutouts] = sheet()
|
||||
for (const drawing of [this.drawing, this.cutoutDrawing]) {
|
||||
this.smallerDrawings = withSmallerSheets(this.texture)
|
||||
for (const [level, drawing] of [this.drawing, ...this.smallerDrawings].entries()) {
|
||||
drawing.fillStyle = WHITE
|
||||
drawing.fillRect(0, 0, CELL_PIXELS, CELL_PIXELS)
|
||||
drawing.fillRect(0, 0, CELL_PIXELS >> level, CELL_PIXELS >> level)
|
||||
}
|
||||
this.cutoutDrawing.fillStyle = WHITE
|
||||
this.cutoutDrawing.fillRect(0, 0, CELL_PIXELS, CELL_PIXELS)
|
||||
}
|
||||
|
||||
cellOf(textureId: string): Promise<UvCell | null> {
|
||||
@@ -105,7 +110,12 @@ export class TerrainAtlas implements TerrainPictures, PictureSource {
|
||||
const average = averageColor(picture)
|
||||
const hasGaps = isOpenInPlaces(picture)
|
||||
this.cutoutDrawing.putImageData(cutoutOf(picture), left, top)
|
||||
this.drawing.putImageData(withGapsFilled(picture, average), left, top)
|
||||
let smaller = withGapsFilled(picture, average)
|
||||
this.drawing.putImageData(smaller, left, top)
|
||||
for (const [index, drawing] of this.smallerDrawings.entries()) {
|
||||
smaller = halved(smaller)
|
||||
drawing.putImageData(smaller, left >> (index + 1), top >> (index + 1))
|
||||
}
|
||||
this.texture.needsUpdate = true
|
||||
this.cutouts.needsUpdate = true
|
||||
return { ...placed, average, hasGaps }
|
||||
@@ -126,6 +136,41 @@ function sheet(): [CanvasRenderingContext2D, CanvasTexture] {
|
||||
return [drawing, texture]
|
||||
}
|
||||
|
||||
// Far off, a texture is drawn smaller, down to a pixel a picture: its average, as the coarser ground's flat colour is,
|
||||
// so the ground looks the same where it changes from textured blocks to coloured columns. Halving no further keeps every
|
||||
// level's pictures apart, and the nearest pixel of a level never reaches into the picture beside it.
|
||||
function withSmallerSheets(texture: CanvasTexture): CanvasRenderingContext2D[] {
|
||||
const drawings: CanvasRenderingContext2D[] = []
|
||||
for (let level = 1; CELL_PIXELS >> level >= 1; level++) {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = ATLAS_PIXELS >> level
|
||||
canvas.height = ATLAS_PIXELS >> level
|
||||
drawings.push(canvas.getContext('2d', { willReadFrequently: true })!)
|
||||
}
|
||||
texture.mipmaps = [texture.image, ...drawings.map((drawing) => drawing.canvas)]
|
||||
texture.minFilter = NearestMipmapLinearFilter
|
||||
return drawings
|
||||
}
|
||||
|
||||
/** The picture at half its size, each pixel the average of the four it covers. */
|
||||
export function halved(picture: ImageData): ImageData {
|
||||
const width = Math.max(1, picture.width >> 1)
|
||||
const height = Math.max(1, picture.height >> 1)
|
||||
const half = new ImageData(width, height)
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
for (let channel = 0; channel < 4; channel++) {
|
||||
let sum = 0
|
||||
for (const [dx, dy] of [[0, 0], [1, 0], [0, 1], [1, 1]]) {
|
||||
sum += picture.data[((y * 2 + dy) * picture.width + x * 2 + dx) * 4 + channel]
|
||||
}
|
||||
half.data[(y * width + x) * 4 + channel] = Math.round(sum / 4)
|
||||
}
|
||||
}
|
||||
}
|
||||
return half
|
||||
}
|
||||
|
||||
function isOpenInPlaces(picture: ImageData): boolean {
|
||||
for (let offset = 3; offset < picture.data.length; offset += 4) {
|
||||
if (picture.data[offset] < OPAQUE_ENOUGH_ALPHA) {
|
||||
|
||||
@@ -92,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 192 tiles each', () => {
|
||||
it('never asks for more than a backdrop, a preview and detail of 64 tiles each', () => {
|
||||
for (const height of [60, 600, 6000, 600_000]) {
|
||||
const { wanted } = planCover(sightFrom(height), nothingReady, COARSEST_LEVEL)
|
||||
expect(wanted.length).toBeLessThanOrEqual(3 * 192)
|
||||
expect(wanted.length).toBeLessThanOrEqual(3 * 64)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -29,12 +29,13 @@ export interface Cover {
|
||||
wanted: TerrainTile[]
|
||||
}
|
||||
|
||||
// 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
|
||||
// A column is drawn at most this many pixels wide, as wider ones show their blockiness; coarser ones only where there
|
||||
// are too many. Finer columns than a pixel cost the GPU faces no one can see: at half a pixel, a forest view held
|
||||
// twelve million triangles.
|
||||
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
|
||||
// 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
|
||||
|
||||
@@ -13,6 +13,8 @@ interface FlatLayer {
|
||||
height: number
|
||||
/** Resolves the tiles of the layer once called; they stay on their way until then. */
|
||||
gate: Promise<void>
|
||||
/** Where given, the gate of the tiles this many blocks a column, in place of {@link gate}. */
|
||||
gateAt?: (blocksPerPixel: number) => Promise<void>
|
||||
}
|
||||
|
||||
const COARSEST_LEVEL = 8
|
||||
@@ -56,7 +58,7 @@ function setUp(
|
||||
fetch: async (address, layer) => {
|
||||
requested.push(address.blocksPerPixel)
|
||||
requestedLayers.push(layer.name)
|
||||
await layer.gate
|
||||
await (layer.gateAt?.(address.blocksPerPixel) ?? layer.gate)
|
||||
return { height: layer.height }
|
||||
},
|
||||
bytesOf: () => 1
|
||||
@@ -223,6 +225,28 @@ describe('terrain stream', () => {
|
||||
expect(stream.content.surfaceAlong!(sight, 2000)!.y).toBeCloseTo(71, 1)
|
||||
})
|
||||
|
||||
it('shows the true ground it has from closer up again, rather than a quick stand-in, while coarser tiles are on their way', async () => {
|
||||
const neverArrives = new Promise<void>(() => {})
|
||||
const slow: FlatLayer = { name: 'slow', height: 90, gate: open, gateAt: (blocksPerPixel) => (blocksPerPixel <= 8 ? open : neverArrives) }
|
||||
const quick: FlatLayer = { name: 'quick', height: 70, gate: open }
|
||||
const { stream, camera, moved } = setUp(COARSEST_LEVEL, (layer) => (layer === slow ? quick : null))
|
||||
stream.restyle(flatStyle)
|
||||
stream.showLayer(slow)
|
||||
await settle()
|
||||
// Looking far away takes the ground near the origin out of sight, and so out of the drawn tiles.
|
||||
camera.position.set(500_000, 664, 360)
|
||||
camera.lookAt(500_000, 64, 0)
|
||||
moved()
|
||||
await settle()
|
||||
camera.position.set(0, 20_000, 12_000)
|
||||
camera.lookAt(LOOKED_AT)
|
||||
moved()
|
||||
await settle()
|
||||
|
||||
const ray = new Ray(new Vector3(10, 30_000, 10), new Vector3(0, -1, 0))
|
||||
expect(stream.content.surfaceAlong!(ray, 40_000)!.y).toBeCloseTo(91, 3)
|
||||
})
|
||||
|
||||
it('stops drawing when it is let go', async () => {
|
||||
const { stream, stopFollowing, requested } = setUp()
|
||||
stream.restyle(flatStyle)
|
||||
|
||||
@@ -8,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, isInside, tileContaining, tileKey, type TerrainTile } from './terrainTiles'
|
||||
import { addressOf, ancestorAt, childrenOf, isInside, tileAt, 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<Tile> {
|
||||
@@ -33,6 +33,14 @@ export interface TerrainStreamOptions<Tile, Layer> {
|
||||
onError(message: string): void
|
||||
}
|
||||
|
||||
/** A layer's tiles that have arrived, and every coarser tile that holds one, as of a version of the store. */
|
||||
interface StoredIndex {
|
||||
version: number
|
||||
layerKey: string
|
||||
tiles: Set<string>
|
||||
holding: Set<string>
|
||||
}
|
||||
|
||||
interface DrawnMesh<Tile> {
|
||||
tile: TerrainTile
|
||||
data: Tile
|
||||
@@ -65,6 +73,7 @@ export class TerrainStream<Tile, Layer> {
|
||||
private readonly drawn = new Map<string, DrawnMesh<Tile>>()
|
||||
private readonly sightListeners = new Set<() => void>()
|
||||
private standIns = new Map<string, Tile>()
|
||||
private storedIndex: StoredIndex | null = null
|
||||
private layer: Layer | null = null
|
||||
private style: TerrainStyle<Tile> | null = null
|
||||
private styleVersion = 0
|
||||
@@ -156,7 +165,7 @@ export class TerrainStream<Tile, Layer> {
|
||||
const layer = this.layer
|
||||
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 knownInside = (tile: TerrainTile): TerrainTile[] => [...this.coarsestStoredInside(tile, layer), ...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)
|
||||
@@ -196,11 +205,49 @@ export class TerrainStream<Tile, Layer> {
|
||||
return this.standIns.get(key) ?? quickTile ?? null
|
||||
}
|
||||
|
||||
// What is drawn now is what the view has; the planner keeps it, however fine, until a tile as true replaces it.
|
||||
// Ground drawn now, such as a stand-in left from the layer before, stays 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))
|
||||
}
|
||||
|
||||
// The layer's tiles that have arrived inside the tile, however much finer, but only the coarsest over each spot: they
|
||||
// show the ground as well from where it is too coarse for its own tile to have arrived, with the fewest faces.
|
||||
private coarsestStoredInside(tile: TerrainTile, layer: Layer): TerrainTile[] {
|
||||
const stored = this.storedIndexOf(layer)
|
||||
const found: TerrainTile[] = []
|
||||
const lookInside = (parent: TerrainTile): void => {
|
||||
for (const child of childrenOf(parent)) {
|
||||
const key = tileKey(child)
|
||||
if (stored.tiles.has(key)) {
|
||||
found.push(child)
|
||||
} else if (stored.holding.has(key)) {
|
||||
lookInside(child)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stored.holding.has(tileKey(tile))) {
|
||||
lookInside(tile)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
private storedIndexOf(layer: Layer): StoredIndex {
|
||||
const layerKey = this.options.source.layerKey(layer)
|
||||
if (this.storedIndex?.version === this.store.version && this.storedIndex.layerKey === layerKey) {
|
||||
return this.storedIndex
|
||||
}
|
||||
const index: StoredIndex = { version: this.store.version, layerKey, tiles: new Set(), holding: new Set() }
|
||||
for (const address of this.store.addressesOf(layer)) {
|
||||
const tile = tileAt(address)
|
||||
index.tiles.add(tileKey(tile))
|
||||
for (let level = tile.level + 1; level <= this.options.coarsestLevel; level++) {
|
||||
index.holding.add(tileKey(ancestorAt(tile, level)))
|
||||
}
|
||||
}
|
||||
this.storedIndex = index
|
||||
return index
|
||||
}
|
||||
|
||||
private draw(cover: Cover, layer: Layer, quick: Layer | null, style: TerrainStyle<Tile>): void {
|
||||
const deadline = performance.now() + MESH_BUILD_BUDGET_MILLISECONDS
|
||||
const stillDrawn = new Set<string>()
|
||||
|
||||
@@ -56,6 +56,11 @@ export function tileContaining(worldX: number, worldZ: number, level: number): T
|
||||
}
|
||||
|
||||
/** What to ask the bridge for: tile (x, z) of a layer sampled a column per pixel covers the same blocks. */
|
||||
/** The tile at an address, the reverse of {@link addressOf}. */
|
||||
export function tileAt(address: TileAddress): TerrainTile {
|
||||
return { level: Math.round(Math.log2(address.blocksPerPixel)), tileX: address.tileX, tileZ: address.tileZ }
|
||||
}
|
||||
|
||||
export function addressOf(tile: TerrainTile): TileAddress {
|
||||
return { tileX: tile.tileX, tileZ: tile.tileZ, blocksPerPixel: blocksPerColumn(tile.level) }
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user