Skip to content

Biomes and Vegetation on Voxel Terrain in Babylon.js · Part 11 of 12 in the series

Part 11: Wind

Set everything that grows in motion with one wind: gusts that travel across the land as waves, written once in GLSL and shared by four vertex shaders. Grass bends, flowers nod, trees lean, bob and flutter, far cards sway with them, and a noise makes the wind heard.

Quest objectives

  • Write gusts as waves that travel with the wind
  • Share one piece of GLSL between several shaders
  • Bend grass and plants by how high a vertex is
  • Lean a tree, bob its limbs and shake its leaves in the vertex shader
  • Keep the far cards in step with the meshes
  • Make the sound of the wind from filtered noise

The world of part 10 is full of plants, and not one of them moves. This part adds wind. Nothing is simulated for it: every vertex of every blade, flower, tree and card is pushed a little in the vertex shader, by a function of where the plant stands and what time it is. The graphics card works that out for all of them every frame, and the page does nothing but tell the shaders the time.

Gusts

Wind that pushed everything alike would look like the camera shaking. What makes a meadow look windy is that the wind comes in gusts: a patch of grass bows, and the bow runs on across the field. A gust is a wave that travels with the wind. Create src/wind.glsl:

src/wind.glsl
// The seconds since the start, and the wind: which way it blows along the ground, in x
// and y, and how hard, from 0 to 1, in z.
uniform float time;
uniform vec3 wind;

// How hard the wind blows at a place right now, from 0 to 1. Gusts are waves that travel
// with the wind: a long one that bends as it goes, and a short one on top.
float gust(vec2 place) {
  float along = dot(place, wind.xy);
  float across = dot(place, vec2(-wind.y, wind.x));
  float swell = sin(along * 0.05 - time * 0.9 + sin(across * 0.03) * 2.0) * 0.5 + 0.5;
  float ripple = sin(along * 0.31 - time * 2.3 + across * 0.17) * 0.5 + 0.5;
  return (swell * 0.7 + ripple * 0.3) * wind.z;
}

// How far the wind pushes something that stands at `place`, in meters per meter of its
// height: a lean with the wind, and a flutter of its own, which `phase` keeps from being
// the same for everything.
vec3 push(vec2 place, float phase) {
  float flutter = sin(time * 3.1 + phase * 6.2832) * 0.25;
  return vec3(wind.x, 0.0, wind.y) * gust(place) * (1.0 + flutter);
}
  • gust() first measures a place along the wind and across it. A sine of along minus the time is a row of wave fronts that move with the wind. The swell is the long wave: a front every 125 m or so, moving at 18 m/s. The sine of across inside it bends the fronts, so that they don't cross the land as straight lines.

  • The ripple is a short wave on top, a front every 20 m, slower and at a slant. Together they give a place a strong pull every few seconds and a small one in between.

  • push() turns the gust into a push along the wind. The flutter makes a plant swing back and forth a little on top of its lean, and phase keeps two plants side by side from swinging in step.

What push() returns is meters of push per meter of height. Each shader decides what to do with it.

One wind for four shaders

Four vertex shaders need these functions: the grass's, the plants', the trees' and the cards'. Copying them four times would mean four places to change. GLSL has no way to include a file, but the shaders are strings before they reach Babylon.js, and a string can be put into a string. Each shader gets a line #include<wind>, and a small function replaces that line with the file. Create src/wind.ts:

src/wind.ts
import { Vector3, type ShaderMaterial } from '@babylonjs/core/pure';
import source from './wind.glsl?raw';

/** Which way the wind blows, along x and z. */
const DIRECTION = [0.8, 0.6];

/** Puts the wind's uniforms and functions into a shader, in place of its line `#include<wind>`. */
export const withWind = (shader: string) => shader.replace('#include<wind>', source);

/** The names of the wind's uniforms, for the list a material is made with. */
export const WIND_UNIFORMS = ['time', 'wind'];

/** How hard the wind blows at `seconds`, from 0 to 1: it rises and falls over minutes. */
export function windStrength(seconds: number): number {
  return 0.45 + 0.25 * Math.sin(seconds * 0.07) + 0.15 * Math.sin(seconds * 0.023 + 2);
}

/** Tells materials the time and the wind. */
export function setWind(materials: (ShaderMaterial | null)[], seconds: number): void {
  const wind = new Vector3(DIRECTION[0], DIRECTION[1], windStrength(seconds));
  for (const material of materials) {
    material?.setFloat('time', seconds);
    material?.setVector3('wind', wind);
  }
}

/** How hard the wind blows at a place at `seconds`: gust() of wind.glsl, for the sound. */
export function gustAt(x: number, z: number, seconds: number): number {
  const along = x * DIRECTION[0] + z * DIRECTION[1];
  const across = -x * DIRECTION[1] + z * DIRECTION[0];
  const swell = Math.sin(along * 0.05 - seconds * 0.9 + Math.sin(across * 0.03) * 2) * 0.5 + 0.5;
  const ripple = Math.sin(along * 0.31 - seconds * 2.3 + across * 0.17) * 0.5 + 0.5;
  return (swell * 0.7 + ripple * 0.3) * windStrength(seconds);
}
  • withWind() is that function: every material hands its vertex shader through it.

  • windStrength() lets the wind rise and fall: two slow sines, one over a minute and a half and one over four and a half minutes, keep it between a breath and a stiff breeze.

  • setWind() tells a list of materials the time and the wind, once a frame.

  • gustAt() is gust() again, in TypeScript: the sound needs to know how hard it blows where the camera is.

Grass

A blade is fixed at its root and free at its tip, and it bends more the further up it is. The shader already knows how far up a vertex is: blade.x, 0 at the root and 1 at the tip. Squared, it leaves the lower half of the blade nearly still and bends the tip. A bent blade is also lower than a straight one, so the vertex goes down by a part of what it goes sideways: without that, the grass would stretch in the wind instead of bowing. Replace src/grass.vertex.glsl:

src/grass.vertex.glsl
precision highp float;

// A vertex of the tuft, and where along its blade it is: x from 0 at the root to 1 at
// the tip, y the blade's own shade.
attribute vec3 position;
attribute vec2 blade;
// The tuft, one for every instance: its place from the chunk's corner and its size,
// then its turn, its light, its tone and a random number.
attribute vec4 place;
attribute vec4 look;

uniform mat4 world;
uniform mat4 viewProjection;
uniform vec3 cameraPosition;
// Where the grass starts to shrink away, and where it is gone, in meters from the camera.
uniform vec2 grassRange;

#include<wind>

varying vec3 vPosition;
varying vec2 vBlade;
varying float vLight;
varying float vTone;

void main() {
  vec3 root = (world * vec4(place.xyz, 1.0)).xyz;
  // Toward the edge of its range the grass shrinks into the ground.
  float size = place.w * (1.0 - smoothstep(grassRange.x, grassRange.y, distance(root, cameraPosition)));
  float c = cos(look.x);
  float s = sin(look.x);
  vec3 turned = vec3(position.x * c - position.z * s, position.y, position.x * s + position.z * c);
  vPosition = root + turned * size;
  // The wind bends a blade more the higher up it is, and a bent blade is lower.
  float bend = blade.x * blade.x * size;
  vec3 pushed = push(root.xz, look.w) * bend * 0.8;
  vPosition += pushed - vec3(0.0, length(pushed) * 0.4, 0.0);
  vBlade = blade;
  vLight = look.y;
  vTone = look.z;
  gl_Position = viewProjection * vec4(vPosition, 1.0);
}

The tuft's random number, look.w, is the phase of its flutter. In src/grass.ts, import WIND_UNIFORMS and withWind from ./wind.ts. In createGrassMaterial(), the vertex shader goes through withWind(), and the wind's uniforms join the list. Replace the call that makes the material:

src/grass.ts
const material = new ShaderMaterial(
  'grass',
  scene,
  { vertexSource: withWind(vertexSource), fragmentSource },
  {
    attributes: ['position', 'blade', 'place', 'look'],
    uniforms: ['world', 'viewProjection', ...LIGHT_UNIFORMS, ...WIND_UNIFORMS, 'grassRange', 'lushRoot', 'lushTip', 'dryRoot', 'dryTip'],
  },
);

Plants

The small plants are cards, and a card has no blades, but it has uv.y: 0 at the ground and 1 at the top of the sprite. In src/plant.vertex.glsl, add the line #include<wind> after the uniform plantRange, and replace the line that sets vPosition:

src/plant.vertex.glsl
vPosition = root + turned * size;
// The wind moves the top of a plant, not its foot.
vPosition += push(root.xz, look.w) * uv.y * uv.y * size * 0.35;

A fern moves less than grass of the same height: its push is scaled by 0.35, the grass's by 0.8. In src/plants.ts, make the same three changes as for the grass: the import, vertexSource: withWind(vertexSource) in createPlantMaterial(), and ...WIND_UNIFORMS in the list of uniforms after ...LIGHT_UNIFORMS.

Trees

A tree moves in three ways at once, and the shader tells them apart by what it knows about a vertex:

  • The whole tree leans with the wind, more the higher up: by the vertex's height, squared, as the grass does. The trunk's foot stays where it is.

  • The limbs bob up and down, more the further out: by the vertex's distance from the trunk's axis. The sine's phase grows with that distance too, so a limb moves like a whip, not like a plank.

  • The leaves flutter: only vertices whose texture layer is one of leaves, each a few centimeters in its own direction and at its own pace.

All three grow with the strength of the gust at the tree, and look.w, the tree's random number, sets them off against the tree next to it. Replace src/tree.vertex.glsl:

src/tree.vertex.glsl
precision highp float;

attribute vec3 position;
attribute vec3 normal;
// Where on its texture the vertex is, the texture's layer, and the vertex's shade.
attribute vec4 paint;
// The tree, one for every instance: its place and its size, then its turn and three
// numbers of its own.
attribute vec4 place;
attribute vec4 look;

uniform mat4 world;
uniform mat4 viewProjection;
uniform vec3 cameraPosition;
// Where the trees start to fade out, and where they are gone, in meters from the camera.
uniform vec2 treeRange;
// The number of the first layer that holds leaves.
uniform float firstLeaves;

#include<wind>

varying vec3 vPosition;
varying vec3 vNormal;
varying vec4 vPaint;
varying float vFade;

void main() {
  // Turned about its trunk, sized, and put in its place.
  float c = cos(look.x);
  float s = sin(look.x);
  mat3 turn = mat3(c, 0.0, s, 0.0, 1.0, 0.0, -s, 0.0, c);
  vec3 local = turn * position * place.w;
  // The wind leans the whole tree, more the higher up, bobs its limbs, more the further
  // out, and shakes its leaves. No two trees move in step: look.w differs.
  vec3 blown = push(place.xz, look.w);
  float height = local.y * 0.07;
  float out_ = length(local.xz);
  local += blown * height * height * 0.6;
  local.y += sin(time * 1.7 + look.w * 40.0 + out_) * out_ * 0.03 * length(blown);
  if (paint.z >= firstLeaves - 0.5) {
    local += sin(time * vec3(5.3, 4.1, 4.7) + position.yzx * 3.0 + look.w * 20.0) * 0.05 * length(blown);
  }
  vec4 worldPosition = world * vec4(place.xyz + local, 1.0);
  vPosition = worldPosition.xyz;
  vNormal = mat3(world) * (turn * normal);
  vPaint = paint;
  // The whole tree fades as one: by how far its foot is from the camera.
  vec3 foot = (world * vec4(place.xyz, 1.0)).xyz;
  vFade = 1.0 - smoothstep(treeRange.x, treeRange.y, distance(foot.xz, cameraPosition.xz));
  gl_Position = viewProjection * worldPosition;
}

The uniform firstLeaves, which the fragment shader has had since part 8, is declared in the vertex shader too now: the material sets it once for both. In src/treeMaterial.ts, make the three changes again: the import, vertexSource: withWind(vertexSource), and ...WIND_UNIFORMS after ...LIGHT_UNIFORMS.

The plain material, which the pictures of part 10 are taken with, is made by the same function and gets the wind's code too. But nobody tells it the time or the wind, and a uniform that was never set is 0: for their pictures, the trees stand still.

Cards

If the meshes swayed and the cards did not, the line 90 m from the camera where one becomes the other would show at once. A card can't bob its limbs or shake its leaves, but it can lean. In src/impostor.vertex.glsl, add the line #include<wind> after the uniform cardRange, and replace the line that sets vPosition:

src/impostor.vertex.glsl
vPosition = position + right * card.x + vec3(0.0, card.y, 0.0);
// The top of the card sways as the tree's top does.
float height = card.y * 0.07;
vPosition += push(position.xz, layer * 0.37 + position.x * 0.13) * height * height * 0.6;

The lean is the tree shader's, number for number: the same share of the height, squared, times the same 0.6. A card has no random number of its own, so the phase is made of its layer and its place. In src/impostors.ts, make the three changes in createImpostorMaterial().

The sound of the wind

The building series made its thuds and cracks from a second of white noise. Wind is that noise too, played without end, with only its middle pitches let through, and louder when a gust passes. In src/sounds.ts, add a field to the class Sounds: private windGain: GainNode | null = null;. In start(), after the loop that fills the noise, add:

src/sounds.ts
// The wind: the noise in a loop, with only its middle pitches let through.
const source = this.context.createBufferSource();
source.buffer = this.noise;
source.loop = true;
const filter = this.context.createBiquadFilter();
filter.type = 'bandpass';
filter.frequency.value = 350;
filter.Q.value = 0.4;
this.windGain = this.context.createGain();
this.windGain.gain.value = 0;
source.connect(filter).connect(this.windGain).connect(this.context.destination);
source.start();

The source plays the buffer in a loop. The band-pass filter around 350 Hz, with a low Q, which makes it wide, turns the hiss into a rush. The gain starts at 0: the wind is silent until someone says how hard it blows. Add the method that does:

src/sounds.ts
/** Makes the wind as loud as it blows at the camera right now, from 0 to 1. */
wind(strength: number): void {
  // Not at once: the loudness follows over a third of a second.
  this.windGain?.gain.setTargetAtTime(strength * 0.25, this.context!.currentTime, 0.3);
}

setTargetAtTime() moves the loudness toward its new value over a third of a second. Set from one frame to the next, it would crackle.

Putting it together

In src/main.ts, import gustAt and setWind from ./wind.ts. In the frame's function, replace the line that tells the water the time:

src/main.ts
const seconds = performance.now() / 1000;
waterMaterial.setFloat('time', seconds);
// The same wind for everything that grows, and its sound where the camera is.
setWind([grassMaterial, plantMaterial, treeMaterial, cardMaterial], seconds);
sounds.wind(gustAt(camera.position.x, camera.position.z, seconds));

The cards' material is in the list although it is null until the pictures are taken: setWind() skips what isn't there yet. The sound is as loud as the gust at the camera: you hear a gust arrive when the grass around you bows.

Try it

Stand on the meadow and look across it: the gusts come over the hill as waves in the grass, pass you and run on. Wait a minute or two: the wind drops until the grass only trembles, then picks up again. Walk under an oak and look up into its crown, where the limbs bob and the leaves shake. Then fly up with F and look at a forest from afar: the same waves run over the cards. Press N to see the savanna's tall grass in the wind, where it shows best.

Wind. Click, then: stand in the grass and watch the gusts pass, with sound. WASD walks, F flies (Q/E down/up), N flies to the next biome, G shows the map.
Open in a new tab

Comments

The comments are GitHub Discussions: sign in with GitHub to write one.

The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.