Wind Sway Shader for Pixel Art: Grass and Trees That Bend
Wind sway makes grass and trees bend back and forth, so that a still landscape looks alive and the player can tell the wind is blowing. In pixel art the shader moves each row of the plant sideways by whole pixels, the higher rows further, and leaves the row at the ground where it is. You draw the plant once; the rule does the swaying, with no extra frames of animation.

Only the oak, the grass and the flowers are given to the rule. Each of their rows moves sideways by the wave's whole pixels, more the higher it stands above the ground; the row at the ground does not move. The gusts come and go.
Also in this lesson 4 things to read up on 3 questions to check yourself
The idea
A tree is fixed at its foot and free at its top. When wind pushes it, the crown travels furthest, the trunk bends, and the roots stay in the earth. In a picture made of rows that is simple to copy: move every row sideways, by more the higher it is, and do not move the bottom one. You see it on a hill in the background of a level, in tall grass before a storm, in reeds at a pond.
The sway comes from a wave, and in pixel art a wave is a short list of whole numbers, not a smooth curve. A curve would put the crown between two pixels most of the time, a place a picture of pixels does not have, and rounding it every frame gives steps of uneven length. This course's wave is sixteen numbers: 0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1. It stays at 2 for three steps, the moment a branch hangs at its furthest before it swings back, and passes 0 in one step, where a branch moves fastest. Every step lasts the same number of ticks, so the tree keeps its beat on every machine.
How it works
For each pixel the rule first asks the time: the tick count divided by the pace is the step of the wave, sixteen steps and then again from the start. The wave's number there, from -2 to 2, times the strength is how far the top of the plant leans now.
Then it asks how far its own row stands above the root. At the root that is 0, and the row stays. At the height, here 32 rows, and above it, the row gets the full lean; in between, its share in whole pixels, rounded down. The share is worked out without the sign, so a row goes as far to the left as to the right. Last, the pixel shows what stood that far beside it: a row leaning 3 pixels right reads the pixel 3 to its left.
In the picture only the oak, the grass and the flowers are given to the rule; the hill, the hives and the beekeeper lie behind it and stand still. The slider strength goes from 0 to 3: at 3 the crown swings 6 pixels to each side. The slider pace is how many ticks one step lasts: at 4 a whole sway takes 64 ticks, a little over a second.
What goes wrong
The rows of a picture are counted from the top: row 0 is the highest. An AI that wants "more sway the higher the row" often takes the row's number, or the vertical position on the texture, as the height. On a texture that position counts from the top in some engines and from the bottom in others. Taken the wrong way round, the bottom row gets the most sway and the top row none.
Switch the picture to "With the mistake". The foot of the oak slides back and forth over the ground while its crown stands still, and the grass slides along the earth like a loose carpet.
Two tests catch it: "the root row never moves, whatever the time" watches the bottom row of a small stalk of grass for sixteen ticks, and "the higher a row stands above the root, the further it sways" compares every row with the one below it.
The mistake, line by line
- /* 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 rightWhat the test says about the mistake
✖ 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 failedTell your AI
Write a wind sway shader for my [grass / tree / plant] sprite, in pixel art.
- Work on whole pixels: each row of the sprite moves sideways by a whole number of pixels. No smoothing, no blending. Sample the texture with nearest filtering.
- The wave is this list of 16 whole numbers, not a sine: 0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1. Its step is the game's tick count divided by [pace, for example 4], wrapped to 16 steps.
- The plant grows from row [root: the sprite's bottom row], and that row never moves. A row's shift is the wave's number times [strength] times its height above the root, divided by [height in rows]. Cap the height there. Work the share out without the sign and put the sign back after, so that left and right round the same way.
- Rows in a picture are counted from the top. Make sure "higher" means further above the root, not a bigger row number.
Before the shader, write the same rule as a small plain function. It takes a grid of whole numbers (0 = empty, 1 to N = the colours of my palette), a place and the tick, and returns the number for that one pixel. Test it: the root row never moves at any tick; a higher row sways at least as far as a lower one; with strength 0 nothing moves; after 16 steps the picture is the same again. Show me the test's output. Then write the shader so that it does exactly what the function does.
The code
Three times the same rule. The first is the one we test; the two shaders are that rule in a shader language, which is what your game runs.
The rule, tested: 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);
}
The same rule as a 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);
}
The same rule for 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);
}
The 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 pass on the rule.
- With the mistake put in, 3 of them fail: "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".
- The mistake shows in the picture above: switch to "With the mistake".
- The shader ran in a browser (Chrome/158.0.8127.37) on 12 pictures and gave the rule's picture in 388,800 of 388,800 pixels.
Try it
- Pull strength to 0, then to 3. At 0 nothing moves at all. At 3 the crown swings wide as one piece, the trunk bends along its length, and the grass tips move less than the crown because they stand lower.
- Pull pace to 1 and then to 12. At 1 a whole sway takes 16 ticks and the plants flutter in a gale; at 12 they lean slowly in a soft breeze.
- Switch to "With the mistake" and watch the ground line, not the crown: the foot of the trunk and the grass slide. With the rule, the ground line is quiet.
Read up
Where to go deeper: the pages of ours this lesson builds on, and what others have written about its point.
A tree that bends at every branch instead of row by row, grown by code from a seed, where smaller branches follow bigger ones and stronger wind moves it further, never faster.
Here every plant swings in step and the wave comes round again. The recipe adds up waves whose lengths do not divide into each other, with a seed for each, so a crowd never moves as one.
Heat Haze Shader for Pixel Art: Shimmer Without Ragged Edges
The same wave of whole numbers moving rows sideways, but climbing through a band of hot air, and the picture's edge, where a moved row pulls in nothing unless the rule repeats the edge.
Converting GLSL to Godot shaders
Godot's own note that its UV is upside down compared with the pixel coordinates of GLSL: the reason a sway rule copied from elsewhere can grow from the top down.
Check yourself: three questions
Each answer is checked and explained at once. The questions are part of the quiz, so they count for your Game Coder IQ like any other.
A tree sways in this lesson's wind. Which part of it does the rule move furthest, and which part not at all?
Next lesson Water Reflection Shader in Pixel Art: Mirror, Darken, Ripple
Give the whole lesson to your AI
The button copies what to tell it together with the tested rule, its test and both shaders, so your AI has everything to build this in your game and to show you that it works.
This is a lesson from the course "Shaders for Pixel Art" on spielerando.com: https://spielerando.com/en/courses/pixel-shaders/wind-sway
Write a wind sway shader for my [grass / tree / plant] sprite, in pixel art.
- Work on whole pixels: each row of the sprite moves sideways by a whole number of pixels. No smoothing, no blending. Sample the texture with nearest filtering.
- The wave is this list of 16 whole numbers, not a sine: 0, 1, 1, 2, 2, 2, 1, 1, 0, -1, -1, -2, -2, -2, -1, -1. Its step is the game's tick count divided by [pace, for example 4], wrapped to 16 steps.
- The plant grows from row [root: the sprite's bottom row], and that row never moves. A row's shift is the wave's number times [strength] times its height above the root, divided by [height in rows]. Cap the height there. Work the share out without the sign and put the sign back after, so that left and right round the same way.
- Rows in a picture are counted from the top. Make sure "higher" means further above the root, not a bigger row number.
Before the shader, write the same rule as a small plain function. It takes a grid of whole numbers (0 = empty, 1 to N = the colours of my palette), a place and the tick, and returns the number for that one pixel. Test it: the root row never moves at any tick; a higher row sways at least as far as a lower one; with strength 0 nothing moves; after 16 steps the picture is the same again. Show me the test's output. Then write the shader so that it does exactly what the function does.
The rule, tested (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);
}
```
Its 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]}`);
}
});
```
The same rule as a GLSL shader (WebGL 2, OpenGL ES 3.0), checked against the rule pixel for pixel:
```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);
}
```
The same rule for Godot 4 (not run by the authors):
```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);
}
```
How useful was this page?
Nobody has rated this page yet.