Stream the 3D world without dropping frames

- Plan the terrain at most once a frame
- Look up tiles inside tiles by their ancestors instead of comparing every pair
- Keep each layer's tile key instead of building it on every lookup
- Hand three each tile's bounds from the packing
- Share materials between tiles
- Draw water in one pass so its shader is not set up twice a tile every frame
This commit is contained in:
piexel committed 2026-11-25 22:49:01 +01:00
1 parent 3490db362d
commit 2607682020
7 files changed
+146 -60

No files matched your search

+16 -1
View File
@@ -40,6 +40,8 @@ export class TileStore<Tile, Layer, Style> {
private storedBytes = 0
private useClock = 0
private changes = 0
// Planning asks after tiles by the hundred thousand, and building a layer's key each time took most of a frame.
private readonly layerKeys = new WeakMap<object, string>()
constructor(
private readonly source: TileSource<Tile, Layer, Style>,
@@ -48,7 +50,20 @@ export class TileStore<Tile, Layer, Style> {
) {}
key(address: TileAddress, layer: Layer): string {
return `${this.source.layerKey(layer)}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}`
return `${this.keyOfLayer(layer)}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}`
}
// Layers are replaced, never changed in place, so a layer's key holds for as long as the layer does.
private keyOfLayer(layer: Layer): string {
if (typeof layer !== 'object' || layer === null) {
return this.source.layerKey(layer)
}
let key = this.layerKeys.get(layer)
if (key === undefined) {
key = this.source.layerKey(layer)
this.layerKeys.set(layer, key)
}
return key
}
/** The tile if it has arrived, marked as just used. */
@@ -1,4 +1,4 @@
import { BufferAttribute, BufferGeometry, type Vector3Tuple } from 'three'
import { Box3, BufferAttribute, BufferGeometry, Sphere, Vector3, type Vector3Tuple } from 'three'
// Positions are kept in sixteenths of a block, the finest step a block model uses, from the geometry's lowest corner.
const STEPS_PER_BLOCK = 16
@@ -17,6 +17,8 @@ export interface CompactArrays {
uv: Uint16Array | null
index: Uint32Array
placement: CompactPlacement
/** The most steps any corner lies from the lowest one, along each axis. */
extent: Vector3Tuple
}
/**
@@ -49,10 +51,16 @@ export function compacted(geometry: BufferGeometry, blocksPerColumn: number): Co
color: color === undefined ? null : Uint8Array.from(color, (channel) => Math.round(Math.min(1, Math.max(0, channel)) * 255)),
uv: uv === undefined ? null : Uint16Array.from(uv, (place) => Math.round(Math.min(1, Math.max(0, place)) * 65_535)),
index: geometry.getIndex()!.array as Uint32Array,
placement: { origin: min, scale }
placement: { origin: min, scale },
extent: [0, 1, 2].map((axis) => stepsAcross(min[axis], max[axis], scale[axis])) as Vector3Tuple
}
}
function stepsAcross(low: number, high: number, step: number): number {
const steps = Math.round((high - low) / step)
return Number.isFinite(steps) ? steps : 0
}
/** The geometry the compact arrays hold, in the steps they were packed in; draw it placed by their placement. */
export function geometryOfCompact(arrays: CompactArrays): BufferGeometry {
const geometry = new BufferGeometry()
@@ -64,5 +72,8 @@ export function geometryOfCompact(arrays: CompactArrays): BufferGeometry {
geometry.setAttribute('uv', new BufferAttribute(arrays.uv, 2, true))
}
geometry.setIndex(new BufferAttribute(arrays.index, 1))
// Known from the packing, so the first frame that draws the tile does not go over every corner to find them.
geometry.boundingBox = new Box3(new Vector3(0, 0, 0), new Vector3(...arrays.extent))
geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new Sphere())
return geometry
}
+22 -4
View File
@@ -3,10 +3,11 @@ import {
ancestorAt,
childrenOf,
columnsUnder,
isInside,
liesInsideAny,
MOST_LEVELS_FINER,
TILE_COLUMNS,
tileKey,
tilesInsideEach,
type ColumnArea,
type TerrainTile
} from './terrainTiles'
@@ -60,7 +61,8 @@ type StateOf = (tile: TerrainTile) => TileState
* @param knownInside the tiles finer than a tile, inside it, whose ground is known, however much finer; where not
* given, the ones up to a couple of levels finer that {@code stateOf} knows
*/
export function planCover(sight: CameraSight, stateOf: StateOf, coarsestLevel: number, knownInside?: (tile: TerrainTile) => TerrainTile[]): Cover {
export function planCover(sight: CameraSight, askState: StateOf, coarsestLevel: number, knownInside?: (tile: TerrainTile) => TerrainTile[]): Cover {
const stateOf = rememberedStates(askState)
const backdropLevel = backdropLevelFor(sight, coarsestLevel)
const finestLevel = Math.max(0, backdropLevel - MOST_LEVELS_FINER)
const backdrop = sight.tilesAt(backdropLevel, BACKDROP_MARGIN).sort(nearestFirst(sight)).slice(0, MOST_BACKDROP_TILES)
@@ -69,14 +71,30 @@ export function planCover(sight: CameraSight, stateOf: StateOf, coarsestLevel: n
const leftOverInside = knownInside ?? ((tile: TerrainTile) => finerLeftOver(tile, finestLevel, stateOf, MOST_LEVELS_FINER_LEFT_OVER))
const candidates = candidatesOf(backdrop, detail, backdropLevel, isTrue, (tile) => leftOverInside(tile).filter((finer) => finer.level >= finestLevel && isTrue(finer)))
const ready = candidates.filter(isTrue)
const quickFill = candidates.filter((tile) => stateOf(tile) === 'quick' && !ready.some((truer) => isInside(tile, truer)))
const readyKeys = new Set(ready.map(tileKey))
const quickFill = candidates.filter((tile) => stateOf(tile) === 'quick' && !liesInsideAny(tile, readyKeys, backdropLevel))
const drawn = [...ready, ...quickFill]
const finerInside = tilesInsideEach(drawn, backdropLevel)
return {
draws: drawn.map((tile) => ({ tile, holes: drawn.filter((finer) => isInside(finer, tile)).map((finer) => columnsUnder(tile, finer)) })),
draws: drawn.map((tile) => ({ tile, holes: (finerInside.get(tileKey(tile)) ?? []).map((finer) => columnsUnder(tile, finer)) })),
wanted: wantedInOrder(sight, backdrop, detail, backdropLevel, stateOf)
}
}
// A plan asks after the same tile many times over, and asking the store builds a key each time.
function rememberedStates(stateOf: StateOf): StateOf {
const known = new Map<string, TileState>()
return (tile) => {
const key = tileKey(tile)
let state = known.get(key)
if (state === undefined) {
state = stateOf(tile)
known.set(key, state)
}
return state
}
}
// The backdrop tiles are about as wide as the camera is far from what is in the middle, which puts a few of them in sight.
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)))
+25 -6
View File
@@ -122,7 +122,7 @@ function present<T>(parts: (T | null)[]): T[] {
/** The geometry drawn in its materials; textured and cut-out parts need {@code pictures}. */
export function meshOfGeometry({ field, parts }: TerrainGeometry, pictures: TerrainPictures | null): TerrainMesh {
const group = new Group()
const materials = parts.map(({ kind }) => materialOf(kind, pictures))
const materials = parts.map(({ kind }) => sharedMaterialOf(kind, pictures))
parts.forEach(({ geometry, placement }, index) => {
const mesh = new Mesh(geometry, materials[index])
if (placement !== undefined) {
@@ -134,13 +134,30 @@ export function meshOfGeometry({ field, parts }: TerrainGeometry, pictures: Terr
return {
object: group,
field,
dispose: () => {
parts.forEach(({ geometry }) => geometry.dispose())
materials.forEach((material) => material.dispose())
}
dispose: () => parts.forEach(({ geometry }) => geometry.dispose())
}
}
const UNPICTURED = {}
const sharedMaterials = new WeakMap<object, Map<GeometryKind, MeshBasicMaterial>>()
// Tiles of a kind are drawn alike, so they share their materials: a material of its own made every new tile set its
// shader up anew, which took a frame's worth of time while the ground streamed in.
function sharedMaterialOf(kind: GeometryKind, pictures: TerrainPictures | null): MeshBasicMaterial {
const owner = pictures ?? UNPICTURED
let byKind = sharedMaterials.get(owner)
if (byKind === undefined) {
byKind = new Map()
sharedMaterials.set(owner, byKind)
}
let material = byKind.get(kind)
if (material === undefined) {
material = materialOf(kind, pictures)
byKind.set(kind, material)
}
return material
}
// Cut-out parts are drawn where their pictures are not open, so the grass between its blades and the leaves between their
// twigs show what lies behind.
function materialOf(kind: GeometryKind, pictures: TerrainPictures | null): MeshBasicMaterial {
@@ -154,7 +171,9 @@ function materialOf(kind: GeometryKind, pictures: TerrainPictures | null): MeshB
new MeshBasicMaterial({ vertexColors: true, map: pictures?.texture ?? null, alphaMap: pictures?.cutouts ?? null, alphaTest: CUTOUT_ALPHA, side: FrontSide })
)
case 'water':
return new MeshBasicMaterial({ color: WATER_SURFACE_COLOR, transparent: true, opacity: WATER_SURFACE_OPACITY, depthWrite: false, side: DoubleSide })
// One pass for both faces: a flat sheet gains nothing from three drawing its back and then its front, and each of
// those passes set the shader up anew, on every tile of water every frame.
return new MeshBasicMaterial({ color: WATER_SURFACE_COLOR, transparent: true, opacity: WATER_SURFACE_OPACITY, depthWrite: false, side: DoubleSide, forceSinglePass: true })
}
}
@@ -70,6 +70,10 @@ function setUp(
quickLayerOf,
focus: focusAround(0, 0, 0, 128),
onPending: (pending) => pendingCounts.push(pending),
nextFrame: (callback) => {
const timer = setTimeout(callback, 0)
return () => clearTimeout(timer)
},
onError: (message) => {
throw new Error(message)
}
+36 -47
View File
@@ -8,7 +8,7 @@ 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'
import { addressOf, ancestorAt, childrenOf, isInside, tileAt, tileContaining, tileKey, type ColumnArea, type TerrainTile } from './terrainTiles'
import { addressOf, ancestorAt, childrenOf, isInside, tileAt, tileContaining, tileKey, tilesInsideEach, type ColumnArea, type TerrainTile } from './terrainTiles'
/** How the tiles of a source look as ground, and how low and high that ground can reach. */
export interface TerrainStyle<Tile> {
@@ -35,6 +35,8 @@ export interface TerrainStreamOptions<Tile, Layer> {
quickLayerOf?(layer: Layer): Layer | null
/** Told how many tiles are still on their way, whenever that changes. */
onPending(pending: number): void
/** Runs the callback before the next frame is drawn; returns how to call it off. Animation frames where not given. */
nextFrame?(callback: () => void): () => void
onError(message: string): void
}
@@ -80,6 +82,11 @@ function bytesOf(mesh: TerrainMesh): number {
})
return bytes
}
function nextAnimationFrame(callback: () => void): () => void {
const handle = requestAnimationFrame(callback)
return () => cancelAnimationFrame(handle)
}
const ABOVE_TOP_BLOCKS = 1
const FOCUS_HALF_SIDE_BLOCKS = 256
@@ -107,13 +114,12 @@ export class TerrainStream<Tile, Layer> {
private readonly building = new Map<string, BuildingMesh<Tile>>()
private storedIndex: StoredIndex | null = null
private uploadBytesLeft = UPLOAD_BYTES_PER_FRAME
private nextFrame: number | null = null
private cancelPlannedFrame: (() => void) | null = null
private layer: Layer | null = null
private style: TerrainStyle<Tile> | null = null
private styleVersion = 0
private camera: CameraLink | null = null
private reportedPending = -1
private continuation: ReturnType<typeof setTimeout> | null = null
private disposed = false
// Tiles are looked for where ground stands, not across the world's whole height: under a tall sky most of a tile's
// box is air, which lands in the view where its ground does not.
@@ -124,7 +130,7 @@ export class TerrainStream<Tile, Layer> {
constructor(private readonly options: TerrainStreamOptions<Tile, Layer>) {
this.lowestGround = options.focus.min.y
this.highestGround = options.focus.max.y
this.store = new TileStore(options.source, () => this.replan(), options.onError)
this.store = new TileStore(options.source, () => this.replanNextFrame(), options.onError)
this.content = {
object: this.group,
bounds: options.focus,
@@ -172,12 +178,7 @@ export class TerrainStream<Tile, Layer> {
dispose(): void {
this.disposed = true
this.sightListeners.clear()
if (this.continuation !== null) {
clearTimeout(this.continuation)
}
if (this.nextFrame !== null) {
cancelAnimationFrame(this.nextFrame)
}
this.cancelPlannedFrame?.()
this.drawn.forEach((drawn) => drawn.mesh.dispose())
this.drawn.clear()
this.building.forEach((building) => building.mesh?.dispose())
@@ -188,7 +189,7 @@ export class TerrainStream<Tile, Layer> {
private follow(camera: CameraLink): () => void {
this.camera = camera
const stop = camera.onMoved(() => this.replan())
const stop = camera.onMoved(() => this.replanNextFrame())
this.replan()
return () => {
stop()
@@ -196,6 +197,18 @@ export class TerrainStream<Tile, Layer> {
}
}
// Tiles arrive, meshes finish and the camera moves many times a frame; planning once a frame covers them all.
private replanNextFrame(): void {
if (this.cancelPlannedFrame !== null || this.disposed) {
return
}
this.cancelPlannedFrame = (this.options.nextFrame ?? nextAnimationFrame)(() => {
this.cancelPlannedFrame = null
this.uploadBytesLeft = UPLOAD_BYTES_PER_FRAME
this.replan()
})
}
private replan(): void {
if (this.disposed || this.layer === null || this.style === null || this.camera === null) {
return
@@ -204,7 +217,9 @@ export class TerrainStream<Tile, Layer> {
const layer = this.layer
const quick = this.options.quickLayerOf?.(layer) ?? null
const stateOf = (tile: TerrainTile): TileState => this.stateOf(tile, layer, quick)
const knownInside = (tile: TerrainTile): TerrainTile[] => [...this.coarsestStoredInside(tile, layer), ...this.drawnInside(tile)]
// Ground drawn now, such as a stand-in left from the layer before, stays until a tile as true replaces it.
const drawnInside = tilesInsideEach([...this.drawn.values()].map((drawn) => drawn.tile), this.options.coarsestLevel)
const knownInside = (tile: TerrainTile): TerrainTile[] => [...this.coarsestStoredInside(tile, layer), ...(drawnInside.get(tileKey(tile)) ?? [])]
const cover = planCover(sight, stateOf, this.options.coarsestLevel, knownInside)
this.store.wantEach(this.wantedOf(cover.wanted, layer, quick))
this.draw(cover, layer, quick, this.style)
@@ -244,11 +259,6 @@ export class TerrainStream<Tile, Layer> {
return this.standIns.get(key) ?? quickTile ?? null
}
// Ground drawn now, such as a stand-in left from the layer before, stays until a tile as true replaces it.
private drawnInside(tile: TerrainTile): TerrainTile[] {
return [...this.drawn.values()].map((drawn) => drawn.tile).filter((finer) => isInside(finer, tile))
}
// The layer's tiles that have arrived inside the tile, however much finer, but only the coarsest over each spot: they
// show the ground as well from where it is too coarse for its own tile to have arrived, with the fewest faces.
private coarsestStoredInside(tile: TerrainTile, layer: Layer): TerrainTile[] {
@@ -291,6 +301,7 @@ export class TerrainStream<Tile, Layer> {
const deadline = performance.now() + MESH_BUILD_BUDGET_MILLISECONDS
const stillDrawn = new Set<string>()
let behind = false
const drawsInside = tilesInsideEach(cover.draws.map((draw) => draw.tile), this.options.coarsestLevel)
// 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)
@@ -307,7 +318,7 @@ export class TerrainStream<Tile, Layer> {
this.show(key, draw, this.builtNow(draw, data, style), data)
continue
}
this.showOnceBuilt(key, draw, data, cover, style.buildMesh, style.floorY)
this.showOnceBuilt(key, draw, data, drawsInside.get(key) ?? [], style.buildMesh, style.floorY)
}
for (const [key, building] of [...this.building]) {
if (!stillDrawn.has(key)) {
@@ -318,10 +329,10 @@ export class TerrainStream<Tile, Layer> {
this.camera?.redraw()
if (this.groundRangeGrew) {
this.groundRangeGrew = false
this.continueLater()
this.replanNextFrame()
}
if (behind) {
this.continueLater()
this.replanNextFrame()
return
}
for (const [key, drawn] of [...this.drawn]) {
@@ -356,17 +367,17 @@ export class TerrainStream<Tile, Layer> {
// A tile is built away from the frames, and shown once built. One with holes is shown only once the finer tiles that
// fill them are, so what it drew before stays meanwhile and the ground never shows a gap.
private showOnceBuilt(key: string, draw: DrawnTile, data: Tile, cover: Cover, buildMesh: NonNullable<TerrainStyle<Tile>['buildMesh']>, base: number): void {
private showOnceBuilt(key: string, draw: DrawnTile, data: Tile, drawnInside: TerrainTile[], buildMesh: NonNullable<TerrainStyle<Tile>['buildMesh']>, base: number): void {
const signature = this.signatureOf(draw)
const building = this.building.get(key)
if (building !== undefined && building.data === data && building.signature === signature) {
const finer = cover.draws.filter((other) => isInside(other.tile, draw.tile)).map((other) => tileKey(other.tile))
if (building.mesh === null || !finer.every((finerKey) => this.drawn.has(finerKey))) {
if (building.mesh === null || !drawnInside.every((finer) => this.drawn.has(tileKey(finer)))) {
return
}
const bytes = bytesOf(building.mesh)
if (bytes > this.uploadBytesLeft && this.uploadBytesLeft < UPLOAD_BYTES_PER_FRAME) {
this.continueNextFrame()
// A frame hands the GPU only so many bytes of new meshes; the rest wait for the next, so a burst never stalls one.
this.replanNextFrame()
return
}
this.uploadBytesLeft -= bytes
@@ -384,7 +395,7 @@ export class TerrainStream<Tile, Layer> {
return
}
started.mesh = mesh
this.continueLater()
this.replanNextFrame()
},
(error: Error) => {
if (!this.disposed && this.building.get(key) === started) {
@@ -421,28 +432,6 @@ export class TerrainStream<Tile, Layer> {
this.drawn.delete(key)
}
// A frame hands the GPU only so many bytes of new meshes; the rest wait for the next, so a burst of tiles never stalls one.
private continueNextFrame(): void {
if (this.nextFrame !== null) {
return
}
this.nextFrame = requestAnimationFrame(() => {
this.nextFrame = null
this.uploadBytesLeft = UPLOAD_BYTES_PER_FRAME
this.replan()
})
}
private continueLater(): void {
if (this.continuation !== null) {
return
}
this.continuation = setTimeout(() => {
this.continuation = null
this.replan()
}, 0)
}
private reportPending(): void {
const pending = this.store.pending()
if (pending !== this.reportedPending) {
@@ -88,6 +88,36 @@ export function isInside(tile: TerrainTile, coarser: TerrainTile): boolean {
return tile.level < coarser.level && sameTile(ancestorAt(tile, coarser.level), coarser)
}
/**
* The tiles inside each coarser tile, up to {@code coarsestLevel}, keyed by that tile, in the order given. Looking them up
* here keeps planning linear in the tiles instead of comparing every pair.
*/
export function tilesInsideEach(tiles: Iterable<TerrainTile>, coarsestLevel: number): Map<string, TerrainTile[]> {
const inside = new Map<string, TerrainTile[]>()
for (const tile of tiles) {
for (let level = tile.level + 1; level <= coarsestLevel; level++) {
const key = tileKey(ancestorAt(tile, level))
const finer = inside.get(key)
if (finer === undefined) {
inside.set(key, [tile])
} else {
finer.push(tile)
}
}
}
return inside
}
/** Whether a tile of {@code keys}, no coarser than {@code coarsestLevel}, holds the tile. */
export function liesInsideAny(tile: TerrainTile, keys: Set<string>, coarsestLevel: number): boolean {
for (let level = tile.level + 1; level <= coarsestLevel; level++) {
if (keys.has(tileKey(ancestorAt(tile, level)))) {
return true
}
}
return false
}
/** The columns of {@code coarser} that the finer tile inside it covers. */
export function columnsUnder(coarser: TerrainTile, finer: TerrainTile): ColumnArea {
const levelsDown = coarser.level - finer.level