Level Discoverystart here Intermediatethe architecture Expertin depth
Expert Β· Batch 4 Β· Volcano
Chapter 4 Β· expert level

Destructible terrain & fast maths

The deep end: generating a heightfield from a sum of sines, carving craters as geometric subtraction, building caverns from a one-line solidity rule, and the continuous turbo wind β€” all with cheap, deterministic maths.

1Heightfield generation: a sum of sines

The surface is one height per column, built by adding three sine waves of decreasing amplitude and increasing frequency β€” large hills, then bumps, then fine detail. A seeded RNG picks the amplitudes, frequencies and phases.

src/sim/terrain.js β€” generateHeights
const waves = [
  { amp: r.int(40, 90) * roughness, freq: r.float(1.2, 2.4), phase: r.float(0, TWO_PI) },
  { amp: r.int(20, 50) * roughness, freq: r.float(3.0, 5.5), phase: r.float(0, TWO_PI) },
  { amp: r.int(8, 22)  * roughness, freq: r.float(6.0, 9.0), phase: r.float(0, TWO_PI) },
];

Two refinements make it playable: the ends are forced to flat tower platforms, and an edgeBlend factor ramps the relief in from those platforms so hills never start with a cliff at the towers.

src/sim/terrain.js β€” platforms & edge blend
if (x <= platformWidth || x >= width - platformWidth) { heights[x] = platformY; continue; }
// flat ground under each tower
const edgeBlend = Math.min(1, Math.min(t, 1 - t) * 6);
heights[x] = platformY + (y - platformY) * edgeBlend;
For the curious. The whole authoritative simulation is square-root-free: trajectories in additive steps, tower hits via axis-aligned boxes, craters via squared distance. The one surviving Math.sqrt serves feel (the proximity whizz), not logic β€” the full story is in the maths annex.

2Caverns & overhangs from one rule

Solidity is a single predicate: below the surface and in no crater. Because a crater can sit fully under a bump, the matter above stays solid β€” so caverns and overhangs emerge for free, no special case.

src/sim/terrain.js β€” pointSolid
export function pointSolid(heights, craters, x, y) {
  if (x < 0 || x >= heights.length) return false;
  if (y < heightAt(heights, x)) return false;   // above ground = air
  return !inCrater(craters, x, y);             // solid, minus craters
}
empty (crater) solid ↑ overhang that β€œfloats”
A crater under the ridge leaves an overhang above it: the same simple test produces a rich topology.

The shell collision uses exactly this: a projectile dies and carves a crater the instant it reaches a solid point β€” and the same rule lets a later shell fly through the hollow it left behind.

3Craters as geometric subtraction

A crater is not painted into a bitmap. It's a circle subtracted from solid space, stored as { x, y, r }. β€œIs this point in a crater?” is the squared-distance test β€” monotonic, so no square root is needed.

src/sim/terrain.js β€” inCrater (squared distance)
const dx = x - c.x, dy = y - c.y;
if (dx * dx + dy * dy <= c.r * c.r) return true;

Because the square root is monotonic, comparing dxΒ² + dyΒ² with rΒ² gives exactly the same verdict as comparing the distance with r, using only multiplications. It's Pythagoras, stripped of its root.

Emergent geometry. No mesh, no boolean polygon ops. A height array plus a list of circles, queried by one boolean function, is enough to model Worms-style caves.

4Determinism: the seed is the terrain

Generation is a pure function of the seed and the biome's roughness. The server rolls the seed, builds the heights, and ships only the seed β€” every client rebuilds the identical surface, so collisions resolved on the server land exactly where the TV drew the ground.

src/sim/Simulation.js β€” newTerrain
this.seed = this.randInt(1, 2**31 - 1);
this.heights = generateHeights(this.seed, this.roughness);
// fresh battlefield; only the seed crosses the wire

And the craters? They follow the same discipline: born from deterministic events (impacts resolved server-side) and travelling in the snapshot as a list. Same seed + same crater list β‡’ same terrain, bit for bit, everywhere.

Same number, same world. The RNG (mulberry32) is seedable and deterministic. Banishing Math.random() from shared generation is what guarantees the heightfield can be reconstructed instead of transmitted.

5Turbo continuous wind: smoothstep + gust

Turbo wind never snaps. It eases between random keypoints every 10 seconds with a smoothstep polynomial, and a two-sine gust wave (scaled by the match's rolled-once gustiness) rides on top so the breeze breathes instead of gliding mechanically.

src/sim/Simulation.js β€” updateTurboWind
this.windClock += dt;
if (this.windClock >= WIND_KEY_SECONDS) {
  this.windClock -= WIND_KEY_SECONDS;       // carry the overshoot, no snap
  this.windFrom = this.windTo;
  this.windTo = this.windKeypoint();        // fresh signed keypoint
}
const t = this.windClock / WIND_KEY_SECONDS;
const s = t * t * (3 - 2 * t);             // smoothstep
const base = this.windFrom + (this.windTo - this.windFrom) * s;

this.gustPhase += dt;
const gustAmp = this.gustiness * MAX_WIND * 0.22;
const gust = gustAmp * (Math.sin(this.gustPhase * 1.7) * 0.6
  + Math.sin(this.gustPhase * 0.9 + 1.3) * 0.4);
this.wind = Math.max(-MAX_WIND, Math.min(MAX_WIND, base + gust));

Keypoints are kept under 80% of the maximum so the gust has headroom before hitting the clamp β€” and the whole thing is just multiplications, additions and two sines: cheap enough to run every tick.

Remember. Batch 4 is fast, deterministic maths end to end: terrain as a sum of sines, craters as squared-distance subtraction, caves from one boolean, the seed as the wire format, and wind eased by a polynomial. For the deeper why, see the maths annex.

β˜…End of the expert path

You've gone through Tower Duel all the way to the metal:

a deterministic loop, asset-free rendering, an authoritative protocol, and a destructible terrain held together by a handful of well-chosen formulas. Everywhere the same discipline: separate what changes from what computes, and prefer reproducible simplicity.

Open the maths annex β†’

← Chapter 3 Β· Network protocol Chapter 5 β†’