FERRETGame engine over Babylon.js
Ferret

Landscapes (terrain)

@ferret/terrain makes a landscape from a small JSON description and answers one question everywhere: what is the ground here? The relief is a pure function of (seed, x, z) and of the ground built so far, so a tile at any resolution, a collision tile, a query from a character and a far mountain all agree, and a game needs no heightmap files. Everything runs in Node (tests), and the Babylon part only draws what the maths says.

The rules the package keeps: no Math.random and no clock (integer hashes only); tiles are Float32 on a lattice snapped to the tile size, so neighbours agree to the bit and a fine tile equals a coarse one at the coarse vertices; every shape, biome and species is data.

The spec#

A TerrainSpec is { version: 1, seed, relief: ReliefOp[] }. Operations run in order on the height built so far, each with optional masks (radial, noise, height, line) and a blend mode (add, max, min, set, mul). validateSpec returns { path, message } issues for a bad spec.

OperationWhat it does
noisefBm, ridged, billow, Voronoi noise with slope damping and domain warp
shapemassif, range, crater, craters (a size law with degraded rims), volcano, mesa, dunes (transverse, linear, barchan, star), valley (V or U), rift, floes, crevasses
terracestepped slopes (badlands, rice terraces)
rivera carved channel with banks and meanders; gives the water level, flow and waterfalls
eroderain carving and thermal creep on world-aligned lattice blocks; valleys drain, ridges sharpen
lakefills every basin deeper than minDepth flat to its spill level
ponda lake you place: a bowl round center with a ragged shore, filled to the ground's height at the centre less drop; exact and cheap at any size
painthand-edited height, stored as sparse tiles (the editor writes brush strokes here)
importa height grid (an Unreal landscape export, a scan) blended into the ground

Relief gives height, gradient, normal, slope, river, waterAt and tile. erode costs about a second per lattice block, so give a flight-scale landscape a coarse step (48 m) and a walking-scale one a fine step (8 m); blocks are cached. A block is made the first time any height in it is asked, so an erode over a wide band (a ring of mountains round a 100 km zone) stalls the first flight over it: mask it to the working area and make its blocks on the loading screen, or shape far mountains with ridged noise and a warp instead.

lake finds pits block by block, so it cannot see a basin wider than a block; for a lake of kilometres use pond, which carries its own level. A world authored as a function (a game's own coast and hills) goes in as import grids: a coarse one over the whole world (to past the horizon, or the land ends in a flat plain at sea level), finer ones where the shape is sharp (a cliff, a harbour), then noise and a river on top.

Climate, biomes and the ground#

Climate gives temperature (lapse rate, a latitude-like gradient), moisture (noise, low ground, rain shadow behind high ground upwind) and exposure; a game may fix any of them (fixed: { temperature: -150, moisture: 0 } is the Moon). BIOMES holds 25 biomes as data: meadow, alpine meadow, mountains, cliffs, taiga, temperate forest, jungle, steppe, savanna, farmland, swamp, floodplain, coast, sand desert, rock desert, badlands, salt flat, volcanic field, tundra, ice sheet, glacier, sea ice, polar coast, Mars, Moon. A biome is a climate box, a blend width, layers with rules by slope, height, wetness and noise, a soil, a surface and what it gives the weather. Narrow biomes win ties; manual biomes (farmland, volcanic) come only from the author's biome map (zones: a circle or polygon with a feathered edge).

Ground.sample(x, z) returns a GroundSample: height, normal, slope, biome and its weights, the dominant layer, soil, surface, wetness and water. Rendering, collision, weather, sound and AI all ask this.

Seeing it#

TerrainView plans square chunks of several sizes round the camera (ChunkPlanner: neighbours differ by one level, the finest cell is yours), builds them under a per-update budget, keeps the old ones until the replacements exist (it never leaves a hole), geomorphs between levels and hides seams with skirts. Colours are baked from the ground layers; with shadows: true the cast shadows of the relief are baked too (setSun rebakes). The mesh maths is buildChunkMesh, with no engine in it. In the Unreal build the view is a Landscape.

A game may colour and draw the ground itself:

  • paint(x, z, h, slope, rgb) returns the colour of a vertex (the layers are then not baked, which is most of the build time). It may return a fourth value: it goes to the vertex alpha as data, not coverage (the flying samples put the share of enclosed farmland there, and minus the share of woodland, and their material draws fields, hedges and crowns per pixel from it, so the edges stay crisp on a coarse far chunk).
  • material: scene => BABYLON.Material replaces the built-in shader with a standard or PBR material of the game's own. Its chunks get uv in world metres (a detail texture tiles the same everywhere), the geomorph is added by a material plugin (addTerrainMorph), the material is made opaque and the alpha written to the frame is 1, so the vertex alpha never lets the page show through. receiveShadows: 1024 lets chunks of that size and smaller take the scene's shadow maps.
  • water: 'inland' draws lakes and rivers and leaves the sea to a surface of the game's own (the OceanView of @ferret/levels, with waves and the depth of this landscape); setWaterReflection(cube) mirrors a sky probe in the water, setWaterColors sets shallow, deep and sky colours.

The build order is nearest first measured in chunk sizes, so the big far chunks that make the horizon come early. On a loading screen raise o.buildsPerUpdate and o.buildMs (64 and 250) and put them back after: a chunk costs 15–30 ms, so the default budget builds one a frame.

Rocks, plants and anything standing on the ground#

scatterCell places Species in a square cell, a pure function of (seed, cell): the same cell holds the same things whichever order cells are asked in. Density comes from the biome weights, the size follows a power law (many small, few large), slope, height, wetness, layer and clustering rules thin it out. ROCKS and PLANT_SPECIES ship with generators (makeRock and PLANTS: conifer, broadleaf, dead tree, shrub, tuft, reed, cactus), so no model files are needed; a species may name a library model instead. ScatterView draws them with thin instances, a few draw calls for thousands of things.

Ice and water#

makeIceberg builds a closed solid, above and below the water, tabular or domed. floatation finds the waterline where the displaced water weighs as much as the ice (917 against 1025 kg/m3), the centres of mass and buoyancy and the metacentric height; settle finds the orientation a berg rolls to. icebergField places bergs by a size law. floes make a sea-ice field with leads and pressure ridges; crevasses crack glacier ice across the flow.

TerrainView draws it with buildWaterMesh: a sheet per chunk with depth colour, fresnel reflection, sun glints and ripples that follow a river's flow and waterfalls where a river bed drops (a curtain from the lip to the foot with streaks running down) (water: false turns both off).

Relief.waterAt says where water lies: the sea, a lake from lake, a river inside its banks (a flat surface across the channel). riverProfile gives bed, surface, width and speed along a river; waterfalls finds the drops; flowSpeed gives the Manning speed at a point.

Mountain hazards#

avalancheHazard is high on 30 to 45 degree slopes with loose snow. slide runs a snow or debris slide down the ground (the Voellmy model: friction, turbulent drag, inertia through a bend) and runout reports how far it went. rockfall lets a boulder fall, bounce, roll and rest. All read the ground through Relief, so a hazard map, a slide and a falling rock agree with what is drawn.

The ground in the physics world#

SURFACES gives friction, restitution and rolling resistance by surface (ice 0.03, rock 0.8); registerSurfaces puts them in a physics material table. toTerrain cuts a @ferret/physics-terrain Terrain from a region, with the biome's soil over rock, so digging, sinking, slumping and flooding work. CollisionChunks keeps static mesh tiles round the bodies you track, built from the same relief the view draws (Havok has no height field shape, so tiles are meshes).

Checking a landscape#

Compare renders with photographs, side by side, from the same kind of place and lighting. Render on the RTX, check the renderer string. A hillshade from the top of the image with a low sun and cast shadows reads craters and dunes correctly; light from below turns hollows into domes.

Not yet there#

Splat and triplanar ground material, far-field backdrop, quality tiers, glacier flow and the ice material, the water surface views, weather and sound hooks, the near-ground detail, sandstorms and waves over ships are later stages of plans/PLAN-TERRAIN.md.

Editing by commands#

Landscape holds the spec, climate and biome zones and rebuilds the Ground on every change (version grows, onChange notifies a view). An operation that makes the spec invalid is rejected and the spec stays as it was. registerLandscapeCommands puts the same calls on world.commands for the inspector and agents: landscape.sample, spec, validate, op.list|add|set|patch|remove|move, zone.add|remove, climate, brush (raise, lower, smooth, flatten with a soft edge, written as sparse tiles into a paint operation) and biomes. A brush stroke does not redo erosion, so put paint after erode in the spec.

Footprints and tracks#

ground.press(x, z, radius, mass) presses the ground by what it is made of (ground.softnessAt): about 2 cm in dry sand under a boot, 8 cm or more in fresh snow, none on rock or ice; the sides rise a little, and time heals the print by surface (ground.memory.step(dt): sand slumps, snow fills, mud keeps its prints). ground.heightAt includes the prints, for the collision. GroundMemory (SOFTNESS, loadKPa) is the maths without an engine; PrintsView draws a 10 m patch round the camera, lifted by the memory and shaded darker where it is pressed.

Plants on a ground of your own#

A game whose ground is its own function (a beach with a tide that the sea, the crowd and the boats all read) can still have the module's plants: hand the function to it as an import op (a height grid sampled from it) and say with zones where a biome grows and where none does. examples/dunkirk/src/dunes.ts does this for the dunes behind a beach: marram grass in clumps, sea buckthorn and reeds in the coast zone behind the spring-tide line, nothing on the beach and in the sea (a salt-flat zone), drawn by ScatterView round the camera. Give the grid a margin past where anything may grow: outside the grid the ground is what was built before it, and a plant's height rule reads that.

Worlds without water#

Sea level defaults to 0 m, and every crater floor below it fills with water in the view. For the Moon, Mars or any dry world give the spec seaLevel: -1e6.