Zum Inhalt springen

Biome und Vegetation auf Voxel-Terrain in Babylon.js · Teil 6 von 12 der Serie

Teil 6: Blumen, Farne und Schilf

Ergänze acht Arten kleiner Pflanzen als Sprites, auf einem Canvas gemalt und auf gekreuzten Karten gezeichnet: Jedes Biom listet seine eigenen, jede Art wächst in Flecken, Schilf steht am Ufer, Pilze in Höhlen, und alle machen den Blöcken Platz, die du baust.

Quest-Ziele

  • Sprites von Pflanzen mit Canvas-Pfaden malen und daraus ein Textur-Array machen
  • Die dunklen Ränder beheben, die durchsichtige Pixel einem Sprite geben
  • Jedes Biom seine Pflanzen listen und jede Art in Flecken wachsen lassen
  • Schilf nach dem Ufer und Pilze nach dem Licht einer Höhle setzen
  • Die Pflanzen als Instanzen zweier gekreuzter Karten zeichnen
  • Die Pflanzen verstecken, wo ein Block steht, und zurückholen, wenn er geht

Die Wiese hat Gras. Dieser Teil setzt Gänseblümchen und Glockenblumen hinein, Farne und Büsche in die Wälder, trockene Sträucher in die Savanne, Heidekraut in die Tundra, Schilf an die Ufer und Pilze in die Höhlen. Acht Arten von Pflanzen, und alle sind dasselbe Mesh: zwei Karten, die sich kreuzen, mit einem Bild darauf. Die Bilder sind in Code gemalt, wie jede Textur bisher, aber diesmal mit einem Pinsel: dem Canvas des Browsers.

Teil 5 hat die schwere Arbeit getan. Stellen finden, sie von den Workern schicken und als Instanzen zeichnen, das ist alles da. Neu ist, welche Pflanze wo wächst, wie sie aussieht und was passiert, wenn du einen Block auf sie setzt.

Flecken

Blumen, die gleichmäßig verteilt sind, sehen aus wie eine Tapete. Auf einer echten Wiese wächst eine Art an einer Stelle dicht und zehn Schritte weiter gar nicht. Das braucht ein Rauschen pro Art, und bei acht Arten, an jeder Stelle gefragt, wäre Simplex-Rauschen viel Arbeit für wenig Wirkung. hash() kann das billig. Ergänze in src/random.ts:

src/random.ts
/**
 * Smooth noise from 0 to 1 made of hash(): random numbers at the whole numbers, blended
 * between them. Much cheaper than simplex noise, and good enough for patches of flowers.
 */
export function patchNoise(x: number, z: number, salt: number): number {
  const x0 = Math.floor(x);
  const z0 = Math.floor(z);
  const smooth = (t: number) => t * t * (3 - 2 * t);
  const fx = smooth(x - x0);
  const fz = smooth(z - z0);
  const at = (i: number, k: number) => hash(x0 + i, z0 + k, salt);
  return (at(0, 0) * (1 - fx) + at(1, 0) * fx) * (1 - fz) + (at(0, 1) * (1 - fx) + at(1, 1) * fx) * fz;
}

An jeder ganzen Zahl sitzt eine Zufallszahl, und dazwischen werden die vier um einen Punkt gemischt, weich. Das salt wird die Nummer der Art sein, also hat jede Art ihre eigenen Flecken.

Was wo wächst

Jedes Biom listet seine Pflanzen, mit dem Anteil der Stellen, den jede einnimmt. Ersetze in src/climate.ts die Liste der Biome:

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.
 */
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 },
  },
  {
    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 },
  },
  {
    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 },
  },
  {
    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 },
  },
  {
    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 },
  },
  {
    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 },
  },
] as const;

Arten und Regeln

Die Arten selbst, mit der Höhe, die jede erreicht, gehören zum Verteilen. Importiere in src/scatter.ts patchNoise aus ./random.ts neben hash und ersetze Scattered:

src/scatter.ts
/** What grows in a chunk: the plants of each kind, PLANT_FLOATS numbers each. */
export interface Scattered {
  grass: Float32Array;
  /** The small plants. Their tone is their kind: its number in PLANT_KINDS. */
  plants: Float32Array;
}

/** The kinds of small plants, in the order of their sprites, with how high they grow at least and at most. */
export const PLANT_KINDS = [
  { name: 'daisy', size: [0.3, 0.45] },
  { name: 'bluebell', size: [0.3, 0.45] },
  { name: 'fern', size: [0.5, 0.9] },
  { name: 'bush', size: [0.9, 1.6] },
  { name: 'shrub', size: [0.6, 1.1] },
  { name: 'reed', size: [1.6, 2.3] },
  { name: 'mushroom', size: [0.18, 0.3] },
  { name: 'heather', size: [0.3, 0.5] },
] as const;

type KindName = (typeof PLANT_KINDS)[number]['name'];
const kindOf = (name: KindName) => PLANT_KINDS.findIndex((kind) => kind.name === name);
const REED = kindOf('reed');
const MUSHROOM = kindOf('mushroom');

Die Reihenfolge der Arten ist die Reihenfolge ihrer Sprites: Die Art einer Pflanze ist die Nummer ihres Bilds. Einige Konstanten ändern sich, einige sind neu. Der Abstand des Grases bekommt einen zweiten für die Pflanzen, eine Stelle alle 1,25 m, das geringste Licht bekommt eines für Höhlen, und nach SHORE kommen die des Schilfs und der Flecken:

src/scatter.ts
/** Meters between the places where a tuft of grass may grow, and where a small plant may. */
const GRASS_SPACING = 0.4;
const PLANT_SPACING = 1.25;

/** Plants need this much of the sky's light, and mushrooms in caves at least a little. */
const DARKEST = 0.6;
const CAVE_DARKEST = 0.1;

/** Reeds stand in water up to this deep, and this far up the shore, in meters. */
const REED_DEPTH = 0.7;
const REED_SHORE = 0.8;
/** Meters across a patch in which a kind of plant grows thickly. */
const PATCH = 14;

Eine Pflanze kann sagen, dass sie in eine Höhle gehört. Ersetze Plant:

src/scatter.ts
/** A plant on its way into the list: `values` are its PLANT_FLOATS numbers. */
interface Plant {
  rank: number;
  values: number[];
  /** Grows in the half-dark of a cave, not under the sky. */
  cave?: boolean;
}

Und pack() behält so eine Pflanze dort, wo die anderen wegfallen: zwischen einem Zehntel und sechs Zehnteln vom Licht des Himmels, im Halbdunkel hinter dem Eingang einer Höhle. Ersetze die Zeile, die lit macht:

src/scatter.ts
const lit = plants
  .filter(({ values, cave }) => (cave ? values[5] >= CAVE_DARKEST && values[5] < DARKEST : values[5] >= DARKEST))
  .sort((a, b) => a.rank - b.rank);

Jetzt die Pflanzen selbst. Ersetze scatter() am Ende der Datei:

src/scatter.ts
/**
 * The small plants of a chunk. Each place takes at most one, of a kind that the biomes
 * there list. Every kind grows in patches of its own: thickly in some, not at all in others.
 */
function scatterPlants(grid: DensityGrid, origin: { x: number; y: number; z: number }, light: LightGrid): Float32Array {
  const plants: Plant[] = [];
  const shares = new Float32Array(PLANT_KINDS.length);
  eachSpot(grid, origin, PLANT_SPACING, 10, (spot) => {
    const random = (n: number) => hash(spot.cellX, spot.cellZ, 10 + n);
    const patch = (kind: number) => {
      const noise = patchNoise((origin.x + spot.x) / PATCH, (origin.z + spot.z) / PATCH, kind);
      return Math.min(Math.max((noise - 0.35) / 0.3, 0), 1) * 2.2;
    };
    const add = (kind: number, cave = false) => {
      const [smallest, largest] = PLANT_KINDS[kind].size;
      const size = smallest + (largest - smallest) * random(4);
      plants.push({ rank: random(3), cave, values: [spot.x, spot.y, spot.z, size, random(5) * Math.PI * 2, 1, kind, random(6)] });
    };

    // Reeds stand at the water's edge, wet feet or dry, where it is not too cold or too dry.
    const flat = spot.up > STEEPEST;
    if (flat && spot.generated > SEA - REED_DEPTH && spot.generated < SEA + REED_SHORE && spot.temperature > 0.2) {
      if (random(2) < 0.5 * patch(REED)) add(REED);
      return;
    }
    // Mushrooms grow on the floors of caves, in what light gets there.
    if (flat && spot.generated - spot.height > 3) {
      if (random(2) < 0.1) add(MUSHROOM, true);
      return;
    }
    if (!fertile(spot)) return;

    // The share of each kind here: what the biomes list, times the kind's patches.
    shares.fill(0);
    for (let b = 0; b < BIOME_COUNT; b += 1) {
      if (spot.biomes[b] === 0) continue;
      for (const [name, share] of Object.entries(BIOMES[b].plants)) shares[kindOf(name as KindName)] += share * spot.biomes[b];
    }
    // One random number picks the kind: each kind gets a stretch as long as its share.
    let pick = random(2);
    for (let kind = 0; kind < shares.length; kind += 1) {
      if (shares[kind] === 0) continue;
      pick -= shares[kind] * patch(kind);
      if (pick < 0) {
        add(kind);
        return;
      }
    }
  });
  return pack(plants, light, origin);
}

/** Everything that grows on the ground in a chunk's grid. */
export function scatter(grid: DensityGrid, origin: { x: number; y: number; z: number }, light: LightGrid): Scattered {
  return { grass: scatterGrass(grid, origin, light), plants: scatterPlants(grid, origin, light) };
}
  • Die Pflanzen nutzen eachSpot() mit breiteren Zellen und einem anderen Salt: andere Stellen und andere Zufallszahlen als das Gras.

  • patch() macht aus dem Rauschen einen Faktor. Wo das Rauschen unter 0,35 liegt, wächst die Art gar nicht, ab 0,65 wächst sie mit dem 2,2-Fachen ihres Anteils. Über das ganze Land ergibt das etwa, was das Biom sagt, aber in Flecken von 14 m.

  • add() wählt eine Größe zwischen der kleinsten und der größten der Art. Die siebte Zahl der Pflanze, bei einem Grasbüschel der Ton, ist ihre Art.

  • Schilf fragt nicht das Biom, sondern den Ort: wo der erzeugte Boden zwischen 70 cm unter dem Meer und 80 cm darüber liegt und wo es nicht zu kalt ist. Das kommt vor fertile(), das das Ufer ablehnen würde. Ein Schilfhalm ist etwa 2 m hoch, einer, der im Wasser steht, zeigt also immer noch das meiste von sich.

  • Eine Stelle mehr als 3 m unter dem erzeugten Boden ist der Boden einer Höhle. Auf einer von zehn wachsen Pilze, fürs Halbdunkel markiert.

  • Überall sonst werden die Listen der Biome nach den Gewichten der Biome addiert, und eine Zufallszahl wählt die Art: Jede Art bekommt eine Strecke, so lang wie ihr Anteil, und eine Zahl, die hinter allen Strecken liegt, wählt nichts. Auf der Wiese ergeben die Anteile 0,17, die meisten Stellen bleiben also leer.

Sonst ändert sich in den Workern und in der Welt nichts: Scattered hat eine Liste mehr, und der Worker aus Teil 5 schickt jede Liste, die er findet.

Die Sprites malen

Die Texturen bisher waren Pixel für Pixel gemalt, aus Rauschen. Das passt zu Erde und Rinde, die keine Formen haben. Ein Gänseblümchen hat welche: Blütenblätter, einen Stängel, Blätter. Der Canvas des Browsers zeichnet so etwas als Pfade, mit glatten Kanten, und seine Pixel lassen sich zurücklesen. Erstelle src/plants.ts:

src/plants.ts
import { Constants, RawTexture2DArray, ShaderMaterial, Texture, Vector2, type Scene } from '@babylonjs/core/pure';
import type { PlantRange, PlantShape } from './chunkPlants.ts';
import { LIGHT_UNIFORMS, setLight, type FogOptions } from './material.ts';
import fragmentSource from './plant.fragment.glsl?raw';
import vertexSource from './plant.vertex.glsl?raw';
import { seededRandom } from './random.ts';
import { PLANT_KINDS } from './scatter.ts';

/** How far the small plants are drawn: all of them near the camera, half of them 90 m away. */
export const PLANT_RANGE: PlantRange = { allWithin: 30, fewest: 0.5, range: 90 };
/** Meters from the camera at which they start to shrink into the ground. */
const FADE_FROM = 70;
/** Pixels along each side of a sprite. */
const SPRITE = 128;

export type Context = CanvasRenderingContext2D;
/** Paints a sprite: one unit wide and high, y up, with (0, 0) at the middle of its bottom edge. */
export type Painter = (ctx: Context, random: () => number) => void;

/** A leaf from (x, y), pointed at both ends. `angle` is 0 straight up, in radians. */
export function leaf(ctx: Context, x: number, y: number, angle: number, length: number, width: number, color: string): void {
  ctx.save();
  ctx.translate(x, y);
  ctx.rotate(-angle);
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.quadraticCurveTo(width, length * 0.5, 0, length);
  ctx.quadraticCurveTo(-width, length * 0.5, 0, 0);
  ctx.fillStyle = color;
  ctx.fill();
  ctx.restore();
}

/** A stalk from (x, y) that leans over by `lean` at its top, and where that top is. */
export function stalk(ctx: Context, x: number, y: number, lean: number, height: number, width: number, color: string): [number, number] {
  ctx.beginPath();
  ctx.moveTo(x, y);
  ctx.quadraticCurveTo(x, y + height * 0.6, x + lean, y + height);
  ctx.lineWidth = width;
  ctx.lineCap = 'round';
  ctx.strokeStyle = color;
  ctx.stroke();
  return [x + lean, y + height];
}

export function dot(ctx: Context, x: number, y: number, radius: number, color: string): void {
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
}

export const pick = (random: () => number, colors: string[]) => colors[Math.floor(random() * colors.length)];
const GREENS = ['#4c7a2b', '#5c8f33', '#6da03c'];

/**
 * How to paint each kind of plant, by its name in PLANT_KINDS. The plant grows from (0, 0),
 * the middle of the sprite's bottom edge.
 */
const PAINTERS: Record<(typeof PLANT_KINDS)[number]['name'], Painter> = {
  // White flowers with yellow middles on thin stalks, over a few leaves.
  daisy: (ctx, random) => {
    for (let i = 0; i < 7; i += 1) leaf(ctx, (random() - 0.5) * 0.2, 0, (random() - 0.5) * 1.6, 0.3 + random() * 0.2, 0.05, pick(random, GREENS));
    for (let i = 0; i < 6; i += 1) {
      const [x, y] = stalk(ctx, (random() - 0.5) * 0.2, 0, (random() - 0.5) * 0.6, 0.5 + random() * 0.35, 0.018, '#5c8f33');
      for (let p = 0; p < 9; p += 1) leaf(ctx, x, y, (p / 9) * Math.PI * 2, 0.085, 0.03, '#f6f3e6');
      dot(ctx, x, y, 0.03, '#f2b632');
    }
  },
  // Bells in a row along stalks that bend over.
  bluebell: (ctx, random) => {
    for (let i = 0; i < 6; i += 1) leaf(ctx, (random() - 0.5) * 0.2, 0, (random() - 0.5) * 1.2, 0.4 + random() * 0.2, 0.04, pick(random, GREENS));
    for (let i = 0; i < 5; i += 1) {
      const x = (random() - 0.5) * 0.25;
      const lean = (random() - 0.5) * 0.5;
      const height = 0.6 + random() * 0.35;
      stalk(ctx, x, 0, lean, height, 0.018, '#4c7a2b');
      for (let b = 0; b < 5; b += 1) {
        const t = 0.55 + b * 0.1;
        dot(ctx, x + lean * t * t + Math.sign(lean) * 0.03, height * t - 0.02, 0.035, pick(random, ['#6a5acd', '#7b68ee', '#8f7cf5']));
      }
    }
  },
  // Fronds that arch out from the middle, each a rib with leaflets on both sides.
  fern: (ctx, random) => {
    for (let i = 0; i < 9; i += 1) {
      const side = (i - 4) / 4 + (random() - 0.5) * 0.2;
      const length = 0.6 + random() * 0.35;
      const color = pick(random, ['#3f6e2c', '#4d8234', '#5b923b']);
      for (let step = 1; step <= 14; step += 1) {
        const t = step / 14;
        // The frond rises, then bends outward under its own weight.
        const x = side * length * t * (0.3 + 0.6 * t);
        const y = length * t * (1 - 0.35 * Math.abs(side) * t);
        const size = 0.11 * Math.sin(t * Math.PI) + 0.015;
        const out = side * 0.8 * t;
        leaf(ctx, x, y, out + 1.2, size, size * 0.3, color);
        leaf(ctx, x, y, out - 1.2, size, size * 0.3, color);
      }
    }
  },
  // A round mass of leaves, the dark ones inside painted first.
  bush: (ctx, random) => {
    for (let i = 0; i < 260; i += 1) {
      const angle = random() * Math.PI * 2;
      const reach = Math.sqrt(random());
      const x = Math.cos(angle) * reach * 0.42;
      const y = 0.46 + Math.sin(angle) * reach * 0.42;
      const shade = i < 110 ? ['#2f5a22', '#3a6a28'] : ['#4a7f2e', '#5c9438', '#6fa644'];
      leaf(ctx, x, y, random() * Math.PI * 2, 0.1 + random() * 0.05, 0.035, pick(random, shade));
    }
  },
  // Dry twigs that fork, with a few small olive leaves left on them.
  shrub: (ctx, random) => {
    const twig = (x: number, y: number, angle: number, length: number, width: number) => {
      const [x1, y1] = [x + Math.sin(angle) * length, y + Math.cos(angle) * length];
      ctx.beginPath();
      ctx.moveTo(x, y);
      ctx.lineTo(x1, y1);
      ctx.lineWidth = width;
      ctx.strokeStyle = pick(random, ['#7a5a3a', '#8b6a45', '#6b4d32']);
      ctx.stroke();
      if (length < 0.09) {
        if (random() < 0.6) leaf(ctx, x1, y1, angle + (random() - 0.5), 0.07, 0.022, pick(random, ['#8a8a45', '#9a9550']));
        return;
      }
      twig(x1, y1, angle - 0.3 - random() * 0.4, length * 0.72, width * 0.7);
      twig(x1, y1, angle + 0.3 + random() * 0.4, length * 0.72, width * 0.7);
    };
    for (let i = 0; i < 5; i += 1) twig((random() - 0.5) * 0.1, 0, (i - 2) * 0.35 + (random() - 0.5) * 0.2, 0.2 + random() * 0.08, 0.03);
  },
  // Tall stalks with long leaves and brown heads.
  reed: (ctx, random) => {
    for (let i = 0; i < 9; i += 1) {
      const x = (random() - 0.5) * 0.5;
      const lean = (random() - 0.5) * 0.25;
      const height = 0.7 + random() * 0.28;
      const [tx, ty] = stalk(ctx, x, 0, lean, height, 0.016, pick(random, ['#6d8f3a', '#86a548']));
      leaf(ctx, x, 0, (random() - 0.5) * 0.5, height * 0.8, 0.022, pick(random, ['#5f8535', '#78a044']));
      if (i % 2 === 0) {
        ctx.beginPath();
        ctx.ellipse(tx, ty - 0.04, 0.022, 0.07, 0, 0, Math.PI * 2);
        ctx.fillStyle = '#6b4226';
        ctx.fill();
      }
    }
  },
  // Three toadstools: pale stems, red caps with white spots.
  mushroom: (ctx, random) => {
    for (const [x, height, cap] of [[-0.22, 0.45, 0.2], [0.05, 0.75, 0.3], [0.3, 0.35, 0.16]]) {
      stalk(ctx, x, 0, 0, height, cap * 0.35, '#efe6d2');
      ctx.beginPath();
      ctx.ellipse(x, height, cap, cap * 0.75, 0, Math.PI, Math.PI * 2, true);
      ctx.closePath();
      ctx.fillStyle = '#c93a2b';
      ctx.fill();
      for (let i = 0; i < 6; i += 1) dot(ctx, x + (random() - 0.5) * cap * 1.4, height + cap * (0.15 + random() * 0.4), cap * 0.08, '#f7efe1');
    }
  },
  // A low cushion of tiny leaves, with flowers the color of heather.
  heather: (ctx, random) => {
    for (let i = 0; i < 320; i += 1) {
      const angle = random() * Math.PI;
      const reach = Math.sqrt(random());
      const x = Math.cos(angle) * reach * 0.46;
      const y = Math.sin(angle) * reach * 0.7 + 0.03;
      if (i % 4 === 3 && y > 0.3) dot(ctx, x, y, 0.022, pick(random, ['#b06cff', '#c48be8', '#9d5bd6']));
      else leaf(ctx, x, y, Math.cos(angle) * -1 + (random() - 0.5), 0.09, 0.02, pick(random, ['#4d5f33', '#5f7040', '#6f7a48']));
    }
  },
};

/**
 * Gives the see-through pixels of a picture its average color. They are black, and would
 * darken the picture's edges where the graphics card blends them with their neighbors.
 */
export function bleed(pixels: Uint8ClampedArray | Uint8Array): void {
  const sum = [0, 0, 0, 0];
  for (let p = 0; p < pixels.length; p += 4) {
    if (pixels[p + 3] < 255) continue;
    for (let c = 0; c < 3; c += 1) sum[c] += pixels[p + c];
    sum[3] += 1;
  }
  for (let p = 0; p < pixels.length; p += 4) {
    if (pixels[p + 3] === 0) for (let c = 0; c < 3; c += 1) pixels[p + c] = sum[c] / sum[3];
  }
}

/**
 * Paints a sprite of `size` pixels on a canvas and hands out its RGBA bytes, row by row
 * from the bottom up, as a texture wants them.
 */
export function paintSprite(size: number, painter: Painter, seed: number): Uint8ClampedArray {
  const canvas = document.createElement('canvas');
  canvas.width = size;
  canvas.height = size;
  const ctx = canvas.getContext('2d')!;
  // One unit is the whole sprite, y points up, and (0, 0) is the middle of the bottom edge.
  ctx.setTransform(size, 0, 0, -size, size / 2, size);
  painter(ctx, seededRandom(seed));
  const pixels = ctx.getImageData(0, 0, size, size).data;
  bleed(pixels);
  // The canvas's first row is its top, the texture's its bottom.
  const flipped = new Uint8ClampedArray(pixels.length);
  for (let row = 0; row < size; row += 1) {
    const from = (size - 1 - row) * size * 4;
    flipped.set(pixels.subarray(from, from + size * 4), row * size * 4);
  }
  return flipped;
}

/** A plant's shape: two cards that cross, each showing the whole sprite, one meter high. */
export function crossedCards(): PlantShape {
  const positions: number[] = [];
  const uvs: number[] = [];
  const indices: number[] = [];
  for (const [dx, dz] of [[1, 0], [0, 1]]) {
    const first = positions.length / 3;
    for (const [u, v] of [[0, 0], [1, 0], [1, 1], [0, 1]]) {
      positions.push((u - 0.5) * dx, v, (u - 0.5) * dz);
      uvs.push(u, v);
    }
    indices.push(first, first + 1, first + 2, first, first + 2, first + 3);
  }
  return { positions, indices, extra: { kind: 'uv', data: uvs } };
}

/** The small plants' material: the painted sprites, cut out along their outlines. */
export function createPlantMaterial(scene: Scene, options: FogOptions): ShaderMaterial {
  // Every kind's sprite, as the layers of one texture array.
  const layers = new Uint8Array(SPRITE * SPRITE * 4 * PLANT_KINDS.length);
  PLANT_KINDS.forEach(({ name }, layer) => layers.set(paintSprite(SPRITE, PAINTERS[name], layer + 1), layer * SPRITE * SPRITE * 4));
  const sprites = new RawTexture2DArray(
    layers,
    SPRITE,
    SPRITE,
    PLANT_KINDS.length,
    Constants.TEXTUREFORMAT_RGBA,
    scene,
    true,
    false,
    Texture.TRILINEAR_SAMPLINGMODE,
  );
  const material = new ShaderMaterial(
    'plants',
    scene,
    { vertexSource, fragmentSource },
    {
      attributes: ['position', 'uv', 'place', 'look'],
      uniforms: ['world', 'viewProjection', ...LIGHT_UNIFORMS, 'plantRange'],
      samplers: ['sprites'],
    },
  );
  material.setTexture('sprites', sprites);
  setLight(material, options);
  material.setVector2('plantRange', new Vector2(FADE_FROM, PLANT_RANGE.range));
  material.backFaceCulling = false;
  return material;
}
  • Ein Maler arbeitet in einem Quadrat, das eine Einheit breit und hoch ist, mit y nach oben und (0, 0) in der Mitte der unteren Kante, wo die Pflanze aus dem Boden wächst. paintSprite() richtet den Canvas mit setTransform() so ein, kein Maler muss also wissen, wie viele Pixel ein Sprite hat.

  • leaf(), stalk() und dot() sind die Pinsel: Ein Blatt sind zwei Kurven, ein Stängel eine Kurve mit rundem Ende, ein Punkt ein Kreis. Die Maler rufen sie ein paar hundert Mal auf, mit Zahlen aus einem Generator mit Seed, eine Art sieht also bei jedem Besuch gleich aus.

  • Der Busch zeigt einen Kniff, den auch die Bäume nutzen werden: Die zuerst gemalten Blätter landen unter den anderen, also sind die ersten dunkel und die letzten hell, und der Busch wirkt rund.

  • Die erste Zeile des Canvas ist seine oberste, die erste Zeile einer Textur ihre unterste: paintSprite() gibt die Zeilen andersherum aus.

  • crossedCards() ist die Form: zwei aufrechte Quadrate durch dieselbe Mitte, im rechten Winkel, jedes mit dem ganzen Sprite darauf. Von jeder Seite ist dir mindestens eines zugewandt.

Dunkle Ränder

bleed() sieht nach einer Kleinigkeit aus und entscheidet, wie die Pflanzen aussehen. Wo der Canvas nichts gemalt hat, sind seine Pixel durchsichtig und schwarz. Der Shader wird die Pflanze entlang ihres Umrisses ausschneiden, aber die Grafikkarte mischt vorher jedes Pixel einer Textur mit seinen Nachbarn, und in den kleineren Kopien, die sie für ferne Pflanzen bereithält, werden ganze Blöcke von Pixeln zu einem. Am Rand der Pflanze gerät Schwarz in die Mischung, und jede Blume bekommt einen dunklen Saum. Die Abhilfe: den durchsichtigen Pixeln eine Farbe geben, die nicht schadet, den Durchschnitt der Pflanze selbst. Sie bleiben durchsichtig, aber was von ihnen hereinläuft, ist grün.

Die Shader der Pflanzen

Der Vertex-Shader ist der des Grases, mit der Stelle auf einem Sprite statt der an einem Halm. Erstelle src/plant.vertex.glsl:

src/plant.vertex.glsl
precision highp float;

// A corner of a card, and where on the sprite it is.
attribute vec3 position;
attribute vec2 uv;
// The plant, one for every instance: its place from the chunk's corner and its size,
// then its turn, its light, its kind and a random number.
attribute vec4 place;
attribute vec4 look;

uniform mat4 world;
uniform mat4 viewProjection;
uniform vec3 cameraPosition;
// Where the plants start to shrink away, and where they are gone, in meters from the camera.
uniform vec2 plantRange;

varying vec3 vPosition;
varying vec2 vUv;
varying float vLight;
varying float vKind;

void main() {
  vec3 root = (world * vec4(place.xyz, 1.0)).xyz;
  float size = place.w * (1.0 - smoothstep(plantRange.x, plantRange.y, distance(root, cameraPosition)));
  float c = cos(look.x);
  float s = sin(look.x);
  vec3 turned = vec3(position.x * c - position.z * s, position.y, position.x * s + position.z * c);
  vPosition = root + turned * size;
  vUv = uv;
  vLight = look.y;
  vKind = look.z;
  gl_Position = viewProjection * vec4(vPosition, 1.0);
}

Die Pflanzen reichen weiter als das Gras: alle bis 30 m, die Hälfte bei 90 m, und über die letzten 20 m schrumpfen sie in den Boden. Einen Busch sieht man von viel weiter als einen Halm. Erstelle src/plant.fragment.glsl:

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

varying vec3 vPosition;
varying vec2 vUv;
varying float vLight;
varying float vKind;

uniform sampler2DArray sprites;
uniform vec3 cameraPosition;
uniform vec3 sunDirection;
uniform vec3 sunColor;
uniform vec3 skyColor;
uniform vec3 caveColor;
uniform vec3 lampColor;
uniform vec3 fogColor;
uniform vec2 fogRange;

// Meters the lamp at the camera reaches.
const float LAMP_RANGE = 24.0;

void main() {
  // The sprite of the plant's kind. Where it is see-through, there is no plant.
  vec4 sprite = texture(sprites, vec3(vUv, floor(vKind + 0.5)));
  if (sprite.a < 0.4) discard;
  // Darker toward the ground, where the plant stands in its own shade.
  vec3 color = sprite.rgb * mix(0.7, 1.0, vUv.y);

  // Lit like flat ground, and by the lamp in the dark, as if the card faced the camera.
  float sky = vLight;
  float sun = max(-sunDirection.y, 0.0) * smoothstep(0.6, 1.0, sky);
  float distanceToCamera = distance(vPosition, cameraPosition);
  float lamp = pow(1.0 - min(distanceToCamera / LAMP_RANGE, 1.0), 2.0) * (1.0 - sky);
  vec3 lit = color * (skyColor * pow(sky, 1.5) + caveColor + sunColor * sun + lampColor * lamp);

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

Ein Pixel, das weniger als 0,4 da ist, wird verworfen: Das schneidet die Pflanze aus ihrer Karte und braucht kein Mischen und kein Sortieren. Das Licht ist das des Grases, mit einer Ergänzung für die Pilze: die Lampe an der Kamera aus der Terrain-Serie, die scheint, wo das Licht des Himmels nicht hinreicht.

Den Blöcken Platz machen

Setz einen Block auf die Wiese, und das Gras ragt oben aus ihm heraus. Die Worker können nicht helfen: Sie kennen den Boden, nicht die Blöcke. Die Seite kennt sie. Also behält ChunkPlants alle Pflanzen eines Chunks und gibt der Grafikkarte nur die, auf denen nichts steht. Ersetze in src/chunkPlants.ts alles ab interface Patch:

src/chunkPlants.ts
interface Patch {
  mesh: Mesh;
  /** All the chunk's plants, and those that show, on the graphics card. */
  plants: Float32Array;
  buffer: Buffer | null;
  count: number;
}

/**
 * The plants of one kind in the scene: one mesh per chunk, which draws the same shape once
 * for every plant of the chunk.
 */
export class ChunkPlants {
  /** Asked for every plant: whether something built stands where it grows. Such plants don't show. */
  blocked: (x: number, y: number, z: number) => boolean = () => false;
  private readonly patches = new Map<string, Patch>();
  private readonly scene: Scene;
  private readonly material: Material;
  private readonly shape: PlantShape;
  private readonly range: PlantRange;

  constructor(scene: Scene, material: Material, shape: PlantShape, range: PlantRange) {
    this.scene = scene;
    this.material = material;
    this.shape = shape;
    this.range = range;
  }

  /** How many plants are drawn. */
  get shown(): number {
    let shown = 0;
    for (const { mesh, count } of this.patches.values()) if (mesh.isEnabled() && count > 0) shown += mesh.forcedInstanceCount;
    return shown;
  }

  /** A chunk's plants came, or went: then `plants` is null. */
  set(position: ChunkPosition, plants: Float32Array | null): void {
    const key = chunkKey(position);
    const old = this.patches.get(key);
    if (old) {
      old.mesh.dispose();
      old.buffer?.dispose();
      this.patches.delete(key);
    }
    if (!plants || plants.length === 0) return;

    const mesh = new Mesh(`plants ${key}`, this.scene);
    const data = new VertexData();
    data.positions = this.shape.positions;
    data.indices = this.shape.indices;
    data.applyToMesh(mesh);
    mesh.setVerticesData(this.shape.extra.kind, this.shape.extra.data, false, 2);
    mesh.position.set(position.x * CHUNK_SIZE, position.y * CHUNK_SIZE, position.z * CHUNK_SIZE);
    // The mesh itself is one plant at the chunk's corner. Babylon.js must know that the
    // instances fill the whole chunk, or it would not draw them when the corner is out of view.
    mesh.setBoundingInfo(new BoundingInfo(new Vector3(-2, -2, -2), new Vector3(CHUNK_SIZE + 2, CHUNK_SIZE + 4, CHUNK_SIZE + 2)));
    mesh.material = this.material;
    mesh.isPickable = false;
    mesh.freezeWorldMatrix();
    const patch = { mesh, plants, buffer: null, count: 0 };
    this.patches.set(key, patch);
    this.fill(patch);
  }

  /** Something was built or taken away in a box of the world: the chunks it reaches into look again at which of their plants show. */
  refresh(low: Vector3, high: Vector3): void {
    for (const patch of this.patches.values()) {
      const corner = patch.mesh.position;
      const apart = (axis: 'x' | 'y' | 'z') => low[axis] > corner[axis] + CHUNK_SIZE + 1 || high[axis] < corner[axis] - 1;
      if (!apart('x') && !apart('y') && !apart('z')) this.fill(patch);
    }
  }

  /** Hands the plants of a chunk that show to the graphics card. */
  private fill(patch: Patch): void {
    const { mesh, plants } = patch;
    // The plants that nothing stands on, in their old order.
    const shown = new Float32Array(plants.length);
    let count = 0;
    for (let p = 0; p < plants.length; p += PLANT_FLOATS) {
      if (this.blocked(mesh.position.x + plants[p], mesh.position.y + plants[p + 1], mesh.position.z + plants[p + 2])) continue;
      shown.set(plants.subarray(p, p + PLANT_FLOATS), count * PLANT_FLOATS);
      count += 1;
    }
    patch.buffer?.dispose();
    patch.buffer = instanceBuffer(mesh, shown.subarray(0, count * PLANT_FLOATS));
    patch.count = count;
  }

  /** Once a frame: the further a chunk is from the camera, the fewer of its plants are drawn. */
  update(focus: Vector3): void {
    const { allWithin, fewest, range } = this.range;
    for (const { mesh, count } of this.patches.values()) {
      const low = mesh.position;
      const nearest = Vector3.Clamp(focus, low, low.add(new Vector3(CHUNK_SIZE, CHUNK_SIZE, CHUNK_SIZE)));
      const distance = Vector3.Distance(focus, nearest);
      mesh.setEnabled(distance < range && count > 0);
      // The plants are in a random order: the first ones are spread as evenly as all.
      const share = 1 - (1 - fewest) * Math.min(Math.max((distance - allWithin) / (range - allWithin), 0), 1);
      mesh.forcedInstanceCount = Math.max(Math.ceil(count * share), 1);
    }
  }
}
  • blocked wird für jede Pflanze mit ihrem Ort in der Welt gefragt.

  • fill() kopiert die Pflanzen, die zu sehen sind, in eine neue Liste, in ihrer alten Reihenfolge, damit das Ausdünnen nach Rang weiter funktioniert, und macht daraus einen neuen Buffer.

  • refresh() tut das erneut für jeden Chunk, in den eine Box der Welt hineinreicht, mit einem Meter Spielraum.

  • Ein Chunk, dessen Pflanzen alle versteckt sind, wird gar nicht gezeichnet.

Der Blockspeicher hat einen Zuhörer für Änderungen, und die BlockWorld nutzt ihn. Also reicht die BlockWorld die Nachricht weiter. Ergänze in src/blockWorld.ts das Feld und ersetze touch():

src/blockWorld.ts
/** Called with every block that came, went or changed its shape. */
onBlock: (block: Block) => void = () => {};

/**
 * A block came or went. Its region is out of date, and so are the regions of the blocks
 * around it, whose sides it covers or uncovers.
 */
private touch(block: Block): void {
  this.onBlock(block);
  this.dirty.add(regionOf(block.x, block.y, block.z));
  const { x, y, z, size } = block;
  for (let k = z - 1; k <= z + size; k += 1) {
    for (let j = y - 1; j <= y + size; j += 1) {
      for (let i = x - 1; i <= x + size; i += 1) {
        const other = this.store.at(i, j, k);
        if (other && other !== block) this.dirty.add(regionOf(other.x, other.y, other.z));
      }
    }
  }
}

Die Seite

Importiere in src/main.ts createPlantMaterial, crossedCards und PLANT_RANGE aus ./plants.ts. Die Pflanzen zeichnet ein zweites ChunkPlants, und die Nachrichten der Welt gehen an beide. Ersetze die Zeilen des Grases:

src/main.ts
// The grass of the chunks near the camera.
const grassMaterial = createGrassMaterial(scene, fog);
const grass = new ChunkPlants(scene, grassMaterial, tuft(), GRASS_RANGE);
// The flowers, ferns, bushes and the like: sprites on crossed cards.
const plantMaterial = createPlantMaterial(scene, fog);
const plants = new ChunkPlants(scene, plantMaterial, crossedCards(), PLANT_RANGE);
world.onPlants = (position, scattered) => {
  grass.set(position, scattered?.grass ?? null);
  plants.set(position, scattered?.plants ?? null);
};

Nachdem die Blöcke erzeugt sind, erfahren beide, was sie blockiert und wann sie neu nachsehen sollen:

src/main.ts
// Nothing grows where a block stands: a plant with a block in the cell at its foot is hidden.
for (const greens of [grass, plants]) {
  greens.blocked = (x, y, z) => blocks.store.at(Math.floor(x / CELL), Math.floor((y + 0.2) / CELL), Math.floor(z / CELL)) !== undefined;
}
blocks.onBlock = ({ x, y, z, size }) => {
  const low = new Vector3(x, y, z).scaleInPlace(CELL);
  const high = low.add(new Vector3(size, size, size).scaleInPlace(CELL));
  for (const greens of [grass, plants]) greens.refresh(low, high);
};

Eine Pflanze ist versteckt, wenn ein Block die Zelle 20 cm über ihrem Fuß füllt: Ein Block, der auf dem Boden steht, versteckt, was unter ihm ist, ein Balken zwei Meter weiter oben nicht. Ergänze im Frame nach grass.update() plants.update(camera.position);. In dive() kommt plantMaterial in die Liste. Und die Zeile des HUD wird zu `${grass.shown} tufts of grass, ${plants.shown} plants\n` +.

Ausprobieren

Die Wiese am Start hat an manchen Stellen Gänseblümchen, an anderen Glockenblumen und hier und da einen Busch. Unter den Blöcken der Beispielszene ist der Boden kahl. Setz mit der rechten Taste einen Block auf einen Fleck Blumen, und sie sind weg, mit dem Gras. Bau ihn mit der linken ab, und sie sind wieder da. Dreh dich um und geh zum See hinunter: An seinem Ufer steht Schilf, manches davon im Wasser. Drück dann N: Farne und Büsche im Laubwald, Farne, Heidekraut und Fliegenpilze im Nadelwald, Heidekraut in der Tundra, trockene Sträucher in der Savanne und, dünn gesät, in der Wüste. Und wenn du den Eingang einer Höhle findest, geh hinein: Wo das Tageslicht endet, stehen Pilze im Licht deiner Lampe.

Schilf am Ufer des Sees, manches auf dem Sand und manches mit den Füßen im Wasser. Jedes sind zwei gekreuzte Karten mit demselben gemalten Sprite.
Blumen, Farne und Schilf. Klick, dann: Sieh dich auf der Wiese um, setz einen Block auf ein paar Blumen (Rechtsklick) und bau ihn wieder ab (Linksklick). Der See hinter dir hat Schilf. N fliegt zum nächsten Biom, F fliegt und landet, T gräbt, G zeigt die Karte.
In neuem Tab öffnen

Kommentare

Die Kommentare sind GitHub Discussions: Zum Schreiben mit GitHub anmelden.

Die Kommentare kommen über giscus von GitHub. Beim Laden gehen deine IP-Adresse an giscus.app und GitHub.