Spielerando

Lektion 16 von 24Licht mit wenigen Farben8 Min.Kostenlos

Nebel im Pixel-Art-Shader, der die Figur frei lässt

Nebel gibt einem flachen Bild Tiefe: Die fernen Hügelkämme verblassen in hellem Dunst, während das Nahe scharf bleibt. In Pixel Art wird der Dunst nicht hineingemischt. Er wird mit dem Muster aus 4 mal 4 Pixeln aus der Lektion über Dithering eingestreut, alle paar Zeilen in die Ferne ein bisschen mehr, und er zieht. Was vorne steht, muss frei bleiben, und dafür braucht die Regel ein zweites Bild.

Ein Tal voller Kiefern im Morgengrauen als Pixel Art, Hügelkamm hinter Hügelkamm unter einem violetten und rosa Himmel, mit fünf Bienenstöcken auf einer Terrasse. Nah bei uns trägt ein alter Baum ein wildes Bienennest an einem Ast, und die Imkerin steigt auf einer Leiter hinauf. Blasser Nebel liegt über den fernen Kämmen, dichter, je weiter weg, und zieht in Schwaden hindurch; Baum, Leiter und Imkerin bleiben scharf.

Das ganze Tal wird der Regel gegeben, und ein zweites Bild hält fest, was vorne steht. Von der Wiese aufwärts wird der Nebel alle paar Zeilen eine Stufe dichter und zieht nach rechts; auf dem Baum, der Leiter und der Imkerin antwortet die Regel mit dem Bild, wie es kam, egal wie hoch sie steigt.

Auch in dieser Lektion 3 Lesetipps zum Vertiefen 3 Fragen zum Selbsttest

Die Idee

In einem Spiel, das du von der Seite siehst, zeigt Nebel, dass die Hügel dahinter weit weg sind: Jeder Kamm ist etwas blasser als der davor, bis der letzte fast Himmel ist. Nebel macht auch Stimmung, ein Tal im Morgengrauen, ein Sumpf, ein Pass im Gebirge, und er kostet keine neue Farbe. Der Dunst ist eine Farbe der Palette, Pixel für Pixel eingestreut.

In so einem Bild steht weiter oben, was weiter weg ist: Die fernen Kämme ragen über die nahen. Also kann die Zeile für die Entfernung stehen, und die Regel zählt sie von vorne nach oben. Das klappt für das Land dahinter, aber nicht für das, was nah bei uns steht und nach oben reicht, einen Baum in der Nähe oder die Imkerin auf einer Leiter. Sie sind nah, egal wie hoch sie reichen. Ein zweites Bild hält sie fest, und dorthin geht der Nebel nicht.

Im Bild liegt ein Tal voller Kiefern mit einer Reihe Bienenstöcke im Morgennebel. Nah bei uns trägt ein alter Baum ein wildes Bienennest, und die Imkerin steigt auf einer Leiter zu ihm hinauf.

So funktioniert es

Für jeden Pixel sieht die Regel zuerst ins zweite Bild. Ist dort etwas gezeichnet, steht es vorne, und die Regel antwortet mit dem Pixel, wie er kam. Sonst rechnet sie aus, wie viel Nebel da ist. Unterhalb der vorderen Zeile, hier Zeile 118, die Oberkante der Wiese, gibt es keinen. Von dort aufwärts wird der Nebel alle paar Zeilen eine Stufe dichter, bis er am dichtesten ist.

Schwaden ziehen hindurch: Die Wellentabelle des Kurses gibt bis zu 4 Stufen dazu oder nimmt sie weg, entlang der Zeile ausgelegt mit 8 Pixeln pro Schritt, und rückt alle 3 Ticks um einen Pixel nach rechts. Weit weg, wo der Nebel schon am dichtesten ist, sieht man die Schwaden nicht, also ist die Ferne ein gleichmäßiger Dunst.

Die Stufen des Nebels wählen dann die Dunstpixel so aus, wie die Lektion über Dithering die dunklen auswählt: Wo die Zahl des Musters kleiner ist als der Nebel, wird der Pixel zu Dunst, hier im blassesten Blau.

Die Regler: „Nebel am dichtesten“ geht von 0 bis 16 und steht am Anfang auf 12. „Zeilen pro Stufe Nebel“ geht von 1 bis 8 und steht am Anfang auf 5.

In einem Spiel ist das zweite Bild das Nahe, noch einmal für sich allein gezeichnet, in ein Bild so groß wie der Bildschirm: die Spielfigur, die Bäume der vordersten Ebene. Die meisten Engines können eine Ebene in ein eigenes Bild zeichnen; mehr braucht die Regel nicht.

Was schiefgeht

Bittest du eine KI in einem 2D-Spiel um Nebel, der „mit der Entfernung dichter wird“, nimmt sie die Höhe auf dem Bildschirm als Entfernung. Für das Land stimmt das, und dabei bleibt sie. Die Figur ist nur ein paar Pixel mehr im selben Bild, also wird sie nach ihrer Zeile vernebelt wie alles um sie herum. Steht sie auf der Wiese, berührt sie der Nebel kaum, weil er direkt darüber am dünnsten ist. Sobald sie klettert oder springt, verblasst sie, als wäre sie in die Hügel davongegangen.

Schalte das Bild auf „Mit dem Fehler“. Während sie klettert, wird sie zu Dunst, die Leiter verblasst, und die Krone des nahen Baums wird blass und fleckig. Zwei Tests fangen das: „what stands in front stays clear, however thick the fog behind it“ und „a pixel in front looks the same at every tick while the mist drifts behind it“. Der zweite sah ihre Schulter bei Tick 204 zu Dunst werden, als eine Schwade vorbeikam.

Der Fehler, Zeile für Zeile

Zeilen mit - sind die Regel mit dem Fehler, Zeilen mit + die Regel, wie sie sein soll.

- /* Fog, with the mistake: the rule never looks at the second picture, the one that says what stands in
-    front. It fogs every pixel by its row alone, so the beekeeper on the ladder fades into the mist as
-    she climbs, as if she stood as far away as the hills behind her, and the near tree goes grey too.
+ /* Fog: mist that thickens with distance and drifts, mixed into the picture pixel by pixel with the
+    4 by 4 pattern, and kept off what stands in front. In a picture seen from the side, what is further
+    away stands higher: the far hills show above the near ones. So the rule counts the rows from the
+    front upward, one step of fog every few rows, up to its thickest, and lets banks of mist drift
+    through by the wave table. A second picture says what stands in front (the beekeeper, the near
+    tree); there the rule leaves the picture as it is, however thick the fog behind.

+    The pixel art way: a picture is a grid of whole numbers, 0 where nothing is and 1 to 25 for the
+    palette's colours. The rule is asked for every pixel and answers with a number.
+
     From the course "Shaders for pixel art" on spielerando.com.
     SPDX-License-Identifier: MIT */
…
  }

- /** The rule, wrong: every pixel is fogged by its row, also what stands in front. */
- export function shade(x: number, y: number, tick: number, src: Frame, p: Params = DEFAULTS, _other?: Frame): number {
+ /** The rule: what stands in front stays as it is; behind it the mist is mixed in by the pattern. */
+ export function shade(x: number, y: number, tick: number, src: Frame, p: Params = DEFAULTS, other?: Frame): number {
    const n = at(src, x, y);
+   // the second picture holds what stands in front: it is not behind the fog
+   if (other && at(other, x, y) !== 0) return n;
    return BAYER[(y & 3) * 4 + (x & 3)] < fog(x, y, tick, p) ? p.mist : n;
  }

Was der Test zum Fehler sagt

✔ below the front row there is no fog
✔ the fog thickens one step every few rows above the front, as rise says
✔ far away the fog stops growing at its thickest, and is even there while banks pass
✔ the mist drifts one pixel to the right every few ticks, as pace says, and not in between
✔ behind, the mist is mixed in by the 4 by 4 pattern: at 8 steps, 8 of every 16 pixels are mist
✖ what stands in front stays clear, however thick the fog behind it
    pixel 3, 1
    got 15, expected 14
✖ a pixel in front looks the same at every tick while the mist drifts behind it
    tick 204
    got 15, expected 14
✔ every answer is the picture's own colour or the mist
8 tests: 6 passed, 2 failed

Das sagst du deiner KI

Bau Nebel als Shader in mein 2D-Pixel-Art-Spiel ein: blassen Dunst, der mit der Entfernung dichter wird, langsam zieht und nie verdeckt, was vorne steht.

- Entfernung: [woher mein Spiel sie kennt: die Zeile auf dem Bildschirm, weiter oben heißt weiter weg, oder die Ebene, auf der etwas gezeichnet wird]. Der Nebel beginnt bei [der vorderen Zeile oder Ebene] und wird alle [paar] Zeilen eine Stufe dichter, bis [am dichtesten, von 0 bis 16].
- Streu den Dunst mit dem Muster aus 4 mal 4 Pixeln des geordneten Ditherings ein (0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5), gelesen bei (x mod 4, y mod 4): Ein Pixel wird zur Farbe des Dunstes [eine Farbe meiner Palette], wo die Zahl des Musters kleiner ist als die Stufe des Nebels. Kein Mischen und keine Transparenz.
- Was vorne steht ([die Spielfigur, die Bäume der vordersten Ebene]), wird noch einmal in ein zweites Bild derselben Größe gezeichnet. Wo dieses Bild etwas hat, antwortet der Shader mit dem Pixel, wie er kam.
- Schwaden: eine Welle aus ganzen Zahlen, die ein paar Stufen dazugibt oder wegnimmt und alle [paar] Bilder um einen Pixel weiterrückt. Wo der Nebel am dichtesten ist, bleibt er gleichmäßig.
- Nur ganze Pixel: Filter auf nearest, kein Glätten.

Bevor du den Shader schreibst, schreib dieselbe Regel als kleine, einfache Funktion auf Rastern aus ganzen Zahlen (das Bild und das Bild dessen, was vorne steht) und teste sie: Unterhalb der vorderen Zeile gibt es keinen Nebel; jeder Pixel dessen, was vorne steht, kommt in jedem Bild so heraus, wie er kam; bei 8 Stufen sind dahinter 8 von je 16 Pixeln Dunst. 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

TypeScript, klein, und sie braucht nichts sonst. Deine KI kann sie lesen und dieselbe Regel für das schreiben, womit dein Spiel gebaut ist.

/* Fog: mist that thickens with distance and drifts, mixed into the picture pixel by pixel with the
   4 by 4 pattern, and kept off what stands in front. In a picture seen from the side, what is further
   away stands higher: the far hills show above the near ones. So the rule counts the rows from the
   front upward, one step of fog every few rows, up to its thickest, and lets banks of mist drift
   through by the wave table. A second picture says what stands in front (the beekeeper, the near
   tree); there the rule leaves the picture as it is, however thick the fog behind.

   The pixel art way: a picture is a grid of whole numbers, 0 where nothing is and 1 to 25 for the
   palette's colours. The rule is asked for every pixel and answers with a number.

   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 = {
  /** How thick the fog gets far away: 0 is none, 16 is mist only. */
  thick: 12,
  /** How many rows each step of fog takes, counted up from the front row. */
  rise: 5,
  /** The row where the fog begins: the front of the scene. Below it there is none. */
  front: 118,
  /** The mist's colour, by its number in the palette: 15 is the palest blue. */
  mist: 15,
  /** How many ticks the mist takes to drift one pixel. */
  pace: 3,
};
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 4 by 4 pattern for dithering: 0 to 15, each once.  BAYER[(y & 3) * 4 + (x & 3)] */
const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];

const wrap = (a: number, n: number) => a - n * Math.floor(a / n);

/** 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];
}

/** How much fog is at a place: 0 to 16 of every 16 pixels are mist. */
export function fog(x: number, y: number, tick: number, p: Params): number {
  const d = p.front - y;
  if (d <= 0) return 0;
  // banks of mist: the wave laid along the row, 8 pixels a step, moved right one pixel every `pace` ticks.
  // It adds or takes up to 4 steps; far away, where the fog is at its thickest, it is even.
  const drift = WAVE[wrap(x - Math.floor(tick / Math.max(1, p.pace)), 128) >> 3];
  return Math.max(0, Math.min(p.thick, Math.floor(d / Math.max(1, p.rise)) + 2 * drift));
}

/** The rule: what stands in front stays as it is; behind it the mist is mixed in by the pattern. */
export function shade(x: number, y: number, tick: number, src: Frame, p: Params = DEFAULTS, other?: Frame): number {
  const n = at(src, x, y);
  // the second picture holds what stands in front: it is not behind the fog
  if (other && at(other, x, y) !== 0) return n;
  return BAYER[(y & 3) * 4 + (x & 3)] < fog(x, y, tick, p) ? p.mist : n;
}

Dieselbe Regel als Shader: GLSL

Für WebGL 2 und OpenGL ES 3.0. Nur der als Regel markierte Teil gehört zu dieser Lektion; der Rest ist in jeder Lektion gleich.

#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 thick; // how thick the fog gets far away: 0 is none, 16 is mist only
uniform int rise;  // how many rows each step of fog takes, counted up from the front row
uniform int front; // the row where the fog begins: the front of the scene. Below it there is none
uniform int mist;  // the mist's colour, by its number in the palette: 15 is the palest blue
uniform int pace;  // how many ticks the mist takes to drift one pixel

// 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);
// the 4 by 4 pattern for dithering: 0 to 15, each once.  BAYER[(y & 3) * 4 + (x & 3)]
const int BAYER[16] = int[16](0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5);

// how much fog is at a place: 0 to 16 of every 16 pixels are mist
int fog(ivec2 p) {
  int d = front - p.y;
  if (d <= 0) return 0;
  // banks of mist: the wave laid along the row, 8 pixels a step, moved right one pixel every `pace` ticks.
  // It adds or takes up to 4 steps; far away, where the fog is at its thickest, it is even.
  int drift = WAVE[wrap(p.x - TICK / max(1, pace), 128) >> 3];
  return max(0, min(thick, d / max(1, rise) + 2 * drift));
}

// what stands in front stays as it is; behind it the mist is mixed in by the pattern
int shade(ivec2 p) {
  int n = at(p);
  // the second picture holds what stands in front: it is not behind the fog
  if (otherAt(p) != 0) return n;
  return BAYER[(p.y & 3) * 4 + (p.x & 3)] < fog(p) ? mist : n;
}
// ---- 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

Der geprüfte Shader mit Godots Namen darum herum. Diesen haben wir nicht ausgeführt: Godot gehört noch nicht zu unseren Prüfungen. Lass deine KI sein Bild mit dem auf dieser Seite vergleichen.

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 a ColorRect that covers the screen, above everything it should change.
// The rule counts pixels as this shader sees them. Let the game draw at the size of its art and
// enlarge the finished picture (the project's stretch mode "viewport"), or it counts window pixels.
uniform sampler2D SRC : hint_screen_texture, filter_nearest; // what is on the screen behind it
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 thick; // how thick the fog gets far away: 0 is none, 16 is mist only
uniform int rise;  // how many rows each step of fog takes, counted up from the front row
uniform int front; // the row where the fog begins: the front of the scene. Below it there is none
uniform int mist;  // the mist's colour, by its number in the palette: 15 is the palest blue
uniform int pace;  // how many ticks the mist takes to drift one pixel

// 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);
// the 4 by 4 pattern for dithering: 0 to 15, each once.  BAYER[(y & 3) * 4 + (x & 3)]
const int BAYER[16] = int[16](0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5);

// how much fog is at a place: 0 to 16 of every 16 pixels are mist
int fog(ivec2 p) {
  int d = front - p.y;
  if (d <= 0) return 0;
  // banks of mist: the wave laid along the row, 8 pixels a step, moved right one pixel every `pace` ticks.
  // It adds or takes up to 4 steps; far away, where the fog is at its thickest, it is even.
  int drift = WAVE[wrap(p.x - TICK / max(1, pace), 128) >> 3];
  return max(0, min(thick, d / max(1, rise) + 2 * drift));
}

// what stands in front stays as it is; behind it the mist is mixed in by the pattern
int shade(ivec2 p) {
  int n = at(p);
  // the second picture holds what stands in front: it is not behind the fog
  if (otherAt(p) != 0) return n;
  return BAYER[(p.y & 3) * 4 + (p.x & 3)] < fog(p) ? mist : n;
}
// ---- end of the rule ----

void fragment() {
  ivec2 p = ivec2(SCREEN_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, fog, shade } from "./shader.ts";

/** A tiny picture from rows of numbers: 0 is nothing, 1 to 25 are the palette's colours. */
function picture(rows: string[]): Frame {
  const cells = rows.map((r) => r.trim().split(/\s+/).map(Number));
  return { width: cells[0].length, height: cells.length, index: Uint8Array.from(cells.flat()) };
}

// At tick 0 the columns 0 to 7 lie where the wave is 0: no bank of mist adds to the fog or takes from it.

/** A far hillside of dark wood, 20, and a beekeeper of light blue, 14, in front of it. */
const HILL = picture([
  "20 20 20 20 20 20 20 20",
  "20 20 20 14 14 20 20 20",
  "20 20 14 14 14 14 20 20",
  "20 20 20 14 14 20 20 20",
  "20 20 20 14 14 20 20 20",
  "20 20 20 14 14 20 20 20",
]);
/** The second picture: what stands in front, the beekeeper alone. */
const FRONT = picture([
  "0 0 0 0 0 0 0 0",
  "0 0 0 14 14 0 0 0",
  "0 0 14 14 14 14 0 0",
  "0 0 0 14 14 0 0 0",
  "0 0 0 14 14 0 0 0",
  "0 0 0 14 14 0 0 0",
]);

test("below the front row there is no fog", () => {
  for (const tick of [0, 50, 200]) {
    for (let x = 0; x < 128; x++) {
      assert.equal(fog(x, DEFAULTS.front, tick, DEFAULTS), 0);
      assert.equal(fog(x, DEFAULTS.front + 9, tick, DEFAULTS), 0);
    }
  }
});

test("the fog thickens one step every few rows above the front, as rise says", () => {
  const p = { ...DEFAULTS, thick: 16, rise: 4, front: 100 };
  assert.equal(fog(0, 97, 0, p), 0, "three rows up is not yet a step");
  for (let step = 1; step <= 16; step++) assert.equal(fog(0, 100 - 4 * step, 0, p), step);
});

test("far away the fog stops growing at its thickest, and is even there while banks pass", () => {
  const p = { ...DEFAULTS, thick: 12, rise: 4, front: 100 };
  assert.equal(fog(0, 52, 0, p), 12);
  for (const tick of [0, 90, 200]) for (let x = 0; x < 128; x++) assert.equal(fog(x, 0, tick, p), 12, `${x} at tick ${tick}`);
});

test("the mist drifts one pixel to the right every few ticks, as pace says, and not in between", () => {
  const p = { ...DEFAULTS, pace: 3 };
  for (let x = 0; x < 256; x++) {
    for (const y of [10, 50, 90]) {
      assert.equal(fog(x + 1, y, 3, p), fog(x, y, 0, p), `${x}, ${y}`);
      assert.equal(fog(x, y, 2, p), fog(x, y, 0, p), `${x}, ${y} moved before its time`);
    }
  }
});

test("behind, the mist is mixed in by the 4 by 4 pattern: at 8 steps, 8 of every 16 pixels are mist", () => {
  const src = picture(["20 20 20 20", "20 20 20 20", "20 20 20 20", "20 20 20 20"]);
  const p = { ...DEFAULTS, thick: 8, front: 100 };
  let mist = 0;
  for (let y = 0; y < 4; y++) for (let x = 0; x < 4; x++) if (shade(x, y, 0, src, p) === p.mist) mist++;
  assert.equal(mist, 8);
});

test("what stands in front stays clear, however thick the fog behind it", () => {
  const p = { ...DEFAULTS, thick: 16, front: 100 };
  for (let y = 0; y < HILL.height; y++) {
    for (let x = 0; x < HILL.width; x++) {
      const want = FRONT.index[y * 8 + x] !== 0 ? HILL.index[y * 8 + x] : p.mist;
      assert.equal(shade(x, y, 0, HILL, p, FRONT), want, `pixel ${x}, ${y}`);
    }
  }
});

test("a pixel in front looks the same at every tick while the mist drifts behind it", () => {
  // the beekeeper's shoulder at (3, 2), 32 rows above the front: 8 steps of fog, and banks of mist pass by
  const p = { ...DEFAULTS, thick: 16, rise: 4, front: 34 };
  for (let tick = 0; tick < 400; tick++) assert.equal(shade(3, 2, tick, HILL, p, FRONT), 14, `tick ${tick}`);
});

test("every answer is the picture's own colour or the mist", () => {
  for (const thick of [0, 6, 16]) {
    for (let tick = 0; tick < 300; tick += 37) {
      for (let y = 0; y < HILL.height; y++) {
        for (let x = 0; x < HILL.width; x++) {
          const n = shade(x, y, tick, HILL, { ...DEFAULTS, thick, front: 40 }, FRONT);
          assert.ok(n === HILL.index[y * 8 + x] || n === DEFAULTS.mist, `${n} at ${x}, ${y}`);
        }
      }
    }
  }
});
Was wir geprüft haben
  • 8 Tests bestehen mit der Regel.
  • Mit dem eingebauten Fehler schlagen 2 davon fehl: "what stands in front stays clear, however thick the fog behind it", "a pixel in front looks the same at every tick while the mist drifts behind it".
  • 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.

Ausgeführt von pnpm courses:check am 2026-11-27 mit Node v24.15.0.

Probier es aus

Zum Nachlesen

Wo es tiefer geht: unsere Seiten, auf denen diese Lektion aufbaut, und was andere zu ihrem Punkt geschrieben haben.

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.

Frage 1 von 3Leicht

Das Tal ist von der Seite zu sehen. Woran erkennt die Regel für den Nebel, wie weit ein Pixel des Landes dahinter entfernt ist?

Alle Fragen dieses Kurses · Das Quiz und der Game Coder IQ

Nächste Lektion Wind-Shader für Pixel Art: Gras und Bäume, die sich biegen

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.

Wie hilfreich war diese Seite?

Diese Seite hat noch niemand bewertet.

Ein Klick, ohne Konto. So sehen wir, welche Seiten wir als Nächstes verbessern.

Stand: 2026-11-27