Wind-Shader für Pixel Art: Gras und Bäume, die sich biegen
Wind lässt Gras und Bäume hin und her schwanken. So wirkt eine stille Landschaft lebendig, und der Spieler merkt, dass Wind weht. In Pixel Art schiebt der Shader jede Zeile der Pflanze um ganze Pixel zur Seite, die oberen weiter, und lässt die Zeile am Boden, wo sie ist. Du zeichnest die Pflanze einmal; das Schwanken macht die Regel, ohne ein einziges Extrabild Animation.

Nur die Eiche, das Gras und die Blumen bekommen die Regel. Jede ihrer Zeilen rückt um die ganzen Pixel der Welle zur Seite, umso mehr, je höher sie über dem Boden steht; die Zeile am Boden bewegt sich nicht. Die Böen kommen und gehen.
Auch in dieser Lektion 4 Lesetipps zum Vertiefen 3 Fragen zum Selbsttest
Die Idee
Ein Baum steckt unten fest und ist oben frei. Drückt der Wind gegen ihn, wandert die Krone am weitesten, der Stamm biegt sich, und die Wurzeln bleiben in der Erde. In einem Bild aus Zeilen ist das leicht nachzumachen: Schieb jede Zeile zur Seite, umso weiter, je höher sie liegt, und lass die unterste stehen. Du siehst das auf einem Hügel im Hintergrund eines Levels, in hohem Gras vor einem Sturm, im Schilf an einem Teich.
Das Schwanken kommt aus einer Welle, und in Pixel Art ist eine Welle eine kurze Liste ganzer Zahlen, keine glatte Kurve. Eine Kurve würde die Krone meistens zwischen zwei Pixel stellen, an einen Platz, den ein Bild aus Pixeln nicht hat, und rundest du sie in jedem Bild, werden die Schritte ungleich lang. Die Welle dieses Kurses sind sechzehn Zahlen: 0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1. Sie bleibt drei Schritte lang bei 2, in dem Moment, in dem ein Ast ganz außen hängt, bevor er zurückschwingt, und geht in einem Schritt durch die 0, dort, wo ein Ast am schnellsten ist. Jeder Schritt dauert gleich viele Ticks, also hält der Baum auf jedem Gerät seinen Takt.
So funktioniert es
Für jeden Pixel fragt die Regel zuerst nach der Zeit: Die Zahl der Ticks geteilt durch das Tempo ist der Schritt der Welle, sechzehn Schritte und dann wieder von vorn. Die Zahl der Welle dort, von -2 bis 2, mal die Stärke ist, wie weit sich die Spitze der Pflanze gerade neigt.
Dann fragt sie, wie weit ihre eigene Zeile über der Wurzel liegt. An der Wurzel ist das 0, und die Zeile bleibt stehen. Ab der Höhe, hier 32 Zeilen, bekommt die Zeile die volle Neigung, dazwischen ihren Anteil in ganzen Pixeln, abgerundet. Der Anteil wird ohne Vorzeichen ausgerechnet, deshalb geht eine Zeile genauso weit nach links wie nach rechts. Zuletzt zeigt der Pixel, was so weit neben ihm stand: Eine Zeile, die sich 3 Pixel nach rechts neigt, liest den Pixel 3 links von ihr.
Im Bild bekommen nur die Eiche, das Gras und die Blumen die Regel; der Hügel, die Bienenstöcke und die Imkerin liegen dahinter und stehen still. Der Regler Stärke geht von 0 bis 3: Bei 3 schwingt die Krone 6 Pixel nach jeder Seite. Der Regler Tempo sagt, wie viele Ticks ein Schritt dauert: Bei 4 dauert ein ganzes Hin und Her 64 Ticks, etwas mehr als eine Sekunde.
Was schiefgeht
Die Zeilen eines Bildes werden von oben gezählt: Zeile 0 ist die höchste. Eine KI, die „je höher die Zeile, desto mehr Schwanken“ will, nimmt oft die Nummer der Zeile oder die senkrechte Stelle auf der Textur als Höhe. Auf einer Textur zählt diese Stelle in manchen Engines von oben und in anderen von unten. Falsch herum genommen bekommt die unterste Zeile das meiste Schwanken und die oberste gar keins.
Schalte das Bild auf „Mit dem Fehler“. Der Fuß der Eiche rutscht über den Boden hin und her, während ihre Krone stillsteht, und das Gras gleitet über die Erde wie ein loser Teppich.
Zwei Tests fangen das: „the root row never moves, whatever the time“ (die Wurzelzeile bewegt sich nie) beobachtet sechzehn Ticks lang die unterste Zeile eines kleinen Grashalms, und „the higher a row stands above the root, the further it sways“ (je höher die Zeile, desto weiter schwankt sie) vergleicht jede Zeile mit der darunter.
Der Fehler, Zeile für Zeile
- /* Wind sway, with the mistake: the rule counts the height from the top of the plant down, because
- the rows of a picture are counted from the top. So the lowest row gets the most sway and the top
- the least: the root slides back and forth over the ground, and the crown stands still.
+ /* Wind sway: grass and a tree that bend in the wind. Every row of the sprite is moved sideways by
+ whole pixels, by a wave that runs in ticks, and the higher a row stands above the root, the
+ further it goes. The root row does not move, so the plant stays in the ground while its top sways.
+ The wave is a short list of whole numbers, not a curve: a pixel cannot move half a pixel, and the
+ list stays at its far end for three steps, the way a branch hangs there before it swings back.
+
From the course "Shaders for pixel art" on spielerando.com.
SPDX-License-Identifier: MIT */
…
}
- /** The rule, wrong: the sway grows downward, so the root moves the most. */
+ /** The rule: a row that sways to the right shows what stands that far to its left. */
export function shade(x: number, y: number, tick: number, src: Frame, p: Params = DEFAULTS): number {
const tall = Math.max(1, p.height);
const wave = WAVE[Math.floor(tick / Math.max(1, p.pace)) & 15];
- // wrong: the row's number grows downward, and here it is taken for how high the row stands
- const above = Math.min(Math.max(y - (p.root - tall), 0), tall);
+ // how far this row stands above the root: 0 at the root and below it, at most the height
+ const above = Math.min(Math.max(p.root - y, 0), tall);
// this row's share of the sway in whole pixels, worked out without the sign, so that it
// rounds the same way to the left as to the rightWas der Test zum Fehler sagt
✖ the root row never moves, whatever the time
at tick 1
got 1, expected 0
✖ the higher a row stands above the root, the further it sways
at tick 1 row 2 moves 0, the row below it 1
✖ at the full height a row sways the wave's number times the strength, both ways
got 0, expected 2
✔ with no wind nothing moves
✔ after 16 steps of the wave every row is back where it started
✔ a row moves as a whole and keeps its colours
✔ neighbouring rows part by one pixel at most, so the stem does not break
7 tests: 4 passed, 3 failedDas sagst du deiner KI
Schreib einen Wind-Shader für mein Sprite [Gras / Baum / Pflanze], in Pixel Art.
- Arbeite mit ganzen Pixeln: Jede Zeile des Sprites rückt um eine ganze Zahl von Pixeln zur Seite. Kein Glätten, kein Mischen. Lies die Textur ohne Filter (nearest).
- Die Welle ist diese Liste aus 16 ganzen Zahlen, kein Sinus: 0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1. Ihr Schritt ist die Zahl der Ticks des Spiels geteilt durch [Tempo, zum Beispiel 4], umgebrochen auf 16 Schritte.
- Die Pflanze wächst aus Zeile [Wurzel: die unterste Zeile des Sprites], und diese Zeile bewegt sich nie. Die Verschiebung einer Zeile ist die Zahl der Welle mal [Stärke] mal ihre Höhe über der Wurzel, geteilt durch [Höhe in Zeilen]. Begrenze die Höhe dort. Rechne den Anteil ohne Vorzeichen aus und setz das Vorzeichen danach wieder davor, damit links und rechts gleich gerundet werden.
- Die Zeilen eines Bildes werden von oben gezählt. Achte darauf, dass „höher“ weiter über der Wurzel heißt und nicht eine größere Zeilennummer.
Schreib vor dem Shader dieselbe Regel als kleine, einfache Funktion. Sie bekommt ein Raster aus ganzen Zahlen (0 = leer, 1 bis N = die Farben meiner Palette), einen Platz und den Tick und gibt die Zahl für diesen einen Pixel zurück. Teste sie: Die Wurzelzeile bewegt sich bei keinem Tick; eine höhere Zeile schwankt mindestens so weit wie eine tiefere; bei Stärke 0 bewegt sich nichts; nach 16 Schritten ist das Bild wieder dasselbe. Zeig mir die Ausgabe des Tests. Schreib dann den Shader so, dass er genau das tut, was die Funktion tut.
Der Code
Dreimal dieselbe Regel. Die erste ist die, die wir testen; die beiden Shader sind diese Regel in einer Shader-Sprache, und die läuft in deinem Spiel.
Die Regel, getestet: shader.ts
/* Wind sway: grass and a tree that bend in the wind. Every row of the sprite is moved sideways by
whole pixels, by a wave that runs in ticks, and the higher a row stands above the root, the
further it goes. The root row does not move, so the plant stays in the ground while its top sways.
The wave is a short list of whole numbers, not a curve: a pixel cannot move half a pixel, and the
list stays at its far end for three steps, the way a branch hangs there before it swings back.
From the course "Shaders for pixel art" on spielerando.com.
SPDX-License-Identifier: MIT */
export interface Frame {
width: number;
height: number;
index: Uint8Array;
}
export const DEFAULTS = {
/** The row the plants grow from, counted from the top of the picture. It never moves. */
root: 119,
/** How many rows above the root the sway is at its fullest. Rows higher up go just as far. */
height: 32,
/** How far the tops go: the wave's number times this, in whole pixels. 0 or more. */
strength: 2,
/** Ticks for one step of the wave. Its 16 steps take 16 times this. */
pace: 4,
};
export type Params = typeof DEFAULTS;
/** A wave in whole pixels, 16 steps long. */
const WAVE = [0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1];
/** The number at a place of the picture; outside the picture nothing is. */
export function at(src: Frame, x: number, y: number): number {
if (x < 0 || y < 0 || x >= src.width || y >= src.height) return 0;
return src.index[y * src.width + x];
}
/** The rule: a row that sways to the right shows what stands that far to its left. */
export function shade(x: number, y: number, tick: number, src: Frame, p: Params = DEFAULTS): number {
const tall = Math.max(1, p.height);
const wave = WAVE[Math.floor(tick / Math.max(1, p.pace)) & 15];
// how far this row stands above the root: 0 at the root and below it, at most the height
const above = Math.min(Math.max(p.root - y, 0), tall);
// this row's share of the sway in whole pixels, worked out without the sign, so that it
// rounds the same way to the left as to the right
const amount = Math.floor((Math.abs(wave) * p.strength * above) / tall);
const shift = wave < 0 ? -amount : amount;
return at(src, x - shift, y);
}
Dieselbe Regel als Shader: GLSL
#version 300 es
// A shader the pixel art way: a pixel is a whole number, 0 where nothing is, 1 to 25 for the
// palette's colours. The rule is shade(): it is asked for every pixel and answers with a number.
// Everything outside the marked part is the same for every rule. Put your own palette in PALETTE.
precision highp float;
precision highp int;
uniform sampler2D SRC; // the picture, sampled without smoothing (nearest)
uniform sampler2D OTHER; // a second picture, where the rule uses one
uniform int TICK; // the time in ticks, 60 a second, counted by the game
const vec3 PALETTE[26] = vec3[26](
vec3(0.0),
vec3(31.0, 33.0, 66.0) / 255.0, // 1: k
vec3(75.0, 78.0, 112.0) / 255.0, // 2: n
vec3(120.0, 123.0, 152.0) / 255.0, // 3: m
vec3(198.0, 199.0, 227.0) / 255.0, // 4: e
vec3(255.0, 255.0, 255.0) / 255.0, // 5: w
vec3(246.0, 241.0, 233.0) / 255.0, // 6: c
vec3(214.0, 205.0, 189.0) / 255.0, // 7: d
vec3(242.0, 193.0, 78.0) / 255.0, // 8: y
vec3(224.0, 138.0, 46.0) / 255.0, // 9: o
vec3(194.0, 65.0, 45.0) / 255.0, // 10: r
vec3(244.0, 163.0, 160.0) / 255.0, // 11: p
vec3(47.0, 98.0, 240.0) / 255.0, // 12: b
vec3(35.0, 83.0, 214.0) / 255.0, // 13: u
vec3(157.0, 184.0, 255.0) / 255.0, // 14: s
vec3(234.0, 240.0, 255.0) / 255.0, // 15: a
vec3(207.0, 224.0, 255.0) / 255.0, // 16: i
vec3(15.0, 138.0, 76.0) / 255.0, // 17: g
vec3(124.0, 207.0, 154.0) / 255.0, // 18: l
vec3(226.0, 244.0, 234.0) / 255.0, // 19: f
vec3(138.0, 90.0, 60.0) / 255.0, // 20: t
vec3(92.0, 59.0, 40.0) / 255.0, // 21: h
vec3(109.0, 76.0, 230.0) / 255.0, // 22: v
vec3(201.0, 187.0, 255.0) / 255.0, // 23: q
vec3(18.0, 20.0, 43.0) / 255.0, // 24: x
vec3(39.0, 43.0, 82.0) / 255.0 // 25: z
);
// Which colour of the palette is this? 0 where nothing is drawn.
int number(vec4 c) {
if (c.a < 0.5) return 0;
int best = 1;
float least = 9.0;
for (int i = 1; i <= 25; i++) {
vec3 d = c.rgb - PALETTE[i];
float away = dot(d, d);
if (away < least) {
least = away;
best = i;
}
}
return best;
}
// The number at a place of the picture; outside the picture nothing is.
int at(ivec2 p) {
ivec2 size = textureSize(SRC, 0);
if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
return number(texelFetch(SRC, p, 0));
}
// The same for the second picture.
int otherAt(ivec2 p) {
ivec2 size = textureSize(OTHER, 0);
if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
return number(texelFetch(OTHER, p, 0));
}
// a wrapped into 0 .. n-1, also for a below zero (the % sign is not safe there)
int wrap(int a, int n) {
return a - n * int(floor(float(a) / float(n)));
}
// ---- the rule ----
uniform int root; // the row the plants grow from, counted from the top of the picture. It never moves.
uniform int height; // how many rows above the root the sway is at its fullest. Rows higher up go just as far.
uniform int strength; // how far the tops go: the wave's number times this, in whole pixels. 0 or more.
uniform int pace; // ticks for one step of the wave. Its 16 steps take 16 times this.
// a wave in whole pixels, 16 steps long
const int WAVE[16] = int[16](0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1);
// a row that sways to the right shows what stands that far to its left
int shade(ivec2 p) {
int tall = max(1, height);
int wave = WAVE[(TICK / max(1, pace)) & 15];
// how far this row stands above the root: 0 at the root and below it, at most the height
int above = min(max(root - p.y, 0), tall);
// this row's share of the sway in whole pixels, worked out without the sign, so that it
// rounds the same way to the left as to the right
int amount = abs(wave) * strength * above / tall;
int shift = wave < 0 ? -amount : amount;
return at(ivec2(p.x - shift, p.y));
}
// ---- end of the rule ----
out vec4 FRAGMENT;
void main() {
// the pixel's place, counted from the top left as in the picture
ivec2 p = ivec2(int(gl_FragCoord.x), textureSize(SRC, 0).y - 1 - int(gl_FragCoord.y));
int n = shade(p);
FRAGMENT = n == 0 ? vec4(0.0) : vec4(PALETTE[n], 1.0);
}
Dieselbe Regel für Godot 4
shader_type canvas_item;
// A shader the pixel art way: a pixel is a whole number, 0 where nothing is, 1 to 25 for the
// palette's colours. The rule is shade(): it is asked for every pixel and answers with a number.
// Everything outside the marked part is the same for every rule. Put your own palette in PALETTE.
//
// Put this on the sprite, and give it the sprite's own picture once:
// material.set_shader_parameter("SRC", texture)
uniform sampler2D SRC : filter_nearest;
uniform sampler2D OTHER : filter_nearest; // a second picture, where the rule uses one
// The time in ticks, 60 a second. The game counts it itself: add 1 in the _physics_process of a
// node that pauses with the game, and set it there, so a paused game pauses its shaders:
// tick += 1
// material.set_shader_parameter("TICK", tick)
uniform int TICK;
const vec3 PALETTE[26] = vec3[26](
vec3(0.0),
vec3(31.0, 33.0, 66.0) / 255.0, // 1: k
vec3(75.0, 78.0, 112.0) / 255.0, // 2: n
vec3(120.0, 123.0, 152.0) / 255.0, // 3: m
vec3(198.0, 199.0, 227.0) / 255.0, // 4: e
vec3(255.0, 255.0, 255.0) / 255.0, // 5: w
vec3(246.0, 241.0, 233.0) / 255.0, // 6: c
vec3(214.0, 205.0, 189.0) / 255.0, // 7: d
vec3(242.0, 193.0, 78.0) / 255.0, // 8: y
vec3(224.0, 138.0, 46.0) / 255.0, // 9: o
vec3(194.0, 65.0, 45.0) / 255.0, // 10: r
vec3(244.0, 163.0, 160.0) / 255.0, // 11: p
vec3(47.0, 98.0, 240.0) / 255.0, // 12: b
vec3(35.0, 83.0, 214.0) / 255.0, // 13: u
vec3(157.0, 184.0, 255.0) / 255.0, // 14: s
vec3(234.0, 240.0, 255.0) / 255.0, // 15: a
vec3(207.0, 224.0, 255.0) / 255.0, // 16: i
vec3(15.0, 138.0, 76.0) / 255.0, // 17: g
vec3(124.0, 207.0, 154.0) / 255.0, // 18: l
vec3(226.0, 244.0, 234.0) / 255.0, // 19: f
vec3(138.0, 90.0, 60.0) / 255.0, // 20: t
vec3(92.0, 59.0, 40.0) / 255.0, // 21: h
vec3(109.0, 76.0, 230.0) / 255.0, // 22: v
vec3(201.0, 187.0, 255.0) / 255.0, // 23: q
vec3(18.0, 20.0, 43.0) / 255.0, // 24: x
vec3(39.0, 43.0, 82.0) / 255.0 // 25: z
);
// Which colour of the palette is this? 0 where nothing is drawn.
int number(vec4 c) {
if (c.a < 0.5) return 0;
int best = 1;
float least = 9.0;
for (int i = 1; i <= 25; i++) {
vec3 d = c.rgb - PALETTE[i];
float away = dot(d, d);
if (away < least) {
least = away;
best = i;
}
}
return best;
}
// The number at a place of the picture; outside the picture nothing is.
int at(ivec2 p) {
ivec2 size = textureSize(SRC, 0);
if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
return number(texelFetch(SRC, p, 0));
}
// The same for the second picture.
int otherAt(ivec2 p) {
ivec2 size = textureSize(OTHER, 0);
if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
return number(texelFetch(OTHER, p, 0));
}
// a wrapped into 0 .. n-1, also for a below zero (the % sign is not safe there)
int wrap(int a, int n) {
return a - n * int(floor(float(a) / float(n)));
}
// ---- the rule ----
uniform int root; // the row the plants grow from, counted from the top of the picture. It never moves.
uniform int height; // how many rows above the root the sway is at its fullest. Rows higher up go just as far.
uniform int strength; // how far the tops go: the wave's number times this, in whole pixels. 0 or more.
uniform int pace; // ticks for one step of the wave. Its 16 steps take 16 times this.
// a wave in whole pixels, 16 steps long
const int WAVE[16] = int[16](0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1);
// a row that sways to the right shows what stands that far to its left
int shade(ivec2 p) {
int tall = max(1, height);
int wave = WAVE[(TICK / max(1, pace)) & 15];
// how far this row stands above the root: 0 at the root and below it, at most the height
int above = min(max(root - p.y, 0), tall);
// this row's share of the sway in whole pixels, worked out without the sign, so that it
// rounds the same way to the left as to the right
int amount = abs(wave) * strength * above / tall;
int shift = wave < 0 ? -amount : amount;
return at(ivec2(p.x - shift, p.y));
}
// ---- end of the rule ----
void fragment() {
ivec2 p = ivec2(UV * vec2(textureSize(SRC, 0)));
int n = shade(p);
COLOR = n == 0 ? vec4(0.0) : vec4(PALETTE[n], 1.0);
}
Der Test: shader.test.ts
import assert from "node:assert/strict";
import { test } from "node:test";
import { DEFAULTS, type Frame, shade } from "./shader.ts";
/** A tiny picture from rows of digits: 0 is nothing, 1 to 9 are colours. */
function picture(rows: string[]): Frame {
return { width: rows[0].length, height: rows.length, index: Uint8Array.from(rows.join(""), Number) };
}
/** A stalk of grass, one pixel wide: its tip in the top row, its root in row 5. */
const STALK = picture([
"000020000",
"000020000",
"000020000",
"000020000",
"000020000",
"000070000",
]);
/** A small tree with a crown and a trunk, rooted in row 5. */
const SAPLING = picture([
"000777000",
"007787700",
"077777770",
"000080000",
"000080000",
"000880000",
]);
/** The stalk's root is row 5, it sways fully at 5 rows above it, and one step of the wave is one tick. */
const SMALL = { ...DEFAULTS, root: 5, height: 5, strength: 1, pace: 1 };
function whole(src: Frame, tick: number, params = SMALL): number[] {
const out: number[] = [];
for (let y = 0; y < src.height; y++) for (let x = 0; x < src.width; x++) out.push(shade(x, y, tick, src, params));
return out;
}
/** How far each row of the stalk has moved: where its one pixel is now, minus where it was. */
function shifts(tick: number, params = SMALL): number[] {
const out = whole(STALK, tick, params);
const moved: number[] = [];
for (let y = 0; y < STALK.height; y++) moved.push(out.slice(y * STALK.width, (y + 1) * STALK.width).findIndex((n) => n !== 0) - 4);
return moved;
}
test("the root row never moves, whatever the time", () => {
for (let tick = 0; tick < 16; tick++) assert.equal(shifts(tick)[5], 0, `at tick ${tick}`);
});
test("the higher a row stands above the root, the further it sways", () => {
for (let tick = 0; tick < 16; tick++) {
const s = shifts(tick, { ...SMALL, strength: 2 });
for (let y = 0; y < 5; y++) assert.ok(Math.abs(s[y]) >= Math.abs(s[y + 1]), `at tick ${tick} row ${y} moves ${s[y]}, the row below it ${s[y + 1]}`);
}
});
test("at the full height a row sways the wave's number times the strength, both ways", () => {
// the wave is 2 at its fourth step and -2 at its twelfth
assert.equal(shifts(4)[0], 2);
assert.equal(shifts(12)[0], -2);
assert.equal(shifts(4, { ...SMALL, strength: 2 })[0], 4);
});
test("with no wind nothing moves", () => {
for (let tick = 0; tick < 16; tick++) assert.deepEqual(whole(SAPLING, tick, { ...SMALL, strength: 0 }), [...SAPLING.index]);
});
test("after 16 steps of the wave every row is back where it started", () => {
const slow = { ...SMALL, pace: 3 };
for (let tick = 0; tick < 48; tick++) assert.deepEqual(whole(SAPLING, tick + 48, slow), whole(SAPLING, tick, slow), `at tick ${tick}`);
// one step lasts `pace` ticks: the first three ticks are the same picture, the fourth is not
assert.deepEqual(whole(SAPLING, 2, slow), whole(SAPLING, 0, slow));
assert.notDeepEqual(whole(SAPLING, 3, slow), whole(SAPLING, 0, slow));
});
test("a row moves as a whole and keeps its colours", () => {
for (let tick = 0; tick < 16; tick++) {
const out = whole(SAPLING, tick);
for (let y = 0; y < SAPLING.height; y++) {
const row = out.slice(y * SAPLING.width, (y + 1) * SAPLING.width).filter((n) => n !== 0);
const before = [...SAPLING.index.slice(y * SAPLING.width, (y + 1) * SAPLING.width)].filter((n) => n !== 0);
assert.deepEqual(row, before, `at tick ${tick} row ${y}`);
}
}
});
test("neighbouring rows part by one pixel at most, so the stem does not break", () => {
for (let tick = 0; tick < 16; tick++) {
const s = shifts(tick, { ...SMALL, strength: 2 });
for (let y = 0; y < 5; y++) assert.ok(Math.abs(s[y] - s[y + 1]) <= 1, `at tick ${tick} rows ${y} and ${y + 1} are ${s[y]} and ${s[y + 1]}`);
}
});
- 7 Tests bestehen mit der Regel.
- Mit dem eingebauten Fehler schlagen 3 davon fehl: "the root row never moves, whatever the time", "the higher a row stands above the root, the further it sways", "at the full height a row sways the wave's number times the strength, both ways".
- Der Fehler ist im Bild oben zu sehen: Schalte auf „Mit dem Fehler“.
- Der Shader lief in einem Browser (Chrome/158.0.8127.37) auf 12 Bildern und ergab in 388.800 von 388.800 Pixeln das Bild der Regel.
Probier es aus
- Zieh die Stärke auf 0 und dann auf 3. Bei 0 bewegt sich gar nichts. Bei 3 schwingt die Krone weit und in einem Stück, der Stamm biegt sich auf seiner ganzen Länge, und die Grasspitzen bewegen sich weniger als die Krone, weil sie tiefer liegen.
- Zieh das Tempo auf 1 und dann auf 12. Bei 1 dauert ein ganzes Hin und Her 16 Ticks, und die Pflanzen flattern wie im Sturm; bei 12 neigen sie sich langsam in einer leichten Brise.
- Schalte auf „Mit dem Fehler“ und schau auf die Bodenlinie, nicht auf die Krone: Der Fuß des Stamms und das Gras rutschen. Mit der Regel ist die Bodenlinie ruhig.
Zum Nachlesen
Wo es tiefer geht: unsere Seiten, auf denen diese Lektion aufbaut, und was andere zu ihrem Punkt geschrieben haben.
Ein Baum, der sich an jedem Ast biegt statt Zeile für Zeile, von Code aus einer Startzahl gewachsen, bei dem kleinere Äste den größeren folgen und stärkerer Wind ihn weiter bewegt, nie schneller.
Hier schwingen alle Pflanzen im Gleichtakt, und die Welle kommt immer wieder. Das Rezept addiert Wellen, deren Längen nicht ineinander aufgehen, mit eigener Startzahl, damit sich eine Menge nie wie eine bewegt.
Hitzeflimmern als Shader für Pixel Art: ohne zerfranste Ränder
Dieselbe Welle aus ganzen Zahlen schiebt Zeilen zur Seite, steigt aber durch ein Band heißer Luft nach oben, dazu der Rand des Bildes, wo eine verschobene Zeile nichts hereinholt, wenn die Regel den Rand nicht wiederholt.
Converting GLSL to Godot shaders
Godots eigener Hinweis, dass sein UV im Vergleich zu den Pixelkoordinaten von GLSL auf dem Kopf steht: der Grund, warum eine übernommene Regel fürs Schwanken von oben nach unten wachsen kann.
Teste dich: drei Fragen
Jede Antwort wird sofort geprüft und erklärt. Die Fragen gehören zum Quiz und zählen für deinen Game Coder IQ wie jede andere.
Ein Baum schwankt im Wind dieser Lektion. Welchen Teil bewegt die Regel am weitesten, und welchen gar nicht?
Nächste Lektion Wasserspiegelung als Shader in Pixel Art: spiegeln, dunkeln, kräuseln
Gib deiner KI die ganze Lektion
Der Knopf kopiert, was du ihr sagst, zusammen mit der getesteten Regel, ihrem Test und beiden Shadern. So hat deine KI alles, um das in dein Spiel zu bauen und dir zu zeigen, dass es funktioniert.
Das ist eine Lektion aus dem Kurs „Shader für Pixel Art“ auf spielerando.com: https://spielerando.com/de/courses/pixel-shaders/wind-sway
Schreib einen Wind-Shader für mein Sprite [Gras / Baum / Pflanze], in Pixel Art.
- Arbeite mit ganzen Pixeln: Jede Zeile des Sprites rückt um eine ganze Zahl von Pixeln zur Seite. Kein Glätten, kein Mischen. Lies die Textur ohne Filter (nearest).
- Die Welle ist diese Liste aus 16 ganzen Zahlen, kein Sinus: 0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1. Ihr Schritt ist die Zahl der Ticks des Spiels geteilt durch [Tempo, zum Beispiel 4], umgebrochen auf 16 Schritte.
- Die Pflanze wächst aus Zeile [Wurzel: die unterste Zeile des Sprites], und diese Zeile bewegt sich nie. Die Verschiebung einer Zeile ist die Zahl der Welle mal [Stärke] mal ihre Höhe über der Wurzel, geteilt durch [Höhe in Zeilen]. Begrenze die Höhe dort. Rechne den Anteil ohne Vorzeichen aus und setz das Vorzeichen danach wieder davor, damit links und rechts gleich gerundet werden.
- Die Zeilen eines Bildes werden von oben gezählt. Achte darauf, dass „höher“ weiter über der Wurzel heißt und nicht eine größere Zeilennummer.
Schreib vor dem Shader dieselbe Regel als kleine, einfache Funktion. Sie bekommt ein Raster aus ganzen Zahlen (0 = leer, 1 bis N = die Farben meiner Palette), einen Platz und den Tick und gibt die Zahl für diesen einen Pixel zurück. Teste sie: Die Wurzelzeile bewegt sich bei keinem Tick; eine höhere Zeile schwankt mindestens so weit wie eine tiefere; bei Stärke 0 bewegt sich nichts; nach 16 Schritten ist das Bild wieder dasselbe. Zeig mir die Ausgabe des Tests. Schreib dann den Shader so, dass er genau das tut, was die Funktion tut.
Die Regel, getestet (shader.ts):
```ts
/* Wind sway: grass and a tree that bend in the wind. Every row of the sprite is moved sideways by
whole pixels, by a wave that runs in ticks, and the higher a row stands above the root, the
further it goes. The root row does not move, so the plant stays in the ground while its top sways.
The wave is a short list of whole numbers, not a curve: a pixel cannot move half a pixel, and the
list stays at its far end for three steps, the way a branch hangs there before it swings back.
From the course "Shaders for pixel art" on spielerando.com.
SPDX-License-Identifier: MIT */
export interface Frame {
width: number;
height: number;
index: Uint8Array;
}
export const DEFAULTS = {
/** The row the plants grow from, counted from the top of the picture. It never moves. */
root: 119,
/** How many rows above the root the sway is at its fullest. Rows higher up go just as far. */
height: 32,
/** How far the tops go: the wave's number times this, in whole pixels. 0 or more. */
strength: 2,
/** Ticks for one step of the wave. Its 16 steps take 16 times this. */
pace: 4,
};
export type Params = typeof DEFAULTS;
/** A wave in whole pixels, 16 steps long. */
const WAVE = [0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1];
/** The number at a place of the picture; outside the picture nothing is. */
export function at(src: Frame, x: number, y: number): number {
if (x < 0 || y < 0 || x >= src.width || y >= src.height) return 0;
return src.index[y * src.width + x];
}
/** The rule: a row that sways to the right shows what stands that far to its left. */
export function shade(x: number, y: number, tick: number, src: Frame, p: Params = DEFAULTS): number {
const tall = Math.max(1, p.height);
const wave = WAVE[Math.floor(tick / Math.max(1, p.pace)) & 15];
// how far this row stands above the root: 0 at the root and below it, at most the height
const above = Math.min(Math.max(p.root - y, 0), tall);
// this row's share of the sway in whole pixels, worked out without the sign, so that it
// rounds the same way to the left as to the right
const amount = Math.floor((Math.abs(wave) * p.strength * above) / tall);
const shift = wave < 0 ? -amount : amount;
return at(src, x - shift, y);
}
```
Ihr Test (shader.test.ts):
```ts
import assert from "node:assert/strict";
import { test } from "node:test";
import { DEFAULTS, type Frame, shade } from "./shader.ts";
/** A tiny picture from rows of digits: 0 is nothing, 1 to 9 are colours. */
function picture(rows: string[]): Frame {
return { width: rows[0].length, height: rows.length, index: Uint8Array.from(rows.join(""), Number) };
}
/** A stalk of grass, one pixel wide: its tip in the top row, its root in row 5. */
const STALK = picture([
"000020000",
"000020000",
"000020000",
"000020000",
"000020000",
"000070000",
]);
/** A small tree with a crown and a trunk, rooted in row 5. */
const SAPLING = picture([
"000777000",
"007787700",
"077777770",
"000080000",
"000080000",
"000880000",
]);
/** The stalk's root is row 5, it sways fully at 5 rows above it, and one step of the wave is one tick. */
const SMALL = { ...DEFAULTS, root: 5, height: 5, strength: 1, pace: 1 };
function whole(src: Frame, tick: number, params = SMALL): number[] {
const out: number[] = [];
for (let y = 0; y < src.height; y++) for (let x = 0; x < src.width; x++) out.push(shade(x, y, tick, src, params));
return out;
}
/** How far each row of the stalk has moved: where its one pixel is now, minus where it was. */
function shifts(tick: number, params = SMALL): number[] {
const out = whole(STALK, tick, params);
const moved: number[] = [];
for (let y = 0; y < STALK.height; y++) moved.push(out.slice(y * STALK.width, (y + 1) * STALK.width).findIndex((n) => n !== 0) - 4);
return moved;
}
test("the root row never moves, whatever the time", () => {
for (let tick = 0; tick < 16; tick++) assert.equal(shifts(tick)[5], 0, `at tick ${tick}`);
});
test("the higher a row stands above the root, the further it sways", () => {
for (let tick = 0; tick < 16; tick++) {
const s = shifts(tick, { ...SMALL, strength: 2 });
for (let y = 0; y < 5; y++) assert.ok(Math.abs(s[y]) >= Math.abs(s[y + 1]), `at tick ${tick} row ${y} moves ${s[y]}, the row below it ${s[y + 1]}`);
}
});
test("at the full height a row sways the wave's number times the strength, both ways", () => {
// the wave is 2 at its fourth step and -2 at its twelfth
assert.equal(shifts(4)[0], 2);
assert.equal(shifts(12)[0], -2);
assert.equal(shifts(4, { ...SMALL, strength: 2 })[0], 4);
});
test("with no wind nothing moves", () => {
for (let tick = 0; tick < 16; tick++) assert.deepEqual(whole(SAPLING, tick, { ...SMALL, strength: 0 }), [...SAPLING.index]);
});
test("after 16 steps of the wave every row is back where it started", () => {
const slow = { ...SMALL, pace: 3 };
for (let tick = 0; tick < 48; tick++) assert.deepEqual(whole(SAPLING, tick + 48, slow), whole(SAPLING, tick, slow), `at tick ${tick}`);
// one step lasts `pace` ticks: the first three ticks are the same picture, the fourth is not
assert.deepEqual(whole(SAPLING, 2, slow), whole(SAPLING, 0, slow));
assert.notDeepEqual(whole(SAPLING, 3, slow), whole(SAPLING, 0, slow));
});
test("a row moves as a whole and keeps its colours", () => {
for (let tick = 0; tick < 16; tick++) {
const out = whole(SAPLING, tick);
for (let y = 0; y < SAPLING.height; y++) {
const row = out.slice(y * SAPLING.width, (y + 1) * SAPLING.width).filter((n) => n !== 0);
const before = [...SAPLING.index.slice(y * SAPLING.width, (y + 1) * SAPLING.width)].filter((n) => n !== 0);
assert.deepEqual(row, before, `at tick ${tick} row ${y}`);
}
}
});
test("neighbouring rows part by one pixel at most, so the stem does not break", () => {
for (let tick = 0; tick < 16; tick++) {
const s = shifts(tick, { ...SMALL, strength: 2 });
for (let y = 0; y < 5; y++) assert.ok(Math.abs(s[y] - s[y + 1]) <= 1, `at tick ${tick} rows ${y} and ${y + 1} are ${s[y]} and ${s[y + 1]}`);
}
});
```
Dieselbe Regel als GLSL-Shader (WebGL 2, OpenGL ES 3.0), Pixel für Pixel gegen die Regel geprüft:
```glsl
#version 300 es
// A shader the pixel art way: a pixel is a whole number, 0 where nothing is, 1 to 25 for the
// palette's colours. The rule is shade(): it is asked for every pixel and answers with a number.
// Everything outside the marked part is the same for every rule. Put your own palette in PALETTE.
precision highp float;
precision highp int;
uniform sampler2D SRC; // the picture, sampled without smoothing (nearest)
uniform sampler2D OTHER; // a second picture, where the rule uses one
uniform int TICK; // the time in ticks, 60 a second, counted by the game
const vec3 PALETTE[26] = vec3[26](
vec3(0.0),
vec3(31.0, 33.0, 66.0) / 255.0, // 1: k
vec3(75.0, 78.0, 112.0) / 255.0, // 2: n
vec3(120.0, 123.0, 152.0) / 255.0, // 3: m
vec3(198.0, 199.0, 227.0) / 255.0, // 4: e
vec3(255.0, 255.0, 255.0) / 255.0, // 5: w
vec3(246.0, 241.0, 233.0) / 255.0, // 6: c
vec3(214.0, 205.0, 189.0) / 255.0, // 7: d
vec3(242.0, 193.0, 78.0) / 255.0, // 8: y
vec3(224.0, 138.0, 46.0) / 255.0, // 9: o
vec3(194.0, 65.0, 45.0) / 255.0, // 10: r
vec3(244.0, 163.0, 160.0) / 255.0, // 11: p
vec3(47.0, 98.0, 240.0) / 255.0, // 12: b
vec3(35.0, 83.0, 214.0) / 255.0, // 13: u
vec3(157.0, 184.0, 255.0) / 255.0, // 14: s
vec3(234.0, 240.0, 255.0) / 255.0, // 15: a
vec3(207.0, 224.0, 255.0) / 255.0, // 16: i
vec3(15.0, 138.0, 76.0) / 255.0, // 17: g
vec3(124.0, 207.0, 154.0) / 255.0, // 18: l
vec3(226.0, 244.0, 234.0) / 255.0, // 19: f
vec3(138.0, 90.0, 60.0) / 255.0, // 20: t
vec3(92.0, 59.0, 40.0) / 255.0, // 21: h
vec3(109.0, 76.0, 230.0) / 255.0, // 22: v
vec3(201.0, 187.0, 255.0) / 255.0, // 23: q
vec3(18.0, 20.0, 43.0) / 255.0, // 24: x
vec3(39.0, 43.0, 82.0) / 255.0 // 25: z
);
// Which colour of the palette is this? 0 where nothing is drawn.
int number(vec4 c) {
if (c.a < 0.5) return 0;
int best = 1;
float least = 9.0;
for (int i = 1; i <= 25; i++) {
vec3 d = c.rgb - PALETTE[i];
float away = dot(d, d);
if (away < least) {
least = away;
best = i;
}
}
return best;
}
// The number at a place of the picture; outside the picture nothing is.
int at(ivec2 p) {
ivec2 size = textureSize(SRC, 0);
if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
return number(texelFetch(SRC, p, 0));
}
// The same for the second picture.
int otherAt(ivec2 p) {
ivec2 size = textureSize(OTHER, 0);
if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
return number(texelFetch(OTHER, p, 0));
}
// a wrapped into 0 .. n-1, also for a below zero (the % sign is not safe there)
int wrap(int a, int n) {
return a - n * int(floor(float(a) / float(n)));
}
// ---- the rule ----
uniform int root; // the row the plants grow from, counted from the top of the picture. It never moves.
uniform int height; // how many rows above the root the sway is at its fullest. Rows higher up go just as far.
uniform int strength; // how far the tops go: the wave's number times this, in whole pixels. 0 or more.
uniform int pace; // ticks for one step of the wave. Its 16 steps take 16 times this.
// a wave in whole pixels, 16 steps long
const int WAVE[16] = int[16](0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1);
// a row that sways to the right shows what stands that far to its left
int shade(ivec2 p) {
int tall = max(1, height);
int wave = WAVE[(TICK / max(1, pace)) & 15];
// how far this row stands above the root: 0 at the root and below it, at most the height
int above = min(max(root - p.y, 0), tall);
// this row's share of the sway in whole pixels, worked out without the sign, so that it
// rounds the same way to the left as to the right
int amount = abs(wave) * strength * above / tall;
int shift = wave < 0 ? -amount : amount;
return at(ivec2(p.x - shift, p.y));
}
// ---- end of the rule ----
out vec4 FRAGMENT;
void main() {
// the pixel's place, counted from the top left as in the picture
ivec2 p = ivec2(int(gl_FragCoord.x), textureSize(SRC, 0).y - 1 - int(gl_FragCoord.y));
int n = shade(p);
FRAGMENT = n == 0 ? vec4(0.0) : vec4(PALETTE[n], 1.0);
}
```
Dieselbe Regel für Godot 4 (von den Autoren nicht ausgeführt):
```gdshader
shader_type canvas_item;
// A shader the pixel art way: a pixel is a whole number, 0 where nothing is, 1 to 25 for the
// palette's colours. The rule is shade(): it is asked for every pixel and answers with a number.
// Everything outside the marked part is the same for every rule. Put your own palette in PALETTE.
//
// Put this on the sprite, and give it the sprite's own picture once:
// material.set_shader_parameter("SRC", texture)
uniform sampler2D SRC : filter_nearest;
uniform sampler2D OTHER : filter_nearest; // a second picture, where the rule uses one
// The time in ticks, 60 a second. The game counts it itself: add 1 in the _physics_process of a
// node that pauses with the game, and set it there, so a paused game pauses its shaders:
// tick += 1
// material.set_shader_parameter("TICK", tick)
uniform int TICK;
const vec3 PALETTE[26] = vec3[26](
vec3(0.0),
vec3(31.0, 33.0, 66.0) / 255.0, // 1: k
vec3(75.0, 78.0, 112.0) / 255.0, // 2: n
vec3(120.0, 123.0, 152.0) / 255.0, // 3: m
vec3(198.0, 199.0, 227.0) / 255.0, // 4: e
vec3(255.0, 255.0, 255.0) / 255.0, // 5: w
vec3(246.0, 241.0, 233.0) / 255.0, // 6: c
vec3(214.0, 205.0, 189.0) / 255.0, // 7: d
vec3(242.0, 193.0, 78.0) / 255.0, // 8: y
vec3(224.0, 138.0, 46.0) / 255.0, // 9: o
vec3(194.0, 65.0, 45.0) / 255.0, // 10: r
vec3(244.0, 163.0, 160.0) / 255.0, // 11: p
vec3(47.0, 98.0, 240.0) / 255.0, // 12: b
vec3(35.0, 83.0, 214.0) / 255.0, // 13: u
vec3(157.0, 184.0, 255.0) / 255.0, // 14: s
vec3(234.0, 240.0, 255.0) / 255.0, // 15: a
vec3(207.0, 224.0, 255.0) / 255.0, // 16: i
vec3(15.0, 138.0, 76.0) / 255.0, // 17: g
vec3(124.0, 207.0, 154.0) / 255.0, // 18: l
vec3(226.0, 244.0, 234.0) / 255.0, // 19: f
vec3(138.0, 90.0, 60.0) / 255.0, // 20: t
vec3(92.0, 59.0, 40.0) / 255.0, // 21: h
vec3(109.0, 76.0, 230.0) / 255.0, // 22: v
vec3(201.0, 187.0, 255.0) / 255.0, // 23: q
vec3(18.0, 20.0, 43.0) / 255.0, // 24: x
vec3(39.0, 43.0, 82.0) / 255.0 // 25: z
);
// Which colour of the palette is this? 0 where nothing is drawn.
int number(vec4 c) {
if (c.a < 0.5) return 0;
int best = 1;
float least = 9.0;
for (int i = 1; i <= 25; i++) {
vec3 d = c.rgb - PALETTE[i];
float away = dot(d, d);
if (away < least) {
least = away;
best = i;
}
}
return best;
}
// The number at a place of the picture; outside the picture nothing is.
int at(ivec2 p) {
ivec2 size = textureSize(SRC, 0);
if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
return number(texelFetch(SRC, p, 0));
}
// The same for the second picture.
int otherAt(ivec2 p) {
ivec2 size = textureSize(OTHER, 0);
if (p.x < 0 || p.y < 0 || p.x >= size.x || p.y >= size.y) return 0;
return number(texelFetch(OTHER, p, 0));
}
// a wrapped into 0 .. n-1, also for a below zero (the % sign is not safe there)
int wrap(int a, int n) {
return a - n * int(floor(float(a) / float(n)));
}
// ---- the rule ----
uniform int root; // the row the plants grow from, counted from the top of the picture. It never moves.
uniform int height; // how many rows above the root the sway is at its fullest. Rows higher up go just as far.
uniform int strength; // how far the tops go: the wave's number times this, in whole pixels. 0 or more.
uniform int pace; // ticks for one step of the wave. Its 16 steps take 16 times this.
// a wave in whole pixels, 16 steps long
const int WAVE[16] = int[16](0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1);
// a row that sways to the right shows what stands that far to its left
int shade(ivec2 p) {
int tall = max(1, height);
int wave = WAVE[(TICK / max(1, pace)) & 15];
// how far this row stands above the root: 0 at the root and below it, at most the height
int above = min(max(root - p.y, 0), tall);
// this row's share of the sway in whole pixels, worked out without the sign, so that it
// rounds the same way to the left as to the right
int amount = abs(wave) * strength * above / tall;
int shift = wave < 0 ? -amount : amount;
return at(ivec2(p.x - shift, p.y));
}
// ---- end of the rule ----
void fragment() {
ivec2 p = ivec2(UV * vec2(textureSize(SRC, 0)));
int n = shade(p);
COLOR = n == 0 ? vec4(0.0) : vec4(PALETTE[n], 1.0);
}
```
Wie hilfreich war diese Seite?
Diese Seite hat noch niemand bewertet.