Steady the studio 3D terrain's detail and move it like the map

The detail was chosen with one threshold for the whole view, which flipped
as the camera moved and swapped large areas between coarse and fine at once,
and most of the tile budget went to the backdrop. The widest-looking tile is
now split first, so a small move changes a tile or two.

Ground moves on a drag and turns on a right drag, without inertia, and the
camera stays above it. The sampling note waits until sampling lasts.
This commit is contained in:
piexel committed 2026-11-11 00:44:14 +01:00
1 parent 468802ac14
commit 9f3da18f2b
6 files changed
+82 -42

No files matched your search

+22 -22
View File
@@ -31,6 +31,8 @@ const MOST_COLUMN_PIXELS = 1
// A little above one, as tiles in sight stick out past the view's edges; beyond it, columns only add faces no one can tell apart. // A little above one, as tiles in sight stick out past the view's edges; beyond it, columns only add faces no one can tell apart.
const MOST_COLUMNS_PER_PIXEL = 1.25 const MOST_COLUMNS_PER_PIXEL = 1.25
const MOST_TILES_IN_SIGHT = 64 const MOST_TILES_IN_SIGHT = 64
// The backdrop reaches to the horizon, where a few coarse tiles do; the rest of the tiles go to ground that is near.
const MOST_BACKDROP_TILES = 16
const DETAIL_MARGIN = 0.15 const DETAIL_MARGIN = 0.15
const BACKDROP_MARGIN = 0.5 const BACKDROP_MARGIN = 0.5
const PREVIEW_LEVELS_ABOVE_DETAIL = 1 const PREVIEW_LEVELS_ABOVE_DETAIL = 1
@@ -51,8 +53,8 @@ type StateOf = (tile: TerrainTile) => TileState
export function planCover(sight: CameraSight, stateOf: StateOf, coarsestLevel: number): Cover { export function planCover(sight: CameraSight, stateOf: StateOf, coarsestLevel: number): Cover {
const backdropLevel = backdropLevelFor(sight, coarsestLevel) const backdropLevel = backdropLevelFor(sight, coarsestLevel)
const finestLevel = Math.max(0, backdropLevel - MOST_LEVELS_FINER) const finestLevel = Math.max(0, backdropLevel - MOST_LEVELS_FINER)
const backdrop = sight.tilesAt(backdropLevel, BACKDROP_MARGIN).sort(nearestFirst(sight)).slice(0, MOST_TILES_IN_SIGHT) const backdrop = sight.tilesAt(backdropLevel, BACKDROP_MARGIN).sort(nearestFirst(sight)).slice(0, MOST_BACKDROP_TILES)
const detail = detailTiles(sight, backdrop, backdropLevel, finestLevel) const detail = detailTiles(sight, backdrop, finestLevel)
const ready = candidatesOf(backdrop, detail, backdropLevel, finestLevel, stateOf).filter((tile) => stateOf(tile) !== 'none') const ready = candidatesOf(backdrop, detail, backdropLevel, finestLevel, stateOf).filter((tile) => stateOf(tile) !== 'none')
return { return {
draws: ready.map((tile) => ({ tile, holes: ready.filter((finer) => isInside(finer, tile)).map((finer) => columnsUnder(tile, finer)) })), draws: ready.map((tile) => ({ tile, holes: ready.filter((finer) => isInside(finer, tile)).map((finer) => columnsUnder(tile, finer)) })),
@@ -64,34 +66,32 @@ export function planCover(sight: CameraSight, stateOf: StateOf, coarsestLevel: n
function backdropLevelFor(sight: CameraSight, coarsestLevel: number): number { function backdropLevelFor(sight: CameraSight, coarsestLevel: number): number {
const wanted = Math.ceil(Math.log2(Math.max(1, (sight.orbitDistance * BACKDROP_TILE_BLOCKS_PER_ORBIT_BLOCK) / TILE_COLUMNS))) const wanted = Math.ceil(Math.log2(Math.max(1, (sight.orbitDistance * BACKDROP_TILE_BLOCKS_PER_ORBIT_BLOCK) / TILE_COLUMNS)))
let level = Math.min(coarsestLevel, Math.max(0, wanted)) let level = Math.min(coarsestLevel, Math.max(0, wanted))
while (level < coarsestLevel && sight.tilesAt(level, BACKDROP_MARGIN).length > MOST_TILES_IN_SIGHT) { while (level < coarsestLevel && sight.tilesAt(level, BACKDROP_MARGIN).length > MOST_BACKDROP_TILES) {
level++ level++
} }
return level return level
} }
// Each backdrop tile is split into finer tiles while their columns would look wider than the threshold, and the // The tile whose columns look widest is split into finer ones, again and again, until no column looks wider than a
// threshold is raised until there are no more columns than the view has pixels to show. // pixel or the view has as many tiles as it may. A camera that moves a little so changes a tile or two, not all of them.
function detailTiles(sight: CameraSight, backdrop: TerrainTile[], backdropLevel: number, finestLevel: number): TerrainTile[] { function detailTiles(sight: CameraSight, backdrop: TerrainTile[], finestLevel: number): TerrainTile[] {
const mostColumns = Math.min(sight.pixelsWithin(DETAIL_MARGIN) * MOST_COLUMNS_PER_PIXEL, MOST_TILES_IN_SIGHT * COLUMNS_PER_TILE) const tilesThePixelsCanShow = Math.floor((sight.pixelsWithin(DETAIL_MARGIN) * MOST_COLUMNS_PER_PIXEL) / COLUMNS_PER_TILE)
let threshold = MOST_COLUMN_PIXELS const mostTiles = Math.min(MOST_TILES_IN_SIGHT, Math.max(backdrop.length, tilesThePixelsCanShow))
const detail = backdrop.map((tile) => ({ tile, columnPixels: sight.columnPixels(tile) }))
for (;;) { for (;;) {
const detail = backdrop.flatMap((tile) => splitWhileCoarse(sight, tile, threshold, finestLevel)) const widest = detail
const nothingToCoarsen = detail.every((tile) => tile.level === backdropLevel) .filter((entry) => entry.tile.level > finestLevel && entry.columnPixels > MOST_COLUMN_PIXELS)
if (nothingToCoarsen || (detail.length * COLUMNS_PER_TILE <= mostColumns && detail.length <= MOST_TILES_IN_SIGHT)) { .reduce<(typeof detail)[number] | null>((most, entry) => (most === null || entry.columnPixels > most.columnPixels ? entry : most), null)
return detail if (widest === null) {
break
} }
threshold *= 2 const finer = childrenOf(widest.tile).filter((child) => sight.sees(child, DETAIL_MARGIN))
if (detail.length - 1 + finer.length > mostTiles) {
break
}
detail.splice(detail.indexOf(widest), 1, ...finer.map((tile) => ({ tile, columnPixels: sight.columnPixels(tile) })))
} }
} return detail.map((entry) => entry.tile)
function splitWhileCoarse(sight: CameraSight, tile: TerrainTile, threshold: number, finestLevel: number): TerrainTile[] {
if (tile.level <= finestLevel || sight.columnPixels(tile) <= threshold) {
return [tile]
}
return childrenOf(tile)
.filter((child) => sight.sees(child, DETAIL_MARGIN))
.flatMap((child) => splitWhileCoarse(sight, child, threshold, finestLevel))
} }
// Everything that may be drawn for the view: the backdrop, the detail and the levels between that happen to be there, // Everything that may be drawn for the view: the backdrop, the detail and the levels between that happen to be there,
@@ -72,6 +72,7 @@ export class TerrainStream<Tile, Layer> {
this.content = { this.content = {
object: this.group, object: this.group,
bounds: options.focus, bounds: options.focus,
isGround: true,
surfaceAlong: (ray, reach) => marchOntoSurface(ray, reach, (this.style?.topY ?? 0) + ABOVE_TOP_BLOCKS, (x, z) => this.finestTopOver(x, z, (field) => field.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) follow: (camera) => this.follow(camera)
} }
@@ -168,7 +169,8 @@ export class TerrainStream<Tile, Layer> {
const deadline = performance.now() + MESH_BUILD_BUDGET_MILLISECONDS const deadline = performance.now() + MESH_BUILD_BUDGET_MILLISECONDS
const stillDrawn = new Set<string>() const stillDrawn = new Set<string>()
let behind = false let behind = false
for (const draw of cover.draws) { // Finer tiles are built before the coarser ones get their holes, so running out of time leaves ground drawn twice, never a gap.
for (const draw of [...cover.draws].sort((first, second) => first.tile.level - second.tile.level)) {
const key = tileKey(draw.tile) const key = tileKey(draw.tile)
stillDrawn.add(key) stillDrawn.add(key)
const data = this.dataOf(draw.tile, layer) const data = this.dataOf(draw.tile, layer)
@@ -181,15 +183,16 @@ export class TerrainStream<Tile, Layer> {
} }
this.show(key, draw, data, style) this.show(key, draw, data, style)
} }
this.camera?.redraw()
if (behind) {
this.continueLater()
return
}
for (const [key, drawn] of [...this.drawn]) { for (const [key, drawn] of [...this.drawn]) {
if (!stillDrawn.has(key)) { if (!stillDrawn.has(key)) {
this.hide(key, drawn) this.hide(key, drawn)
} }
} }
this.camera?.redraw()
if (behind) {
this.continueLater()
}
} }
private isCurrent(drawn: DrawnMesh<Tile> | undefined, data: Tile, draw: DrawnTile): boolean { private isCurrent(drawn: DrawnMesh<Tile> | undefined, data: Tile, draw: DrawnTile): boolean {
@@ -16,7 +16,7 @@ import { hexColor } from './colors'
import { SceneViewport } from './SceneViewport' import { SceneViewport } from './SceneViewport'
import { TiledCanvas } from './TiledCanvas' import { TiledCanvas } from './TiledCanvas'
import { Panel, SidebarPanel } from './Sidebar' import { Panel, SidebarPanel } from './Sidebar'
import { useTerrainStream } from './useTerrainStream' import { useLongPending, useTerrainStream } from './useTerrainStream'
type NoiseDisplay = 'flat' | 'terrain' type NoiseDisplay = 'flat' | 'terrain'
@@ -307,10 +307,11 @@ function NoiseTerrainView({
[source, scale, reliefBlocks] [source, scale, reliefBlocks]
) )
const { content, pending } = useTerrainStream(tileSource, COARSEST_NOISE_LEVEL, focus, layer, style, tell) const { content, pending } = useTerrainStream(tileSource, COARSEST_NOISE_LEVEL, focus, layer, style, tell)
const sampling = useLongPending(pending)
return ( return (
<div className="absolute inset-0"> <div className="absolute inset-0">
<SceneViewport content={content} framing={content} /> <SceneViewport content={content} framing={content} />
{pending > 0 && <div className={cn(PILL, 'top-3 left-1/2 -translate-x-1/2')}>Sampling {source.name}</div>} {sampling && <div className={cn(PILL, 'top-3 left-1/2 -translate-x-1/2')}>Sampling {source.name}</div>}
</div> </div>
) )
} }
@@ -17,7 +17,12 @@ const FAR_CLIP_PER_ORBIT_DISTANCE = 20
// A press that moves further than this between pressing and releasing is a drag, not a click. // A press that moves further than this between pressing and releasing is a drag, not a click.
const CLICK_SLOP_PIXELS = 4 const CLICK_SLOP_PIXELS = 4
function turnsView(event: PointerEvent): boolean { // Ground is looked at from above: the camera stops a little over the horizon instead of going under it.
const LOWEST_OVER_GROUND_RADIANS = Math.PI / 2 - 0.05
const TURNS_ON_DRAG = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.PAN, RIGHT: MOUSE.PAN }
const MOVES_ON_DRAG = { LEFT: MOUSE.PAN, MIDDLE: MOUSE.ROTATE, RIGHT: MOUSE.ROTATE }
function picks(event: PointerEvent): boolean {
return event.button === 0 && !event.shiftKey && !event.ctrlKey && !event.metaKey return event.button === 0 && !event.shiftKey && !event.ctrlKey && !event.metaKey
} }
@@ -35,6 +40,8 @@ export interface CameraLink {
export interface ViewportContent { export interface ViewportContent {
object: Object3D object: Object3D
bounds: Box3 bounds: Box3
/** Ground to travel over: a drag moves it as the map does and a right drag turns the view; anything else turns on a drag. */
isGround?: boolean
/** Where a ray first meets what is drawn within {@code reach}, or null; without it the viewport casts the ray at the object's meshes. */ /** Where a ray first meets what is drawn within {@code reach}, or null; without it the viewport casts the ray at the object's meshes. */
surfaceAlong?(ray: Ray, reach: number): Vector3 | null surfaceAlong?(ray: Ray, reach: number): Vector3 | null
/** Called when the content is shown, so it can follow the camera; returns how to stop following when it goes. */ /** Called when the content is shown, so it can follow the camera; returns how to stop following when it goes. */
@@ -52,7 +59,11 @@ interface SceneViewportProps {
onPick?(picked: PickedSurface): void onPick?(picked: PickedSurface): void
} }
/** Something in 3D: drag to turn around what is in the middle, right drag to move, scroll to come closer to the cursor. Drawn only when it changes. */ /**
* Something in 3D. An object turns on a drag and moves on a right drag; ground moves on a drag, as the map does, and
* turns on a right drag. Either turns around what is in the middle, and scrolling comes closer to the cursor. The
* camera stops with the mouse, and the view is drawn only when it changes.
*/
export function SceneViewport({ content, framing, onPick }: SceneViewportProps): React.JSX.Element { export function SceneViewport({ content, framing, onPick }: SceneViewportProps): React.JSX.Element {
const host = useRef<HTMLDivElement>(null) const host = useRef<HTMLDivElement>(null)
const stage = useRef<Stage | null>(null) const stage = useRef<Stage | null>(null)
@@ -94,12 +105,11 @@ class Stage {
this.renderer.setClearAlpha(0) this.renderer.setClearAlpha(0)
host.appendChild(this.renderer.domElement) host.appendChild(this.renderer.domElement)
this.controls = new OrbitControls(this.camera, this.renderer.domElement) this.controls = new OrbitControls(this.camera, this.renderer.domElement)
this.controls.enableDamping = true
this.controls.zoomToCursor = true this.controls.zoomToCursor = true
this.controls.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.PAN, RIGHT: MOUSE.PAN } this.navigateAs(false)
this.renderer.domElement.addEventListener('pointerdown', (event) => { this.renderer.domElement.addEventListener('pointerdown', (event) => {
this.pressedAt = turnsView(event) ? { x: event.clientX, y: event.clientY } : null this.pressedAt = picks(event) ? { x: event.clientX, y: event.clientY } : null
this.pivotOnSurfaceInMiddle(event) this.pivotOnSurfaceInMiddle()
}) })
this.renderer.domElement.addEventListener('pointerup', (event) => this.pickIfClicked(event)) this.renderer.domElement.addEventListener('pointerup', (event) => this.pickIfClicked(event))
this.controls.addEventListener('change', () => { this.controls.addEventListener('change', () => {
@@ -117,6 +127,7 @@ class Stage {
this.shown = content this.shown = content
if (content !== null) { if (content !== null) {
this.scene.add(content.object) this.scene.add(content.object)
this.navigateAs(content.isGround === true)
if (!this.framed) { if (!this.framed) {
this.frameShown() this.frameShown()
} }
@@ -125,6 +136,13 @@ class Stage {
this.requestFrame() this.requestFrame()
} }
private navigateAs(ground: boolean): void {
this.controls.mouseButtons = ground ? MOVES_ON_DRAG : TURNS_ON_DRAG
// Ground moves along itself, so dragging up brings what is further away closer instead of lifting the camera.
this.controls.screenSpacePanning = !ground
this.controls.maxPolarAngle = ground ? LOWEST_OVER_GROUND_RADIANS : Math.PI
}
private removeShown(): void { private removeShown(): void {
this.stopFollowing?.() this.stopFollowing?.()
this.stopFollowing = null this.stopFollowing = null
@@ -196,9 +214,10 @@ class Stage {
this.pickListener(point === null ? null : { point, direction: caster.ray.direction.clone() }) this.pickListener(point === null ? null : { point, direction: caster.ray.direction.clone() })
} }
// The pivot slides along the line of sight, so the picture stays put while turning now goes around what is there. // The pivot slides along the line of sight, so the picture stays put while turning now goes around what is there,
private pivotOnSurfaceInMiddle(event: PointerEvent): void { // and moving keeps pace with it.
if (!turnsView(event) || this.shown === null) { private pivotOnSurfaceInMiddle(): void {
if (this.shown === null) {
return return
} }
const ray = new Ray(this.camera.getWorldPosition(new Vector3()), this.camera.getWorldDirection(new Vector3())) const ray = new Ray(this.camera.getWorldPosition(new Vector3()), this.camera.getWorldDirection(new Vector3()))
@@ -244,8 +263,6 @@ class Stage {
this.frameRequested = true this.frameRequested = true
requestAnimationFrame(() => { requestAnimationFrame(() => {
this.frameRequested = false this.frameRequested = false
// Damping keeps turning the camera for a moment after a drag, and asks for frames until it stops.
this.controls.update()
this.renderer.render(this.scene, this.camera) this.renderer.render(this.scene, this.camera)
}) })
} }
@@ -13,7 +13,7 @@ import { PickInspector } from './PickInspector'
import { SceneViewport } from './SceneViewport' import { SceneViewport } from './SceneViewport'
import { usePickInspection } from './usePickInspection' import { usePickInspection } from './usePickInspection'
import { Panel } from './Sidebar' import { Panel } from './Sidebar'
import { useGroundInView, useTerrainStream } from './useTerrainStream' import { useGroundInView, useLongPending, useTerrainStream } from './useTerrainStream'
const NUMBER = new Intl.NumberFormat('en-US') const NUMBER = new Intl.NumberFormat('en-US')
// The map's coarsest tiles are 4096 blocks a pixel, which is level 12. // The map's coarsest tiles are 4096 blocks a pixel, which is level 12.
@@ -54,6 +54,7 @@ export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary,
[coloring, world.fluidHeight, world.minY, world.height] [coloring, world.fluidHeight, world.minY, world.height]
) )
const { content, pending, stream } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell) const { content, pending, stream } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell)
const sampling = useLongPending(pending)
const ground = useGroundInView(stream) const ground = useGroundInView(stream)
const heightShares = useMemo(() => heightBandShares(ground?.heights ?? [], world.fluidHeight), [ground, world.fluidHeight]) const heightShares = useMemo(() => heightBandShares(ground?.heights ?? [], world.fluidHeight), [ground, world.fluidHeight])
const inspectsPicks = coloring !== 'height' const inspectsPicks = coloring !== 'height'
@@ -88,7 +89,7 @@ export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary,
Height Height
</ToggleGroupItem> </ToggleGroupItem>
</ToggleGroup> </ToggleGroup>
{pending > 0 && ( {sampling && (
<div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text"> <div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text">
Sampling the terrain Sampling the terrain
</div> </div>
@@ -46,6 +46,24 @@ export function useTerrainStream<Tile, Layer>(
return { content: stream?.content ?? null, pending, stream } return { content: stream?.content ?? null, pending, stream }
} }
// Moving the camera a little samples a tile or two, which is over before it is worth a word.
const WORTH_TELLING_MILLIS = 700
/** Whether tiles have been on their way for long enough to say so. */
export function useLongPending(pending: number): boolean {
const waiting = pending > 0
const [long, setLong] = useState(false)
useEffect(() => {
if (!waiting) {
setLong(false)
return
}
const timer = window.setTimeout(() => setLong(true), WORTH_TELLING_MILLIS)
return () => window.clearTimeout(timer)
}, [waiting])
return long
}
// The camera drifts and tiles arrive in bursts; the ground it sees is read once they have rested this long. // 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 const GROUND_REST_MILLIS = 250