Skip to content

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

Part 7: Growing a tree

Grow trees as skeletons: a trunk, limbs that reach for the outline of a crown, and branches off the limbs. Wrap them in tubes, paint four barks in code, and get six species, from oak to cactus, out of one set of numbers.

Quest objectives

  • Describe a species of tree with a handful of numbers and a crown outline
  • Grow a trunk, limbs and branches as bent tubes, the same for the same seed
  • Mesh the tubes with rings that do not twist, and close thick ends
  • Paint bark textures in code and wrap them around the wood
  • Draw the trees as instances, like the grass, and stand them in a nursery

The land has grass, flowers and reeds now, and nothing taller than a bush. This part and the next make trees, and they make them the way the terrain and the textures are made: in code, from a few numbers. A tree is grown as a skeleton, the lines its wood follows: a trunk, limbs off the trunk, branches off the limbs. Around each line goes a tube, and on the tubes goes bark. This part ends with bare trees of six species in a nursery next to the start. Part 8 gives them their leaves, and part 9 plants them as forests.

A crown to reach for

Rules that let a tree branch freely, one fork after the other, grow something tree-like, but it is hard to make them grow an oak rather than a spruce. So the growing here starts from the other end: from the outline of the crown. Each species has a function that says how far its crown reaches at every height, from 0 at the crown's bottom to 1 at its top: a dome for an oak, an egg for a birch, a cone for a spruce, an umbrella for an acacia. Every limb then reaches for a point on that outline. Whatever the random numbers do to a single limb, the tree as a whole keeps the shape of its species.

The rest of a species is a handful of numbers, all of them shares of the tree's height, so that a small tree is a big one scaled down:

  • girth is the trunk's radius at the ground, and taper how much of it is left at the top.

  • leader says whether the trunk runs up to the very top, as in a spruce, or ends where the limbs part, as in an oak.

  • bare is the share of the height below the crown, and spread how far the crown reaches at most.

  • limbs and branches count the limbs off the trunk and the branches off each limb.

  • rise says how steeply a limb climbs on its way out, and droop how it bends: below 0 it arches up and hangs at its tip, above 0 it sags and turns up at the end.

A cactus fits in the same table: a thick trunk that keeps its girth, two limbs that sag far and then turn straight up, and no branches.

Growing the skeleton

Every part of the wood is a Limb: a list of points and a radius at each of them. The trunk goes up in eight steps and wanders a little sideways on its way, less if it is a leader. It thins out toward the top, and in its lowest eighth it is up to half again as thick, where a real trunk spreads into its roots.

The limbs come next. Limb number i ends at the share (i + 0.5) / limbs of the crown's height, so the lowest limb ends near the crown's bottom and the highest near its top, and it reaches as far out as the outline says there, give or take a fifth. From one limb to the next, the direction turns by the golden angle, about 137.5°. That is how many plants set their leaves, and for the same reason: no two limbs end up above each other, however many there are.

Where a limb starts on the trunk follows from where it ends: the more steeply the species' limbs rise, the further down it starts, but never below the crown. Between start and tip the limb is a quadratic Bézier curve: a curve from one point to another that bends toward a third, the pull point. The pull point lies half way out. Raised above the straight line, it makes the limb arch up and come down to its tip, like a spruce's. Lowered, it makes the limb sag and turn up, like a cactus's arm.

The branches grow off the outer part of each limb, to the left and to the right in turn, shorter the further out they start. They are curves too, with only two segments each: they are thin, and there are many of them.

All the random numbers come from seededRandom(), so the same seed grows the same tree. Three seeds per species make three variants: eighteen different trees in all, grown once when the page loads.

Tubes that don't twist

The mesh is a tube around every limb: a ring of vertices around each of its points, and two triangles between each pair of neighbors on two rings. The trunk has seven sides, a limb four and a branch three. More would not show: the bark hides the corners, and from part 9 on there will be hundreds of trees in view.

A ring lies across the way the limb goes at its point, but that leaves it free to turn about the limb, and if each ring picked its first corner on its own, the tube would be wrung like a towel between them. So the first corner is handed on: its direction on one ring is taken to the next, and whatever part of it points along the limb there is taken off. The corner stays as near as it can to where it was.

A ring has one corner more than it has sides. The first and the last are at the same place, but at the two ends of the texture, which goes twice around the tube; up the tube, it repeats every two meters. A limb that ends thicker than 3 cm gets a round tip, a single vertex a little beyond its last ring: a cactus's arm, or the top of an oak's trunk. A branch ends as a twig, too thin to need one.

Each vertex also carries four numbers under the name paint: where on the texture it is, which layer of the texture array it shows, and a shade, which is 1 until the leaves of part 8 cast one. Create src/trees.ts:

src/trees.ts
import { seededRandom } from './random.ts';

export type Vec = [number, number, number];

const add = (a: Vec, b: Vec, times = 1): Vec => [a[0] + b[0] * times, a[1] + b[1] * times, a[2] + b[2] * times];
const subtract = (a: Vec, b: Vec): Vec => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const dot = (a: Vec, b: Vec) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a: Vec, b: Vec): Vec => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
const normalize = (a: Vec): Vec => {
  const length = Math.hypot(...a) || 1;
  return [a[0] / length, a[1] / length, a[2] / length];
};
const UP: Vec = [0, 1, 0];

/**
 * A point on the curve from `from` to `to` that bends toward `pull`, at a share `t` of the
 * way: a quadratic Bézier curve.
 */
function curve(from: Vec, pull: Vec, to: Vec, t: number): Vec {
  const a = (1 - t) * (1 - t);
  const b = 2 * (1 - t) * t;
  return [0, 1, 2].map((axis) => from[axis] * a + pull[axis] * b + to[axis] * t * t) as Vec;
}

/** The layers of the trees' texture array: the barks. */
export const TREE_LAYERS = ['oak bark', 'birch bark', 'conifer bark', 'cactus skin'] as const;

type Layer = (typeof TREE_LAYERS)[number];

/** The outlines of crowns: how far a crown reaches at a share `t` of the way from its bottom to its top, from 0 to 1. */
const OUTLINES = {
  /** Widest in the middle and broad on top: an oak. */
  dome: (t: number) => Math.sin(Math.PI * t ** 0.8) ** 0.55,
  /** Widest low down, round on top: a birch. */
  egg: (t: number) => Math.sin(Math.PI * t ** 0.65) ** 0.7,
  /** A cone up to the tip: a spruce. */
  cone: (t: number) => 1 - t * 0.95,
  /** Narrow below and spread out flat on top: an acacia, or an old pine. */
  umbrella: (t: number) => Math.min(0.2 + t * 1.3, 1) * Math.sqrt(1 - t ** 5),
};

/** What makes a kind of tree. Shares are of the tree's height. */
export interface Species {
  name: string;
  /** Meters, at least and at most. */
  height: [number, number];
  /** The trunk's radius at the ground, as a share, and how much of it is left at the top. */
  girth: number;
  taper: number;
  /** Whether the trunk runs up to the very top, or ends where the crown's limbs part. */
  leader: boolean;
  /** The share below the crown, where the trunk is bare. */
  bare: number;
  /** How far the crown reaches from the trunk at most, as a share, and its outline. */
  spread: number;
  outline: (t: number) => number;
  /** How many limbs grow off the trunk, and how many branches off each limb. */
  limbs: number;
  branches: number;
  /** How steeply a limb rises on its way out: 0 is level, 1 is 45°. */
  rise: number;
  /** How a limb bends: below 0 it arches up and hangs at its tip, above 0 it sags and turns up. */
  droop: number;
  bark: Layer;
}

export const SPECIES: Species[] = [
  {
    name: 'oak', height: [9, 13], girth: 0.036, taper: 0.3, leader: false, bare: 0.28, spread: 0.42, outline: OUTLINES.dome,
    limbs: 7, branches: 3, rise: 0.55, droop: 0.1, bark: 'oak bark',
  },
  {
    name: 'birch', height: [9, 13], girth: 0.02, taper: 0.12, leader: true, bare: 0.3, spread: 0.2, outline: OUTLINES.egg,
    limbs: 11, branches: 2, rise: 1, droop: -0.3, bark: 'birch bark',
  },
  {
    name: 'spruce', height: [13, 19], girth: 0.022, taper: 0.06, leader: true, bare: 0.12, spread: 0.18, outline: OUTLINES.cone,
    limbs: 24, branches: 1, rise: 0.1, droop: -0.35, bark: 'conifer bark',
  },
  {
    name: 'pine', height: [11, 15], girth: 0.026, taper: 0.2, leader: true, bare: 0.55, spread: 0.3, outline: OUTLINES.umbrella,
    limbs: 8, branches: 3, rise: 0.35, droop: 0.15, bark: 'conifer bark',
  },
  {
    name: 'acacia', height: [6, 8.5], girth: 0.036, taper: 0.35, leader: false, bare: 0.5, spread: 0.6, outline: OUTLINES.umbrella,
    limbs: 6, branches: 3, rise: 0.8, droop: 0.05, bark: 'oak bark',
  },
  {
    name: 'cactus', height: [3, 5.5], girth: 0.075, taper: 0.8, leader: true, bare: 0.3, spread: 0.24, outline: () => 1,
    limbs: 2, branches: 0, rise: 1.6, droop: 1.3, bark: 'cactus skin',
  },
];

/** How many different trees are grown of each species. */
export const VARIANTS = 3;

/** A part of the tree's wood: a bent tube along `points`, as thick as `radii` at each of them. */
export interface Limb {
  points: Vec[];
  radii: number[];
  /** 0 is the trunk, 1 a limb off it, 2 a branch off a limb. */
  level: number;
}

/** A grown tree, before it is a mesh. */
export interface Tree {
  species: Species;
  height: number;
  limbs: Limb[];
}

const TRUNK_SEGMENTS = 8;
const LIMB_SEGMENTS = 5;
const BRANCH_SEGMENTS = 2;
const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));

/** Where a limb is at a share `t` of its length, between its points. */
function along(limb: Limb, t: number): { point: Vec; radius: number; direction: Vec } {
  const last = limb.points.length - 1;
  const segment = Math.min(Math.floor(t * last), last - 1);
  const within = t * last - segment;
  const [from, to] = [limb.points[segment], limb.points[segment + 1]];
  return {
    point: add(from, subtract(to, from), within),
    radius: limb.radii[segment] + (limb.radii[segment + 1] - limb.radii[segment]) * within,
    direction: normalize(subtract(to, from)),
  };
}

/** Grows a tree of a species. The same seed grows the same tree. */
export function growTree(species: Species, seed: number): Tree {
  const random = seededRandom(seed);
  const between = (low: number, high: number) => low + (high - low) * random();
  const height = between(...species.height);
  const limbs: Limb[] = [];
  const crownBottom = height * species.bare;

  // The trunk: up to the top, or to where the crown's limbs part. It wanders a little
  // on its way, and is thicker right at the ground.
  const top = species.leader ? height : crownBottom + (height - crownBottom) * 0.6;
  const base = species.girth * height;
  const wander = species.leader ? 0.008 : 0.03;
  const trunk: Limb = { points: [], radii: [], level: 0 };
  let [x, z] = [0, 0];
  for (let i = 0; i <= TRUNK_SEGMENTS; i += 1) {
    const t = i / TRUNK_SEGMENTS;
    trunk.points.push([x, top * t, z]);
    trunk.radii.push(base * (1 - (1 - species.taper) * t) * (1 + 0.5 * Math.max(1 - t * 8, 0)));
    x += between(-1, 1) * wander * height;
    z += between(-1, 1) * wander * height;
  }
  limbs.push(trunk);

  // The limbs: each reaches for a point of the crown's outline. The lowest ends at the
  // crown's bottom, the highest at its top, and they go around the trunk by the golden
  // angle, so that no two grow above each other.
  for (let i = 0; i < species.limbs; i += 1) {
    const share = (i + 0.5) / species.limbs;
    const reach = species.outline(share) * species.spread * height * between(0.8, 1.2);
    const tipHeight = crownBottom + (height - crownBottom) * share * 0.97;
    const turn = i * GOLDEN_ANGLE + between(-0.3, 0.3);
    const out: Vec = [Math.cos(turn), 0, Math.sin(turn)];
    // It starts lower on the trunk the more steeply it rises, but never below the crown.
    const start = Math.min(Math.max(tipHeight - species.rise * reach, crownBottom * 0.85), top * 0.98);
    const from = along(trunk, start / top);
    const tip = add([from.point[0], tipHeight, from.point[2]], out, reach);
    const pull = add([from.point[0], (start + tipHeight) / 2 - species.droop * reach * 0.5, from.point[2]], out, reach * 0.5);
    const thickness = Math.min(from.radius * 0.6, base * 0.4);
    const limb: Limb = { points: [], radii: [], level: 1 };
    for (let s = 0; s <= LIMB_SEGMENTS; s += 1) {
      const t = s / LIMB_SEGMENTS;
      limb.points.push(curve(from.point, pull, tip, t));
      // A cactus keeps its girth to the end; a limb of wood thins out to a twig.
      limb.radii.push(thickness * (1 - (1 - species.taper) * t ** 0.8) + 0.012);
    }
    limbs.push(limb);

    // The branches: off the outer part of the limb, to the left and the right in turn.
    for (let b = 0; b < species.branches; b += 1) {
      const t = 0.35 + (0.55 * (b + between(0, 0.6))) / species.branches;
      const fork = along(limb, t);
      const sideways = normalize(cross(fork.direction, UP));
      const way = normalize(add(add(fork.direction, sideways, b % 2 ? 1.5 : -1.5), UP, between(-0.1, 0.3)));
      const length = reach * 0.42 * (1.15 - t * 0.5);
      const end = add(add(fork.point, way, length), UP, -species.droop * length * 0.3);
      const bend = add(add(fork.point, way, length * 0.5), UP, length * 0.12);
      const branch: Limb = { points: [], radii: [], level: 2 };
      for (let s = 0; s <= BRANCH_SEGMENTS; s += 1) {
        branch.points.push(curve(fork.point, bend, end, s / BRANCH_SEGMENTS));
        branch.radii.push(fork.radius * 0.6 * (1 - s / BRANCH_SEGMENTS) + 0.012);
      }
      limbs.push(branch);
    }
  }
  return { species, height, limbs };
}

/**
 * A tree's mesh. Each vertex has four numbers in `paints`: u, v, the texture's layer, and a
 * shade, which is 1 until the tree has leaves to shade it.
 */
export interface TreeMesh {
  positions: Float32Array;
  normals: Float32Array;
  indices: Uint32Array;
  paints: Float32Array;
}

/** A tree as it is drawn: its mesh, and its measures in meters. */
export interface TreeModel {
  species: Species;
  mesh: TreeMesh;
  height: number;
  /** The trunk's radius at the ground. */
  girth: number;
}

/** Sides of the tubes around the trunk, the limbs and the branches. */
const SIDES = [7, 4, 3];
/** Meters of bark that the texture covers, up a limb. */
const BARK_TILE = 2;

/** Makes the mesh of a grown tree: a tube around every limb. */
export function meshTree(tree: Tree): TreeModel {
  const { species, height } = tree;
  const positions: number[] = [];
  const normals: number[] = [];
  const paints: number[] = [];
  const indices: number[] = [];
  const bark = TREE_LAYERS.indexOf(species.bark);

  const vertex = (point: Vec, normal: Vec, u: number, v: number, layer: number) => {
    positions.push(...point);
    normals.push(...normal);
    paints.push(u, v, layer, 1);
    return positions.length / 3 - 1;
  };

  for (const limb of tree.limbs) {
    const sides = SIDES[limb.level];
    const last = limb.points.length - 1;
    let side: Vec = [1, 0, 0];
    let length = 0;
    const rings: number[] = [];
    for (let p = 0; p <= last; p += 1) {
      // The ring around this point lies across the limb's way here. Its first corner
      // stays as near as it can to the first corner of the ring before, so that the
      // tube doesn't twist.
      const way = normalize(subtract(limb.points[Math.min(p + 1, last)], limb.points[Math.max(p - 1, 0)]));
      side = normalize(subtract(side, [way[0] * dot(side, way), way[1] * dot(side, way), way[2] * dot(side, way)]));
      const other = cross(way, side);
      if (p > 0) length += Math.hypot(...subtract(limb.points[p], limb.points[p - 1]));
      rings.push(positions.length / 3);
      // One corner more than sides: the first and the last are at the same place, at
      // both ends of the bark's texture.
      for (let s = 0; s <= sides; s += 1) {
        const angle = (s / sides) * Math.PI * 2;
        const out = add([side[0] * Math.cos(angle), side[1] * Math.cos(angle), side[2] * Math.cos(angle)], other, Math.sin(angle));
        vertex(add(limb.points[p], out, limb.radii[p]), out, (s / sides) * 2, length / BARK_TILE, bark);
      }
    }
    for (let p = 0; p < last; p += 1) {
      for (let s = 0; s < sides; s += 1) {
        const [a, b] = [rings[p] + s, rings[p + 1] + s];
        indices.push(a, b, a + 1, a + 1, b, b + 1);
      }
    }
    // A thick end is closed with a round tip: a cactus's arm doesn't end in a twig.
    if (limb.radii[last] > 0.03) {
      const way = normalize(subtract(limb.points[last], limb.points[last - 1]));
      const tip = vertex(add(limb.points[last], way, limb.radii[last] * 0.7), way, 1, length / BARK_TILE, bark);
      for (let s = 0; s < sides; s += 1) indices.push(rings[last] + s, tip, rings[last] + s + 1);
    }
  }

  return {
    species,
    height,
    girth: tree.limbs[0].radii[0],
    mesh: {
      positions: new Float32Array(positions),
      normals: new Float32Array(normals),
      indices: new Uint32Array(indices),
      paints: new Float32Array(paints),
    },
  };
}

/** Every tree the world has: VARIANTS of each species, in the order of SPECIES. */
export function growModels(): TreeModel[] {
  return SPECIES.flatMap((species, s) => Array.from({ length: VARIANTS }, (_, variant) => meshTree(growTree(species, s * 100 + variant + 1))));
}
  • along() finds the point, the radius and the direction of a limb at any share of its length, between its points. The limbs use it to start on the trunk, the branches to start on a limb.

  • In growTree(), pull is the Bézier curve's third point, and curve() walks along the curve.

  • In meshTree(), side is the direction of a ring's first corner. Taking off way * dot(side, way) leaves the part of it that lies across the limb.

  • growModels() grows and meshes every variant of every species, in the order of SPECIES. The number of a model is its species' number times VARIANTS plus the variant: part 9 counts on that.

Bark

The barks are painted like the ground's textures in the terrain series, pixel by pixel from tiling noise, into the layers of one texture array. What makes them bark is the shape of the noise. tilingNoise(20, 3) repeats twenty times across the texture and three times up it, so its ups and downs are long streaks up the trunk: the furrows of an oak. Five across and 48 up gives the dark marks that run around a birch. The conifers get reddish plates with dark gaps where a noise crosses 0, and the cactus eight ribs around its trunk, from a cosine, with pale spines along their crests. Create src/treeTextures.ts:

src/treeTextures.ts
import { hex, layeredNoise, mix, shade, tilingNoise, type Rgb } from './textures.ts';
import { TREE_LAYERS } from './trees.ts';

/** Pixels along each side of a tree's texture. */
export const TREE_TEXTURE = 256;

type Bark = (typeof TREE_LAYERS)[number];

/**
 * How to paint each bark, from u around the trunk and v up it, both from 0 to 1. The
 * texture goes twice around a trunk, and covers two meters of its height.
 */
const BARKS: Record<Bark, (u: number, v: number) => Rgb> = (() => {
  const furrows = tilingNoise(20, 3);
  const patches = layeredNoise(4, 8, 16);
  const marks = tilingNoise(5, 48);
  const plates = tilingNoise(9, 6);
  const fine = tilingNoise(64);
  return {
    // Furrows that run up the trunk: the noise is seven times finer around than up.
    'oak bark': (u, v) => shade(mix(hex('#3a2c21'), hex('#7d6549'), furrows(u, v) * 0.9 + 0.5), patches(u, v) * 0.3),
    // White, with dark marks that run around the trunk.
    'birch bark': (u, v) => {
      const color = shade(hex('#e2decf'), patches(u, v) * 0.12);
      const mark = marks(u, v);
      return mark > 0.45 ? mix(color, hex('#2b2826'), (mark - 0.45) * 8) : color;
    },
    // Reddish plates with dark gaps between them.
    'conifer bark': (u, v) => {
      const color = mix(hex('#5d3d2a'), hex('#96643f'), patches(u, v) + 0.5);
      return Math.abs(plates(u, v)) < 0.06 ? shade(color, -0.5) : shade(color, fine(u, v) * 0.2);
    },
    // Eight ribs around the trunk, light on their crests, with pale spines along them.
    'cactus skin': (u, v) => {
      const rib = Math.cos(u * Math.PI * 8);
      return rib > 0.8 && fine(u, v) > 0.25 ? hex('#ebe4b8') : shade(hex('#4c8a3a'), rib * 0.25);
    },
  };
})();

/** Paints every layer of the trees' texture array: RGBA bytes, one layer after the other. */
export function paintTreeLayers(): Uint8Array {
  const pixels = TREE_TEXTURE * TREE_TEXTURE;
  const data = new Uint8Array(pixels * 4 * TREE_LAYERS.length);
  TREE_LAYERS.forEach((name, layer) => {
    const paint = BARKS[name];
    for (let y = 0; y < TREE_TEXTURE; y += 1) {
      for (let x = 0; x < TREE_TEXTURE; x += 1) {
        const [r, g, b] = paint(x / TREE_TEXTURE, y / TREE_TEXTURE);
        data.set([r, g, b, 255], (layer * pixels + y * TREE_TEXTURE + x) * 4);
      }
    }
  });
  return data;
}

The shaders

There will be a forest of these trees, and only eighteen meshes. So the trees are drawn the way the grass of part 5 is: each mesh once for every tree of its kind, with two vec4 per tree instead of a matrix. place holds where the tree stands and its size, look.x how far it is turned about its trunk. The vertex shader turns the vertex and its normal, sizes the vertex and puts it in its place. The other three numbers of look are for later parts. Create 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;

varying vec3 vPosition;
varying vec3 vNormal;
varying vec4 vPaint;

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;
  gl_Position = viewProjection * worldPosition;
}

The fragment shader reads the bark from the vertex's layer and lights it with the sun and the sky, as the terrain is lit. Trees stand in the open, so there is no light grid to ask: a tree sees all of the sky. Create src/tree.fragment.glsl:

src/tree.fragment.glsl
precision highp float;
precision highp sampler2DArray;

varying vec3 vPosition;
varying vec3 vNormal;
varying vec4 vPaint;

uniform sampler2DArray layers;
uniform vec3 cameraPosition;
uniform vec3 sunDirection;
uniform vec3 sunColor;
uniform vec3 skyColor;
uniform vec3 groundColor;
uniform vec3 fogColor;
uniform vec2 fogRange;

void main() {
  vec4 texel = texture(layers, vec3(vPaint.xy, floor(vPaint.z + 0.5)));

  // Lit by the sun and the sky. A tree stands in the open: it sees all of the sky.
  vec3 normal = normalize(vNormal);
  float sun = max(dot(normal, -sunDirection), 0.0);
  vec3 ambient = mix(groundColor, skyColor, normal.y * 0.5 + 0.5);
  vec3 lit = texel.rgb * vPaint.w * (ambient + sunColor * sun);

  float fog = smoothstep(fogRange.x, fogRange.y, distance(vPosition, cameraPosition));
  gl_FragColor = vec4(mix(lit, fogColor, fog), 1.0);
}

The material paints the layers and wraps them in both directions, since the bark goes around and up the trunk without an end. createTreeMesh() puts a model in the scene. Babylon.js decides from a mesh's own box whether it is in view, and this mesh's instances will stand anywhere, so the mesh is always drawn. Create src/treeMaterial.ts:

src/treeMaterial.ts
import { Constants, RawTexture2DArray, ShaderMaterial, Texture, type Mesh, type Scene } from '@babylonjs/core/pure';
import { LIGHT_UNIFORMS, setLight, type FogOptions } from './material.ts';
import { createMesh } from './meshData.ts';
import fragmentSource from './tree.fragment.glsl?raw';
import vertexSource from './tree.vertex.glsl?raw';
import { TREE_LAYERS, type TreeModel } from './trees.ts';
import { paintTreeLayers, TREE_TEXTURE } from './treeTextures.ts';

/** The trees' material: the barks from one texture array, lit by the sun and the sky. */
export function createTreeMaterial(scene: Scene, options: FogOptions): 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],
      samplers: ['layers'],
    },
  );
  material.setTexture('layers', layers);
  setLight(material, options);
  // Nothing is left out for facing away: the leaves of the next part are seen from both sides.
  material.backFaceCulling = false;
  return material;
}

/** A tree's mesh in the scene. It is drawn once for every instance it is given. */
export function createTreeMesh(scene: Scene, model: TreeModel, material: ShaderMaterial): Mesh {
  const mesh = createMesh(model.species.name, model.mesh, scene);
  mesh.setVerticesData('paint', model.mesh.paints, false, 4);
  mesh.material = material;
  mesh.isPickable = false;
  // Its instances stand anywhere: Babylon.js can't tell from the mesh whether they are in view.
  mesh.alwaysSelectAsActiveMesh = true;
  return mesh;
}

A nursery

Until part 9 plants them, the trees stand in a nursery: every species 14 m further along x, its three variants 14 m apart along z. Each mesh gets a list with one instance, made with instanceBuffer() of part 5: the place, the size 1, and a turn. Create src/nursery.ts:

src/nursery.ts
import type { Scene, ShaderMaterial } from '@babylonjs/core/pure';
import { instanceBuffer } from './chunkPlants.ts';
import { surfaceHeight } from './terrain.ts';
import { createTreeMesh } from './treeMaterial.ts';
import { VARIANTS, type TreeModel } from './trees.ts';

/** Meters between the trees of the nursery. */
const APART = 14;

/**
 * Plants one of every tree in rows from (x, z): a row for each species. Each mesh is drawn
 * for one instance, which says where the tree stands and how it is turned.
 */
export function plantNursery(scene: Scene, models: TreeModel[], material: ShaderMaterial, x: number, z: number): void {
  models.forEach((model, i) => {
    const mesh = createTreeMesh(scene, model, material);
    const treeX = x + Math.floor(i / VARIANTS) * APART;
    const treeZ = z - (i % VARIANTS) * APART;
    // A little into the ground, which is not level.
    instanceBuffer(mesh, new Float32Array([treeX, surfaceHeight(treeX, treeZ) - 0.3, treeZ, 1, i * 2.4, 0, 0, 0]));
  });
}

In src/main.ts, import plantNursery from ./nursery.ts, createTreeMaterial from ./treeMaterial.ts and growModels from ./trees.ts. Before the blocks' material is made, grow the trees and plant the nursery to the left of the start:

src/main.ts
// The trees: every species in a few variants, grown once. For now they stand in a nursery
// next to the start.
const treeMaterial = createTreeMaterial(scene, fog);
const treeModels = growModels();
plantNursery(scene, treeModels, treeMaterial, 112, 172);

Under water the trees need the water's fog like everything else: add treeMaterial to the list of materials in dive().

Try it

From the start, turn left: the nursery begins 16 m away, with the oaks in front and, beyond them, the birches, the spruces, the pines, the acacias and the cacti. Walk through it and compare the three variants of a species: the same shape, never the same tree. Look up a spruce's trunk to see its limbs go around it by the golden angle, and at an oak's to see where the trunk ends and the limbs part. In src/trees.ts, change a species' numbers and reload: a droop of -1 turns the oak into a weeping tree, and a spread of 0.1 makes a spruce a pole.

A bare oak from close: the trunk ends where the limbs part, each limb bends toward its point on the crown's outline, and branches grow off the limbs to both sides.
Bare trees. Click, then turn left and walk into the nursery: three variants of each of the six species. WASD walks, Shift runs, F flies (Q/E down and up).
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.