Weather
@ferret/weather is a module of its own. A WeatherService holds one state (a dozen numbers) and moves it on the world's clock; every model reads that state, and every model is a pure function of the state and the time, so all peers of a network game see the same lightning, the same freak wave, the same tornado in the same place.
const weather = world.addService(new WeatherService({ state: 'fair', seed: 7, shore: 'rock', sea: true }));
weather.blendTo('sea-storm', 120); // two minutes from fair weather to a storm
weather.grove.add(x, z, 'oak', 1.1); // trees the wind works on
const trees = new TreesView(scene, weather); // the picture of them (see "Near the camera")
The state#
wind (m/s at 10 m), windDir (degrees, 0 = +x, 90 = +z), gustiness, cloudCover, convection, humidity, temperature, freezingLevel, precipitation (mm/h), thunder, dustiness, looseSnow, soilWetness. Presets: clear fair overcast fog drizzle rain downpour thunderstorm sea-gale sea-storm hurricane snow blizzard hail sandstorm haboob simoom tornado. set changes at once, blendTo over seconds (directions go the short way round). The service writes the wind into the flow field (weather.wind) and every whirl as a vortex, so smoke, flags, sails, clouds and the water read the same wind. Soil gets wet in rain and dries; snow lies and melts.
Commands: weather.state, weather.presets, weather.set, weather.blend, weather.sample, weather.sky, weather.sea, weather.surf, weather.tornado, weather.haboob, weather.report. The option ground(x, z) is what the ground gives the weather at a place (dustiness, looseSnow, soilWetness; the terrain's weatherAt fits): sample uses it, so a sandstorm rises over sand and not over meadow, and snow blows only where it lies. sample([x, y, z]) is what a character meets at a place: the wind vector (with gusts and whirls), what falls, the visibility and what limits it (fog, rain, snow, dust, blizzard, spray), the sea, the sand.
Wind#
The profile with height is the log law; the direction veers with height; the gusts are patches of 30–200 m carried by the wind at three quarters of its speed (Taylor's frozen turbulence), so a gust that bends the grass at one place reaches the trees downwind a moment later. gustFactor, windVector.
Sky: clouds and what falls#
cloudDeck(state) makes the layers by genus (cumulus, stratocumulus, stratus, nimbostratus, altostratus, altocumulus, cirrus, cirrostratus, cirrocumulus, cumulonimbus with an anvil); cloudCells places the cells of a layer, each born, grown and dead on the clock, carried by the wind aloft (stronger and veered with height); cloudFieldFor(state) feeds the @ferret/clouds package. Precipitation: drizzle, rain, shower, sleet, snow, graupel or hail from the temperature profile and the convection; drop sizes follow Marshall-Palmer, fall speed Atlas, hail its terminal velocity; every kind has size, speed, number, visibility, sound and the slant the wind gives it.
Thunderstorm. flashes is a schedule by hash slots, the same for any way of cutting the time; ground and cloud flashes with 1–6 strokes. thunderOf gives the delay (distance over the speed of sound, 3 s to the km), loudness, crack/clap/rumble and the low-pass of far thunder. strikeTarget takes the tallest, best-conducting thing near the point (a mast, a tree: the service adds the grove); boltPath is the jagged path with branches. Events weather:lightning, weather:strike, weather:thunder.
Blizzard. Snow moves when the friction velocity passes the threshold, if loose snow lies; the transport follows Bagnold, the visibility the extinction of the blowing snow, with whiteout and wind chill.
The sea and the shore#
seaCondition(state, { fetch, duration }): Beaufort force, Hs and period from Pierson-Moskowitz (a short fetch or a short gale gives a smaller sea), whitecaps by Monahan (W = 3.84e-6 U^3.41), streaks from force 8, spindrift and the visibility it leaves. seaWaves(state) gives the components for the water shader. Freak waves: rogueWaves makes rare events, at least twice Hs, with a deep trough ahead, that grow out of the sea and go back into it; rogueHeight adds to the surface; event weather:rogue.
surf(sea, shore, angle) is the surf zone of a shore kind (sand, cobble, boulder, rock):
| shore | slope | breaker (at Hs 2 m, T 9 s) | what you see and hear |
|---|---|---|---|
| sand | 0.035 | spilling, wide foamy zone | long swash, hiss, rip currents, longshore current |
| cobble | 0.13 | plunging | crash at the edge, backwash rattles the stones |
| boulder | 0.25 | collapsing | jets of water between blocks, boom |
| rock | 1.2 | surging, reflecting | the wave hits the wall, a plume of spray several wave heights high, boom |
Breaking at γ = 0.78 of the depth, the breaker kind by the Iribarren number, run-up by Stockdon, the longshore current by Longuet-Higgins. surfAt is the water at a distance from the shore and a time (a swell that steepens into a bore), waterline the swash up the beach and back.
Rivers#
manning(q, width, slope, bed) gives depth and speed from the discharge; the Froude number says pool, run, riffle, rapids or cascade; whitewaterClass is I–VI; conjugateDepth the hydraulic jump. A River is reaches and waterfalls, sample(point) gives the velocity across the profile (fast in the middle), the foam and the roar; sources() feeds flow channels. waterfall gives the nappe thickness, the time in the air, the pool depth, the mist and the loudness; discharge swells the river with rain on wet soil.
Trees and grass#
Each species (SPECIES: oak, birch, poplar, pine, spruce, willow, palm, dead) has crown, drag, wood strength and root anchor. treeLoad is drag on the crown (which folds up in strong wind), the bending moment at the base against the strength of the wood, and the overturning moment against the roots (wet soil weakens them); criticalWind is the wind that snaps or uproots (25–55 m/s in the crown, fitted). A Tree is a damped oscillator at its natural frequency (0.2–0.8 Hz), driven by the gusts at its own crown, with damage in order: leaves stripped, twigs, branches, limbs, then the trunk snaps (a stump stays) or the tree is uprooted and falls downwind by the pendulum law. Each tree's strength is from its id, so a grove fails tree by tree, the same on every peer. Events weather:tree.
grassWave gives lean, direction, sheen of the gust's front and tip shiver at a place and time; the wave runs across the field with the wind. foliageWind and driveFoliageWind set the intensity of the foliageWind shader rules of @ferret/levels from the gust at the camera.
Sand and dust#
Bagnold's threshold (≈ 6 m/s at 10 m for dune sand; coarser or wetter grains need more) and Kawamura's flux, the saltation layer, ripples that creep, dune speed, sandStreamers (snakes of sand running along the ground), dust visibility by the Koschmieder law, a haboob (a wall 1–2 km high that moves with the outflow, dense behind its front, with the gust at the front) and the simoom (hot dry gale, heat stress).
Tornadoes#
A smooth Rankine vortex (tangential), pressure drop by the cyclostrophic balance (≈ 120 hPa at 70 m/s), the Enhanced Fujita scale (efOf), what the wind lifts (lifted). whirls(state, t0, t1, area, seed) makes tornadoes, dust devils and waterspouts from the state in ten-minute slots (a tornado only from a violent hot wet storm, a dust devil from hot calm sun). A whirl has a life: the funnel lowers, matures, ropes out; the service adds it to the flow as a vortex and tears the trees near it. Events weather:whirl, weather:whirl-end.
Near the camera#
The pictures spend their effort by distance. TreesView: within near (45 m) of the camera the trunk leans and the crown bends more than the trunk (a curve, not a stick), every limb rocks at its own frequency, every leaf cluster shivers at the flutter frequency of the wind in that crown (in its own phase, stripped by a gale); within mid (160 m) only trunk and crown; farther a few times a second. Fallen trees go over about their foot or break, leaving a stump (upper); limbs that tear off are hidden and reported (onLimbLost).
SurfView: a mesh from up the beach to the open water; the swell rises, steepens, whitens and breaks, a thin sheet of white water runs up the sand and slides back, oblique waves arrive later along the shore, and on rock, boulders and cobble each wave throws up a column of spray (a ParticleCloud: a dense core of fine drops (streaks: ParticleCloud.emit(..., stretch) draws a drop as long as it flies in that time), a head of big dense puffs that climbs together (a sharp white front), a billowing mist of ragged puffs around it (the sprite is a core ringed with small blobs, so a crowd of them has cauliflower edges, not a smooth beam), water streaming down the face of the wall) that is fed for as long as the plume lasts and stands where the camera looks at the shore; its height follows the wave height. On a plunging or collapsing breaker the crest throws a lip (SurfView.lip): a thin translucent sheet that leaves the crest, arches shoreward and falls toward the trough, thick at the crest and a film at its tip, so the front of the wave is the inner wall of a barrel; the swell steepens into the bore over the last part of its way to the break (SurfPoint.steep), so the surface has no step at the edge of the surf zone. Where a lip comes down on the trough it throws fine drops and a billow of mist; the sheet dissolves at its far end and at its ends along the shore, so no edge of the mesh shows. The crest and the plume are in step (sprayPlume starts a moment before the crest reaches the wall). After the plume the water runs down the face of the wall in thinning streams. SurfView.wet (0..1) is how soaked the rock is; WetSurfaces takes the meshes of the rocks and, given wet, makes their materials darker and glossier and dries them back to what they were. The callback onBreak(strength, kind, at) is for the sound. ground(x, z) puts the water on the terrain's own relief; setLight sets the sun and the sky it reflects. GrassView is grass you walk in: thousands of tufts about the camera, leaning downwind under the gust at their place (grassWave read by the vertex shader from a texture), standing up behind it, lighter at its front; ground and density put it on the land and keep it off sand, rock and water. TreesView.restoreAll stands the felled trees up again. RiverView draws a River: a ribbon along every reach (green over the deep, the bed showing through the shallows, standing waves and lace foam where the Froude number and the bed make the water white, foam and ripples that run downstream at the speed of the water) and every waterfall as a sheet that leaves the lip at the critical speed, falls on its parabola, spreads and turns white, lands in a plunge pool that boils and sends up mist. scale (a function) is the discharge relative to the base: with discharge(base, rain, soilWetness, area, hours) rain swells the river, thickens the sheet and raises the mist; fallStates() gives the numbers. SnowView lays the weather's snow (WeatherService.snow, m) on the land: a skin cloned over the meshes you give (instanced rocks too), thick on the flat and thin on the steep, with drifts and bare patches that the wind makes more, sparkling in the sun; GrassView.setSnow buries the tufts and dusts the rest white. PrecipView (streaks in a box about the camera), LightningView (the bolt and the flash of the sky), FunnelView (the funnel and orbiting debris).
With landscapes and physics#
bridge.ts joins the weather to @ferret/terrain and to the physics host. It takes only the shapes of those packages (GroundLike, PhysicsLike), so @ferret/weather imports neither and a game wires them in one place.
From the landscape (the ground is asked, not copied):
terrainGround(ground, () => weather.state)is thegroundoption ofWeatherService: dust, loose snow and soil wetness at a place from the biome weights (Ground.sample().weightsand each biome'sweather), and the air's temperature from the climate (or the lapse rate, 6.5 K per km, against a reference place). A sandstorm rises over the sand desert and not over the meadow, snow blows only where it lies, and the mountain is colder than the beach.shoreAt(ground, x, z, seaward)walks to the sea and says what the shore is (sand, cobble, boulder or rock by the paint layer under the waterline and the slope), its slope and where the sea lies;bathymetryis the depth the waves shoal on.riverFromProfile(riverProfile(...), waterfalls(...), { floor })makes aRiverfrom the landscape's river line and falls: reaches cut at every fall with the bed that their slope gives, the fall as a lip with its direction, and the drop measured to the level of the water it lands in.
To the physics:
SeaSurface(remembers the bathymetry per point: a vessel asks hundreds of points a step): the sea's height, orbital velocity and foam from the weather's wind (the Pierson-Moskowitz components ofseaWaves), the freak waves, and every component shoaled on the bathymetry (shoalAmplitude: Green's law, never taller than 0.4 of the depth, nothing at the waterline).sea.fn()is the(x, z, t) => ythatvehicles().surfacetakes, so ships ride the water the camera sees;floatOnSeafloats any body on it.riverMedia(river, { scale }): every reach becomes arivermedium ofphysics-media(the current at Manning's speed, drag, buoyancy under the surface) and every fall a medium of aerated water going down. Rain swells it (scale), and a log put in the river is carried along.slipperiness: the friction scale of the wet, snowy and freezing ground (rain takes up to a third of the grip, snow a quarter more, wet ground below freezing is black ice) forphysics-friction.TreeDebris: a limb or branch the wind breaks off falls as a body with the mass of its wood and is carried by the wind; it lands, lies where it came to rest and then costs nothing. A felled trunk lies as a static box along the way it fell (also in the game's character world through thetrunkhook) and goes when the tree stands again.WeatherPhysicsis the service that keeps it all in step (register it after thePhysicsHostand theWeatherService).
Seen from the air#
A flying game (the airwar and zeppelin samples) takes the same service and draws it to the horizon:
- One state. The panel's sliders write into the service (
set), a preset is blended in (blendTo(name, 20)), and the game reads the wind, the cover and the visibility back fromstateandsample(); nothing keeps a copy of its own. - The wind the physics flies in.
windVector(state, x, z, height, t)for a body near the ground (the airship: gusts that sweep over the land, the log profile, the veer) andwindAloft(state, height)for the mean wind kilometres up (a bomber at 6 km meets a stronger wind from another side than the waves show). Aeroplanes, bullets, bombs and the airship all read it, so drift and ballistics change with the weather. - Clouds.
new CloudField({ cover: state.cloudCover, wind: h => cloudFieldFor(state).wind(h, 0) })and aCloudViewof@ferret/clouds;setCoverwhen the state changes. - The sea.
OceanViewof@ferret/levels: one polar grid round the camera to the horizon (no far plane, so no band on the horizon), the components ofseaWaves(state),setWind(state.windDir)for the patches of ripples, anddepthAt(x, z)from the landscape (minus the ground height): three depth boxes round the camera (8, 48 and 400 km) give shoaling, the pale shallows, the surf along the coast and the waterline, and the far box keeps the sea from showing under distant land, where the depth buffer cannot tell 0 m from 20 m. Waves shorter than the grid step or than a pixel's footprint are left out, so a low view over the water does not shimmer.heightAtfor the physics iswaveHeightof the same components. - The sky in the water. A probe of the sky dome, the sun, the moon, the stars and the cloud meshes (
createSkyProbe; the cloud meshes are rebuilt as the camera moves, so the probe's list is refreshed each frame) given to the ocean and to the landscape's water. - What falls.
PrecipViewwith a box of 70–90 m round the camera andLightningView, updated each frame.
The sky colours for an hour and a state are lookOf in examples/_shared/weather-look.ts (the weather sample's), with the sun's direction passed in.
The sample#
examples/weather is a coast to walk about (beach, headland, meadow, forest, and a river that crosses the meadow, runs down rapids and falls over the cliff into the sea, swelling in rain) with a panel for the weather and the hour: build it with node tools/build.mjs weather and open /weather/. Its land is a @ferret/terrain Landscape made from a description (the coast as a height grid, the river as a river operation, a dune biome): the weather asks it for the height, the water, the biomes, the shore and the river's fall, and the physics host runs the sea, the river, the friction and the limbs (buoys float on the waves, logs ride the river, limbs and trunks lie where a gale put them); the trees, rocks and ground textures are from the asset library.
Testing#
makeWorld(), add the FlowService and a WeatherService, step the world; everything above is deterministic. The tests in packages/weather/test assert the laws (Manning's discharge, γ = 0.78 at the break, the Bagnold threshold, EF classes, schedules that do not depend on how the time is cut).