Architecture snapshot: December 2026. This article documents Play2Train's volumetric terrain generation, erosion, hydrology, meshing, and persistence stack (src/engine/runtime/terrain/TerrainVolumeData.h/.cpp, TerrainMaterialWeights.h, TerrainNoise.h, TerrainGenerator.h/.cpp, TerrainErosion.h/.cpp, TerrainHydrology.h/.cpp, TerrainSurfaceData.h, TerrainNormals.h, TerrainAO.h, TerrainLayers.h/.cpp, and TerrainFormat.md — 2,369 lines of C++23 and specification inside the reusable Play2Train SDK, paired with the 249-line game-side P2TTRN v4 serializer in src/game/systems/TerrainPersistence.h/.cpp and the native regression suites in unit-tests/Engine/Terrain/) inside Gattic's closed-source Play2Train SDK. Both Robot Universe and PloppyPals build on Play2Train.

Most 3D games cheat when they build hills and valleys. Under the hood, their ground is not a solid earth you can carve into — it is a flat rubber sheet stretched up and down over a grid of invisible pins. Each spot on the map gets one height number, and that is all the engine knows. The moment a player tries to dig a tunnel into a cliffside, sculpt a natural stone arch, or carve an overhanging cave, the rubber sheet runs out of tricks: a single sheet can only sit at one altitude at any (x, z) coordinate.

A second problem shows up even before anyone picks up a shovel. Procedural terrain generators usually stack bumpy fractal noise and drop thousands of simulated raindrops across the hills. Those raindrops carve convincing little gullies on steep slopes, then get trapped in random puddles a few meters later. Zoom out over the landscape and instead of streams flowing down valleys to the sea, you see disconnected pits and isolated scars that never join into real watersheds.

Play2Train solves both problems together with a terrain architecture built on three interlocking layers:

  1. An editable 3D scalar density field with independent material blends. Rather than a flat elevation sheet, terrain is stored as a 3D grid of UNORM8 density values (kIsoDensity = 128) paired with independent 3-byte normalized material weights (grass, sand, rock, and implicit snow). Meshing happens on demand in 64 × 64 × 64 chunks via Surface Nets, turning the density field into smooth, manifold-friendly triangles that support true caves, arches, and live brush editing.
  2. Layered procedural generation capped by a deterministic hydrology pass. Initial worlds are synthesized by stacking domain-warped ridged peaks, hydraulic droplet erosion, and thermal talus slumping — followed by a zero-RNG, order-stable hydrology pass (TerrainHydrology.cpp): Barnes priority-flood depression filling, D8 steepest-descent flow accumulation, logarithmic stream carving, alluvial valley sedimentation, and localized bank relaxation so disconnected erosion scars become continuous drainage networks.
  3. Run-length encoded P2TTRN v4 persistence without vertex dumps. Worlds never save baked triangle meshes or derived scattering maps to disk. Instead, TerrainPersistence writes a 76-byte binary header plus 8-byte run-length encoded (count, density, grass, sand, rock) runs over Y-fast columns — compressing a 129.5 MiB production volume down to roughly 6–8 MiB while rebuilding meshes, collision geometry, horizon ambient occlusion, and scatter deterministically on load.

Why a 3D density field beats a flat heightmap

For non-technical readers, compare a pin-art toy with a block of sculptor's clay. A traditional 2D heightfield works like a pin-art frame: you can push pins higher to make mountains or lower to make valleys, and you can drape a painted cloth over the tips, but you can never hollow out a cavern underneath a hill because every pin is solid all the way down. A volumetric density field is the block of clay. Every point in 3D space — below ground, at the surface, and up in the sky — holds a single "fullness" number from 0 (completely empty air) to 255 (solid rock). Wherever fullness crosses the halfway mark of 128, the engine wraps the visible surface of the world.

In Play2Train, that block of clay lives in Engine::TerrainVolumeData (src/engine/runtime/terrain/TerrainVolumeData.h/.cpp), exposed to the scene ECS via the thin TerrainVolume component (src/engine/components/TerrainVolume.h). Every 3D sample stores 4 bytes total:

  • 1 byte of scalar density (std::uint8_t, UNORM8): values < 128 are empty air; values >= 128 (kIsoDensity = 128) are solid terrain.
  • 3 bytes of independent material blends (Engine::TerrainMaterialWeights): grass, sand, and rock, each in [0, 255], constrained by the invariant grass + sand + rock <= 255. The fourth layer — snow — is never stored explicitly; it is the exact remainder 255 - grass - sand - rock (static_assert(sizeof(TerrainMaterialWeights) == 3)).

Separating material weights from density means material is not a function of altitude. You can dig into a grassy hillside and expose rock, paint a sandy path across a mountain ridge, or carve a tunnel through snow-capped stone without the engine suddenly re-coloring your edits back into default elevation stripes.

Diagram contrasting a traditional 2D heightfield against Play2Train's 3D scalar volume. Top-left shows a 2D rubber sheet y = h(x, z) unable to represent caves or overhangs. Top-right shows Play2Train's Y-fast 3D density columns (Index = (z * nx + x) * ny + y) with kIsoDensity = 128 supporting overhangs and a dug d < 128 tunnel. Bottom-left compares Play2Train's two-cell unsaturated quantization (127/dy giving d0 = 160, d1 = 33, reconstructed t = 0.2520 for true height 0.25) against a naive 255/dy gradient (d0 = 192, d1 = 0 saturated, shifting t to 0.3333). Bottom-right maps the 4-byte per-sample memory budget: 1-byte density plus 3-byte TerrainMaterialWeights (grass, sand, rock) with exact implicit remainder snow = 255 - g - s - r quantized via largest-remainder.
TerrainVolumeData stores 4 bytes per 3D sample in Y-fast columns, using two-cell 127/dy quantization to avoid heightfield terracing and largest-remainder 3-byte weights for four terrain layers.

Three subtle storage choices in TerrainVolumeData.cpp and TerrainMaterialWeights.h carry outsized engineering weight:

  1. Y-fast column memory order. Most 3D voxel engines lay out arrays with X or Z fastest. Play2Train puts Y fastest: Index(x, y, z) = (z * nx + x) * ny + y. As the comment in TerrainVolumeData.cpp notes, contiguous vertical columns make top-surface scans cache-local and turn every vertical column into two long constant runs (deep solid 255 below, open air 0 above) for P2TTRN v4 run-length encoding.
  2. Two-cell unsaturated quantization (127 / dy, never 255 / dy). When seeding a 3D volume from a floating-point heightfield (WriteHeightColumn), an intuitive formula might scale density by 255 / dy around the surface. Play2Train discovered that 255 / dy saturates one of the two bracketing grid samples to 0 or 255 whenever a height does not land cleanly on a half-voxel: for a true height of 0.25 (with y0 = 0, dy = 1), 255 / dy clamps the upper sample to 0 while setting the lower sample to 192, so linear interpolation reconstructs (128 - 192) / (0 - 192) = 0.3333 — introducing systematic stair-step terracing! Using 128.0f + (height - sampleY) * (127.0f / dy) keeps both bracketing samples unsaturated (160 and 33), reconstructing 32 / 127 = 0.2520 and capping vertical quantization error to dy / (2 × 127) = dy / 254 (under 4 millimeters on a 1-meter vertical step).
  3. Strict height-seeding bounds and largest-remainder material quantization. InitializeFromHeights and SetHeightSubRegion validate every height before mutating a single sample, accepting only finite heights in [y0, y0 + (ny - 2) * dy] (default y0 = -64.0f, dy = 1.0f, ny = 129, giving [-64, +63]) so there is always a solid floor sample and at least one air sample above the highest peak — never silently clipping a mountain flat against the volume ceiling. Meanwhile, TerrainMaterialWeights::FromFloats converts four floating-point material fractions (grass, sand, rock, implicit snow) to four uint8 counts summing to 255 using largest-remainder (Hamilton) apportionment, guaranteeing at most 1/255 quantization error per layer across all four channels.
cpp
// src/engine/runtime/terrain/TerrainVolumeData.cpp
void TerrainVolumeData::WriteHeightColumn(int x, int z, float height)
{
    for (int y = 0; y < m_ny; ++y) {
        const float sampleY = m_y0 + static_cast<float>(y) * m_dy;
        // Keep BOTH samples bracketing the height unsaturated. A 255/dy
        // gradient clipped one endpoint and moved a height of .25 to .333.
        // The two-cell band limits vertical error to dy/(2*127), rather than
        // introducing systematic terracing before meshing and placement.
        const float value = 128.0f + (height - sampleY) * (127.0f / m_dy);
        m_density[Index(x, y, z)] = static_cast<std::uint8_t>(
            std::lround(std::max(0.0f, std::min(255.0f, value))));
    }
}

From sculpted noise to eroded hills: ridges, droplets, and talus

Before the 3D density volume is even populated, Play2Train synthesizes the initial natural landscape on a deterministic 2D grid (TerrainGenerator::GenerateHeights). Think of the process like a physical terrain workshop with four sequential stations:

  1. Rough-carving the mountain ranges out of foam with warped ridges, broad rolling lowlands, and sunken basins (TerrainNoise.h, TerrainGenerator.cpp).
  2. Pouring 60,000 virtual raindrops over the foam to cut gullies and wash sediment downhill, followed by shaking the table so overly steep gravel piles slump to a natural angle of repose (TerrainErosion.cpp).
  3. Running a global watershed and river pass that connects every trapped puddle into continuous streams, flattens silty valley floors, and softens stream banks (TerrainHydrology.cpp).
  4. Painting geomorphology-aware biomes (grass, sand, rock, snow) onto the terrain and baking both heights and weights into the 3D volume (TerrainGenerator::GenerateWeights → TerrainVolumeData).
Four-stage diagram of Play2Train's procedural terrain pipeline with synchronized elevation cross-sections. Stage 1 (TerrainNoise.h and TerrainGenerator.cpp) combines SplitMix64 seed offsets, FbmEroded lowlands, domain-warped Ridged peaks gated by a macro mountainousness mask, and low-frequency basin carving across five biome profiles. Stage 2 (TerrainErosion.h/.cpp) runs 60,000 SplitMix64 hydraulic droplets and 3 double-buffered thermal talus iterations, leaving natural gullies alongside isolated local pits. Stage 3 (TerrainHydrology.h/.cpp) executes the deterministic zero-RNG hydrology pass: Barnes Priority-Flood pit filling on a routing copy, D8 flow accumulation, logarithmic stream incision with 2 box-blur passes clamped above seaLevel - 1.2m, alluvial valley sedimentation, and localized bank talus. Stage 4 (TerrainVolumeData and TerrainAO) assigns geomorphology-aware material blends, seeds 127/dy density columns, meshes 64^3 Surface Nets chunks, and rebuilds horizon AO and scatter from upward-facing triangles.
Play2Train separates terrain generation into four clean CPU stages with zero graphics-API dependencies, culminating in 64³ Surface Nets chunks.

Stage 1: Analytic derivative noise, domain-warped ridges, and five biomes on one generator

TerrainNoise.h is a 72-line header-only pure-CPU library with no GPU or engine dependencies. Every coordinate hashes deterministically via 32-bit integer wraparound (Hash2), interpolated with a C² quintic fade curve u(t) = 6t⁵ − 15t⁴ + 10t³ alongside its exact analytic derivatives du(t) = 30t⁴ − 60t³ + 30t² (ValueNoiseD).

Why compute exact derivatives during noise evaluation? Because Play2Train uses Inigo Quilez's gradient-damped noise in both of its fractal building blocks:

  • FbmEroded(x, z, octaves): accumulates the weighted gradient (dx, dz) across octaves (gain 0.5, lacunarity 2.02) and divides each octave's contribution by 1.0 + 0.7 · (dx² + dz²). Steep slopes automatically damp out high-frequency chatter while flat valley floors keep fine surface texture — mimicking hydraulic smoothing before a single raindrop runs.
  • Ridged(x, z, octaves): folds noise into sharp crests via r = (1 - |n|)², multiplies each octave by the previous octave prev so crisp rocky detail concentrates along existing ridge spines, and damps by 1.0 + 0.35 · (dx² + dz²) (lacunarity 2.07).

TerrainGenerator (TerrainGenerator.cpp) hashes its 64-bit seed through a SplitMix64 avalanche into stable coordinate offsets (m_seedOffX, m_seedOffZ) in [0, ~16,384), then evaluates HeightAt(wx, wz) by blending four fields:

  • A very low-frequency macro mountainousness mask (macroFreq = 0.004, smoothstepped over [0.35, 0.58]) so one world contains both broad rolling lowlands (baseAmp = 1.5, 5 octaves of FbmEroded) and tall alpine ranges without looking uniformly noisy.
  • Domain-warped ridged peaks: two independent ValueNoiseD lookups offset the ridge sampling coordinates by up to ±15 units (warpFreq = 0.01, warpAmp = 30.0) before sampling 5 octaves of Ridged (ridgeFreq = 0.012), sharpened by pow(ridge, 1.3) and scaled by ridgeAmp = 38.0 (needed because world terrains are roughly 50× wider than tall).
  • Low-frequency basin carving: subtracts carveAmp · (1 - carveRaw) · (1 + 0.6 · macro) (carveFreq = 0.015, carveAmp = 7.0) to pull lowland basins below seaLevel = 2.0f for natural ponds and deepen alpine valleys.
  • Five biomes on one deterministic generator (TerrainBiome: Hybrid = 0, Ocean = 1, Grassland = 2, Desert = 3, Mountain = 4): instead of maintaining five incompatible terrain algorithms, focused profiles simply bias the same shared fields (Ocean builds a submerged archipelago with island peaks above macroRaw ∈ [0.58, 0.78]; Grassland dampens mountains to 7% and basin carve to 12%; Mountain holds ridge strength at 0.65 + 0.35 · macro; Desert and dry zones in Hybrid layer wind-aligned warped (½ + ½ sin)² dunes with duneFreq = 0.055, duneAmp = 2.8, duneWarpAmp = 18.0, with Hybrid aridity damped out of mountain cores by 1 - 0.65 · mountains).

Stage 2: 60,000 hydraulic droplets and 3 thermal talus passes

Once the raw height grid exists, Engine::Erode (TerrainErosion.h/.cpp) runs two physical weathering passes in place using an explicit local SplitMix64 PRNG seeded with erosion.seed ^ params.seed (no global RNG state, never std::rand):

Pass Default parameters (ErosionParams) Exact physical rule
Hydraulic droplet erosion (HydraulicErode) numDroplets = 60,000, maxLifetime = 30, erosionRadius = 3, inertia = 0.05, sedimentCapacity = 4.0, minSedimentCapacity = 0.01, erodeSpeed = 0.3, depositSpeed = 0.3, evaporateSpeed = 0.01, gravity = 4.0 Each droplet samples bilinear height & gradient, blends downhill direction with inertia, computes capacity = max(-Δh · speed · water · 4.0, 0.01), deposits bilinearly when uphill (min(Δh, sediment)) or over capacity ((sediment - capacity) · 0.3), or erodes via a precomputed normalized cone brush of radius 3 (min((capacity - sediment) · 0.3, -Δh)). Updates speed = sqrt(max(0, speed² - Δh · 4.0)), evaporates 1% water per step, and deposits all remaining sediment on exit so carried sediment is not discarded.
Thermal talus erosion (ThermalErode) thermalIterations = 3, talusAngle = 0.6, thermalRate = 0.5 Double-buffered across all 4 cardinal neighbors (±x with dx, ±z with dz). Wherever hc - hn > 0.6 · cellSpacing, shifts 0.5 · 0.5 · excess from the higher cell to the lower cell, slumping unstable vertical spikes into realistic scree slopes.

Droplet and thermal erosion transform mathematical noise into weathered slopes — but they leave a structural flaw. Because each droplet lives for at most 30 steps and stops whenever it hits a flat spot or local depression, eroded mountains end up dotted with hundreds of tiny disconnected hollows. Rainwater never travels from the highest ridge all the way to the coast. That is the exact problem Stage 3 exists to solve.

The deterministic hydrology pass: turning erosion scars into connected drainage networks

For non-technical readers, imagine standing over a sandbox sculpted into hills and pouring a watering can over the top. If the sand has dozens of small footprints and thumb-sized pits, water pools inside each little crater and stops. To discover where real rivers ought to flow, hydrologists use a clever two-step trick: first, they make a temporary photocopy of the map and mentally fill every pothole with water up to its rim — sloping the water surface downward by a hair's breadth (1 millimeter) toward the map's outer edge so every drop knows which way to escape. Next, they trace where every single square of rain flows downhill on that filled map. Where hundreds of squares all funnel into the same crease, a stream emerges; where the stream reaches flat valley ground, silt settles into a wide alluvial meadow; and right along the freshly cut stream edges, loose dirt slumps into gentle riverbanks — leaving distant mountain cliffs untouched.

Engine::ApplyHydrology (src/engine/runtime/terrain/TerrainHydrology.h/.cpp) implements that exact five-step pipeline in 200 lines of pure, order-stable C++23 with zero random number generation. Given the same input heightfield, it produces bit-identical output on every run (verified by FNV-1a float buffer hashes in unit-tests/Engine/Terrain/terrain-hydrology-test.cpp).

Two-tier technical diagram and quantitative graph of Play2Train's deterministic hydrology pass. Top-left illustrates Step 1 (Barnes Priority-Flood FillDepressions on a routing copy hr with kEps = 1e-3): a min-heap seeded from border cells raises trapped droplet pits just enough to enforce a strictly downhill outlet without modifying the real heightfield h yet. Top-right illustrates Step 2 (ComputeFlowAccumulation): cells rain 1 unit each, sort descending by hr with index tie-breaking, and drain in one linear sweep to their steepest-descent 8-neighbor weighted by cardinal or diagonal world spacing. Bottom plots the exact mathematical incision curve carve(flow) = min(2.0 m, 0.28 * ln(1 + max(0, flow - 250))) on a log10 flow axis from 100 to 5000 cells, marking sedimentFlowMin = 150, flowThreshold = 250, 500 cells -> 1.55 m, and maxCarve = 2.0 m saturation at 1514 cells, flanked by sidebar cards for the 2-pass 3x3 carve blur and seaLevel - 1.2m floor clamp, 2-pass valley sedimentation (slope <= 0.10, strength 0.45), and 3-iteration localized bank talus (carve > 0.01, bankTalus 0.50).
FillDepressions bridges isolated erosion pits on a routing copy, D8 accumulates upstream catchment area, and logarithmic carving plus sedimentation and masked bank talus turn gullies into connected valleys.

Let's walk through all five deterministic stages inside TerrainHydrology.cpp:

  1. Priority-Flood depression filling (FillDepressions, Barnes et al.) on a routing copy. The pass copies heights into a temporary routing surface hr, pushes every border cell into a min-heap keyed by (filledHeight, cellIndex) (guaranteeing deterministic tie-breaking by index), and floods inward across all 8 neighbors. Any interior cell lower than hr[i] + kEps is lifted to std::max(hr[ni], hr[i] + kEps) with kEps = 1e-3f. That tiny millimeter tilt guarantees every filled depression has a strictly downhill neighbor all the way to the map border — while leaving the original terrain h completely untouched so real basins and lake beds are not erased.
  2. D8 steepest-descent flow accumulation (ComputeFlowAccumulation). Every cell starts with flow[i] = 1.0f unit of rain. All nx × nz indices are sorted descending by hr[a] > hr[b] (tie-breaking deterministically on a < b). A single linear sweep processes every upstream cell before its downstream recipient, selecting the steepest-descent neighbor among the 8 directions (slope = (hr[i] - hr[n]) / dist[k], where diagonal neighbors divide by sqrt(dx² + dz²)) and adding flow[i] directly into flow[best]. Border cells drain off-map.
  3. Logarithmic stream carving + valley cross-section blur + waterline floor clamp. A cell only begins carving once its accumulated upstream catchment exceeds flowThreshold = 250.0f (~0.1 hectares at 2 m cell spacing). Above that threshold, raw incision depth grows logarithmically — because real rivers deepen slowly downstream rather than linearly into bottomless canyons:
    • carve[i] = min(maxCarve, carveStrength * log1p(flow[i] - flowThreshold)) with defaults carveStrength = 0.28f and maxCarve = 2.0f.
    • At flow = 260, raw carve is 0.67 m; at flow = 500, 1.55 m; at flow = 1,000, 1.85 m; and at flow = 1,514.04 cells, incision cleanly saturates at the 2.0 m cap.
    • Next, Blur3x3 runs carveBlurPasses = 2 passes of a 3×3 box blur over the carve field, widening a harsh 1-cell trench into a smooth V/U valley cross-section.
    • Finally, before subtracting carve[i] from the real terrain h[i], TerrainGenerator::GenerateHeights clamps hp.carveFloorY = std::max(hp.carveFloorY, m_p.seaLevel - 1.2f). Streams visibly incise down into the shoreline so they meet the water naturally, without ever trenching deep channels across submerged lake beds.
  4. Valley sedimentation (alluvial flats). Over sedimentPasses = 2 double-buffered (order-independent) iterations, any interior cell that carries substantial water (flow[i] >= 150.0f) and sits on already-gentle ground (|∇h| <= 0.10, checked via squared central differences (hx² + hz²) <= 0.01) relaxes 45% (sedimentStrength = 0.45f) toward the mean of its 4 cardinal neighbors. Bumpy stream bottoms smooth out into flat alluvial valley floors.
  5. Localized bank relaxation (talus near streams only). Carving a stream creates steep fresh cut-banks. Rather than running global thermal erosion again (which would soften distant alpine cliffs), ApplyHydrology runs bankIterations = 3 double-buffered thermal-talus passes (bankTalus = 0.50f, bankRate = 0.30f) gated strictly by if (carve[i] <= 0.01f) continue;. Only freshly carved stream banks slump to a stable angle; every cliff and peak outside the drainage corridor stays crisp.
cpp
// src/engine/runtime/terrain/TerrainHydrology.cpp
// ---- Stream carving ----
std::vector<float> carve(N, 0.0f);
for (size_t i = 0; i < N; ++i) {
    const float excess = flow[i] - p.flowThreshold;
    if (excess > 0.0f)
        carve[i] = std::min(p.maxCarve, p.carveStrength * std::log1p(excess));
}
Blur3x3(carve, nx, nz, p.carveBlurPasses);
for (size_t i = 0; i < N; ++i) {
    if (carve[i] <= 0.0f) continue;
    const float floorRoom = h[i] - p.carveFloorY;
    if (floorRoom <= 0.0f) continue;              // already at/below the floor
    h[i] -= std::min(carve[i], floorRoom);
}

Geomorphology-aware material weights (TerrainGenerator::GenerateWeights)

Before seeding the 3D volume, GenerateWeights computes the initial 4-layer material blend (grass, sand, rock, implicit snow) for every column — and it deliberately avoids ugly horizontal contour stripes. Alongside central-difference slope (1 - ny) and altitude above seaLevel, it evaluates two real-world geomorphological cues:

  • Topographic position against an ~8 m ring (kx = max(1, round(8 / dx))): (h[i] - ringMean) / ringDistance is positive on exposed crests and plateau lips, and negative inside gullies and hollows. Scaled by snowBand = max(snowHi - snowLo, 1e-3) (default 3.0 m), effective snowAltitude is boosted in sheltered hollows (-1.2 × snowBand × position when position < 0) and scoured off exposed ridges (-0.5 × snowBand × position when position > 0), while sharp highland crests add bare rock (+(1 - rock) · 0.7 · highland · SmoothStep(0.4, 0.8, position)).
  • Poleward aspect (dhdz * ny): slopes facing the fixed shaded poleward direction (-Z) hold snow lower down the mountain (+0.6 × snowBand × poleward), while FbmEroded perturbations break up the snowline, rock-slope threshold, and shoreline sand band.

Every biome then biases the exact same 4-way partition (grass + sand + rock + snow == 1), which TerrainVolumeData::SetMaterialGrid quantizes via largest-remainder into the 3-byte TerrainMaterialWeights column.

Meshing the volume with Surface Nets and keeping materials intact

Now that we have a 3D grid of (density, grass, sand, rock) samples — possibly carved with tunnels and overhangs — how does Play2Train turn those numbers into triangles the GPU and physics engine can use?

For non-technical readers, imagine a 3D jungle gym of tiny cubes covering the landscape. Some cubes are completely buried underground (all 8 corners solid); some float in empty air (all 8 corners empty); and only a thin skin of boundary cubes straddles the solid-to-air transition. The classic algorithm (Marching Cubes) consults a 256-entry lookup table to stamp miniature triangle templates inside each boundary cube — often producing sliver triangles and tricky lookup seams. Surface Nets takes the dual approach: it places just one vertex inside each boundary cube, parked at the average position of all edges where solid meets air, and then weaves a clean quad (two triangles) connecting the four cubes around every grid edge that crosses from rock into air. The result looks like an elastic fishing net pulled smoothly over the clay.

Three-part diagram of Play2Train's Surface Nets mesher in TerrainVolumeData::BuildChunkMesh. Top-left shows a single active voxel cell: corners >= 128 are solid, corners < 128 are empty, edge crossings interpolate at t = (128 - dA)/(dB - dA), the single dual vertex sits at the mean of all edge crossings, and each crossing inherits its solid endpoint's full 3-byte material blend averaged over all crossings to emit an 11-float vertex (pos3, weights3, uv2, normal3). Top-right shows four adjacent cells around a crossed interior +X/+Y/+Z lattice edge emitting a dual quad split into 2 triangles across 64x64x64 chunks (21-bit packed EncodeChunkKey and -2 cell dirty halo). Bottom compares naive shading-gradient quad orientation (which flipped 16 to 45 shared edges per seed on sharp ridges) against Play2Train's topological edge-density-sign orientation (0 inconsistent edges and verified signed volume on closed islands and cavities).
Surface Nets places one dual vertex per active cell, averages solid-endpoint material blends across crossings, and orients every quad strictly from solid to empty along its crossed lattice edge.

Inside TerrainVolumeData::BuildChunkMesh(std::uint64_t key) (TerrainVolumeData.cpp), the volume is partitioned into 64 × 64 × 64 cell chunks (kChunkSizeXZ = 64, kChunkSizeY = 64), addressed by 21-bit packed 64-bit keys (EncodeChunkKey / EncodeCell, supporting grids up to 2²¹ = 2,097,152 per axis). Four concrete details make the mesher rock-solid:

  • One dual vertex per active cell (vertexForCell). For every cell with at least one solid (>= 128) and one empty (< 128) corner, the mesher walks all 12 cube edges (kEdges). On each sign-changing edge (a, b), it linearly interpolates the crossing point at t = (128 - dA) / (dB - dA) and averages all crossings to place the dual vertex. The vertex shading normal comes from the 8-corner finite-difference density gradient (-Δx/dx, -Δy/dy, -Δz/dz), normalized with an upward fallback if degenerate. Each emitted vertex packs 11 floats: pos(3), weights RGB(3), uv(2), normal(3).
  • Material blend preservation instead of winner-take-all voting. Notice a subtle trap in volumetric terrain: if a cell simply picks the dominant material among its 8 corners, smooth procedural grass-to-rock transitions collapse into blocky voxel staircases, and painted brushes jitter. Instead, Play2Train lets every crossed edge inherit the full 3-byte material blend of its solid endpoint (kCorners[solidA ? a : b]) and averages those blends across all crossings (materialSum / (255.0f * intersections)). Smooth transitions and painted boundaries survive meshing intact.
  • Topological edge-sign quad orientation — never shading normals. For each interior cell (x, y, z), the mesher checks the three lattice edges bordering its far corner (+X, +Y, +Z) and emits a quad joining the four surrounding cells whenever an edge crosses kIsoDensity. Crucially, winding order (swap(q[1], q[3])) is decided strictly by whether the lower endpoint of that crossed edge is solid or empty — never by checking the dot product against the averaged shading normal. Why? As unit-tests/Engine/Terrain/terrain-volume-mesh-test.cpp records from real regression testing, orienting quads by averaged shading normals reversed 16–45 shared edges per seed along sharp ridges where the 8-corner gradient leaned across the crest! With edge-density-sign winding, the test suite verifies zero inconsistent shared edges across 20 rough random seeds, multi-chunk generated worlds spanning chunk seams, and exact positive/negative signed volumes on closed solid islands and hollow cavities.
  • Two-cell dirty halo across chunk seams (MarkDirtySamples). Because a single modified sample can alter dual vertices in cells up to 1 behind it and shared quads owned by cells up to 2 behind it, editing any sample bounding box [min, max] expands the dirty cell range to [min - 2, max] before marking affected 64³ chunks dirty (ConsumeDirtyChunks() returns sorted keys deterministically).

Volumetric brushes, exact reverse-replay undo, and upward-triangle surface indexing

Because the underlying truth is the 3D density + material field, editing tools and runtime queries operate cleanly on the volume without brittle mesh surgery:

Diagram of Play2Train's volumetric editing brushes, undo/redo log, and derived surface query indices. Top-left plots the exact mathematical falloff curves for DigEllipsoid: 0 smooth (1-d^2)^2, 1 linear (1-d), 2 hard constant 1, and 3 exponential exp(-4d^2). Top-right summarizes PlaceEllipsoid (complete 8-corner solid cells with sub-cell fallback), PaintEllipsoid (solid-only material writes), and ApplyChanges reverse-replay undo walking rbegin() to rend() so shared cell corners restore exact pre-edit blends. Bottom-left shows TerrainSurfaceData indexing only upward-facing rendered triangles (face.y > 1e-10) so downward SampleTop rays and capsule HeightUpperBound queries never snap onto cave ceilings. Bottom-right details RaycastLocal's AABB slab clip, axis-adaptive quarter-cell march (~25x fewer density evaluations on vertical rays), and 16-step binary bisection.
Three ellipsoidal brushes record reversible SampleChange logs; TerrainSurfaceData and RaycastLocal provide exact volumetric queries without mistaking cave ceilings for ground floors.
Operation Exact implementation (TerrainVolumeData.cpp / TerrainSurfaceData.h) Engineering invariant
DigEllipsoid Subtracts max(1, round(255 · amount01 · falloff(d²))) from density across 4 falloff kernels (0: (1−d²)², 1: 1−d, 2: hard 1, 3: exp(−4d²)), leaving underlying materials intact Radii clamp up to at least (dx, dy, dz) so even the smallest UI brush always reaches a sample
PlaceEllipsoid Marks every 8-corner cell whose center lies inside the ellipsoid to density = 255 and TerrainMaterialWeights::Layer(material) Adds complete unit cells (not fractional height increments); sub-cell brushes fall back to placing their containing cell
PaintEllipsoid Writes Layer(material) only to solid samples (density >= 128) inside the ellipsoid Never changes terrain geometry or contaminates air samples
ApplyChanges (Undo/Redo) Validates every SampleChange index and material sum before mutating; Redo walks forward, Undo walks rbegin() → rend() PlaceEllipsoid writes shared cell corners multiple times; reverse replay guarantees the very first pre-edit density and blend are restored
RaycastLocal Clips ray to volume AABB, marches at quarter-cell step along axes the ray actually crosses (step = max(1e-4, cellCrossingT · 0.25)), then runs 16 iterations of binary bisection on trilinear >= 128 sign flip Adaptive stepping avoids ~25× redundant evaluations on vertical rays over wide terrain; 16-step bisection resolves hits to 2⁻¹⁶ of a step inside caves and overhangs
TerrainSurfaceData Bins all actual rendered triangles with upward face normal (face.y > 1e-10f) into an (nx-1) × (nz-1) XZ grid; provides SampleTop(x, z) (exact barycentric highest upward triangle + weights) and HeightUpperBound(x, z, radius) Density-column scanning bridges dug holes and misses Surface Nets averaging; filtering face.y > 1e-10f ensures a cave ceiling never becomes a placement floor for grass, trees, or spawned characters

On top of TerrainSurfaceData, TerrainAO.h bakes world-space horizon-based ambient occlusion (ComputeHeightfieldAO): from each grid cell, it marches outward in 8 compass directions × 16 steps using true world-space (dx, dz) spacing, records the steepest sky-blocking horizon angle atan(maxSlope) · (2 / π), and darkens crevices, gullies, and cliff bases while leaving open ridges bright. Meanwhile, TerrainLayers.h defines the engine's material layer textures (grass.png, sand.png, stone.png, snow.png, plus forest, grasstall, ocean, oceandeep, path) paired with per-texture metric relief depths (0.020 m for grass blades, 0.012 m for sand ripples, 0.150 m for stone joints, 0.050 m for wind-packed snow).

Storing worlds without vertex dumps: the P2TTRN v4 binary format

When a player saves an edited terrain — complete with carved tunnels, painted roads, and hydrological valleys — what should actually go to disk?

For non-technical readers, imagine mailing a Lego castle to a friend. You could ship the giant pre-assembled castle in a fragile crate (a vertex dump: tens of megabytes of raw triangles, normals, collision trees, and baked shadows that break the moment you want to edit a brick). Or you could mail a compact instruction sheet: "65 layers of solid rock, 2 transition bricks, 62 layers of empty sky." That is run-length encoding (RLE) over a vertical column. Because almost every vertical column in a terrain volume consists of solid earth below and open air above, 129 samples collapse into 3 or 4 tiny 8-byte notes.

Play2Train's P2TTRN v4 specification (TerrainFormat.md) and serializer (src/game/systems/TerrainPersistence.h/.cpp) store only the scalar density field, normalized material blends, grid geometry, and four lightweight appearance settings — never meshes, never collision BVHs, never AO textures, and never scatter instances.

Byte-exact specification diagram of the P2TTRN v4 binary container. Top dark band maps all 76 packed little-endian header bytes with zero padding: offset 0 Magic P2TTRN\0\0 (8B), offset 8 Version uint32 = 4 (4B), offset 12 dimensions nx/ny/nz (12B), offset 24 spacing dx/dy/dz (12B), offset 36 origin x0/y0/z0 (12B), offset 48 biome int32 (4B), offset 52 decorated uint32 0/1 (4B), offset 56 scatter seed uint64 (8B), offset 64 seaLevel float32 (4B), offset 68 snowHi float32 (4B), and offset 72 runCount uint32 (4B). Middle band shows a 129-sample Y-fast vertical column (516 B raw) collapsing into four 8-byte Run structs (32 B: count u32, density u8, grass/sand/rock u8), scaling a 513x129x513 volume (33.95M samples, 129.50 MiB raw) down to roughly 6.0 to 8.0 MiB (16x to 21.5x compression) with zero precision loss. Bottom cards contrast the fail-closed ReadCurrent validation checks (v4 only, 64M sample zip-bomb cap, finite floats, valid material sums, exact payload size with zero trailing bytes, atomic no-mutation on error) against the derived resources rebuilt on load from rendered triangles.
P2TTRN v4 packs a 76-byte header and 8-byte RLE runs over Y-fast columns, achieving 16×–21.5× lossless compression of the quantized volume while validating every invariant fail-closed.

Exact 76-byte header and 8-byte run stream (TerrainFormat.md)

Every .terrain.p2t sidecar is raw little-endian binary (IEEE-754 float32) with zero struct padding:

Offset Field Type Notes
0 Magic P2TTRN\0\0 8 bytes Exact match required
8 Schema version uint32 Must equal 4; versions 1–3 rejected outright without migration
12 Sample dimensions nx, ny, nz 3 × uint32 Each in [2, 2²¹]; product <= 64 × 1024 × 1024 (67,108,864 samples)
24 Local sample spacing dx, dy, dz 3 × float32 Finite and strictly > 0
36 Local grid origin x0, y0, z0 3 × float32 Finite
48 Terrain/biome type int32 0 Hybrid, 1 Ocean, 2 Grassland, 3 Desert, 4 Mountain
52 Procedural presentation enabled uint32 Strictly 0 or 1 (decorated > 1 is rejected)
56 Scatter seed uint64 Rebuilds deterministic foliage/rock placement on load
64 Sea level (world Y) float32 Finite
68 Snow threshold (snowHi, above sea level) float32 Finite
72 Run count (runCount) uint32 Must satisfy 1 <= runCount <= nx * ny * nz

Immediately following byte 75 come runCount packed 8-byte Run records (static_assert(sizeof(Run) == 8)):

cpp
// src/game/systems/TerrainPersistence.cpp
struct Run {
    std::uint32_t count = 0;               // repeated consecutive samples
    std::uint8_t density = 0;              // UNORM8 scalar density (iso = 128)
    Engine::TerrainMaterialWeights material; // 3 bytes: grass, sand, rock (snow implicit)
};
static_assert(sizeof(Run) == 8);

Run the numbers on a full 513 × 129 × 513 production terrain (33,948,801 samples):

  • Uncompressed 4-byte volume: 33,948,801 × 4 = 129.50 MiB.
  • Y-fast RLE stream (P2TTRN v4): each of the 263,169 vertical columns runs solid 255 from bedrock up to the surface, passes through 1–2 unsaturated 127/dy transition samples, and runs 0 to the top of the volume — 3 to 4 runs per column (76 + 263,169 × {3,4} × 8 bytes), landing at 6.02–8.03 MiB, a 16.1×–21.5× size reduction with zero loss of the quantized density field or material blends (and often even smaller when consecutive columns share identical top/bottom states).

Fail-closed load checks and deterministic rebuilds

ReadCurrent in TerrainPersistence.cpp treats every file on disk as untrusted input:

  • No legacy shims. Anything other than exact P2TTRN\0\0 magic and version == 4 fails immediately with a descriptive error string.
  • Zip-bomb protection. kMaximumSamples = 64 × 1024 × 1024 (67,108,864 samples, capping raw allocation at 256 MiB) gives comfortable headroom above 513 × 129 × 513 while stopping a tiny forged RLE file from triggering multi-gigabyte allocations.
  • Exact payload verification. Before allocating or decoding a single run, the loader seeks to EOF and verifies payloadBytes == runCount * 8 — rejecting both truncated files and files with trailing garbage bytes.
  • Per-run validation and atomic commit. Every run must satisfy count > 0, material.IsValid() (grass + sand + rock <= 255), and count <= sampleCount - decoded; total decoded samples must equal nx * ny * nz exactly. Everything parses into a local TerrainData parsed and only moves into the caller's data on the final line — so a failed read never leaves half-loaded terrain in memory.
  • Derived presentation rebuilt from rendered triangles. On successful load, the engine rebuilds the 64³ Surface Nets render chunks and collision meshes, builds TerrainSurfaceData from the upward-facing triangles, and regenerates horizon AO, terrain/water height textures, and deterministic scatter from those triangles. If the header's decorated flag is 0, any stale presentation resources left over from a previously loaded world are explicitly cleared.

Honest boundaries and where the system stops

Play2Train's terrain pipeline makes clear, deliberate trade-offs rather than trying to be every kind of voxel engine at once:

  • Strict height-seeding range. InitializeFromHeights and SetHeightSubRegion refuse any height outside [y0, y0 + (ny - 2) * dy] (default [-64, +63] in local Y) rather than clipping peaks flat. Worlds that need taller seeded relief must increase ny or dy explicitly before seeding (arbitrary caves and overhangs inside [0, ny - 1] remain fully supported via Import and brushes).
  • Hydrology runs once on the pre-volume heightfield. Domain-warped generation, hydraulic/thermal erosion, and D8 hydrology all operate on the 2D height grid before seeding the 3D density volume. If a player later digs a cavern or trenches through a ridge with DigEllipsoid, the terrain updates its 64³ Surface Nets chunks and collision live — it does not re-run watershed hydrology or simulate dynamic underground river physics.
  • Single-layer painting vs. four-way procedural blends. Procedural generation writes smooth 4-channel largest-remainder blends (TerrainMaterialWeights::FromFloats), and Surface Nets, undo/redo, and P2TTRN v4 preserve arbitrary 4-way blends faithfully. The interactive PaintEllipsoid and PlaceEllipsoid brushes currently stamp a single pure layer (Layer(material) = 255 on one channel) onto touched samples rather than soft-blending partial paint opacity.
  • Bounded single-volume storage, not infinite streaming. P2TTRN v4 stores one bounded terrain volume per .terrain.p2t sidecar (capped at 64 × 1024 × 1024 samples) and rejects versions 1–3 without migration code. It is designed for rich, editable handcrafted/procedural world maps rather than infinite Minecraft-style chunk streaming.
  • Smooth Surface Nets vs. sharp-corner Dual Contouring. Surface Nets averages edge crossings without solving Quadratic Error Functions (QEF) over Hermite normals. That keeps chunk meshing simple, fast, and organically smooth for hills, riverbeds, and caves — at the trade-off that razor-sharp 90° architectural corners round off slightly, and saddle edges can join four faces (or three at an open grid rim), explicitly checked as balanced edge pairs in terrain-volume-mesh-test.cpp.
  • Clean SDK vs. game boundary. Pure-CPU noise, generation, erosion, hydrology, volume data, Surface Nets meshing, surface indexing, normals, and horizon AO live in the reusable Play2Train SDK (src/engine/runtime/terrain/), whereas .terrain.p2t sidecar persistence (TerrainPersistence.{h,cpp}), editor undo stacks, and chunk entity orchestration live on the game side (HavenCity).

Sources and further reading