Docs / World
Weather
Weather describes a world's weather as a handful of numbers: what the sky is doing, how severe it is, which way the wind blows, how much snow lies and how wet things are. Everything else follows from those numbers: how much the clouds dim the sun, how thick the air is, when lightning strikes and how loud the rain is. The engine draws the sky, clouds, falling rain and snow, and the fog. Your shaders draw what the weather does to your props and ground, using one Metal header.
A kind and a severity
public init(kind: Kind = .clear, severity: Float = 0.5, windHeading: Float = 60, byHand: Settings? = nil, seed: UInt32 = 1, schedule: WeatherSchedule? = nil, lyingSnow: Float = 0, snowDepth: Bool = false, wetness: Float = 0, puddles: Float? = nil, cloudShape: CloudShape = CloudShape(), sway: Float = 1, dustColour: SIMD3<Float> = Weather.desertDust, groundFog: GroundFog = GroundFog())
Kind is .clear, .overcast, .rain, .storm, .snow, .fog or .dust. severity runs from 0 (the kind at its lightest) to 1 (its heaviest), and Weather.preset(_:severity:) turns the pair into Settings: cloudCover, precipitation, snow, windSpeed (meters a second, up to 25), fogDensity, lightning (strikes a minute) and dust. To reach a mix no preset gives, set byHand to your own Settings; the kind and severity are then ignored. settings always gives the numbers in use.
windHeading is the compass bearing the wind blows toward: 0 is north (−z), 90 is east (+x). wind is that direction times the wind speed.
Clear changes nothing. At any severity, a clear sky only grows its breeze. lighting(_:flash:) hands back the sky it was given, and fogDensity(over:) hands back the world's own fog exactly, so turning weather on in a game that had none doesn't shift its look by a rounding error.
lighting(_:flash:)takes the hour'sDaySky.Lighting(see the sky by the hour) and dims the sun under cloud, turns the sky an even gray, and darkens everything a little as rain thickens. The sun's direction is left alone, so shadows under thin cloud still fall the right way, only fainter. Passflash(at:seenFrom:)to add lightning's light.fogDensity(over:)combines the world's fog with the weather's, so that the thicker one counts for most. Weather never thins a foggy world.rainVolume,windVolumeanddustVolumeare 0…1 levels for sound.
Lightning
strikes(from:to:) returns every Weather.Strike in a span of time. Strikes come from seed and the clock, never from a random generator's state, so two players on one clock see the same storm, however each one cuts up the time. A strike has a time, a position on the ground, inCloud for a flash that stays in the clouds, isClose for one of the roughly one in ten that land within 15–220 m of the world's middle (Weather.closeDistances), and a seed that shapes its bolt. Most land 400–3,000 m out. thunderDelay(heardFrom:) is the distance over 343 m/s, and thunderVolume(heardFrom:) fades with distance.
Weather that changes by itself
Set schedule to a WeatherSchedule and the weather runs in spells: clear for a while, then cloud, then a shower. A schedule has a chance for each kind (shares that don't have to add up to anything), the shortest and longest a spell lasts, how long a change from one spell to the next takes, the lightest and heaviest a spell may be, and how far the wind may wander from the world's heading.
// your game var weather = Weather(kind: .clear, windHeading: 60) weather.schedule = WeatherSchedule(chances: [.clear: 50, .overcast: 25, .rain: 15, .storm: 10], shortest: 10 * 60, longest: 30 * 60, change: 2 * 60) // each frame let now = serverTime ?? Weather.realTime() let current = weather.current(at: now)
Nothing is stored as time passes. The weather at any moment is worked out from the seed and the time alone, so a moment years into real time costs the same as the first one. current(at:) is what you draw and hear each frame. With no schedule, or one that's off, it returns the weather as set. Weather.realTime() is seconds since 1970, UTC, so every player shares one sky with no server at all. A game that has a server passes the server's time instead, which means a player who changes their Mac's clock changes nothing. spells(from:to:) lists the coming spells, which is useful for a forecast.
seasons gives each season its own chances, and gives the year warmth. A snow spell falls as rain when it's warm, and lying snow melts faster. To put a schedule's seasons on a game's calendar, see the world's clock.
Snow, wet ground, dust and ground fog
lyingSnow, 0…1, is how white everything that faces the sky is. It stays white under a clear sky, so a winter map stays a winter map. On a schedule, snow also builds while it snows and melts afterward.current(at:)never gives less snow than the value set.snowDepthraises the ground by up toWeather.deepestSnow(0.25 m). Players can turn it off withGraphicsSettings.snowDepth, and the Low preset does.wetnessis how dark and shiny surfaces are, andpuddlesis how full the puddles are. Settingwetnesssetspuddlestoo. Rain wets surfaces as it falls; on a schedule, surfaces soak in minutes and puddles fill more slowly and linger.dustColour(defaultWeather.desertDust) colors a dust storm's haze, its streaks, and the dust that settles on surfaces.groundFogis aGroundFog:amount(0…3),heightin meters, andcolour. The weather and the hour decide when it comes.groundFogDensity(hour:)is thickest just after sunrise and gone by late morning, heavier after rain, and blown away by strong wind.FogFloorsmooths your ground's heights so that fog pools in hollows and over water.
What the engine draws
| Type | What it draws |
|---|---|
CloudPass | Volumetric clouds into a picture SkyPass lays over the sky. See the sky by the hour. |
WeatherRenderer | Rain streaks, snowflakes or dust in a box that follows the eye, splashes where rain lands, drips from roof edges, and lightning bolts. |
WeatherCover | What is overhead, from straight above, so rain stays out from under roofs and splashes land on whatever is uppermost. |
VolumetricFog | The air in front of the eye as cells: sun shafts, ground fog, lights glowing in the haze. |
FogSkyPass | That fog laid over the sky where nothing solid was drawn. |
Nothing is simulated. Every drop is made in the vertex shader from its number and the time, so the cost is the drops drawn, up to WeatherRenderer.maxDrops. The cover is drawn with your own shadow batches. WeatherCover.encode(into:frameSlot:batches:) takes the same ShadowBatch list the sun's cascades use, and asks each batch for ShadowPass.Target.cover. A self-drawing batch that switches on pass.target has to handle .cover. A batch that culls with pass.viewProjection already works. Without a cover, rain falls through roofs and nothing splashes.
The order of a frame
- In
encodePrePasses, write uniforms, then record the sun's shadows. cover.update(around: eye), thencover.encode(into:frameSlot:batches:).CloudPass.encode(into:frameSlot:viewProjection:eye:lighting:layer:quality:width:height:)withcurrent.clouds(at: now). It returns the picture the sky pass reads, ornilat.flatquality.VolumetricFog.encode(into:frameSlot:frame:quality:width:height:), which comes after the shadows because itsFramereads them throughVolumetricFog.Shadows. It returns aDrawn, ornilat Low or when there's no fog to draw.- In the scene pass, draw
SkyPassfirst, then your solid surfaces, thenFogSkyPass.encode(into:fog:). - After the opaque scene, draw the falling weather and the lightning:
// your game, in encode(into:frameSlot:interpolation:) weatherRenderer.draw(current, into: encoder, frameSlot: frameSlot, viewProjection: viewProjection, eye: eye, time: now, lighting: lighting, fogDensity: current.fogDensity(over: sky.fogDensity), cover: cover) let struck = weatherRenderer.drawLightning(current, into: encoder, frameSlot: frameSlot, viewProjection: viewProjection, eye: eye, time: now) { strike in groundPoint(under: strike.position) // your game's: where it lands }
drawLightning returns the strikes it drew. That's your cue to scorch, burn or hurt where a close one lands. Each pass sets its own pipeline and argument table, so set yours again after it. Add allocations from WeatherRenderer, WeatherCover, CloudPass, SkyPass and VolumetricFog to your residency set, and add them again when CloudPass.picturesChanged or VolumetricFog.volumesChanged is set.
Sound
WorldFile.Sounds.WeatherSounds names a rain loop, a wind loop, a dust loop and thunder takes. Soundscape plays them: call setWeather(_:at:) once a frame, before update(listener:forward:up:elapsed:), with the same time that lightning is drawn by. The loops play as loud as the weather is heavy, and each strike's thunder arrives as long after the flash as sound takes to cover the distance. See worlds from a file.
The weather on your own surfaces
Your props and ground are drawn by your shaders. DuctaneWeather.h is a Metal header with what the weather does to them: snow lying on whatever faces up, dust settling, wet darkening, puddles in hollows with rain rings, water running down slopes, footprints, the clouds' shadows, swaying in the wind, and the fog volume. Every function is static inline and compiles into your own library.
Include it with #include "DuctaneWeather.h", and add the header folder to Xcode's MTL_HEADER_SEARCH_PATHS:
# the package added by path $(SRCROOT)/<relative path>/Ductane/Sources/Ductane/ShaderHeaders # the package added by URL $(BUILD_DIR)/../../SourcePackages/checkouts/Ductane/Sources/Ductane/ShaderHeaders
Shaders compiled from source at run time have no search path. Pass the source through ShaderLibrary.withEngineHeaders(_:), which writes the header in where it's included, once.
One block carries the frame's weather. Swift's WeatherSurface matches DUWeatherSurface field for field. It's all SIMD4<Float> and simd_float4x4, so the two sides never disagree about padding. Make it a member of your frame uniforms and write it each frame:
// your game uniforms.weather = WeatherSurface(weather: current, snowDepth: settings.snowDepth, cover: cover, coverDrawn: true, footprints: prints, printsDrawn: printCount > 0, time: now, clouds: current.clouds(at: now), fog: drawnFog?.lookup ?? .none)
Write it after the fog pass, which gives the lookup. WeatherSurface() with no arguments is a clear day. You bind the textures and buffers wherever you like: the cover's texture, CloudPass.coverageMap, the footprint buffers, and the fog's Drawn.volume.
#include class="p">"DuctaneWeather.h" fragment float4 groundFragment(GroundOut in [[stage_in]], // your game's constant FrameUniforms &frame [[buffer(0)]], // holds DUWeatherSurface weather depth2d<float> cover [[texture(3)]], texture2d<float> cloudMap [[texture(4)]], texture3d<float> fogVolume [[texture(5)]], device const DUFootprint *prints [[buffer(1)]], device const uint *cells [[buffer(2)]], device const float *puddles [[buffer(3)]], device const float *litter [[buffer(4)]]) { DUWeathered w = duWeathered(in.albedo, normalize(in.normal), normalize(in.faceNormal), in.world, true, true, in.soft, frame.weather, frame.groundGrid, cover, prints, cells, puddles, litter); float roughness = duWetRoughness(in.roughness, w); float sun = duCloudShadow(in.world, frame.sunDirection.xyz, frame.weather, cloudMap); float3 v = normalize(frame.eye.xyz - in.world); float3 color = shade(w.albedo, w.normal, roughness, sun) // your game's lighting + skyLight(reflect(-v, w.normal)) * duWetSheen(w.normal, v, w); return float4(duFogApply(color, in.world, distance(in.world, frame.eye.xyz), frame.viewProjection, frame.weather.fogVolume, fogVolume), 1); }
duWeathered lays everything on a surface in order: fallen leaves, snow, dust, wet, puddles, running water and footprints. Pass true for ground only on the ground, because litter and puddles lie only there. Pass false for settles on anything that moves through the world, such as a player or a held weapon. soft is how soft the ground is at that point, from WorldFile.Ground.softness(_:softLayers:). In the vertex stage, duSwayed bends props in the wind (see the world's clock), and duSnowCapRaise raises a snow cap made by SnowCap.make(_:) from a prop's upward-facing triangles. duFogApply comes last of all.
Footprints
FootprintTrail makes a print each stride for each character you report with step(character:feet:speed:onGround:shape:). Prints alternate left and right, point the way the character went, are spaced by speed, and come in .boot or .bare shapes. Call advance(seconds:weather:) to run the wiping clock. A print lasts about half an hour in calm weather, but only minutes in falling snow or heavy rain. forget(beyond:of:) lets go of the far ones. Each frame, FootprintGrid.update(frameSlot:trail:around:) writes the prints within 48 m of the eye into the buffers that duWeathered reads, at printsAddress(frameSlot:) and cellsAddress(frameSlot:). Prints show only where snow lies or the ground is soft, and only at the height the foot stood, so prints on a deck don't show up on the roof above it.