Skip to content

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

Part 4: Water

Fill the low land with water: a sea level, an ocean that the ground sinks into, lakes in the hollows, a water surface of rings with waves, a mirrored sky and foam, beaches of sand, a player that floats, and fog under water.

Quest objectives

  • Give the terrain a sea level, an ocean and lakes
  • Keep caves shut under the sea, and decide where water stands
  • Build the water as a flat mesh of rings that knows its depth
  • Write a water shader with waves, a mirrored sky, glints and foam
  • Paint beaches and wet shores in the terrain shader
  • Let the player float, and fade the view under water

The land has six biomes and shapes of its own now, but it is dry from one horizon to the other. This part adds water: a sea level, an ocean that the ground sinks into, lakes where the hills leave a hollow, beaches, a surface with waves that mirrors the sky, a player that floats, and fog under water.

One thing this water doesn't do is flow. It stands where the ground was generated below the sea's level, and nowhere else. That is a rule the terrain, the shaders and the player can all ask without anyone keeping track of anything, and it gets surprisingly far: a hole dug on a beach fills with water, and a cave deep under a hill stays dry.

The sea in the terrain

The sea lies at height 0. That alone makes lakes: wherever the land of part 3 dips below 0 between its hills, there is water now. For a real sea, one more noise says how much a place is open sea. It is 3.5 km wide, so seas and continents are large, and a smoothstep turns it into a number that is exactly 0 on land, 1 far out, and something in between along the coast. In src/terrain.ts, above the comment about the column's kept numbers, add:

src/terrain.ts
/** The height of the sea: ground below it lies under water. */
export const SEA = 0;
/** How deep the open sea is, in meters. */
const SEA_DEPTH = 45;

/** How much a place is open sea: 0 on land, 1 far out, and the coast in between. */
function ocean(x: number, z: number): number {
  return smoothstep(0.35, 0.55, noise2(x / 3500 + 1.05, z / 3500 + 9.93));
}

The numbers added to x and z move the noise, as in the climate: the start lies well inland, and the nearest open sea is some hundred meters away. At the end of column(), the ground sinks:

src/terrain.ts
// Out at sea the ground sinks to the sea's floor, which keeps a fifth of its ups and downs.
const sea = ocean(x, z);
if (sea > 0) columnHeight += (columnHeight * 0.2 - SEA_DEPTH - columnHeight) * sea;

Far out, the ground ends up 45 m below the sea, with a fifth of the hills it had. On the coast it is on its way there, which makes a shore that slopes into the water. And because the smoothstep is exactly 0 on land, nothing changes there: the ground around the start is still the ground of the earlier series.

Caves under the sea

Some caves break through the surface. On land that is an entrance. Under the sea it would be a hole in the sea's floor with air below it, since this water doesn't flow. So under the sea the caves stay shut near the surface. In density(), replace the lines of the caves:

src/terrain.ts
// Caves: tunnels along the lines where two noises are both 0. Near the surface they
// narrow, so that only some of them break through. Under water none does: the top
// 10 m of the sea's floor stay shut, since the water wouldn't run into a cave.
const a = noise3(x / 100, y / 50, z / 100);
const b = noise3(x / 100 + 43.7, y / 50 - 11.3, z / 100 + 7.9);
const shut = smoothstep(SEA + 4, SEA, columnHeight);
const cave = (Math.hypot(a, b) - 0.09) * 50 + Math.max(4 - d, 0) * 0.6 + Math.max(10 - d, 0) * 2 * shut;
return Math.min(d, cave);

shut is 0 where the ground is more than 4 m above the sea and 1 where it is below it. It adds to the cave's density near the surface, 20 at the very top and nothing from 10 m down, which is more than any tunnel takes away. Deeper down, the caves are as they were.

Where the water stands

The rule from the start of this part, as a function. At the end of src/terrain.ts, add:

src/terrain.ts
/** How far up a shore the water still stands in a hole dug there, in meters. */
export const SHORE = 1.5;

/**
 * The height of the water at (x, z): the sea's, where the generated ground lies below it
 * or just above, and none further inland, so that a cave below the sea's level stays dry.
 */
export function waterLevel(x: number, z: number): number {
  return surfaceHeight(x, z) < SEA + SHORE ? SEA : -Infinity;
}

The water stands where the generated ground is below the sea, or less than 1.5 m above it. The generated ground, not the one you dug: it can be worked out anywhere, in a worker or on the page, without knowing the edits. The 1.5 m are the shore. There, the water is under the sand already, so a hole dug on a beach has water in it. Further inland there is none, and a cave below the sea's level stays dry. The price: a channel dug from a lake into the land stays dry too, beyond that strip.

A sheet of rings

The water's surface is flat, so its mesh could be one big square. But the shader will want to know how deep the water is at every point, and that has to come from the mesh's vertices: it needs many of them near the camera and few far away. The far view of the terrain series already builds exactly that, rings around the camera that get wider with distance. So the far worker builds the water too: the same rings, flat, starting at the camera instead of 150 m out.

The code that made the ground's rings becomes a function for any list of radii. Replace src/farWorker.ts:

src/farWorker.ts
import { climateAt } from './climate.ts';
import type { MeshData } from './meshData.ts';
import { SEA, surfaceHeight } from './terrain.ts';

/** The ground's rings go from INNER to OUTER meters around the center, each further one wider. */
export const INNER = 150;
export const OUTER = 4500;
const RINGS = 128;
const SEGMENTS = 256;
/** The far ground lies this much lower, so that the chunks win where both are drawn. */
const SINK = 1;
/** The water's rings start at the center: one point, then rings from WATER_INNER meters out. */
const WATER_RINGS = 96;
const WATER_INNER = 3;

export interface FarJob {
  x: number;
  z: number;
}

/** The far ground's mesh, with the climate at each vertex. */
export interface FarMesh extends MeshData {
  climates: Float32Array;
}

/** The water's mesh, with how deep the water is at each vertex: below 0 over land. */
export interface WaterMesh extends MeshData {
  depths: Float32Array;
}

export interface FarResult {
  ground: FarMesh;
  water: WaterMesh;
}

/** Radii from `inner` to OUTER, each a constant factor larger than the one before. */
function growing(inner: number, count: number): number[] {
  const growth = (OUTER / inner) ** (1 / (count - 1));
  return Array.from({ length: count }, (_, ring) => inner * growth ** ring);
}

/**
 * A mesh of rings with the given radii around its own origin. `each` is called for every
 * vertex with its place and its number, and returns its height.
 */
function ringMesh(radii: number[], each: (px: number, pz: number, vertex: number) => number): MeshData {
  const rings = radii.length;
  const positions = new Float32Array(rings * SEGMENTS * 3);
  for (let ring = 0; ring < rings; ring += 1) {
    for (let segment = 0; segment < SEGMENTS; segment += 1) {
      const angle = (segment / SEGMENTS) * Math.PI * 2;
      const px = Math.cos(angle) * radii[ring];
      const pz = Math.sin(angle) * radii[ring];
      const vertex = ring * SEGMENTS + segment;
      positions.set([px, each(px, pz, vertex), pz], vertex * 3);
    }
  }

  // Normals from the neighbors: across the ring outwards, and along it.
  const at = (ring: number, segment: number, axis: number) =>
    positions[(Math.min(Math.max(ring, 0), rings - 1) * SEGMENTS + ((segment + SEGMENTS) % SEGMENTS)) * 3 + axis];
  const normals = new Float32Array(positions.length);
  for (let ring = 0; ring < rings; ring += 1) {
    for (let segment = 0; segment < SEGMENTS; segment += 1) {
      const out = [0, 1, 2].map((axis) => at(ring + 1, segment, axis) - at(ring - 1, segment, axis));
      const along = [0, 1, 2].map((axis) => at(ring, segment + 1, axis) - at(ring, segment - 1, axis));
      // The cross product of the two, turned to point up.
      let nx = out[1] * along[2] - out[2] * along[1];
      let ny = out[2] * along[0] - out[0] * along[2];
      let nz = out[0] * along[1] - out[1] * along[0];
      if (ny < 0) [nx, ny, nz] = [-nx, -ny, -nz];
      // A ring of radius 0 is one point, with no direction along it: straight up then.
      const length = Math.hypot(nx, ny, nz);
      normals.set(length > 0 ? [nx / length, ny / length, nz / length] : [0, 1, 0], (ring * SEGMENTS + segment) * 3);
    }
  }

  // Two triangles between each ring and the next, segment by segment, split along the
  // shorter diagonal as in the surface nets: the triangles then follow the ridges.
  const distance = (a: number, b: number) =>
    Math.hypot(
      positions[a * 3] - positions[b * 3],
      positions[a * 3 + 1] - positions[b * 3 + 1],
      positions[a * 3 + 2] - positions[b * 3 + 2],
    );
  const indices = new Uint32Array((rings - 1) * SEGMENTS * 6);
  let i = 0;
  for (let ring = 0; ring < rings - 1; ring += 1) {
    for (let segment = 0; segment < SEGMENTS; segment += 1) {
      const a = ring * SEGMENTS + segment;
      const b = ring * SEGMENTS + ((segment + 1) % SEGMENTS);
      const c = a + SEGMENTS;
      const d = b + SEGMENTS;
      if (distance(a, d) <= distance(b, c)) indices.set([a, d, b, a, c, d], i);
      else indices.set([a, c, b, b, c, d], i);
      i += 6;
    }
  }
  return { positions, normals, indices };
}

/** The far ground and the water around (x, z), positions from that point. */
self.onmessage = (event: MessageEvent<FarJob>) => {
  const { x, z } = event.data;

  // The ground: a heightfield of the generated heights.
  const climates = new Float32Array(RINGS * SEGMENTS * 2);
  const ground: FarMesh = {
    ...ringMesh(growing(INNER, RINGS), (px, pz, vertex) => {
      const { temperature, moisture } = climateAt(x + px, z + pz);
      climates.set([temperature, moisture], vertex * 2);
      return surfaceHeight(x + px, z + pz) - SINK;
    }),
    climates,
  };

  // The water: a flat sheet at the height of the sea, which knows how deep it is.
  const depths = new Float32Array(WATER_RINGS * SEGMENTS);
  const water: WaterMesh = {
    ...ringMesh([0, ...growing(WATER_INNER, WATER_RINGS - 1)], (px, pz, vertex) => {
      depths[vertex] = SEA - surfaceHeight(x + px, z + pz);
      return SEA;
    }),
    depths,
  };

  const result: FarResult = { ground, water };
  const arrays = [ground.positions, ground.normals, ground.indices, climates, water.positions, water.normals, water.indices, depths];
  self.postMessage(result, { transfer: arrays.map((array) => array.buffer) });
};
  • growing() makes radii that each are a constant factor larger than the one before: the ground's, from 150 m to the horizon, as before.

  • ringMesh() is the old code, for the radii it is given. each returns a vertex's height, and gets the vertex's number, so that the caller can fill arrays of its own: the climates of the ground, the depths of the water.

  • The water's first ring has the radius 0: all its vertices are one point, the middle of the sheet. Such a ring has no direction along it, so its normals are set straight up.

  • The depth of a vertex is the sea's height less the generated ground's: above 0 in the water, below 0 over land.

  • Both meshes go back in one message, so they always show the same place.

The far view shows both, and moves both along. Replace src/farView.ts:

src/farView.ts
import type { Material, Mesh, Scene, Vector3 } from '@babylonjs/core/pure';
import type { FarJob, FarResult } from './farWorker.ts';
import { createMesh } from './meshData.ts';

/** The far view moves along in steps of this many meters, and is built again each time. */
const STEP = 64;

/**
 * The ground beyond the chunks, to the horizon: a heightfield of the generated heights.
 * And the water, from the camera to the horizon, which is flat anyway.
 */
export class FarView {
  private ground: Mesh | null = null;
  private water: Mesh | null = null;
  private center: FarJob | null = null;
  private building: FarJob | null = null;
  private readonly worker = new Worker(new URL('./farWorker.ts', import.meta.url), { type: 'module' });
  private readonly scene: Scene;
  private readonly material: Material;
  private readonly waterMaterial: Material;

  constructor(scene: Scene, material: Material, waterMaterial: Material) {
    this.scene = scene;
    this.material = material;
    this.waterMaterial = waterMaterial;
    this.worker.onmessage = (event: MessageEvent<FarResult>) => this.show(event.data);
  }

  get vertices(): number {
    return this.ground?.getTotalVertices() ?? 0;
  }

  /** Once a frame: builds the far view again when the camera has moved a step. */
  update(focus: Vector3): void {
    const x = Math.round(focus.x / STEP) * STEP;
    const z = Math.round(focus.z / STEP) * STEP;
    if (this.building || (this.center?.x === x && this.center.z === z)) return;
    this.building = { x, z };
    this.worker.postMessage(this.building);
  }

  private show(data: FarResult): void {
    this.ground?.dispose();
    this.water?.dispose();
    const ground = createMesh('far view', data.ground, this.scene);
    // The far ground is all surface, under the open sky.
    const count = data.ground.positions.length / 3;
    ground.setVerticesData('depth', new Float32Array(count), false, 1);
    ground.setVerticesData('light', new Float32Array(count).fill(1), false, 1);
    ground.setVerticesData('climate', data.ground.climates, false, 2);
    ground.material = this.material;
    this.ground = ground;

    const water = createMesh('water', data.water, this.scene);
    water.setVerticesData('depth', data.water.depths, false, 1);
    water.material = this.waterMaterial;
    this.water = water;

    for (const mesh of [ground, water]) {
      mesh.position.set(this.building!.x, 0, this.building!.z);
      mesh.isPickable = false;
      mesh.freezeWorldMatrix();
    }
    this.center = this.building;
    this.building = null;
  }
}

The water's shader

The vertex shader only passes the position and the depth on. Create src/water.vertex.glsl:

src/water.vertex.glsl
precision highp float;

attribute vec3 position;
attribute float depth;

uniform mat4 world;
uniform mat4 viewProjection;

varying vec3 vPosition;
varying float vDepth;

void main() {
  vec4 worldPosition = world * vec4(position, 1.0);
  vPosition = worldPosition.xyz;
  vDepth = depth;
  gl_Position = viewProjection * worldPosition;
}

Water shaders usually read the scene's depth to find out how much water lies between the surface and the ground behind it, which takes a second pass over the scene. This one gets the depth with the mesh, blended between the vertices, and needs no such pass. It is the depth above the generated ground, not above what you dug, and that is good enough. Create src/water.fragment.glsl:

src/water.fragment.glsl
precision highp float;

varying vec3 vPosition;
varying float vDepth;

uniform vec3 cameraPosition;
uniform vec3 sunDirection;
uniform vec3 sunColor;
uniform vec3 skyColor;
uniform vec3 fogColor;
uniform vec2 fogRange;
uniform float time;

// How far up a shore the sheet of water reaches under the ground, as SHORE in terrain.ts.
const float SHORE = 1.5;
// Nearer than this, the sheet is cut away over land: caves below the sea stay dry.
const float CUT_RANGE = 300.0;
const vec3 SHALLOW = vec3(0.25, 0.62, 0.6);
const vec3 DEEP = vec3(0.04, 0.2, 0.36);

// The slope of the waves at a point: a few sine waves that run different ways.
vec2 waves(vec2 p) {
  vec2 slope = vec2(0.0);
  slope += vec2(0.8, 0.6) * cos(dot(p, vec2(0.8, 0.6)) * 0.9 + time * 1.4) * 0.05;
  slope += vec2(-0.5, 0.86) * cos(dot(p, vec2(-0.5, 0.86)) * 1.7 + time * 1.9) * 0.04;
  slope += vec2(0.3, -0.95) * cos(dot(p, vec2(0.3, -0.95)) * 3.1 + time * 2.6) * 0.03;
  slope += vec2(-0.9, -0.4) * cos(dot(p, vec2(-0.9, -0.4)) * 0.23 + time * 0.7) * 0.03;
  return slope;
}

void main() {
  vec3 toCamera = cameraPosition - vPosition;
  float distanceToCamera = length(toCamera);
  if (vDepth < -SHORE && distanceToCamera < CUT_RANGE) discard;
  toCamera /= distanceToCamera;

  // Far away the waves are smaller than a pixel: they fade out, and the sea lies flat.
  vec2 slope = waves(vPosition.xz) * (1.0 - smoothstep(60.0, 400.0, distanceToCamera));
  vec3 normal = normalize(vec3(-slope.x, 1.0, -slope.y));
  // Seen from below, the surface faces down.
  if (toCamera.y < 0.0) normal = -normal;

  // The water's own color, darker the deeper it is, and the sky it mirrors: more of the
  // sky the flatter the look at it.
  float depth = max(vDepth, 0.0);
  vec3 body = mix(SHALLOW, DEEP, smoothstep(0.0, 9.0, depth)) * (skyColor + sunColor * 0.6);
  float mirror = 0.03 + 0.97 * pow(1.0 - max(dot(normal, toCamera), 0.0), 5.0);
  vec3 color = mix(body, fogColor, mirror);
  // The sun glints where the surface mirrors it into the eye.
  vec3 halfway = normalize(toCamera - sunDirection);
  color += sunColor * pow(max(dot(normal, halfway), 0.0), 300.0);

  // Foam where the water is ankle deep, in bands that run up the shore.
  float foam = (1.0 - smoothstep(0.0, 0.35, depth)) * (0.6 + 0.4 * sin(depth * 30.0 + time * 2.0 + vPosition.x * 0.7));
  color = mix(color, vec3(1.0), clamp(foam, 0.0, 1.0) * 0.7);

  // Shallow water is clear, deep water is not, and a flat look sees only the mirror.
  float alpha = max(mix(0.5, 0.94, smoothstep(0.0, 6.0, depth)), mirror);
  // At the very edge it thins out to nothing.
  alpha *= smoothstep(-0.05, 0.15, vDepth + foam * 0.1);

  float fog = smoothstep(fogRange.x, fogRange.y, distanceToCamera);
  gl_FragColor = vec4(mix(color, fogColor, fog), alpha);
}
  • Over land the sheet is cut away, by the same 1.5 m as waterLevel(): that keeps it out of caves and pits. Only within 300 m, though. Further out the rings are too wide to tell a small lake from its shores, and the ground hides the sheet wherever it is higher anyway.

  • waves() adds up four sine waves that run different ways and returns the slope of the surface, which gives the normal. Beyond 60 m the waves fade, and at 400 m the sea lies flat: waves smaller than a pixel would only flicker.

  • The water's own color goes from a light green-blue to a dark blue over 9 m of depth. How much of the sky it mirrors depends on the angle: 3% looking straight down, all of it at a flat look. The sky's color is the fog's.

  • The sun glints where the surface mirrors it into the eye: the halfway vector, to a high power, makes small bright spots on the waves.

  • Where the water is less than 35 cm deep there is foam, in bands that move up the shore.

  • Shallow water is half see-through, deep water almost not at all, and at the very edge the sheet thins out to nothing, so that it meets the sand without a hard line.

  • Seen from below, the normal is turned around.

The material is blended over what is behind it, and seen from both sides. Create src/water.ts:

src/water.ts
import { ShaderMaterial, type Scene } from '@babylonjs/core/pure';
import { LIGHT_UNIFORMS, setLight, type FogOptions } from './material.ts';
import fragmentSource from './water.fragment.glsl?raw';
import vertexSource from './water.vertex.glsl?raw';

/** The water's material: see-through, with waves that move with the `time` it is given. */
export function createWaterMaterial(scene: Scene, options: FogOptions): ShaderMaterial {
  const material = new ShaderMaterial(
    'water',
    scene,
    { vertexSource, fragmentSource },
    {
      attributes: ['position', 'depth'],
      uniforms: ['world', 'viewProjection', ...LIGHT_UNIFORMS, 'time'],
      // Drawn after everything solid, and blended over it.
      needAlphaBlending: true,
    },
  );
  setLight(material, options);
  material.setFloat('time', 0);
  // The surface is also seen from below.
  material.backFaceCulling = false;
  return material;
}

Fog that can change

Under water the view will end after a few meters. For that, the fog of a material has to be set again later. In src/material.ts, the two lines at the end of setLight() that set the fog become a function of their own. Replace them and the closing brace:

src/material.ts
setFog(material, SKY, options);
}

/** Sets the fog: its color, and where it starts and ends. */
export function setFog(material: ShaderMaterial, color: Color3, options: FogOptions): void {
  material.setColor3('fogColor', color);
  material.setVector2('fogRange', new Vector2(options.fogStart, options.fogEnd));
}

Beaches

The sea's floor and its shores are sand, in every biome. The terrain's shader can tell where that is without a new attribute: vDepth is how far a point lies below the generated ground, so the point's height plus vDepth is the height of that ground. In src/terrain.fragment.glsl, add two constants after SNOW:

src/terrain.fragment.glsl
const float SAND = 8.0;
// The height of the sea, as in terrain.ts.
const float SEA = 0.0;

After the loop over the biomes, before the soil's color is looked up, the sand takes over from the biomes' covers:

src/terrain.fragment.glsl
// The sea's floor and its shore are sand, whatever the biome: where the ground was
// generated below the sea or just above it.
float ground = vPosition.y + vDepth;
float beach = 1.0 - smoothstep(SEA + 1.0, SEA + 2.5, ground);
if (cover > 0.0 && beach > 0.0) covered = mix(covered, triplanar(SAND, blend), beach);

The sand is all there from 1 m above the sea down, and fades out up to 2.5 m. And the line that mixes the snow in gets company. Replace it:

src/terrain.fragment.glsl
// No snow under water, and the shore is dark where the waves wet it.
snow *= smoothstep(SEA, SEA + 0.5, vPosition.y);
if (snow > 0.0) color = mix(color, triplanar(SNOW, blend), snow);
color *= mix(1.0, 0.65, beach * (1.0 - smoothstep(SEA + 0.1, SEA + 0.6, vPosition.y)));

The far view uses the same shader, so the far shores are sand too.

Floating

The player doesn't dive, but floats: in water that reaches the chin, the body is carried up until the eyes are just above the surface, and moves more slowly. In src/player.ts, import waterLevel from ./terrain.ts, and add to the constants:

src/player.ts
const SWIM_SPEED = 3;

/** In water deeper than this the body floats, the eyes just above the surface. */
const FLOAT_DEPTH = 1.45;
/** How hard the water pushes a body up per meter it is too deep, and how much it slows it. */
const BUOYANCY = 14;
const DRAG = 5;

The class gets a field swimming = false; after grounded. In update(), replace the line that picks the speed:

src/player.ts
// In water that reaches the chin, the body floats and swims.
const depth = waterLevel(this.position.x, this.position.z) - this.position.y;
this.swimming = depth > FLOAT_DEPTH;
const speed = this.swimming ? SWIM_SPEED : input.pressed('ShiftLeft') ? RUN_SPEED : WALK_SPEED;

And replace the lines of the jump and of gravity:

src/player.ts
if (this.swimming) {
  // The water carries the body up to where it floats, and slows its rise and fall.
  this.velocity.y += ((depth - FLOAT_DEPTH) * BUOYANCY - this.velocity.y * DRAG) * dt;
} else {
  if (this.grounded && input.pressed('Space')) {
    this.velocity.y = JUMP_SPEED;
    this.grounded = false;
  }
  if (!this.grounded) this.velocity.y -= GRAVITY * dt;
}

The water is a spring with a brake: it pushes up harder the deeper the body is below where it floats, and slows whatever speed the body has, up or down. Without the brake the player would bob forever. A jump from a cliff ends a few meters under water, and the body comes back up. Walking out works by itself: where the ground rises, it carries the feet.

Not into the sea

The key N should not fly out to sea. In src/travel.ts, import SEA from ./terrain.ts, and replace holds:

src/travel.ts
const holds = (px: number, pz: number) => {
  const height = surfaceHeight(px, pz);
  biomesAt(px, height, pz, weights);
  // On dry land.
  return weights[biome] > 0.98 && height > SEA + 2;
};

The page

In src/main.ts, import Color3 from Babylon.js, setFog from ./material.ts, waterLevel from ./terrain.ts and createWaterMaterial from ./water.ts. The far view gets the water's material. Replace the line that makes it:

src/main.ts
const waterMaterial = createWaterMaterial(scene, fog);
const farView = new FarView(scene, farMaterial, waterMaterial);

Under water, everything fades into the water's color within 35 m, and the sky has that color too. Before travel(), add:

src/main.ts
// Under water, everything fades into the water's color within a few meters.
const WATER_FOG = { color: Color3.FromHexString('#1c5a72'), fogStart: 0, fogEnd: 35 };
let underWater = false;

/** Sets the fog of everything for a camera above or below the water. */
function dive(under: boolean): void {
  underWater = under;
  for (const lit of [material, farMaterial, blockMaterial, waterMaterial]) {
    setFog(lit, under ? WATER_FOG.color : SKY, under ? WATER_FOG : fog);
  }
  scene.clearColor = (under ? WATER_FOG.color : SKY).toColor4();
}

Once a frame, the water gets the time for its waves, and the fog is switched when the camera goes through the surface. After farView.update():

src/main.ts
waterMaterial.setFloat('time', performance.now() / 1000);
const under = camera.position.y < waterLevel(camera.position.x, camera.position.z);
if (under !== underWater) dive(under);

And the HUD says when the player swims. In its second line, replace the part for walking with (player.swimming ? 'Swimming' : player.grounded ? 'Walking' : 'In the air').

Try it

The nearest water is a lake about 200 m behind you: turn around and run, or fly with F to see it from above. Walk down the beach into the water. The sand is dark where the waves wet it, the foam moves up the shore, and when the water reaches your chin you float. Switch to the terrain tool with T and dig a hole on the beach: there is water in it. Dig one a little further up the meadow: it stays dry. Then fly, and take the camera under the surface: the view closes in, and the sheet of water is above you.

On a beach, looking over a lake. The water is clear over the sand and dark where it is deep, and mirrors more of the sky the flatter the look at it.
Water. Click, then: turn around and run to the lake, walk in and float. T digs: a hole on the beach fills with water. F flies, also under water. G shows the map, N flies to the next biome.
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.