Biomes and Vegetation on Voxel Terrain in Babylon.js · Part 10 of 12 in the series
Part 10: Forests to the horizon
Carry the forests on past the last mesh: take a picture of every tree model once, by drawing it into a texture, and let a card with that picture stand for each far tree, out to a kilometer. Beyond that, the far ground takes the color of the crowns.
Biomes and Vegetation on Voxel Terrain in Babylon.jsPart 10 of 12
On this page
Quest objectives
- Draw a tree into a texture with a camera without perspective, and read the picture back
- Stand a card for every far tree, four vertices that the shader turns to the camera
- Light a flat card as if it were a ball
- Fade cards in where the meshes fade out
- Plant the tiles of a whole square kilometer, nearest first
- Paint the far ground in the color of the crowns where no tree is drawn any more
The forests of part 9 end 130 m from the camera. From a hilltop that looks like a garden around you in a bare land. Drawing more meshes is no way out: a tree is a couple of thousand triangles, and a forest has a tree every few meters. But a tree 300 m away covers a handful of pixels. For that, a picture of it will do: a card of four vertices that shows the tree and always faces the camera. Such a stand-in is called an impostor.
This part takes the pictures, once, when the game starts. Then the forest draws meshes only up to 95 m, cards from there out to a kilometer, and beyond the last card the far ground itself turns the color of the crowns.
How far a tree reaches
A picture needs a frame that holds the whole tree. A model knows its height, but not how far its crown reaches out. That is the largest distance of any of its vertices from the trunk's axis. In src/trees.ts, TreeModel gets one more field, and meshTree() fills it in, in the object it returns, right after girth:
/** How far the tree reaches from its trunk at most. */
reach: number;
reach: Math.sqrt(positions.reduce((most, x, i) => (i % 3 === 0 ? Math.max(most, x * x + positions[i + 2] ** 2) : most), 0)),A tree in plain colors
The picture must not hold any light. A card turns with the camera, and a sunny side painted into the picture would turn with it: walk around the forest and the sun would seem to follow you. So the picture holds only the tree's own colors, darkened by the shade inside its crown from part 8, and the card is lit when it is drawn.
The trees' shader gets a second way to work for that, switched on by a #define: with PLAIN, it leaves out the fading of part 9, which depends on where the camera is, and writes the texture's color times the shade and nothing else. In src/tree.fragment.glsl, replace the start of main(), down to the line that works out the sun:
void main() {
#ifndef PLAIN
// A fading tree is drawn with only some of its pixels: fewer the more it has faded.
if (vFade < 1.0 && vFade <= grain()) discard;
#endif
float layer = floor(vPaint.z + 0.5);
vec4 texel = texture(layers, vec3(vPaint.xy, layer));
// Between the leaves of a spray there is nothing.
if (texel.a < 0.4) discard;
#ifdef PLAIN
// For its picture, a tree shows its colors in its own shade, and no light.
gl_FragColor = vec4(texel.rgb * vPaint.w, 1.0);
return;
#endif
vec3 normal = normalize(vNormal);
float sun = max(dot(normal, -sunDirection), 0.0);There are two materials now, the trees' own and the plain one, and both use the same texture array. So making the textures moves out of createTreeMaterial() into a function of its own, and the material takes them as an argument. With plain in its options it is made with the #define. Replace src/treeMaterial.ts:
import { Constants, RawTexture2DArray, ShaderMaterial, Texture, Vector2, 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' textures: the barks and the sprays of leaves, as the layers of one texture array. */
export function createTreeTextures(scene: Scene): RawTexture2DArray {
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;
return layers;
}
/**
* 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. With `plain`, it
* shows the trees' colors without the light, for their pictures.
*/
export function createTreeMaterial(
scene: Scene,
layers: RawTexture2DArray,
options: FogOptions & { fadeFrom: number; range: number; plain?: boolean },
): ShaderMaterial {
const material = new ShaderMaterial(
options.plain ? 'plain trees' : 'trees',
scene,
{ vertexSource, fragmentSource },
{
attributes: ['position', 'normal', 'paint', 'place', 'look'],
uniforms: ['world', 'viewProjection', ...LIGHT_UNIFORMS, 'firstLeaves', 'treeRange'],
samplers: ['layers'],
defines: options.plain ? ['#define PLAIN'] : [],
},
);
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;
}
/** 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;
}Taking the pictures
Babylon.js can draw into a texture instead of onto the screen: a RenderTargetTexture has its own camera and its own list of meshes. The camera for a picture has no perspective. An orthographic camera shows a box of the world, and that box is set to the tree's frame: as wide as it is high, the foot of the tree in the middle of the bottom edge. Create src/impostors.ts:
import {
Camera,
Color4,
Constants,
FreeCamera,
RawTexture2DArray,
RenderTargetTexture,
ShaderMaterial,
Texture,
Vector3,
Vector4,
type Mesh,
type Scene,
} from '@babylonjs/core/pure';
import { instanceBuffer } from './chunkPlants.ts';
import fragmentSource from './impostor.fragment.glsl?raw';
import vertexSource from './impostor.vertex.glsl?raw';
import { LIGHT_UNIFORMS, setLight, type FogOptions } from './material.ts';
import { createMesh } from './meshData.ts';
import { bleed } from './plants.ts';
import { createTreeMesh } from './treeMaterial.ts';
import { TREE_FLOATS } from './treeRule.ts';
import type { TreeModel } from './trees.ts';
/** Pixels along each side of a tree's picture. */
const PICTURE = 128;
/** Only the camera that takes the pictures sees this layer. */
const STUDIO = 0x10000000;
/** The side of the square that holds a model's picture, in meters: its foot is the middle of the bottom edge. */
export const frameOf = (model: TreeModel) => Math.max(model.height, model.reach * 2) * 1.04;
/**
* Takes a picture of every model from the side, and hands them out as the layers of a
* texture array. `material` is the trees' material in its plain colors, without the light.
*/
export async function takePictures(scene: Scene, models: TreeModel[], material: ShaderMaterial): Promise<RawTexture2DArray> {
const target = new RenderTargetTexture('pictures', PICTURE, scene, false);
target.clearColor = new Color4(0, 0, 0, 0);
// A camera without perspective, far enough away to see the whole tree.
const camera = new FreeCamera('studio', new Vector3(0, 0, -100), scene);
camera.mode = Camera.ORTHOGRAPHIC_CAMERA;
camera.minZ = 1;
camera.maxZ = 200;
camera.layerMask = STUDIO;
target.activeCamera = camera;
const layers = new Uint8Array(PICTURE * PICTURE * 4 * models.length);
for (const [layer, model] of models.entries()) {
// One tree at the world's origin, its foot at the middle of the picture's bottom edge.
const mesh = createTreeMesh(scene, model, material);
mesh.layerMask = STUDIO;
const buffer = instanceBuffer(mesh, new Float32Array([0, 0, 0, 1, 0, 0, 0, 0]));
const frame = frameOf(model);
camera.orthoLeft = -frame / 2;
camera.orthoRight = frame / 2;
camera.orthoBottom = 0;
camera.orthoTop = frame;
// The shader has to be ready, or the picture stays empty.
await material.forceCompilationAsync(mesh);
target.renderList = [mesh];
target.render();
const pixels = new Uint8Array((await target.readPixels()!).buffer);
bleed(pixels);
layers.set(pixels, layer * PICTURE * PICTURE * 4);
mesh.dispose();
buffer.dispose();
}
camera.dispose();
target.dispose();
return new RawTexture2DArray(layers, PICTURE, PICTURE, models.length, Constants.TEXTUREFORMAT_RGBA, scene, true, false, Texture.TRILINEAR_SAMPLINGMODE);
}
/** Where the cards fade in and out again, in meters from the camera. */
export interface CardRange {
from: number;
full: number;
fade: number;
range: number;
}
/** The material of the cards that stand for far trees: the pictures, lit as if each tree were a ball. */
export function createImpostorMaterial(scene: Scene, pictures: RawTexture2DArray, options: FogOptions & CardRange): ShaderMaterial {
const material = new ShaderMaterial(
'impostors',
scene,
{ vertexSource, fragmentSource },
{
attributes: ['position', 'card', 'layer'],
uniforms: ['viewProjection', ...LIGHT_UNIFORMS, 'cardRange'],
samplers: ['pictures'],
},
);
material.setTexture('pictures', pictures);
setLight(material, options);
material.setVector4('cardRange', new Vector4(options.from, options.full, options.fade, options.range));
material.backFaceCulling = false;
return material;
}
/**
* The cards of a tile's trees, as one mesh: four corners per tree, all at the tree's foot.
* The shader moves them apart. `skip` says which trees get no card, by their number in the list.
*/
export function createCards(
scene: Scene,
trees: Float32Array,
models: TreeModel[],
material: ShaderMaterial,
skip: (tree: number) => boolean = () => false,
): Mesh | null {
const positions: number[] = [];
const cards: number[] = [];
const layers: number[] = [];
const indices: number[] = [];
for (let t = 0; t < trees.length; t += TREE_FLOATS) {
if (skip(t)) continue;
const model = trees[t + 6];
const frame = frameOf(models[model]) * trees[t + 3];
const first = positions.length / 3;
for (const [u, v] of [[0, 0], [1, 0], [1, 1], [0, 1]]) {
positions.push(trees[t], trees[t + 1], trees[t + 2]);
cards.push((u - 0.5) * frame, v * frame, u, v);
layers.push(model);
}
indices.push(first, first + 1, first + 2, first, first + 2, first + 3);
}
if (indices.length === 0) return null;
const count = positions.length / 3;
const mesh = createMesh('cards', { positions: new Float32Array(positions), normals: new Float32Array(count * 3), indices: new Uint32Array(indices) }, scene);
mesh.setVerticesData('card', cards, false, 4);
mesh.setVerticesData('layer', layers, false, 1);
// The mesh only knows the trees' feet. Its box has to hold the cards too.
const { minimum, maximum } = mesh.getBoundingInfo();
mesh.buildBoundingInfo(minimum.subtract(new Vector3(15, 2, 15)), maximum.add(new Vector3(15, 30, 15)));
mesh.material = material;
mesh.isPickable = false;
mesh.freezeWorldMatrix();
return mesh;
}takePictures() goes through the models one by one:
The tree is a mesh with one instance, at the world's origin, in the plain material. It is in the scene for a moment, so it gets a layer mask that only the studio's camera has: the game's camera never draws it, and the studio's camera draws nothing else.
The camera stands 100 m away on the z axis and looks along it. Its four
orthonumbers are the edges of the frame, fromframeOf(): the larger of the height and twice the reach, and a little room around.forceCompilationAsync()waits until the shader is compiled. Babylon.js compiles shaders in the background and skips a mesh whose shader isn't ready, which would leave the picture empty.render()draws into the texture at once, andreadPixels()hands back its bytes, row by row from the bottom up, as the texture array wants them.bleed()from part 6 gives the see-through pixels the tree's average color, so that the picture has no dark rim where it is blended.
All the pictures end up as the layers of one texture array, in the order of the models, with smaller copies of themselves for the distance. A model is pictured from one side only. Trees are round enough for that, and with three variants of each species in different sizes a far forest doesn't look stamped.
createCards() makes the cards of one tile of trees as a single mesh. Every tree has four vertices, and all four have the same position: the tree's foot. What tells them apart is the attribute card: how far the corner lies from the foot, to the right and up, in meters, and where on the picture it is. The shader moves the corners apart, because only the shader knows where the camera is. The mesh's bounding box comes from the positions, which are only the feet, so it is made larger by hand: without that, Babylon.js would stop drawing a tile whose feet are out of view while its crowns still reach into it. The last argument, skip, leaves trees out. Part 12 needs it.
The card's shaders
Create src/impostor.vertex.glsl:
precision highp float;
// The tree's foot: the same for all four corners of its card.
attribute vec3 position;
// Where the corner lies from the foot, in meters to the right and up, and where on the picture.
attribute vec4 card;
// The picture's layer.
attribute float layer;
uniform mat4 viewProjection;
uniform vec3 cameraPosition;
// Where the cards fade in, and where they fade out again, in meters from the camera.
uniform vec4 cardRange;
varying vec3 vPosition;
varying vec3 vNormal;
varying vec3 vPicture;
varying float vFade;
void main() {
// The card stands upright and turns about the trunk to face the camera.
vec3 toCamera = normalize(vec3(cameraPosition.x - position.x, 0.0, cameraPosition.z - position.z));
vec3 right = vec3(toCamera.z, 0.0, -toCamera.x);
vPosition = position + right * card.x + vec3(0.0, card.y, 0.0);
// A flat card would be lit all alike. Its normals bulge instead, as if it were a ball:
// to the right on its right side, up at its top.
vNormal = right * (card.z * 2.0 - 1.0) + vec3(0.0, card.w * 1.4 - 0.4, 0.0) + toCamera * 0.6;
vPicture = vec3(card.zw, layer);
float away = distance(position.xz, cameraPosition.xz);
vFade = smoothstep(cardRange.x, cardRange.y, away) * (1.0 - smoothstep(cardRange.z, cardRange.w, away));
gl_Position = viewProjection * vec4(vPosition, 1.0);
}The card stands upright and turns about the trunk only.
toCamerais the level direction from the foot to the camera, andrightis square to it: the corners gocard.xalongrightandcard.yup.The normal is where a card gives itself away. A flat card has one normal, so the sun would light all of it alike, and a forest of such cards looks like cut-outs. Here the normals bulge: to the right on the card's right half, to the left on its left, upward at the top, and toward the camera in the middle. The fragment shader lights the card as if it were a ball, with a bright side toward the sun.
vFaderises from 0 to 1 over the first two numbers ofcardRangeand falls back to 0 over the last two: the cards fade in where the meshes fade out, and fade out at the end of their range.
Create src/impostor.fragment.glsl:
precision highp float;
precision highp sampler2DArray;
varying vec3 vPosition;
varying vec3 vNormal;
varying vec3 vPicture;
varying float vFade;
uniform sampler2DArray pictures;
uniform vec3 cameraPosition;
uniform vec3 sunDirection;
uniform vec3 sunColor;
uniform vec3 skyColor;
uniform vec3 groundColor;
uniform vec3 fogColor;
uniform vec2 fogRange;
// 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() {
if (vFade < 1.0 && vFade <= grain()) discard;
vec4 texel = texture(pictures, vec3(vPicture.xy, floor(vPicture.z + 0.5)));
if (texel.a < 0.5) discard;
// The picture holds the tree's colors in its own shade. The sun and the sky light it here.
vec3 normal = normalize(vNormal);
float sun = max(dot(normal, -sunDirection), 0.0) * 0.75 + max(dot(normal, sunDirection), 0.0) * 0.25;
vec3 ambient = mix(mix(groundColor, skyColor, normal.y * 0.5 + 0.5), skyColor, 0.5) * 1.2;
vec3 lit = texel.rgb * (ambient + sunColor * sun);
float fog = smoothstep(fogRange.x, fogRange.y, distance(vPosition, cameraPosition));
gl_FragColor = vec4(mix(lit, fogColor, fog), 1.0);
}A fading card is drawn with only some of its pixels, by the same grain() as the trees. Then the picture is cut out along the tree's outline, and lit as the leaves are in part 8: mostly from the sun's side, a little from behind, under a bright sky.
The forest, near and far
The forest now keeps tiles out to a kilometer, and each tile has a mesh of cards. Replace src/forest.ts:
import type { Buffer, Mesh, Scene, ShaderMaterial, Vector3 } from '@babylonjs/core/pure';
import { instanceBuffer } from './chunkPlants.ts';
import { createCards } from './impostors.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 as meshes, in meters, and where they start to fade out. */
export const TREE_RANGE = 95;
export const TREE_FADE = 80;
/** How far they are drawn as cards, and where those start to fade out. */
export const CARD_RANGE = 1000;
export const CARD_FADE = 850;
/** 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;
/** The cards that stand for the tile's trees from afar. */
cards: Mesh | 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. Further away, a card with
* the model's picture stands for each tree. The 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;
/** The cards' material, once the pictures are taken. */
private cardMaterial: ShaderMaterial | null = null;
private readonly scene: Scene;
private readonly models: TreeModel[];
constructor(scene: Scene, models: TreeModel[], material: ShaderMaterial) {
this.scene = scene;
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;
this.card(tile);
};
}
/** How many trees are drawn as cards. */
get cards(): number {
let cards = 0;
for (const tile of this.tiles.values()) cards += (tile.cards?.getTotalVertices() ?? 0) / 4;
return cards;
}
/** The pictures are taken: from now on, far trees are drawn as cards. */
showCards(material: ShaderMaterial): void {
this.cardMaterial = material;
for (const tile of this.tiles.values()) this.card(tile);
}
/** Makes a tile's cards, anew if it had some. */
private card(tile: Tile): void {
tile.cards?.dispose();
tile.cards = null;
if (tile.trees && this.cardMaterial) tile.cards = createCards(this.scene, tile.trees, this.models, this.cardMaterial);
}
/** 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(CARD_RANGE / TILE);
const [centerX, centerZ] = [Math.floor(focus.x / TILE), Math.floor(focus.z / TILE)];
const wanted: (TileJob & { distance: number })[] = [];
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))) wanted.push({ x, z, distance: Math.hypot(x - centerX, z - centerZ) });
}
}
// The worker plants the tiles in the order it is asked: the nearest first.
for (const { x, z } of wanted.sort((a, b) => a.distance - b.distance)) {
this.tiles.set(tileKey(x, z), { trees: null, grid: null, cards: null });
this.worker.postMessage({ x, z } satisfies TileJob);
}
for (const [key, tile] of this.tiles) {
const [x, z] = key.split(',').map(Number);
if (Math.max(Math.abs(x - centerX), Math.abs(z - centerZ)) <= reach + 1) continue;
tile.cards?.dispose();
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;
}The meshes' range shrinks from 130 m to 95 m, fading from 80 m. That is the reward: about half as many meshes as before, and a forest that reaches a kilometer.
update()asks for the tiles withinCARD_RANGE. That is a few hundred at the start, and the worker plants them in the order it is asked, so the list is sorted first: the nearest tiles come first, and the forest grows outward from the camera.card()makes a tile's mesh of cards, once its trees are there and the pictures are taken.showCards()is called when the pictures are ready, and makes the cards of all the tiles that came before.A tile that is dropped takes its cards with it.
Every tree within a kilometer has a card, the near ones too. Their cards are faded out, so they cost a few vertices and no pixels, and no list has to be kept of which tree is drawn how: the two shaders decide by the distance.
The color of the crowns
A kilometer is still not the horizon, which the far view puts at 4.5 km. But out there a tree is smaller than a pixel, and a forest is a dark patch on the land. The far ground can paint that itself: its vertices know how much of the ground trees cover since part 9, as the third number of the climate. In src/terrain.fragment.glsl, the far view's block of uniforms gets two constants. Replace it:
#ifdef FAR
uniform float nearRadius;
// Where the forests turn from single trees into the color of their crowns, in meters.
const float CANOPY_FROM = 750.0;
const float CANOPY_FULL = 950.0;
#endifAnd where the ground is shaded under trees, the far ground goes on to mix in the color of the crowns. Replace the two lines of the shade:
// Under trees the ground lies in their shade.
color *= 1.0 - 0.3 * vClimate.z;
#ifdef FAR
// Beyond the last tree that is drawn, a forest is the color of its crowns.
float canopy = vClimate.z * smoothstep(CANOPY_FROM, CANOPY_FULL, distance(vPosition.xz, cameraPosition.xz));
color = mix(color, mapColor * 0.45, canopy);
#endifThe color is the biome's color on the map of part 1, darkened: dark green for the broadleaf forest, a bluish green for the conifers. It comes in between 750 m and 950 m, a little before the cards fade out between 850 m and 1000 m, so that the cards dissolve into ground that already has their color.
Putting it together
Drawing into a texture and reading it back are two more parts of Babylon.js to register. In src/main.ts, import RegisterRenderTargetTexture, RegisterEnginesExtensionsEngineReadTexture and the type ShaderMaterial from Babylon.js, and add after the registrations for the dust:
// For the pictures of the trees: drawing into a texture, and reading it back.
RegisterRenderTargetTexture();
RegisterEnginesExtensionsEngineReadTexture();Import CARD_FADE and CARD_RANGE from ./forest.ts, createImpostorMaterial and takePictures from ./impostors.ts, and createTreeTextures from ./treeMaterial.ts. Then replace the two lines that make the trees' material and the forest:
const treeLayers = createTreeTextures(scene);
const treeRange = { fadeFrom: TREE_FADE, range: TREE_RANGE };
const treeMaterial = createTreeMaterial(scene, treeLayers, { ...fog, ...treeRange });
const treeModels = growModels();
const forest = new Forest(scene, treeModels, treeMaterial);
// Further away, a card with its picture stands for each tree. The cards come in where
// the meshes fade out.
const cardRange = { from: TREE_FADE, full: TREE_RANGE, fade: CARD_FADE, range: CARD_RANGE };
let cardMaterial: ShaderMaterial | null = null;
takePictures(scene, treeModels, createTreeMaterial(scene, treeLayers, { ...fog, ...treeRange, plain: true })).then((pictures) => {
cardMaterial = createImpostorMaterial(scene, pictures, { ...fog, ...cardRange });
forest.showCards(cardMaterial);
});The textures are made once and go to both materials. The models get a name, because the pictures need them too. takePictures() takes a moment, since it waits for a shader and for the graphics card to hand back the pixels: the game doesn't wait for it. Until the promise is kept there is no material for the cards, and the forest is as it was in part 9, only smaller. Then the cards appear, all at once.
The cards' range starts where the meshes' range ends: from and full are the trees' TREE_FADE and TREE_RANGE. Between 80 m and 95 m a tree is a mesh that loses pixels and a card that gains them.
Under water, the cards need the water's fog too, but their material may not be there yet. In dive(), replace the loop:
for (const lit of [material, farMaterial, blockMaterial, waterMaterial, grassMaterial, plantMaterial, treeMaterial, cardMaterial]) {
if (lit) setFog(lit, under ? WATER_FOG.color : SKY, under ? WATER_FOG : fog);
}And the HUD counts the cards: in its line of grass, plants and trees, add , ${forest.cards} as cards after the trees.
Try it
Press F and fly up with E. The forests run on over the hills, thin out to single trees on the meadows and stop at the tree line of the mountains, and far out they are dark patches on the land. Fly low over a forest and watch the trees ahead: somewhere around 90 m in front of you cards turn into meshes, and it takes some looking to find the place. Press N to fly to the next biome: the tiles around you are planted first, and the forest grows outward from where you are.
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.
