diff --git a/studio/src/renderer/src/map/census.ts b/studio/src/renderer/src/map/census.ts index 83df8b6ee..04851c1d5 100644 --- a/studio/src/renderer/src/map/census.ts +++ b/studio/src/renderer/src/map/census.ts @@ -61,6 +61,21 @@ export function countShares(tiles: PlacedTile[], area: WorldArea, byHeight: bool .sort((first, second) => second.fraction - first.fraction) } +/** The shares of the height bands the {@code heights} fall in, highest band first. */ +export function heightBandShares(heights: readonly number[], seaLevel: number): Share[] { + const counts = new Map() + for (const height of heights) { + const band = bandIndexOf(height, seaLevel) + counts.set(band, (counts.get(band) ?? 0) + 1) + } + return [...counts] + .sort(([firstBand], [secondBand]) => secondBand - firstBand) + .map(([band, count]) => { + const { key, name, color } = HEIGHT_BANDS[band] + return { subject: { kind: 'HEIGHT', key, name }, color, fraction: count / heights.length } + }) +} + function subjectAt(tile: MapTile, cell: number, byHeight: boolean, seaLevel: number): { subject: Highlight; color: number } | null { if (byHeight) { if (tile.heights === null) { diff --git a/studio/src/renderer/src/map/map.test.ts b/studio/src/renderer/src/map/map.test.ts index 1bbcca662..82b2a519b 100644 --- a/studio/src/renderer/src/map/map.test.ts +++ b/studio/src/renderer/src/map/map.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { decodeTile, gridIndex } from '../bridge/tileDecoding' import type { MapLabel, MapTile } from '../bridge/types' -import { countShares } from './census' +import { countShares, heightBandShares } from './census' import { bandIndexOf, HEIGHT_BANDS, heightColor } from './heightColors' import { arrowCorners } from './playerArrow' import { stylePixels, type TileStyle } from './tileStyle' @@ -214,6 +214,18 @@ describe('census', () => { expect(shares).toHaveLength(1) expect(shares[0].subject).toMatchObject({ kind: 'HEIGHT', name: '0–8 above sea' }) }) + + it('shares spot heights between their bands, highest band first', () => { + const shares = heightBandShares([64, 64, 64, 500, 30], 63) + + expect(shares.map((share) => share.subject.name)).toEqual(['300+ above sea', '0–8 above sea', '10–40 below sea']) + expect(shares.map((share) => share.fraction)).toEqual([0.2, 0.6, 0.2]) + expect(shares[1].color).toBe(HEIGHT_BANDS[bandIndexOf(64, 63)].color) + }) + + it('has no shares for no heights', () => { + expect(heightBandShares([], 63)).toEqual([]) + }) }) describe('player arrow', () => { diff --git a/studio/src/renderer/src/scene/columnField.ts b/studio/src/renderer/src/scene/columnField.ts index 62b95cc47..e0218fb65 100644 --- a/studio/src/renderer/src/scene/columnField.ts +++ b/studio/src/renderer/src/scene/columnField.ts @@ -72,9 +72,22 @@ export class ColumnField { /** The face shown to the sky over the world block, or null where the field has none. */ surfaceTopOver(worldX: number, worldZ: number): number | null { - const column = Math.floor((worldX - this.originX) / this.blocksPerColumn) - const row = Math.floor((worldZ - this.originZ) / this.blocksPerColumn) - return this.surfaceTop(column, row) + return this.surfaceTop(this.columnOf(worldX), this.rowOf(worldZ)) + } + + /** The top face of the ground under any water over the world block, or null where the field has none. */ + groundTopOver(worldX: number, worldZ: number): number | null { + const column = this.columnOf(worldX) + const row = this.rowOf(worldZ) + return this.hasGround(column, row) ? this.groundTop[this.indexOf(column, row)] : null + } + + private columnOf(worldX: number): number { + return Math.floor((worldX - this.originX) / this.blocksPerColumn) + } + + private rowOf(worldZ: number): number { + return Math.floor((worldZ - this.originZ) / this.blocksPerColumn) } private holeMask(holes: readonly ColumnArea[]): Uint8Array { diff --git a/studio/src/renderer/src/scene/groundInView.test.ts b/studio/src/renderer/src/scene/groundInView.test.ts new file mode 100644 index 000000000..0cb83389e --- /dev/null +++ b/studio/src/renderer/src/scene/groundInView.test.ts @@ -0,0 +1,62 @@ +import { PerspectiveCamera, Vector3 } from 'three' +import { describe, expect, it } from 'vitest' +import { ColumnField } from './columnField' +import { groundInView } from './groundInView' + +const GROUND = 70 +const CEILING = 128 +const FIELD_BLOCKS = 4000 +const BLOCKS_PER_COLUMN = 8 +const VIEW_WIDTH = 1280 +const VIEW_HEIGHT = 800 + +// A square of flat ground from the origin, with a ridge ten blocks higher along its eastern edge. +const RIDGE_FROM_X = 3000 +const ground = new ColumnField({ + columns: FIELD_BLOCKS / BLOCKS_PER_COLUMN, + rows: FIELD_BLOCKS / BLOCKS_PER_COLUMN, + originX: 0, + originZ: 0, + blocksPerColumn: BLOCKS_PER_COLUMN, + groundAt: (column) => (column * BLOCKS_PER_COLUMN >= RIDGE_FROM_X ? GROUND + 10 : GROUND), + waterAt: () => null, + colorAt: () => 0 +}) + +function lookDownFrom(position: Vector3, lookedAt: Vector3): { camera: PerspectiveCamera; width: number; height: number; orbitDistance: number } { + const camera = new PerspectiveCamera(45, VIEW_WIDTH / VIEW_HEIGHT, 1, 20_000) + camera.position.copy(position) + camera.lookAt(lookedAt) + camera.updateMatrixWorld() + return { camera, width: VIEW_WIDTH, height: VIEW_HEIGHT, orbitDistance: position.distanceTo(lookedAt) } +} + +const drawn = { + surfaceTopOver: (x: number, z: number) => ground.surfaceTopOver(x, z), + groundTopOver: (x: number, z: number) => ground.groundTopOver(x, z) +} + +describe('ground in view', () => { + it('boxes the ground the camera looks down at and reads its height', () => { + const seen = groundInView(lookDownFrom(new Vector3(1000, 400, 1400), new Vector3(1000, GROUND, 1000)), CEILING, drawn)! + + expect(seen.heights.length).toBeGreaterThan(100) + expect(new Set(seen.heights)).toEqual(new Set([GROUND])) + expect(seen.area.minX).toBeLessThan(1000) + expect(seen.area.maxX).toBeGreaterThan(1000) + expect(seen.area.minZ).toBeLessThan(1000) + expect(seen.area.maxZ).toBeGreaterThan(1000) + expect(seen.area.maxX).toBeLessThan(FIELD_BLOCKS) + }) + + it('reads the height of every kind of ground in view', () => { + const seen = groundInView(lookDownFrom(new Vector3(3000, 400, 1400), new Vector3(3000, GROUND, 1000)), CEILING, drawn)! + + expect(new Set(seen.heights)).toEqual(new Set([GROUND, GROUND + 10])) + }) + + it('sees no ground over where nothing is drawn, or when looking at the sky', () => { + expect(groundInView(lookDownFrom(new Vector3(9000, 400, 1400), new Vector3(9000, GROUND, 1000)), CEILING, drawn)).toBeNull() + expect(groundInView(lookDownFrom(new Vector3(1000, 400, 1400), new Vector3(1000, 900, 1000)), CEILING, drawn)).toBeNull() + }) +}) diff --git a/studio/src/renderer/src/scene/groundInView.ts b/studio/src/renderer/src/scene/groundInView.ts new file mode 100644 index 000000000..84e108122 --- /dev/null +++ b/studio/src/renderer/src/scene/groundInView.ts @@ -0,0 +1,66 @@ +import { Ray, Vector3 } from 'three' +import type { WorldRect } from '../bridge/BridgeClient' +import type { SightView } from './cameraSight' +import { marchOntoSurface } from './surfaceMarch' + +/** Where the ground drawn so far stands: over a block, what the sky sees there, and the ground under any water. Null where nothing is known. */ +export interface DrawnGround { + surfaceTopOver(worldX: number, worldZ: number): number | null + groundTopOver(worldX: number, worldZ: number): number | null +} + +/** The ground the camera looks at: the box around it, and the height of the ground at each spot looked at. */ +export interface GroundInView { + area: WorldRect + heights: number[] +} + +// The spots are laid across the longer side of the view, as many along the shorter side as keeps them evenly apart. +const SPOTS_ALONG_LONGER_SIDE = 32 +const NDC_MIDDLE_DEPTH = 0.5 +const NDC_SPAN = 2 +const SMALLEST_AREA_SIDE_BLOCKS = 1 + +/** + * What the camera sees of {@code ground}: rays through an even grid of spots on the screen, each met where it comes + * down onto the ground, and the box around the places they meet. Null when no ray meets any ground. + * + * @param ceilingY the height above which no ground stands + */ +export function groundInView(view: SightView, ceilingY: number, ground: DrawnGround): GroundInView | null { + const { camera } = view + camera.updateMatrixWorld() + const eye = camera.getWorldPosition(new Vector3()) + const longer = Math.max(view.width, view.height) + const spotsAcross = Math.max(1, Math.round((SPOTS_ALONG_LONGER_SIDE * view.width) / longer)) + const spotsDown = Math.max(1, Math.round((SPOTS_ALONG_LONGER_SIDE * view.height) / longer)) + const heights: number[] = [] + let [minX, minZ, maxX, maxZ] = [Infinity, Infinity, -Infinity, -Infinity] + for (let spotZ = 0; spotZ < spotsDown; spotZ++) { + for (let spotX = 0; spotX < spotsAcross; spotX++) { + const through = new Vector3(centreOf(spotX, spotsAcross), -centreOf(spotZ, spotsDown), NDC_MIDDLE_DEPTH).unproject(camera) + const ray = new Ray(eye, through.sub(eye).normalize()) + const hit = marchOntoSurface(ray, camera.far, ceilingY, (x, z) => ground.surfaceTopOver(x, z)) + const groundTop = hit === null ? null : ground.groundTopOver(hit.x, hit.z) + if (hit === null || groundTop === null) { + continue + } + heights.push(groundTop - 1) + minX = Math.min(minX, hit.x) + maxX = Math.max(maxX, hit.x) + minZ = Math.min(minZ, hit.z) + maxZ = Math.max(maxZ, hit.z) + } + } + if (heights.length === 0) { + return null + } + return { + area: { minX, minZ, maxX: Math.max(maxX, minX + SMALLEST_AREA_SIDE_BLOCKS), maxZ: Math.max(maxZ, minZ + SMALLEST_AREA_SIDE_BLOCKS) }, + heights + } +} + +function centreOf(spot: number, spots: number): number { + return -1 + ((spot + 0.5) * NDC_SPAN) / spots +} diff --git a/studio/src/renderer/src/scene/terrainStream.test.ts b/studio/src/renderer/src/scene/terrainStream.test.ts index 94d38d9c5..58ecfe49b 100644 --- a/studio/src/renderer/src/scene/terrainStream.test.ts +++ b/studio/src/renderer/src/scene/terrainStream.test.ts @@ -163,6 +163,26 @@ describe('terrain stream', () => { expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(71, 3) }) + it('reads the height of the ground the camera looks at once it is drawn, and tells when the view may have changed', async () => { + const { stream, camera, moved } = setUp() + const sightChanges = vi.fn() + stream.onSightChanged(sightChanges) + stream.restyle(flatStyle) + expect(stream.groundInView()).toBeNull() + stream.showLayer({ name: 'one', height: 70, gate: open }) + await settle() + expect(sightChanges).toHaveBeenCalled() + const seen = stream.groundInView()! + expect(new Set(seen.heights)).toEqual(new Set([70])) + expect(seen.area.maxX).toBeGreaterThan(seen.area.minX) + + camera.position.set(40_000, 664, 360) + camera.lookAt(new Vector3(40_000, 64, 0)) + moved() + await settle() + expect(stream.groundInView()!.area.minX).toBeGreaterThan(seen.area.maxX) + }) + it('stops drawing when it is let go', async () => { const { stream, stopFollowing, requested } = setUp() stream.restyle(flatStyle) diff --git a/studio/src/renderer/src/scene/terrainStream.ts b/studio/src/renderer/src/scene/terrainStream.ts index d9035e98b..561131f78 100644 --- a/studio/src/renderer/src/scene/terrainStream.ts +++ b/studio/src/renderer/src/scene/terrainStream.ts @@ -2,6 +2,8 @@ import { Box3, Group, Vector3 } from 'three' import { TileStore, type TileSource } from '../map/TileStore' import type { CameraLink, ViewportContent } from '../studio/SceneViewport' import { CameraSight } from './cameraSight' +import type { ColumnField } from './columnField' +import { groundInView, type GroundInView } from './groundInView' import { marchOntoSurface } from './surfaceMarch' import { planCover, type Cover, type DrawnTile, type TileState } from './terrainCover' import { buildTerrainMesh, type TerrainMesh, type TerrainSurface } from './terrainMesh' @@ -55,6 +57,7 @@ export class TerrainStream { private readonly group = new Group() private readonly store: TileStore private readonly drawn = new Map>() + private readonly sightListeners = new Set<() => void>() private standIns = new Map() private layer: Layer | null = null private style: TerrainStyle | null = null @@ -69,7 +72,7 @@ export class TerrainStream { this.content = { object: this.group, bounds: options.focus, - surfaceAlong: (ray, reach) => marchOntoSurface(ray, reach, (this.style?.topY ?? 0) + ABOVE_TOP_BLOCKS, (x, z) => this.surfaceTopOver(x, z)), + surfaceAlong: (ray, reach) => marchOntoSurface(ray, reach, (this.style?.topY ?? 0) + ABOVE_TOP_BLOCKS, (x, z) => this.finestTopOver(x, z, (field) => field.surfaceTopOver(x, z))), follow: (camera) => this.follow(camera) } } @@ -85,6 +88,23 @@ export class TerrainStream { this.replan() } + /** Tells the listener whenever what the camera sees may have changed: it moved, or ground arrived; returns how to stop. */ + onSightChanged(listener: () => void): () => void { + this.sightListeners.add(listener) + return () => this.sightListeners.delete(listener) + } + + /** The ground the camera looks at now, or null while none is drawn there. */ + groundInView(): GroundInView | null { + if (this.camera === null || this.style === null) { + return null + } + return groundInView(this.camera.view(), this.style.topY + ABOVE_TOP_BLOCKS, { + surfaceTopOver: (x, z) => this.finestTopOver(x, z, (field) => field.surfaceTopOver(x, z)), + groundTopOver: (x, z) => this.finestTopOver(x, z, (field) => field.groundTopOver(x, z)) + }) + } + /** Draws the tiles another way, without sampling them again. */ restyle(style: TerrainStyle): void { this.style = style @@ -94,6 +114,7 @@ export class TerrainStream { dispose(): void { this.disposed = true + this.sightListeners.clear() if (this.continuation !== null) { clearTimeout(this.continuation) } @@ -123,6 +144,7 @@ export class TerrainStream { this.store.want(cover.wanted.map(addressOf), layer) this.draw(cover, layer, this.style) this.reportPending() + this.sightListeners.forEach((listener) => listener()) } private stateOf(tile: TerrainTile, layer: Layer): TileState { @@ -213,9 +235,11 @@ export class TerrainStream { } } - private surfaceTopOver(worldX: number, worldZ: number): number | null { + // The finest drawn tile that knows the block answers; coarser ones have holes where finer ones are drawn. + private finestTopOver(worldX: number, worldZ: number, topOf: (field: ColumnField) => number | null): number | null { for (let level = 0; level <= this.options.coarsestLevel; level++) { - const top = this.drawn.get(tileKey(tileContaining(worldX, worldZ, level)))?.mesh.field.surfaceTopOver(worldX, worldZ) ?? null + const field = this.drawn.get(tileKey(tileContaining(worldX, worldZ, level)))?.mesh.field + const top = field === undefined ? null : topOf(field) if (top !== null) { return top } diff --git a/studio/src/renderer/src/studio/Legend.tsx b/studio/src/renderer/src/studio/Legend.tsx index 83125383f..0545dd388 100644 --- a/studio/src/renderer/src/studio/Legend.tsx +++ b/studio/src/renderer/src/studio/Legend.tsx @@ -4,47 +4,66 @@ import type { Share } from '../map/census' import type { Highlight } from '../map/tileStyle' import { hexColor } from './colors' +const ROW = 'flex h-[26px] w-full items-center gap-2 rounded-md px-2.5 text-left' + +/** What highlighting does in a view that can highlight. */ +export interface LegendSelection { + highlight: Highlight | null + onSelect(subject: Highlight): void +} + interface LegendProps { title: string shares: Share[] - highlight: Highlight | null - onSelect(subject: Highlight): void + /** Absent in a view with nothing to highlight, such as the 3D world, where the legend only lists. */ + selection?: LegendSelection + /** What to say while there is nothing to list. */ + emptyText?: string className?: string } /** 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, className }: LegendProps): React.JSX.Element { +export function Legend({ title, shares, selection, emptyText = 'Drawing the map…', className }: LegendProps): React.JSX.Element { const sharedNames = namesUsedMoreThanOnce(shares) return (

{title}

    - {shares.length === 0 &&
  • Drawing the map…
  • } + {shares.length === 0 &&
  • {emptyText}
  • } {shares.map((share) => { - const selected = highlight !== null && highlight.kind === share.subject.kind && highlight.key === share.subject.key + const row = ( + <> + + + {share.subject.name} + {sharedNames.has(share.subject.name) && ( + {fileName(share.subject.key)} + )} + + {percent(share.fraction)} + + ) + const selected = selection?.highlight != null && selection.highlight.kind === share.subject.kind && selection.highlight.key === share.subject.key return (
  • - + {selection === undefined ? ( +
    {row}
    + ) : ( + + )}
  • ) })}
-

Click to highlight · Esc clears

+ {selection !== undefined &&

Click to highlight · Esc clears

}
) } diff --git a/studio/src/renderer/src/studio/MapStudio.tsx b/studio/src/renderer/src/studio/MapStudio.tsx index bab242e9e..ee624f2d0 100644 --- a/studio/src/renderer/src/studio/MapStudio.tsx +++ b/studio/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, ModuleViewInfo, PickDisplay, PickInspection, ServerUsage, ViewInfo, WorldInfo } from '../bridge/types' +import type { MapHover, MapLabel, Marker, ModuleViewInfo, PickDisplay, ServerUsage, 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' @@ -19,13 +19,12 @@ import { WorldStudio3D } from './WorldStudio3D' import { actionForKey, isTypingInto, viewForKey, type ShortcutAction } from './shortcuts' import { StatusBar } from './StatusBar' import { StudioToolbar } from './StudioToolbar' +import { usePickInspection } from './usePickInspection' import { ViewList } from './ViewList' const KEYBOARD_ZOOM_FACTOR = 2 ** 0.25 const ENTITY_POLL_MILLIS = 2000 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']) @@ -273,18 +272,15 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps {inspectsPicks && ( )} setHighlight((current) => (sameSubject(current, subject) ? null : subject))} + selection={{ highlight, onSelect: (subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject)) }} /> @@ -381,38 +377,6 @@ function usePreviewableRegions(client: BridgeClient, packRevision: number): MapL 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(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, usage and hotloads from the server; the first world event only says the world runs, which is known. */ function useServerEvents( client: BridgeClient, diff --git a/studio/src/renderer/src/studio/PickInspector.tsx b/studio/src/renderer/src/studio/PickInspector.tsx index 36610ae72..b60c6d69c 100644 --- a/studio/src/renderer/src/studio/PickInspector.tsx +++ b/studio/src/renderer/src/studio/PickInspector.tsx @@ -9,45 +9,53 @@ 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' +/** How the map draws the picks, for a view that recolours its tiles. */ +export interface PickDisplayChoice { + /** What the map shows when it draws the picks: "Regions" or "Biomes". */ + picksLabel: string + value: PickDisplay + onChange(display: PickDisplay): void +} + 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 + /** Absent in a view that draws no map tiles, such as the 3D world. */ + display?: PickDisplayChoice } /** * 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 { +export function PickInspector({ title, inspection, display }: PickInspectorProps): React.JSX.Element { return (

{title}

{inspection?.detail ?? 'Measuring what is in view…'}

- value !== '' && onDisplay(value as PickDisplay)} - > - - {picksLabel} - - - Noise - - - Both - - + {display !== undefined && ( + value !== '' && display.onChange(value as PickDisplay)} + > + + {display.picksLabel} + + + Noise + + + Both + + + )}
{inspection !== null && }
diff --git a/studio/src/renderer/src/studio/WorldStudio3D.tsx b/studio/src/renderer/src/studio/WorldStudio3D.tsx index a8c499f5e..e3b29679a 100644 --- a/studio/src/renderer/src/studio/WorldStudio3D.tsx +++ b/studio/src/renderer/src/studio/WorldStudio3D.tsx @@ -1,13 +1,18 @@ import { useEffect, useMemo, useState } from 'react' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' -import type { BridgeClient, WorldRect } from '../bridge/BridgeClient' +import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' import type { MapTile, WorldInfo } from '../bridge/types' +import { heightBandShares } from '../map/census' import { mapTileSource, type TileLayer } from '../map/mapTileSource' +import type { GroundInView } from '../scene/groundInView' import { MapTerrain, type MapTerrainColoring } from '../scene/mapTerrain' import { focusAround, type TerrainStyle } from '../scene/terrainStream' import { TILE_COLUMNS } from '../scene/terrainTiles' +import { Legend } from './Legend' +import { PickInspector } from './PickInspector' import { SceneViewport } from './SceneViewport' -import { useTerrainStream } from './useTerrainStream' +import { usePickInspection } from './usePickInspection' +import { useGroundInView, useTerrainStream } from './useTerrainStream' const NUMBER = new Intl.NumberFormat('en-US') // The map's coarsest tiles are 4096 blocks a pixel, which is level 12. @@ -26,7 +31,10 @@ interface WorldStudio3DProps { tell(message: string): void } -/** The terrain around where the map looked, in 3D and without an edge, coloured by biome, region or height (v3e's 3D world view). */ +/** + * The terrain around where the map looked, in 3D and without an edge, coloured by biome, region or height, beside how + * the noise picks the biomes or regions the camera sees, or how much of that ground lies at each height (v3e's 3D world view). + */ export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary, tell }: WorldStudio3DProps): React.JSX.Element { const [coloring, setColoring] = useState('biomes') const centre = useMemo(() => centreOf(mapArea), [mapArea]) @@ -44,7 +52,13 @@ export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary, }), [coloring, world.fluidHeight, world.minY, world.height] ) - const { content, pending } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell) + const { content, pending, stream } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell) + const ground = useGroundInView(stream) + const heightShares = useMemo(() => heightBandShares(ground?.heights ?? [], world.fluidHeight), [ground, world.fluidHeight]) + const inspectsPicks = coloring !== 'height' + const pickLayer = useMemo(() => ({ view: coloring, preview: null }), [coloring]) + const area = useAreaOf(ground) + const inspection = usePickInspection(client, pickLayer, area, inspectsPicks, packRevision) useEffect(() => { onSummary(`Around ${NUMBER.format(centre.x)}, ${NUMBER.format(centre.z)}`) @@ -52,35 +66,53 @@ export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary, }, [centre, onSummary]) return ( -
- - value !== '' && setColoring(value as MapTerrainColoring)} - > - - Biomes - - - Regions - - - Height - - - {pending > 0 && ( -
- Sampling the terrain -
- )} -
+ <> +
+ + value !== '' && setColoring(value as MapTerrainColoring)} + > + + Biomes + + + Regions + + + Height + + + {pending > 0 && ( +
+ Sampling the terrain +
+ )} +
+ + ) } +// The same box is the same area, so the measurement is not asked for again while only the heights in it change. +function useAreaOf(ground: GroundInView | null): WorldRect | null { + const minX = ground?.area.minX + const minZ = ground?.area.minZ + const maxX = ground?.area.maxX + const maxZ = ground?.area.maxZ + return useMemo(() => (minX === undefined || minZ === undefined || maxX === undefined || maxZ === undefined ? null : { minX, minZ, maxX, maxZ }), [minX, minZ, maxX, maxZ]) +} + function centreOf(area: WorldRect | null): { x: number; z: number } { if (area === null) { return { x: 0, z: 0 } diff --git a/studio/src/renderer/src/studio/usePickInspection.ts b/studio/src/renderer/src/studio/usePickInspection.ts new file mode 100644 index 000000000..b9a4b5744 --- /dev/null +++ b/studio/src/renderer/src/studio/usePickInspection.ts @@ -0,0 +1,38 @@ +import { useEffect, useState } from 'react' +import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' +import type { PickInspection } from '../bridge/types' + +// Measuring the picks in view samples thousands of spots, so it waits for the view to rest. +const INSPECTION_REST_MILLIS = 350 + +/** + * Measures how the noise picks what the view shows, once the view 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. + */ +export function usePickInspection( + client: BridgeClient, + layer: MapLayerQuery, + area: WorldRect | null, + enabled: boolean, + packRevision: number +): PickInspection | null { + const [inspection, setInspection] = useState(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 +} diff --git a/studio/src/renderer/src/studio/useTerrainStream.ts b/studio/src/renderer/src/studio/useTerrainStream.ts index 7a752dbc3..c49389f1c 100644 --- a/studio/src/renderer/src/studio/useTerrainStream.ts +++ b/studio/src/renderer/src/studio/useTerrainStream.ts @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from 'react' import type { Box3 } from 'three' import type { TileSource } from '../map/TileStore' +import type { GroundInView } from '../scene/groundInView' import { TerrainStream, type TerrainStyle } from '../scene/terrainStream' import type { ViewportContent } from './SceneViewport' @@ -17,7 +18,7 @@ export function useTerrainStream( layer: Layer | null, style: TerrainStyle | null, tell: (message: string) => void -): { content: ViewportContent | null; pending: number } { +): { content: ViewportContent | null; pending: number; stream: TerrainStream | null } { const [stream, setStream] = useState | null>(null) const [pending, setPending] = useState(0) const latestTell = useRef(tell) @@ -42,5 +43,28 @@ export function useTerrainStream( } }, [stream, style]) - return { content: stream?.content ?? null, pending } + return { content: stream?.content ?? null, pending, stream } +} + +// The camera drifts and tiles arrive in bursts; the ground it sees is read once they have rested this long. +const GROUND_REST_MILLIS = 250 + +/** The ground the camera of a stream looks at, read once the view has rested; the last reading stays until the next one. */ +export function useGroundInView(stream: TerrainStream | null): GroundInView | null { + const [ground, setGround] = useState(null) + useEffect(() => { + if (stream === null) { + return + } + let timer: number | undefined + const stopWatching = stream.onSightChanged(() => { + window.clearTimeout(timer) + timer = window.setTimeout(() => setGround(stream.groundInView()), GROUND_REST_MILLIS) + }) + return () => { + stopWatching() + window.clearTimeout(timer) + } + }, [stream]) + return ground }