Biome und Vegetation auf Voxel-Terrain in Babylon.js · Teil 8 von 12 der Serie
Teil 8: Blätter
Gib den Bäumen ihre Blätter: auf einen Canvas gemalte Blattzweige, als Karten entlang der Äste gesetzt, geneigt und gerollt, sodass dir immer einige ihr Gesicht zeigen, mit Normalen, die aus der Krone zeigen, Schatten tief in ihr und Licht, das durchscheint.
Biome und Vegetation auf Voxel-Terrain in Babylon.jsTeil 8 von 12
Auf dieser Seite
Quest-Ziele
- Blatt- und Nadelzweige auf einen Canvas malen, eine Ebene pro Sorte
- Karten entlang der Äste und Zweige setzen, zufällig geneigt und gerollt
- Die Blattzweige einer Fichte und einer Akazie flach halten, die einer Eiche frei
- Eine Krone als ein rundes Ding schattieren, mit Normalen, die aus ihr herauszeigen
- Die Blätter im Shader ausschneiden und Licht durch sie hindurchlassen
Die Bäume aus Teil 7 sind Skelette. Eine echte Eiche trägt ein paar hunderttausend Blätter, und kein Mesh kann sie sich einzeln leisten. Was ein Baum in einem Spiel stattdessen trägt, sind Blattzweige: flache Karten, jede mit dem Bild eines ganzen Zweigs voller Blätter darauf. Etwa hundert davon, entlang der Äste und Zweige gesetzt, lesen sich als Krone. Dieser Teil malt die Blattzweige, setzt die Karten und beleuchtet sie so, dass die Krone rund aussieht und nicht wie ein Stapel Papier.
Blätter im Textur-Array
Die Blattzweige liegen im selben Textur-Array wie die Rinden, sodass ein Mesh und ein Material einen ganzen Baum zeichnen. Fünf Ebenen kommen zu den vier Rinden: breite Blätter für die Eiche, kleinere und hellere für die Birke, die Nadeln einer Fichte und einer Kiefer und die gefiederten Blätter einer Akazie. Ersetze in src/trees.ts TREE_LAYERS:
/** The layers of the trees' texture array: the barks first, then the sprays of leaves. */
export const TREE_LAYERS = [
'oak bark',
'birch bark',
'conifer bark',
'cactus skin',
'broad leaves',
'birch leaves',
'spruce needles',
'pine needles',
'acacia leaves',
] as const;Eine Art sagt, welchen Blattzweig sie trägt, wie lang einer in Metern ist und wie flach ihre Blattzweige liegen. Die einer Eiche liegen, wie sie wollen. Die einer Fichte liegen fast waagrecht entlang ihrer Äste, und die einer Akazie bilden das flache Dach ihres Schirms. Ersetze im Interface Species das letzte Feld und die schließende Klammer:
bark: Layer;
/** The sprays of leaves, and how long one is in meters. None for a cactus. */
leaves: Layer | null;
spray: number;
/** How flat the sprays lie: 0 lets them tilt and roll any way, 1 keeps them level. */
flat: number;
}Und die Arten bekommen ihre Blätter. Ein Kaktus hat keine. Ersetze SPECIES:
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', leaves: 'broad leaves', spray: 2.7, flat: 0,
},
{
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', leaves: 'birch leaves', spray: 1.9, flat: 0.2,
},
{
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', leaves: 'spruce needles', spray: 2.4, flat: 0.8,
},
{
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', leaves: 'pine needles', spray: 2, flat: 0.3,
},
{
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', leaves: 'acacia leaves', spray: 2.3, flat: 0.85,
},
{
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', leaves: null, spray: 0, flat: 0,
},
];Wo die Blattzweige wachsen
Ein Blattzweig ist eine quadratische Karte. Sie beginnt an einem Punkt des Holzes, at, läuft size Meter entlang ihres Stiels stem und ist entlang side ebenso breit. Ein gewachsener Baum führt seine Blattzweige neben seinen Ästen. Füge nach dem Interface Limb das Interface Spray hinzu und ersetze Tree:
/** A spray of leaves: a card from `at`, `size` meters along `stem` and as wide along `side`. */
export interface Spray {
at: Vec;
stem: Vec;
side: Vec;
size: number;
}
/** A grown tree, before it is a mesh. */
export interface Tree {
species: Species;
height: number;
limbs: Limb[];
sprays: Spray[];
}Ein Blattzweig wächst in die Richtung, in die sein Ast geht: Sein Stiel zeigt entlang des Asts, der gemalte Zweig setzt also fort, wo das Holz endet. Läge aber jede Karte in derselben Ebene, zeigte ein Baum von der Seite nichts als ihre Kanten. Jede Karte wird deshalb geneigt, aus der Richtung ihres Asts nach oben oder unten und ein wenig zur Seite, und um ihren eigenen Stiel gerollt. Von wo du auch schaust, einige Blattzweige zeigen dir ihr Gesicht. Das flat der Art nimmt diese Freiheit wieder: Bei 1 neigt sich ein Blattzweig nur noch mit dem Hängen der Äste, und rollt ein Viertel so stark.
Beginne in growTree() nach der Liste der Äste eine weitere: const sprays: Spray[] = [];. Füge dann, nachdem der Stamm zu den Ästen gelegt ist, die Funktion hinzu, die einen Blattzweig wachsen lässt:
/**
* A spray of leaves at a point of a limb, growing on the way the limb goes. `scale`
* makes it smaller, where the crown is narrow.
*/
const leaf = (limb: Limb, t: number, scale: number) => {
if (!species.leaves) return;
const { point, direction } = along(limb, t);
// Out along the limb, tilted at random, and rolled about its own stem: seen from any
// side, some sprays always show their face. A flat spray tilts and rolls less.
const free = 1 - species.flat;
const tilt = between(-0.25, 0.45) * free + species.droop * species.flat * 0.5;
const stem = normalize(add(add(direction, UP, tilt), [between(-0.3, 0.3), 0, between(-0.3, 0.3)]));
const level = normalize(cross(stem, UP));
const roll = between(-1.2, 1.2) * (0.25 + 0.75 * free);
const side = normalize(add(level, cross(stem, level), Math.tan(roll) * 0.5));
const size = species.spray * scale * between(0.8, 1.2);
sprays.push({ at: add(point, stem, -size * 0.12), stem, side, size });
};stemist die Richtung des Asts, plus etwasUPfür die Neigung und ein zufälliger Schub zur Seite.levelliegt quer zum Stiel und waagrecht. Etwas von der Richtung dazu, die zu beiden senkrecht steht, rollt die Karte.Die Karte beginnt ein Stück hinter ihrem Punkt auf dem Ast, ein Achtel ihrer Größe zurück entlang des Stiels, sodass sie das Holz überlappt, aus dem sie wächst.
Jeder Ast trägt drei Blattzweige entlang seines äußeren Teils, und jeder Zweig drei weitere. Wo die Krone schmal ist, an der Spitze einer Fichte oder am unteren Rand der Kuppel einer Eiche, sind sie kleiner: bis zur Hälfte ihrer Größe, wo der Umriss 0 ist. Füge nach limbs.push(limb); hinzu:
// Where the crown is narrow, the sprays are small.
const scale = 0.5 + 0.5 * species.outline(share);
for (const t of [1, 0.8, 0.6]) leaf(limb, t, scale);Nach limbs.push(branch); bekommt der Zweig seine Blattzweige: for (const t of [1, 0.7, 0.4]) leaf(branch, t, scale);. Eine Eiche mit ihren 7 Ästen und 21 Zweigen trägt so 84 Blattzweige. Ein Stamm, der bis zur Spitze durchläuft, bekommt dort noch einen, und der Baum gibt seine Blattzweige mit seinen Ästen heraus. Ersetze die letzte Zeile von growTree():
// A leader carries leaves up to its tip.
if (species.leader) leaf(trunk, 1, 0.5);
return { species, height, limbs, sprays };Eine Krone, kein Kartenstapel
Beleuchte eine Karte mit ihrer eigenen Normale, und sie ist überall hell oder überall dunkel, und neben ihr hängt eine, bei der es umgekehrt ist: Die Krone flimmert wie ein Haufen Konfetti. Der Trick, der sie zu einem runden Ding macht, ist, den Karten die Normalen einer Kugel zu geben. Die Normale jeder Ecke zeigt von der Mitte der Krone zur Ecke und ein wenig nach oben. Die Seite der Krone, die zur Sonne zeigt, ist hell, die abgewandte dunkel, und dazwischen nimmt das Licht gleichmäßig ab, wie auch immer die einzelnen Karten liegen.
Dieselbe Kugel gibt den Schatten, die vierte Zahl von paint. Was tief in der Krone liegt, liegt im Schatten dessen, was darum herum ist: Der Schatten fällt von 1 am Rand der Krone auf 0,65 in ihrer Mitte, für die Blätter und für das Holz darin. Ein Kaktus hat keine Krone und bleibt bei 1.
Der Kommentar über TreeMesh kann seine letzten Worte verlieren: Der Schatten ist nicht mehr immer 1. Ersetze meshTree():
/** Makes the mesh of a grown tree: a tube around every limb, and a card for every spray. */
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);
// The crown, as a ball: what is deep inside it is in the shade of what is around it.
const crownY = height * (species.bare + 1) * 0.5;
const crownRadius = Math.max(species.spread * height, height * (1 - species.bare) * 0.5);
const shadeAt = (point: Vec) => {
if (!species.leaves) return 1;
const inside = 1 - Math.min(Math.hypot(point[0], point[1] - crownY, point[2]) / crownRadius, 1);
return 1 - 0.35 * inside;
};
const vertex = (point: Vec, normal: Vec, u: number, v: number, layer: number) => {
positions.push(...point);
normals.push(...normal);
paints.push(u, v, layer, shadeAt(point));
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 has no twigs to end in.
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);
}
}
// The sprays: a card each. Their normals point out of the crown, not out of the card,
// so that the light shades the crown as one round thing.
const leaves = species.leaves ? TREE_LAYERS.indexOf(species.leaves) : 0;
for (const { at, stem, side, size } of tree.sprays) {
const first = positions.length / 3;
for (const [u, v] of [[0, 0], [1, 0], [1, 1], [0, 1]]) {
const point = add(add(at, side, (u - 0.5) * size), stem, v * size);
const outward = normalize(add(normalize([point[0], point[1] - crownY, point[2]]), UP, 0.4));
vertex(point, outward, u, v, leaves);
}
indices.push(first, first + 1, first + 2, first, first + 2, first + 3);
}
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),
},
};
}Die Röhren sind, wie sie waren. Neu sind shadeAt(), das vertex() für jeden Vertex fragt, und die Schleife über die Blattzweige am Ende: vier Ecken und zwei Dreiecke pro Karte.
Die Blattzweige malen
Die Blattzweige werden gemalt wie die kleinen Pflanzen aus Teil 6: auf einem Canvas, mit den Helfern aus src/plants.ts, von der Mitte der unteren Kante nach oben wachsend. paintSprite() gibt die Bytes heraus und hat den durchsichtigen Pixeln schon die Durchschnittsfarbe des Blattzweigs gegeben, sodass die Blätter keine dunklen Ränder bekommen.
cloud()malt die breiten Blätter und die der Birke: ein paar hundert Blätter in einem Oval um einen Zweig, jedes mehr oder weniger von dort wegzeigend, wo der Zweig beginnt. Die dunklen Töne werden zuerst gemalt und landen unten, was dem Blattzweig etwas Tiefe gibt.Der Blattzweig der Fichte ist flach, wie am Baum: Seitenzweige zu beiden Seiten eines Stiels, zur Spitze hin kürzer, jeder eine Reihe kurzer Striche quer dazu.
Die Kiefer hat fünf Zweige, die in Büscheln langer Nadeln enden.
Die Akazie hat neun dünne Zweige, die sich weit auffächern, mit Paaren winziger Fiederblättchen an ihnen.
Die Typen sortieren die Namen der Ebenen danach, wie sie enden, in Rinden und Blätter. Ersetze src/treeTextures.ts:
import { dot, leaf, paintSprite, pick, type Context, type Painter } from './plants.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 = Extract<(typeof TREE_LAYERS)[number], `${string} bark` | `${string} skin`>;
type Leaves = Exclude<(typeof TREE_LAYERS)[number], Bark>;
/**
* 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);
},
};
})();
function line(ctx: Context, x0: number, y0: number, x1: number, y1: number, width: number, color: string): void {
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
ctx.lineWidth = width;
ctx.lineCap = 'round';
ctx.strokeStyle = color;
ctx.stroke();
}
/**
* A cloud of leaves around a twig: `count` leaves of about `size`, in an oval that is
* `width` and `height` from its middle to its rim. `colors` go from the darkest tones,
* painted first and so underneath, to the lightest.
*/
function cloud(ctx: Context, random: () => number, count: number, width: number, height: number, size: number, colors: string[][]): void {
line(ctx, 0, 0, 0, 0.5 + height * 0.6, 0.02, '#5b4632');
for (let i = 0; i < count; i += 1) {
const angle = random() * Math.PI * 2;
const reach = Math.sqrt(random());
const x = Math.cos(angle) * reach * width;
const y = 0.5 + Math.sin(angle) * reach * height;
const tones = colors[Math.floor((i / count) * colors.length)];
// Each leaf points more or less away from where the twig starts.
leaf(ctx, x, y, Math.atan2(x, y - 0.1) + (random() - 0.5) * 3, size * (0.8 + random() * 0.4), size * 0.4, pick(random, tones));
}
}
/** How to paint each spray of leaves: a twig from the middle of the bottom edge, as it grows off a branch. */
const SPRAYS: Record<Leaves, Painter> = {
'broad leaves': (ctx, random) =>
cloud(ctx, random, 330, 0.46, 0.46, 0.085, [['#2f5c22', '#386a28'], ['#447c2d', '#508c33'], ['#5e9c3a', '#6eae44']]),
'birch leaves': (ctx, random) =>
cloud(ctx, random, 200, 0.38, 0.46, 0.06, [['#4d7d2c', '#5a8d33'], ['#6fa23c', '#82b446'], ['#96c452', '#a9d05e']]),
// A flat spray of a spruce: twigs to both sides of the stem, each thick with needles.
'spruce needles': (ctx, random) => {
const needles = (x0: number, y0: number, x1: number, y1: number) => {
const steps = Math.ceil(Math.hypot(x1 - x0, y1 - y0) / 0.02);
const [nx, ny] = [-(y1 - y0), x1 - x0].map((c) => (c / Math.hypot(x1 - x0, y1 - y0)) * 0.035);
for (let i = 0; i <= steps; i += 1) {
const [x, y] = [x0 + ((x1 - x0) * i) / steps, y0 + ((y1 - y0) * i) / steps];
const color = pick(random, ['#24543f', '#2f6649', '#3b7653', '#4a885e']);
line(ctx, x - nx, y - ny + 0.02, x + nx, y + ny + 0.02, 0.012, color);
}
};
needles(0, 0, 0, 0.96);
for (let i = 0; i < 9; i += 1) {
const y = 0.05 + i * 0.1;
const length = 0.46 * (1 - i / 11);
for (const way of [-1, 1]) needles(0, y, way * length * (0.9 + random() * 0.2), y + length * 0.6);
}
},
// Twigs that end in tufts of long needles.
'pine needles': (ctx, random) => {
for (const [x, y] of [[0, 0.72], [-0.28, 0.55], [0.27, 0.5], [-0.14, 0.3], [0.16, 0.26]]) {
line(ctx, 0, 0, x, y, 0.022, '#6b4a33');
for (let i = 0; i < 46; i += 1) {
const angle = Math.atan2(x, y) + (random() - 0.5) * 3.4;
const length = 0.17 + random() * 0.09;
line(ctx, x, y, x + Math.sin(angle) * length, y + Math.cos(angle) * length, 0.012, pick(random, ['#2d5e3e', '#3a7147', '#488352', '#57945c']));
}
}
},
// Feathery leaves on twigs that fan out wide: a flat-topped spray.
'acacia leaves': (ctx, random) => {
for (let i = 0; i < 9; i += 1) {
const angle = (i - 4) * 0.3 + (random() - 0.5) * 0.15;
const length = 0.75 + random() * 0.2;
const color = pick(random, ['#5f8433', '#6f953b', '#80a646']);
line(ctx, 0, 0, Math.sin(angle) * length, Math.cos(angle) * length, 0.012, '#6d5a3a');
for (let step = 3; step <= 16; step += 1) {
const t = step / 16;
const [x, y] = [Math.sin(angle) * length * t, Math.cos(angle) * length * t];
leaf(ctx, x, y, angle + 1.1, 0.075, 0.02, color);
leaf(ctx, x, y, angle - 1.1, 0.075, 0.02, color);
}
}
dot(ctx, 0, 0, 0.015, '#6d5a3a');
},
};
/** 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) => {
if (name in SPRAYS) {
data.set(paintSprite(TREE_TEXTURE, SPRAYS[name as Leaves], layer + 20), layer * pixels * 4);
return;
}
const paint = BARKS[name as Bark];
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;
}Ausschneiden und beleuchten
Der Fragment-Shader wirft die Pixel zwischen den Blättern weg, wie der Shader der Pflanzen. Rinde ist undurchsichtig, dort greift der Test also nie. Blätter bekommen außerdem ihr eigenes Licht. Ein Blatt ist dünn: Von hinten beleuchtet, leuchtet es. Ein Viertel des Sonnenlichts zählt deshalb für die Seite, die von ihr abgewandt ist, und das Licht des Himmels wird zu dem hin angehoben, was ein offener Platz bekommt, denn es findet seinen Weg zwischen den Blättern hinein. Der Shader muss wissen, welche Ebenen Blätter sind: Das Uniform firstLeaves ist die Nummer der ersten. Ersetze 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;
// The number of the first layer that holds leaves: the ones before it are bark.
uniform float firstLeaves;
void main() {
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;
vec3 normal = normalize(vNormal);
float sun = max(dot(normal, -sunDirection), 0.0);
vec3 ambient = mix(groundColor, skyColor, normal.y * 0.5 + 0.5);
// Leaves let some of the light through: their far side is not all dark.
if (layer >= firstLeaves) {
sun = sun * 0.75 + max(dot(normal, sunDirection), 0.0) * 0.25;
ambient = mix(ambient, skyColor, 0.5) * 1.2;
}
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);
}Das Material nennt das Uniform und setzt es: die erste Ebene, deren Name Blätter oder Nadeln sagt. Ersetze in src/treeMaterial.ts createTreeMaterial():
/** The trees' material: bark and leaves 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, 'firstLeaves'],
samplers: ['layers'],
},
);
material.setTexture('layers', layers);
setLight(material, options);
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;
}Dass das Material beide Seiten jedes Dreiecks zeichnet, war in Teil 7 ein Versprechen. Jetzt wird es gebraucht: Ein Blattzweig wird von oben und von unten gesehen.
Ausprobieren
Dreh dich am Start nach links und geh wieder in die Baumschule. Die Eichen haben jetzt Kuppeln, die Birken dünne, helle Kronen, die Fichten Stockwerke aus flachen Blattzweigen und die Akazien ihre Schirme. Die Kakteen sind so kahl wie zuvor. Stell dich unter eine Eiche und schau nach oben: Du siehst die einzelnen Karten, in alle Richtungen geneigt. Geh dann zurück, bis sie zu einer Krone verschmelzen, und geh um sie herum: Die Seite zur Sonne bleibt hell, welche Karten dir auch gerade zugewandt sind. Setz in src/trees.ts das flat der Eiche auf 1 und lade neu, um zu sehen, warum ihre Blattzweige ihre Freiheit brauchen, und probier ein spray von 1.5 für einen Baum, der einen trockenen Sommer hinter sich hat.
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.
