Draw studio 3D terrain as one-block columns

The studio's 3D views drew a smooth mesh; they now draw block columns sampled one block per
pixel, 512 blocks a side, with neighbouring faces of one height and colour merged, sides only
where a column stands above its neighbour, and flat Minecraft-style face shading. Pack and
server are untouched.

v3: 1e8c47918 030ee0604 4eb7da0ce
This commit is contained in:
piexel committed 2026-11-10 11:39:47 +01:00
1 parent 6f772a2808
commit 30c063853d
12 files changed
+526 -388

No files matched your search

+9 -2
View File
@@ -30,13 +30,13 @@ describe('noise scale', () => {
})
describe('noise terrain', () => {
const area = (values: number[]) => ({ tiles: [[{ size: 2, values: Float32Array.from(values) }]], originX: 10, originZ: 20, blocksPerValue: 4 })
const area = (values: number[]) => ({ tiles: [[{ size: 2, values: Float32Array.from(values) }]], originX: 10, originZ: 20 })
it('raises noise of 0 to 1 to the relief, without water', () => {
const terrain = new NoiseTerrain(area([0, 0.5, 1, Number.NaN]), UNIT_NOISE, noiseScale('terrain', UNIT_NOISE), 64)
expect([terrain.groundAt(0, 0), terrain.groundAt(1, 0), terrain.groundAt(0, 1), terrain.groundAt(1, 1)]).toEqual([0, 32, 64, null])
expect(terrain.waterAt(0, 0)).toBeNull()
expect([terrain.worldX(1), terrain.worldZ(1)]).toEqual([14, 24])
expect([terrain.originX, terrain.originZ]).toEqual([10, 20])
})
it('stands noise in blocks at its own height, under water below the fluid', () => {
@@ -45,4 +45,11 @@ describe('noise terrain', () => {
expect(terrain.waterAt(0, 0)).toBe(0)
expect(terrain.waterAt(1, 0)).toBeNull()
})
it('fills each column up to the block its noise reaches into', () => {
const terrain = new NoiseTerrain(area([-0.5, 12.9, 0.4, 3]), BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64)
expect([terrain.groundAt(0, 0), terrain.groundAt(1, 0), terrain.groundAt(0, 1)]).toEqual([-1, 12, 0])
expect(terrain.waterAt(0, 0)).toBe(0)
expect(terrain.waterAt(0, 1)).toBeNull()
})
})
+6 -11
View File
@@ -2,12 +2,11 @@ import type { NoiseSource, NoiseTile } from '../bridge/types'
import type { TerrainSurface } from '../scene/terrainMesh'
import type { NoiseScale } from './noiseScale'
/** A square of noise tiles, row by row from the north west, and the block its first value is taken at. */
/** A square of noise tiles at one block a value, row by row from the north west, and the block its first value is taken at. */
export interface NoiseArea {
tiles: NoiseTile[][]
originX: number
originZ: number
blocksPerValue: number
}
// The fluid of noise measured in blocks lies at its zero, as the world adds the overlay above its fluid height.
@@ -20,6 +19,8 @@ const FLUID_BLOCKS = 0
export class NoiseTerrain implements TerrainSurface {
readonly columns: number
readonly rows: number
readonly originX: number
readonly originZ: number
private readonly tileSize: number
constructor(
@@ -29,21 +30,15 @@ export class NoiseTerrain implements TerrainSurface {
private readonly reliefBlocks: number
) {
this.tileSize = area.tiles[0][0].size
this.originX = area.originX
this.originZ = area.originZ
this.rows = area.tiles.length * this.tileSize
this.columns = area.tiles[0].length * this.tileSize
}
worldX(column: number): number {
return this.area.originX + column * this.area.blocksPerValue
}
worldZ(row: number): number {
return this.area.originZ + row * this.area.blocksPerValue
}
groundAt(column: number, row: number): number | null {
const value = this.valueAt(column, row)
return Number.isFinite(value) ? this.heightOf(value) : null
return Number.isFinite(value) ? Math.floor(this.heightOf(value)) : null
}
waterAt(column: number, row: number): number | null {
@@ -0,0 +1,145 @@
import type { ColumnField } from './columnField'
import { QuadBatch, type Vec3 } from './quadBatch'
// Light on each face, as Minecraft shades blocks: tops full, north and south sides lighter than east and west.
const TOP_LIGHT = 1
const NORTH_SOUTH_LIGHT = 0.8
const EAST_WEST_LIGHT = 0.6
const WATER_COLOR = 0
interface Span {
bottom: number
top: number
color: number
}
interface Side {
/** Which way the side looks, as a step to the neighbouring column. */
columnStep: number
rowStep: number
light: number
}
const SIDES: readonly Side[] = [
{ columnStep: 0, rowStep: -1, light: NORTH_SOUTH_LIGHT },
{ columnStep: 0, rowStep: 1, light: NORTH_SOUTH_LIGHT },
{ columnStep: -1, rowStep: 0, light: EAST_WEST_LIGHT },
{ columnStep: 1, rowStep: 0, light: EAST_WEST_LIGHT }
]
/**
* The ground as block faces: the top of every column, and the sides where a column stands above its neighbour, or
* above {@code base} at the field's edge and next to columns where nothing is known. Neighbouring columns showing the
* same face in the same colour are one face.
*/
export function groundFaces(field: ColumnField, base: number): QuadBatch {
const batch = new QuadBatch(true)
addTops(field, batch, (column, row) => {
const top = field.hasGround(column, row) ? field.groundTop[field.indexOf(column, row)] : null
return top === null ? null : { bottom: top, top, color: field.color[field.indexOf(column, row)] }
})
addSides(field, batch, (column, row, side) => {
if (!field.hasGround(column, row)) {
return null
}
const top = field.groundTop[field.indexOf(column, row)]
const [nextColumn, nextRow] = [column + side.columnStep, row + side.rowStep]
const bottom = field.hasGround(nextColumn, nextRow) ? field.groundTop[field.indexOf(nextColumn, nextRow)] : base
return bottom < top ? { bottom, top, color: field.color[field.indexOf(column, row)] } : null
})
return batch
}
/**
* The water over the ground: its top where a column holds some, and the sides where it stands above what lies next
* to it, down to its own ground. Drawn without colour; the water has one.
*/
export function waterFaces(field: ColumnField): QuadBatch {
const batch = new QuadBatch(false)
const waterAt = (column: number, row: number): number | null => {
if (!field.contains(column, row)) {
return null
}
const top = field.waterTop[field.indexOf(column, row)]
return Number.isNaN(top) ? null : top
}
addTops(field, batch, (column, row) => {
const top = waterAt(column, row)
return top === null ? null : { bottom: top, top, color: WATER_COLOR }
})
addSides(field, batch, (column, row, side) => {
const top = waterAt(column, row)
if (top === null) {
return null
}
const next = field.surfaceTop(column + side.columnStep, row + side.rowStep)
const bottom = Math.max(next ?? -Infinity, field.groundTop[field.indexOf(column, row)])
return bottom < top ? { bottom, top, color: WATER_COLOR } : null
})
return batch
}
function addTops(field: ColumnField, batch: QuadBatch, spanAt: (column: number, row: number) => Span | null): void {
for (let row = 0; row < field.rows; row++) {
mergeRuns(field.columns, (column) => spanAt(column, row), (first, count, span) => {
batch.add([field.originX + first, span.top, field.originZ + row], [count, 0, 0], [0, 0, 1], shaded(span.color, TOP_LIGHT))
})
}
}
function addSides(field: ColumnField, batch: QuadBatch, spanAt: (column: number, row: number, side: Side) => Span | null): void {
for (const side of SIDES) {
const runsAlongRow = side.rowStep !== 0
const lanes = runsAlongRow ? field.rows : field.columns
const length = runsAlongRow ? field.columns : field.rows
for (let lane = 0; lane < lanes; lane++) {
const columnOf = (step: number): number => (runsAlongRow ? step : lane)
const rowOf = (step: number): number => (runsAlongRow ? lane : step)
mergeRuns(length, (step) => spanAt(columnOf(step), rowOf(step), side), (first, count, span) => {
batch.add(...sideQuad(field, side, columnOf(first), rowOf(first), count, span), shaded(span.color, side.light))
})
}
}
}
// The corner a side starts from is the one on its left as seen from outside, so it runs and rises into view.
function sideQuad(field: ColumnField, side: Side, column: number, row: number, count: number, span: Span): [Vec3, Vec3, Vec3] {
const x = field.originX + column
const z = field.originZ + row
const up: Vec3 = [0, span.top - span.bottom, 0]
if (side.rowStep < 0) {
return [[x, span.bottom, z], [count, 0, 0], up]
}
if (side.rowStep > 0) {
return [[x + count, span.bottom, z + 1], [-count, 0, 0], up]
}
if (side.columnStep < 0) {
return [[x, span.bottom, z + count], [0, 0, -count], up]
}
return [[x + 1, span.bottom, z], [0, 0, count], up]
}
function mergeRuns(length: number, spanAt: (index: number) => Span | null, emit: (first: number, count: number, span: Span) => void): void {
let first = 0
while (first < length) {
const span = spanAt(first)
if (span === null) {
first++
continue
}
let end = first + 1
while (end < length && sameSpan(span, spanAt(end))) {
end++
}
emit(first, end - first, span)
first = end
}
}
function sameSpan(span: Span, other: Span | null): boolean {
return other !== null && other.top === span.top && other.bottom === span.bottom && other.color === span.color
}
function shaded(color: number, light: number): Vec3 {
return [(((color >> 16) & 0xff) / 255) * light, (((color >> 8) & 0xff) / 255) * light, ((color & 0xff) / 255) * light]
}
@@ -0,0 +1,128 @@
import { Box3, Vector3, type Ray } from 'three'
import type { TerrainSurface } from './terrainMesh'
const NO_VALUE = Number.NaN
const MARCH_STEPS_PER_BLOCK = 2
const MARCH_REFINEMENTS = 16
/**
* The surface read once into columns of one block: where each column's ground and water faces stand, and its colour.
* A top face stands one above the block's Y, so ground and water sit where a player stands on them. Where nothing is
* known, the column has no ground and no water.
*/
export class ColumnField {
readonly columns: number
readonly rows: number
readonly originX: number
readonly originZ: number
readonly groundTop: Float32Array
readonly waterTop: Float32Array
readonly color: Int32Array
constructor(surface: TerrainSurface) {
this.columns = surface.columns
this.rows = surface.rows
this.originX = surface.originX
this.originZ = surface.originZ
const count = this.columns * this.rows
this.groundTop = new Float32Array(count).fill(NO_VALUE)
this.waterTop = new Float32Array(count).fill(NO_VALUE)
this.color = new Int32Array(count)
for (let row = 0; row < this.rows; row++) {
for (let column = 0; column < this.columns; column++) {
const ground = surface.groundAt(column, row)
if (ground === null) {
continue
}
const water = surface.waterAt(column, row)
const index = this.indexOf(column, row)
this.groundTop[index] = ground + 1
this.waterTop[index] = water === null ? NO_VALUE : water + 1
this.color[index] = surface.colorAt(column, row)
}
}
}
indexOf(column: number, row: number): number {
return row * this.columns + column
}
contains(column: number, row: number): boolean {
return column >= 0 && row >= 0 && column < this.columns && row < this.rows
}
hasGround(column: number, row: number): boolean {
return this.contains(column, row) && !Number.isNaN(this.groundTop[this.indexOf(column, row)])
}
/** The face the column shows to the sky: its water where it has some, else its ground; null where nothing is known. */
surfaceTop(column: number, row: number): number | null {
if (!this.hasGround(column, row)) {
return null
}
const index = this.indexOf(column, row)
return Number.isNaN(this.waterTop[index]) ? this.groundTop[index] : this.waterTop[index]
}
lowestTop(): number {
let lowest = Infinity
for (const top of this.groundTop) {
if (!Number.isNaN(top)) {
lowest = Math.min(lowest, top)
}
}
return Number.isFinite(lowest) ? lowest : 0
}
/** The box round the field from {@code base} to its highest ground or water. */
bounds(base: number): Box3 {
let highest = base
for (const tops of [this.groundTop, this.waterTop]) {
for (const top of tops) {
if (!Number.isNaN(top)) {
highest = Math.max(highest, top)
}
}
}
return new Box3(new Vector3(this.originX, base, this.originZ), new Vector3(this.originX + this.columns, highest, this.originZ + this.rows))
}
/**
* Where the ray first comes down onto the ground or the water over it, found by marching along it through the
* {@code bounds}, so a pick does not have to test every face. A ray that starts below the surface inside the bounds,
* or runs over columns where nothing is known and out of the field, finds nothing there.
*/
surfaceAlong(ray: Ray, bounds: Box3): Vector3 | null {
const start = bounds.containsPoint(ray.origin) ? ray.origin.clone() : ray.intersectBox(bounds, new Vector3())
if (start === null) {
return null
}
const step = 1 / MARCH_STEPS_PER_BLOCK
const reach = bounds.getSize(new Vector3()).length()
const pointAt = (distance: number): Vector3 => ray.direction.clone().multiplyScalar(distance).add(start)
const isBelow = (point: Vector3): boolean => {
const top = this.surfaceTop(Math.floor(point.x - this.originX), Math.floor(point.z - this.originZ))
return top !== null && point.y <= top
}
if (isBelow(start)) {
return bounds.containsPoint(ray.origin) ? null : start
}
for (let distance = step; distance <= reach; distance += step) {
if (!isBelow(pointAt(distance))) {
continue
}
let above = distance - step
let below = distance
for (let refinement = 0; refinement < MARCH_REFINEMENTS; refinement++) {
const middle = (above + below) / 2
if (isBelow(pointAt(middle))) {
below = middle
} else {
above = middle
}
}
return pointAt(below)
}
return null
}
}
+16 -19
View File
@@ -4,61 +4,58 @@ import type { TerrainSurface } from './terrainMesh'
export type MapTerrainColoring = 'biomes' | 'regions' | 'height'
/** A square of map tiles with heights, row by row from the north west. */
/** A square of map tiles with heights at one block a pixel, row by row from the north west. */
export interface MapTerrainArea {
tiles: MapTile[][]
/** The world spot of the first tile's first pixel. */
/** The world block of the first tile's first pixel. */
originX: number
originZ: number
}
const UNLABELLED_COLOR = 0x5a5f6b
/** The area's tiles as one surface, without the ring each tile carries for its neighbours; the sea fills up to fluid height. */
/** The area's tiles as one surface, a column to a pixel, without the ring each tile carries for its neighbours; the sea fills up to fluid height. */
export class MapTerrain implements TerrainSurface {
readonly columns: number
readonly rows: number
readonly originX: number
readonly originZ: number
private readonly size: number
private readonly blocksPerPixel: number
constructor(
private readonly area: MapTerrainArea,
private readonly coloring: MapTerrainColoring,
private readonly fluidHeight: number
) {
const first = area.tiles[0][0]
this.size = first.size
this.blocksPerPixel = first.blocksPerPixel
this.size = area.tiles[0][0].size
this.originX = area.originX
this.originZ = area.originZ
this.columns = area.tiles[0].length * this.size
this.rows = area.tiles.length * this.size
}
worldX(column: number): number {
return this.area.originX + column * this.blocksPerPixel
}
worldZ(row: number): number {
return this.area.originZ + row * this.blocksPerPixel
}
groundAt(column: number, row: number): number {
const { tile, cell } = this.cellAt(column, row)
return tile.heights![cell]
return Math.floor(this.heightAt(column, row))
}
waterAt(column: number, row: number): number | null {
return this.groundAt(column, row) < this.fluidHeight ? this.fluidHeight : null
return this.heightAt(column, row) < this.fluidHeight ? Math.floor(this.fluidHeight) : null
}
colorAt(column: number, row: number): number {
if (this.coloring === 'height') {
return heightColor(this.groundAt(column, row), this.fluidHeight)
return heightColor(this.heightAt(column, row), this.fluidHeight)
}
const { tile, cell } = this.cellAt(column, row)
const index = this.coloring === 'regions' ? tile.regions[cell] : tile.subjects[cell]
return index === NO_LABEL ? UNLABELLED_COLOR : tile.labels[index].color
}
private heightAt(column: number, row: number): number {
const { tile, cell } = this.cellAt(column, row)
return tile.heights![cell]
}
private cellAt(column: number, row: number): { tile: MapTile; cell: number } {
const tile = this.area.tiles[Math.floor(row / this.size)][Math.floor(column / this.size)]
const gridSize = this.size + 2
@@ -0,0 +1,75 @@
import { BufferAttribute, BufferGeometry } from 'three'
const VERTICES_PER_QUAD = 4
const INDICES_PER_QUAD = 6
const COMPONENTS = 3
const FIRST_CAPACITY_QUADS = 1024
/** Flat quads gathered for one geometry; vertices are not shared, so every quad keeps its own colour and shade. */
export class QuadBatch {
private positions = new Float32Array(FIRST_CAPACITY_QUADS * VERTICES_PER_QUAD * COMPONENTS)
private colors: Float32Array | null
private quads = 0
constructor(coloured: boolean) {
this.colors = coloured ? new Float32Array(this.positions.length) : null
}
get count(): number {
return this.quads
}
/**
* A quad from {@code origin} along {@code along} and {@code up}; it faces the way {@code up} crosses {@code along}.
* Colours are red, green and blue from 0 to 1.
*/
add(origin: Vec3, along: Vec3, up: Vec3, color: Vec3 | null): void {
this.reserveOne()
const first = this.quads * VERTICES_PER_QUAD * COMPONENTS
for (let corner = 0; corner < VERTICES_PER_QUAD; corner++) {
const [alongSteps, upSteps] = [corner >> 1, corner & 1]
for (let axis = 0; axis < COMPONENTS; axis++) {
const at = first + corner * COMPONENTS + axis
this.positions[at] = origin[axis] + along[axis] * alongSteps + up[axis] * upSteps
if (this.colors !== null && color !== null) {
this.colors[at] = color[axis]
}
}
}
this.quads++
}
geometry(): BufferGeometry {
const geometry = new BufferGeometry()
const used = this.quads * VERTICES_PER_QUAD * COMPONENTS
geometry.setAttribute('position', new BufferAttribute(this.positions.slice(0, used), COMPONENTS))
if (this.colors !== null) {
geometry.setAttribute('color', new BufferAttribute(this.colors.slice(0, used), COMPONENTS))
}
const indices = new Uint32Array(this.quads * INDICES_PER_QUAD)
for (let quad = 0; quad < this.quads; quad++) {
const first = quad * VERTICES_PER_QUAD
indices.set([first, first + 1, first + 2, first + 2, first + 1, first + 3], quad * INDICES_PER_QUAD)
}
geometry.setIndex(new BufferAttribute(indices, 1))
return geometry
}
private reserveOne(): void {
if ((this.quads + 1) * VERTICES_PER_QUAD * COMPONENTS <= this.positions.length) {
return
}
this.positions = grown(this.positions)
if (this.colors !== null) {
this.colors = grown(this.colors)
}
}
}
export type Vec3 = readonly [number, number, number]
function grown(values: Float32Array): Float32Array<ArrayBuffer> {
const bigger = new Float32Array(values.length * 2)
bigger.set(values)
return bigger
}
+10 -18
View File
@@ -4,10 +4,10 @@ import type { TerrainSurface } from './terrainMesh'
export type SavedTerrainColoring = 'biomes' | 'blocks' | 'height'
/** A square of saved tiles, row by row from the north west. */
/** A square of saved tiles at one block a pixel, row by row from the north west. */
export interface SavedTerrainArea {
tiles: SavedTile[][]
/** The world spot of the first tile's first pixel. */
/** The world block of the first tile's first pixel. */
originX: number
originZ: number
}
@@ -17,14 +17,14 @@ const VANILLA_SEA_LEVEL = 63
const UNKNOWN_BLOCK_COLOR = 0x7f7f7f
/**
* The saved columns as one surface. Heights are the tops of the blocks, one above their Y, so ground and water sit
* where a player stands on them.
* The saved columns as one surface, a column to a pixel, so each is the block it was read from.
*/
export class SavedTerrain implements TerrainSurface {
readonly columns: number
readonly rows: number
readonly originX: number
readonly originZ: number
private readonly size: number
private readonly blocksPerPixel: number
constructor(
private readonly area: SavedTerrainArea,
@@ -32,31 +32,23 @@ export class SavedTerrain implements TerrainSurface {
private readonly seaLevel: number | null,
private readonly blockColors: Map<string, number>
) {
const first = area.tiles[0][0]
this.size = first.size
this.blocksPerPixel = first.blocksPerPixel
this.size = area.tiles[0][0].size
this.originX = area.originX
this.originZ = area.originZ
this.columns = area.tiles[0].length * this.size
this.rows = area.tiles.length * this.size
}
worldX(column: number): number {
return this.area.originX + column * this.blocksPerPixel
}
worldZ(row: number): number {
return this.area.originZ + row * this.blocksPerPixel
}
groundAt(column: number, row: number): number | null {
const { tile, pixel } = this.pixelAt(column, row)
const ground = tile.groundY[pixel]
return ground === tile.noGround ? null : ground + 1
return ground === tile.noGround ? null : ground
}
waterAt(column: number, row: number): number | null {
const { tile, pixel } = this.pixelAt(column, row)
const water = tile.waterSurfaceY[pixel]
return water === tile.noWater ? null : water + 1
return water === tile.noWater ? null : water
}
colorAt(column: number, row: number): number {
+108 -41
View File
@@ -1,51 +1,112 @@
import { Ray, Vector3, type Mesh } from 'three'
import { Ray, Vector3, type BufferGeometry, type Mesh } from 'three'
import { describe, expect, it } from 'vitest'
import { buildTerrainMesh, type TerrainSurface } from './terrainMesh'
const GROUND = 10
const WATER = 12
const BLOCKS_PER_VERTEX = 2
const POND_GROUND = 7
const WATER = 9
const BASE_DEPTH = 8
const GREY = 0x808080
const RED = 0xff0000
// Three by three vertices: nothing known at the north west corner, a pond at the middle vertex.
const surface: TerrainSurface = {
columns: 3,
rows: 3,
worldX: (column) => column * BLOCKS_PER_VERTEX,
worldZ: (row) => row * BLOCKS_PER_VERTEX,
groundAt: (column, row) => (column === 0 && row === 0 ? null : GROUND),
waterAt: (column, row) => (column === 1 && row === 1 ? WATER : null),
colorAt: () => 0x808080
// Three by three columns: nothing known at the north west corner, a pond at the middle column.
function surfaceOf(colorAt: TerrainSurface['colorAt'] = () => GREY): TerrainSurface {
return {
columns: 3,
rows: 3,
originX: 100,
originZ: 200,
groundAt: (column, row) => {
if (column === 0 && row === 0) {
return null
}
return column === 1 && row === 1 ? POND_GROUND : GROUND
},
waterAt: (column, row) => (column === 1 && row === 1 ? WATER : null),
colorAt
}
}
function meshes(): Mesh[] {
return buildTerrainMesh(surface).content.object.children as Mesh[]
const surface = surfaceOf()
function meshes(terrain: TerrainSurface = surface): { ground: Mesh; water: Mesh } {
const [ground, water] = buildTerrainMesh(terrain).content.object.children as Mesh[]
return { ground, water }
}
function triangles(mesh: Mesh): number {
return mesh.geometry.getIndex()!.count / 3
function quads(mesh: Mesh): number {
return mesh.geometry.getIndex()!.count / 6
}
// The quads of a geometry as the point in the middle of each and the way it faces.
function faces(geometry: BufferGeometry): { middle: Vector3; normal: Vector3 }[] {
const positions = geometry.getAttribute('position')
const found: { middle: Vector3; normal: Vector3 }[] = []
for (let first = 0; first < positions.count; first += 4) {
const corner = (index: number): Vector3 => new Vector3().fromBufferAttribute(positions, first + index)
const [origin, up, along, far] = [corner(0), corner(1), corner(2), corner(3)]
found.push({
middle: origin.clone().add(far).multiplyScalar(0.5),
normal: up.clone().sub(origin).cross(along.clone().sub(origin)).normalize()
})
}
return found
}
describe('terrain mesh', () => {
it('leaves out the squares that touch a hole', () => {
const [ground] = meshes()
expect(triangles(ground)).toBe(3 * 2)
it('draws one top for each run of neighbouring columns at one height', () => {
const { ground } = meshes()
const tops = faces(ground.geometry).filter((face) => face.normal.y === 1)
expect(tops).toHaveLength(5)
expect(tops.filter((top) => top.middle.y === GROUND + 1)).toHaveLength(4)
})
it('frames the known surface from below its walls to its highest water, not the unused vertices', () => {
it('draws a side only where a column stands above its neighbour or beside nothing known', () => {
const { ground } = meshes()
expect(quads(ground) - faces(ground.geometry).filter((face) => face.normal.y === 1).length).toBe(10)
})
it('keeps columns of other colours apart', () => {
const striped = surfaceOf((column) => (column === 2 ? RED : GREY))
const tops = faces(meshes(striped).ground.geometry).filter((face) => face.normal.y === 1)
expect(tops).toHaveLength(7)
})
it('faces every side outwards from the column it belongs to', () => {
const { ground } = meshes()
const sides = faces(ground.geometry).filter((face) => face.normal.y === 0)
const pondSide = sides.find((side) => side.middle.x === 101 + 1 && side.normal.x === -1 && side.middle.z === 201.5)!
expect(pondSide.middle.y).toBe((POND_GROUND + 1 + GROUND + 1) / 2)
const edge = sides.find((side) => side.normal.z === -1 && side.middle.z === 200)!
expect(edge.middle.y).toBe((GROUND + 1 + POND_GROUND + 1 - BASE_DEPTH) / 2)
})
it('lights tops fully and sides less', () => {
const colors = meshes().ground.geometry.getAttribute('color')
const lights = new Set<number>()
for (let vertex = 0; vertex < colors.count; vertex += 4) {
lights.add(Math.round((colors.getX(vertex) * 255 * 100) / 0x80) / 100)
}
expect([...lights].sort()).toEqual([0.6, 0.8, 1])
})
it('frames the known columns from below their sides to the highest water or ground', () => {
const bounds = buildTerrainMesh(surface).content.bounds
expect(bounds.min.toArray()).toEqual([0, GROUND - 8, 0])
expect(bounds.max.toArray()).toEqual([2 * BLOCKS_PER_VERTEX, WATER, 2 * BLOCKS_PER_VERTEX])
expect(bounds.min.toArray()).toEqual([100, POND_GROUND + 1 - BASE_DEPTH, 200])
expect(bounds.max.toArray()).toEqual([103, GROUND + 1, 203])
})
it('carries the water out to the shore around the vertex that holds it, except into the hole', () => {
const [, , water] = meshes()
expect(triangles(water)).toBe(3 * 2)
it('draws the water of a column as its top, and no side where the ground beside it stands higher', () => {
const { water } = meshes()
expect(quads(water)).toBe(1)
expect(faces(water.geometry)[0].middle.toArray()).toEqual([101.5, WATER + 1, 201.5])
})
it('stands walls only between rim vertices that both have ground', () => {
const [, landWalls] = meshes()
// The rim has eight segments; the two at the hole's corner fall away.
expect(triangles(landWalls)).toBe(6 * 2)
it('draws a water side where the water stands above what lies beside it', () => {
const lake = { ...surface, groundAt: (column: number, row: number) => (column === 1 && row === 1 ? POND_GROUND : column === 0 && row === 0 ? null : WATER - 3) }
const sides = faces(meshes(lake).water.geometry).filter((face) => face.normal.y === 0)
expect(sides).toHaveLength(4)
expect(sides.every((side) => side.middle.y === (POND_GROUND + 1 + WATER + 1) / 2)).toBe(true)
})
})
@@ -53,22 +114,28 @@ describe('terrain surface picking', () => {
const content = buildTerrainMesh(surface).content
const pick = (origin: Vector3, direction: Vector3): Vector3 | null => content.surfaceAlong!(new Ray(origin, direction.normalize()))
it('finds where a slanted ray meets the water over the pond', () => {
const hit = pick(new Vector3(-7, WATER + 10, 3), new Vector3(1, -1, 0))!
expect(hit.x).toBeCloseTo(3, 3)
expect(hit.y).toBeCloseTo(WATER, 3)
expect(hit.z).toBeCloseTo(3, 3)
it('finds the water over the pond and the top of the ground beside it', () => {
const water = pick(new Vector3(101.5, 30, 201.5), new Vector3(0, -1, 0))!
expect(water.x).toBeCloseTo(101.5, 3)
expect(water.y).toBeCloseTo(WATER + 1, 3)
expect(water.z).toBeCloseTo(201.5, 3)
expect(pick(new Vector3(102.5, 30, 201.5), new Vector3(0, -1, 0))!.y).toBeCloseTo(GROUND + 1, 3)
})
it('finds nothing over a hole, beside the field, or from below the ground', () => {
expect(pick(new Vector3(1, 30, 1), new Vector3(0, -1, 0))).toBeNull()
expect(pick(new Vector3(100, 30, 3), new Vector3(0, -1, 0))).toBeNull()
expect(pick(new Vector3(3, GROUND - 2, 3), new Vector3(0, 1, 0))).toBeNull()
it('finds where a slanted ray meets the side of a column', () => {
const hit = pick(new Vector3(95, GROUND, 202.5), new Vector3(1, -0.01, 0))!
expect(hit.x).toBeCloseTo(100, 1)
})
it('meets the wall where a ray comes in from the side below the rim', () => {
const hit = pick(new Vector3(-10, GROUND - 1, 3), new Vector3(1, 0, 0))!
expect(hit.x).toBeCloseTo(0, 3)
it('finds nothing over an unknown column, beside the field, or from below the ground', () => {
expect(pick(new Vector3(100.5, 30, 200.5), new Vector3(0, -1, 0))).toBeNull()
expect(pick(new Vector3(300, 30, 202.5), new Vector3(0, -1, 0))).toBeNull()
expect(pick(new Vector3(102.5, GROUND - 2, 202.5), new Vector3(0, 1, 0))).toBeNull()
})
it('meets the side where a ray comes in from the side below the rim', () => {
const hit = pick(new Vector3(90, GROUND - 1, 202.5), new Vector3(1, 0, 0))!
expect(hit.x).toBeCloseTo(100, 3)
expect(hit.y).toBeCloseTo(GROUND - 1, 3)
})
})
+22 -289
View File
@@ -1,17 +1,21 @@
import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, Vector3, type Ray } from 'three'
import { DoubleSide, FrontSide, Group, Mesh, MeshBasicMaterial } from 'three'
import type { ViewportContent } from '../studio/SceneViewport'
import { groundFaces, waterFaces } from './columnFaces'
import { ColumnField } from './columnField'
/**
* A height field to draw, one vertex per map pixel, row by row from the north west: the ground, the water over it,
* and the ground's colour. Where nothing is known, the ground is null and the field has a hole.
* Terrain to draw as columns, one block each, row by row from the north west: the ground, the water over it, and the
* ground's colour. Heights are the Y of the top block, so a column of 64 has its top face at 65. Where nothing is
* known, the ground is null and the column is left out.
*/
export interface TerrainSurface {
readonly columns: number
readonly rows: number
worldX(column: number): number
worldZ(row: number): number
/** The world block of the first column and of the first row. */
readonly originX: number
readonly originZ: number
groundAt(column: number, row: number): number | null
/** The water's surface over the vertex, or null where it is dry. */
/** The Y of the water's top block over the column, or null where it is dry. */
waterAt(column: number, row: number): number | null
colorAt(column: number, row: number): number
}
@@ -23,301 +27,30 @@ export interface TerrainMesh {
const WATER_COLOR = 0x3f76e4
const WATER_OPACITY = 0.55
// Light from high in the south west, so slopes read as relief; the darkest side keeps some light.
const LIGHT = new Vector3(-0.6, 1, 0.4).normalize()
const AMBIENT_LIGHT = 0.5
const WALL_DEPTH_BLOCKS = 8
const WALL_TOP_LIGHT = 0.55
const WALL_BASE_LIGHT = 0.25
const NO_VALUE = Number.NaN
const MARCH_STEPS_PER_CELL = 2
const MARCH_REFINEMENTS = 16
const BASE_DEPTH_BLOCKS = 8
/**
* The surface as ground lit by its slopes, see-through water over it, and walls round the rim down to below the lowest
* ground, so the square reads as a solid block cut from the world.
* The surface as block columns with their faces merged where neighbours show the same one, flat-shaded as Minecraft
* shades blocks, with see-through water over them. Sides on the rim reach down to below the lowest ground, so the
* square reads as a solid block cut from the world.
*/
export function buildTerrainMesh(surface: TerrainSurface): TerrainMesh {
const field = HeightField.of(surface)
const base = field.lowest() - WALL_DEPTH_BLOCKS
const ground = groundGeometry(field)
const water = waterGeometry(field)
const landWalls = rimWall(field, (vertex) => field.ground[vertex], () => base)
const seaWalls = rimWall(field, (vertex) => field.water[vertex], (vertex) => Math.min(field.ground[vertex], field.water[vertex]))
const groundMaterial = new MeshBasicMaterial({ vertexColors: true, side: DoubleSide })
const field = new ColumnField(surface)
const base = field.lowestTop() - BASE_DEPTH_BLOCKS
const ground = groundFaces(field, base).geometry()
const water = waterFaces(field).geometry()
const groundMaterial = new MeshBasicMaterial({ vertexColors: true, side: FrontSide })
const waterMaterial = new MeshBasicMaterial({ color: WATER_COLOR, transparent: true, opacity: WATER_OPACITY, depthWrite: false, side: DoubleSide })
const group = new Group()
group.add(new Mesh(ground, groundMaterial), new Mesh(landWalls, groundMaterial), new Mesh(water, waterMaterial), new Mesh(seaWalls, waterMaterial))
const geometries = [ground, water, landWalls, seaWalls]
group.add(new Mesh(ground, groundMaterial), new Mesh(water, waterMaterial))
const bounds = field.bounds(base)
return {
content: { object: group, bounds, surfaceAlong: (ray) => field.surfaceAlong(ray, bounds) },
dispose: () => {
geometries.forEach((geometry) => geometry.dispose())
ground.dispose()
water.dispose()
groundMaterial.dispose()
waterMaterial.dispose()
}
}
}
function groundGeometry(field: HeightField): BufferGeometry {
const { surface, ground } = field
const positions = new Float32Array(ground.length * 3)
const colors = new Float32Array(ground.length * 3)
for (let vertex = 0; vertex < ground.length; vertex++) {
if (Number.isNaN(ground[vertex])) {
continue
}
const [column, row] = field.columnAndRow(vertex)
positions.set([surface.worldX(column), ground[vertex], surface.worldZ(row)], vertex * 3)
const light = AMBIENT_LIGHT + (1 - AMBIENT_LIGHT) * Math.max(0, field.normal(column, row).dot(LIGHT))
colors.set(rgb(surface.colorAt(column, row), light), vertex * 3)
}
return indexedGeometry(positions, colors, field.quadsWhere((corners) => corners.every((vertex) => !Number.isNaN(ground[vertex]))))
}
// Only quads holding water of their own; the vertices next to water carry its level, so it meets the shore.
function waterGeometry(field: HeightField): BufferGeometry {
const { surface, water, ownWater } = field
const positions = new Float32Array(water.length * 3)
for (let vertex = 0; vertex < water.length; vertex++) {
if (!Number.isNaN(water[vertex])) {
const [column, row] = field.columnAndRow(vertex)
positions.set([surface.worldX(column), water[vertex], surface.worldZ(row)], vertex * 3)
}
}
const quads = field.quadsWhere((corners) => corners.every((vertex) => !Number.isNaN(water[vertex])) && corners.some((vertex) => ownWater[vertex]))
return indexedGeometry(positions, null, quads)
}
/** A wall round the field's rim from {@code topOf} down to {@code bottomOf} each rim vertex, darkening downwards. */
function rimWall(field: HeightField, topOf: (vertex: number) => number, bottomOf: (vertex: number) => number): BufferGeometry {
const rim = field.rimVertices()
const positions = new Float32Array(rim.length * 2 * 3)
const colors = new Float32Array(rim.length * 2 * 3)
// A rim vertex without a top or a bottom, such as dry land for the water's wall, holds no wall and keeps the origin.
const standing = rim.map((vertex) => !Number.isNaN(topOf(vertex)) && !Number.isNaN(bottomOf(vertex)))
rim.forEach((vertex, index) => {
if (!standing[index]) {
return
}
const [column, row] = field.columnAndRow(vertex)
const [x, z] = [field.surface.worldX(column), field.surface.worldZ(row)]
positions.set([x, topOf(vertex), z, x, bottomOf(vertex), z], index * 6)
const color = field.surface.colorAt(column, row)
colors.set([...rgb(color, WALL_TOP_LIGHT), ...rgb(color, WALL_BASE_LIGHT)], index * 6)
})
const indices: number[] = []
for (let index = 0; index < rim.length; index++) {
const next = (index + 1) % rim.length
if (standing[index] && standing[next]) {
const [upper, lower, nextUpper, nextLower] = [index * 2, index * 2 + 1, next * 2, next * 2 + 1]
indices.push(upper, lower, nextUpper, nextUpper, lower, nextLower)
}
}
return indexedGeometry(positions, colors, indices)
}
function indexedGeometry(positions: Float32Array, colors: Float32Array | null, indices: number[] | Uint32Array): BufferGeometry {
const geometry = new BufferGeometry()
geometry.setAttribute('position', new BufferAttribute(positions, 3))
if (colors !== null) {
geometry.setAttribute('color', new BufferAttribute(colors, 3))
}
geometry.setIndex(new BufferAttribute(indices instanceof Uint32Array ? indices : Uint32Array.from(indices), 1))
return geometry
}
function rgb(color: number, light: number): [number, number, number] {
return [(((color >> 16) & 0xff) / 255) * light, (((color >> 8) & 0xff) / 255) * light, ((color & 0xff) / 255) * light]
}
/** The surface's ground and water read once per vertex, with no value as NaN, and how its vertices stand together. */
class HeightField {
readonly ground: Float32Array
readonly water: Float32Array
readonly ownWater: Uint8Array
private constructor(readonly surface: TerrainSurface) {
const count = surface.columns * surface.rows
this.ground = new Float32Array(count)
this.water = new Float32Array(count)
this.ownWater = new Uint8Array(count)
for (let vertex = 0; vertex < count; vertex++) {
const [column, row] = this.columnAndRow(vertex)
const ground = surface.groundAt(column, row)
const water = ground === null ? null : surface.waterAt(column, row)
this.ground[vertex] = ground ?? NO_VALUE
this.water[vertex] = water ?? NO_VALUE
this.ownWater[vertex] = water === null ? 0 : 1
}
this.extendWaterToShores()
}
static of(surface: TerrainSurface): HeightField {
return new HeightField(surface)
}
columnAndRow(vertex: number): [number, number] {
return [vertex % this.surface.columns, Math.floor(vertex / this.surface.columns)]
}
lowest(): number {
let lowest = Infinity
for (let vertex = 0; vertex < this.ground.length; vertex++) {
if (!Number.isNaN(this.ground[vertex])) {
lowest = Math.min(lowest, this.ground[vertex], Number.isNaN(this.water[vertex]) ? Infinity : this.water[vertex])
}
}
return Number.isFinite(lowest) ? lowest : 0
}
/** The box round the field from {@code base} to its highest ground or water; vertices left out of it do not count. */
bounds(base: number): Box3 {
let highest = base
for (let vertex = 0; vertex < this.ground.length; vertex++) {
for (const height of [this.ground[vertex], this.water[vertex]]) {
if (!Number.isNaN(height)) {
highest = Math.max(highest, height)
}
}
}
const { columns, rows } = this.surface
return new Box3(
new Vector3(this.surface.worldX(0), base, this.surface.worldZ(0)),
new Vector3(this.surface.worldX(columns - 1), highest, this.surface.worldZ(rows - 1))
)
}
/**
* Where the ray first comes down onto the ground or the water over it, found by marching along it through the
* {@code bounds}, so a pick does not have to test every triangle. A ray that starts below the surface inside the
* bounds, or runs over holes and out of the field, finds nothing there.
*/
surfaceAlong(ray: Ray, bounds: Box3): Vector3 | null {
const start = bounds.containsPoint(ray.origin) ? ray.origin.clone() : ray.intersectBox(bounds, new Vector3())
if (start === null) {
return null
}
const cell = Math.abs(this.surface.worldX(1) - this.surface.worldX(0)) || 1
const step = cell / MARCH_STEPS_PER_CELL
const reach = bounds.getSize(new Vector3()).length()
const pointAt = (distance: number): Vector3 => ray.direction.clone().multiplyScalar(distance).add(start)
const isBelow = (point: Vector3): boolean => {
const top = this.topAt(point.x, point.z)
return top !== null && point.y <= top
}
if (isBelow(start)) {
return bounds.containsPoint(ray.origin) ? null : start
}
for (let distance = step; distance <= reach; distance += step) {
if (!isBelow(pointAt(distance))) {
continue
}
let above = distance - step
let below = distance
for (let refinement = 0; refinement < MARCH_REFINEMENTS; refinement++) {
const middle = (above + below) / 2
if (isBelow(pointAt(middle))) {
below = middle
} else {
above = middle
}
}
return pointAt(below)
}
return null
}
/** The height of the ground, or of the water over it, at a place in the field, blended between its four vertices. */
private topAt(x: number, z: number): number | null {
const { columns, rows } = this.surface
if (columns < 2 || rows < 2) {
return null
}
const columnAt = (x - this.surface.worldX(0)) / ((this.surface.worldX(columns - 1) - this.surface.worldX(0)) / (columns - 1))
const rowAt = (z - this.surface.worldZ(0)) / ((this.surface.worldZ(rows - 1) - this.surface.worldZ(0)) / (rows - 1))
if (!(columnAt >= 0 && columnAt <= columns - 1 && rowAt >= 0 && rowAt <= rows - 1)) {
return null
}
const column = Math.min(Math.floor(columnAt), columns - 2)
const row = Math.min(Math.floor(rowAt), rows - 2)
const [alongColumn, alongRow] = [columnAt - column, rowAt - row]
const northWest = row * columns + column
const tops = [northWest, northWest + 1, northWest + columns, northWest + columns + 1].map((vertex) =>
Number.isNaN(this.water[vertex]) ? this.ground[vertex] : Math.max(this.ground[vertex], this.water[vertex])
)
if (tops.some(Number.isNaN)) {
return null
}
const north = tops[0] + (tops[1] - tops[0]) * alongColumn
const south = tops[2] + (tops[3] - tops[2]) * alongColumn
return north + (south - north) * alongRow
}
/** The two triangles of each grid square whose four corners pass {@code wanted}. */
quadsWhere(wanted: (corners: [number, number, number, number]) => boolean): Uint32Array {
const { columns, rows } = this.surface
const indices: number[] = []
for (let row = 0; row < rows - 1; row++) {
for (let column = 0; column < columns - 1; column++) {
const northWest = row * columns + column
const southWest = northWest + columns
if (wanted([northWest, northWest + 1, southWest, southWest + 1])) {
indices.push(northWest, southWest, northWest + 1, northWest + 1, southWest, southWest + 1)
}
}
}
return Uint32Array.from(indices)
}
normal(column: number, row: number): Vector3 {
const { columns, rows } = this.surface
const here = this.ground[row * columns + column]
const at = (atColumn: number, atRow: number): number => {
const height = this.ground[Math.min(rows - 1, Math.max(0, atRow)) * columns + Math.min(columns - 1, Math.max(0, atColumn))]
return Number.isNaN(height) ? here : height
}
const spacing = Math.abs(this.surface.worldX(Math.min(columns - 1, 1)) - this.surface.worldX(0)) || 1
return new Vector3(at(column - 1, row) - at(column + 1, row), 2 * spacing, at(column, row - 1) - at(column, row + 1)).normalize()
}
/** The vertices on the edge of the field, once each, going round clockwise from the north west corner. */
rimVertices(): number[] {
const { columns, rows } = this.surface
const rim: number[] = []
for (let column = 0; column < columns - 1; column++) rim.push(column)
for (let row = 0; row < rows - 1; row++) rim.push(row * columns + columns - 1)
for (let column = columns - 1; column > 0; column--) rim.push((rows - 1) * columns + column)
for (let row = rows - 1; row > 0; row--) rim.push(row * columns)
return rim
}
// A dry vertex next to water takes the highest water beside it, so the water's edge runs under the shore.
private extendWaterToShores(): void {
const { columns, rows } = this.surface
const own = Float32Array.from(this.water)
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
const vertex = row * columns + column
if (this.ownWater[vertex] === 1 || Number.isNaN(this.ground[vertex])) {
continue
}
let highest = NO_VALUE
for (let offsetRow = -1; offsetRow <= 1; offsetRow++) {
for (let offsetColumn = -1; offsetColumn <= 1; offsetColumn++) {
const [nearColumn, nearRow] = [column + offsetColumn, row + offsetRow]
if (nearColumn < 0 || nearRow < 0 || nearColumn >= columns || nearRow >= rows) {
continue
}
const near = own[nearRow * columns + nearColumn]
if (!Number.isNaN(near) && (Number.isNaN(highest) || near > highest)) {
highest = near
}
}
}
this.water[vertex] = highest
}
}
}
}
@@ -21,6 +21,7 @@ type NoiseDisplay = 'flat' | 'terrain'
const NUMBER = new Intl.NumberFormat('en-US', { maximumFractionDigits: 3 })
const DEFAULT_SEED = '12345'
const TERRAIN_TILES_PER_SIDE = 4
const TERRAIN_BLOCKS_PER_VALUE = 1
const LOWEST_RELIEF_BLOCKS = 1
const TALLEST_RELIEF_BLOCKS = 4064
const DEFAULT_RELIEF_BLOCKS = 64
@@ -298,7 +299,7 @@ function NoiseTerrainView({
)
}
/** The square of tiles around where the 2D view looked, at the scale it drew; every tile arrives before it is shown. */
/** The square of tiles around where the 2D view looked, one block a value; every tile arrives before it is shown. */
function useNoiseArea(
client: BridgeClient,
sourceId: string,
@@ -310,21 +311,19 @@ function useNoiseArea(
const [area, setArea] = useState<NoiseArea | null>(null)
useEffect(() => {
const stop = new AbortController()
const tileBlocks = NOISE_TILE_PIXELS * framing.renderScale
const tileBlocks = NOISE_TILE_PIXELS * TERRAIN_BLOCKS_PER_VALUE
const firstTileX = Math.floor(framing.centerX / tileBlocks - TERRAIN_TILES_PER_SIDE / 2)
const firstTileZ = Math.floor(framing.centerZ / tileBlocks - TERRAIN_TILES_PER_SIDE / 2)
const rows = Array.from({ length: TERRAIN_TILES_PER_SIDE }, (_, row) =>
Promise.all(
Array.from({ length: TERRAIN_TILES_PER_SIDE }, (_, column) =>
client.noiseTile(sourceId, seed, firstTileX + column, firstTileZ + row, framing.renderScale, NOISE_TILE_PIXELS, stop.signal)
client.noiseTile(sourceId, seed, firstTileX + column, firstTileZ + row, TERRAIN_BLOCKS_PER_VALUE, NOISE_TILE_PIXELS, stop.signal)
)
)
)
setArea(null)
Promise.all(rows)
.then((tiles: NoiseTile[][]) =>
setArea({ tiles, originX: firstTileX * tileBlocks, originZ: firstTileZ * tileBlocks, blocksPerValue: framing.renderScale })
)
.then((tiles: NoiseTile[][]) => setArea({ tiles, originX: firstTileX * tileBlocks, originZ: firstTileZ * tileBlocks }))
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
return () => stop.abort()
}, [client, sourceId, seed, revision, framing, tell])
@@ -16,7 +16,7 @@ import { SceneViewport } from './SceneViewport'
const NUMBER = new Intl.NumberFormat('en-US')
const TILES_PER_SIDE = 4
const TILE_PIXELS = 128
const BLOCKS_PER_PIXEL = 2
const BLOCKS_PER_PIXEL = 1
const TILE_BLOCKS = TILE_PIXELS * BLOCKS_PER_PIXEL
const NO_COLORS = new Map<string, number>()
const COLORING_ITEM = 'h-7 px-3 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground'
@@ -9,7 +9,7 @@ import { SceneViewport } from './SceneViewport'
const NUMBER = new Intl.NumberFormat('en-US')
const TILES_PER_SIDE = 4
const TILE_PIXELS = 128
const BLOCKS_PER_PIXEL = 2
const BLOCKS_PER_PIXEL = 1
const TILE_BLOCKS = TILE_PIXELS * BLOCKS_PER_PIXEL
const COLORING_ITEM = 'h-7 px-3 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground'