diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java index ad3b4ced1..72b3730bb 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java @@ -41,7 +41,8 @@ import java.util.function.Function; * u8 voxelX[voxels] | padding to 4 | u8 voxelZ[voxels] | padding to 4 | i16 voxelY[voxels] | padding to 4 * | i16 voxelBlock[voxels] | padding to 4 | u8 voxelFaces[voxels] | padding to 4, when the header counts voxels * i16 runCounts[grid²] | padding to 4 | i16 runBottoms[runs] | padding to 4 | i16 runTops[runs] | padding to 4 - * | i16 runBlocks[runs] | padding to 4, when the header counts runs + * | i16 runBlocks[runs] | padding to 4 | i16 runCovers[runs] | padding to 4 | u8 runCoverShares[runs] | padding to 4, + * when the header counts runs * * {@code raised} is the sum of the raised counts, which the header also holds, as it holds {@code voxels}, the count of * blocks seen from the open air, and {@code runs}, the sum of the run counts, each -1 for a tile without them. @@ -79,7 +80,7 @@ final class MapTileEncoding { + (hasPickNoise ? cells * Float.BYTES : 0) + (blocks == null ? 0 : aligned(cells * Short.BYTES) * 3 + aligned(raised * Short.BYTES) * 2) + (voxels == null ? 0 : aligned(voxelCount) * 3 + aligned(voxelCount * Short.BYTES) * 2) - + (runs == null ? 0 : aligned(cells * Short.BYTES) + aligned(runCount * Short.BYTES) * 3); + + (runs == null ? 0 : aligned(cells * Short.BYTES) + aligned(runCount * Short.BYTES) * 4 + aligned(runCount)); ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(header.length).put(header); align(buffer); @@ -112,6 +113,8 @@ final class MapTileEncoding { putShorts(buffer, runs.bottoms()); putShorts(buffer, runs.tops()); putShorts(buffer, runs.blocks()); + putShorts(buffer, runs.covers()); + putBytes(buffer, runs.coverShares()); } return buffer.array(); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnRuns.java b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnRuns.java index 12ebfaded..0a3ed8d74 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnRuns.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnRuns.java @@ -20,6 +20,7 @@ package art.arcane.iris.core.studio.map; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.project.hunk.Hunk; +import it.unimi.dsi.fastutil.bytes.ByteArrayList; import it.unimi.dsi.fastutil.shorts.ShortArrayList; import java.util.ArrayList; @@ -35,22 +36,21 @@ import java.util.function.UnaryOperator; * solid blocks, highest first, as Distant Horizons draws far terrain. A height of an area counts as solid where at least * a quarter of its blocks are, so a tree is a canopy on a trunk with air beneath, not a pillar down to the ground. The * runs go down to the area's ground and no further; the last of each area is that ground, solid all the way down. - * Plants and water fill no run, as they are drawn their own way. + * Plants and water fill no run: plants count toward the look of the run they stand on, and water is drawn its own way. * - * @param counts how many runs each area has, the areas row by row from the north west - * @param bottoms the lowest height of each run, area after area - * @param tops the highest height of each run - * @param blocks the key of the block most of each run's top shows + * @param counts how many runs each area has, the areas row by row from the north west + * @param bottoms the lowest height of each run, area after area + * @param tops the highest height of each run + * @param blocks the key of the block most of each run's top shows + * @param covers the key of the plant most often standing on each run's top, or null where none does + * @param coverShares how much of each run's top its plants stand on, 0 for none to {@link #WHOLE_SHARE} for all of it */ -record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks) { +record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks, String[] covers, byte[] coverShares) { static final int MOST_LEVEL = 4; + static final int WHOLE_SHARE = 255; private static final int ACROSS = 16; private static final int SOLID_SHARE_DIVISOR = 4; - int areasAcross() { - return (int) Math.round(Math.sqrt(counts.length)); - } - /** Where the runs of the area at {@code index} start in {@link #bottoms}. */ int firstRunOf(int index) { int first = 0; @@ -70,24 +70,23 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks int areasAcross = ACROSS / areaBlocks; int fewestSolid = Math.max(1, areaBlocks * areaBlocks / SOLID_SHARE_DIVISOR); short[] counts = new short[areasAcross * areasAcross]; - ShortArrayList bottoms = new ShortArrayList(); - ShortArrayList tops = new ShortArrayList(); - List blocks = new ArrayList<>(); + Runs runs = new Runs(); for (int areaZ = 0; areaZ < areasAcross; areaZ++) { for (int areaX = 0; areaX < areasAcross; areaX++) { Area area = new Area(chunk, areaX * areaBlocks, areaZ * areaBlocks, areaBlocks, seenByPlayers); - int groundY = area.lowestOf(terrainY); - int found = area.addRuns(fewestSolid, groundY, bottoms, tops, blocks); - counts[areaZ * areasAcross + areaX] = (short) found; + int before = runs.found; + area.addRuns(fewestSolid, area.lowestOf(terrainY), runs); + counts[areaZ * areasAcross + areaX] = (short) (runs.found - before); } } - return new ColumnRuns(counts, bottoms.toShortArray(), tops.toShortArray(), blocks.toArray(String[]::new)); + return runs.toColumnRuns(counts); } @Override public boolean equals(Object other) { return other instanceof ColumnRuns runs && Arrays.equals(counts, runs.counts) && Arrays.equals(bottoms, runs.bottoms) - && Arrays.equals(tops, runs.tops) && Arrays.equals(blocks, runs.blocks); + && Arrays.equals(tops, runs.tops) && Arrays.equals(blocks, runs.blocks) && Arrays.equals(covers, runs.covers) + && Arrays.equals(coverShares, runs.coverShares); } @Override @@ -97,57 +96,75 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks @Override public String toString() { - return "ColumnRuns" + Arrays.toString(counts) + Arrays.toString(bottoms) + Arrays.toString(tops) + Arrays.toString(blocks); + return "ColumnRuns" + Arrays.toString(counts) + Arrays.toString(bottoms) + Arrays.toString(tops) + Arrays.toString(blocks) + + Arrays.toString(covers) + Arrays.toString(coverShares); } - /** The runs of one area as they are found from the top down. */ + /** The plant most often standing on a run's top, and how much of the top plants stand on. */ + private record Cover(String block, int share) { + static final Cover NONE = new Cover(null, 0); + } + + /** The runs of every area as they are found, area after area and each area's from the top down. */ private static final class Runs { private static final int NONE = -1; - private final ShortArrayList bottoms; - private final ShortArrayList tops; - private final List blocks; + private final ShortArrayList bottoms = new ShortArrayList(); + private final ShortArrayList tops = new ShortArrayList(); + private final List blocks = new ArrayList<>(); + private final List covers = new ArrayList<>(); + private final ByteArrayList coverShares = new ByteArrayList(); private int top = NONE; private int bottom; private String block; + private Cover cover; private int found; - Runs(ShortArrayList bottoms, ShortArrayList tops, List blocks) { - this.bottoms = bottoms; - this.tops = tops; - this.blocks = blocks; + boolean isOpen() { + return top != NONE; } - void extendTo(int y, String shown) { - if (top != NONE && !shown.equals(block)) { - end(bottom); - } - if (top == NONE) { - top = y; - block = shown; - } + boolean continues(String shown) { + return isOpen() && shown.equals(block); + } + + void start(int y, String shown, Cover onTop) { + top = y; + bottom = y; + block = shown; + cover = onTop; + } + + void extendTo(int y) { bottom = y; } - void endAbove(int y) { - if (top != NONE) { - end(y + 1); + void end() { + if (isOpen()) { + add(bottom); } } // The ground reaches down out of sight, so its run has no bottom to draw. void endAsGround() { - if (top != NONE) { - end(0); + if (isOpen()) { + add(0); } } - private void end(int runBottom) { + private void add(int runBottom) { bottoms.add((short) runBottom); tops.add((short) top); blocks.add(block); + covers.add(cover.block()); + coverShares.add((byte) cover.share()); found++; top = NONE; } + + ColumnRuns toColumnRuns(short[] counts) { + return new ColumnRuns(counts, bottoms.toShortArray(), tops.toShortArray(), blocks.toArray(String[]::new), + covers.toArray(String[]::new), coverShares.toByteArray()); + } } /** One square area of a chunk, read a height at a time. */ @@ -164,21 +181,25 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks // From the top down, a run holds the solid heights in a row that mostly show one block, so a canopy, the trunk // under it and the ground are runs of their own. Once a run reaches the ground, it is the ground and the last. - int addRuns(int fewestSolid, int groundY, ShortArrayList bottoms, ShortArrayList tops, List blocks) { - Runs runs = new Runs(bottoms, tops, blocks); + void addRuns(int fewestSolid, int groundY, Runs runs) { for (int y = chunk.getHeight() - 1; y >= 0; y--) { if (solidCountAt(y) < fewestSolid) { - runs.endAbove(y); + runs.end(); continue; } - runs.extendTo(y, mostShownAt(y)); + String shown = mostShownAt(y); + if (runs.continues(shown)) { + runs.extendTo(y); + } else { + runs.end(); + runs.start(y, shown, coverOn(y)); + } if (y <= groundY) { runs.endAsGround(); - return runs.found; + return; } } runs.endAsGround(); - return runs.found; } private int solidCountAt(int y) { @@ -203,7 +224,30 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks } } } - return shown.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElseThrow(); + return mostOf(shown); + } + + // The plants standing on the area's blocks at the height, out of all the area's columns. + private Cover coverOn(int y) { + if (y + 1 >= chunk.getHeight()) { + return Cover.NONE; + } + Map plants = new HashMap<>(); + int standing = 0; + for (int z = minZ; z < minZ + across; z++) { + for (int x = minX; x < minX + across; x++) { + PlatformBlockState above = chunk.get(x, y + 1, z); + if (isSolid(chunk.get(x, y, z)) && isPlant(above)) { + plants.merge(above.key(), 1, Integer::sum); + standing++; + } + } + } + return standing == 0 ? Cover.NONE : new Cover(mostOf(plants), standing * WHOLE_SHARE / (across * across)); + } + + private static String mostOf(Map counts) { + return counts.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElseThrow(); } private boolean isSolid(PlatformBlockState block) { @@ -213,5 +257,13 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks PlatformBlockState seen = seenByPlayers.apply(block); return !seen.isAir() && !seen.isFluid() && seen.isSolid(); } + + private boolean isPlant(PlatformBlockState block) { + if (block == null || block.isAir()) { + return false; + } + PlatformBlockState seen = seenByPlayers.apply(block); + return !seen.isAir() && !seen.isFluid() && !seen.isSolid(); + } } } 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 6ed243fc1..df7a21c3b 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 @@ -51,8 +51,11 @@ interface ColumnTops { return null; } - /** One area's runs of solid blocks, highest first, the last being the ground. */ - record AreaRuns(short[] bottoms, short[] tops, String[] blocks) { + /** + * One area's runs of solid blocks, highest first, the last being the ground, with the plant most often standing on + * each run's top, or null, and how much of the top plants stand on, out of {@link ColumnRuns#WHOLE_SHARE}. + */ + record AreaRuns(short[] bottoms, short[] tops, String[] blocks, String[] covers, byte[] coverShares) { } /** 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 cfc4700ec..f435d2591 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 @@ -264,7 +264,8 @@ final class GeneratedChunks implements ColumnTops { int first = runs.firstRunOf(area); int last = first + runs.counts()[area]; return new AreaRuns(Arrays.copyOfRange(runs.bottoms(), first, last), Arrays.copyOfRange(runs.tops(), first, last), - Arrays.copyOfRange(runs.blocks(), first, last)); + Arrays.copyOfRange(runs.blocks(), first, last), Arrays.copyOfRange(runs.covers(), first, last), + Arrays.copyOfRange(runs.coverShares(), first, last)); } private static void awaitUnlessCancelled(Future chunk, BooleanSupplier cancelled) { diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java index 37654eb16..43a2d3d21 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java @@ -61,9 +61,11 @@ public record MapTile(int size, double blocksPerPixel, MapLabel.Kind subjectKind * @param counts how many runs each cell has * @param bottoms the lowest height of each run, cell after cell * @param tops the highest height of each run - * @param blocks the index in the tile's block names of the block most of each run's top shows + * @param blocks the index in the tile's block names of the block most of each run's top shows + * @param covers the index of the plant most often standing on each run's top, or {@link Blocks#NO_BLOCK} + * @param coverShares how much of each run's top plants stand on, 0 to 255 for all of it */ - public record Runs(short[] counts, short[] bottoms, short[] tops, short[] blocks) { + public record Runs(short[] counts, short[] bottoms, short[] tops, short[] blocks, short[] covers, byte[] coverShares) { public int count() { return tops.length; } 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 872008020..554f43035 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 @@ -24,6 +24,7 @@ import art.arcane.iris.engine.framework.render.RenderType; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.util.project.stream.ProceduralStream; +import it.unimi.dsi.fastutil.bytes.ByteArrayList; import it.unimi.dsi.fastutil.shorts.ShortArrayList; import java.util.ArrayList; @@ -130,6 +131,8 @@ public final class MapTileRenderer { ShortArrayList bottoms = new ShortArrayList(); ShortArrayList runTops = new ShortArrayList(); ShortArrayList blocks = new ShortArrayList(); + ShortArrayList covers = new ShortArrayList(); + ByteArrayList coverShares = new ByteArrayList(); for (int gridZ = 0; gridZ < grid.size(); gridZ++) { int worldZ = (int) Math.floor(grid.worldZ(gridZ)); for (int gridX = 0; gridX < grid.size(); gridX++) { @@ -140,12 +143,15 @@ public final class MapTileRenderer { counts[gridZ * grid.size() + gridX] = (short) area.tops().length; bottoms.addElements(bottoms.size(), area.bottoms()); runTops.addElements(runTops.size(), area.tops()); - for (String block : area.blocks()) { - blocks.add(names.indexOf(block)); + for (int run = 0; run < area.tops().length; run++) { + blocks.add(names.indexOf(area.blocks()[run])); + covers.add(names.indexOf(area.covers()[run])); } + coverShares.addElements(coverShares.size(), area.coverShares()); } } - return new MapTile.Runs(counts, bottoms.toShortArray(), runTops.toShortArray(), blocks.toShortArray()); + return new MapTile.Runs(counts, bottoms.toShortArray(), runTops.toShortArray(), blocks.toShortArray(), covers.toShortArray(), + coverShares.toByteArray()); } // Only a tile of a block a pixel shows its blocks one by one; coarser ones show the tops of their columns. diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java index 2688b413f..bd515770c 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java @@ -17,6 +17,7 @@ public class ColumnRunsTest { private static final PlatformBlockState GRASS = block("minecraft:grass_block"); private static final PlatformBlockState LOG = block("minecraft:oak_log"); private static final PlatformBlockState LEAVES = block("minecraft:oak_leaves"); + private static final PlatformBlockState GRASS_PLANT = plant("minecraft:short_grass"); @Test public void flatGroundIsOneRunPerArea() { @@ -67,6 +68,18 @@ public class ColumnRunsTest { assertEquals(GROUND_Y, runs.tops()[first + 1]); } + @Test + public void aRunKnowsThePlantsStandingOnItsTop() { + Hunk chunk = groundUpTo(GROUND_Y); + chunk.set(0, GROUND_Y + 1, 0, GRASS_PLANT); + + ColumnRuns runs = ColumnRuns.of(chunk, 1, (x, z) -> GROUND_Y, UnaryOperator.identity()); + + assertEquals("minecraft:short_grass", runs.covers()[0]); + assertEquals(ColumnRuns.WHOLE_SHARE / 4, runs.coverShares()[0] & 0xFF); + assertEquals(null, runs.covers()[1]); + } + private static Hunk groundUpTo(int topY) { Hunk chunk = Hunk.newArrayHunk(16, HEIGHT, 16); for (int y = 0; y <= topY; y++) { @@ -85,4 +98,10 @@ public class ColumnRunsTest { when(block.isSolid()).thenReturn(true); return block; } + + private static PlatformBlockState plant(String key) { + PlatformBlockState block = mock(PlatformBlockState.class); + when(block.key()).thenReturn(key); + return block; + } } diff --git a/studio/src/main/discreteGpu.ts b/studio/src/main/discreteGpu.ts new file mode 100644 index 000000000..81a8ad25c --- /dev/null +++ b/studio/src/main/discreteGpu.ts @@ -0,0 +1,47 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs' +import { join } from 'node:path' + +const NVIDIA_VENDOR_ID = '0x10de' +const DRM_FOLDER = '/sys/class/drm' +const DEVICE_FOLDER = '/dev/dri' +const RENDER_NODE_PREFIX = 'renderD' +// Where glvnd looks for EGL drivers, NixOS's first. +const EGL_VENDOR_FOLDERS = ['/run/opengl-driver/share/glvnd/egl_vendor.d', '/usr/share/glvnd/egl_vendor.d', '/etc/glvnd/egl_vendor.d'] +const NVIDIA_EGL_VENDOR_FILE = '10_nvidia.json' + +/** + * On Linux, Chromium draws with the default EGL driver, which on a laptop with an NVIDIA GPU beside the integrated one + * is the integrated GPU's: there the 3D world, tens of millions of triangles, runs at a few frames a second where the + * NVIDIA GPU keeps 60. Where there is an NVIDIA GPU and its EGL driver, this sets the environment that points the GPU + * process at that driver with PRIME render offload. An environment that already names an EGL driver is left as it is, + * which is also how to keep the integrated GPU. + * + * @return the NVIDIA GPU's render node, on which the window's buffers must be made too, as the NVIDIA driver cannot draw + * into buffers of the integrated GPU; null where nothing changed. The GPU process has read the environment by the + * time the app's code runs, so the app has to start again, with the render node, for the change to count. + */ +export function preferDiscreteGpu(env: NodeJS.ProcessEnv): string | null { + if (process.platform !== 'linux' || env.__EGL_VENDOR_LIBRARY_FILENAMES !== undefined) { + return null + } + const renderNode = nvidiaRenderNode() + const driver = EGL_VENDOR_FOLDERS.map((folder) => join(folder, NVIDIA_EGL_VENDOR_FILE)).find((file) => existsSync(file)) + if (renderNode === null || driver === undefined) { + return null + } + env.__EGL_VENDOR_LIBRARY_FILENAMES = driver + env.__NV_PRIME_RENDER_OFFLOAD = '1' + env.__GLX_VENDOR_LIBRARY_NAME = 'nvidia' + return renderNode +} + +function nvidiaRenderNode(): string | null { + try { + const node = readdirSync(DRM_FOLDER) + .filter((name) => name.startsWith(RENDER_NODE_PREFIX)) + .find((name) => readFileSync(join(DRM_FOLDER, name, 'device', 'vendor'), 'utf8').trim() === NVIDIA_VENDOR_ID) + return node === undefined ? null : join(DEVICE_FOLDER, node) + } catch { + return null + } +} diff --git a/studio/src/main/index.ts b/studio/src/main/index.ts index f2213f1c2..074727202 100644 --- a/studio/src/main/index.ts +++ b/studio/src/main/index.ts @@ -3,6 +3,15 @@ import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises' import { homedir } from 'node:os' import { dirname, join } from 'node:path' import type { BridgeConnection, StoredShortcuts, ThemeChoice } from '../shared/bridge' +import { preferDiscreteGpu } from './discreteGpu' + +// The GPU process started with the environment the app was launched with, so a change to it takes a fresh start, which +// then finds the environment already set and goes on. +const discreteRenderNode = preferDiscreteGpu(process.env) +if (discreteRenderNode !== null) { + app.relaunch({ args: [...process.argv.slice(1), `--render-node-override=${discreteRenderNode}`] }) + app.exit(0) +} const CONNECTION_FOLDER = join(homedir(), '.iris', 'studio', 'bridges') const SETTINGS_FILE = 'studio.json' diff --git a/studio/src/renderer/src/bridge/tileDecoding.ts b/studio/src/renderer/src/bridge/tileDecoding.ts index efcb5b5c6..e7ca7ac95 100644 --- a/studio/src/renderer/src/bridge/tileDecoding.ts +++ b/studio/src/renderer/src/bridge/tileDecoding.ts @@ -86,11 +86,15 @@ function decodeRuns(buffer: ArrayBuffer, countsAt: number, cells: number, count: const bottomsAt = countsAt + aligned(cells * Int16Array.BYTES_PER_ELEMENT) const topsAt = bottomsAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) const blocksAt = topsAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const coversAt = blocksAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const coverSharesAt = coversAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) return { starts: startsOf(new Int16Array(buffer, countsAt, cells)), bottoms: new Int16Array(buffer, bottomsAt, count), tops: new Int16Array(buffer, topsAt, count), - blocks: new Int16Array(buffer, blocksAt, count) + blocks: new Int16Array(buffer, blocksAt, count), + covers: new Int16Array(buffer, coversAt, count), + coverShares: new Uint8Array(buffer, coverSharesAt, count) } } diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index f81fbc88c..f90d04891 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -402,6 +402,10 @@ export interface TileRuns { tops: Int16Array /** The index in the tile's block names of the block most of each run's top shows. */ blocks: Int16Array + /** The index of the plant most often standing on each run's top, or {@link NO_BLOCK}. */ + covers: Int16Array + /** How much of each run's top plants stand on, 0 to 255 for all of it. */ + coverShares: Uint8Array } /** The order of the sides in {@link TileVoxels.faces}. */ diff --git a/studio/src/renderer/src/map/TileStore.ts b/studio/src/renderer/src/map/TileStore.ts index 00b42814e..89a920bf3 100644 --- a/studio/src/renderer/src/map/TileStore.ts +++ b/studio/src/renderer/src/map/TileStore.ts @@ -24,7 +24,8 @@ interface StoredTile { // Drawing a few hundred tiles at once only queues them on the server; a handful in flight keeps it busy. const MAXIMUM_IN_FLIGHT = 6 -const CACHE_BYTES = 256 * 1024 * 1024 +// A 3D view holds a couple of hundred tiles of blocks, half a megabyte each, and turning back should not sample them again. +const CACHE_BYTES = 1024 * 1024 * 1024 /** * Tiles fetched from the bridge as a view needs them, kept within a memory budget, and drawn as the current style diff --git a/studio/src/renderer/src/scene/columnField.ts b/studio/src/renderer/src/scene/columnField.ts index a0d60bdd6..3039b9a27 100644 --- a/studio/src/renderer/src/scene/columnField.ts +++ b/studio/src/renderer/src/scene/columnField.ts @@ -13,6 +13,18 @@ const NOTHING_RAISED: readonly RaisedBlock[] = [] * stands one above the block's Y, so ground and water sit where a player stands on them. Where nothing is known, or * where the columns are {@code holes} left to finer ground, the column has no ground and no water. */ +/** Where a field's ground and water stand, without the looks it was drawn with. */ +export interface FieldShape { + columns: number + rows: number + originX: number + originZ: number + blocksPerColumn: number + groundTop: Float32Array + waterTop: Float32Array + topRange: { lowest: number; highest: number } | null +} + export class ColumnField { readonly columns: number readonly rows: number @@ -75,6 +87,25 @@ export class ColumnField { this.topRange = lowestTop === Infinity ? null : { lowest: lowestTop, highest: highestTop } } + /** Where the field's ground and water stand, as plain data that can be sent to and from a worker. */ + shape(): FieldShape { + const { columns, rows, originX, originZ, blocksPerColumn, groundTop, waterTop, topRange } = this + return { columns, rows, originX, originZ, blocksPerColumn, groundTop, waterTop, topRange } + } + + /** A field rebuilt from its {@link shape}, which answers where its ground and water stand but holds no looks to draw. */ + static ofShape(shape: FieldShape): ColumnField { + const count = shape.columns * shape.rows + return Object.assign(Object.create(ColumnField.prototype) as ColumnField, { + ...shape, + color: new Int32Array(count), + looks: [], + covers: [], + raised: [], + pictures: null + }) + } + indexOf(column: number, row: number): number { return row * this.columns + column } diff --git a/studio/src/renderer/src/scene/compactGeometry.test.ts b/studio/src/renderer/src/scene/compactGeometry.test.ts new file mode 100644 index 000000000..b8189b147 --- /dev/null +++ b/studio/src/renderer/src/scene/compactGeometry.test.ts @@ -0,0 +1,37 @@ +import { BufferAttribute, BufferGeometry, Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import { compacted, geometryOfCompact } from './compactGeometry' + +function geometryOf(positions: number[], colors: number[], uvs: number[]): BufferGeometry { + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(Float32Array.from(positions), 3)) + geometry.setAttribute('color', new BufferAttribute(Float32Array.from(colors), 3)) + geometry.setAttribute('uv', new BufferAttribute(Float32Array.from(uvs), 2)) + geometry.setIndex(new BufferAttribute(Uint32Array.of(0, 1, 2), 1)) + return geometry +} + +// Where a corner of the packed geometry lands once placed. +function placedCorner(arrays: ReturnType, corner: number): Vector3 { + const position = geometryOfCompact(arrays).getAttribute('position') + const { origin, scale } = arrays.placement + return new Vector3(origin[0] + position.getX(corner) * scale[0], origin[1] + position.getY(corner) * scale[1], origin[2] + position.getZ(corner) * scale[2]) +} + +describe('compact geometry', () => { + it('keeps the corners of block models where they were, to a sixteenth of a block', () => { + const arrays = compacted(geometryOf([100, 64, 200, 100.3125, 65, 200, 101, 64.5, 201], [0, 0.5, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0.5, 0.25, 1, 1]), 1) + + expect(placedCorner(arrays, 1).toArray()).toEqual([100.3125, 65, 200]) + expect(placedCorner(arrays, 2).toArray()).toEqual([101, 64.5, 201]) + expect(geometryOfCompact(arrays).getAttribute('color').getY(0)).toBeCloseTo(0.5, 2) + expect(geometryOfCompact(arrays).getAttribute('uv').getX(1)).toBeCloseTo(0.5, 4) + }) + + it('fits ground reaching far down by taking longer steps up and down', () => { + const arrays = compacted(geometryOf([0, -2048, 0, 1, 2048, 0, 0, 0, 1], new Array(9).fill(0), new Array(6).fill(0)), 1) + + expect(placedCorner(arrays, 1).y).toBeCloseTo(2048, 0) + expect(placedCorner(arrays, 0).y).toBe(-2048) + }) +}) diff --git a/studio/src/renderer/src/scene/compactGeometry.ts b/studio/src/renderer/src/scene/compactGeometry.ts new file mode 100644 index 000000000..55d4bfbc0 --- /dev/null +++ b/studio/src/renderer/src/scene/compactGeometry.ts @@ -0,0 +1,68 @@ +import { BufferAttribute, BufferGeometry, type Vector3Tuple } from 'three' + +// Positions are kept in sixteenths of a block, the finest step a block model uses, from the geometry's lowest corner. +const STEPS_PER_BLOCK = 16 +const MOST_STEPS = 32_767 + +/** Where a compact geometry's corner lies in the world and how far one of its steps goes along each axis. */ +export interface CompactPlacement { + origin: Vector3Tuple + scale: Vector3Tuple +} + +/** A geometry's arrays packed small: positions in whole steps, colours a byte a channel, picture places in 16 bits. */ +export interface CompactArrays { + position: Int16Array + color: Uint8Array | null + uv: Uint16Array | null + index: Uint32Array + placement: CompactPlacement +} + +/** + * The geometry's arrays in about half the bytes, which the GPU takes in half the time: a tile's corners are whole steps + * of a sixteenth of a block, or of a column across wider columns, from the tile's lowest corner; colours and picture + * places are fractions packed into integers. A geometry too tall for that many steps takes longer steps up and down. + */ +export function compacted(geometry: BufferGeometry, blocksPerColumn: number): CompactArrays { + const positions = geometry.getAttribute('position').array as Float32Array + const min: Vector3Tuple = [Infinity, Infinity, Infinity] + const max: Vector3Tuple = [-Infinity, -Infinity, -Infinity] + for (let at = 0; at < positions.length; at += 3) { + for (let axis = 0; axis < 3; axis++) { + min[axis] = Math.min(min[axis], positions[at + axis]) + max[axis] = Math.max(max[axis], positions[at + axis]) + } + } + const horizontal = blocksPerColumn / STEPS_PER_BLOCK + const stepFor = (axis: number, finest: number): number => Math.max(finest, (max[axis] - min[axis]) / MOST_STEPS) + const scale: Vector3Tuple = [stepFor(0, horizontal), stepFor(1, 1 / STEPS_PER_BLOCK), stepFor(2, horizontal)] + const position = new Int16Array(positions.length) + for (let at = 0; at < positions.length; at++) { + const axis = at % 3 + position[at] = Math.round((positions[at] - min[axis]) / scale[axis]) + } + const color = geometry.getAttribute('color')?.array as Float32Array | undefined + const uv = geometry.getAttribute('uv')?.array as Float32Array | undefined + return { + position, + color: color === undefined ? null : Uint8Array.from(color, (channel) => Math.round(Math.min(1, Math.max(0, channel)) * 255)), + uv: uv === undefined ? null : Uint16Array.from(uv, (place) => Math.round(Math.min(1, Math.max(0, place)) * 65_535)), + index: geometry.getIndex()!.array as Uint32Array, + placement: { origin: min, scale } + } +} + +/** The geometry the compact arrays hold, in the steps they were packed in; draw it placed by their placement. */ +export function geometryOfCompact(arrays: CompactArrays): BufferGeometry { + const geometry = new BufferGeometry() + geometry.setAttribute('position', new BufferAttribute(arrays.position, 3)) + if (arrays.color !== null) { + geometry.setAttribute('color', new BufferAttribute(arrays.color, 3, true)) + } + if (arrays.uv !== null) { + geometry.setAttribute('uv', new BufferAttribute(arrays.uv, 2, true)) + } + geometry.setIndex(new BufferAttribute(arrays.index, 1)) + return geometry +} diff --git a/studio/src/renderer/src/scene/runFaces.test.ts b/studio/src/renderer/src/scene/runFaces.test.ts index 70fe66394..7bec40384 100644 --- a/studio/src/renderer/src/scene/runFaces.test.ts +++ b/studio/src/renderer/src/scene/runFaces.test.ts @@ -26,7 +26,9 @@ const runs: SurfaceRuns = { starts: Int32Array.of(0, 1, 3), bottoms: Int16Array.of(0, CANOPY_BOTTOM, 0), tops: Int16Array.of(GROUND, CANOPY_TOP, GROUND), - blocks: Int16Array.of(0, 1, 0) + blocks: Int16Array.of(0, 1, 0), + covers: Int16Array.of(-1, -1, -1), + coverShares: new Uint8Array(3) }, cellAt: (column) => column, looks: [null, null], @@ -51,6 +53,20 @@ describe('run faces', () => { expect(uncovered({ bottom: -Infinity, top: 10 }, [{ bottom: -Infinity, top: 12 }])).toEqual([]) }) + it('draws the tops of neighbouring columns at one height in one block as one face', () => { + const flat: SurfaceRuns = { ...runs, runs: { starts: Int32Array.of(0, 1, 2), bottoms: Int16Array.of(0, 0), tops: Int16Array.of(GROUND, GROUND), blocks: Int16Array.of(0, 0), covers: Int16Array.of(-1, -1), coverShares: new Uint8Array(2) } } + const geometry = runFaces(new ColumnField(surface), flat, BASE).geometry() + const positions = geometry.getAttribute('position') + const tops = [] + for (let first = 0; first < positions.count; first += 4) { + if (positions.getY(first) === GROUND + 1 && positions.getY(first + 3) === GROUND + 1) { + tops.push(Math.abs(positions.getX(first + 3) - positions.getX(first))) + } + } + + expect(tops).toEqual([2]) + }) + it('floats a canopy over the ground with its underside showing', () => { const drawn = faces() diff --git a/studio/src/renderer/src/scene/runFaces.ts b/studio/src/renderer/src/scene/runFaces.ts index 68ff288e9..4e5e58674 100644 --- a/studio/src/renderer/src/scene/runFaces.ts +++ b/studio/src/renderer/src/scene/runFaces.ts @@ -1,4 +1,4 @@ -import type { TileRuns } from '../bridge/types' +import { NO_BLOCK, type TileRuns } from '../bridge/types' import type { Direction } from './blockModels' import type { BlockLook } from './blockLooks' import type { ColumnField } from './columnField' @@ -40,21 +40,22 @@ interface Span { * its underside where it floats, and its sides where the columns beside it leave them in the open. The ground reaches * down to the run under its neighbours' tops, or to {@code base} at the field's edge and beside holes, so tiles next to * each other leave no cracks. Each face takes the average colour of its block's picture on that side, as the textures of - * finer ground fade to it with distance, so the change from one to the other cannot be seen. + * finer ground fade to it with distance, so the change from one to the other cannot be seen. Faces of neighbouring + * columns that lie in one plane over the same heights in the same colour are one face. */ export function runFaces(field: ColumnField, surface: SurfaceRuns, base: number): QuadBatch { - const batch = new QuadBatch(true) + const faces = new MergedFaces(field) for (let row = 0; row < field.rows; row++) { for (let column = 0; column < field.columns; column++) { if (field.hasGround(column, row)) { - addColumn(batch, field, surface, column, row, base) + addColumn(faces, field, surface, column, row, base) } } } - return batch + return faces.batch() } -function addColumn(batch: QuadBatch, field: ColumnField, surface: SurfaceRuns, column: number, row: number, base: number): void { +function addColumn(faces: MergedFaces, field: ColumnField, surface: SurfaceRuns, column: number, row: number, base: number): void { const { runs } = surface const cell = surface.cellAt(column, row) const first = runs.starts[cell] @@ -66,10 +67,12 @@ function addColumn(batch: QuadBatch, field: ColumnField, surface: SurfaceRuns, c const bottom = runs.bottoms[run] const block = runs.blocks[run] if (run === first || runs.bottoms[run - 1] !== top + 1) { - addTop(batch, field, column, row, top + 1, colorOf(surface, block, 'top', FACE_LIGHT.up), water) + const color = underWater(withPlants(surface, run, colorOf(surface, block, 'top', FACE_LIGHT.up)), top + 1, water) + faces.add('up', row, column, top + 1, top + 1, color, color) } if (!isGround && (run === last || runs.tops[run + 1] !== bottom - 1)) { - addBottom(batch, field, column, row, bottom, colorOf(surface, block, 'top', FACE_LIGHT.down), water) + const color = underWater(colorOf(surface, block, 'top', FACE_LIGHT.down), bottom, water) + faces.add('down', row, column, bottom, bottom, color, color) } for (const side of SIDES) { const neighbour = [column + side.columnStep, row + side.rowStep] as const @@ -77,7 +80,7 @@ function addColumn(batch: QuadBatch, field: ColumnField, surface: SurfaceRuns, c const lowest = isGround ? (known ? -Infinity : base) : bottom const covered = known ? spansOf(surface, surface.cellAt(...neighbour)) : [] for (const open of uncovered({ bottom: lowest, top }, covered)) { - addSide(batch, field, surface, column, row, side, open, top, block, water) + addSide(faces, surface, column, row, side, open, top, block, water) } } } @@ -120,50 +123,117 @@ export function uncovered(span: Span, covered: readonly Span[]): Span[] { } // The top block of a run shows its side picture; the blocks under it, the picture of the blocks under a column's top. -function addSide(batch: QuadBatch, field: ColumnField, surface: SurfaceRuns, column: number, row: number, side: Side, open: Span, runTop: number, block: number, water: number | null): void { +function addSide(faces: MergedFaces, surface: SurfaceRuns, column: number, row: number, side: Side, open: Span, runTop: number, block: number, water: number | null): void { const light = side.direction === 'north' || side.direction === 'south' ? FACE_LIGHT.north : FACE_LIGHT.west if (open.top === runTop) { - addSideQuad(batch, field, column, row, side, runTop, runTop + 1, colorOf(surface, block, 'side', light), water) + const color = colorOf(surface, block, 'side', light) + faces.add(side.direction, row, column, runTop, runTop + 1, underWater(color, runTop, water), underWater(color, runTop + 1, water)) } const belowTop = open.top === runTop ? runTop - 1 : open.top if (belowTop >= open.bottom) { - addSideQuad(batch, field, column, row, side, open.bottom, belowTop + 1, colorOf(surface, block, 'below', light), water) + const color = colorOf(surface, block, 'below', light) + faces.add(side.direction, row, column, open.bottom, belowTop + 1, underWater(color, open.bottom, water), underWater(color, belowTop + 1, water)) } } -function addSideQuad(batch: QuadBatch, field: ColumnField, column: number, row: number, side: Side, from: number, to: number, color: Vec3, water: number | null): void { - const step = field.blocksPerColumn - const x = field.originX + column * step - const z = field.originZ + row * step - const up: Vec3 = [0, to - from, 0] - const [origin, along]: [Vec3, Vec3] = - side.rowStep < 0 - ? [[x, from, z], [step, 0, 0]] - : side.rowStep > 0 - ? [[x + step, from, z + step], [-step, 0, 0]] - : side.columnStep < 0 - ? [[x, from, z + step], [0, 0, -step]] - : [[x + step, from, z], [0, 0, step]] - batch.add(origin, along, up, underWater(color, from, water), underWater(color, to, water)) -} - -function addTop(batch: QuadBatch, field: ColumnField, column: number, row: number, y: number, color: Vec3, water: number | null): void { - const step = field.blocksPerColumn - const shown = underWater(color, y, water) - batch.add([field.originX + column * step, y, field.originZ + row * step], [step, 0, 0], [0, 0, step], shown, shown) -} - -function addBottom(batch: QuadBatch, field: ColumnField, column: number, row: number, y: number, color: Vec3, water: number | null): void { - const step = field.blocksPerColumn - const shown = underWater(color, y, water) - batch.add([field.originX + column * step, y, field.originZ + row * step], [0, 0, step], [step, 0, 0], shown, shown) -} - function colorOf(surface: SurfaceRuns, block: number, face: 'top' | 'side' | 'below', light: number): Vec3 { const look = surface.looks[block] return shaded(look === null || look === undefined ? surface.colors[block] : look[face].color, light) } +// Seen from afar, the plants on a block hide this much of its top where they stand. +const PLANT_COVER = 0.5 +const WHOLE_SHARE = 255 + +// Near ground draws its grass and flowers, which colour it seen from afar; the run's top takes their colour as they would. +function withPlants(surface: SurfaceRuns, run: number, color: Vec3): Vec3 { + const plant = surface.runs.covers[run] + if (plant === NO_BLOCK) { + return color + } + const share = (surface.runs.coverShares[run] / WHOLE_SHARE) * PLANT_COVER + const plantColor = shaded(surface.colors[plant], FACE_LIGHT.up) + return [color[0] + (plantColor[0] - color[0]) * share, color[1] + (plantColor[1] - color[1]) * share, color[2] + (plantColor[2] - color[2]) * share] +} + function underWater(color: Vec3, y: number, water: number | null): Vec3 { return water === null ? color : sunk(color, tintAt(water - y)) } + +/** Faces that lie along one line of columns in one plane, over the same heights in the same colours, and where along it they stand. */ +interface FaceLine { + direction: Direction + /** The row of the line, or its column for faces looking west or east. */ + lane: number + from: number + to: number + bottomColor: Vec3 + topColor: Vec3 + /** The columns along the line, or rows for faces looking west or east, in the order they were added. */ + places: number[] +} + +/** + * Column faces gathered first and drawn as few quads as they allow: faces of columns next to each other along a row, or + * along a column for faces looking west or east, that lie at the same heights in the same colours become one. + */ +class MergedFaces { + private readonly lines = new Map() + + constructor(private readonly field: ColumnField) {} + + /** A face of the column; tops and undersides lie at {@code from}, sides reach from {@code from} to {@code to}. */ + add(direction: Direction, row: number, column: number, from: number, to: number, bottomColor: Vec3, topColor: Vec3): void { + const alongColumns = direction !== 'west' && direction !== 'east' + const lane = alongColumns ? row : column + const key = `${direction}|${lane}|${from}|${to}|${bottomColor.join(',')}|${topColor.join(',')}` + let line = this.lines.get(key) + if (line === undefined) { + line = { direction, lane, from, to, bottomColor, topColor, places: [] } + this.lines.set(key, line) + } + line.places.push(alongColumns ? column : row) + } + + batch(): QuadBatch { + const batch = new QuadBatch(true) + for (const line of this.lines.values()) { + let start = 0 + for (let at = 1; at <= line.places.length; at++) { + if (at === line.places.length || line.places[at] !== line.places[at - 1] + 1) { + this.addQuad(batch, line, line.places[start], at - start) + start = at + } + } + } + return batch + } + + private addQuad(batch: QuadBatch, line: FaceLine, first: number, count: number): void { + const step = this.field.blocksPerColumn + const { originX, originZ } = this.field + const length = count * step + const lane = line.lane * step + const along = first * step + const height: Vec3 = [0, line.to - line.from, 0] + switch (line.direction) { + case 'up': + batch.add([originX + along, line.from, originZ + lane], [length, 0, 0], [0, 0, step], line.bottomColor, line.topColor) + return + case 'down': + batch.add([originX + along, line.from, originZ + lane], [0, 0, step], [length, 0, 0], line.bottomColor, line.topColor) + return + case 'north': + batch.add([originX + along, line.from, originZ + lane], [length, 0, 0], height, line.bottomColor, line.topColor) + return + case 'south': + batch.add([originX + along + length, line.from, originZ + lane + step], [-length, 0, 0], height, line.bottomColor, line.topColor) + return + case 'west': + batch.add([originX + lane, line.from, originZ + along + length], [0, 0, -length], height, line.bottomColor, line.topColor) + return + case 'east': + batch.add([originX + lane + step, line.from, originZ + along], [0, 0, length], height, line.bottomColor, line.topColor) + } + } +} diff --git a/studio/src/renderer/src/scene/terrainCover.test.ts b/studio/src/renderer/src/scene/terrainCover.test.ts index 2b5d65b20..d29e5a665 100644 --- a/studio/src/renderer/src/scene/terrainCover.test.ts +++ b/studio/src/renderer/src/scene/terrainCover.test.ts @@ -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 64 tiles each', () => { + it('never asks for more than a backdrop, a preview and detail of 256 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 * 256) } }) diff --git a/studio/src/renderer/src/scene/terrainCover.ts b/studio/src/renderer/src/scene/terrainCover.ts index 83cbecbe7..c15326469 100644 --- a/studio/src/renderer/src/scene/terrainCover.ts +++ b/studio/src/renderer/src/scene/terrainCover.ts @@ -29,13 +29,13 @@ 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. 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 +// Tuned for a workstation GPU, which draws tens of millions of triangles a frame. A column is drawn at most a quarter of +// a pixel wide, so ground drawn block by block goes on until its blocks are far too small to tell apart from the runs +// coarser tiles draw, and the change between them cannot be seen. +const MOST_COLUMN_PIXELS = 0.25 +// Columns finer than a pixel still decide the colour each pixel takes, so the view holds many to a pixel. +const MOST_COLUMNS_PER_PIXEL = 16 +const MOST_TILES_IN_SIGHT = 256 // 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 diff --git a/studio/src/renderer/src/scene/terrainMesh.ts b/studio/src/renderer/src/scene/terrainMesh.ts index ee9c8e404..f3f95aa70 100644 --- a/studio/src/renderer/src/scene/terrainMesh.ts +++ b/studio/src/renderer/src/scene/terrainMesh.ts @@ -6,8 +6,10 @@ import { coverGeometry } from './coverFaces' import type { CoverLook } from './coverLooks' import { QuadBatch } from './quadBatch' import { addRaisedFaces } from './raisedFaces' +import type { CompactPlacement } from './compactGeometry' import { runFaces, type SurfaceRuns } from './runFaces' import { voxelGeometries, type SurfaceVoxels } from './voxelMesh' + import type { TerrainPictures } from './terrainAtlas' import type { ColumnArea } from './terrainTiles' import { WATER_SURFACE_COLOR, WATER_SURFACE_OPACITY } from './waterTint' @@ -70,100 +72,86 @@ export interface TerrainMesh { * whole blocks; what is seen through, such as leaves, is cut out along its pictures. */ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: readonly ColumnArea[] = []): TerrainMesh { + const geometry = buildTerrainGeometry(surface, base, holes) + return meshOfGeometry(geometry, geometry.field.pictures) +} + +/** How a part of a tile's geometry is drawn: in its colours alone, textured, cut out along its pictures, or as water. */ +export type GeometryKind = 'coloured' | 'textured' | 'cutOut' | 'water' + +/** A tile's faces, ready to draw in materials of their kinds, in the order they are drawn; water comes last. */ +export interface TerrainGeometry { + field: ColumnField + /** Each part's faces; where a part has a placement, its corners are in the steps of a compact geometry. */ + parts: { kind: GeometryKind; geometry: BufferGeometry; placement?: CompactPlacement }[] +} + +/** The faces {@link buildTerrainMesh} draws, without materials, so they can be built away from where they are drawn. */ +export function buildTerrainGeometry(surface: TerrainSurface, base: number, holes: readonly ColumnArea[] = []): TerrainGeometry { const field = new ColumnField(surface, holes) - const group = new Group() if (!field.hasAnyGround()) { - return { object: group, field, dispose: () => {} } + return { field, parts: [] } } const voxels = field.pictures === null ? null : (surface.voxels?.() ?? null) if (voxels !== null && field.pictures !== null) { - return voxelMesh(field, voxels, field.pictures) + const { opaque, cutOut, water } = voxelGeometries(field, voxels, field.pictures.plain) + return { field, parts: present([part('textured', opaque), part('cutOut', cutOut), part('water', water)]) } } const runs = surface.runs?.() ?? null if (runs !== null) { - return runMesh(field, runs, base) + return { field, parts: [{ kind: 'coloured', geometry: runFaces(field, runs, base).geometry() }, { kind: 'water', geometry: waterFaces(field).geometry() }] } } const groundBatch = groundFaces(field, base) const seeThroughBatch = new QuadBatch(true, field.pictures?.plain ?? null) addRaisedFaces(field, groundBatch, seeThroughBatch) - const ground = groundBatch.geometry() - const water = waterFaces(field).geometry() - const groundMaterial = new MeshBasicMaterial({ vertexColors: true, side: FrontSide, map: field.pictures?.texture ?? null }) - const columnWaterMaterial = waterMaterial() - const cutOut = field.pictures === null ? [] : [cutOutMesh(coverGeometry(field), field.pictures), cutOutMesh(seeThroughGeometry(seeThroughBatch), field.pictures)] - const shownCutOut = cutOut.filter((mesh) => mesh !== null) - // The water is drawn last, over what stands under it. - group.add(new Mesh(ground, groundMaterial), ...shownCutOut.map((mesh) => mesh.mesh), new Mesh(water, columnWaterMaterial)) + const cutOut = field.pictures === null ? [] : present([part('cutOut', coverGeometry(field)), part('cutOut', seeThroughBatch.count === 0 ? null : seeThroughBatch.geometry())]) + return { + field, + parts: [{ kind: field.pictures === null ? 'coloured' : 'textured', geometry: groundBatch.geometry() }, ...cutOut, { kind: 'water', geometry: waterFaces(field).geometry() }] + } +} + +function part(kind: GeometryKind, geometry: BufferGeometry | null): { kind: GeometryKind; geometry: BufferGeometry } | null { + return geometry === null ? null : { kind, geometry } +} + +function present(parts: (T | null)[]): T[] { + return parts.filter((found): found is T => found !== null) +} + +/** The geometry drawn in its materials; textured and cut-out parts need {@code pictures}. */ +export function meshOfGeometry({ field, parts }: TerrainGeometry, pictures: TerrainPictures | null): TerrainMesh { + const group = new Group() + const materials = parts.map(({ kind }) => materialOf(kind, pictures)) + parts.forEach(({ geometry, placement }, index) => { + const mesh = new Mesh(geometry, materials[index]) + if (placement !== undefined) { + mesh.position.set(...placement.origin) + mesh.scale.set(...placement.scale) + } + group.add(mesh) + }) return { object: group, field, dispose: () => { - ground.dispose() - water.dispose() - groundMaterial.dispose() - columnWaterMaterial.dispose() - shownCutOut.forEach((mesh) => mesh.dispose()) + parts.forEach(({ geometry }) => geometry.dispose()) + materials.forEach((material) => material.dispose()) } } } -function voxelMesh(field: ColumnField, voxels: SurfaceVoxels, pictures: TerrainPictures): TerrainMesh { - const { opaque, cutOut, water } = voxelGeometries(field, voxels, pictures.plain) - const parts: { mesh: Mesh; dispose(): void }[] = [] - if (opaque !== null) { - parts.push(meshOf(opaque, new MeshBasicMaterial({ vertexColors: true, side: FrontSide, map: pictures.texture }))) - } - const cutOutPart = cutOutMesh(cutOut, pictures) - if (cutOutPart !== null) { - parts.push(cutOutPart) - } - // The water is drawn last, over what stands under it. - if (water !== null) { - parts.push(meshOf(water, waterMaterial())) - } - const group = new Group() - group.add(...parts.map((part) => part.mesh)) - return { object: group, field, dispose: () => parts.forEach((part) => part.dispose()) } -} - -function runMesh(field: ColumnField, runs: SurfaceRuns, base: number): TerrainMesh { - const batch = runFaces(field, runs, base) - const parts = [meshOf(batch.geometry(), new MeshBasicMaterial({ vertexColors: true, side: FrontSide })), meshOf(waterFaces(field).geometry(), waterMaterial())] - const group = new Group() - // The water is drawn last, over what stands under it. - group.add(...parts.map((part) => part.mesh)) - return { object: group, field, dispose: () => parts.forEach((part) => part.dispose()) } -} - -function meshOf(geometry: BufferGeometry, material: MeshBasicMaterial): { mesh: Mesh; dispose(): void } { - return { - mesh: new Mesh(geometry, material), - dispose: () => { - geometry.dispose() - material.dispose() - } - } -} - -function waterMaterial(): MeshBasicMaterial { - return new MeshBasicMaterial({ color: WATER_SURFACE_COLOR, transparent: true, opacity: WATER_SURFACE_OPACITY, depthWrite: false, side: DoubleSide }) -} - -function seeThroughGeometry(batch: QuadBatch): BufferGeometry | null { - return batch.count === 0 ? null : batch.geometry() -} - -// Drawn where the pictures are not open, so the grass between its blades and the leaves between their twigs show what lies behind. -function cutOutMesh(geometry: BufferGeometry | null, pictures: TerrainPictures): { mesh: Mesh; dispose(): void } | null { - if (geometry === null) { - return null - } - const material = new MeshBasicMaterial({ vertexColors: true, map: pictures.texture, alphaMap: pictures.cutouts, alphaTest: CUTOUT_ALPHA, side: FrontSide }) - return { - mesh: new Mesh(geometry, material), - dispose: () => { - geometry.dispose() - material.dispose() - } +// Cut-out parts are drawn where their pictures are not open, so the grass between its blades and the leaves between their +// twigs show what lies behind. +function materialOf(kind: GeometryKind, pictures: TerrainPictures | null): MeshBasicMaterial { + switch (kind) { + case 'coloured': + return new MeshBasicMaterial({ vertexColors: true, side: FrontSide }) + case 'textured': + return new MeshBasicMaterial({ vertexColors: true, side: FrontSide, map: pictures?.texture ?? null }) + case 'cutOut': + return new MeshBasicMaterial({ vertexColors: true, map: pictures?.texture ?? null, alphaMap: pictures?.cutouts ?? null, alphaTest: CUTOUT_ALPHA, side: FrontSide }) + case 'water': + return new MeshBasicMaterial({ color: WATER_SURFACE_COLOR, transparent: true, opacity: WATER_SURFACE_OPACITY, depthWrite: false, side: DoubleSide }) } } diff --git a/studio/src/renderer/src/scene/terrainMeshWorker.ts b/studio/src/renderer/src/scene/terrainMeshWorker.ts new file mode 100644 index 000000000..7eeac987a --- /dev/null +++ b/studio/src/renderer/src/scene/terrainMeshWorker.ts @@ -0,0 +1,56 @@ +/// +import type { MapTile } from '../bridge/types' +import { compacted, type CompactArrays } from './compactGeometry' +import type { FieldShape } from './columnField' +import { MapTerrain, type MapTerrainColoring } from './mapTerrain' +import type { TerrainPictures, UvCell } from './terrainAtlas' +import { buildTerrainGeometry, type GeometryKind } from './terrainMesh' +import type { ColumnArea, TerrainTile } from './terrainTiles' + +/** One map tile to build the faces of, as the studio's 3D world draws it. */ +export interface MeshRequest { + id: number + tile: MapTile + place: TerrainTile + coloring: MapTerrainColoring + fluidHeight: number + /** The atlas's plain cell, or null to draw the tile in colour alone. */ + plain: UvCell | null + base: number + holes: ColumnArea[] +} + +/** A built geometry's arrays, packed small, as a worker sends them back. */ +export interface GeometryArrays { + kind: GeometryKind + arrays: CompactArrays +} + +export interface MeshResult { + id: number + field: FieldShape + parts: GeometryArrays[] +} + +// The faces are built from the atlas's cell layout alone; the textures themselves stay where they are drawn. +function picturesOf(plain: UvCell | null): TerrainPictures | undefined { + return plain === null ? undefined : ({ plain, texture: null, cutouts: null } as unknown as TerrainPictures) +} + +self.onmessage = (event: MessageEvent) => { + const { id, tile, place, coloring, fluidHeight, plain, base, holes } = event.data + const surface = new MapTerrain(tile, place, coloring, fluidHeight, picturesOf(plain)) + const { field, parts } = buildTerrainGeometry(surface, base, holes) + const packed: GeometryArrays[] = parts.map(({ kind, geometry }) => ({ kind, arrays: compacted(geometry, field.blocksPerColumn) })) + const shape = field.shape() + const buffers = new Set([shape.groundTop.buffer as ArrayBuffer, shape.waterTop.buffer as ArrayBuffer]) + for (const { arrays } of packed) { + for (const array of [arrays.position, arrays.color, arrays.uv, arrays.index]) { + if (array !== null) { + buffers.add(array.buffer as ArrayBuffer) + } + } + } + const result: MeshResult = { id, field: shape, parts: packed } + self.postMessage(result, [...buffers]) +} diff --git a/studio/src/renderer/src/scene/terrainMeshWorkers.ts b/studio/src/renderer/src/scene/terrainMeshWorkers.ts new file mode 100644 index 000000000..1510f8041 --- /dev/null +++ b/studio/src/renderer/src/scene/terrainMeshWorkers.ts @@ -0,0 +1,74 @@ +import { ColumnField } from './columnField' +import { geometryOfCompact } from './compactGeometry' +import type { TerrainGeometry } from './terrainMesh' +import type { MeshRequest, MeshResult } from './terrainMeshWorker' + +const MOST_WORKERS = 6 + +/** + * Map tiles' faces built on worker threads, so a tile arriving never holds up a frame: the main thread only wraps the + * arrays a worker sends back, without copying them. Tiles are built in the order they are asked for. + */ +export class TerrainMeshWorkers { + private readonly workers: Worker[] = [] + private readonly idle: Worker[] = [] + private readonly queue: { request: MeshRequest; resolve(geometry: TerrainGeometry): void; reject(error: Error): void }[] = [] + private readonly running = new Map() + private nextId = 0 + + constructor() { + const count = Math.max(1, Math.min(MOST_WORKERS, (navigator.hardwareConcurrency || 2) - 1)) + for (let index = 0; index < count; index++) { + const worker = new Worker(new URL('./terrainMeshWorker.ts', import.meta.url), { type: 'module' }) + worker.onmessage = (event: MessageEvent) => this.finished(worker, event.data) + worker.onerror = (event) => this.failed(worker, new Error(event.message)) + this.workers.push(worker) + this.idle.push(worker) + } + } + + build(request: Omit): Promise { + return new Promise((resolve, reject) => { + this.queue.push({ request: { ...request, id: this.nextId++ }, resolve, reject }) + this.startNext() + }) + } + + dispose(): void { + this.workers.forEach((worker) => worker.terminate()) + this.queue.forEach((job) => job.reject(new Error('The terrain is no longer drawn'))) + this.queue.length = 0 + } + + private startNext(): void { + while (this.idle.length > 0 && this.queue.length > 0) { + const worker = this.idle.pop()! + const job = this.queue.shift()! + this.running.set(worker, job) + worker.postMessage(job.request) + } + } + + private finished(worker: Worker, result: MeshResult): void { + const job = this.running.get(worker) + this.running.delete(worker) + this.idle.push(worker) + job?.resolve(geometryOf(result)) + this.startNext() + } + + private failed(worker: Worker, error: Error): void { + const job = this.running.get(worker) + this.running.delete(worker) + this.idle.push(worker) + job?.reject(error) + this.startNext() + } +} + +function geometryOf(result: MeshResult): TerrainGeometry { + return { + field: ColumnField.ofShape(result.field), + parts: result.parts.map(({ kind, arrays }) => ({ kind, geometry: geometryOfCompact(arrays), placement: arrays.placement })) + } +} diff --git a/studio/src/renderer/src/scene/terrainStream.test.ts b/studio/src/renderer/src/scene/terrainStream.test.ts index 5d665d590..534d5812f 100644 --- a/studio/src/renderer/src/scene/terrainStream.test.ts +++ b/studio/src/renderer/src/scene/terrainStream.test.ts @@ -2,6 +2,7 @@ import { PerspectiveCamera, Ray, Vector3, type Mesh } from 'three' import { describe, expect, it, vi } from 'vitest' import type { TileSource } from '../map/TileStore' import type { CameraLink } from '../studio/SceneViewport' +import { buildTerrainMesh } from './terrainMesh' import { focusAround, TerrainStream, type TerrainStyle } from './terrainStream' interface FlatTile { @@ -245,6 +246,27 @@ describe('terrain stream', () => { 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) + // Three views of up to a few hundred tiles each, every one built as a mesh. + }, 30_000) + + it('draws tiles built away from the frames once they are built', async () => { + const { stream } = setUp() + let builds = 0 + const builtLater: TerrainStyle = { + ...flatStyle, + buildMesh: async (tile, place, base, holes) => { + builds++ + await Promise.resolve() + return buildTerrainMesh(flatStyle.surfaceOf(tile, place), base, holes) + } + } + stream.restyle(builtLater) + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + + const ray = new Ray(new Vector3(10, 300, 10), new Vector3(0, -1, 0)) + expect(builds).toBeGreaterThan(0) + expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(71, 3) }) it('stops drawing when it is let go', async () => { diff --git a/studio/src/renderer/src/scene/terrainStream.ts b/studio/src/renderer/src/scene/terrainStream.ts index 1d69266a1..094797d7f 100644 --- a/studio/src/renderer/src/scene/terrainStream.ts +++ b/studio/src/renderer/src/scene/terrainStream.ts @@ -1,4 +1,4 @@ -import { Box3, Group, Vector3 } from 'three' +import { Box3, Group, Vector3, type BufferGeometry } from 'three' import { TileStore, type TileSource } from '../map/TileStore' import type { TileAddress } from '../map/viewport' import type { CameraLink, ViewportContent } from '../studio/SceneViewport' @@ -8,13 +8,18 @@ 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, ancestorAt, childrenOf, isInside, tileAt, tileContaining, tileKey, type TerrainTile } from './terrainTiles' +import { addressOf, ancestorAt, childrenOf, isInside, tileAt, tileContaining, tileKey, type ColumnArea, 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 { surfaceOf(tile: Tile, place: TerrainTile): TerrainSurface floorY: number topY: number + /** + * Builds a tile's mesh away from the frames, as {@link buildTerrainMesh} does from {@link surfaceOf}; where not given, + * tiles are built on the spot. + */ + buildMesh?(tile: Tile, place: TerrainTile, base: number, holes: ColumnArea[]): Promise } export interface TerrainStreamOptions { @@ -41,6 +46,14 @@ interface StoredIndex { holding: Set } +/** A tile's mesh on its way from a worker, for the data and holes it was asked for; null until it is built. */ +interface BuildingMesh { + tile: TerrainTile + data: Tile + signature: string + mesh: TerrainMesh | null +} + interface DrawnMesh { tile: TerrainTile data: Tile @@ -49,6 +62,24 @@ interface DrawnMesh { } const MESH_BUILD_BUDGET_MILLISECONDS = 12 +// What a workstation GPU takes in a few milliseconds. +const UPLOAD_BYTES_PER_FRAME = 16 * 1024 * 1024 + +/** The bytes a mesh's geometry hands the GPU when it is first drawn. */ +function bytesOf(mesh: TerrainMesh): number { + let bytes = 0 + mesh.object.traverse((object) => { + const geometry = (object as { geometry?: BufferGeometry }).geometry + if (geometry === undefined) { + return + } + for (const attribute of Object.values(geometry.attributes)) { + bytes += (attribute.array as ArrayLike & { byteLength: number }).byteLength + } + bytes += (geometry.getIndex()?.array as { byteLength: number } | undefined)?.byteLength ?? 0 + }) + return bytes +} const ABOVE_TOP_BLOCKS = 1 const FOCUS_HALF_SIDE_BLOCKS = 256 @@ -73,7 +104,10 @@ export class TerrainStream { private readonly drawn = new Map>() private readonly sightListeners = new Set<() => void>() private standIns = new Map() + private readonly building = new Map>() private storedIndex: StoredIndex | null = null + private uploadBytesLeft = UPLOAD_BYTES_PER_FRAME + private nextFrame: number | null = null private layer: Layer | null = null private style: TerrainStyle | null = null private styleVersion = 0 @@ -141,8 +175,13 @@ export class TerrainStream { if (this.continuation !== null) { clearTimeout(this.continuation) } + if (this.nextFrame !== null) { + cancelAnimationFrame(this.nextFrame) + } this.drawn.forEach((drawn) => drawn.mesh.dispose()) this.drawn.clear() + this.building.forEach((building) => building.mesh?.dispose()) + this.building.clear() this.group.clear() this.store.clear() } @@ -264,7 +303,17 @@ export class TerrainStream { behind = true continue } - this.show(key, draw, data, style) + if (style.buildMesh === undefined) { + this.show(key, draw, this.builtNow(draw, data, style), data) + continue + } + this.showOnceBuilt(key, draw, data, cover, style.buildMesh, style.floorY) + } + for (const [key, building] of [...this.building]) { + if (!stillDrawn.has(key)) { + building.mesh?.dispose() + this.building.delete(key) + } } this.camera?.redraw() if (this.groundRangeGrew) { @@ -276,7 +325,7 @@ export class TerrainStream { return } for (const [key, drawn] of [...this.drawn]) { - if (!stillDrawn.has(key)) { + if (!stillDrawn.has(key) && !this.isReplacementBuilding(drawn.tile)) { this.hide(key, drawn) } } @@ -291,12 +340,66 @@ export class TerrainStream { return `${this.styleVersion}/${holes.join(';')}` } - private show(key: string, draw: DrawnTile, data: Tile, style: TerrainStyle): void { + // Ground leaving the plan stays until what takes its place, a coarser tile over it or finer ones in it, is built. + private isReplacementBuilding(tile: TerrainTile): boolean { + for (const building of this.building.values()) { + if (building.mesh === null && (isInside(tile, building.tile) || isInside(building.tile, tile))) { + return true + } + } + return false + } + + private builtNow(draw: DrawnTile, data: Tile, style: TerrainStyle): TerrainMesh { + return buildTerrainMesh(style.surfaceOf(data, draw.tile), style.floorY, draw.holes) + } + + // A tile is built away from the frames, and shown once built. One with holes is shown only once the finer tiles that + // fill them are, so what it drew before stays meanwhile and the ground never shows a gap. + private showOnceBuilt(key: string, draw: DrawnTile, data: Tile, cover: Cover, buildMesh: NonNullable['buildMesh']>, base: number): void { + const signature = this.signatureOf(draw) + const building = this.building.get(key) + if (building !== undefined && building.data === data && building.signature === signature) { + const finer = cover.draws.filter((other) => isInside(other.tile, draw.tile)).map((other) => tileKey(other.tile)) + if (building.mesh === null || !finer.every((finerKey) => this.drawn.has(finerKey))) { + return + } + const bytes = bytesOf(building.mesh) + if (bytes > this.uploadBytesLeft && this.uploadBytesLeft < UPLOAD_BYTES_PER_FRAME) { + this.continueNextFrame() + return + } + this.uploadBytesLeft -= bytes + this.building.delete(key) + this.show(key, draw, building.mesh, data) + return + } + building?.mesh?.dispose() + const started: BuildingMesh = { tile: draw.tile, data, signature, mesh: null } + this.building.set(key, started) + buildMesh(data, draw.tile, base, draw.holes).then( + (mesh) => { + if (this.disposed || this.building.get(key) !== started) { + mesh.dispose() + return + } + started.mesh = mesh + this.continueLater() + }, + (error: Error) => { + if (!this.disposed && this.building.get(key) === started) { + this.building.delete(key) + this.options.onError(error.message) + } + } + ) + } + + private show(key: string, draw: DrawnTile, mesh: TerrainMesh, data: Tile): void { const previous = this.drawn.get(key) if (previous !== undefined) { this.hide(key, previous) } - const mesh = buildTerrainMesh(style.surfaceOf(data, draw.tile), style.floorY, draw.holes) this.group.add(mesh.object) this.drawn.set(key, { tile: draw.tile, data, signature: this.signatureOf(draw), mesh }) this.growGroundRangeOver(mesh.field) @@ -318,6 +421,18 @@ export class TerrainStream { this.drawn.delete(key) } + // A frame hands the GPU only so many bytes of new meshes; the rest wait for the next, so a burst of tiles never stalls one. + private continueNextFrame(): void { + if (this.nextFrame !== null) { + return + } + this.nextFrame = requestAnimationFrame(() => { + this.nextFrame = null + this.uploadBytesLeft = UPLOAD_BYTES_PER_FRAME + this.replan() + }) + } + private continueLater(): void { if (this.continuation !== null) { return diff --git a/studio/src/renderer/src/studio/WorldStudio3D.tsx b/studio/src/renderer/src/studio/WorldStudio3D.tsx index d1330989f..3a885a3b2 100644 --- a/studio/src/renderer/src/studio/WorldStudio3D.tsx +++ b/studio/src/renderer/src/studio/WorldStudio3D.tsx @@ -7,6 +7,8 @@ import { mapTileSource, type TileLayer } from '../map/mapTileSource' import type { GroundInView } from '../scene/groundInView' import { blockArt } from '../scene/blockArt' import { MapTerrain, type MapTerrainColoring } from '../scene/mapTerrain' +import { meshOfGeometry } from '../scene/terrainMesh' +import { TerrainMeshWorkers } from '../scene/terrainMeshWorkers' import { focusAround, type TerrainStyle } from '../scene/terrainStream' import { TILE_COLUMNS } from '../scene/terrainTiles' import { Legend } from './Legend' @@ -62,13 +64,19 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS () => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, blocks: showsBlocks ? 'generated' : null, shape: showsBlocks, revision: packRevision }), [packRevision, showsBlocks] ) + const meshWorkers = useMemo(() => new TerrainMeshWorkers(), []) + useEffect(() => () => meshWorkers.dispose(), [meshWorkers]) const style = useMemo>( () => ({ surfaceOf: (tile, place) => new MapTerrain(tile, place, coloring, world.fluidHeight, art.atlas ?? undefined), floorY: world.minY, - topY: world.minY + world.height + topY: world.minY + world.height, + buildMesh: (tile, place, base, holes) => + meshWorkers + .build({ tile, place, coloring, fluidHeight: world.fluidHeight, plain: art.atlas?.plain ?? null, base, holes }) + .then((geometry) => meshOfGeometry(geometry, art.atlas)) }), - [coloring, world.fluidHeight, world.minY, world.height, art] + [coloring, world.fluidHeight, world.minY, world.height, art, meshWorkers] ) const { content, pending, stream } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell, withoutBlocks) const sampling = useLongPending(pending)