From 3fde8c420f3b72f7a44eb70a3a80545692847a99 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 01:58:23 +0100 Subject: [PATCH] Add the saved world view A world the server saved, read from its region files, in 3D: the 1,024 blocks square around the region nearest its origin, coloured by biome, block (each block's top texture, tinted) or height, with lakes and rivers at their own levels. The saved worlds are listed by namespace, the studio's own world first, and can be read again. The terrain mesh now takes any surface with ground, water and colour per vertex, holes where nothing is known; the 3D world is one such surface. Framing uses the surface's own bounds, so vertices left out of the mesh do not move the camera. --- src/renderer/src/bridge/BridgeClient.ts | 31 +- src/renderer/src/bridge/savedTileDecoding.ts | 40 +++ src/renderer/src/bridge/types.ts | 37 +++ src/renderer/src/scene/blockColors.ts | 74 +++++ src/renderer/src/scene/mapTerrain.ts | 67 ++++ src/renderer/src/scene/savedTerrain.ts | 78 +++++ src/renderer/src/scene/terrainMesh.test.ts | 50 +++ src/renderer/src/scene/terrainMesh.ts | 317 +++++++++++-------- src/renderer/src/scene/textureAtlas.ts | 2 +- src/renderer/src/studio/MapStudio.tsx | 19 +- src/renderer/src/studio/SavedWorldStudio.tsx | 223 +++++++++++++ src/renderer/src/studio/ViewList.tsx | 3 +- src/renderer/src/studio/WorldStudio3D.tsx | 13 +- 13 files changed, 810 insertions(+), 144 deletions(-) create mode 100644 src/renderer/src/bridge/savedTileDecoding.ts create mode 100644 src/renderer/src/scene/blockColors.ts create mode 100644 src/renderer/src/scene/mapTerrain.ts create mode 100644 src/renderer/src/scene/savedTerrain.ts create mode 100644 src/renderer/src/scene/terrainMesh.test.ts create mode 100644 src/renderer/src/studio/SavedWorldStudio.tsx diff --git a/src/renderer/src/bridge/BridgeClient.ts b/src/renderer/src/bridge/BridgeClient.ts index 15a27ab73..2658ef309 100644 --- a/src/renderer/src/bridge/BridgeClient.ts +++ b/src/renderer/src/bridge/BridgeClient.ts @@ -1,7 +1,20 @@ import type { BridgeConnection } from '../../../shared/bridge' import { decodeScene, type BlockScene } from '../scene/sceneDecoding' +import { decodeSavedTile } from './savedTileDecoding' import { decodeTile } from './tileDecoding' -import type { MapHover, MapLabel, MapTile, Marker, PickInspection, SceneEntry, SceneViewInfo, WorldInfo } from './types' +import type { + MapHover, + MapLabel, + MapTile, + Marker, + PickInspection, + SavedStart, + SavedTile, + SavedWorldInfo, + SceneEntry, + SceneViewInfo, + WorldInfo +} from './types' export const STATUS_NOT_FOUND = 404 export const STATUS_UNAVAILABLE = 503 @@ -118,6 +131,22 @@ export class BridgeClient { return decodeScene(await response.arrayBuffer()) } + /** The worlds saved on the server's disk. */ + savedWorlds(): Promise { + return this.json('saved-worlds') + } + + /** Where a saved world's view opens; reads the region nearest the origin whole, so it can take a second or two. */ + savedStart(worldId: string, signal?: AbortSignal): Promise { + return this.json(`saved-start?${new URLSearchParams({ world: worldId })}`, { signal }) + } + + async savedTile(worldId: string, tileX: number, tileZ: number, blocksPerPixel: number, size: number, signal: AbortSignal): Promise { + const query = new URLSearchParams({ world: worldId, x: String(tileX), z: String(tileZ), scale: String(blocksPerPixel), size: String(size) }) + const response = await this.fetch(`saved-tile?${query}`, { signal }) + return decodeSavedTile(await response.arrayBuffer()) + } + /** A file of the Minecraft client's assets, such as {@code minecraft/blockstates/stone.json}; null when there is none. */ async asset(path: string): Promise { try { diff --git a/src/renderer/src/bridge/savedTileDecoding.ts b/src/renderer/src/bridge/savedTileDecoding.ts new file mode 100644 index 000000000..e287d85dc --- /dev/null +++ b/src/renderer/src/bridge/savedTileDecoding.ts @@ -0,0 +1,40 @@ +import type { MapLabel, SavedTile } from './types' + +const ALIGNMENT_BYTES = 4 + +interface SavedTileHeader { + size: number + blocksPerPixel: number + blocks: string[] + biomes: MapLabel[] + noGround: number + noWater: number +} + +function aligned(bytes: number): number { + return Math.ceil(bytes / ALIGNMENT_BYTES) * ALIGNMENT_BYTES +} + +/** + * Reads a saved tile as the bridge writes it (SavedTileEncoding): a u32 header length, the JSON header, then the ground, + * water, block and biome grids, each starting on a multiple of 4 bytes. The grids are views into the buffer. + */ +export function decodeSavedTile(buffer: ArrayBuffer): SavedTile { + const headerLength = new DataView(buffer).getUint32(0, true) + const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as SavedTileHeader + const pixels = header.size * header.size + const gridBytes = aligned(pixels * Int16Array.BYTES_PER_ELEMENT) + const gridAt = (index: number): Int16Array => new Int16Array(buffer, aligned(4 + headerLength) + index * gridBytes, pixels) + return { + size: header.size, + blocksPerPixel: header.blocksPerPixel, + groundY: gridAt(0), + waterSurfaceY: gridAt(1), + blocks: gridAt(2), + biomes: gridAt(3), + blockNames: header.blocks, + biomeLabels: header.biomes, + noGround: header.noGround, + noWater: header.noWater + } +} diff --git a/src/renderer/src/bridge/types.ts b/src/renderer/src/bridge/types.ts index ec4592f5c..a31b79356 100644 --- a/src/renderer/src/bridge/types.ts +++ b/src/renderer/src/bridge/types.ts @@ -33,6 +33,43 @@ export interface SceneEntry { variants: number } +/** A world saved on the server's disk, a dimension folder of region files. */ +export interface SavedWorldInfo { + /** Its folder below the server's level folder. */ + id: string + name: string + /** Who added the dimension, such as minecraft or iris. */ + namespace: string +} + +/** Where a saved world's view opens: the middle of the region nearest the origin, and how its ground lies there. */ +export interface SavedStart { + centerX: number + centerZ: number + minY: number + lowestGround: number + highestGround: number + /** The water surface most water lies at, or null where the region holds none. */ + seaLevel: number | null +} + +/** A square of a saved world, one column per pixel, row by row from the north west. */ +export interface SavedTile { + size: number + blocksPerPixel: number + /** The top block of the ground under any water; {@link noGround} where nothing finished is saved. */ + groundY: Int16Array + /** The top water block over the ground; {@link noWater} where it is dry. */ + waterSurfaceY: Int16Array + /** Indices into {@link blockNames} and {@link biomes}. */ + blocks: Int16Array + biomes: Int16Array + blockNames: string[] + biomeLabels: MapLabel[] + noGround: number + noWater: number +} + export interface WorldInfo { world: string dimension: string diff --git a/src/renderer/src/scene/blockColors.ts b/src/renderer/src/scene/blockColors.ts new file mode 100644 index 000000000..9154879ce --- /dev/null +++ b/src/renderer/src/scene/blockColors.ts @@ -0,0 +1,74 @@ +import { blockTint } from './blockTints' +import { parseState, type BlockModels } from './blockModels' +import { texturePath, type ImageSource } from './textureAtlas' + +const UNKNOWN_BLOCK_COLOR = 0x7f7f7f +const OPAQUE_ENOUGH_ALPHA = 128 + +/** Each block's colour seen from above: its top face's texture averaged and tinted as the client tints it, read once. */ +export class BlockColors { + private readonly known = new Map>() + + constructor( + private readonly models: BlockModels, + private readonly images: ImageSource + ) {} + + colorOf(block: string): Promise { + let color = this.known.get(block) + if (color === undefined) { + color = this.read(block).catch(() => UNKNOWN_BLOCK_COLOR) + this.known.set(block, color) + } + return color + } + + /** Every block's colour, by name. */ + async colorsOf(blocks: Iterable): Promise> { + const names = [...new Set(blocks)] + const colors = await Promise.all(names.map((name) => this.colorOf(name))) + return new Map(names.map((name, index) => [name, colors[index]])) + } + + private async read(block: string): Promise { + const model = await this.models.model(block) + const top = model?.quads.filter((quad) => quad.facing === 'up').at(-1) + const texture = top?.texture ?? model?.particle + if (texture === undefined || texture === null) { + return UNKNOWN_BLOCK_COLOR + } + const bitmap = await this.images.image(texturePath(texture)) + if (bitmap === null) { + return UNKNOWN_BLOCK_COLOR + } + const state = parseState(block) + return multiplied(averageColor(bitmap), blockTint(state.name, state.properties, top?.tintIndex ?? -1)) + } +} + +// The first frame only: an animated texture stacks its frames downwards. +function averageColor(bitmap: ImageBitmap): number { + const side = bitmap.width + const canvas = new OffscreenCanvas(side, side) + const drawing = canvas.getContext('2d', { willReadFrequently: true })! + drawing.drawImage(bitmap, 0, 0, side, side, 0, 0, side, side) + const pixels = drawing.getImageData(0, 0, side, side).data + let [red, green, blue, counted] = [0, 0, 0, 0] + for (let offset = 0; offset < pixels.length; offset += 4) { + if (pixels[offset + 3] >= OPAQUE_ENOUGH_ALPHA) { + red += pixels[offset] + green += pixels[offset + 1] + blue += pixels[offset + 2] + counted++ + } + } + if (counted === 0) { + return UNKNOWN_BLOCK_COLOR + } + return (Math.round(red / counted) << 16) | (Math.round(green / counted) << 8) | Math.round(blue / counted) +} + +function multiplied(color: number, tint: number): number { + const channel = (shift: number): number => Math.round((((color >> shift) & 0xff) * ((tint >> shift) & 0xff)) / 255) + return (channel(16) << 16) | (channel(8) << 8) | channel(0) +} diff --git a/src/renderer/src/scene/mapTerrain.ts b/src/renderer/src/scene/mapTerrain.ts new file mode 100644 index 000000000..ec3bd8f46 --- /dev/null +++ b/src/renderer/src/scene/mapTerrain.ts @@ -0,0 +1,67 @@ +import { NO_LABEL, type MapTile } from '../bridge/types' +import { heightColor } from '../map/heightColors' +import type { TerrainSurface } from './terrainMesh' + +export type MapTerrainColoring = 'biomes' | 'regions' | 'height' + +/** A square of map tiles with heights, row by row from the north west. */ +export interface MapTerrainArea { + tiles: MapTile[][] + /** The world spot of the first tile's first pixel. */ + originX: number + originZ: number +} + +const UNLABELLED_COLOR = 0x5a5f6b + +/** The area's tiles as one surface, without the ring each tile carries for its neighbours; the sea fills up to fluid height. */ +export class MapTerrain implements TerrainSurface { + readonly columns: number + readonly rows: number + private readonly size: number + private readonly blocksPerPixel: number + + constructor( + private readonly area: MapTerrainArea, + private readonly coloring: MapTerrainColoring, + private readonly fluidHeight: number + ) { + const first = area.tiles[0][0] + this.size = first.size + this.blocksPerPixel = first.blocksPerPixel + this.columns = area.tiles[0].length * this.size + this.rows = area.tiles.length * this.size + } + + worldX(column: number): number { + return this.area.originX + column * this.blocksPerPixel + } + + worldZ(row: number): number { + return this.area.originZ + row * this.blocksPerPixel + } + + groundAt(column: number, row: number): number { + const { tile, cell } = this.cellAt(column, row) + return tile.heights![cell] + } + + waterAt(column: number, row: number): number | null { + return this.groundAt(column, row) < this.fluidHeight ? this.fluidHeight : null + } + + colorAt(column: number, row: number): number { + if (this.coloring === 'height') { + return heightColor(this.groundAt(column, row), this.fluidHeight) + } + const { tile, cell } = this.cellAt(column, row) + const index = this.coloring === 'regions' ? tile.regions[cell] : tile.subjects[cell] + return index === NO_LABEL ? UNLABELLED_COLOR : tile.labels[index].color + } + + private cellAt(column: number, row: number): { tile: MapTile; cell: number } { + const tile = this.area.tiles[Math.floor(row / this.size)][Math.floor(column / this.size)] + const gridSize = this.size + 2 + return { tile, cell: ((row % this.size) + 1) * gridSize + (column % this.size) + 1 } + } +} diff --git a/src/renderer/src/scene/savedTerrain.ts b/src/renderer/src/scene/savedTerrain.ts new file mode 100644 index 000000000..102a10783 --- /dev/null +++ b/src/renderer/src/scene/savedTerrain.ts @@ -0,0 +1,78 @@ +import type { SavedTile } from '../bridge/types' +import { heightColor } from '../map/heightColors' +import type { TerrainSurface } from './terrainMesh' + +export type SavedTerrainColoring = 'biomes' | 'blocks' | 'height' + +/** A square of saved tiles, row by row from the north west. */ +export interface SavedTerrainArea { + tiles: SavedTile[][] + /** The world spot of the first tile's first pixel. */ + originX: number + originZ: number +} + +// A world without water is measured from where vanilla's sea would be. +const VANILLA_SEA_LEVEL = 63 +const UNKNOWN_BLOCK_COLOR = 0x7f7f7f + +/** + * The saved columns as one surface. Heights are the tops of the blocks, one above their Y, so ground and water sit + * where a player stands on them. + */ +export class SavedTerrain implements TerrainSurface { + readonly columns: number + readonly rows: number + private readonly size: number + private readonly blocksPerPixel: number + + constructor( + private readonly area: SavedTerrainArea, + private readonly coloring: SavedTerrainColoring, + private readonly seaLevel: number | null, + private readonly blockColors: Map + ) { + const first = area.tiles[0][0] + this.size = first.size + this.blocksPerPixel = first.blocksPerPixel + this.columns = area.tiles[0].length * this.size + this.rows = area.tiles.length * this.size + } + + worldX(column: number): number { + return this.area.originX + column * this.blocksPerPixel + } + + worldZ(row: number): number { + return this.area.originZ + row * this.blocksPerPixel + } + + groundAt(column: number, row: number): number | null { + const { tile, pixel } = this.pixelAt(column, row) + const ground = tile.groundY[pixel] + return ground === tile.noGround ? null : ground + 1 + } + + waterAt(column: number, row: number): number | null { + const { tile, pixel } = this.pixelAt(column, row) + const water = tile.waterSurfaceY[pixel] + return water === tile.noWater ? null : water + 1 + } + + colorAt(column: number, row: number): number { + const { tile, pixel } = this.pixelAt(column, row) + switch (this.coloring) { + case 'height': + return heightColor(tile.groundY[pixel], this.seaLevel ?? VANILLA_SEA_LEVEL) + case 'blocks': + return this.blockColors.get(tile.blockNames[tile.blocks[pixel]]) ?? UNKNOWN_BLOCK_COLOR + case 'biomes': + return tile.biomeLabels[tile.biomes[pixel]].color + } + } + + private pixelAt(column: number, row: number): { tile: SavedTile; pixel: number } { + const tile = this.area.tiles[Math.floor(row / this.size)][Math.floor(column / this.size)] + return { tile, pixel: (row % this.size) * this.size + (column % this.size) } + } +} diff --git a/src/renderer/src/scene/terrainMesh.test.ts b/src/renderer/src/scene/terrainMesh.test.ts new file mode 100644 index 000000000..667ad643c --- /dev/null +++ b/src/renderer/src/scene/terrainMesh.test.ts @@ -0,0 +1,50 @@ +import type { Mesh } from 'three' +import { describe, expect, it } from 'vitest' +import { buildTerrainMesh, type TerrainSurface } from './terrainMesh' + +const GROUND = 10 +const WATER = 12 +const BLOCKS_PER_VERTEX = 2 + +// Three by three vertices: nothing known at the north west corner, a pond at the middle vertex. +const surface: TerrainSurface = { + columns: 3, + rows: 3, + worldX: (column) => column * BLOCKS_PER_VERTEX, + worldZ: (row) => row * BLOCKS_PER_VERTEX, + groundAt: (column, row) => (column === 0 && row === 0 ? null : GROUND), + waterAt: (column, row) => (column === 1 && row === 1 ? WATER : null), + colorAt: () => 0x808080 +} + +function meshes(): Mesh[] { + return buildTerrainMesh(surface).content.object.children as Mesh[] +} + +function triangles(mesh: Mesh): number { + return mesh.geometry.getIndex()!.count / 3 +} + +describe('terrain mesh', () => { + it('leaves out the squares that touch a hole', () => { + const [ground] = meshes() + expect(triangles(ground)).toBe(3 * 2) + }) + + it('frames the known surface from below its walls to its highest water, not the unused vertices', () => { + const bounds = buildTerrainMesh(surface).content.bounds + expect(bounds.min.toArray()).toEqual([0, GROUND - 8, 0]) + expect(bounds.max.toArray()).toEqual([2 * BLOCKS_PER_VERTEX, WATER, 2 * BLOCKS_PER_VERTEX]) + }) + + it('carries the water out to the shore around the vertex that holds it, except into the hole', () => { + const [, , water] = meshes() + expect(triangles(water)).toBe(3 * 2) + }) + + it('stands walls only between rim vertices that both have ground', () => { + const [, landWalls] = meshes() + // The rim has eight segments; the two at the hole's corner fall away. + expect(triangles(landWalls)).toBe(6 * 2) + }) +}) diff --git a/src/renderer/src/scene/terrainMesh.ts b/src/renderer/src/scene/terrainMesh.ts index 175b3cbaa..e69287dc2 100644 --- a/src/renderer/src/scene/terrainMesh.ts +++ b/src/renderer/src/scene/terrainMesh.ts @@ -1,16 +1,19 @@ -import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, PlaneGeometry, Vector3 } from 'three' -import { NO_LABEL, type MapTile } from '../bridge/types' -import { heightColor } from '../map/heightColors' +import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, Vector3 } from 'three' import type { ViewportContent } from '../studio/SceneViewport' -export type TerrainColoring = 'biomes' | 'regions' | 'height' - -/** A square of map tiles with heights, row by row from the north west. */ -export interface TerrainArea { - tiles: MapTile[][] - /** The world spot of the first tile's first pixel. */ - originX: number - originZ: number +/** + * A height field to draw, one vertex per map pixel, row by row from the north west: the ground, the water over it, + * and the ground's colour. Where nothing is known, the ground is null and the field has a hole. + */ +export interface TerrainSurface { + readonly columns: number + readonly rows: number + worldX(column: number): number + worldZ(row: number): number + groundAt(column: number, row: number): number | null + /** The water's surface over the vertex, or null where it is dry. */ + waterAt(column: number, row: number): number | null + colorAt(column: number, row: number): number } export interface TerrainMesh { @@ -20,161 +23,199 @@ export interface TerrainMesh { const WATER_COLOR = 0x3f76e4 const WATER_OPACITY = 0.55 -const UNLABELLED_COLOR = 0x5a5f6b // Light from high in the south west, so slopes read as relief; the darkest side keeps some light. const LIGHT = new Vector3(-0.6, 1, 0.4).normalize() const AMBIENT_LIGHT = 0.5 const WALL_DEPTH_BLOCKS = 8 const WALL_TOP_LIGHT = 0.55 const WALL_BASE_LIGHT = 0.25 -const SEA_INSET_BLOCKS = 0.05 +const NO_VALUE = Number.NaN -/** The terrain of the area, one vertex per map pixel, with the dimension's sea as a sheet of water at fluid height. */ -export function buildTerrainMesh(area: TerrainArea, coloring: TerrainColoring, fluidHeight: number): TerrainMesh { - const grid = TerrainGrid.of(area) - const terrain = terrainGeometry(grid, coloring, fluidHeight) - const base = Math.min(grid.lowestHeight(), fluidHeight) - WALL_DEPTH_BLOCKS - const landWalls = rimWall(grid, terrain, (ground) => ground, () => base) - const seaWalls = rimWall(grid, terrain, () => fluidHeight, (ground) => Math.min(ground, fluidHeight)) - const terrainMaterial = new MeshBasicMaterial({ vertexColors: true, side: DoubleSide }) - const sea = seaSurface(grid, fluidHeight) +/** + * The surface as ground lit by its slopes, see-through water over it, and walls round the rim down to below the lowest + * ground, so the square reads as a solid block cut from the world. + */ +export function buildTerrainMesh(surface: TerrainSurface): TerrainMesh { + const field = HeightField.of(surface) + const base = field.lowest() - WALL_DEPTH_BLOCKS + const ground = groundGeometry(field) + const water = waterGeometry(field) + const landWalls = rimWall(field, (vertex) => field.ground[vertex], () => base) + const seaWalls = rimWall(field, (vertex) => field.water[vertex], (vertex) => Math.min(field.ground[vertex], field.water[vertex])) + const groundMaterial = new MeshBasicMaterial({ vertexColors: true, side: DoubleSide }) const waterMaterial = new MeshBasicMaterial({ color: WATER_COLOR, transparent: true, opacity: WATER_OPACITY, depthWrite: false, side: DoubleSide }) const group = new Group() - group.add(new Mesh(terrain, terrainMaterial), new Mesh(landWalls, terrainMaterial), new Mesh(sea, waterMaterial), new Mesh(seaWalls, waterMaterial)) - const geometries = [terrain, landWalls, sea, seaWalls] + group.add(new Mesh(ground, groundMaterial), new Mesh(landWalls, groundMaterial), new Mesh(water, waterMaterial), new Mesh(seaWalls, waterMaterial)) + const geometries = [ground, water, landWalls, seaWalls] return { - content: { object: group, bounds: new Box3().setFromObject(group) }, + content: { object: group, bounds: field.bounds(base) }, dispose: () => { geometries.forEach((geometry) => geometry.dispose()) - terrainMaterial.dispose() + groundMaterial.dispose() waterMaterial.dispose() } } } -// Kept a little inside the walls, so its edge does not flicker against them. -function seaSurface(grid: TerrainGrid, fluidHeight: number): BufferGeometry { - const sea = new PlaneGeometry(grid.spanX - 2 * SEA_INSET_BLOCKS, grid.spanZ - 2 * SEA_INSET_BLOCKS).rotateX(-Math.PI / 2) - return sea.translate(grid.worldX(0) + grid.spanX / 2, fluidHeight, grid.worldZ(0) + grid.spanZ / 2) +function groundGeometry(field: HeightField): BufferGeometry { + const { surface, ground } = field + const positions = new Float32Array(ground.length * 3) + const colors = new Float32Array(ground.length * 3) + for (let vertex = 0; vertex < ground.length; vertex++) { + if (Number.isNaN(ground[vertex])) { + continue + } + const [column, row] = field.columnAndRow(vertex) + positions.set([surface.worldX(column), ground[vertex], surface.worldZ(row)], vertex * 3) + const light = AMBIENT_LIGHT + (1 - AMBIENT_LIGHT) * Math.max(0, field.normal(column, row).dot(LIGHT)) + colors.set(rgb(surface.colorAt(column, row), light), vertex * 3) + } + return indexedGeometry(positions, colors, field.quadsWhere((corners) => corners.every((vertex) => !Number.isNaN(ground[vertex])))) } -/** - * A wall round the terrain's rim, from {@code topAt} down to {@code bottomAt} of the ground height at each rim vertex; - * in the terrain's colour, darkening downwards, for a material that uses vertex colours. - */ -function rimWall(grid: TerrainGrid, terrain: BufferGeometry, topAt: (ground: number) => number, bottomAt: (ground: number) => number): BufferGeometry { - const rim = grid.rimVertices() - const surface = terrain.getAttribute('position') - const shade = terrain.getAttribute('color') +// Only quads holding water of their own; the vertices next to water carry its level, so it meets the shore. +function waterGeometry(field: HeightField): BufferGeometry { + const { surface, water, ownWater } = field + const positions = new Float32Array(water.length * 3) + for (let vertex = 0; vertex < water.length; vertex++) { + if (!Number.isNaN(water[vertex])) { + const [column, row] = field.columnAndRow(vertex) + positions.set([surface.worldX(column), water[vertex], surface.worldZ(row)], vertex * 3) + } + } + const quads = field.quadsWhere((corners) => corners.every((vertex) => !Number.isNaN(water[vertex])) && corners.some((vertex) => ownWater[vertex])) + return indexedGeometry(positions, null, quads) +} + +/** A wall round the field's rim from {@code topOf} down to {@code bottomOf} each rim vertex, darkening downwards. */ +function rimWall(field: HeightField, topOf: (vertex: number) => number, bottomOf: (vertex: number) => number): BufferGeometry { + const rim = field.rimVertices() const positions = new Float32Array(rim.length * 2 * 3) const colors = new Float32Array(rim.length * 2 * 3) + // A rim vertex without a top or a bottom, such as dry land for the water's wall, holds no wall and keeps the origin. + const standing = rim.map((vertex) => !Number.isNaN(topOf(vertex)) && !Number.isNaN(bottomOf(vertex))) rim.forEach((vertex, index) => { - const [x, ground, z] = [surface.getX(vertex), surface.getY(vertex), surface.getZ(vertex)] - positions.set([x, topAt(ground), z, x, bottomAt(ground), z], index * 6) - const [red, green, blue] = [shade.getX(vertex), shade.getY(vertex), shade.getZ(vertex)] - colors.set([red * WALL_TOP_LIGHT, green * WALL_TOP_LIGHT, blue * WALL_TOP_LIGHT], index * 6) - colors.set([red * WALL_BASE_LIGHT, green * WALL_BASE_LIGHT, blue * WALL_BASE_LIGHT], index * 6 + 3) + if (!standing[index]) { + return + } + const [column, row] = field.columnAndRow(vertex) + const [x, z] = [field.surface.worldX(column), field.surface.worldZ(row)] + positions.set([x, topOf(vertex), z, x, bottomOf(vertex), z], index * 6) + const color = field.surface.colorAt(column, row) + colors.set([...rgb(color, WALL_TOP_LIGHT), ...rgb(color, WALL_BASE_LIGHT)], index * 6) }) const indices: number[] = [] for (let index = 0; index < rim.length; index++) { const next = (index + 1) % rim.length - const [upper, lower, nextUpper, nextLower] = [index * 2, index * 2 + 1, next * 2, next * 2 + 1] - indices.push(upper, lower, nextUpper, nextUpper, lower, nextLower) + if (standing[index] && standing[next]) { + const [upper, lower, nextUpper, nextLower] = [index * 2, index * 2 + 1, next * 2, next * 2 + 1] + indices.push(upper, lower, nextUpper, nextUpper, lower, nextLower) + } } + return indexedGeometry(positions, colors, indices) +} + +function indexedGeometry(positions: Float32Array, colors: Float32Array | null, indices: number[] | Uint32Array): BufferGeometry { const geometry = new BufferGeometry() geometry.setAttribute('position', new BufferAttribute(positions, 3)) - geometry.setAttribute('color', new BufferAttribute(colors, 3)) - geometry.setIndex(indices) + if (colors !== null) { + geometry.setAttribute('color', new BufferAttribute(colors, 3)) + } + geometry.setIndex(new BufferAttribute(indices instanceof Uint32Array ? indices : Uint32Array.from(indices), 1)) return geometry } -function terrainGeometry(grid: TerrainGrid, coloring: TerrainColoring, fluidHeight: number): BufferGeometry { - const { columns, rows } = grid - const positions = new Float32Array(columns * rows * 3) - const colors = new Float32Array(columns * rows * 3) - for (let row = 0; row < rows; row++) { - for (let column = 0; column < columns; column++) { - const vertex = row * columns + column - const height = grid.height(column, row) - positions.set([grid.worldX(column), height, grid.worldZ(row)], vertex * 3) - const color = coloring === 'height' ? heightColor(height, fluidHeight) : grid.labelColor(column, row, coloring) - const light = AMBIENT_LIGHT + (1 - AMBIENT_LIGHT) * Math.max(0, grid.normal(column, row).dot(LIGHT)) - colors.set([(((color >> 16) & 0xff) / 255) * light, (((color >> 8) & 0xff) / 255) * light, ((color & 0xff) / 255) * light], vertex * 3) - } - } - const indices = new Uint32Array((columns - 1) * (rows - 1) * 6) - let next = 0 - for (let row = 0; row < rows - 1; row++) { - for (let column = 0; column < columns - 1; column++) { - const northWest = row * columns + column - const southWest = northWest + columns - indices.set([northWest, southWest, northWest + 1, northWest + 1, southWest, southWest + 1], next) - next += 6 - } - } - const geometry = new BufferGeometry() - geometry.setAttribute('position', new BufferAttribute(positions, 3)) - geometry.setAttribute('color', new BufferAttribute(colors, 3)) - geometry.setIndex(new BufferAttribute(indices, 1)) - return geometry +function rgb(color: number, light: number): [number, number, number] { + return [(((color >> 16) & 0xff) / 255) * light, (((color >> 8) & 0xff) / 255) * light, ((color & 0xff) / 255) * light] } -/** The area's tiles as one grid of pixels, without the ring each tile carries for its neighbours. */ -class TerrainGrid { - readonly columns: number - readonly rows: number - /** How far the vertices reach, west to east and north to south, in blocks. */ - readonly spanX: number - readonly spanZ: number - private readonly size: number - private readonly blocksPerPixel: number +/** The surface's ground and water read once per vertex, with no value as NaN, and how its vertices stand together. */ +class HeightField { + readonly ground: Float32Array + readonly water: Float32Array + readonly ownWater: Uint8Array - private constructor(private readonly area: TerrainArea) { - const first = area.tiles[0][0] - this.size = first.size - this.blocksPerPixel = first.blocksPerPixel - this.columns = area.tiles[0].length * this.size - this.rows = area.tiles.length * this.size - this.spanX = (this.columns - 1) * this.blocksPerPixel - this.spanZ = (this.rows - 1) * this.blocksPerPixel + private constructor(readonly surface: TerrainSurface) { + const count = surface.columns * surface.rows + this.ground = new Float32Array(count) + this.water = new Float32Array(count) + this.ownWater = new Uint8Array(count) + for (let vertex = 0; vertex < count; vertex++) { + const [column, row] = this.columnAndRow(vertex) + const ground = surface.groundAt(column, row) + const water = ground === null ? null : surface.waterAt(column, row) + this.ground[vertex] = ground ?? NO_VALUE + this.water[vertex] = water ?? NO_VALUE + this.ownWater[vertex] = water === null ? 0 : 1 + } + this.extendWaterToShores() } - static of(area: TerrainArea): TerrainGrid { - return new TerrainGrid(area) + static of(surface: TerrainSurface): HeightField { + return new HeightField(surface) } - worldX(column: number): number { - return this.area.originX + column * this.blocksPerPixel + columnAndRow(vertex: number): [number, number] { + return [vertex % this.surface.columns, Math.floor(vertex / this.surface.columns)] } - worldZ(row: number): number { - return this.area.originZ + row * this.blocksPerPixel - } - - height(column: number, row: number): number { - const { tile, cell } = this.cellAt(column, row) - return tile.heights![cell] - } - - labelColor(column: number, row: number, coloring: 'biomes' | 'regions'): number { - const { tile, cell } = this.cellAt(column, row) - const index = coloring === 'regions' ? tile.regions[cell] : tile.subjects[cell] - return index === NO_LABEL ? UNLABELLED_COLOR : tile.labels[index].color - } - - lowestHeight(): number { + lowest(): number { let lowest = Infinity - for (let row = 0; row < this.rows; row++) { - for (let column = 0; column < this.columns; column++) { - lowest = Math.min(lowest, this.height(column, row)) + for (let vertex = 0; vertex < this.ground.length; vertex++) { + if (!Number.isNaN(this.ground[vertex])) { + lowest = Math.min(lowest, this.ground[vertex], Number.isNaN(this.water[vertex]) ? Infinity : this.water[vertex]) } } - return lowest + return Number.isFinite(lowest) ? lowest : 0 } - /** The vertices on the edge of the grid, once each, going round clockwise from the north west corner. */ + /** The box round the field from {@code base} to its highest ground or water; vertices left out of it do not count. */ + bounds(base: number): Box3 { + let highest = base + for (let vertex = 0; vertex < this.ground.length; vertex++) { + for (const height of [this.ground[vertex], this.water[vertex]]) { + if (!Number.isNaN(height)) { + highest = Math.max(highest, height) + } + } + } + const { columns, rows } = this.surface + return new Box3( + new Vector3(this.surface.worldX(0), base, this.surface.worldZ(0)), + new Vector3(this.surface.worldX(columns - 1), highest, this.surface.worldZ(rows - 1)) + ) + } + + /** The two triangles of each grid square whose four corners pass {@code wanted}. */ + quadsWhere(wanted: (corners: [number, number, number, number]) => boolean): Uint32Array { + const { columns, rows } = this.surface + const indices: number[] = [] + for (let row = 0; row < rows - 1; row++) { + for (let column = 0; column < columns - 1; column++) { + const northWest = row * columns + column + const southWest = northWest + columns + if (wanted([northWest, northWest + 1, southWest, southWest + 1])) { + indices.push(northWest, southWest, northWest + 1, northWest + 1, southWest, southWest + 1) + } + } + } + return Uint32Array.from(indices) + } + + normal(column: number, row: number): Vector3 { + const { columns, rows } = this.surface + const here = this.ground[row * columns + column] + const at = (atColumn: number, atRow: number): number => { + const height = this.ground[Math.min(rows - 1, Math.max(0, atRow)) * columns + Math.min(columns - 1, Math.max(0, atColumn))] + return Number.isNaN(height) ? here : height + } + const spacing = Math.abs(this.surface.worldX(Math.min(columns - 1, 1)) - this.surface.worldX(0)) || 1 + return new Vector3(at(column - 1, row) - at(column + 1, row), 2 * spacing, at(column, row - 1) - at(column, row + 1)).normalize() + } + + /** The vertices on the edge of the field, once each, going round clockwise from the north west corner. */ rimVertices(): number[] { - const { columns, rows } = this + const { columns, rows } = this.surface const rim: number[] = [] for (let column = 0; column < columns - 1; column++) rim.push(column) for (let row = 0; row < rows - 1; row++) rim.push(row * columns + columns - 1) @@ -183,17 +224,31 @@ class TerrainGrid { return rim } - normal(column: number, row: number): Vector3 { - const west = this.height(Math.max(0, column - 1), row) - const east = this.height(Math.min(this.columns - 1, column + 1), row) - const north = this.height(column, Math.max(0, row - 1)) - const south = this.height(column, Math.min(this.rows - 1, row + 1)) - return new Vector3(west - east, 2 * this.blocksPerPixel, north - south).normalize() - } - - private cellAt(column: number, row: number): { tile: MapTile; cell: number } { - const tile = this.area.tiles[Math.floor(row / this.size)][Math.floor(column / this.size)] - const gridSize = this.size + 2 - return { tile, cell: ((row % this.size) + 1) * gridSize + (column % this.size) + 1 } + // A dry vertex next to water takes the highest water beside it, so the water's edge runs under the shore. + private extendWaterToShores(): void { + const { columns, rows } = this.surface + const own = Float32Array.from(this.water) + for (let row = 0; row < rows; row++) { + for (let column = 0; column < columns; column++) { + const vertex = row * columns + column + if (this.ownWater[vertex] === 1 || Number.isNaN(this.ground[vertex])) { + continue + } + let highest = NO_VALUE + for (let offsetRow = -1; offsetRow <= 1; offsetRow++) { + for (let offsetColumn = -1; offsetColumn <= 1; offsetColumn++) { + const [nearColumn, nearRow] = [column + offsetColumn, row + offsetRow] + if (nearColumn < 0 || nearRow < 0 || nearColumn >= columns || nearRow >= rows) { + continue + } + const near = own[nearRow * columns + nearColumn] + if (!Number.isNaN(near) && (Number.isNaN(highest) || near > highest)) { + highest = near + } + } + } + this.water[vertex] = highest + } + } } } diff --git a/src/renderer/src/scene/textureAtlas.ts b/src/renderer/src/scene/textureAtlas.ts index ffc8d6665..4bf1599a6 100644 --- a/src/renderer/src/scene/textureAtlas.ts +++ b/src/renderer/src/scene/textureAtlas.ts @@ -80,7 +80,7 @@ export class TextureAtlas { } /** {@code minecraft:block/stone} lies at {@code minecraft/textures/block/stone.png}. */ -function texturePath(textureId: string): string { +export function texturePath(textureId: string): string { const colon = textureId.indexOf(':') return `${textureId.slice(0, colon)}/textures/${textureId.slice(colon + 1)}.png` } diff --git a/src/renderer/src/studio/MapStudio.tsx b/src/renderer/src/studio/MapStudio.tsx index a3a2e3498..8a9b8160a 100644 --- a/src/renderer/src/studio/MapStudio.tsx +++ b/src/renderer/src/studio/MapStudio.tsx @@ -11,6 +11,7 @@ import { Legend } from './Legend' import { MapCanvas, type CanvasPoint } from './MapCanvas' import { PickInspector } from './PickInspector' import { RegionPreviewList } from './RegionPreviewList' +import { SavedWorldStudio } from './SavedWorldStudio' import { SceneStudio } from './SceneStudio' import { WorldStudio3D } from './WorldStudio3D' import { actionForKey, viewForKey, type ShortcutAction } from './shortcuts' @@ -60,9 +61,9 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps const [packRevision, setPackRevision] = useState(0) const [sceneSummary, setSceneSummary] = useState(null) const sceneViews = useSceneViews(client, packRevision) - const views = useMemo(() => [...withWorld3D(world.views), ...sceneViews.map(asViewInfo)], [world.views, sceneViews]) + const views = useMemo(() => [...withAppViews(world.views), ...sceneViews.map(asViewInfo)], [world.views, sceneViews]) const sceneView = sceneViews.find((candidate) => candidate.id === viewId) ?? null - const showsMap = sceneView === null && viewId !== WORLD_3D.id + const showsMap = sceneView === null && !APP_VIEW_IDS.has(viewId) const view = views.find((candidate) => candidate.id === viewId) ?? views[0] const layer = useMemo(() => ({ view: viewId, preview: viewId === 'regions' ? preview : null }), [viewId, preview]) const regions = usePreviewableRegions(client, packRevision) @@ -218,6 +219,8 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps ) : viewId === WORLD_3D.id ? ( + ) : viewId === SAVED_WORLD.id ? ( + ) : ( <>
@@ -288,10 +291,18 @@ const WORLD_3D: ViewInfo = { group: 'WORLD', groupLabel: 'World' } +const SAVED_WORLD: ViewInfo = { + id: 'savedWorld', + label: 'Saved world', + description: 'A world as the server saved it to disk, in 3D', + group: 'WORLD', + groupLabel: 'World' +} +const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id]) -function withWorld3D(serverViews: ViewInfo[]): ViewInfo[] { +function withAppViews(serverViews: ViewInfo[]): ViewInfo[] { const afterHeight = serverViews.findIndex((candidate) => candidate.id === 'height') + 1 - return [...serverViews.slice(0, afterHeight), WORLD_3D, ...serverViews.slice(afterHeight)] + return [...serverViews.slice(0, afterHeight), WORLD_3D, SAVED_WORLD, ...serverViews.slice(afterHeight)] } function asViewInfo(view: SceneViewInfo): ViewInfo { diff --git a/src/renderer/src/studio/SavedWorldStudio.tsx b/src/renderer/src/studio/SavedWorldStudio.tsx new file mode 100644 index 000000000..a128038cb --- /dev/null +++ b/src/renderer/src/studio/SavedWorldStudio.tsx @@ -0,0 +1,223 @@ +import { RotateCw } from 'lucide-react' +import { useEffect, useMemo, useState } from 'react' +import { Button } from '@/components/ui/button' +import { ScrollArea } from '@/components/ui/scroll-area' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import { cn } from '@/lib/utils' +import { BridgeError, STATUS_NOT_FOUND, type BridgeClient } from '../bridge/BridgeClient' +import type { SavedStart, SavedTile, SavedWorldInfo, WorldInfo } from '../bridge/types' +import { BlockColors } from '../scene/blockColors' +import { BlockModels } from '../scene/blockModels' +import { BridgeAssets } from '../scene/BridgeAssets' +import { SavedTerrain, type SavedTerrainArea, type SavedTerrainColoring } from '../scene/savedTerrain' +import { buildTerrainMesh } from '../scene/terrainMesh' +import { SceneViewport } from './SceneViewport' + +const NUMBER = new Intl.NumberFormat('en-US') +const TILES_PER_SIDE = 4 +const TILE_PIXELS = 128 +const BLOCKS_PER_PIXEL = 2 +const TILE_BLOCKS = TILE_PIXELS * BLOCKS_PER_PIXEL +const NO_COLORS = new Map() +const COLORING_ITEM = 'h-7 px-3 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground' +const PILL = 'pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text' + +interface SavedWorldStudioProps { + client: BridgeClient + /** The studio's own world, whose saved copy is chosen first. */ + world: WorldInfo + onSummary(summary: string | null): void + tell(message: string): void +} + +/** A world as its region files hold it, in 3D, around the region nearest its origin (v3e's saved world explorer). */ +export function SavedWorldStudio({ client, world, onSummary, tell }: SavedWorldStudioProps): React.JSX.Element { + const worlds = useSavedWorlds(client, tell) + const [chosenId, setChosenId] = useState(null) + const chosen = worlds.find((candidate) => candidate.id === chosenId) ?? ownWorldAmong(worlds, world) ?? worlds[0] ?? null + const [coloring, setColoring] = useState('biomes') + const [readings, setReadings] = useState(0) + const { start, area, reading } = useSavedArea(client, chosen?.id ?? null, readings, tell) + const blockColors = useBlockColors(client, coloring === 'blocks' ? area : null) + const mesh = useMemo(() => { + if (area === null || start === null || (coloring === 'blocks' && blockColors === null)) { + return null + } + return buildTerrainMesh(new SavedTerrain(area, coloring, start.seaLevel, blockColors ?? NO_COLORS)) + }, [area, start, coloring, blockColors]) + + useEffect(() => () => mesh?.dispose(), [mesh]) + useEffect(() => { + if (chosen === null || start === null) { + onSummary(null) + return + } + const side = NUMBER.format(TILES_PER_SIDE * TILE_BLOCKS) + onSummary(`${chosen.name} · ${side} × ${side} blocks around ${NUMBER.format(start.centerX)}, ${NUMBER.format(start.centerZ)}`) + }, [chosen, start, onSummary]) + useEffect(() => () => onSummary(null), [onSummary]) + + return ( + <> +
+ +
+ value !== '' && setColoring(value as SavedTerrainColoring)} + > + + Biomes + + + Blocks + + + Height + + + +
+ {reading && chosen !== null &&
Reading {chosen.name}
} + {!reading && chosen !== null && start === null &&
Nothing finished is saved in {chosen.name}
} +
+ + + ) +} + +function WorldList({ worlds, current, onSelect }: { worlds: SavedWorldInfo[]; current: string | null; onSelect(id: string): void }): React.JSX.Element { + const namespaces = [...new Set(worlds.map((world) => world.namespace))] + return ( +
+ {namespaces.map((namespace) => ( +
+

{namespace}

+ {worlds + .filter((world) => world.namespace === namespace) + .map((world) => ( + + ))} +
+ ))} + {worlds.length === 0 &&

Nothing to show

} +
+ ) +} + +// The studio's world folder is named after its dimension, so world_iris_procfix is saved as iris/procfix. +function ownWorldAmong(worlds: SavedWorldInfo[], world: WorldInfo): SavedWorldInfo | undefined { + return worlds.find((candidate) => world.world.endsWith(`_${candidate.name}`) || world.world === candidate.name) +} + +function useSavedWorlds(client: BridgeClient, tell: (message: string) => void): SavedWorldInfo[] { + const [worlds, setWorlds] = useState([]) + useEffect(() => { + let active = true + client + .savedWorlds() + .then((found) => active && setWorlds(found)) + .catch((failure: Error) => active && tell(failure.message)) + return () => { + active = false + } + }, [client, tell]) + return worlds +} + +/** Where the chosen world's view opens and the square of tiles around it; every tile arrives before it is shown. */ +function useSavedArea( + client: BridgeClient, + worldId: string | null, + readings: number, + tell: (message: string) => void +): { start: SavedStart | null; area: SavedTerrainArea | null; reading: boolean } { + const [start, setStart] = useState(null) + const [area, setArea] = useState(null) + const [reading, setReading] = useState(false) + useEffect(() => { + if (worldId === null) { + return + } + const stop = new AbortController() + setReading(true) + setStart(null) + setArea(null) + readSavedArea(client, worldId, stop.signal) + .then((found) => { + setStart(found?.start ?? null) + setArea(found?.area ?? null) + }) + .catch((failure: Error) => !stop.signal.aborted && tell(failure.message)) + .finally(() => !stop.signal.aborted && setReading(false)) + return () => stop.abort() + }, [client, worldId, readings, tell]) + return { start, area, reading } +} + +async function readSavedArea(client: BridgeClient, worldId: string, signal: AbortSignal): Promise<{ start: SavedStart; area: SavedTerrainArea } | null> { + let start: SavedStart + try { + start = await client.savedStart(worldId, signal) + } catch (failure) { + if (failure instanceof BridgeError && failure.status === STATUS_NOT_FOUND) { + return null + } + throw failure + } + const firstTileX = Math.floor(start.centerX / TILE_BLOCKS - TILES_PER_SIDE / 2) + const firstTileZ = Math.floor(start.centerZ / TILE_BLOCKS - TILES_PER_SIDE / 2) + const tiles: SavedTile[][] = await Promise.all( + Array.from({ length: TILES_PER_SIDE }, (_, row) => + Promise.all( + Array.from({ length: TILES_PER_SIDE }, (_, column) => + client.savedTile(worldId, firstTileX + column, firstTileZ + row, BLOCKS_PER_PIXEL, TILE_PIXELS, signal) + ) + ) + ) + ) + return { start, area: { tiles, originX: firstTileX * TILE_BLOCKS, originZ: firstTileZ * TILE_BLOCKS } } +} + +/** The colour of every block in the area, read from the client's textures, or null until they are read. */ +function useBlockColors(client: BridgeClient, area: SavedTerrainArea | null): Map | null { + const colors = useMemo(() => { + const images = new BridgeAssets(client, () => {}) + return new BlockColors(new BlockModels(images), images) + }, [client]) + const [read, setRead] = useState | null>(null) + useEffect(() => { + setRead(null) + if (area === null) { + return + } + let active = true + const blocks = area.tiles.flat().flatMap((tile) => tile.blockNames) + colors.colorsOf(blocks).then((found) => active && setRead(found)) + return () => { + active = false + } + }, [colors, area]) + return read +} diff --git a/src/renderer/src/studio/ViewList.tsx b/src/renderer/src/studio/ViewList.tsx index 505beac6b..6db760567 100644 --- a/src/renderer/src/studio/ViewList.tsx +++ b/src/renderer/src/studio/ViewList.tsx @@ -1,4 +1,4 @@ -import { Box, Gem, Globe, Map as MapIcon, Mountain, Shapes, Sprout, Trees, Waves, type LucideIcon } from 'lucide-react' +import { Box, Gem, Globe, HardDrive, Map as MapIcon, Mountain, Shapes, Sprout, Trees, Waves, type LucideIcon } from 'lucide-react' import { Kbd } from '@/components/ui/kbd' import { ScrollArea } from '@/components/ui/scroll-area' import { cn } from '@/lib/utils' @@ -10,6 +10,7 @@ const VIEW_ICONS: Record = { regions: MapIcon, height: Mountain, world3d: Globe, + savedWorld: HardDrive, landBiomes: Sprout, seaBiomes: Waves, caveBiomes: Gem, diff --git a/src/renderer/src/studio/WorldStudio3D.tsx b/src/renderer/src/studio/WorldStudio3D.tsx index 4117c5dc6..a9a5b58bc 100644 --- a/src/renderer/src/studio/WorldStudio3D.tsx +++ b/src/renderer/src/studio/WorldStudio3D.tsx @@ -2,7 +2,8 @@ import { useEffect, useMemo, useState } from 'react' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import type { BridgeClient, WorldRect } from '../bridge/BridgeClient' import type { MapTile, WorldInfo } from '../bridge/types' -import { buildTerrainMesh, type TerrainArea, type TerrainColoring } from '../scene/terrainMesh' +import { MapTerrain, type MapTerrainArea, type MapTerrainColoring } from '../scene/mapTerrain' +import { buildTerrainMesh } from '../scene/terrainMesh' import { SceneViewport } from './SceneViewport' const NUMBER = new Intl.NumberFormat('en-US') @@ -24,10 +25,10 @@ interface WorldStudio3DProps { /** The terrain around where the map looked, in 3D, coloured by biome, region or height (v3e's 3D world view). */ export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary, tell }: WorldStudio3DProps): React.JSX.Element { - const [coloring, setColoring] = useState('biomes') + const [coloring, setColoring] = useState('biomes') const centre = useMemo(() => centreOf(mapArea), [mapArea]) const area = useTerrainArea(client, centre, packRevision, tell) - const mesh = useMemo(() => (area === null ? null : buildTerrainMesh(area, coloring, world.fluidHeight)), [area, coloring, world.fluidHeight]) + const mesh = useMemo(() => (area === null ? null : buildTerrainMesh(new MapTerrain(area, coloring, world.fluidHeight))), [area, coloring, world.fluidHeight]) useEffect(() => () => mesh?.dispose(), [mesh]) useEffect(() => { @@ -45,7 +46,7 @@ export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary, size="sm" className="absolute top-3 left-3 bg-card/90" value={coloring} - onValueChange={(value) => value !== '' && setColoring(value as TerrainColoring)} + onValueChange={(value) => value !== '' && setColoring(value as MapTerrainColoring)} > Biomes @@ -74,8 +75,8 @@ function centreOf(area: WorldRect | null): { x: number; z: number } { } /** The tiles of the square around {@code centre}, with heights; every tile arrives before the square is shown. */ -function useTerrainArea(client: BridgeClient, centre: { x: number; z: number }, packRevision: number, tell: (message: string) => void): TerrainArea | null { - const [area, setArea] = useState(null) +function useTerrainArea(client: BridgeClient, centre: { x: number; z: number }, packRevision: number, tell: (message: string) => void): MapTerrainArea | null { + const [area, setArea] = useState(null) useEffect(() => { const stop = new AbortController() const firstTileX = Math.floor(centre.x / TILE_BLOCKS - TILES_PER_SIDE / 2)