Skip to content

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

Part 9: Forests

Plant the trees as forests: a rule that says for every cell of 6 m whether a tree stands there, of which species and how big, a worker that plants tile by tile, instanced drawing near the camera, trees that fade out in a grain, solid trunks, and shade on the ground.

Quest objectives

  • Decide from a cell's numbers alone whether it holds a tree, and which
  • Open glades in every forest, and keep the shore, the slopes and the cold bare
  • Plant tiles of trees in a worker, on the ground as it really is
  • Draw each model once per tree near the camera, and fade trees out in a grain
  • Make the trunks solid, and put the ground, the grass and the plants in the shade

Eighteen trees stand in a nursery. This part takes them out of it and plants them where the biomes want them: close together in the broadleaf and conifer forests, one here and there on the meadow, small and far apart on the tundra, acacias in the savanna and cacti in the desert. The forests have glades, their trunks stop you, and the ground under them lies in their shade.

What the biomes say

Each biome gets one more entry, trees: how much of the ground its trees cover, from 0 to 1, how big they grow, and which species they are, each with its share. In src/climate.ts, replace BIOMES:

src/climate.ts
/**
 * The biomes, each with the climate it is at home in and a color for the map. A place
 * belongs to the biome whose climate is nearest to its own. `ground` is the texture that
 * covers its ground, and `tint` colors its soil and rock. `shape` holds the numbers that
 * shape its ground, in meters: see Shape. `grass` says how much of the ground grass covers,
 * from 0 to 1, how high it grows in meters, and how dry it is: 0 is lush, 1 is straw.
 * `plants` lists the small plants that grow in it, each with the share of the places for
 * plants that it takes. `trees` says how much of the ground trees cover, how big they
 * grow, 1 being their full size, and the share of each species among them.
 */
export const BIOMES = [
  {
    name: 'Meadow', temperature: 0.5, moisture: 0.4, color: '#7fae3c', ground: 'grass', tint: '#ffffff',
    shape: { base: 12, hills: 40, mountains: 150, knolls: 0, dunes: 0 },
    grass: { amount: 1, height: 0.42, tone: 0.1 },
    plants: { daisy: 0.1, bluebell: 0.06, bush: 0.012 },
    trees: { cover: 0.05, size: 1, kinds: { oak: 0.6, birch: 0.4 } },
  },
  {
    name: 'Broadleaf forest', temperature: 0.52, moisture: 0.76, color: '#3c7a2a', ground: 'litter', tint: '#f2f0e6',
    shape: { base: 14, hills: 46, mountains: 150, knolls: 0, dunes: 0 },
    grass: { amount: 0.5, height: 0.36, tone: 0.2 },
    plants: { fern: 0.14, bush: 0.05, bluebell: 0.04, mushroom: 0.01 },
    trees: { cover: 0.9, size: 1, kinds: { oak: 0.7, birch: 0.3 } },
  },
  {
    name: 'Conifer forest', temperature: 0.3, moisture: 0.62, color: '#28584a', ground: 'needles', tint: '#e6e8f2',
    shape: { base: 20, hills: 55, mountains: 170, knolls: 10, dunes: 0 },
    grass: { amount: 0.22, height: 0.3, tone: 0.35 },
    plants: { fern: 0.1, mushroom: 0.03, heather: 0.03, bush: 0.01 },
    trees: { cover: 0.9, size: 1, kinds: { spruce: 0.7, pine: 0.2, birch: 0.1 } },
  },
  {
    name: 'Tundra', temperature: 0.1, moisture: 0.45, color: '#c3ccd6', ground: 'moss', tint: '#dfe6f5',
    shape: { base: 24, hills: 20, mountains: 190, knolls: 5, dunes: 0 },
    grass: { amount: 0.3, height: 0.2, tone: 0.65 },
    plants: { heather: 0.1 },
    trees: { cover: 0.06, size: 0.5, kinds: { pine: 0.5, birch: 0.5 } },
  },
  {
    name: 'Savanna', temperature: 0.76, moisture: 0.5, color: '#c9a545', ground: 'straw', tint: '#ffd9b0',
    shape: { base: 7, hills: 12, mountains: 40, knolls: 22, dunes: 0 },
    grass: { amount: 0.5, height: 0.75, tone: 1 },
    plants: { shrub: 0.05 },
    trees: { cover: 0.1, size: 1, kinds: { acacia: 1 } },
  },
  {
    name: 'Desert', temperature: 0.86, moisture: 0.14, color: '#e8bd7c', ground: 'sand', tint: '#ffc08a',
    shape: { base: 9, hills: 14, mountains: 70, knolls: 30, dunes: 9 },
    grass: { amount: 0.03, height: 0.5, tone: 1 },
    plants: { shrub: 0.012 },
    trees: { cover: 0.04, size: 1, kinds: { cactus: 1 } },
  },
] as const;

A rule for every cell

Grass is scattered in the chunk workers, on the ground a chunk's grid holds. Trees can't be: a tree is seen from much further away than the 96 m in which chunks get their plants, and part 10 will show forests a kilometer off, where no chunk is loaded at all. So the trees come from a rule that needs nothing but a place. The land is laid out in cells of 6 m, and for each cell the rule says whether a tree stands in it, of which species, and how big. It asks only the cell's own numbers, the climate and the generated terrain, so it gives the same answer whenever and wherever it is asked.

The tree stands somewhere in the middle of its cell, never in the outer 15 % on any side, so two trees are at least 1.8 m apart. Then the cell has to pass a row of tests:

  • Not on the shore or in the water, and not within 45 m of the place where the earlier series built: the start stays an open meadow.

  • Warm enough. The temperature falls with the height, as in part 1, and below 0.14 no tree grows. That is a little warmer than where the snow begins, so the mountains have a tree line with bare ground between the last trees and the snow.

  • A random number below the cover. In a forest, nine cells in ten hold a tree, on the meadow one in twenty.

  • Not too steep: the generated ground may rise or fall 1.7 m over 2 m.

The cover is not what the biomes say alone. A forest that fills every cell is a wall. So a noise with patches 70 m across opens glades: where it is low, the cover is 0, whatever the biome, and at the edge of a glade it rises to the full cover. treeCover() is a function of its own, since the ground will ask for it too.

The species is picked as part 6 picks a kind of plant: one random number, and each species gets a stretch of it as long as its share. Another random number picks one of the three variants. The tree's numbers have the same layout as a plant's, eight floats: its place and its size, then its turn, a random number for later, its model and another random number. That lets instanceBuffer() of part 5 hand them to the graphics card as they are.

On the ground as it really is

surfaceHeight() is the height of the ground before the overhangs: the 3D noise of the density pushes the real surface up or down, by a meter on the plains and by up to 10 m in the mountains. A tree planted at surfaceHeight() would float or be buried. So the rule asks the density itself: from above everything the ground could reach, down in steps of half a meter to the first solid point, and from there to where the density crosses 0. In src/terrain.ts, add after density():

src/terrain.ts
/**
 * The height of the generated ground at (x, z) as it really is, overhangs and all: the
 * highest point of the column that is solid.
 */
export function groundLevel(x: number, z: number): number {
  // Down from above everything in steps of half a meter, to the first solid point.
  let y = surfaceHeight(x, z) + MOST_BEND + 1;
  while (density(x, y, z) <= 0 && y > -200) y -= 0.5;
  // The surface lies between that point and the one above it, where the density is 0.
  const below = density(x, y, z);
  const above = density(x, y + 0.5, z);
  return y + (0.5 * below) / (below - above);
}

This is the generated ground, without your edits. A tree whose ground you dig away hangs in the air for now: part 12 makes it fall. The tree is set a quarter of a meter into the ground, so that its foot doesn't show on a slope. Create src/treeRule.ts:

src/treeRule.ts
import { BIOME_COUNT, BIOMES, biomeWeights, climateAt, cooling } from './climate.ts';
import { hash, patchNoise } from './random.ts';
import { groundLevel, SEA, surfaceHeight } from './terrain.ts';
import { SPECIES, VARIANTS } from './trees.ts';

/** Meters along each side of a tile of trees, and of a cell: a cell holds one tree at most. */
export const TILE = 120;
export const TREE_CELL = 6;
/** Floats per tree: its place and its size, then its turn, a tint, its model and a random number. */
export const TREE_FLOATS = 8;
/** Trees grow this far above the sea at least, and where it is this warm at least. */
const SHORE = 2.5;
const TREE_LINE = 0.14;
/** The ground may rise or fall this much over 2 m: steeper slopes stay bare. */
const STEEPEST = 1.7;
/** No tree grows this near the start, where the earlier series built: around (96, 166). */
const HOME = { x: 96, z: 166, radius: 45 };
/** Meters across a glade or a stand of trees. */
const GLADE = 70;

/**
 * How much of the ground trees cover at a place, from 0 to 1: what its biomes say, less
 * in the glades that a noise opens in every forest.
 */
export function treeCover(x: number, z: number, biomes: Float32Array | number[]): number {
  let cover = 0;
  for (let b = 0; b < BIOME_COUNT; b += 1) cover += BIOMES[b].trees.cover * biomes[b];
  const glade = Math.min(Math.max((patchNoise(x / GLADE, z / GLADE, 99) - 0.3) / 0.2, 0), 1);
  return cover * glade;
}

const speciesOf = (name: string) => SPECIES.findIndex((species) => species.name === name);

/**
 * The trees of a tile: TREE_FLOATS numbers each. Whether a cell holds a tree, of which
 * species and how big, follows from the cell's numbers alone, so a tile comes out the
 * same whenever it is asked for.
 */
export function plantTile(tileX: number, tileZ: number): Float32Array {
  const trees: number[] = [];
  const biomes = new Float32Array(BIOME_COUNT);
  const shares = new Float32Array(SPECIES.length);
  const cells = TILE / TREE_CELL;
  for (let k = 0; k < cells; k += 1) {
    for (let i = 0; i < cells; i += 1) {
      const cellX = tileX * cells + i;
      const cellZ = tileZ * cells + k;
      const random = (n: number) => hash(cellX, cellZ, 20 + n);
      // Somewhere in the middle of its cell, so that two trees never stand trunk to trunk.
      const x = (cellX + 0.15 + random(0) * 0.7) * TREE_CELL;
      const z = (cellZ + 0.15 + random(1) * 0.7) * TREE_CELL;
      const ground = surfaceHeight(x, z);
      if (ground < SEA + SHORE || Math.hypot(x - HOME.x, z - HOME.z) < HOME.radius) continue;
      const climate = climateAt(x, z);
      const temperature = climate.temperature - cooling(ground);
      if (temperature < TREE_LINE) continue;
      biomeWeights(temperature, climate.moisture, biomes);
      if (random(2) >= treeCover(x, z, biomes)) continue;
      if (Math.abs(surfaceHeight(x + 2, z) - ground) > STEEPEST || Math.abs(surfaceHeight(x, z + 2) - ground) > STEEPEST) continue;

      // The species: one random number picks among those the biomes list, by their shares.
      shares.fill(0);
      let size = 0;
      for (let b = 0; b < BIOME_COUNT; b += 1) {
        if (biomes[b] === 0) continue;
        size += BIOMES[b].trees.size * biomes[b];
        for (const [name, share] of Object.entries(BIOMES[b].trees.kinds)) shares[speciesOf(name)] += share * biomes[b];
      }
      let pick = random(3);
      let species = shares.findIndex((share) => share > 0);
      for (let s = 0; s < shares.length; s += 1) {
        pick -= shares[s];
        if (shares[s] > 0 && pick < 0) {
          species = s;
          break;
        }
      }
      const model = species * VARIANTS + Math.floor(random(4) * VARIANTS);
      // On the ground as it really is there, overhangs and all, and a little into it.
      trees.push(x, groundLevel(x, z) - 0.25, z, size * (0.75 + random(5) * 0.5), random(6) * Math.PI * 2, random(7), model, random(8));
    }
  }
  return new Float32Array(trees);
}

Tiles from a worker

The rule is asked tile by tile: a tile is 120 m along each side and holds 20 by 20 cells. Each cell costs a few noise lookups, and each tree a walk down the density, so the tiles are planted in a worker of their own, which answers with the list of a tile's trees. Create src/treeWorker.ts:

src/treeWorker.ts
import { plantTile } from './treeRule.ts';

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

export interface TileResult extends TileJob {
  /** The tile's trees, TREE_FLOATS numbers each. */
  trees: Float32Array;
}

/** Plants the tiles it is asked for, one after the other. */
self.onmessage = (event: MessageEvent<TileJob>) => {
  const { x, z } = event.data;
  const result: TileResult = { x, z, trees: plantTile(x, z) };
  self.postMessage(result, { transfer: [result.trees.buffer] });
};

The forest

The class Forest keeps the tiles around the camera and draws their trees. Drawing is where the instancing pays off. There are eighteen meshes, one per model, and each is drawn once for every tree of its kind that is near enough: a whole forest in eighteen draw calls. A mesh per chunk, as the grass has it, would not do here: with eighteen models, that would be eighteen meshes per chunk.

So the instances are sorted out anew whenever something changes: a tile arrived, or the camera has moved 8 m since the last time. Sorting out means going through the trees of all the tiles, copying those within range into the list of their model, and handing each model its list. That is a few thousand trees at most, and a matter of a millisecond.

The forest is also a solid, as the rubble of the building series is: it answers the question for the nearest surface to a point. A trunk is a standing cylinder, as thick as the model's trunk at the ground and half as high as the tree, where the crown begins. To find the trunks near a point without asking every tree, each tile sorts its trees into a grid of 8 m cells the first time it is asked, and only the nine cells around the point are looked at. Create src/forest.ts:

src/forest.ts
import type { Buffer, Mesh, Scene, ShaderMaterial, Vector3 } from '@babylonjs/core/pure';
import { instanceBuffer } from './chunkPlants.ts';
import type { Solid, Surface } from './solids.ts';
import { createTreeMesh } from './treeMaterial.ts';
import { TILE, TREE_FLOATS } from './treeRule.ts';
import type { TreeModel } from './trees.ts';
import type { TileJob, TileResult } from './treeWorker.ts';

/** How far from the camera trees are drawn, in meters, and where they start to fade out. */
export const TREE_RANGE = 130;
export const TREE_FADE = 110;
/** The trees are sorted out again once the camera has moved this far. */
const STEP = 8;
/** A trunk is solid up to this share of the tree's height, where the crown begins. */
const TRUNK = 0.5;
/** Meters along each side of a cell of a tile's grid, which finds the trees near a point. */
const GRID = 8;

interface Tile {
  /** TREE_FLOATS numbers per tree, or null while the worker plants the tile. */
  trees: Float32Array | null;
  /** Which trees stand in each cell of the grid, as their numbers in the list. */
  grid: Map<number, number[]> | null;
}

const tileKey = (x: number, z: number) => `${x},${z}`;

/**
 * The trees around the camera. A worker plants them tile by tile, and every model's mesh
 * is drawn once for each tree of its kind that is near enough. Their trunks are solid.
 */
export class Forest implements Solid {
  /** How many trees are drawn. */
  shown = 0;
  private readonly tiles = new Map<string, Tile>();
  private readonly meshes: Mesh[];
  private readonly buffers: (Buffer | null)[];
  private readonly worker = new Worker(new URL('./treeWorker.ts', import.meta.url), { type: 'module' });
  /** Where the camera was when the trees were last sorted out, or null if they must be now. */
  private sorted: { x: number; z: number } | null = null;
  private readonly models: TreeModel[];

  constructor(scene: Scene, models: TreeModel[], material: ShaderMaterial) {
    this.models = models;
    this.meshes = models.map((model) => createTreeMesh(scene, model, material));
    this.buffers = models.map(() => null);
    for (const mesh of this.meshes) mesh.setEnabled(false);
    this.worker.onmessage = (event: MessageEvent<TileResult>) => {
      const tile = this.tiles.get(tileKey(event.data.x, event.data.z));
      // A tile that was dropped while it was planted is not wanted any more.
      if (!tile) return;
      tile.trees = event.data.trees;
      this.sorted = null;
    };
  }

  /** Once a frame: asks for the tiles in range, drops those far away, and sorts out the trees. */
  update(focus: Vector3): void {
    const reach = Math.ceil(TREE_RANGE / TILE);
    const [centerX, centerZ] = [Math.floor(focus.x / TILE), Math.floor(focus.z / TILE)];
    for (let z = centerZ - reach; z <= centerZ + reach; z += 1) {
      for (let x = centerX - reach; x <= centerX + reach; x += 1) {
        if (this.tiles.has(tileKey(x, z))) continue;
        this.tiles.set(tileKey(x, z), { trees: null, grid: null });
        this.worker.postMessage({ x, z } satisfies TileJob);
      }
    }
    for (const key of this.tiles.keys()) {
      const [x, z] = key.split(',').map(Number);
      if (Math.max(Math.abs(x - centerX), Math.abs(z - centerZ)) > reach + 1) this.tiles.delete(key);
    }
    if (!this.sorted || Math.hypot(focus.x - this.sorted.x, focus.z - this.sorted.z) > STEP) this.sort(focus);
  }

  /** Hands every model the trees of its kind that are in range, as its instances. */
  private sort(focus: Vector3): void {
    this.sorted = { x: focus.x, z: focus.z };
    const lists: number[][] = this.models.map(() => []);
    // A little further than they are drawn, for the way to the next sorting.
    const range = TREE_RANGE + STEP;
    for (const { trees } of this.tiles.values()) {
      if (!trees) continue;
      for (let t = 0; t < trees.length; t += TREE_FLOATS) {
        if (Math.hypot(trees[t] - focus.x, trees[t + 2] - focus.z) > range) continue;
        for (let f = 0; f < TREE_FLOATS; f += 1) lists[trees[t + 6]].push(trees[t + f]);
      }
    }
    this.shown = 0;
    lists.forEach((list, model) => {
      this.buffers[model]?.dispose();
      this.buffers[model] = list.length > 0 ? instanceBuffer(this.meshes[model], new Float32Array(list)) : null;
      this.meshes[model].setEnabled(list.length > 0);
      this.shown += list.length / TREE_FLOATS;
    });
  }

  /** The nearest trunk to a point, if one is within `reach` meters. */
  nearest(x: number, y: number, z: number, reach: number): Surface | null {
    let nearest: Surface | null = null;
    // The trees of the cells around the point, each in the tile it lies in: no trunk is
    // thicker than a cell.
    for (let k = -1; k <= 1; k += 1) {
      for (let i = -1; i <= 1; i += 1) {
        const [cellX, cellZ] = [x + i * GRID, z + k * GRID];
        const tile = this.tiles.get(tileKey(Math.floor(cellX / TILE), Math.floor(cellZ / TILE)));
        if (!tile?.trees) continue;
        const { trees } = tile;
        tile.grid ??= gridOf(trees);
        for (const t of tile.grid.get(gridKey(cellX, cellZ)) ?? []) {
          const model = this.models[trees[t + 6]];
          const size = trees[t + 3];
          if (y < trees[t + 1] || y > trees[t + 1] + model.height * size * TRUNK) continue;
          // A trunk is a standing cylinder: the way out of it is level.
          const [dx, dz] = [x - trees[t], z - trees[t + 2]];
          const apart = Math.hypot(dx, dz) || 0.001;
          const distance = apart - model.girth * size;
          if (distance < reach && (!nearest || distance < nearest.distance)) {
            nearest = { distance, normal: [dx / apart, 0, dz / apart] };
          }
        }
      }
    }
    return nearest;
  }
}

const gridKey = (x: number, z: number) => Math.floor(x / GRID) * 65536 + Math.floor(z / GRID);

/** Sorts a tile's trees into the cells of a grid. */
function gridOf(trees: Float32Array): Map<number, number[]> {
  const grid = new Map<number, number[]>();
  for (let t = 0; t < trees.length; t += TREE_FLOATS) {
    const key = gridKey(trees[t], trees[t + 2]);
    if (!grid.has(key)) grid.set(key, []);
    grid.get(key)!.push(t);
  }
  return grid;
}
  • update() asks the worker for every tile within two tiles of the camera's that it doesn't have, and drops those further than three. A tile is in the map from the moment it is asked for, with trees: null, so that it is not asked for twice.

  • sort() takes trees a step further than they are drawn, so that none is missing before the next sorting. A model without trees is switched off.

  • nearest() looks up each of the nine cells in the tile it lies in: a trunk at a tile's edge is found from the other side too.

Fading out

Trees are drawn up to 130 m from the camera. A tree that popped into view at that distance would catch the eye every time, and blending it in would need the trees sorted from back to front. There is a cheaper way to fade something that needs no blending at all: draw only some of its pixels. A function gives every pixel of the screen a number from 0 to 1, in a pattern too fine to see. A tree that has faded to 0.3 keeps the pixels whose number is below 0.3 and throws the others away. From 110 m on, a tree thins out like that until it is gone at 130 m.

The vertex shader works out how far a tree has faded, from the distance of its foot, so that the whole tree fades as one. 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;

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);
  vec4 worldPosition = world * vec4(place.xyz + turn * position * place.w, 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;
}

In src/tree.fragment.glsl, add varying float vFade; after the other varyings. Then replace the line void main() { with the grain and the test:

src/tree.fragment.glsl
// A number from 0 to 1 that differs from pixel to pixel, in a pattern too fine to see.
float grain() {
  return fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
}

void main() {
  // A fading tree is drawn with only some of its pixels: fewer the more it has faded.
  if (vFade < 1.0 && vFade <= grain()) discard;

The material takes the two distances and hands them on. In src/treeMaterial.ts, import Vector2 from Babylon.js, and replace createTreeMaterial():

src/treeMaterial.ts
/**
 * The trees' material: bark and leaves from one texture array, lit by the sun and the sky.
 * Trees fade out between `fadeFrom` and `range` meters from the camera.
 */
export function createTreeMaterial(scene: Scene, options: FogOptions & { fadeFrom: number; range: number }): ShaderMaterial {
  const layers = new RawTexture2DArray(
    paintTreeLayers(),
    TREE_TEXTURE,
    TREE_TEXTURE,
    TREE_LAYERS.length,
    Constants.TEXTUREFORMAT_RGBA,
    scene,
    true,
    false,
    Texture.TRILINEAR_SAMPLINGMODE,
  );
  // The bark goes around and up the trunk without an end.
  layers.wrapU = Texture.WRAP_ADDRESSMODE;
  layers.wrapV = Texture.WRAP_ADDRESSMODE;
  const material = new ShaderMaterial(
    'trees',
    scene,
    { vertexSource, fragmentSource },
    {
      attributes: ['position', 'normal', 'paint', 'place', 'look'],
      uniforms: ['world', 'viewProjection', ...LIGHT_UNIFORMS, 'firstLeaves', 'treeRange'],
      samplers: ['layers'],
    },
  );
  material.setTexture('layers', layers);
  setLight(material, options);
  material.setVector2('treeRange', new Vector2(options.fadeFrom, options.range));
  material.setFloat('firstLeaves', TREE_LAYERS.findIndex((name) => name.includes('leaves') || name.includes('needles')));
  // A spray of leaves is seen from both sides.
  material.backFaceCulling = false;
  return material;
}

Shade on the ground

The series has no shadows, and trees without any look as if they were stuck onto the ground. Real shadows are a topic of their own, but a forest doesn't need them: its floor is in the shade everywhere. So the ground gets darker by how much of it trees cover, up to 30 %, and the glades stay in the sun.

The cover travels with the climate: the two numbers per vertex become three. In src/chunks.ts, import BIOME_COUNT, biomeWeights and cooling from ./climate.ts along with climateAt, and treeCover from ./treeRule.ts. The comment on ChunkMesh can say that there are three numbers now. In buildChunk(), replace the loop over the vertices and the lines before it:

src/chunks.ts
// Meters below the generated ground, for the material: soil first, then rock. And the
// climate, for the biome.
const { positions } = mesh;
const depths = new Float32Array(positions.length / 3);
const climates = new Float32Array(depths.length * 3);
const biomes = new Float32Array(BIOME_COUNT);
for (let i = 0; i < depths.length; i += 1) {
  const x = origin.x + positions[i * 3];
  const y = origin.y + positions[i * 3 + 1];
  const z = origin.z + positions[i * 3 + 2];
  depths[i] = surfaceHeight(x, z) - y;
  const { temperature, moisture } = climateAt(x, z);
  biomeWeights(temperature - cooling(y), moisture, biomes);
  climates.set([temperature, moisture, treeCover(x, z, biomes)], i * 3);
}

In src/world.ts, the attribute has three numbers: mesh.setVerticesData('climate', data.climates, false, 3);. The same in src/farView.ts: ground.setVerticesData('climate', data.ground.climates, false, 3);. The far worker works the cover out for its vertices. In src/farWorker.ts, add the same imports as in src/chunks.ts, and replace the start of the ground's mesh:

src/farWorker.ts
const climates = new Float32Array(RINGS * SEGMENTS * 3);
const biomes = new Float32Array(BIOME_COUNT);
const ground: FarMesh = {
  ...ringMesh(growing(INNER, RINGS), (px, pz, vertex) => {
    const height = surfaceHeight(x + px, z + pz);
    const { temperature, moisture } = climateAt(x + px, z + pz);
    biomeWeights(temperature - cooling(height), moisture, biomes);
    climates.set([temperature, moisture, treeCover(x + px, z + pz, biomes)], vertex * 3);
    return height - SINK;
  }),
  climates,

In src/terrain.vertex.glsl, the attribute becomes attribute vec3 climate; and the varying varying vec3 vClimate;. In src/terrain.fragment.glsl, the varying changes the same way. The climate is still read as vClimate.x and vClimate.y. After the line that darkens the wet shore, add:

src/terrain.fragment.glsl
// Under trees the ground lies in their shade.
color *= 1.0 - 0.3 * vClimate.z;

The grass and the small plants stand in the same shade. Each spot learns how bright it is, and the plants take that along in their sixth number, where the light goes. In src/scatter.ts, import treeCover from ./treeRule.ts. Add a field to Spot, and in eachSpot(), after the line that works out the biomes, set it:

src/scatter.ts
/** How bright it is there: less than 1 in the shade of trees. */
shade: number;

spot.shade = 1 - 0.3 * treeCover(origin.x + spot.x, origin.z + spot.z, spot.biomes);

The spot that eachSpot() makes at its start gets shade: 1 as its last entry. In scatterGrass() and in add() of scatterPlants(), the sixth of the values was a 1, a place kept for the light: put spot.shade there. And pack() no longer writes the light over that number, but multiplies it in. Replace its comment and the two lines after it:

src/scatter.ts
// The light as the vertices of the mesh get it. The plant's sixth number, which holds
// its shade so far, is multiplied by it.
const lights = lightAt(light, origin, positions, normals);
plants.forEach((plant, p) => (plant.values[5] *= lights[p]));

Into the world

The nursery has done its work: delete src/nursery.ts and its import in src/main.ts. Import Forest, TREE_FADE and TREE_RANGE from ./forest.ts, and replace the lines that grew the trees and planted the nursery:

src/main.ts
// The trees: every species in a few variants, grown once, and drawn wherever the forest
// has a tree of their kind.
const treeMaterial = createTreeMaterial(scene, { ...fog, fadeFrom: TREE_FADE, range: TREE_RANGE });
const forest = new Forest(scene, growModels(), treeMaterial);

The solids so far ask the rubble for more solids. Now they ask the forest too. Pieces set solids.others when it was made, so right after the line that makes pieces, set it again. A generator function hands out one solid after the other without building a list each time it is asked:

src/main.ts
// The trunks are solid too, for the player and for what falls: the solids ask the rubble
// and the forest.
solids.others = function* () {
  yield* pieces.rubble;
  yield forest;
};

Every frame, after plants.update(camera.position);, the forest follows the camera: forest.update(camera.position);. And the HUD counts the trees: its second line ends with , ${forest.shown} trees after the plants.

Try it

Around the start the meadow is open, with single oaks and birches further out. Press N to fly to the broadleaf forest, come down with Q and press F to walk. The trunks stop you, the ground between them is darker than the meadow's, and the grass and the ferns are too. Walk until the trees open into a glade: sunlit ground, with the forest standing around it. Then fly up and look around. The forest ends in a ring 130 m from you, where the trees thin out into their grain, and beyond it the ground is bare: part 10 carries the forest on to the horizon.

Press N again for the conifers, and on through the tundra with its small pines and birches, the savanna with its acacias and the desert with its cacti. On the way, look at a mountain: the trees climb its sides and stop below the snow.

A broadleaf forest from above. Around the camera every tree is a mesh. Further out the trees thin into a grain and are gone: the forest ends where they fade out.
Forests. Click, then press N to fly to the broadleaf forest, Q to come down and F to walk among the trees. N again goes on to the conifers, the tundra, the savanna and the desert. 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.