Map: pick inspector, noise display and region preview

A right-hand panel shows how the noise picks the regions or biomes in
view: a histogram per noise over its pick bands, and each option's weight
against its share of the view. The map can draw the picks, the settling
noise, or both, and any prepared region can be previewed across the map.
This commit is contained in:
piexel committed 2026-11-06 01:10:21 +01:00
1 parent e20bf1dd57
commit 674f9756e3
17 files changed
+718 -65

No files matched your search

+41 -6
View File
@@ -1,6 +1,6 @@
import type { BridgeConnection } from '../../../shared/bridge' import type { BridgeConnection } from '../../../shared/bridge'
import { decodeTile } from './tileDecoding' import { decodeTile } from './tileDecoding'
import type { MapHover, MapTile, Marker, WorldInfo } from './types' import type { MapHover, MapLabel, MapTile, Marker, PickInspection, WorldInfo } from './types'
export class BridgeError extends Error { export class BridgeError extends Error {
constructor( constructor(
@@ -13,11 +13,27 @@ export class BridgeError extends Error {
export interface TileRequest { export interface TileRequest {
view: string view: string
/** The region the region view previews everywhere, or null for the world as it is. */
preview: string | null
tileX: number tileX: number
tileZ: number tileZ: number
blocksPerPixel: number blocksPerPixel: number
size: number size: number
heights: boolean heights: boolean
pickNoise: boolean
}
/** What a map spot or area is asked about: a view, and the region it previews. */
export interface MapLayerQuery {
view: string
preview: string | null
}
export interface WorldRect {
minX: number
minZ: number
maxX: number
maxZ: number
} }
export interface BridgeEvents { export interface BridgeEvents {
@@ -42,8 +58,19 @@ export class BridgeClient {
return this.json('world') return this.json('world')
} }
hover(view: string, worldX: number, worldZ: number, signal?: AbortSignal): Promise<MapHover> { hover(layer: MapLayerQuery, worldX: number, worldZ: number, signal?: AbortSignal): Promise<MapHover> {
return this.json(`hover?view=${encodeURIComponent(view)}&x=${worldX}&z=${worldZ}`, { signal }) return this.json(`hover?${layerQuery(layer, { x: String(worldX), z: String(worldZ) })}`, { signal })
}
/** How the noise picks what the layer shows across {@code area}. */
picks(layer: MapLayerQuery, area: WorldRect, signal?: AbortSignal): Promise<PickInspection> {
const corners = { minX: String(area.minX), minZ: String(area.minZ), maxX: String(area.maxX), maxZ: String(area.maxZ) }
return this.json(`picks?${layerQuery(layer, corners)}`, { signal })
}
/** The regions the world picks biomes for, which the region view can preview. */
regions(): Promise<MapLabel[]> {
return this.json('regions')
} }
entities(): Promise<Marker[]> { entities(): Promise<Marker[]> {
@@ -61,13 +88,13 @@ export class BridgeClient {
} }
async tile(request: TileRequest, signal: AbortSignal): Promise<MapTile> { async tile(request: TileRequest, signal: AbortSignal): Promise<MapTile> {
const query = new URLSearchParams({ const query = layerQuery(request, {
view: request.view,
x: String(request.tileX), x: String(request.tileX),
z: String(request.tileZ), z: String(request.tileZ),
scale: String(request.blocksPerPixel), scale: String(request.blocksPerPixel),
size: String(request.size), size: String(request.size),
heights: request.heights ? '1' : '0' heights: request.heights ? '1' : '0',
noise: request.pickNoise ? '1' : '0'
}) })
const response = await this.fetch(`tile?${query}`, { signal }) const response = await this.fetch(`tile?${query}`, { signal })
return decodeTile(await response.arrayBuffer()) return decodeTile(await response.arrayBuffer())
@@ -120,6 +147,14 @@ export class BridgeClient {
} }
} }
function layerQuery(layer: MapLayerQuery, rest: Record<string, string>): URLSearchParams {
const query = new URLSearchParams({ view: layer.view, ...rest })
if (layer.preview !== null) {
query.set('preview', layer.preview)
}
return query
}
function dispatch(block: string, events: BridgeEvents): void { function dispatch(block: string, events: BridgeEvents): void {
let name = 'message' let name = 'message'
let data = '' let data = ''
+6 -2
View File
@@ -8,6 +8,7 @@ interface TileHeader {
subjectKind: LabelKind subjectKind: LabelKind
labels: MapLabel[] labels: MapLabel[]
heights: boolean heights: boolean
pickNoise: boolean
} }
function aligned(bytes: number): number { function aligned(bytes: number): number {
@@ -16,7 +17,8 @@ function aligned(bytes: number): number {
/** /**
* Reads a tile as the bridge writes it (MapTileEncoding): a u32 header length, the JSON header, then the subject, * Reads a tile as the bridge writes it (MapTileEncoding): a u32 header length, the JSON header, then the subject,
* region and height grids, each starting on a multiple of 4 bytes. The grids are views into the buffer, not copies. * region, height and pick noise grids, each starting on a multiple of 4 bytes. The grids are views into the buffer,
* not copies.
*/ */
export function decodeTile(buffer: ArrayBuffer): MapTile { export function decodeTile(buffer: ArrayBuffer): MapTile {
const view = new DataView(buffer) const view = new DataView(buffer)
@@ -27,6 +29,7 @@ export function decodeTile(buffer: ArrayBuffer): MapTile {
const subjectsAt = aligned(4 + headerLength) const subjectsAt = aligned(4 + headerLength)
const regionsAt = aligned(subjectsAt + cells * Int16Array.BYTES_PER_ELEMENT) const regionsAt = aligned(subjectsAt + cells * Int16Array.BYTES_PER_ELEMENT)
const heightsAt = aligned(regionsAt + cells * Int16Array.BYTES_PER_ELEMENT) const heightsAt = aligned(regionsAt + cells * Int16Array.BYTES_PER_ELEMENT)
const pickNoiseAt = heightsAt + (header.heights ? cells * Float32Array.BYTES_PER_ELEMENT : 0)
return { return {
size: header.size, size: header.size,
blocksPerPixel: header.blocksPerPixel, blocksPerPixel: header.blocksPerPixel,
@@ -34,7 +37,8 @@ export function decodeTile(buffer: ArrayBuffer): MapTile {
labels: header.labels, labels: header.labels,
subjects: new Int16Array(buffer, subjectsAt, cells), subjects: new Int16Array(buffer, subjectsAt, cells),
regions: new Int16Array(buffer, regionsAt, cells), regions: new Int16Array(buffer, regionsAt, cells),
heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null,
pickNoise: header.pickNoise ? new Float32Array(buffer, pickNoiseAt, cells) : null
} }
} }
+38 -2
View File
@@ -47,8 +47,8 @@ export interface MapHover {
pickPath: PickStep[] pickPath: PickStep[]
} }
/** REGION, BIOME and CHILD were picked by noise; IMAGE_MAP and FOCUS were set without a pick. */ /** REGION, BIOME and CHILD were picked by noise; IMAGE_MAP, FOCUS and PREVIEW were set without a pick. */
export type PickKind = 'REGION' | 'BIOME' | 'CHILD' | 'IMAGE_MAP' | 'FOCUS' export type PickKind = 'REGION' | 'BIOME' | 'CHILD' | 'IMAGE_MAP' | 'FOCUS' | 'PREVIEW'
export interface PickStep { export interface PickStep {
kind: PickKind kind: PickKind
@@ -69,6 +69,40 @@ export interface PickBand {
to: number to: number
} }
/** How the noise picks what an area of the map shows (MapPickInspection). */
export interface PickInspection {
detail: string
sections: PickSection[]
}
/** The picks on one region's ground; `region` is null in the region view, where the regions themselves are picked. */
export interface PickSection {
region: MapLabel | null
/** How much of the area's picked ground the region holds. */
share: number
biomeCount: number
spreads: PickSpread[]
}
/** One noise in the area: its values in 50 equal steps from 0 to 1, and each option's share of it. */
export interface PickSpread {
title: string
bands: PickBand[]
histogram: number[]
samples: number
rows: PickShare[]
}
/** `weight`: how much of the noise picks the option; `inView`: how much of the area's values do. */
export interface PickShare {
option: MapLabel
weight: number
inView: number
}
/** How the region and biome views draw their picks: the labels, the noise that picked them, or the labels by noise. */
export type PickDisplay = 'picks' | 'noise' | 'both'
export interface Marker { export interface Marker {
label: string label: string
worldX: number worldX: number
@@ -89,6 +123,8 @@ export interface MapTile {
subjects: Int16Array subjects: Int16Array
regions: Int16Array regions: Int16Array
heights: Float32Array | null heights: Float32Array | null
/** The noise value that settled each cell's pick, 0 to 1 and NaN where nothing picked it; null unless asked for. */
pickNoise: Float32Array | null
} }
export const NO_LABEL = -1 export const NO_LABEL = -1
@@ -0,0 +1,69 @@
import * as React from "react"
import { type VariantProps } from "class-variance-authority"
import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle"
const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
size: "default",
variant: "default",
})
function ToggleGroup({
className,
variant,
size,
children,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<ToggleGroupPrimitive.Root
data-slot="toggle-group"
data-variant={variant}
data-size={size}
className={cn(
"group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
className
)}
{...props}
>
<ToggleGroupContext.Provider value={{ variant, size }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
)
}
function ToggleGroupItem({
className,
children,
variant,
size,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
VariantProps<typeof toggleVariants>) {
const context = React.useContext(ToggleGroupContext)
return (
<ToggleGroupPrimitive.Item
data-slot="toggle-group-item"
data-variant={context.variant || variant}
data-size={context.size || size}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
"min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",
className
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
)
}
export { ToggleGroup, ToggleGroupItem }
+43 -12
View File
@@ -1,6 +1,6 @@
import type { BridgeClient } from '../bridge/BridgeClient' import type { BridgeClient, WorldRect } from '../bridge/BridgeClient'
import { gridIndex } from '../bridge/tileDecoding' import { gridIndex } from '../bridge/tileDecoding'
import { NO_LABEL, type MapLabel, type Marker, type WorldInfo } from '../bridge/types' import { NO_LABEL, type MapLabel, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types'
import { countShares, type PlacedTile, type Share } from './census' import { countShares, type PlacedTile, type Share } from './census'
import { bandIndexOf, HEIGHT_BANDS } from './heightColors' import { bandIndexOf, HEIGHT_BANDS } from './heightColors'
import type { Highlight, TileStyle } from './tileStyle' import type { Highlight, TileStyle } from './tileStyle'
@@ -33,9 +33,14 @@ export interface MapStatus {
export interface MapListener { export interface MapListener {
onStatus(status: MapStatus): void onStatus(status: MapStatus): void
onShares(shares: Share[]): void onShares(shares: Share[]): void
/** The world area on screen, reported with the shares: a few times a second while it moves, and once at rest. */
onArea(area: WorldRect): void
onError(message: string): void onError(message: string): void
} }
/** The views whose spots a noise picks, so they can draw that noise. */
const PICK_NOISE_VIEWS = new Set(['biomes', 'regions'])
/** What the map shows at a spot, read from the tiles already drawn. */ /** What the map shows at a spot, read from the tiles already drawn. */
export interface SpotSubjects { export interface SpotSubjects {
subject: Highlight | null subject: Highlight | null
@@ -72,6 +77,7 @@ export class MapController {
private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_BLOCKS_PER_PIXEL, width: 1, height: 1 } private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_BLOCKS_PER_PIXEL, width: 1, height: 1 }
private layer: TileLayer private layer: TileLayer
private toggles: MapToggles = { shading: true, regionBorders: false, grid: false } private toggles: MapToggles = { shading: true, regionBorders: false, grid: false }
private pickDisplay: PickDisplay = 'picks'
private highlight: Highlight | null = null private highlight: Highlight | null = null
private players: Marker[] = [] private players: Marker[] = []
private entities: Marker[] = [] private entities: Marker[] = []
@@ -89,7 +95,7 @@ export class MapController {
private readonly listener: MapListener private readonly listener: MapListener
) { ) {
this.context = canvas.getContext('2d')! this.context = canvas.getContext('2d')!
this.layer = { view, heights: this.needsHeights(view, this.toggles), revision: 0 } 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(client, world.tileSize, () => this.redraw(), (message) => listener.onError(message))
} }
@@ -108,11 +114,29 @@ export class MapController {
this.redraw() this.redraw()
} }
setView(view: string): void { /** Shows a view; the region view previews {@code preview} everywhere when it is not null. */
this.layer = { ...this.layer, view, heights: this.needsHeights(view, this.toggles) } setView(view: string, preview: string | null = null): void {
this.layer = {
...this.layer,
view,
preview: view === 'regions' ? preview : null,
heights: this.needsHeights(view, this.toggles),
pickNoise: this.needsPickNoise(view, this.pickDisplay)
}
this.redraw() this.redraw()
} }
setPickDisplay(display: PickDisplay): void {
this.pickDisplay = display
this.layer = { ...this.layer, pickNoise: this.needsPickNoise(this.layer.view, display) }
this.redraw()
}
// Tiles only carry their pick noise while it is drawn, so drawing the picks alone costs nothing extra.
private needsPickNoise(view: string, display: PickDisplay): boolean {
return display !== 'picks' && PICK_NOISE_VIEWS.has(view)
}
setToggles(toggles: MapToggles): void { setToggles(toggles: MapToggles): void {
this.toggles = toggles this.toggles = toggles
this.layer = { ...this.layer, heights: this.needsHeights(this.layer.view, toggles) } this.layer = { ...this.layer, heights: this.needsHeights(this.layer.view, toggles) }
@@ -214,7 +238,8 @@ export class MapController {
shading: this.toggles.shading, shading: this.toggles.shading,
regionBorders: this.toggles.regionBorders, regionBorders: this.toggles.regionBorders,
highlight: this.highlight, highlight: this.highlight,
seaLevel: this.world.fluidHeight seaLevel: this.world.fluidHeight,
pickDisplay: this.pickDisplay
} }
} }
@@ -375,9 +400,19 @@ export class MapController {
this.censusTimer = window.setTimeout(() => { this.censusTimer = window.setTimeout(() => {
this.lastCensusMillis = performance.now() this.lastCensusMillis = performance.now()
this.listener.onShares(this.census(tiles)) this.listener.onShares(this.census(tiles))
this.listener.onArea(this.screenArea())
}, wait) }, wait)
} }
private screenArea(): WorldRect {
return {
minX: screenToWorldX(this.view, 0),
minZ: screenToWorldZ(this.view, 0),
maxX: screenToWorldX(this.view, this.view.width),
maxZ: screenToWorldZ(this.view, this.view.height)
}
}
private census(tiles: TileAddress[]): Share[] { private census(tiles: TileAddress[]): Share[] {
const placed: PlacedTile[] = [] const placed: PlacedTile[] = []
for (const address of tiles) { for (const address of tiles) {
@@ -387,12 +422,8 @@ export class MapController {
placed.push({ tile, worldX: address.tileX * span, worldZ: address.tileZ * span }) placed.push({ tile, worldX: address.tileX * span, worldZ: address.tileZ * span })
} }
} }
const area = { const screen = this.screenArea()
minimumX: screenToWorldX(this.view, 0), const area = { minimumX: screen.minX, minimumZ: screen.minZ, maximumX: screen.maxX, maximumZ: screen.maxZ }
minimumZ: screenToWorldZ(this.view, 0),
maximumX: screenToWorldX(this.view, this.view.width),
maximumZ: screenToWorldZ(this.view, this.view.height)
}
return countShares(placed, area, this.isHeightView(), this.world.fluidHeight) return countShares(placed, area, this.isHeightView(), this.world.fluidHeight)
} }
} }
+7 -3
View File
@@ -6,7 +6,10 @@ import type { TileAddress } from './viewport'
/** What one tile request needs besides where the tile is. */ /** What one tile request needs besides where the tile is. */
export interface TileLayer { export interface TileLayer {
view: string view: string
/** The region the region view previews everywhere, or null for the world as it is. */
preview: string | null
heights: boolean heights: boolean
pickNoise: boolean
/** Bumped when the pack is hotloaded, so older tiles are not used again. */ /** Bumped when the pack is hotloaded, so older tiles are not used again. */
revision: number revision: number
} }
@@ -44,7 +47,8 @@ export class TileStore {
) {} ) {}
key(address: TileAddress, layer: TileLayer): string { key(address: TileAddress, layer: TileLayer): string {
return `${layer.revision}/${layer.view}/${layer.heights}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}` const parts = [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise]
return `${parts.join('/')}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}`
} }
/** The tile if it has arrived, marked as just used. */ /** The tile if it has arrived, marked as just used. */
@@ -118,7 +122,7 @@ export class TileStore {
private fetchTile(key: string, address: TileAddress, layer: TileLayer): void { private fetchTile(key: string, address: TileAddress, layer: TileLayer): void {
const controller = new AbortController() const controller = new AbortController()
this.inFlight.set(key, controller) this.inFlight.set(key, controller)
const request = { view: layer.view, ...address, size: this.tileSize, heights: layer.heights } const request = { ...layer, ...address, size: this.tileSize }
this.client this.client
.tile(request, controller.signal) .tile(request, controller.signal)
.then((tile) => this.store(key, tile)) .then((tile) => this.store(key, tile))
@@ -139,7 +143,7 @@ export class TileStore {
} }
private store(key: string, tile: MapTile): void { private store(key: string, tile: MapTile): void {
const bytes = tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + tile.size * tile.size * 4 const bytes = tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + tile.size * tile.size * 4
this.tiles.set(key, { tile, bytes, lastUsed: ++this.useClock, picture: null, pictureStyle: '' }) this.tiles.set(key, { tile, bytes, lastUsed: ++this.useClock, picture: null, pictureStyle: '' })
this.storedBytes += bytes this.storedBytes += bytes
this.evictOldest() this.evictOldest()
+43 -5
View File
@@ -9,7 +9,7 @@ import { coarserTile, previewsFor, renderBlocksPerPixel, screenToWorldX, visible
const PLAINS: MapLabel = { kind: 'BIOME', key: 'plains', name: 'Plains', color: 0x00ff00 } const PLAINS: MapLabel = { kind: 'BIOME', key: 'plains', name: 'Plains', color: 0x00ff00 }
const DESERT: MapLabel = { kind: 'BIOME', key: 'desert', name: 'Desert', color: 0xffff00 } const DESERT: MapLabel = { kind: 'BIOME', key: 'desert', name: 'Desert', color: 0xffff00 }
const WARM: MapLabel = { kind: 'REGION', key: 'warm', name: 'Warm', color: 0xff0000 } const WARM: MapLabel = { kind: 'REGION', key: 'warm', name: 'Warm', color: 0xff0000 }
const FLAT: TileStyle = { byHeight: false, shading: false, regionBorders: false, highlight: null, seaLevel: 63 } const FLAT: TileStyle = { byHeight: false, shading: false, regionBorders: false, highlight: null, seaLevel: 63, pickDisplay: 'picks' }
/** A tile whose left half is plains and right half desert, all in one region, at height 70. */ /** A tile whose left half is plains and right half desert, all in one region, at height 70. */
function splitTile(size = 4): MapTile { function splitTile(size = 4): MapTile {
@@ -25,19 +25,23 @@ function splitTile(size = 4): MapTile {
labels: [PLAINS, DESERT, WARM], labels: [PLAINS, DESERT, WARM],
subjects, subjects,
regions: new Int16Array(cells).fill(2), regions: new Int16Array(cells).fill(2),
heights: new Float32Array(cells).fill(70) heights: new Float32Array(cells).fill(70),
pickNoise: null
} }
} }
/** A tile as the bridge sends it: u32 header length, JSON header, aligned grids. */ /** A tile as the bridge sends it: u32 header length, JSON header, aligned grids. */
function encode(size: number, withHeights: boolean): ArrayBuffer { function encode(size: number, withHeights: boolean, withPickNoise = false): ArrayBuffer {
const header = new TextEncoder().encode(JSON.stringify({ size, blocksPerPixel: 2, subjectKind: 'BIOME', labels: [PLAINS], heights: withHeights })) const header = new TextEncoder().encode(
JSON.stringify({ size, blocksPerPixel: 2, subjectKind: 'BIOME', labels: [PLAINS], heights: withHeights, pickNoise: withPickNoise })
)
const cells = (size + 2) ** 2 const cells = (size + 2) ** 2
const align = (bytes: number): number => Math.ceil(bytes / 4) * 4 const align = (bytes: number): number => Math.ceil(bytes / 4) * 4
const subjectsAt = align(4 + header.length) const subjectsAt = align(4 + header.length)
const regionsAt = align(subjectsAt + cells * 2) const regionsAt = align(subjectsAt + cells * 2)
const heightsAt = align(regionsAt + cells * 2) const heightsAt = align(regionsAt + cells * 2)
const buffer = new ArrayBuffer(heightsAt + (withHeights ? cells * 4 : 0)) const pickNoiseAt = heightsAt + (withHeights ? cells * 4 : 0)
const buffer = new ArrayBuffer(pickNoiseAt + (withPickNoise ? cells * 4 : 0))
new DataView(buffer).setUint32(0, header.length, true) new DataView(buffer).setUint32(0, header.length, true)
new Uint8Array(buffer, 4).set(header) new Uint8Array(buffer, 4).set(header)
new Int16Array(buffer, subjectsAt, cells).fill(0) new Int16Array(buffer, subjectsAt, cells).fill(0)
@@ -45,6 +49,9 @@ function encode(size: number, withHeights: boolean): ArrayBuffer {
if (withHeights) { if (withHeights) {
new Float32Array(buffer, heightsAt, cells).fill(81.5) new Float32Array(buffer, heightsAt, cells).fill(81.5)
} }
if (withPickNoise) {
new Float32Array(buffer, pickNoiseAt, cells).fill(0.25)
}
return buffer return buffer
} }
@@ -63,6 +70,37 @@ describe('tile decoding', () => {
it('has no heights when the header says so', () => { it('has no heights when the header says so', () => {
expect(decodeTile(encode(3, false)).heights).toBeNull() expect(decodeTile(encode(3, false)).heights).toBeNull()
}) })
it('reads the pick noise after the heights, or in their place without them', () => {
expect(decodeTile(encode(3, true, true)).pickNoise?.[24]).toBe(0.25)
expect(decodeTile(encode(3, false, true)).pickNoise?.[0]).toBe(0.25)
expect(decodeTile(encode(3, true)).pickNoise).toBeNull()
})
})
describe('pick noise', () => {
function noisyTile(noise: number): MapTile {
const tile = splitTile()
return { ...tile, pickNoise: new Float32Array(tile.subjects.length).fill(noise) }
}
it('draws the bare noise from dark to white', () => {
const pixels = stylePixels(noisyTile(1), { ...FLAT, pickDisplay: 'noise' })
expect([pixels[0], pixels[1], pixels[2]]).toEqual([255, 255, 255])
})
it('draws the picks darker where their noise is lower', () => {
const pixels = stylePixels(noisyTile(0), { ...FLAT, pickDisplay: 'both' })
expect(pixels[1]).toBe(Math.floor(255 * 0.3))
})
it('leaves a spot nothing picked in its own colour', () => {
const pixels = stylePixels(noisyTile(Number.NaN), { ...FLAT, pickDisplay: 'noise' })
expect([pixels[0], pixels[1], pixels[2]]).toEqual([0, 255, 0])
})
}) })
describe('height colours', () => { describe('height colours', () => {
+23 -3
View File
@@ -1,5 +1,5 @@
import { gridIndex } from '../bridge/tileDecoding' import { gridIndex } from '../bridge/tileDecoding'
import { NO_LABEL, type MapTile } from '../bridge/types' import { NO_LABEL, type MapTile, type PickDisplay } from '../bridge/types'
import { bandIndexOf, blend, heightColor } from './heightColors' import { bandIndexOf, blend, heightColor } from './heightColors'
/** What a highlight picks out: a biome or region by key, or a height band in the height view. */ /** What a highlight picks out: a biome or region by key, or a height band in the height view. */
@@ -16,11 +16,13 @@ export interface TileStyle {
regionBorders: boolean regionBorders: boolean
highlight: Highlight | null highlight: Highlight | null
seaLevel: number seaLevel: number
/** How tiles that carry their pick noise draw it. */
pickDisplay: PickDisplay
} }
export function styleKey(style: TileStyle): string { export function styleKey(style: TileStyle): string {
const highlight = style.highlight === null ? '' : `${style.highlight.kind}:${style.highlight.key}` const highlight = style.highlight === null ? '' : `${style.highlight.kind}:${style.highlight.key}`
return `${style.byHeight}|${style.shading}|${style.regionBorders}|${highlight}|${style.seaLevel}` return `${style.byHeight}|${style.shading}|${style.regionBorders}|${highlight}|${style.seaLevel}|${style.pickDisplay}`
} }
const UNKNOWN_SUBJECT = 0x5a5c62 const UNKNOWN_SUBJECT = 0x5a5c62
@@ -43,6 +45,10 @@ const HIGHLIGHT_EDGE = 0xffffff
const HIGHLIGHT_EDGE_STRENGTH = 0.55 const HIGHLIGHT_EDGE_STRENGTH = 0.55
const REGION_BORDER = 0x101114 const REGION_BORDER = 0x101114
const REGION_BORDER_STRENGTH = 0.6 const REGION_BORDER_STRENGTH = 0.6
const NOISE_LOW = 0x050505
const NOISE_HIGH = 0xffffff
// Picks drawn by their noise keep some colour where the noise is low, so they still read as the pick.
const DARKEST_PICK_SHADE = 0.3
/** The tile's pixels as RGBA, as {@code style} draws them (v3e MapTile.styledPixels). */ /** The tile's pixels as RGBA, as {@code style} draws them (v3e MapTile.styledPixels). */
export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray<ArrayBuffer> { export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray<ArrayBuffer> {
@@ -50,12 +56,17 @@ export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray<
const pixels = new Uint8ClampedArray(size * size * 4) const pixels = new Uint8ClampedArray(size * size * 4)
const colors = tile.labels.map((label) => label.color) const colors = tile.labels.map((label) => label.color)
const byHeight = style.byHeight && heights !== null const byHeight = style.byHeight && heights !== null
const shading = (style.shading || byHeight) && heights !== null const pickNoise = style.pickDisplay === 'picks' ? null : tile.pickNoise
// The bare noise is read by its brightness, which relief shading would mix up.
const shading = (style.shading || byHeight) && heights !== null && !(pickNoise !== null && style.pickDisplay === 'noise')
const highlighted = highlightCells(tile, style) const highlighted = highlightCells(tile, style)
for (let pixelZ = 0; pixelZ < size; pixelZ++) { for (let pixelZ = 0; pixelZ < size; pixelZ++) {
for (let pixelX = 0; pixelX < size; pixelX++) { for (let pixelX = 0; pixelX < size; pixelX++) {
const cell = gridIndex(tile, pixelX, pixelZ) const cell = gridIndex(tile, pixelX, pixelZ)
let color = byHeight ? heightColor(heights[cell], style.seaLevel) : labelColor(colors, tile.subjects[cell]) let color = byHeight ? heightColor(heights[cell], style.seaLevel) : labelColor(colors, tile.subjects[cell])
if (pickNoise !== null) {
color = byNoise(color, pickNoise[cell], style.pickDisplay)
}
if (shading) { if (shading) {
color = shade(tile, heights, cell, color, style.seaLevel) color = shade(tile, heights, cell, color, style.seaLevel)
} }
@@ -79,6 +90,15 @@ function labelColor(colors: number[], index: number): number {
return index === NO_LABEL ? UNKNOWN_SUBJECT : colors[index] return index === NO_LABEL ? UNKNOWN_SUBJECT : colors[index]
} }
// Where nothing picked the spot, as on an image map, it keeps its colour.
function byNoise(color: number, noise: number, display: PickDisplay): number {
if (Number.isNaN(noise)) {
return color
}
const value = Math.min(1, Math.max(0, noise))
return display === 'noise' ? blend(NOISE_LOW, NOISE_HIGH, value) : scale(color, DARKEST_PICK_SHADE + (1 - DARKEST_PICK_SHADE) * value)
}
// Lit from the north west like a relief map, so slopes read as hills and valleys at a glance. // Lit from the north west like a relief map, so slopes read as hills and valleys at a glance.
function shade(tile: MapTile, heights: Float32Array, cell: number, color: number, seaLevel: number): number { function shade(tile: MapTile, heights: Float32Array, cell: number, color: number, seaLevel: number): number {
const row = tile.size + 2 const row = tile.size + 2
+6 -3
View File
@@ -10,6 +10,8 @@ interface HoverCardProps {
hover: MapHover hover: MapHover
point: CanvasPoint point: CanvasPoint
viewId: string viewId: string
/** The region view fills the map with one region's biomes, so the spot is described by its previewed biome. */
previewing: boolean
detailed: boolean detailed: boolean
minY: number minY: number
} }
@@ -24,7 +26,7 @@ interface Row {
} }
/** The spot under the cursor: its biome and ground, and with Shift held, the rest of what the server knows. */ /** The spot under the cursor: its biome and ground, and with Shift held, the rest of what the server knows. */
export function HoverCard({ hover, point, viewId, detailed, minY }: HoverCardProps): React.JSX.Element { export function HoverCard({ hover, point, viewId, previewing, detailed, minY }: HoverCardProps): React.JSX.Element {
const card = useRef<HTMLDivElement>(null) const card = useRef<HTMLDivElement>(null)
const [position, setPosition] = useState({ left: point.x + CURSOR_GAP_PIXELS, top: point.y + CURSOR_GAP_PIXELS }) const [position, setPosition] = useState({ left: point.x + CURSOR_GAP_PIXELS, top: point.y + CURSOR_GAP_PIXELS })
@@ -42,7 +44,8 @@ export function HoverCard({ hover, point, viewId, detailed, minY }: HoverCardPro
}) })
}, [point, hover, detailed]) }, [point, hover, detailed])
const subject = viewId === 'caveBiomes' ? hover.caveBiome : viewId === 'regions' ? hover.region : hover.biome const labelsRegions = viewId === 'regions' && !previewing
const subject = viewId === 'caveBiomes' ? hover.caveBiome : labelsRegions ? hover.region : hover.biome
const groups = detailed ? detailGroups(hover, viewId) : [] const groups = detailed ? detailGroups(hover, viewId) : []
const parent = replacedParent(hover.pickPath) const parent = replacedParent(hover.pickPath)
return ( return (
@@ -51,7 +54,7 @@ export function HoverCard({ hover, point, viewId, detailed, minY }: HoverCardPro
className="pointer-events-none absolute z-10 w-80 rounded-[10px] border border-overlay-border bg-popover px-3.5 py-3 text-popover-foreground shadow-xl backdrop-blur-sm" className="pointer-events-none absolute z-10 w-80 rounded-[10px] border border-overlay-border bg-popover px-3.5 py-3 text-popover-foreground shadow-xl backdrop-blur-sm"
style={position} style={position}
> >
<Header subject={subject} region={viewId === 'regions' ? null : hover.region} /> <Header subject={subject} region={labelsRegions ? null : hover.region} />
{parent !== null && <p className="mt-0.5 truncate text-[12px] text-secondary-text">child of {parent}</p>} {parent !== null && <p className="mt-0.5 truncate text-[12px] text-secondary-text">child of {parent}</p>}
<p className="mt-0.5 truncate text-[12px] text-secondary-text tabular-nums">{ground(hover, minY)}</p> <p className="mt-0.5 truncate text-[12px] text-secondary-text tabular-nums">{ground(hover, minY)}</p>
<PickRows path={hover.pickPath} /> <PickRows path={hover.pickPath} />
+4 -3
View File
@@ -9,13 +9,14 @@ interface LegendProps {
shares: Share[] shares: Share[]
highlight: Highlight | null highlight: Highlight | null
onSelect(subject: Highlight): void onSelect(subject: Highlight): void
className?: string
} }
/** What is on screen and how much of it each covers; clicking one highlights it on the map. */ /** What is on screen and how much of it each covers; clicking one highlights it on the map. */
export function Legend({ title, shares, highlight, onSelect }: LegendProps): React.JSX.Element { export function Legend({ title, shares, highlight, onSelect, className }: LegendProps): React.JSX.Element {
const sharedNames = namesUsedMoreThanOnce(shares) const sharedNames = namesUsedMoreThanOnce(shares)
return ( return (
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card"> <section className={cn('flex min-h-0 flex-col', className)}>
<h2 className="px-4 pt-2.5 pb-1.5 text-[11px] font-semibold text-muted-foreground">{title}</h2> <h2 className="px-4 pt-2.5 pb-1.5 text-[11px] font-semibold text-muted-foreground">{title}</h2>
<ScrollArea className="min-h-0 flex-1"> <ScrollArea className="min-h-0 flex-1">
<ul className="px-1.5 pb-1"> <ul className="px-1.5 pb-1">
@@ -44,7 +45,7 @@ export function Legend({ title, shares, highlight, onSelect }: LegendProps): Rea
</ul> </ul>
</ScrollArea> </ScrollArea>
<p className="px-4 pt-1.5 pb-2 text-[11px] text-muted-foreground">Click to highlight · Esc clears</p> <p className="px-4 pt-1.5 pb-2 text-[11px] text-muted-foreground">Click to highlight · Esc clears</p>
</aside> </section>
) )
} }
+1
View File
@@ -56,6 +56,7 @@ export function MapCanvas(props: MapCanvasProps): React.JSX.Element {
const map = new MapController(canvas, client, world, viewId, { const map = new MapController(canvas, client, world, viewId, {
onStatus: (status) => latest.current.listener.onStatus(status), onStatus: (status) => latest.current.listener.onStatus(status),
onShares: (shares) => latest.current.listener.onShares(shares), onShares: (shares) => latest.current.listener.onShares(shares),
onArea: (area) => latest.current.listener.onArea(area),
onError: (message) => latest.current.listener.onError(message) onError: (message) => latest.current.listener.onError(message)
}) })
controllerRef.current = map controllerRef.current = map
+114 -24
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { ThemeChoice } from '../../../shared/bridge' import type { ThemeChoice } from '../../../shared/bridge'
import type { BridgeClient } from '../bridge/BridgeClient' import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient'
import type { MapHover, Marker, WorldInfo } from '../bridge/types' import type { MapHover, MapLabel, Marker, PickDisplay, PickInspection, WorldInfo } from '../bridge/types'
import type { Share } from '../map/census' import type { Share } from '../map/census'
import type { MapController, MapStatus, MapToggles } from '../map/MapController' import type { MapController, MapStatus, MapToggles } from '../map/MapController'
import type { Highlight } from '../map/tileStyle' import type { Highlight } from '../map/tileStyle'
@@ -9,6 +9,8 @@ import { HelpDialog } from './HelpDialog'
import { HoverCard } from './HoverCard' import { HoverCard } from './HoverCard'
import { Legend } from './Legend' import { Legend } from './Legend'
import { MapCanvas, type CanvasPoint } from './MapCanvas' import { MapCanvas, type CanvasPoint } from './MapCanvas'
import { PickInspector } from './PickInspector'
import { RegionPreviewList } from './RegionPreviewList'
import { actionForKey, viewForKey, type ShortcutAction } from './shortcuts' import { actionForKey, viewForKey, type ShortcutAction } from './shortcuts'
import { StatusBar } from './StatusBar' import { StatusBar } from './StatusBar'
import { StudioToolbar } from './StudioToolbar' import { StudioToolbar } from './StudioToolbar'
@@ -17,6 +19,10 @@ import { ViewList } from './ViewList'
const KEYBOARD_ZOOM_FACTOR = 2 ** 0.25 const KEYBOARD_ZOOM_FACTOR = 2 ** 0.25
const ENTITY_POLL_MILLIS = 2000 const ENTITY_POLL_MILLIS = 2000
const NOTICE_MILLIS = 4000 const NOTICE_MILLIS = 4000
// Measuring the picks in view samples thousands of spots, so it waits for the map to rest.
const INSPECTION_REST_MILLIS = 350
/** The views whose spots a noise picks, which the pick inspector explains. */
const PICK_VIEWS = new Set(['biomes', 'regions'])
interface MapStudioProps { interface MapStudioProps {
client: BridgeClient client: BridgeClient
@@ -46,7 +52,16 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
const [helpOpen, setHelpOpen] = useState(false) const [helpOpen, setHelpOpen] = useState(false)
const [notice, setNotice] = useState<string | null>(null) const [notice, setNotice] = useState<string | null>(null)
const [connected, setConnected] = useState(true) const [connected, setConnected] = useState(true)
const [preview, setPreview] = useState<string | null>(null)
const [pickDisplay, setPickDisplay] = useState<PickDisplay>('picks')
const [area, setArea] = useState<WorldRect | null>(null)
const [packRevision, setPackRevision] = useState(0)
const view = world.views.find((candidate) => candidate.id === viewId) ?? world.views[0] const view = world.views.find((candidate) => candidate.id === viewId) ?? world.views[0]
const layer = useMemo<MapLayerQuery>(() => ({ view: viewId, preview: viewId === 'regions' ? preview : null }), [viewId, preview])
const regions = usePreviewableRegions(client, packRevision)
const inspectsPicks = PICK_VIEWS.has(viewId)
const inspection = usePickInspection(client, layer, area, inspectsPicks, packRevision)
const previewName = layer.preview === null ? null : (regions.find((region) => region.key === layer.preview)?.name ?? layer.preview)
const tell = useCallback((message: string) => setNotice(message), []) const tell = useCallback((message: string) => setNotice(message), [])
@@ -58,7 +73,8 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
return () => window.clearTimeout(timer) return () => window.clearTimeout(timer)
}, [notice]) }, [notice])
useEffect(() => controller.current?.setView(viewId), [viewId]) useEffect(() => controller.current?.setView(layer.view, layer.preview), [layer])
useEffect(() => controller.current?.setPickDisplay(pickDisplay), [pickDisplay])
useEffect(() => controller.current?.setToggles(toggles), [toggles]) useEffect(() => controller.current?.setToggles(toggles), [toggles])
useEffect(() => controller.current?.setHighlight(highlight), [highlight]) useEffect(() => controller.current?.setHighlight(highlight), [highlight])
useEffect(() => controller.current?.setMarkers(players, toggles.entities ? entities : []), [players, entities, toggles.entities]) useEffect(() => controller.current?.setMarkers(players, toggles.entities ? entities : []), [players, entities, toggles.entities])
@@ -69,15 +85,21 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
} }
}, [players, toggles.follow]) }, [players, toggles.follow])
useServerEvents(client, controller, setPlayers, tell, setConnected) const packReloaded = useCallback(() => setPackRevision((revision) => revision + 1), [])
useServerEvents(client, controller, setPlayers, tell, setConnected, packReloaded)
useEntities(client, toggles.entities, setEntities) useEntities(client, toggles.entities, setEntities)
useHover(client, controller, viewId, pointer, setHover) useHover(client, controller, layer, pointer, setHover)
const selectView = useCallback((nextViewId: string) => { const selectView = useCallback((nextViewId: string) => {
setViewId(nextViewId) setViewId(nextViewId)
setHighlight(null) setHighlight(null)
}, []) }, [])
const selectPreview = useCallback((regionKey: string | null) => {
setPreview(regionKey)
setHighlight(null)
}, [])
const toggle = useCallback((name: keyof StudioToggles) => setToggles((current) => ({ ...current, [name]: !current[name] })), []) const toggle = useCallback((name: keyof StudioToggles) => setToggles((current) => ({ ...current, [name]: !current[name] })), [])
const highlightUnderCursor = useCallback(() => { const highlightUnderCursor = useCallback(() => {
@@ -181,14 +203,16 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
onDisconnect={onDisconnect} onDisconnect={onDisconnect}
/> />
<div className="flex min-h-0 flex-1"> <div className="flex min-h-0 flex-1">
<ViewList views={world.views} current={viewId} onSelect={selectView} /> <ViewList views={world.views} current={viewId} onSelect={selectView}>
{viewId === 'regions' && regions.length > 1 && <RegionPreviewList regions={regions} current={layer.preview} onSelect={selectPreview} />}
</ViewList>
<div className="relative min-w-0 flex-1"> <div className="relative min-w-0 flex-1">
<MapCanvas <MapCanvas
client={client} client={client}
world={world} world={world}
viewId={viewId} viewId={viewId}
controllerRef={controller} controllerRef={controller}
listener={{ onStatus: setStatus, onShares: setShares, onError: tell }} listener={{ onStatus: setStatus, onShares: setShares, onArea: (next) => setArea((current) => (sameRect(current, next) ? current : next)), onError: tell }}
onPointer={setPointer} onPointer={setPointer}
onDragged={() => setToggles((current) => (current.follow ? { ...current, follow: false } : current))} onDragged={() => setToggles((current) => (current.follow ? { ...current, follow: false } : current))}
onTeleport={teleport} onTeleport={teleport}
@@ -201,7 +225,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
}} }}
/> />
{pointer !== null && hover !== null && ( {pointer !== null && hover !== null && (
<HoverCard hover={hover} point={pointer} viewId={viewId} detailed={detailed} minY={world.minY} /> <HoverCard hover={hover} point={pointer} viewId={viewId} previewing={layer.preview !== null} detailed={detailed} minY={world.minY} />
)} )}
{!connected && ( {!connected && (
<div className="absolute inset-0 flex items-center justify-center bg-background/70"> <div className="absolute inset-0 flex items-center justify-center bg-background/70">
@@ -214,14 +238,26 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
</div> </div>
)} )}
</div> </div>
<Legend <aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
title={legendTitle(viewId)} {inspectsPicks && (
shares={shares} <PickInspector
highlight={highlight} title={previewName ?? view.label}
onSelect={(subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject))} picksLabel={viewId === 'regions' && layer.preview === null ? 'Regions' : 'Biomes'}
/> inspection={inspection}
display={pickDisplay}
onDisplay={setPickDisplay}
/>
)}
<Legend
className={inspectsPicks ? 'flex-[3]' : 'flex-1'}
title={legendTitle(layer)}
shares={shares}
highlight={highlight}
onSelect={(subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject))}
/>
</aside>
</div> </div>
<StatusBar viewLabel={view.label} status={status} notice={notice} /> <StatusBar viewLabel={previewName === null ? view.label : `${view.label} · ${previewName}`} status={status} notice={notice} />
<HelpDialog open={helpOpen} onOpenChange={setHelpOpen} views={world.views} /> <HelpDialog open={helpOpen} onOpenChange={setHelpOpen} views={world.views} />
</div> </div>
) )
@@ -231,11 +267,63 @@ function sameSubject(first: Highlight | null, second: Highlight | null): boolean
return first !== null && second !== null && first.kind === second.kind && first.key === second.key return first !== null && second !== null && first.kind === second.kind && first.key === second.key
} }
function legendTitle(viewId: string): string { function sameRect(first: WorldRect | null, second: WorldRect): boolean {
if (viewId === 'regions') { return first !== null && first.minX === second.minX && first.minZ === second.minZ && first.maxX === second.maxX && first.maxZ === second.maxZ
}
function legendTitle(layer: MapLayerQuery): string {
if (layer.view === 'regions' && layer.preview === null) {
return 'Regions on screen' return 'Regions on screen'
} }
return viewId === 'height' ? 'Heights on screen' : 'Biomes on screen' return layer.view === 'height' ? 'Heights on screen' : 'Biomes on screen'
}
/** The regions the region view can preview, read again after the pack reloads. */
function usePreviewableRegions(client: BridgeClient, packRevision: number): MapLabel[] {
const [regions, setRegions] = useState<MapLabel[]>([])
useEffect(() => {
let active = true
client
.regions()
.then((found) => active && setRegions(found))
.catch(() => undefined)
return () => {
active = false
}
}, [client, packRevision])
return regions
}
/**
* Measures how the noise picks what the view shows, once the map has rested on an area for a moment; the last
* measurement stays up until the next one arrives, so panning does not blank the panel.
*/
function usePickInspection(
client: BridgeClient,
layer: MapLayerQuery,
area: WorldRect | null,
enabled: boolean,
packRevision: number
): PickInspection | null {
const [inspection, setInspection] = useState<PickInspection | null>(null)
useEffect(() => setInspection(null), [layer, packRevision])
useEffect(() => {
if (!enabled || area === null) {
return
}
const stop = new AbortController()
const timer = window.setTimeout(() => {
client
.picks(layer, area, stop.signal)
.then(setInspection)
.catch(() => undefined)
}, INSPECTION_REST_MILLIS)
return () => {
window.clearTimeout(timer)
stop.abort()
}
}, [client, layer, area, enabled, packRevision])
return inspection
} }
/** Players and hotloads from the server; the first world event only says the world runs, which is known. */ /** Players and hotloads from the server; the first world event only says the world runs, which is known. */
@@ -244,7 +332,8 @@ function useServerEvents(
controller: React.RefObject<MapController | null>, controller: React.RefObject<MapController | null>,
setPlayers: (players: Marker[]) => void, setPlayers: (players: Marker[]) => void,
tell: (message: string) => void, tell: (message: string) => void,
setConnected: (connected: boolean) => void setConnected: (connected: boolean) => void,
onPackReloaded: () => void
): void { ): void {
useEffect(() => { useEffect(() => {
const stop = new AbortController() const stop = new AbortController()
@@ -258,6 +347,7 @@ function useServerEvents(
} }
if (running) { if (running) {
controller.current?.refresh() controller.current?.refresh()
onPackReloaded()
tell('Pack reloaded, redrawing') tell('Pack reloaded, redrawing')
} else { } else {
tell('The world stopped') tell('The world stopped')
@@ -269,7 +359,7 @@ function useServerEvents(
stop.signal stop.signal
) )
return () => stop.abort() return () => stop.abort()
}, [client, controller, setPlayers, tell, setConnected]) }, [client, controller, setPlayers, tell, setConnected, onPackReloaded])
} }
function useEntities(client: BridgeClient, visible: boolean, setEntities: (entities: Marker[]) => void): void { function useEntities(client: BridgeClient, visible: boolean, setEntities: (entities: Marker[]) => void): void {
@@ -297,7 +387,7 @@ function useEntities(client: BridgeClient, visible: boolean, setEntities: (entit
function useHover( function useHover(
client: BridgeClient, client: BridgeClient,
controller: React.RefObject<MapController | null>, controller: React.RefObject<MapController | null>,
viewId: string, layer: MapLayerQuery,
pointer: CanvasPoint | null, pointer: CanvasPoint | null,
setHover: (hover: MapHover | null) => void setHover: (hover: MapHover | null) => void
): void { ): void {
@@ -309,11 +399,11 @@ function useHover(
const spot = controller.current.worldAt(pointer.x, pointer.y) const spot = controller.current.worldAt(pointer.x, pointer.y)
const stop = new AbortController() const stop = new AbortController()
client client
.hover(viewId, Math.floor(spot.x), Math.floor(spot.z), stop.signal) .hover(layer, Math.floor(spot.x), Math.floor(spot.z), stop.signal)
.then(setHover) .then(setHover)
.catch(() => undefined) .catch(() => undefined)
return () => stop.abort() return () => stop.abort()
}, [client, controller, viewId, pointer, setHover]) }, [client, controller, layer, pointer, setHover])
} }
function useKeyboard( function useKeyboard(
+131
View File
@@ -0,0 +1,131 @@
import { useState } from 'react'
import { cn } from '@/lib/utils'
import type { PickShare, PickSpread } from '../bridge/types'
import { hexColor } from './colors'
// A long table keeps the options with the most ground in view until asked for all.
const SHORT_TABLE_ROWS = 6
// An option getting under half or over twice its share of the noise stands out.
const FAR_FROM_WEIGHT_FACTOR = 2
interface NoiseChartProps {
spread: PickSpread
/** What the noise picks, as the table's heading: "Regions" or "Biomes". */
optionNoun: string
}
/**
* One noise that picks regions or biomes: how its values in view spread over the bands that pick each option, and a
* table of each option's share of the noise against its share of the ground in view (v3e NoisePickChart).
*/
export function NoiseChart({ spread, optionNoun }: NoiseChartProps): React.JSX.Element {
if (spread.rows.length === 1) {
return (
<section className="py-2.5">
<ChartTitle>{spread.title}</ChartTitle>
<div className="mt-1.5 flex items-center gap-2 text-[12px]">
<OptionName share={spread.rows[0]} rows={spread.rows} />
<span className="shrink-0 text-secondary-text">Picked everywhere</span>
</div>
</section>
)
}
return (
<section className="py-2.5">
<ChartTitle>{spread.title}</ChartTitle>
<Spread spread={spread} />
<ShareTable rows={spread.rows} optionNoun={optionNoun} />
</section>
)
}
function ChartTitle({ children }: { children: React.ReactNode }): React.JSX.Element {
return <h4 className="truncate text-[11px] font-semibold text-muted-foreground">{children}</h4>
}
function Spread({ spread }: { spread: PickSpread }): React.JSX.Element {
const peak = Math.max(1, ...spread.histogram)
return (
<div className="mt-1.5">
<div className="relative flex h-12 items-end gap-px">
{spread.histogram.map((count, bin) => (
<span key={bin} className="flex-1 rounded-t-[1px] bg-secondary-text/45" style={{ height: `${(count / peak) * 100}%` }} />
))}
{spread.bands.slice(0, -1).map((band, index) => (
<span key={index} className="absolute inset-y-0 w-px bg-foreground/20" style={{ left: `${band.to * 100}%` }} />
))}
</div>
<div className="mt-0.5 flex h-2.5 overflow-hidden rounded-[2px]">
{spread.bands.map((band, index) => (
<span
key={index}
title={band.option.name}
className="h-full"
style={{ flexGrow: band.to - band.from, flexBasis: 0, backgroundColor: hexColor(band.option.color) }}
/>
))}
</div>
<div className="mt-0.5 flex justify-between font-mono text-[10.5px] text-secondary-text">
<span>0</span>
<span>0.5</span>
<span>1</span>
</div>
</div>
)
}
function ShareTable({ rows, optionNoun }: { rows: PickShare[]; optionNoun: string }): React.JSX.Element {
const [showsAll, setShowsAll] = useState(false)
const long = rows.length > SHORT_TABLE_ROWS
const shown = showsAll || !long ? rows : largestInView(rows)
return (
<div className="mt-2 grid grid-cols-[1fr_auto_auto] items-center gap-x-2.5 gap-y-0.5 text-[12px]">
<span className="text-[11px] font-semibold text-muted-foreground">{optionNoun}</span>
<span className="text-right text-[11px] font-semibold text-muted-foreground">Weight</span>
<span className="text-right text-[11px] font-semibold text-muted-foreground">In view</span>
{shown.map((share) => (
<ShareRow key={share.option.key} share={share} rows={rows} />
))}
{long && (
<button className="col-span-3 justify-self-start py-0.5 text-link hover:underline" onClick={() => setShowsAll(!showsAll)}>
{showsAll ? 'Show fewer' : `Show all ${rows.length} ${optionNoun.toLowerCase()}`}
</button>
)}
</div>
)
}
function ShareRow({ share, rows }: { share: PickShare; rows: PickShare[] }): React.JSX.Element {
const farFromWeight = share.inView * FAR_FROM_WEIGHT_FACTOR < share.weight || share.inView > share.weight * FAR_FROM_WEIGHT_FACTOR
return (
<>
<OptionName share={share} rows={rows} />
<span className="text-right text-secondary-text tabular-nums">{percent(share.weight)}</span>
<span className={cn('text-right tabular-nums', farFromWeight && 'text-warning')}>{percent(share.inView)}</span>
</>
)
}
// Two biomes in different folders can share a name, so their keys tell them apart.
function OptionName({ share, rows }: { share: PickShare; rows: PickShare[] }): React.JSX.Element {
const shared = rows.some((other) => other !== share && other.option.name === share.option.name)
return (
<span className="flex min-w-0 flex-1 items-center gap-1.5" title={share.option.key}>
<span className="size-2.5 shrink-0 rounded-[3px]" style={{ backgroundColor: hexColor(share.option.color) }} />
<span className="truncate">{shared ? `${share.option.name} (${share.option.key})` : share.option.name}</span>
</span>
)
}
/** The rows with the most ground in view, still in the order the noise meets them. */
export function largestInView(rows: PickShare[]): PickShare[] {
const largest = new Set([...rows].sort((first, second) => second.inView - first.inView).slice(0, SHORT_TABLE_ROWS))
return rows.filter((row) => largest.has(row))
}
export function percent(fraction: number): string {
if (fraction > 0 && fraction < 0.001) {
return '<0.1%'
}
return `${(fraction * 100).toFixed(1)}%`
}
+112
View File
@@ -0,0 +1,112 @@
import { ChevronRight } from 'lucide-react'
import { useState } from 'react'
import { ScrollArea } from '@/components/ui/scroll-area'
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
import type { PickDisplay, PickInspection, PickSection } from '../bridge/types'
import { hexColor } from './colors'
import { NoiseChart, percent } from './NoiseChart'
// The chosen display reads like the toolbar's switched-on toggles.
const DISPLAY_ITEM = 'h-7 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground'
interface PickInspectorProps {
/** What is inspected: "Regions", "Biomes", or the previewed region's name. */
title: string
/** What the map shows when it draws the picks: "Regions" or "Biomes". */
picksLabel: string
/** The latest measurement of the view; null until the first one arrives. */
inspection: PickInspection | null
display: PickDisplay
onDisplay(display: PickDisplay): void
}
/**
* How noise picks the regions or biomes in view, measured against what is in view, with a switch for how the map
* draws the picks (v3e PickInspectorPanel).
*/
export function PickInspector({ title, picksLabel, inspection, display, onDisplay }: PickInspectorProps): React.JSX.Element {
return (
<section className="flex min-h-0 flex-[7] flex-col border-b">
<header className="px-4 pt-2.5 pb-2.5">
<h2 className="truncate text-[13px] font-semibold">{title}</h2>
<p className="truncate text-[11.5px] text-secondary-text">{inspection?.detail ?? 'Measuring what is in view…'}</p>
<ToggleGroup
type="single"
variant="outline"
size="sm"
className="mt-2 w-full"
value={display}
onValueChange={(value) => value !== '' && onDisplay(value as PickDisplay)}
>
<ToggleGroupItem value="picks" className={DISPLAY_ITEM}>
{picksLabel}
</ToggleGroupItem>
<ToggleGroupItem value="noise" className={DISPLAY_ITEM}>
Noise
</ToggleGroupItem>
<ToggleGroupItem value="both" className={DISPLAY_ITEM}>
Both
</ToggleGroupItem>
</ToggleGroup>
</header>
<ScrollArea className="min-h-0 flex-1 border-t">
<div className="px-4 pb-2">{inspection !== null && <Sections sections={inspection.sections} />}</div>
</ScrollArea>
</section>
)
}
// A single section is the whole view, so its charts stand on their own; several are one region each, folded.
function Sections({ sections }: { sections: PickSection[] }): React.JSX.Element {
const [opened, setOpened] = useState<Set<string> | null>(null)
if (sections.length === 1) {
return <Charts section={sections[0]} />
}
const open = opened ?? new Set(sections.slice(0, 1).map(sectionKey))
const toggle = (key: string): void => {
const next = new Set(open)
if (!next.delete(key)) {
next.add(key)
}
setOpened(next)
}
return (
<>
{sections.map((section) => (
<RegionSection key={sectionKey(section)} section={section} open={open.has(sectionKey(section))} onToggle={() => toggle(sectionKey(section))} />
))}
</>
)
}
function RegionSection({ section, open, onToggle }: { section: PickSection; open: boolean; onToggle(): void }): React.JSX.Element {
const region = section.region
return (
<div className="border-b last:border-b-0">
<button className="-mx-1.5 flex w-[calc(100%+12px)] items-center gap-2 rounded-md px-1.5 py-2 text-left hover:bg-accent" onClick={onToggle}>
<ChevronRight className={`size-3.5 shrink-0 text-secondary-text transition-transform ${open ? 'rotate-90' : ''}`} />
{region !== null && <span className="size-2.5 shrink-0 rounded-[3px]" style={{ backgroundColor: hexColor(region.color) }} />}
<span className="min-w-0 flex-1 truncate font-medium">{region?.name ?? 'Regions'}</span>
<span className="shrink-0 text-[11.5px] text-secondary-text tabular-nums">
{percent(section.share)} · {section.biomeCount === 1 ? '1 biome' : `${section.biomeCount} biomes`}
</span>
</button>
{open && <Charts section={section} />}
</div>
)
}
function Charts({ section }: { section: PickSection }): React.JSX.Element {
const optionNoun = section.region === null ? 'Regions' : 'Biomes'
return (
<div className="divide-y">
{section.spreads.map((spread) => (
<NoiseChart key={spread.title} spread={spread} optionNoun={optionNoun} />
))}
</div>
)
}
function sectionKey(section: PickSection): string {
return section.region?.key ?? ''
}
+4 -1
View File
@@ -4,6 +4,8 @@ import { hexColor } from './colors'
// Gaps between bands shrink as there are more of them, so many thin bands still read as a bar. // Gaps between bands shrink as there are more of them, so many thin bands still read as a bar.
const WIDE_GAP_MOST_BANDS = 18 const WIDE_GAP_MOST_BANDS = 18
const NARROW_GAP_MOST_BANDS = 50 const NARROW_GAP_MOST_BANDS = 50
/** Why a step that nothing picked has its label. */
const UNPICKED_NOTES: Partial<Record<PickStep['kind'], string>> = { FOCUS: 'Focus', IMAGE_MAP: 'Image map', PREVIEW: 'Preview' }
/** How the spot got its region and biome: one row per pick, the noise value marked on every option's share of it. */ /** How the spot got its region and biome: one row per pick, the noise value marked on every option's share of it. */
export function PickRows({ path }: { path: PickStep[] }): React.JSX.Element | null { export function PickRows({ path }: { path: PickStep[] }): React.JSX.Element | null {
@@ -24,7 +26,7 @@ function PickRow({ step }: { step: PickStep }): React.JSX.Element {
<> <>
<span className="text-muted-foreground">{rowLabel(step)}</span> <span className="text-muted-foreground">{rowLabel(step)}</span>
{step.noise === null ? ( {step.noise === null ? (
<span className="truncate text-secondary-text">{step.kind === 'FOCUS' ? 'Focus' : 'Image map'}</span> <span className="truncate text-secondary-text">{UNPICKED_NOTES[step.kind] ?? ''}</span>
) : ( ) : (
<NoiseBar bands={step.bands} noise={step.noise} /> <NoiseBar bands={step.bands} noise={step.noise} />
)} )}
@@ -73,6 +75,7 @@ function rowLabel(step: PickStep): string {
return 'Child' return 'Child'
case 'IMAGE_MAP': case 'IMAGE_MAP':
case 'FOCUS': case 'FOCUS':
case 'PREVIEW':
return step.picked.kind === 'REGION' ? 'Region' : 'Biome' return step.picked.kind === 'REGION' ? 'Region' : 'Biome'
} }
} }
@@ -0,0 +1,72 @@
import { useState } from 'react'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
import type { MapLabel } from '../bridge/types'
import { hexColor } from './colors'
// Short lists are scanned at a glance; longer ones get a search field.
const SEARCHABLE_FROM_REGIONS = 8
interface RegionPreviewListProps {
regions: MapLabel[]
/** The previewed region's key, or null for all regions. */
current: string | null
onSelect(regionKey: string | null): void
}
/** The region view's regions, any of which can fill the map with its biomes, or all of them as they are (v3e RegionNavigator). */
export function RegionPreviewList({ regions, current, onSelect }: RegionPreviewListProps): React.JSX.Element {
const [search, setSearch] = useState('')
const wanted = search.trim().toLowerCase()
const shown = wanted === '' ? regions : regions.filter((region) => `${region.name} ${region.key}`.toLowerCase().includes(wanted))
return (
<section>
<h2 className="px-2 pt-1 pb-1.5 text-[11px] font-semibold text-muted-foreground">Preview a region</h2>
{regions.length >= SEARCHABLE_FROM_REGIONS && (
<Input
className="mb-1 h-7 text-[12px]"
placeholder="Find a region"
value={search}
onChange={(event) => setSearch(event.target.value)}
onKeyDown={(event) => event.key === 'Escape' && setSearch('')}
/>
)}
<RegionRow name="All regions" color={null} selected={current === null} onSelect={() => onSelect(null)} />
{shown.map((region) => (
<RegionRow
key={region.key}
name={region.name}
color={region.color}
title={region.key}
selected={region.key === current}
onSelect={() => onSelect(region.key)}
/>
))}
{shown.length === 0 && <p className="px-2 py-1 text-[12px] text-muted-foreground">No region matches</p>}
</section>
)
}
interface RegionRowProps {
name: string
color: number | null
title?: string
selected: boolean
onSelect(): void
}
function RegionRow({ name, color, title, selected, onSelect }: RegionRowProps): React.JSX.Element {
return (
<button
onClick={onSelect}
title={title}
className={cn('flex h-[26px] w-full items-center gap-2 rounded-md px-2 text-left', selected ? 'bg-selection' : 'hover:bg-accent')}
>
<span
className={cn('size-3 shrink-0 rounded-[3px]', color === null && 'border border-secondary-text/60')}
style={color === null ? undefined : { backgroundColor: hexColor(color) }}
/>
<span className="truncate">{name}</span>
</button>
)
}
+4 -1
View File
@@ -18,10 +18,12 @@ interface ViewListProps {
views: ViewInfo[] views: ViewInfo[]
current: string current: string
onSelect(view: string): void onSelect(view: string): void
/** What the current view adds below the views, such as the regions it can preview. */
children?: React.ReactNode
} }
/** The views the server offers, in its groups, each with what it shows and its key. */ /** The views the server offers, in its groups, each with what it shows and its key. */
export function ViewList({ views, current, onSelect }: ViewListProps): React.JSX.Element { export function ViewList({ views, current, onSelect, children }: ViewListProps): React.JSX.Element {
const groups = [...new Set(views.map((view) => view.groupLabel))] const groups = [...new Set(views.map((view) => view.groupLabel))]
return ( return (
<aside className="w-60 shrink-0 border-r bg-card"> <aside className="w-60 shrink-0 border-r bg-card">
@@ -37,6 +39,7 @@ export function ViewList({ views, current, onSelect }: ViewListProps): React.JSX
))} ))}
</section> </section>
))} ))}
{children}
</nav> </nav>
</ScrollArea> </ScrollArea>
</aside> </aside>