diff --git a/src/renderer/src/bridge/BridgeClient.ts b/src/renderer/src/bridge/BridgeClient.ts index 2658ef309..be9774ac9 100644 --- a/src/renderer/src/bridge/BridgeClient.ts +++ b/src/renderer/src/bridge/BridgeClient.ts @@ -7,6 +7,8 @@ import type { MapLabel, MapTile, Marker, + NoiseSource, + NoiseTile, PickInspection, SavedStart, SavedTile, @@ -147,6 +149,17 @@ export class BridgeClient { return decodeSavedTile(await response.arrayBuffer()) } + /** The pack's generators and expressions, the dimension's overlay noise, and the built-in noise styles. */ + noiseSources(): Promise { + return this.json('noise-sources') + } + + async noiseTile(sourceId: string, seed: string, tileX: number, tileZ: number, blocksPerPixel: number, size: number, signal: AbortSignal): Promise { + const query = new URLSearchParams({ source: sourceId, seed, x: String(tileX), z: String(tileZ), scale: String(blocksPerPixel), size: String(size) }) + const response = await this.fetch(`noise-tile?${query}`, { signal }) + return { size, values: new Float32Array(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/types.ts b/src/renderer/src/bridge/types.ts index a31b79356..b3e256bbf 100644 --- a/src/renderer/src/bridge/types.ts +++ b/src/renderer/src/bridge/types.ts @@ -42,6 +42,23 @@ export interface SavedWorldInfo { namespace: string } +/** One noise the noise view can show. */ +export interface NoiseSource { + id: string + name: string + category: string + /** Whether the view's seed changes it; the dimension's overlay keeps the world's. */ + usesSeed: boolean + /** What the noise spans where it is measured in blocks above the fluid; null for noise of 0 to 1. */ + blockRange: { lowest: number; highest: number } | null +} + +/** A square of noise values, a pixel's value taken at its north west corner, row by row from the north west. */ +export interface NoiseTile { + size: number + values: Float32Array +} + /** 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 diff --git a/src/renderer/src/map/MapController.ts b/src/renderer/src/map/MapController.ts index 287bc8dd2..0cdb5b9c4 100644 --- a/src/renderer/src/map/MapController.ts +++ b/src/renderer/src/map/MapController.ts @@ -1,19 +1,18 @@ import type { BridgeClient, WorldRect } from '../bridge/BridgeClient' import { gridIndex } from '../bridge/tileDecoding' -import { NO_LABEL, type MapLabel, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types' +import { NO_LABEL, type MapLabel, type MapTile, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types' import { countShares, type PlacedTile, type Share } from './census' import { bandIndexOf, HEIGHT_BANDS } from './heightColors' +import { mapTileSource, type TileLayer } from './mapTileSource' +import { drawVisibleTiles } from './tileDrawing' import type { Highlight, TileStyle } from './tileStyle' -import { TileStore, type TileLayer } from './TileStore' +import { TileStore } from './TileStore' import { clampBlocksPerPixel, - coarserTile, - previewsFor, DEFAULT_BLOCKS_PER_PIXEL, renderBlocksPerPixel, screenToWorldX, screenToWorldZ, - visibleTiles, worldToScreenX, worldToScreenZ, type TileAddress, @@ -53,8 +52,6 @@ export interface MapToggles { grid: boolean } -// While a tile is on its way, a coarser one already drawn stands in, up to this many zoom levels out. -const COARSER_FALLBACK_LEVELS = 6 const CENSUS_INTERVAL_MILLIS = 250 const CHUNK_BLOCKS = 16 const REGION_BLOCKS = 512 @@ -73,7 +70,7 @@ const ENTITY_RADIUS_PIXELS = 3 */ export class MapController { private readonly context: CanvasRenderingContext2D - private readonly store: TileStore + private readonly store: TileStore private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_BLOCKS_PER_PIXEL, width: 1, height: 1 } private layer: TileLayer private toggles: MapToggles = { shading: true, regionBorders: false, grid: false } @@ -96,7 +93,7 @@ export class MapController { ) { this.context = canvas.getContext('2d')! this.layer = { view, preview: null, heights: this.needsHeights(view, this.toggles), pickNoise: false, revision: 0 } - this.store = new TileStore(client, world.tileSize, () => this.redraw(), (message) => listener.onError(message)) + this.store = new TileStore(mapTileSource(client, world.tileSize), () => this.redraw(), (message) => listener.onError(message)) } close(): void { @@ -263,56 +260,17 @@ export class MapController { context.fillStyle = getComputedStyle(this.canvas).getPropertyValue('--map-background') || '#16171a' context.fillRect(0, 0, this.view.width, this.view.height) - const scale = this.renderScale() - const tiles = visibleTiles(this.view, scale, this.world.tileSize) const style = this.style() - context.imageSmoothingEnabled = this.view.blocksPerPixel > scale - let ready = 0 - const blank: TileAddress[] = [] - for (const address of tiles) { - const picture = this.store.picture(address, this.layer, style) - if (picture !== null) { - this.drawTile(picture, address, 0, 0, picture.width) - ready++ - } else if (!this.drawFallback(address, style)) { - blank.push(address) - } - } - this.store.want([...previewsFor(blank), ...tiles], this.layer) + const drawn = drawVisibleTiles(context, this.view, this.renderScale(), this.world.tileSize, (address) => + this.store.picture(address, this.layer, style) + ) + this.store.want(drawn.wanted, this.layer) if (this.toggles.grid) { this.drawGrid() } this.drawMarkers() - this.reportStatus(ready, tiles.length) - this.scheduleCensus(tiles) - } - - /** Draws the part of a tile picture from (sourceX, sourceZ), {@code sourceSize} pixels wide, over {@code address}. */ - private drawTile(picture: HTMLCanvasElement, address: TileAddress, sourceX: number, sourceZ: number, sourceSize: number): void { - const span = this.world.tileSize * address.blocksPerPixel - const left = Math.round(worldToScreenX(this.view, address.tileX * span)) - const top = Math.round(worldToScreenZ(this.view, address.tileZ * span)) - const right = Math.round(worldToScreenX(this.view, (address.tileX + 1) * span)) - const bottom = Math.round(worldToScreenZ(this.view, (address.tileZ + 1) * span)) - this.context.drawImage(picture, sourceX, sourceZ, sourceSize, sourceSize, left, top, right - left, bottom - top) - } - - /** Draws the part of a coarser tile that covers {@code address}; false when no coarser tile has arrived either. */ - private drawFallback(address: TileAddress, style: TileStyle): boolean { - for (let levels = 1; levels <= COARSER_FALLBACK_LEVELS; levels++) { - const coarser = coarserTile(address, levels) - const picture = this.store.picture(coarser, this.layer, style) - if (picture === null) { - continue - } - const factor = 2 ** levels - const sourceSize = picture.width / factor - const sourceX = (address.tileX - coarser.tileX * factor) * sourceSize - const sourceZ = (address.tileZ - coarser.tileZ * factor) * sourceSize - this.drawTile(picture, address, sourceX, sourceZ, sourceSize) - return true - } - return false + this.reportStatus(drawn.ready, drawn.tiles.length) + this.scheduleCensus(drawn.tiles) } private drawGrid(): void { diff --git a/src/renderer/src/map/TileStore.ts b/src/renderer/src/map/TileStore.ts index 9ecc91c10..30d949527 100644 --- a/src/renderer/src/map/TileStore.ts +++ b/src/renderer/src/map/TileStore.ts @@ -1,21 +1,18 @@ -import { BridgeError, type BridgeClient } from '../bridge/BridgeClient' -import type { MapTile } from '../bridge/types' -import { stylePixels, styleKey, type TileStyle } from './tileStyle' +import { BridgeError } from '../bridge/BridgeClient' import type { TileAddress } from './viewport' -/** What one tile request needs besides where the tile is. */ -export interface TileLayer { - view: string - /** The region the region view previews everywhere, or null for the world as it is. */ - preview: string | null - heights: boolean - pickNoise: boolean - /** Bumped when the pack is hotloaded, so older tiles are not used again. */ - revision: number +/** What a store's tiles are, where they come from, and how one is drawn in a style. */ +export interface TileSource { + /** Tells layers apart; a layer that changes on hotload carries its revision here, so older tiles are not used again. */ + layerKey(layer: Layer): string + fetch(address: TileAddress, layer: Layer, signal: AbortSignal): Promise + bytesOf(tile: Tile): number + styleKey(style: Style): string + pixels(tile: Tile, style: Style): ImageData } -interface StoredTile { - tile: MapTile +interface StoredTile { + tile: Tile bytes: number lastUsed: number picture: HTMLCanvasElement | null @@ -27,32 +24,30 @@ const MAXIMUM_IN_FLIGHT = 6 const CACHE_BYTES = 256 * 1024 * 1024 /** - * The map's tiles: fetched from the bridge as the view needs them, kept within a memory budget, and drawn as the - * current style asks. A tile that leaves the view before it arrives is not fetched. + * Tiles fetched from the bridge as a view needs them, kept within a memory budget, and drawn as the current style + * asks. A tile that leaves the view before it arrives is not fetched. */ -export class TileStore { - private readonly tiles = new Map() +export class TileStore { + private readonly tiles = new Map>() private readonly inFlight = new Map() /** Asked for again only after a refresh, which changes every key, so a broken tile is not fetched on every frame. */ private readonly failed = new Set() - private wanted: { key: string; address: TileAddress; layer: TileLayer }[] = [] + private wanted: { key: string; address: TileAddress; layer: Layer }[] = [] private storedBytes = 0 private useClock = 0 constructor( - private readonly client: BridgeClient, - private readonly tileSize: number, + private readonly source: TileSource, private readonly onChange: () => void, private readonly onError: (message: string) => void ) {} - key(address: TileAddress, layer: TileLayer): string { - const parts = [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise] - return `${parts.join('/')}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}` + key(address: TileAddress, layer: Layer): string { + return `${this.source.layerKey(layer)}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}` } /** The tile if it has arrived, marked as just used. */ - get(address: TileAddress, layer: TileLayer): MapTile | null { + get(address: TileAddress, layer: Layer): Tile | null { const stored = this.tiles.get(this.key(address, layer)) if (stored === undefined) { return null @@ -62,23 +57,23 @@ export class TileStore { } /** The tile drawn in {@code style}; restyled only when the style changed since it was last drawn. */ - picture(address: TileAddress, layer: TileLayer, style: TileStyle): HTMLCanvasElement | null { + picture(address: TileAddress, layer: Layer, style: Style): HTMLCanvasElement | null { const stored = this.tiles.get(this.key(address, layer)) if (stored === undefined) { return null } stored.lastUsed = ++this.useClock - const wantedStyle = styleKey(style) + const wantedStyle = this.source.styleKey(style) if (stored.picture === null || stored.pictureStyle !== wantedStyle) { stored.picture = stored.picture ?? document.createElement('canvas') - paint(stored.picture, stored.tile, style) + paint(stored.picture, this.source.pixels(stored.tile, style)) stored.pictureStyle = wantedStyle } return stored.picture } /** Fetches the tiles the view shows, in the order given, and gives up on the ones it no longer shows. */ - want(addresses: TileAddress[], layer: TileLayer): void { + want(addresses: TileAddress[], layer: Layer): void { this.wanted = addresses .map((address) => ({ key: this.key(address, layer), address, layer })) .filter((entry) => !this.tiles.has(entry.key) && !this.failed.has(entry.key)) @@ -119,12 +114,11 @@ export class TileStore { } } - private fetchTile(key: string, address: TileAddress, layer: TileLayer): void { + private fetchTile(key: string, address: TileAddress, layer: Layer): void { const controller = new AbortController() this.inFlight.set(key, controller) - const request = { ...layer, ...address, size: this.tileSize } - this.client - .tile(request, controller.signal) + this.source + .fetch(address, layer, controller.signal) .then((tile) => this.store(key, tile)) .catch((error: unknown) => { if (!controller.signal.aborted) { @@ -142,8 +136,8 @@ export class TileStore { }) } - private store(key: string, tile: MapTile): void { - const bytes = tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + tile.size * tile.size * 4 + private store(key: string, tile: Tile): void { + const bytes = this.source.bytesOf(tile) this.tiles.set(key, { tile, bytes, lastUsed: ++this.useClock, picture: null, pictureStyle: '' }) this.storedBytes += bytes this.evictOldest() @@ -164,8 +158,8 @@ export class TileStore { } } -function paint(canvas: HTMLCanvasElement, tile: MapTile, style: TileStyle): void { - canvas.width = tile.size - canvas.height = tile.size - canvas.getContext('2d')!.putImageData(new ImageData(stylePixels(tile, style), tile.size, tile.size), 0, 0) +function paint(canvas: HTMLCanvasElement, pixels: ImageData): void { + canvas.width = pixels.width + canvas.height = pixels.height + canvas.getContext('2d')!.putImageData(pixels, 0, 0) } diff --git a/src/renderer/src/map/heightColors.ts b/src/renderer/src/map/heightColors.ts index 60c364b0a..de14ad17e 100644 --- a/src/renderer/src/map/heightColors.ts +++ b/src/renderer/src/map/heightColors.ts @@ -1,7 +1,7 @@ /** The height scale of the map, from deep water to snowy peaks, measured from sea level (v3e HeightColors). */ -const DEEPEST_BELOW_SEA_BLOCKS = 90 -const HIGHEST_ABOVE_SEA_BLOCKS = 300 +export const DEEPEST_BELOW_SEA_BLOCKS = 90 +export const HIGHEST_ABOVE_SEA_BLOCKS = 300 const DEPTH_BLOCKS = [0, 10, 40, DEEPEST_BELOW_SEA_BLOCKS] const DEPTH_COLORS = [0x7db8d8, 0x4c8dba, 0x2a5e8f, 0x15304f] const ABOVE_SEA_BLOCKS = [0, 8, 30, 70, 130, 200, HIGHEST_ABOVE_SEA_BLOCKS] diff --git a/src/renderer/src/map/mapTileSource.ts b/src/renderer/src/map/mapTileSource.ts new file mode 100644 index 000000000..fc8c0bf7a --- /dev/null +++ b/src/renderer/src/map/mapTileSource.ts @@ -0,0 +1,26 @@ +import type { BridgeClient } from '../bridge/BridgeClient' +import type { MapTile } from '../bridge/types' +import { stylePixels, styleKey, type TileStyle } from './tileStyle' +import type { TileSource } from './TileStore' + +/** What one map tile request needs besides where the tile is. */ +export interface TileLayer { + view: string + /** The region the region view previews everywhere, or null for the world as it is. */ + preview: string | null + heights: boolean + pickNoise: boolean + /** Bumped when the pack is hotloaded, so older tiles are not used again. */ + revision: number +} + +/** The world map's tiles: the engine's streams, drawn in the map's styles. */ +export function mapTileSource(client: BridgeClient, tileSize: number): TileSource { + return { + layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise].join('/'), + fetch: (address, layer, signal) => client.tile({ ...layer, ...address, size: tileSize }, signal), + bytesOf: (tile) => tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + tile.size * tile.size * 4, + styleKey, + pixels: (tile, style) => new ImageData(stylePixels(tile, style), tile.size, tile.size) + } +} diff --git a/src/renderer/src/map/tileDrawing.ts b/src/renderer/src/map/tileDrawing.ts new file mode 100644 index 000000000..ac3b9545a --- /dev/null +++ b/src/renderer/src/map/tileDrawing.ts @@ -0,0 +1,82 @@ +import { coarserTile, previewsFor, visibleTiles, worldToScreenX, worldToScreenZ, type TileAddress, type Viewport } from './viewport' + +// While a tile is on its way, a coarser one already drawn stands in, up to this many zoom levels out. +const COARSER_FALLBACK_LEVELS = 6 + +export interface DrawnTiles { + /** Every tile the view covers, nearest the centre first. */ + tiles: TileAddress[] + ready: number + /** What to fetch, in order: a coarser preview for each blank stretch first, then the tiles themselves. */ + wanted: TileAddress[] +} + +/** + * Draws the tiles covering the view at {@code renderScale}, from {@code pictureOf}; where one hasn't arrived, the part + * of a coarser one that covers it. + */ +export function drawVisibleTiles( + context: CanvasRenderingContext2D, + view: Viewport, + renderScale: number, + tileSize: number, + pictureOf: (address: TileAddress) => HTMLCanvasElement | null +): DrawnTiles { + const tiles = visibleTiles(view, renderScale, tileSize) + context.imageSmoothingEnabled = view.blocksPerPixel > renderScale + let ready = 0 + const blank: TileAddress[] = [] + for (const address of tiles) { + const picture = pictureOf(address) + if (picture !== null) { + drawTile(context, view, tileSize, picture, address, 0, 0, picture.width) + ready++ + } else if (!drawFallback(context, view, tileSize, address, pictureOf)) { + blank.push(address) + } + } + return { tiles, ready, wanted: [...previewsFor(blank), ...tiles] } +} + +/** Draws the part of a tile picture from (sourceX, sourceZ), {@code sourceSize} pixels wide, over {@code address}. */ +function drawTile( + context: CanvasRenderingContext2D, + view: Viewport, + tileSize: number, + picture: HTMLCanvasElement, + address: TileAddress, + sourceX: number, + sourceZ: number, + sourceSize: number +): void { + const span = tileSize * address.blocksPerPixel + const left = Math.round(worldToScreenX(view, address.tileX * span)) + const top = Math.round(worldToScreenZ(view, address.tileZ * span)) + const right = Math.round(worldToScreenX(view, (address.tileX + 1) * span)) + const bottom = Math.round(worldToScreenZ(view, (address.tileZ + 1) * span)) + context.drawImage(picture, sourceX, sourceZ, sourceSize, sourceSize, left, top, right - left, bottom - top) +} + +/** Draws the part of a coarser tile that covers {@code address}; false when no coarser tile has arrived either. */ +function drawFallback( + context: CanvasRenderingContext2D, + view: Viewport, + tileSize: number, + address: TileAddress, + pictureOf: (address: TileAddress) => HTMLCanvasElement | null +): boolean { + for (let levels = 1; levels <= COARSER_FALLBACK_LEVELS; levels++) { + const coarser = coarserTile(address, levels) + const picture = pictureOf(coarser) + if (picture === null) { + continue + } + const factor = 2 ** levels + const sourceSize = picture.width / factor + const sourceX = (address.tileX - coarser.tileX * factor) * sourceSize + const sourceZ = (address.tileZ - coarser.tileZ * factor) * sourceSize + drawTile(context, view, tileSize, picture, address, sourceX, sourceZ, sourceSize) + return true + } + return false +} diff --git a/src/renderer/src/map/viewport.ts b/src/renderer/src/map/viewport.ts index 8fd0a5254..c243ff9ac 100644 --- a/src/renderer/src/map/viewport.ts +++ b/src/renderer/src/map/viewport.ts @@ -43,9 +43,13 @@ export function worldToScreenZ(view: Viewport, worldZ: number): number { * The scale tiles are drawn at for a view: the nearest power of two to one tile pixel per device pixel, so tiles stay * sharp on dense screens and every zoom between two levels reuses the same tiles. */ -export function renderBlocksPerPixel(viewBlocksPerPixel: number, devicePixelRatio: number): number { +export function renderBlocksPerPixel( + viewBlocksPerPixel: number, + devicePixelRatio: number, + finestBlocksPerPixel = MINIMUM_RENDER_BLOCKS_PER_PIXEL +): number { const level = 2 ** Math.round(Math.log2(viewBlocksPerPixel / devicePixelRatio)) - return Math.min(MAXIMUM_BLOCKS_PER_PIXEL, Math.max(MINIMUM_RENDER_BLOCKS_PER_PIXEL, level)) + return Math.min(MAXIMUM_BLOCKS_PER_PIXEL, Math.max(finestBlocksPerPixel, level)) } /** The tiles covering the view, nearest the centre first so the middle of the screen fills in first. */ diff --git a/src/renderer/src/noise/NoiseController.ts b/src/renderer/src/noise/NoiseController.ts new file mode 100644 index 000000000..ca8a71d96 --- /dev/null +++ b/src/renderer/src/noise/NoiseController.ts @@ -0,0 +1,206 @@ +import type { BridgeClient } from '../bridge/BridgeClient' +import type { NoiseTile } from '../bridge/types' +import { drawVisibleTiles } from '../map/tileDrawing' +import { TileStore, type TileSource } from '../map/TileStore' +import { clampBlocksPerPixel, renderBlocksPerPixel, screenToWorldX, screenToWorldZ, type TileAddress, type Viewport } from '../map/viewport' +import type { NoiseScale } from './noiseScale' + +/** Which noise the tiles hold. */ +export interface NoiseLayer { + sourceId: string + /** A 64 bit seed, as text so no digit is lost. */ + seed: string + /** Bumped when the pack is hotloaded, so older tiles are not used again. */ + revision: number +} + +export interface NoiseStyle { + /** Tells styles apart, so a tile is recoloured only when its style changed. */ + key: string + scale: NoiseScale +} + +export interface NoiseStatus { + blocksPerPixel: number + tilesReady: number + tilesTotal: number + cursorX: number + cursorZ: number + /** The noise at the cursor, or null before its tile arrived. */ + value: number | null +} + +export interface NoiseListener { + onStatus(status: NoiseStatus): void + onError(message: string): void +} + +export const NOISE_TILE_PIXELS = 128 +const DEFAULT_NOISE_BLOCKS_PER_PIXEL = 1 +// Noise has detail finer than a block, so it is drawn finer than the world map's one block per pixel. +const FINEST_NOISE_BLOCKS_PER_PIXEL = 1 / 16 + +function noiseTileSource(client: BridgeClient): TileSource { + return { + layerKey: (layer) => `${layer.revision}/${layer.sourceId}/${layer.seed}`, + fetch: (address, layer, signal) => + client.noiseTile(layer.sourceId, layer.seed, address.tileX, address.tileZ, address.blocksPerPixel, NOISE_TILE_PIXELS, signal), + bytesOf: (tile) => tile.values.byteLength + tile.size * tile.size * 4, + styleKey: (style) => style.key, + pixels: (tile, style) => noisePixels(tile, style.scale) + } +} + +function noisePixels(tile: NoiseTile, scale: NoiseScale): ImageData { + const pixels = new ImageData(tile.size, tile.size) + for (let index = 0; index < tile.values.length; index++) { + const color = scale.colorOf(tile.values[index]) + pixels.data[index * 4] = (color >> 16) & 0xff + pixels.data[index * 4 + 1] = (color >> 8) & 0xff + pixels.data[index * 4 + 2] = color & 0xff + pixels.data[index * 4 + 3] = 0xff + } + return pixels +} + +/** The noise from above on a canvas, fetched in tiles as the view moves. Kept outside React, as it redraws on every drag. */ +export class NoiseController { + private readonly context: CanvasRenderingContext2D + private readonly store: TileStore + private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_NOISE_BLOCKS_PER_PIXEL, width: 1, height: 1 } + private layer: NoiseLayer | null = null + private style: NoiseStyle | null = null + private cursor: { x: number; y: number } | null = null + private lastReady = 0 + private lastTotal = 0 + private frameRequested = false + private closed = false + + constructor( + private readonly canvas: HTMLCanvasElement, + client: BridgeClient, + private readonly listener: NoiseListener + ) { + this.context = canvas.getContext('2d')! + this.store = new TileStore(noiseTileSource(client), () => this.redraw(), (message) => listener.onError(message)) + } + + close(): void { + this.closed = true + this.store.clear() + } + + resize(width: number, height: number): void { + const ratio = window.devicePixelRatio + this.canvas.width = Math.round(width * ratio) + this.canvas.height = Math.round(height * ratio) + this.view.width = width + this.view.height = height + this.redraw() + } + + show(layer: NoiseLayer | null, style: NoiseStyle): void { + this.layer = layer + this.style = style + this.redraw() + } + + panBy(screenDeltaX: number, screenDeltaZ: number): void { + this.view.centerX -= screenDeltaX * this.view.blocksPerPixel + this.view.centerZ -= screenDeltaZ * this.view.blocksPerPixel + this.redraw() + } + + /** Zooms by {@code factor} (above 1 zooms in) keeping the spot under the screen point where it is. */ + zoomAt(factor: number, screenX = this.view.width / 2, screenZ = this.view.height / 2): void { + const worldX = screenToWorldX(this.view, screenX) + const worldZ = screenToWorldZ(this.view, screenZ) + this.view.blocksPerPixel = clampBlocksPerPixel(this.view.blocksPerPixel / factor) + this.view.centerX = worldX - (screenX - this.view.width / 2) * this.view.blocksPerPixel + this.view.centerZ = worldZ - (screenZ - this.view.height / 2) * this.view.blocksPerPixel + this.redraw() + } + + resetView(): void { + this.view.centerX = 0 + this.view.centerZ = 0 + this.view.blocksPerPixel = DEFAULT_NOISE_BLOCKS_PER_PIXEL + this.redraw() + } + + setCursor(cursor: { x: number; y: number } | null): void { + this.cursor = cursor + this.reportStatus() + } + + /** Where the view looks and the scale its tiles are drawn at, for the 3D view to sample the same noise. */ + framing(): { centerX: number; centerZ: number; renderScale: number } { + return { centerX: this.view.centerX, centerZ: this.view.centerZ, renderScale: this.renderScale() } + } + + private renderScale(): number { + return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio, FINEST_NOISE_BLOCKS_PER_PIXEL) + } + + private redraw(): void { + if (this.frameRequested || this.closed) { + return + } + this.frameRequested = true + requestAnimationFrame(() => { + this.frameRequested = false + if (!this.closed) { + this.draw() + } + }) + } + + private draw(): void { + const ratio = window.devicePixelRatio + const context = this.context + context.setTransform(ratio, 0, 0, ratio, 0, 0) + context.fillStyle = getComputedStyle(this.canvas).getPropertyValue('--map-background') || '#16171a' + context.fillRect(0, 0, this.view.width, this.view.height) + const layer = this.layer + const style = this.style + if (layer === null || style === null) { + this.reportStatus(0, 0) + return + } + const drawn = drawVisibleTiles(context, this.view, this.renderScale(), NOISE_TILE_PIXELS, (address) => this.store.picture(address, layer, style)) + this.store.want(drawn.wanted, layer) + this.reportStatus(drawn.ready, drawn.tiles.length) + } + + private valueAt(worldX: number, worldZ: number): number | null { + if (this.layer === null) { + return null + } + const scale = this.renderScale() + const span = NOISE_TILE_PIXELS * scale + const address: TileAddress = { tileX: Math.floor(worldX / span), tileZ: Math.floor(worldZ / span), blocksPerPixel: scale } + const tile = this.store.get(address, this.layer) + if (tile === null) { + return null + } + const pixelX = Math.min(tile.size - 1, Math.floor((worldX - address.tileX * span) / scale)) + const pixelZ = Math.min(tile.size - 1, Math.floor((worldZ - address.tileZ * span) / scale)) + return tile.values[pixelZ * tile.size + pixelX] + } + + private reportStatus(ready = this.lastReady, total = this.lastTotal): void { + this.lastReady = ready + this.lastTotal = total + const cursor = this.cursor ?? { x: this.view.width / 2, y: this.view.height / 2 } + const worldX = screenToWorldX(this.view, cursor.x) + const worldZ = screenToWorldZ(this.view, cursor.y) + this.listener.onStatus({ + blocksPerPixel: this.view.blocksPerPixel, + tilesReady: ready, + tilesTotal: total, + cursorX: worldX, + cursorZ: worldZ, + value: this.valueAt(worldX, worldZ) + }) + } +} diff --git a/src/renderer/src/noise/noise.test.ts b/src/renderer/src/noise/noise.test.ts new file mode 100644 index 000000000..1b6c6abed --- /dev/null +++ b/src/renderer/src/noise/noise.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import type { NoiseSource } from '../bridge/types' +import { heightColor } from '../map/heightColors' +import { INVALID_NOISE_COLOR, noiseScale } from './noiseScale' +import { NoiseTerrain } from './noiseTerrain' + +const UNIT_NOISE: NoiseSource = { id: 'style:SIMPLEX', name: 'Simplex', category: 'Simplex', usesSeed: true, blockRange: null } +const BLOCK_NOISE: NoiseSource = { id: 'world:overlay', name: 'Overlay noise', category: 'Pack generators', usesSeed: false, blockRange: { lowest: -20, highest: 40 } } + +describe('noise scale', () => { + it('spans the palette for noise of 0 to 1 and takes its end colours past it', () => { + const terrain = noiseScale('terrain', UNIT_NOISE) + expect([terrain.minimum, terrain.maximum]).toEqual([0, 1]) + expect(terrain.colorOf(0)).toBe(0x071a2f) + expect(terrain.colorOf(1)).toBe(0xf4f1de) + expect(terrain.colorOf(7)).toBe(0xf4f1de) + expect(noiseScale('signed', UNIT_NOISE).minimum).toBe(-1) + }) + + it('spans the block range for noise in blocks, coloured as heights above the fluid', () => { + const height = noiseScale('height', BLOCK_NOISE) + expect([height.minimum, height.maximum]).toEqual([-20, 40]) + expect(height.colorOf(-20)).toBe(heightColor(-20, 0)) + expect(height.colorOf(40)).toBe(heightColor(40, 0)) + }) + + it('marks a value the noise could not give', () => { + expect(noiseScale('grayscale', UNIT_NOISE).colorOf(Number.NaN)).toBe(INVALID_NOISE_COLOR) + }) +}) + +describe('noise terrain', () => { + const area = (values: number[]) => ({ tiles: [[{ size: 2, values: Float32Array.from(values) }]], originX: 10, originZ: 20, blocksPerValue: 4 }) + + it('raises noise of 0 to 1 to the relief, without water', () => { + const terrain = new NoiseTerrain(area([0, 0.5, 1, Number.NaN]), UNIT_NOISE, noiseScale('terrain', UNIT_NOISE), 64) + expect([terrain.groundAt(0, 0), terrain.groundAt(1, 0), terrain.groundAt(0, 1), terrain.groundAt(1, 1)]).toEqual([0, 32, 64, null]) + expect(terrain.waterAt(0, 0)).toBeNull() + expect([terrain.worldX(1), terrain.worldZ(1)]).toEqual([14, 24]) + }) + + it('stands noise in blocks at its own height, under water below the fluid', () => { + const terrain = new NoiseTerrain(area([-5, 12, 0, 3]), BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64) + expect(terrain.groundAt(0, 0)).toBe(-5) + expect(terrain.waterAt(0, 0)).toBe(0) + expect(terrain.waterAt(1, 0)).toBeNull() + }) +}) diff --git a/src/renderer/src/noise/noiseScale.ts b/src/renderer/src/noise/noiseScale.ts new file mode 100644 index 000000000..4c5026bef --- /dev/null +++ b/src/renderer/src/noise/noiseScale.ts @@ -0,0 +1,81 @@ +import type { NoiseSource } from '../bridge/types' +import { DEEPEST_BELOW_SEA_BLOCKS, heightColor, HIGHEST_ABOVE_SEA_BLOCKS } from '../map/heightColors' + +export type NoisePaletteId = 'terrain' | 'signed' | 'grayscale' | 'height' | 'green' + +interface NoisePalette { + id: NoisePaletteId + label: string + minimum: number + maximum: number + /** Colours from the minimum to the maximum, evenly spaced; null for the map's height colours. */ + stops: number[] | null +} + +/** v3e's noise palettes, each with the values it spans when the noise is not measured in blocks. */ +export const NOISE_PALETTES: readonly NoisePalette[] = [ + { id: 'terrain', label: 'Terrain', minimum: 0, maximum: 1, stops: [0x071a2f, 0x155e75, 0x2a9d8f, 0xe9c46a, 0xf4f1de] }, + { id: 'signed', label: 'Signed', minimum: -1, maximum: 1, stops: [0x173b66, 0x4f86c6, 0xe7edf3, 0xe89555, 0x9d3b35] }, + { id: 'grayscale', label: 'Grayscale', minimum: 0, maximum: 1, stops: [0x050505, 0xffffff] }, + { id: 'height', label: 'Height', minimum: 0, maximum: 1, stops: null }, + { id: 'green', label: 'Green', minimum: 0, maximum: 1, stops: [0x2a3330, 0x5fd3a8] } +] + +/** The colour of a value the noise couldn't give, so it stands out from every palette. */ +export const INVALID_NOISE_COLOR = 0xff2daa +const LOOKUP_SIZE = 256 + +/** How values become colours: the span the palette covers, and the colour of a value. */ +export interface NoiseScale { + minimum: number + maximum: number + /** Over and under the span take the end colours. */ + colorOf(value: number): number + /** The colour a fraction of the way along the span, for the legend. */ + colorAlong(fraction: number): number +} + +/** + * The scale for a palette and a source: noise of 0 to 1 spans the palette's own range; noise in blocks spans its block + * range, and the height palette then colours it as the map colours heights above the fluid. + */ +export function noiseScale(paletteId: NoisePaletteId, source: NoiseSource | null): NoiseScale { + const palette = NOISE_PALETTES.find((candidate) => candidate.id === paletteId)! + const blocks = source?.blockRange ?? null + const minimum = blocks?.lowest ?? palette.minimum + const maximum = blocks?.highest ?? palette.maximum + const colorAlong = paletteColors(palette, blocks === null ? null : [blocks.lowest, blocks.highest]) + const span = maximum - minimum + return { + minimum, + maximum, + colorAlong, + colorOf: (value) => (Number.isFinite(value) ? colorAlong(span <= 0 ? 0.5 : (value - minimum) / span) : INVALID_NOISE_COLOR) + } +} + +function paletteColors(palette: NoisePalette, blockSpan: [number, number] | null): (fraction: number) => number { + if (palette.stops === null) { + const [lowest, highest] = blockSpan ?? [-DEEPEST_BELOW_SEA_BLOCKS, HIGHEST_ABOVE_SEA_BLOCKS] + return (fraction) => heightColor(lowest + (highest - lowest) * clampUnit(fraction), 0) + } + const lookup = lookupOf(palette.stops) + return (fraction) => lookup[Math.round(clampUnit(fraction) * (LOOKUP_SIZE - 1))] +} + +function lookupOf(stops: number[]): number[] { + return Array.from({ length: LOOKUP_SIZE }, (_, index) => { + const position = (index / (LOOKUP_SIZE - 1)) * (stops.length - 1) + const lower = Math.min(stops.length - 2, Math.floor(position)) + return mix(stops[lower], stops[lower + 1], position - lower) + }) +} + +function mix(from: number, to: number, fraction: number): number { + const channel = (shift: number): number => Math.round(((from >>> shift) & 0xff) + (((to >>> shift) & 0xff) - ((from >>> shift) & 0xff)) * fraction) + return (channel(16) << 16) | (channel(8) << 8) | channel(0) +} + +function clampUnit(fraction: number): number { + return Math.min(1, Math.max(0, fraction)) +} diff --git a/src/renderer/src/noise/noiseTerrain.ts b/src/renderer/src/noise/noiseTerrain.ts new file mode 100644 index 000000000..173c2b74e --- /dev/null +++ b/src/renderer/src/noise/noiseTerrain.ts @@ -0,0 +1,73 @@ +import type { NoiseSource, NoiseTile } from '../bridge/types' +import type { TerrainSurface } from '../scene/terrainMesh' +import type { NoiseScale } from './noiseScale' + +/** A square of noise tiles, row by row from the north west, and the block its first value is taken at. */ +export interface NoiseArea { + tiles: NoiseTile[][] + originX: number + originZ: number + blocksPerValue: number +} + +// The fluid of noise measured in blocks lies at its zero, as the world adds the overlay above its fluid height. +const FLUID_BLOCKS = 0 + +/** + * Noise as terrain (v3e's 3D noise): noise measured in blocks stands at its own height with water at the fluid; + * other noise rises from its scale's minimum to {@code reliefBlocks} at its maximum, with no water. + */ +export class NoiseTerrain implements TerrainSurface { + readonly columns: number + readonly rows: number + private readonly tileSize: number + + constructor( + private readonly area: NoiseArea, + private readonly source: NoiseSource, + private readonly scale: NoiseScale, + private readonly reliefBlocks: number + ) { + this.tileSize = area.tiles[0][0].size + this.rows = area.tiles.length * this.tileSize + this.columns = area.tiles[0].length * this.tileSize + } + + worldX(column: number): number { + return this.area.originX + column * this.area.blocksPerValue + } + + worldZ(row: number): number { + return this.area.originZ + row * this.area.blocksPerValue + } + + groundAt(column: number, row: number): number | null { + const value = this.valueAt(column, row) + return Number.isFinite(value) ? this.heightOf(value) : null + } + + waterAt(column: number, row: number): number | null { + if (this.source.blockRange === null) { + return null + } + const ground = this.groundAt(column, row) + return ground !== null && ground < FLUID_BLOCKS ? FLUID_BLOCKS : null + } + + colorAt(column: number, row: number): number { + return this.scale.colorOf(this.valueAt(column, row)) + } + + private heightOf(value: number): number { + if (this.source.blockRange !== null) { + return value + } + const span = this.scale.maximum - this.scale.minimum + return ((value - this.scale.minimum) / span) * this.reliefBlocks + } + + private valueAt(column: number, row: number): number { + const tile = this.area.tiles[Math.floor(row / this.tileSize)][Math.floor(column / this.tileSize)] + return tile.values[(row % this.tileSize) * tile.size + (column % this.tileSize)] + } +} diff --git a/src/renderer/src/studio/MapStudio.tsx b/src/renderer/src/studio/MapStudio.tsx index 8a9b8160a..5d43af44f 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 { NoiseStudio } from './NoiseStudio' import { SavedWorldStudio } from './SavedWorldStudio' import { SceneStudio } from './SceneStudio' import { WorldStudio3D } from './WorldStudio3D' @@ -61,7 +62,7 @@ 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(() => [...withAppViews(world.views), ...sceneViews.map(asViewInfo)], [world.views, sceneViews]) + const views = useMemo(() => [...withAppViews(world.views), ...sceneViews.map(asViewInfo), NOISE], [world.views, sceneViews]) const sceneView = sceneViews.find((candidate) => candidate.id === viewId) ?? null const showsMap = sceneView === null && !APP_VIEW_IDS.has(viewId) const view = views.find((candidate) => candidate.id === viewId) ?? views[0] @@ -221,6 +222,8 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps ) : viewId === SAVED_WORLD.id ? ( + ) : viewId === NOISE.id ? ( + ) : ( <>
@@ -298,7 +301,14 @@ const SAVED_WORLD: ViewInfo = { group: 'WORLD', groupLabel: 'World' } -const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id]) +const NOISE: ViewInfo = { + id: 'noise', + label: 'Noise', + description: "The pack's generators and expressions and the built-in noise styles, from above or as terrain", + group: 'PACK', + groupLabel: 'Pack' +} +const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id, NOISE.id]) function withAppViews(serverViews: ViewInfo[]): ViewInfo[] { const afterHeight = serverViews.findIndex((candidate) => candidate.id === 'height') + 1 diff --git a/src/renderer/src/studio/NoiseCanvas.tsx b/src/renderer/src/studio/NoiseCanvas.tsx new file mode 100644 index 000000000..49621ac93 --- /dev/null +++ b/src/renderer/src/studio/NoiseCanvas.tsx @@ -0,0 +1,82 @@ +import { useEffect, useRef } from 'react' +import type { BridgeClient } from '../bridge/BridgeClient' +import { NoiseController, type NoiseListener } from '../noise/NoiseController' + +interface NoiseCanvasProps { + client: BridgeClient + controllerRef: React.RefObject + listener: NoiseListener + className?: string +} + +// One wheel notch is about 100; this zooms about 15% per notch, and smoothly on touchpads. +const WHEEL_ZOOM_PER_DELTA = 0.002 + +/** The noise from above: drag to move, wheel to zoom. */ +export function NoiseCanvas({ client, controllerRef, listener, className }: NoiseCanvasProps): React.JSX.Element { + const canvasRef = useRef(null) + const latestListener = useRef(listener) + latestListener.current = listener + + useEffect(() => { + const canvas = canvasRef.current! + const noise = new NoiseController(canvas, client, { + onStatus: (status) => latestListener.current.onStatus(status), + onError: (message) => latestListener.current.onError(message) + }) + controllerRef.current = noise + const resize = new ResizeObserver(([entry]) => noise.resize(entry.contentRect.width, entry.contentRect.height)) + resize.observe(canvas) + const stopMouse = followMouse(canvas, noise) + return () => { + stopMouse() + resize.disconnect() + noise.close() + controllerRef.current = null + } + }, [client, controllerRef]) + + return +} + +function followMouse(canvas: HTMLCanvasElement, noise: NoiseController): () => void { + let last: { x: number; y: number } | null = null + const pointOf = (event: MouseEvent): { x: number; y: number } => { + const bounds = canvas.getBoundingClientRect() + return { x: event.clientX - bounds.left, y: event.clientY - bounds.top } + } + const down = (event: PointerEvent): void => { + if (event.button === 0) { + canvas.setPointerCapture(event.pointerId) + last = { x: event.clientX, y: event.clientY } + } + } + const move = (event: PointerEvent): void => { + noise.setCursor(pointOf(event)) + if (last !== null) { + noise.panBy(event.clientX - last.x, event.clientY - last.y) + last = { x: event.clientX, y: event.clientY } + } + } + const up = (): void => { + last = null + } + const leave = (): void => noise.setCursor(null) + const wheel = (event: WheelEvent): void => { + event.preventDefault() + const point = pointOf(event) + noise.zoomAt(2 ** (-event.deltaY * WHEEL_ZOOM_PER_DELTA), point.x, point.y) + } + canvas.addEventListener('pointerdown', down) + canvas.addEventListener('pointermove', move) + canvas.addEventListener('pointerup', up) + canvas.addEventListener('pointerleave', leave) + canvas.addEventListener('wheel', wheel, { passive: false }) + return () => { + canvas.removeEventListener('pointerdown', down) + canvas.removeEventListener('pointermove', move) + canvas.removeEventListener('pointerup', up) + canvas.removeEventListener('pointerleave', leave) + canvas.removeEventListener('wheel', wheel) + } +} diff --git a/src/renderer/src/studio/NoiseStudio.tsx b/src/renderer/src/studio/NoiseStudio.tsx new file mode 100644 index 000000000..7fe0d1e49 --- /dev/null +++ b/src/renderer/src/studio/NoiseStudio.tsx @@ -0,0 +1,348 @@ +import { Dices, RotateCcw, Search } from 'lucide-react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { ScrollArea } from '@/components/ui/scroll-area' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import { cn } from '@/lib/utils' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { NoiseSource, NoiseTile } from '../bridge/types' +import { NOISE_TILE_PIXELS, type NoiseController, type NoiseStatus } from '../noise/NoiseController' +import { NOISE_PALETTES, noiseScale, type NoisePaletteId, type NoiseScale } from '../noise/noiseScale' +import { NoiseTerrain, type NoiseArea } from '../noise/noiseTerrain' +import { buildTerrainMesh } from '../scene/terrainMesh' +import { hexColor } from './colors' +import { NoiseCanvas } from './NoiseCanvas' +import { SceneViewport } from './SceneViewport' + +type NoiseDisplay = 'flat' | 'terrain' + +const NUMBER = new Intl.NumberFormat('en-US', { maximumFractionDigits: 3 }) +const DEFAULT_SEED = '12345' +const TERRAIN_TILES_PER_SIDE = 4 +const LOWEST_RELIEF_BLOCKS = 1 +const TALLEST_RELIEF_BLOCKS = 4064 +const DEFAULT_RELIEF_BLOCKS = 64 +const RELIEF_STEPS = 1000 +const SWATCH_STEPS = 24 +const TOGGLE_ITEM = 'h-7 px-3 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground' +const PILL = 'pointer-events-none absolute rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text' + +interface NoiseStudioProps { + client: BridgeClient + packRevision: number + onSummary(summary: string | null): void + tell(message: string): void +} + +/** The pack's noise and the built-in styles, from above or as terrain (v3e's noise explorer). */ +export function NoiseStudio({ client, packRevision, onSummary, tell }: NoiseStudioProps): React.JSX.Element { + const sources = useNoiseSources(client, packRevision, tell) + const [chosenId, setChosenId] = useState(null) + const source = sources.find((candidate) => candidate.id === chosenId) ?? sources[0] ?? null + const [seed, setSeed] = useState(DEFAULT_SEED) + const [paletteId, setPaletteId] = useState('terrain') + const [display, setDisplay] = useState('flat') + const [reliefBlocks, setReliefBlocks] = useState(DEFAULT_RELIEF_BLOCKS) + const [status, setStatus] = useState(null) + const [terrainFraming, setTerrainFraming] = useState(null) + const controllerRef = useRef(null) + const scale = useMemo(() => noiseScale(paletteId, source), [paletteId, source]) + const listener = useMemo(() => ({ onStatus: setStatus, onError: tell }), [tell]) + + useEffect(() => { + const layer = source === null ? null : { sourceId: source.id, seed, revision: packRevision } + controllerRef.current?.show(layer, { key: `${paletteId}/${source?.blockRange?.lowest}/${source?.blockRange?.highest}`, scale }) + }, [source, seed, packRevision, paletteId, scale]) + + const showAs = useCallback((next: NoiseDisplay) => { + setDisplay(next) + if (next === 'terrain') { + setTerrainFraming(controllerRef.current?.framing() ?? null) + } + }, []) + + useEffect(() => { + if (source === null) { + onSummary(null) + return + } + const seedText = source.usesSeed ? `seed ${seed}` : "the world's seed" + onSummary(`${source.name} · ${seedText}`) + }, [source, seed, onSummary]) + useEffect(() => () => onSummary(null), [onSummary]) + + return ( + <> +
+ + {display === 'terrain' && source !== null && terrainFraming !== null && ( + + )} +
+ value !== '' && showAs(value as NoiseDisplay)}> + + 2D + + + 3D + + + {display === 'flat' && ( + + )} + {display === 'terrain' && source?.blockRange === null && } +
+ {display === 'flat' && status !== null && source !== null &&
{readout(status, source)}
} +
+ + + ) +} + +function readout(status: NoiseStatus, source: NoiseSource): string { + const spot = `${Math.floor(status.cursorX)}, ${Math.floor(status.cursorZ)}` + if (status.value === null) { + return spot + } + const value = NUMBER.format(status.value) + return `${spot} · ${source.blockRange === null ? value : `${value} blocks`}` +} + +function SeedField({ seed, usesSeed, onChange }: { seed: string; usesSeed: boolean; onChange(seed: string): void }): React.JSX.Element { + const [draft, setDraft] = useState(seed) + useEffect(() => setDraft(seed), [seed]) + const commit = (): void => { + const trimmed = draft.trim() + if (/^-?\d{1,19}$/.test(trimmed) && isLong(trimmed)) { + onChange(trimmed) + } else { + setDraft(seed) + } + } + return ( +
+

Seed

+
+ setDraft(event.target.value)} + onBlur={commit} + onKeyDown={(event) => event.key === 'Enter' && commit()} + /> + +
+ {!usesSeed &&

Keeps the world's seed

} +
+ ) +} + +const LONG_LIMIT = 2n ** 63n + +function isLong(text: string): boolean { + const value = BigInt(text) + return value >= -LONG_LIMIT && value < LONG_LIMIT +} + +function randomSeed(): string { + const [high, low] = crypto.getRandomValues(new Uint32Array(2)) + return BigInt.asIntN(64, (BigInt(high) << 32n) | BigInt(low)).toString() +} + +function PaletteList({ + current, + source, + scale, + onSelect +}: { + current: NoisePaletteId + source: NoiseSource | null + scale: NoiseScale + onSelect(palette: NoisePaletteId): void +}): React.JSX.Element { + return ( +
+

Palette

+ {NOISE_PALETTES.map((palette) => ( + + ))} +

+ {NUMBER.format(scale.minimum)} + {source?.blockRange === null ? '' : 'blocks above the fluid'} + {NUMBER.format(scale.maximum)} +

+
+ ) +} + +function gradientOf(scale: NoiseScale): string { + const stops = Array.from({ length: SWATCH_STEPS + 1 }, (_, step) => hexColor(scale.colorAlong(step / SWATCH_STEPS))) + return `linear-gradient(to right, ${stops.join(', ')})` +} + +function SourceList({ sources, current, onSelect }: { sources: NoiseSource[]; current: string | null; onSelect(id: string): void }): React.JSX.Element { + const [filter, setFilter] = useState('') + const shown = sources.filter((source) => source.name.toLowerCase().includes(filter.trim().toLowerCase())) + const categories = [...new Set(shown.map((source) => source.category))] + return ( +
+
+ + setFilter(event.target.value)} /> +
+ +
+ {categories.map((category) => ( +
+

{category}

+ {shown + .filter((source) => source.category === category) + .map((source) => ( + + ))} +
+ ))} + {shown.length === 0 &&

Nothing to show

} +
+
+
+ ) +} + +/** How many blocks the highest noise rises above the lowest, on a scale that gives low reliefs room. */ +function ReliefControl({ blocks, onChange }: { blocks: number; onChange(blocks: number): void }): React.JSX.Element { + const span = Math.log(TALLEST_RELIEF_BLOCKS) - Math.log(LOWEST_RELIEF_BLOCKS) + const step = Math.round(((Math.log(blocks) - Math.log(LOWEST_RELIEF_BLOCKS)) / span) * RELIEF_STEPS) + return ( + + ) +} + +interface TerrainFraming { + centerX: number + centerZ: number + renderScale: number +} + +function NoiseTerrainView({ + client, + source, + seed, + revision, + framing, + scale, + reliefBlocks, + tell +}: { + client: BridgeClient + source: NoiseSource + seed: string + revision: number + framing: TerrainFraming + scale: NoiseScale + reliefBlocks: number + tell(message: string): void +}): React.JSX.Element { + const area = useNoiseArea(client, source.id, seed, revision, framing, tell) + const mesh = useMemo(() => (area === null ? null : buildTerrainMesh(new NoiseTerrain(area, source, scale, reliefBlocks))), [area, source, scale, reliefBlocks]) + useEffect(() => () => mesh?.dispose(), [mesh]) + return ( +
+ + {area === null &&
Sampling {source.name}
} +
+ ) +} + +/** The square of tiles around where the 2D view looked, at the scale it drew; every tile arrives before it is shown. */ +function useNoiseArea( + client: BridgeClient, + sourceId: string, + seed: string, + revision: number, + framing: TerrainFraming, + tell: (message: string) => void +): NoiseArea | null { + const [area, setArea] = useState(null) + useEffect(() => { + const stop = new AbortController() + const tileBlocks = NOISE_TILE_PIXELS * framing.renderScale + const firstTileX = Math.floor(framing.centerX / tileBlocks - TERRAIN_TILES_PER_SIDE / 2) + const firstTileZ = Math.floor(framing.centerZ / tileBlocks - TERRAIN_TILES_PER_SIDE / 2) + const rows = Array.from({ length: TERRAIN_TILES_PER_SIDE }, (_, row) => + Promise.all( + Array.from({ length: TERRAIN_TILES_PER_SIDE }, (_, column) => + client.noiseTile(sourceId, seed, firstTileX + column, firstTileZ + row, framing.renderScale, NOISE_TILE_PIXELS, stop.signal) + ) + ) + ) + setArea(null) + Promise.all(rows) + .then((tiles: NoiseTile[][]) => + setArea({ tiles, originX: firstTileX * tileBlocks, originZ: firstTileZ * tileBlocks, blocksPerValue: framing.renderScale }) + ) + .catch((failure: Error) => !stop.signal.aborted && tell(failure.message)) + return () => stop.abort() + }, [client, sourceId, seed, revision, framing, tell]) + return area +} + +function useNoiseSources(client: BridgeClient, packRevision: number, tell: (message: string) => void): NoiseSource[] { + const [sources, setSources] = useState([]) + useEffect(() => { + let active = true + client + .noiseSources() + .then((found) => active && setSources(found)) + .catch((failure: Error) => active && tell(failure.message)) + return () => { + active = false + } + }, [client, packRevision, tell]) + return sources +} diff --git a/src/renderer/src/studio/ViewList.tsx b/src/renderer/src/studio/ViewList.tsx index 6db760567..5734c8cc2 100644 --- a/src/renderer/src/studio/ViewList.tsx +++ b/src/renderer/src/studio/ViewList.tsx @@ -1,4 +1,4 @@ -import { Box, Gem, Globe, HardDrive, Map as MapIcon, Mountain, Shapes, Sprout, Trees, Waves, type LucideIcon } from 'lucide-react' +import { AudioWaveform, 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' @@ -11,6 +11,7 @@ const VIEW_ICONS: Record = { height: Mountain, world3d: Globe, savedWorld: HardDrive, + noise: AudioWaveform, landBiomes: Sprout, seaBiomes: Waves, caveBiomes: Gem,