From 1aba4301539287da3a2871316ed8036a032efad6 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 02:39:48 +0100 Subject: [PATCH] Add the Palettes view Pattern views from the server get a view each: entries by biome with a search over names, a depth stepper, the entry's facts, and the blocks on screen. Tiles are a pixel per column from afar and each block's tinted top texture up close; spots a layer leaves empty read as nothing at this depth. The pan and zoom tile canvas the noise view had is now TiledView and TiledCanvas, shared by noise and palettes, and the entry list is shared with the scene views. --- src/renderer/src/bridge/BridgeClient.ts | 42 +++- .../src/bridge/patternDecoding.test.ts | 25 +++ src/renderer/src/bridge/patternDecoding.ts | 25 +++ src/renderer/src/bridge/types.ts | 28 ++- src/renderer/src/map/TiledView.ts | 188 ++++++++++++++++ src/renderer/src/noise/NoiseController.ts | 206 ----------------- src/renderer/src/noise/noiseTiles.ts | 77 +++++++ src/renderer/src/pattern/patternTiles.ts | 152 +++++++++++++ src/renderer/src/scene/blockColors.ts | 59 +++-- src/renderer/src/studio/EntryBrowser.tsx | 76 +++++++ src/renderer/src/studio/MapStudio.tsx | 31 ++- src/renderer/src/studio/NoiseStudio.tsx | 27 ++- src/renderer/src/studio/PatternStudio.tsx | 209 ++++++++++++++++++ src/renderer/src/studio/SceneStudio.tsx | 71 +----- .../{NoiseCanvas.tsx => TiledCanvas.tsx} | 46 ++-- src/renderer/src/studio/ViewList.tsx | 5 +- 16 files changed, 921 insertions(+), 346 deletions(-) create mode 100644 src/renderer/src/bridge/patternDecoding.test.ts create mode 100644 src/renderer/src/bridge/patternDecoding.ts create mode 100644 src/renderer/src/map/TiledView.ts delete mode 100644 src/renderer/src/noise/NoiseController.ts create mode 100644 src/renderer/src/noise/noiseTiles.ts create mode 100644 src/renderer/src/pattern/patternTiles.ts create mode 100644 src/renderer/src/studio/EntryBrowser.tsx create mode 100644 src/renderer/src/studio/PatternStudio.tsx rename src/renderer/src/studio/{NoiseCanvas.tsx => TiledCanvas.tsx} (56%) diff --git a/src/renderer/src/bridge/BridgeClient.ts b/src/renderer/src/bridge/BridgeClient.ts index be9774ac9..142a0b005 100644 --- a/src/renderer/src/bridge/BridgeClient.ts +++ b/src/renderer/src/bridge/BridgeClient.ts @@ -1,5 +1,6 @@ import type { BridgeConnection } from '../../../shared/bridge' import { decodeScene, type BlockScene } from '../scene/sceneDecoding' +import { decodePattern } from './patternDecoding' import { decodeSavedTile } from './savedTileDecoding' import { decodeTile } from './tileDecoding' import type { @@ -7,14 +8,16 @@ import type { MapLabel, MapTile, Marker, + ModuleViewInfo, NoiseSource, NoiseTile, + PatternEntry, + PatternTile, PickInspection, SavedStart, SavedTile, SavedWorldInfo, SceneEntry, - SceneViewInfo, WorldInfo } from './types' @@ -42,6 +45,17 @@ export interface TileRequest { pickNoise: boolean } +/** One tile of a pattern: tile (x, z) covers columns × blocksPerColumn blocks from x × that, z × that. */ +export interface PatternRequest { + viewId: string + key: string + depth: number + tileX: number + tileZ: number + blocksPerColumn: number + columns: number +} + /** What a map spot or area is asked about: a view, and the region it previews. */ export interface MapLayerQuery { view: string @@ -120,7 +134,7 @@ export class BridgeClient { } /** The scene views the pack's modules show, such as its objects. */ - sceneViews(): Promise { + sceneViews(): Promise { return this.json('scenes') } @@ -133,6 +147,30 @@ export class BridgeClient { return decodeScene(await response.arrayBuffer()) } + /** The pattern views the pack's modules show, such as its palettes. */ + patternViews(): Promise { + return this.json('patterns') + } + + patternEntries(viewId: string): Promise { + return this.json(`pattern-entries?${new URLSearchParams({ view: viewId })}`) + } + + /** What an entry places at {@code depth} below the top across one tile, a column every {@code blocksPerColumn} blocks. */ + async pattern(request: PatternRequest, signal: AbortSignal): Promise { + const query = new URLSearchParams({ + view: request.viewId, + key: request.key, + depth: String(request.depth), + x: String(request.tileX), + z: String(request.tileZ), + scale: String(request.blocksPerColumn), + size: String(request.columns) + }) + const response = await this.fetch(`pattern?${query}`, { signal }) + return decodePattern(await response.arrayBuffer()) + } + /** The worlds saved on the server's disk. */ savedWorlds(): Promise { return this.json('saved-worlds') diff --git a/src/renderer/src/bridge/patternDecoding.test.ts b/src/renderer/src/bridge/patternDecoding.test.ts new file mode 100644 index 000000000..7921cf6a3 --- /dev/null +++ b/src/renderer/src/bridge/patternDecoding.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest' +import { decodePattern } from './patternDecoding' +import { NO_PATTERN_BLOCK } from './types' + +function encodedPattern(header: object, picks: number[]): ArrayBuffer { + const headerBytes = new TextEncoder().encode(JSON.stringify(header)) + const picksAt = Math.ceil((4 + headerBytes.length) / 4) * 4 + const buffer = new ArrayBuffer(picksAt + picks.length * 2) + const view = new DataView(buffer) + view.setUint32(0, headerBytes.length, true) + new Uint8Array(buffer, 4).set(headerBytes) + picks.forEach((pick, index) => view.setInt16(picksAt + index * 2, pick, true)) + return buffer +} + +describe('decodePattern', () => { + it('reads the picks after the padded header, row by row, with no block as -1', () => { + const header = { columns: 2, blocksPerColumn: 4, blocks: ['minecraft:grass_block[snowy=false]', 'minecraft:dirt'], noBlock: -1 } + const pattern = decodePattern(encodedPattern(header, [0, -1, 1, 0])) + expect(pattern.columns).toBe(2) + expect(pattern.blocksPerColumn).toBe(4) + expect(pattern.blocks).toEqual(header.blocks) + expect([...pattern.picks]).toEqual([0, NO_PATTERN_BLOCK, 1, 0]) + }) +}) diff --git a/src/renderer/src/bridge/patternDecoding.ts b/src/renderer/src/bridge/patternDecoding.ts new file mode 100644 index 000000000..a31b0e434 --- /dev/null +++ b/src/renderer/src/bridge/patternDecoding.ts @@ -0,0 +1,25 @@ +import type { PatternTile } from './types' + +const ALIGNMENT_BYTES = 4 + +interface PatternHeader { + columns: number + blocksPerColumn: number + blocks: string[] +} + +/** + * Reads a pattern as the bridge writes it (PatternEncoding): a u32 header length, the JSON header, then from the next + * multiple of 4 bytes an i16 pick per column, row by row. The picks are a view into the buffer, not a copy. + */ +export function decodePattern(buffer: ArrayBuffer): PatternTile { + const headerLength = new DataView(buffer).getUint32(0, true) + const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as PatternHeader + const picksAt = Math.ceil((4 + headerLength) / ALIGNMENT_BYTES) * ALIGNMENT_BYTES + return { + columns: header.columns, + blocksPerColumn: header.blocksPerColumn, + blocks: header.blocks, + picks: new Int16Array(buffer, picksAt, header.columns * header.columns) + } +} diff --git a/src/renderer/src/bridge/types.ts b/src/renderer/src/bridge/types.ts index b3e256bbf..7b24d5887 100644 --- a/src/renderer/src/bridge/types.ts +++ b/src/renderer/src/bridge/types.ts @@ -18,8 +18,8 @@ export interface ViewInfo { groupLabel: string } -/** A view of block scenes a module of the pack shows, such as its objects (IrisApi SceneView). */ -export interface SceneViewInfo { +/** A studio view a module of the pack shows (IrisApi StudioView): block scenes such as its objects, or patterns such as its palettes. */ +export interface ModuleViewInfo { id: string label: string description: string @@ -33,6 +33,30 @@ export interface SceneEntry { variants: number } +/** Something a pattern view lays out, such as one of a biome's palettes (IrisApi PatternEntry). */ +export interface PatternEntry { + key: string + name: string + /** The heading it is listed under, such as its biome. */ + group: string + /** How many depths below the top it has a pick for; at least 1. */ + depths: number + /** Short lines about it, such as its blocks and noise. */ + facts: string[] +} + +/** What a pattern entry places across a square of columns, row by row from the north west. */ +export interface PatternTile { + columns: number + blocksPerColumn: number + /** The block states the picks index, as BlockState keys. */ + blocks: string[] + /** Each column's block, or NO_PATTERN_BLOCK where the pattern places none. */ + picks: Int16Array +} + +export const NO_PATTERN_BLOCK = -1 + /** 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. */ diff --git a/src/renderer/src/map/TiledView.ts b/src/renderer/src/map/TiledView.ts new file mode 100644 index 000000000..faedff9dc --- /dev/null +++ b/src/renderer/src/map/TiledView.ts @@ -0,0 +1,188 @@ +import { drawVisibleTiles } from './tileDrawing' +import { TileStore, type TileSource } from './TileStore' +import { + MAXIMUM_BLOCKS_PER_PIXEL, + MINIMUM_VIEW_BLOCKS_PER_PIXEL, + renderBlocksPerPixel, + screenToWorldX, + screenToWorldZ, + type TileAddress, + type Viewport +} from './viewport' + +export interface TiledViewOptions { + source: TileSource + tileSize: number + defaultBlocksPerPixel: number + /** The finest scale tiles are asked for at; closer views magnify them. */ + finestRenderBlocksPerPixel: number + /** How far the view may zoom out. */ + coarsestBlocksPerPixel?: number + onFrame(frame: TiledFrame): void + onError(message: string): void +} + +export interface TiledFrame { + blocksPerPixel: number + tilesReady: number + tilesTotal: number + /** The world spot under the cursor, or under the middle when the cursor is away. */ + cursorX: number + cursorZ: number +} + +/** A tile and the pixel of it at a world spot. */ +export interface TileSpot { + tile: Tile + pixelX: number + pixelZ: number +} + +/** Where a view looks and the scale its tiles are drawn at. */ +export interface TiledFraming { + centerX: number + centerZ: number + renderScale: number +} + +/** + * A pan and zoom view of tiles on a canvas, fetched as the view moves and drawn in the current style. Kept outside + * React, as it redraws on every drag and wheel step. + */ +export class TiledView { + private readonly context: CanvasRenderingContext2D + private readonly store: TileStore + private readonly view: Viewport + private layer: Layer | null = null + private style: Style | null = null + private cursor: { x: number; y: number } | null = null + private drawn = { tilesReady: 0, tilesTotal: 0 } + private frameRequested = false + private closed = false + + constructor( + private readonly canvas: HTMLCanvasElement, + private readonly options: TiledViewOptions + ) { + this.context = canvas.getContext('2d')! + this.view = { centerX: 0, centerZ: 0, blocksPerPixel: options.defaultBlocksPerPixel, width: 1, height: 1 } + this.store = new TileStore(options.source, () => this.redraw(), options.onError) + } + + 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: Layer | null, style: Style): 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) + const coarsest = this.options.coarsestBlocksPerPixel ?? MAXIMUM_BLOCKS_PER_PIXEL + this.view.blocksPerPixel = Math.min(coarsest, Math.max(MINIMUM_VIEW_BLOCKS_PER_PIXEL, 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 = this.options.defaultBlocksPerPixel + this.redraw() + } + + setCursor(cursor: { x: number; y: number } | null): void { + this.cursor = cursor + this.reportFrame() + } + + framing(): TiledFraming { + return { centerX: this.view.centerX, centerZ: this.view.centerZ, renderScale: this.renderScale() } + } + + /** The tile drawn at a world spot at the current scale and its pixel there; null before it arrived. */ + spotAt(worldX: number, worldZ: number): TileSpot | null { + if (this.layer === null) { + return null + } + const scale = this.renderScale() + const span = this.options.tileSize * 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 last = this.options.tileSize - 1 + const pixelX = Math.min(last, Math.floor((worldX - address.tileX * span) / scale)) + const pixelZ = Math.min(last, Math.floor((worldZ - address.tileZ * span) / scale)) + return { tile, pixelX, pixelZ } + } + + private renderScale(): number { + return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio, this.options.finestRenderBlocksPerPixel) + } + + 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.drawn = { tilesReady: 0, tilesTotal: 0 } + this.reportFrame() + return + } + const drawn = drawVisibleTiles(context, this.view, this.renderScale(), this.options.tileSize, (address) => this.store.picture(address, layer, style)) + this.store.want(drawn.wanted, layer) + this.drawn = { tilesReady: drawn.ready, tilesTotal: drawn.tiles.length } + this.reportFrame() + } + + private reportFrame(): void { + const cursor = this.cursor ?? { x: this.view.width / 2, y: this.view.height / 2 } + this.options.onFrame({ + blocksPerPixel: this.view.blocksPerPixel, + ...this.drawn, + cursorX: screenToWorldX(this.view, cursor.x), + cursorZ: screenToWorldZ(this.view, cursor.y) + }) + } +} diff --git a/src/renderer/src/noise/NoiseController.ts b/src/renderer/src/noise/NoiseController.ts deleted file mode 100644 index ca8a71d96..000000000 --- a/src/renderer/src/noise/NoiseController.ts +++ /dev/null @@ -1,206 +0,0 @@ -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/noiseTiles.ts b/src/renderer/src/noise/noiseTiles.ts new file mode 100644 index 000000000..a2fa4ae4c --- /dev/null +++ b/src/renderer/src/noise/noiseTiles.ts @@ -0,0 +1,77 @@ +import type { BridgeClient } from '../bridge/BridgeClient' +import type { NoiseTile } from '../bridge/types' +import { TiledView, type TiledFrame } from '../map/TiledView' +import type { TileSource } from '../map/TileStore' +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 type NoiseView = TiledView + +export interface NoiseStatus extends TiledFrame { + /** 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 + +export function createNoiseView(canvas: HTMLCanvasElement, client: BridgeClient, listener: NoiseListener): NoiseView { + const view: NoiseView = new TiledView(canvas, { + source: noiseTileSource(client), + tileSize: NOISE_TILE_PIXELS, + defaultBlocksPerPixel: DEFAULT_NOISE_BLOCKS_PER_PIXEL, + finestRenderBlocksPerPixel: FINEST_NOISE_BLOCKS_PER_PIXEL, + onFrame: (frame) => listener.onStatus({ ...frame, value: valueAt(view, frame.cursorX, frame.cursorZ) }), + onError: (message) => listener.onError(message) + }) + return view +} + +function valueAt(view: NoiseView, worldX: number, worldZ: number): number | null { + const spot = view.spotAt(worldX, worldZ) + return spot === null ? null : spot.tile.values[spot.pixelZ * spot.tile.size + spot.pixelX] +} + +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 +} diff --git a/src/renderer/src/pattern/patternTiles.ts b/src/renderer/src/pattern/patternTiles.ts new file mode 100644 index 000000000..eff5e4e0b --- /dev/null +++ b/src/renderer/src/pattern/patternTiles.ts @@ -0,0 +1,152 @@ +import type { BridgeClient } from '../bridge/BridgeClient' +import { NO_PATTERN_BLOCK, type PatternTile } from '../bridge/types' +import { TiledView, type TiledFrame } from '../map/TiledView' +import type { TileSource } from '../map/TileStore' +import type { TileAddress } from '../map/viewport' +import type { BlockColors } from '../scene/blockColors' + +/** Which entry, at which depth, the tiles lay out. */ +export interface PatternLayer { + viewId: string + key: string + depth: number + /** Bumped when the pack is hotloaded, so older tiles are not used again. */ + revision: number +} + +/** A pattern tile with what it needs to be drawn: each block's colour, and its texture once a block spans pixels. */ +export interface PatternPicture { + pattern: PatternTile + colors: number[] + /** Per block, its top texture; empty while a block is a pixel or smaller. */ + textures: (ImageData | null)[] + /** How many pixels across a column is drawn; 1 when it is a pixel or smaller. */ + pixelsPerColumn: number +} + +/** Patterns have one look; the style only satisfies the tile store. */ +export type PatternStyle = 'blocks' +export type PatternView = TiledView + +/** What is under the cursor: a block, nothing placed there, or not known before its tile arrived. */ +export type PatternSpot = { kind: 'block'; block: string } | { kind: 'none' } | { kind: 'unknown' } + +export interface PatternStatus extends TiledFrame { + spot: PatternSpot +} + +/** The blocks a tile placed with their colours, and whether it left some columns without a block. */ +export interface PatternBlocks { + colors: Map + someNone: boolean +} + +export interface PatternListener { + onStatus(status: PatternStatus): void + /** What a tile of the layer showed, for the legend. */ + onBlocks(layer: PatternLayer, blocks: PatternBlocks): void + onError(message: string): void +} + +export const PATTERN_TILE_PIXELS = 128 +const DEFAULT_PATTERN_BLOCKS_PER_PIXEL = 1 +// A block texture is 16 pixels across; drawing a block that wide shows it whole. +const FINEST_PATTERN_BLOCKS_PER_PIXEL = 1 / 16 +// The bridge lays out a column at most every 64 blocks; views stop a level short so their previews stay within it. +const COARSEST_PATTERN_BLOCKS_PER_PIXEL = 32 +const NO_COLOR = 0x000000 +const OPAQUE = 0xff +const OPAQUE_ENOUGH_ALPHA = 128 + +export function createPatternView(canvas: HTMLCanvasElement, client: BridgeClient, blockColors: BlockColors, listener: PatternListener): PatternView { + const view: PatternView = new TiledView(canvas, { + source: patternTileSource(client, blockColors, listener), + tileSize: PATTERN_TILE_PIXELS, + defaultBlocksPerPixel: DEFAULT_PATTERN_BLOCKS_PER_PIXEL, + finestRenderBlocksPerPixel: FINEST_PATTERN_BLOCKS_PER_PIXEL, + coarsestBlocksPerPixel: COARSEST_PATTERN_BLOCKS_PER_PIXEL, + onFrame: (frame) => listener.onStatus({ ...frame, spot: spotAt(view, frame.cursorX, frame.cursorZ) }), + onError: (message) => listener.onError(message) + }) + return view +} + +function spotAt(view: PatternView, worldX: number, worldZ: number): PatternSpot { + const spot = view.spotAt(worldX, worldZ) + if (spot === null) { + return { kind: 'unknown' } + } + const { pattern, pixelsPerColumn } = spot.tile + const column = Math.floor(spot.pixelX / pixelsPerColumn) + const row = Math.floor(spot.pixelZ / pixelsPerColumn) + const pick = pattern.picks[row * pattern.columns + column] + return pick === NO_PATTERN_BLOCK ? { kind: 'none' } : { kind: 'block', block: pattern.blocks[pick] } +} + +function patternTileSource(client: BridgeClient, blockColors: BlockColors, listener: PatternListener): TileSource { + return { + layerKey: (layer) => `${layer.revision}/${layer.viewId}/${layer.key}/${layer.depth}`, + fetch: async (address, layer, signal) => { + const picture = await fetchPicture(client, blockColors, address, layer, signal) + listener.onBlocks(layer, { + colors: new Map(picture.pattern.blocks.map((block, index) => [block, picture.colors[index]])), + someNone: picture.pattern.picks.includes(NO_PATTERN_BLOCK) + }) + return picture + }, + bytesOf: (picture) => picture.pattern.picks.byteLength + PATTERN_TILE_PIXELS * PATTERN_TILE_PIXELS * 4, + styleKey: (style) => style, + pixels: (picture) => patternPixels(picture) + } +} + +/** + * A tile a pixel per column where a column is a pixel or more, and otherwise a column per block, each drawn a few + * pixels wide in its texture. + */ +async function fetchPicture(client: BridgeClient, blockColors: BlockColors, address: TileAddress, layer: PatternLayer, signal: AbortSignal): Promise { + const blocksPerColumn = Math.max(1, address.blocksPerPixel) + const pixelsPerColumn = Math.round(blocksPerColumn / address.blocksPerPixel) + const columns = PATTERN_TILE_PIXELS / pixelsPerColumn + const pattern = await client.pattern({ ...layer, tileX: address.tileX, tileZ: address.tileZ, blocksPerColumn, columns }, signal) + const colors = await Promise.all(pattern.blocks.map((block) => blockColors.colorOf(block))) + const textures = pixelsPerColumn > 1 ? await Promise.all(pattern.blocks.map((block) => blockColors.topTexture(block))) : [] + return { pattern, colors, textures, pixelsPerColumn } +} + +function patternPixels(picture: PatternPicture): ImageData { + const pixels = new ImageData(PATTERN_TILE_PIXELS, PATTERN_TILE_PIXELS) + const { pattern, pixelsPerColumn } = picture + for (let pixelZ = 0; pixelZ < PATTERN_TILE_PIXELS; pixelZ++) { + for (let pixelX = 0; pixelX < PATTERN_TILE_PIXELS; pixelX++) { + const pick = pattern.picks[Math.floor(pixelZ / pixelsPerColumn) * pattern.columns + Math.floor(pixelX / pixelsPerColumn)] + if (pick !== NO_PATTERN_BLOCK) { + writePixel(pixels, (pixelZ * PATTERN_TILE_PIXELS + pixelX) * 4, picture, pick, pixelX % pixelsPerColumn, pixelZ % pixelsPerColumn) + } + } + } + return pixels +} + +/** + * The block's texture at a spot within its column, and its colour where it has no texture or the texture is see + * through, such as between leaves, so a palette reads as solid ground. + */ +function writePixel(pixels: ImageData, offset: number, picture: PatternPicture, pick: number, insideX: number, insideZ: number): void { + const texture = picture.textures[pick] ?? null + if (texture !== null) { + const textureX = Math.floor((insideX * texture.width) / picture.pixelsPerColumn) + const textureZ = Math.floor((insideZ * texture.height) / picture.pixelsPerColumn) + const from = (textureZ * texture.width + textureX) * 4 + if (texture.data[from + 3] >= OPAQUE_ENOUGH_ALPHA) { + pixels.data.set(texture.data.subarray(from, from + 3), offset) + pixels.data[offset + 3] = OPAQUE + return + } + } + const color = picture.colors[pick] ?? NO_COLOR + pixels.data[offset] = (color >> 16) & 0xff + pixels.data[offset + 1] = (color >> 8) & 0xff + pixels.data[offset + 2] = color & 0xff + pixels.data[offset + 3] = OPAQUE +} diff --git a/src/renderer/src/scene/blockColors.ts b/src/renderer/src/scene/blockColors.ts index 9154879ce..fb26184fc 100644 --- a/src/renderer/src/scene/blockColors.ts +++ b/src/renderer/src/scene/blockColors.ts @@ -4,21 +4,33 @@ import { texturePath, type ImageSource } from './textureAtlas' const UNKNOWN_BLOCK_COLOR = 0x7f7f7f const OPAQUE_ENOUGH_ALPHA = 128 +const NO_TINT = 0xffffff -/** Each block's colour seen from above: its top face's texture averaged and tinted as the client tints it, read once. */ +/** Each block seen from above: its top face's texture tinted as the client tints it, and that texture's average colour, read once. */ export class BlockColors { - private readonly known = new Map>() + private readonly textures = new Map>() + private readonly colors = new Map>() constructor( private readonly models: BlockModels, private readonly images: ImageSource ) {} + /** The first frame of the block's top face texture, tinted; null when the block has no model or texture. */ + topTexture(block: string): Promise { + let texture = this.textures.get(block) + if (texture === undefined) { + texture = this.readTopTexture(block).catch(() => null) + this.textures.set(block, texture) + } + return texture + } + colorOf(block: string): Promise { - let color = this.known.get(block) + let color = this.colors.get(block) if (color === undefined) { - color = this.read(block).catch(() => UNKNOWN_BLOCK_COLOR) - this.known.set(block, color) + color = this.topTexture(block).then((texture) => (texture === null ? UNKNOWN_BLOCK_COLOR : averageColor(texture))) + this.colors.set(block, color) } return color } @@ -30,29 +42,47 @@ export class BlockColors { return new Map(names.map((name, index) => [name, colors[index]])) } - private async read(block: string): Promise { + private async readTopTexture(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 + return null } const bitmap = await this.images.image(texturePath(texture)) if (bitmap === null) { - return UNKNOWN_BLOCK_COLOR + return null } const state = parseState(block) - return multiplied(averageColor(bitmap), blockTint(state.name, state.properties, top?.tintIndex ?? -1)) + return tinted(firstFrame(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 { +// An animated texture stacks its frames downwards. +function firstFrame(bitmap: ImageBitmap): ImageData { 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 + return drawing.getImageData(0, 0, side, side) +} + +function tinted(texture: ImageData, tint: number): ImageData { + if (tint === NO_TINT) { + return texture + } + const pixels = texture.data + const [red, green, blue] = [(tint >> 16) & 0xff, (tint >> 8) & 0xff, tint & 0xff] + for (let offset = 0; offset < pixels.length; offset += 4) { + pixels[offset] = Math.round((pixels[offset] * red) / 255) + pixels[offset + 1] = Math.round((pixels[offset + 1] * green) / 255) + pixels[offset + 2] = Math.round((pixels[offset + 2] * blue) / 255) + } + return texture +} + +function averageColor(texture: ImageData): number { + const pixels = texture.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) { @@ -67,8 +97,3 @@ function averageColor(bitmap: ImageBitmap): number { } 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/studio/EntryBrowser.tsx b/src/renderer/src/studio/EntryBrowser.tsx new file mode 100644 index 000000000..f2663fc0e --- /dev/null +++ b/src/renderer/src/studio/EntryBrowser.tsx @@ -0,0 +1,76 @@ +import { useMemo, useState } from 'react' +import { Input } from '@/components/ui/input' +import { ScrollArea } from '@/components/ui/scroll-area' +import { cn } from '@/lib/utils' + +const NUMBER = new Intl.NumberFormat('en-US') + +/** An entry of a module view: its key, the name it is listed by, and the heading it is listed under (empty for none). */ +export interface BrowsableEntry { + key: string + name: string + group: string +} + +interface EntryBrowserProps { + title: string + entries: BrowsableEntry[] + current: string | null + onSelect(key: string): void + className?: string +} + +/** A view's entries under their headings, with a search over keys, names and headings (v3e ObjectBrowser). */ +export function EntryBrowser({ title, entries, current, onSelect, className }: EntryBrowserProps): React.JSX.Element { + const [search, setSearch] = useState('') + const wanted = search.trim().toLowerCase() + const groups = useMemo(() => groupedEntries(entries, wanted), [entries, wanted]) + return ( +
+
+

{title}

+

{NUMBER.format(entries.length)} in the pack

+ setSearch(event.target.value)} + onKeyDown={(event) => event.key === 'Escape' && setSearch('')} + /> +
+ +
+ {groups.map(([group, members]) => ( +
+ {group !== '' &&

{group}

} + {members.map((entry) => ( + + ))} +
+ ))} + {groups.length === 0 &&

{entries.length === 0 ? 'Nothing to show' : 'Nothing matches'}

} +
+
+
+ ) +} + +function groupedEntries(entries: Entry[], wanted: string): [string, Entry[]][] { + const groups = new Map() + for (const entry of entries) { + if (wanted !== '' && ![entry.key, entry.name, entry.group].some((text) => text.toLowerCase().includes(wanted))) { + continue + } + const members = groups.get(entry.group) ?? [] + members.push(entry) + groups.set(entry.group, members) + } + return [...groups.entries()] +} diff --git a/src/renderer/src/studio/MapStudio.tsx b/src/renderer/src/studio/MapStudio.tsx index 5d43af44f..762f4440e 100644 --- a/src/renderer/src/studio/MapStudio.tsx +++ b/src/renderer/src/studio/MapStudio.tsx @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { ThemeChoice } from '../../../shared/bridge' import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' -import type { MapHover, MapLabel, Marker, PickDisplay, PickInspection, SceneViewInfo, ViewInfo, WorldInfo } from '../bridge/types' +import type { MapHover, MapLabel, Marker, ModuleViewInfo, PickDisplay, PickInspection, ViewInfo, WorldInfo } from '../bridge/types' import type { Share } from '../map/census' import type { MapController, MapStatus, MapToggles } from '../map/MapController' import type { Highlight } from '../map/tileStyle' @@ -12,6 +12,7 @@ import { MapCanvas, type CanvasPoint } from './MapCanvas' import { PickInspector } from './PickInspector' import { RegionPreviewList } from './RegionPreviewList' import { NoiseStudio } from './NoiseStudio' +import { PatternStudio } from './PatternStudio' import { SavedWorldStudio } from './SavedWorldStudio' import { SceneStudio } from './SceneStudio' import { WorldStudio3D } from './WorldStudio3D' @@ -61,10 +62,17 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps const [area, setArea] = useState(null) const [packRevision, setPackRevision] = useState(0) const [sceneSummary, setSceneSummary] = useState(null) - const sceneViews = useSceneViews(client, packRevision) - const views = useMemo(() => [...withAppViews(world.views), ...sceneViews.map(asViewInfo), NOISE], [world.views, sceneViews]) + const loadSceneViews = useCallback(() => client.sceneViews(), [client]) + const loadPatternViews = useCallback(() => client.patternViews(), [client]) + const sceneViews = useModuleViews(loadSceneViews, packRevision) + const patternViews = useModuleViews(loadPatternViews, packRevision) + const views = useMemo( + () => [...withAppViews(world.views), ...patternViews.map(asViewInfo), ...sceneViews.map(asViewInfo), NOISE], + [world.views, patternViews, sceneViews] + ) const sceneView = sceneViews.find((candidate) => candidate.id === viewId) ?? null - const showsMap = sceneView === null && !APP_VIEW_IDS.has(viewId) + const patternView = patternViews.find((candidate) => candidate.id === viewId) ?? null + const showsMap = sceneView === null && patternView === 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 +226,8 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps {sceneView !== null ? ( + ) : patternView !== null ? ( + ) : viewId === WORLD_3D.id ? ( ) : viewId === SAVED_WORLD.id ? ( @@ -315,7 +325,7 @@ function withAppViews(serverViews: ViewInfo[]): ViewInfo[] { return [...serverViews.slice(0, afterHeight), WORLD_3D, SAVED_WORLD, ...serverViews.slice(afterHeight)] } -function asViewInfo(view: SceneViewInfo): ViewInfo { +function asViewInfo(view: ModuleViewInfo): ViewInfo { return { ...view, ...SCENE_GROUP } } @@ -324,19 +334,18 @@ function statusLabel(viewLabel: string, previewName: string | null, sceneSummary return detail === null ? viewLabel : `${viewLabel} · ${detail}` } -/** The scene views the pack's modules show, read again after the pack reloads. */ -function useSceneViews(client: BridgeClient, packRevision: number): SceneViewInfo[] { - const [views, setViews] = useState([]) +/** Views the pack's modules show, read again after the pack reloads; keep {@code load} stable. */ +function useModuleViews(load: () => Promise, packRevision: number): ModuleViewInfo[] { + const [views, setViews] = useState([]) useEffect(() => { let active = true - client - .sceneViews() + load() .then((found) => active && setViews(found)) .catch(() => undefined) return () => { active = false } - }, [client, packRevision]) + }, [load, packRevision]) return views } diff --git a/src/renderer/src/studio/NoiseStudio.tsx b/src/renderer/src/studio/NoiseStudio.tsx index 7fe0d1e49..25d25776e 100644 --- a/src/renderer/src/studio/NoiseStudio.tsx +++ b/src/renderer/src/studio/NoiseStudio.tsx @@ -7,13 +7,14 @@ 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 type { TiledFraming as TerrainFraming } from '../map/TiledView' import { NOISE_PALETTES, noiseScale, type NoisePaletteId, type NoiseScale } from '../noise/noiseScale' import { NoiseTerrain, type NoiseArea } from '../noise/noiseTerrain' +import { createNoiseView, NOISE_TILE_PIXELS, type NoiseStatus, type NoiseView } from '../noise/noiseTiles' import { buildTerrainMesh } from '../scene/terrainMesh' import { hexColor } from './colors' -import { NoiseCanvas } from './NoiseCanvas' import { SceneViewport } from './SceneViewport' +import { TiledCanvas } from './TiledCanvas' type NoiseDisplay = 'flat' | 'terrain' @@ -46,9 +47,14 @@ export function NoiseStudio({ client, packRevision, onSummary, tell }: NoiseStud const [reliefBlocks, setReliefBlocks] = useState(DEFAULT_RELIEF_BLOCKS) const [status, setStatus] = useState(null) const [terrainFraming, setTerrainFraming] = useState(null) - const controllerRef = useRef(null) + const controllerRef = useRef(null) const scale = useMemo(() => noiseScale(paletteId, source), [paletteId, source]) - const listener = useMemo(() => ({ onStatus: setStatus, onError: tell }), [tell]) + const latestTell = useRef(tell) + latestTell.current = tell + const createView = useCallback( + (canvas: HTMLCanvasElement) => createNoiseView(canvas, client, { onStatus: setStatus, onError: (message) => latestTell.current(message) }), + [client] + ) useEffect(() => { const layer = source === null ? null : { sourceId: source.id, seed, revision: packRevision } @@ -75,10 +81,9 @@ export function NoiseStudio({ client, packRevision, onSummary, tell }: NoiseStud return ( <>
- {display === 'terrain' && source !== null && terrainFraming !== null && ( @@ -263,12 +268,6 @@ function ReliefControl({ blocks, onChange }: { blocks: number; onChange(blocks: ) } -interface TerrainFraming { - centerX: number - centerZ: number - renderScale: number -} - function NoiseTerrainView({ client, source, diff --git a/src/renderer/src/studio/PatternStudio.tsx b/src/renderer/src/studio/PatternStudio.tsx new file mode 100644 index 000000000..32b7e2218 --- /dev/null +++ b/src/renderer/src/studio/PatternStudio.tsx @@ -0,0 +1,209 @@ +import { ChevronLeft, ChevronRight, RotateCcw } from 'lucide-react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Button } from '@/components/ui/button' +import { ScrollArea } from '@/components/ui/scroll-area' +import { cn } from '@/lib/utils' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { ModuleViewInfo, PatternEntry } from '../bridge/types' +import { createPatternView, type PatternBlocks, type PatternLayer, type PatternStatus, type PatternView } from '../pattern/patternTiles' +import { BlockColors } from '../scene/blockColors' +import { BlockModels } from '../scene/blockModels' +import { BridgeAssets } from '../scene/BridgeAssets' +import { hexColor } from './colors' +import { EntryBrowser } from './EntryBrowser' +import { TiledCanvas } from './TiledCanvas' + +const DEFAULT_NAMESPACE_PREFIX = 'minecraft:' +// A layer thinner than the depth shown, or a palette with no block for the spot. +const NONE_LABEL = 'nothing at this depth' + +/** The blocks the shown layer's tiles placed so far by name, with their colours, and whether some spots got none. */ +interface LegendBlocks { + colors: Map + someNone: boolean +} + +const EMPTY_LEGEND: LegendBlocks = { colors: new Map(), someNone: false } +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 PatternStudioProps { + client: BridgeClient + view: ModuleViewInfo + /** Changes when the pack reloads, so the entries and the tiles are read again. */ + packRevision: number + onSummary(summary: string | null): void + tell(message: string): void +} + +/** A pattern view: its entries on the right, what the chosen one places from above in the middle (v3e palette explorer). */ +export function PatternStudio({ client, view, packRevision, onSummary, tell }: PatternStudioProps): React.JSX.Element { + const entries = usePatternEntries(client, view.id, packRevision, tell) + const [chosen, setChosen] = useState<{ key: string; depth: number } | null>(null) + const entry = entries.find((candidate) => candidate.key === chosen?.key) ?? entries[0] ?? null + const depth = entry !== null && chosen?.key === entry.key ? Math.min(chosen.depth, entry.depths - 1) : 0 + const layer = useMemo( + () => (entry === null ? null : { viewId: view.id, key: entry.key, depth, revision: packRevision }), + [view.id, entry, depth, packRevision] + ) + const [status, setStatus] = useState(null) + const { legend, createView } = usePatternView(client, layer, setStatus, tell) + const viewRef = useRef(null) + + useEffect(() => viewRef.current?.show(layer, 'blocks'), [layer]) + useEffect(() => onSummary(entry === null ? null : `${entry.group} · ${entry.name}`), [entry, onSummary]) + useEffect(() => () => onSummary(null), [onSummary]) + + const chooseDepth = (next: number): void => { + if (entry !== null) { + setChosen({ key: entry.key, depth: (next + entry.depths) % entry.depths }) + } + } + + return ( + <> +
+ +
+ {entry !== null && entry.depths > 1 && ( + <> + + + Depth {depth + 1} of {entry.depths} + + + + )} + +
+ {status !== null && entry !== null &&
{readout(status)}
} +
+ + + ) +} + +function readout(status: PatternStatus): string { + const spot = `${Math.floor(status.cursorX)}, ${Math.floor(status.cursorZ)}` + switch (status.spot.kind) { + case 'block': + return `${spot} · ${shortName(status.spot.block)}` + case 'none': + return `${spot} · ${NONE_LABEL}` + case 'unknown': + return spot + } +} + +/** The block without its namespace when that is Minecraft's, and without its state, as a builder names it. */ +function shortName(block: string): string { + const material = block.includes('[') ? block.slice(0, block.indexOf('[')) : block + return material.startsWith(DEFAULT_NAMESPACE_PREFIX) ? material.slice(DEFAULT_NAMESPACE_PREFIX.length) : material +} + +function usePatternEntries(client: BridgeClient, viewId: string, packRevision: number, tell: (message: string) => void): PatternEntry[] { + const [entries, setEntries] = useState([]) + useEffect(() => { + let active = true + client + .patternEntries(viewId) + .then((found) => active && setEntries(found)) + .catch((failure: Error) => active && tell(failure.message)) + return () => { + active = false + } + }, [client, viewId, packRevision, tell]) + return entries +} + +/** The view's maker for the canvas, and the blocks the shown layer's tiles placed so far with their colours. */ +function usePatternView( + client: BridgeClient, + layer: PatternLayer | null, + onStatus: (status: PatternStatus) => void, + tell: (message: string) => void +): { legend: LegendBlocks; createView(canvas: HTMLCanvasElement): PatternView } { + const blockColors = useMemo(() => { + const images = new BridgeAssets(client, () => {}) + return new BlockColors(new BlockModels(images), images) + }, [client]) + const [legend, setLegend] = useState(EMPTY_LEGEND) + const latest = useRef({ layer, onStatus, tell }) + latest.current = { layer, onStatus, tell } + + useEffect(() => setLegend(EMPTY_LEGEND), [layer]) + + const createView = useCallback( + (canvas: HTMLCanvasElement) => + createPatternView(canvas, client, blockColors, { + onStatus: (status) => latest.current.onStatus(status), + onBlocks: (tileLayer, blocks) => tileLayer === latest.current.layer && setLegend((shown) => withBlocks(shown, blocks)), + onError: (message) => latest.current.tell(message) + }), + [client, blockColors] + ) + return { legend, createView } +} + +/** The legend with the tile's blocks added, one row per block whatever its state; unchanged when it had them all. */ +function withBlocks(shown: LegendBlocks, tile: PatternBlocks): LegendBlocks { + const added = [...tile.colors].map(([block, color]) => [shortName(block), color] as const).filter(([name]) => !shown.colors.has(name)) + const someNone = shown.someNone || tile.someNone + if (added.length === 0 && someNone === shown.someNone) { + return shown + } + return { colors: new Map([...shown.colors, ...added]), someNone } +} + +function EntryFacts({ entry }: { entry: PatternEntry | null }): React.JSX.Element | null { + if (entry === null) { + return null + } + return ( +
+

+ {entry.group} · {entry.name} +

+ {entry.facts.map((fact) => ( +

+ {fact} +

+ ))} +
+ ) +} + +/** The blocks the shown tiles place, each with the colour it is drawn in from afar. */ +function Legend({ blocks }: { blocks: LegendBlocks }): React.JSX.Element { + const sorted = [...blocks.colors.entries()].sort(([first], [second]) => first.localeCompare(second)) + return ( +
+

Blocks

+ +
+ {sorted.map(([block, color]) => ( +
+ + {block} +
+ ))} + {blocks.someNone && ( +
+ + Nothing at this depth +
+ )} +
+
+
+ ) +} diff --git a/src/renderer/src/studio/SceneStudio.tsx b/src/renderer/src/studio/SceneStudio.tsx index ffecd61dc..a282b0fc8 100644 --- a/src/renderer/src/studio/SceneStudio.tsx +++ b/src/renderer/src/studio/SceneStudio.tsx @@ -1,15 +1,14 @@ import { ChevronLeft, ChevronRight } from 'lucide-react' import { useEffect, useMemo, useState } from 'react' import { Button } from '@/components/ui/button' -import { Input } from '@/components/ui/input' import { ScrollArea } from '@/components/ui/scroll-area' -import { cn } from '@/lib/utils' import type { BridgeClient } from '../bridge/BridgeClient' -import type { SceneEntry, SceneViewInfo } from '../bridge/types' +import type { ModuleViewInfo, SceneEntry } from '../bridge/types' import { BlockModels } from '../scene/blockModels' import { BridgeAssets } from '../scene/BridgeAssets' import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding' import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh' +import { EntryBrowser } from './EntryBrowser' import { SceneViewport } from './SceneViewport' const NUMBER = new Intl.NumberFormat('en-US') @@ -17,7 +16,7 @@ const DEFAULT_NAMESPACE_PREFIX = 'minecraft:' interface SceneStudioProps { client: BridgeClient - view: SceneViewInfo + view: ModuleViewInfo /** Changes when the pack reloads, so the entries and the scene are read again. */ packRevision: number /** What the status bar says about the scene, or null while none is shown. */ @@ -68,7 +67,7 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce )}
@@ -146,68 +145,6 @@ function disposeMesh(mesh: SceneMesh | null): void { mesh?.dispose() } -interface EntryBrowserProps { - title: string - entries: SceneEntry[] - current: string | null - onSelect(key: string): void -} - -/** The view's entries under their folders, with a search over names and folders (v3e ObjectBrowser). */ -function EntryBrowser({ title, entries, current, onSelect }: EntryBrowserProps): React.JSX.Element { - const [search, setSearch] = useState('') - const wanted = search.trim().toLowerCase() - const groups = useMemo(() => groupedEntries(entries, wanted), [entries, wanted]) - return ( -
-
-

{title}

-

{NUMBER.format(entries.length)} in the pack

- setSearch(event.target.value)} - onKeyDown={(event) => event.key === 'Escape' && setSearch('')} - /> -
- -
- {groups.map(([group, members]) => ( -
- {group !== '' &&

{group}

} - {members.map((entry) => ( - - ))} -
- ))} - {groups.length === 0 &&

{entries.length === 0 ? 'Nothing to show' : 'Nothing matches'}

} -
-
-
- ) -} - -function groupedEntries(entries: SceneEntry[], wanted: string): [string, SceneEntry[]][] { - const groups = new Map() - for (const entry of entries) { - if (wanted !== '' && !entry.key.toLowerCase().includes(wanted)) { - continue - } - const members = groups.get(entry.group) ?? [] - members.push(entry) - groups.set(entry.group, members) - } - return [...groups.entries()] -} - /** The blocks of the scene, most used first, each with its count (v3e ObjectOverviewPanel). */ function BlockList({ scene }: { scene: BlockScene | null }): React.JSX.Element { const counts = useMemo(() => (scene === null ? [] : blockCounts(scene)), [scene]) diff --git a/src/renderer/src/studio/NoiseCanvas.tsx b/src/renderer/src/studio/TiledCanvas.tsx similarity index 56% rename from src/renderer/src/studio/NoiseCanvas.tsx rename to src/renderer/src/studio/TiledCanvas.tsx index 49621ac93..79a291f1f 100644 --- a/src/renderer/src/studio/NoiseCanvas.tsx +++ b/src/renderer/src/studio/TiledCanvas.tsx @@ -1,45 +1,41 @@ import { useEffect, useRef } from 'react' -import type { BridgeClient } from '../bridge/BridgeClient' -import { NoiseController, type NoiseListener } from '../noise/NoiseController' +import type { TiledView } from '../map/TiledView' -interface NoiseCanvasProps { - client: BridgeClient - controllerRef: React.RefObject - listener: NoiseListener +type AnyTiledView = TiledView + +interface TiledCanvasProps { + /** Makes the view on the canvas; called again only when it changes, so keep it stable. */ + create(canvas: HTMLCanvasElement): View + viewRef: React.RefObject 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 { +/** A tiled view from above: drag to move, wheel to zoom. */ +export function TiledCanvas({ create, viewRef, className }: TiledCanvasProps): 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)) + const view = create(canvas) + viewRef.current = view + const resize = new ResizeObserver(([entry]) => view.resize(entry.contentRect.width, entry.contentRect.height)) resize.observe(canvas) - const stopMouse = followMouse(canvas, noise) + const stopMouse = followMouse(canvas, view) return () => { stopMouse() resize.disconnect() - noise.close() - controllerRef.current = null + view.close() + viewRef.current = null } - }, [client, controllerRef]) + }, [create, viewRef]) return } -function followMouse(canvas: HTMLCanvasElement, noise: NoiseController): () => void { +function followMouse(canvas: HTMLCanvasElement, view: AnyTiledView): () => void { let last: { x: number; y: number } | null = null const pointOf = (event: MouseEvent): { x: number; y: number } => { const bounds = canvas.getBoundingClientRect() @@ -52,20 +48,20 @@ function followMouse(canvas: HTMLCanvasElement, noise: NoiseController): () => v } } const move = (event: PointerEvent): void => { - noise.setCursor(pointOf(event)) + view.setCursor(pointOf(event)) if (last !== null) { - noise.panBy(event.clientX - last.x, event.clientY - last.y) + view.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 leave = (): void => view.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) + view.zoomAt(2 ** (-event.deltaY * WHEEL_ZOOM_PER_DELTA), point.x, point.y) } canvas.addEventListener('pointerdown', down) canvas.addEventListener('pointermove', move) diff --git a/src/renderer/src/studio/ViewList.tsx b/src/renderer/src/studio/ViewList.tsx index 5734c8cc2..40e6aeef9 100644 --- a/src/renderer/src/studio/ViewList.tsx +++ b/src/renderer/src/studio/ViewList.tsx @@ -1,4 +1,4 @@ -import { AudioWaveform, Box, Gem, Globe, HardDrive, Map as MapIcon, Mountain, Shapes, Sprout, Trees, Waves, type LucideIcon } from 'lucide-react' +import { AudioWaveform, Box, Gem, Globe, HardDrive, Layers, 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' @@ -16,7 +16,8 @@ const VIEW_ICONS: Record = { seaBiomes: Waves, caveBiomes: Gem, 'iris:objects': Box, - 'iris:objects/procedural': Shapes + 'iris:objects/procedural': Shapes, + 'iris:terrain/palettes': Layers } interface ViewListProps {