Spielerando

Lektion 15 von 24Licht mit wenigen Farben8 Min.Kostenlos

Tag-und-Nacht-Shader für Pixel Art: dunkler nach der Uhrzeit

Ein Tag, der zur Nacht wird, ist eine einzige Regel über dem ganzen Bildschirm. Sie sieht auf die Uhrzeit und macht jede Farbe um so viele Stufen dunkler, wie die Stunde verlangt, über die eigenen dunkleren Farben der Palette. Nur was leuchtet, lässt sie aus: Fenster und Laternen bleiben hell, und genau das macht ein Nachtbild lesbar.

Eine Dorfstraße als Pixel Art mit zwei Häuschen, einer Straßenlaterne, zwei Bienenstöcken und einem Busch unter blauem Himmel. Die Imkerin geht die Straße entlang. Die Stunden vergehen: Der Himmel und alles darunter werden in kleinen gepunkteten Stufen dunkler, bis es Nacht ist, während die Fensterscheiben und das Glas der Laterne ihr warmes Honiggelb behalten. Dann kommt der Morgen zurück.

Ein Tag in acht Sekunden, ab Mittag. Die Regel macht das ganze Bild nach der Stunde dunkler, über die Tabelle der Palette und in Sechzehnteln, die ein Muster mischt. Die Fensterscheiben und die Laterne stehen in einem zweiten Bild dessen, was leuchtet. Deshalb behalten sie ihre Farbe, während der Honig der Bienenstöcke mit dem Rest dunkel wird.

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

Die Idee

Spiele mit einer Uhr, ein Hof, ein Dorf, eine lange Reise, zeigen die Tageszeit in der Farbe des ganzen Bildes. Gegen Abend wird alles dunkler und blauer, in der Nacht ist die Welt nur noch ein paar dunkle Formen, und am Morgen kommt sie zurück. Wer spielt, liest die Uhrzeit ab, ohne auf eine Zahl zu sehen.

In Pixel Art ist die Nacht kein dunkler Schleier über dem Bild. Sie besteht aus den eigenen dunkleren Farben der Palette: Die cremefarbene Wand eines Häuschens wird Sand, dann Holz, dann dunkles Holz, dann Nacht; der Himmel geht über Hellblau, Blau und Tiefblau in die Nacht. Niemand zeichnet die Straße zweimal. Sie wird einmal gezeichnet, bei Tag, und die Regel entscheidet, wie dunkel sie ist.

Was ein Nachtbild trägt, ist das, was hell bleibt. Ein Fenster mit Licht dahinter, eine Straßenlaterne, ein Feuer: Daran findet man die Häuser und den Weg. Deshalb hat die Regel ein zweites Bild, so groß wie der Bildschirm, in dem nur gezeichnet ist, was leuchtet.

So funktioniert es

Die Regel sieht auf drei Dinge: die Farbe des Pixels, die Stunde („Stunde des Tages“, 0 bis 23) und wie viele Stufen dunkler die tiefste Nacht ist („Stufen dunkler in der Nacht“, am Anfang 4).

Eine Tabelle gibt jeder Stunde ihren Anteil an der Nacht in Sechzehnteln. Von 8 bis 16 Uhr ist der Anteil 0, und das Bild bleibt, wie es gezeichnet ist. Von 21 bis 3 Uhr ist er 16, volle Nacht. Abend- und Morgendämmerung dauern dazwischen je vier Stunden. Anteil mal Stufen ergibt die Dunkelheit in Sechzehnteln einer Stufe: Die ganzen Stufen gehen durch die Tabelle der dunkleren Farben, und der Rest wird mit dem 4×4-Muster aus der Lektion übers Dithering eingemischt. Bei 4 Stufen Nacht liegt jede Stunde der Dämmerung genau zwischen zwei Stufen. Die Hälfte der Pixel ist dann eine Stufe weiter als die andere Hälfte.

Vor alldem sieht die Regel ins zweite Bild. Ist dort an dieser Stelle etwas gezeichnet, behält der Pixel die Farbe, mit der er kam, zu jeder Stunde. In der Dorfstraße hält dieses zweite Bild die Fensterscheiben und das Glas der Laterne, sonst nichts. Bis du einen Regler anfasst, vergeht alle Drittelsekunde eine Stunde, angefangen am Mittag.

Was schiefgeht

Bittet man sie um Nacht, macht eine KI meist den ganzen Bildschirm auf einmal dunkler und vergisst die Lichter. Fenster und Laterne werden mit allem anderen dunkel, und die Straße um Mitternacht ist eine einzige dunkle Form, an der sich niemand orientieren kann. Das fällt leicht nicht auf: Bei Tag geben beide Regeln dasselbe Bild, ein kurzer Blick aufs Spiel am Mittag zeigt also keinen Fehler.

Es passiert, weil eine Regel für den ganzen Bildschirm nur Farben sieht. Der Honig eines erleuchteten Fensters ist dieselbe Zahl wie der Honig eines Bienenstocks, und nichts an der Farbe sagt, dass eins davon leuchtet. Schalte das Bild nachts auf „Mit dem Fehler“: Die Scheiben und das Glas der Laterne werden so dunkel wie die Wände um sie herum.

Der Test „what gives light keeps its colour at every hour“ (was leuchtet, behält zu jeder Stunde seine Farbe) fängt das. Ein zweiter Test, „the picture of what gives light decides, not the colour“ (das Bild dessen, was leuchtet, entscheidet, nicht die Farbe), fängt die schnelle Reparatur, die eine KI als Nächstes versuchen könnte: jeden Honig-Pixel hell lassen. Dann würden auch die Bienenstöcke im Dunkeln leuchten.

Der Fehler, Zeile für Zeile

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

- /* Day and night, with the mistake: the whole picture is darkened by the hour, and the rule never looks
-    at the picture of what gives light. The lit windows and the lantern's flame go dark with everything
-    else, so at night the street is one dark shape with nothing lit in it.
+ /* Day and night: the whole picture is graded by the hour. At noon every colour is its own; in the
+    evening the picture goes darker, step by step through the palette's table of darker colours, until
+    at night it is as many steps darker as `night` says. Between two steps the 4 by 4 pattern mixes
+    them, so dusk comes in sixteen small steps instead of a few jumps. What gives light, a lit window or
+    a lantern's flame, is kept out of the grade: it keeps its colour at every hour.

+    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. `other` is a second picture of the same size: what is drawn in it gives light.
+
     From the course "Shaders for pixel art" on spielerando.com.
     SPDX-License-Identifier: MIT */
…
  }

- /** The rule, wrong: everything darkened by the hour, also what gives light. */
- export function shade(x: number, y: number, _tick: number, src: Frame, p: Params = DEFAULTS, _other?: Frame): number {
+ /** The rule: the picture darkened by the hour, except what gives light. */
+ export function shade(x: number, y: number, _tick: number, src: Frame, p: Params = DEFAULTS, other?: Frame): number {
    const n = at(src, x, y);
+   // what gives light (a lit window, a lantern's flame) keeps its colour at every hour
+   if (other && at(other, x, y) !== 0) return n;
    // how dark this hour is, in sixteenths of a step: the whole steps, and what is left over
    const depth = DUSK[wrap(p.hour, 24)] * p.night;

Was der Test zum Fehler sagt

✔ by day every pixel keeps its colour
✔ at midnight a colour is as many steps darker as `night` says, by the table
✖ what gives light keeps its colour at every hour
    at 0 o'clock
    got 24, expected 8
✖ the picture of what gives light decides, not the colour: the same honey on the hive goes dark
    got 20, expected 8
✔ dusk comes in sixteenths: at 17 o'clock 6 of every 16 pixels are one step darker
✔ the evening only gets darker, hour by hour, and the morning only lighter
✔ an empty pixel stays empty at every hour
7 tests: 5 passed, 2 failed

Das sagst du deiner KI

Schreib einen Shader für mein Pixel-Art-Spiel, der den ganzen Bildschirm nach der Tageszeit färbt, vom Mittag in die Nacht und zurück.

- Arbeite mit ganzen Pixeln und nur mit den Farben meiner Palette: kein Mischen, keine neuen Farben. Die nächstdunklere Farbe zu jeder Farbe: [eine Tabelle, oder jede Farbreihe meiner Palette von hell nach dunkel].
- Die Stunde ist eine ganze Zahl von 0 bis 23, die das Spiel setzt. Eine Tabelle gibt jeder Stunde ihren Anteil an der Nacht in Sechzehnteln: 0 von 8 bis 16 Uhr, 16 von 21 bis 3 Uhr, und dazwischen je vier Stunden Abend- und Morgendämmerung.
- In voller Nacht ist jede Farbe [4] Stufen dunkler, über die Tabelle. Zwischen zwei Stufen mischst du beide mit dem 4×4-Bayer-Muster, fest am Bildschirm, damit die Dämmerung in kleinen Schritten kommt.
- Was leuchtet, behält zu jeder Stunde seine Farbe: [die erleuchteten Fenster, Laternen, Feuer, das Leuchten der Spielfigur]. Nimm das aus einem zweiten Bild oder einer Ebene dessen, was leuchtet, so groß wie der Bildschirm, nicht aus der Farbe.

Bevor du den Shader schreibst, schreib dieselbe Regel als kleine, einfache Funktion. Sie bekommt das Bild als Raster aus ganzen Zahlen (0 = leer, 1 bis N = meine Farben), das Bild dessen, was leuchtet, einen Platz und die Stunde und gibt die Zahl für diesen einen Pixel zurück. Teste sie: Am Mittag ändert sich nichts; um Mitternacht ist eine Farbe [4] Stufen dunkler; ein erleuchtetes Fenster behält zu jeder Stunde seine Farbe; ein Pixel derselben Farbe, der nicht im Bild dessen steht, was leuchtet, wird dunkel. 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.

/* Day and night: the whole picture is graded by the hour. At noon every colour is its own; in the
   evening the picture goes darker, step by step through the palette's table of darker colours, until
   at night it is as many steps darker as `night` says. Between two steps the 4 by 4 pattern mixes
   them, so dusk comes in sixteen small steps instead of a few jumps. What gives light, a lit window or
   a lantern's flame, is kept out of the grade: it keeps its colour at every hour.

   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. `other` is a second picture of the same size: what is drawn in it gives light.

   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 hour of the day, 0 to 23: 12 is noon, 0 is midnight. */
  hour: 12,
  /** How many steps darker the picture is in the middle of the night. */
  night: 4,
};
export type Params = typeof DEFAULTS;

/** How much of the night's dark each hour has, in sixteenths: 0 by day, 16 in the night. */
const DUSK = [16, 16, 16, 16, 14, 10, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 10, 14, 16, 16, 16];
/** 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];
/** The next darker colour of the palette for each number. [0] is nothing. */
const DARKER = [0, 24, 25, 2, 3, 15, 7, 20, 9, 20, 21, 10, 13, 25, 12, 16, 14, 25, 17, 18, 21, 24, 25, 22, 24, 24];

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

/** a wrapped into 0 .. n-1, also for a below zero */
const wrap = (a: number, n: number) => a - n * Math.floor(a / n);

/** A colour made darker by the table, `steps` times. */
function darker(n: number, steps: number): number {
  let c = n;
  for (let i = 0; i < steps; i++) c = DARKER[c];
  return c;
}

/** The rule: the picture darkened by the hour, except what gives light. */
export function shade(x: number, y: number, _tick: number, src: Frame, p: Params = DEFAULTS, other?: Frame): number {
  const n = at(src, x, y);
  // what gives light (a lit window, a lantern's flame) keeps its colour at every hour
  if (other && at(other, x, y) !== 0) return n;
  // how dark this hour is, in sixteenths of a step: the whole steps, and what is left over
  const depth = DUSK[wrap(p.hour, 24)] * p.night;
  let steps = depth >> 4;
  // what is left over is mixed in by the pattern: that many of every 16 pixels go one step further
  if ((depth & 15) > BAYER[(y & 3) * 4 + (x & 3)]) steps++;
  return darker(n, steps);
}

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 hour;  // the hour of the day, 0 to 23: 12 is noon, 0 is midnight
uniform int night; // how many steps darker the picture is in the middle of the night

// how much of the night's dark each hour has, in sixteenths: 0 by day, 16 in the night
const int DUSK[24] = int[24](16, 16, 16, 16, 14, 10, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 10, 14, 16, 16, 16);
// 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);
// the next darker colour of the palette for each number. [0] is nothing.
const int DARKER[26] = int[26](0, 24, 25, 2, 3, 15, 7, 20, 9, 20, 21, 10, 13, 25, 12, 16, 14, 25, 17, 18, 21, 24, 25, 22, 24, 24);

// a colour made darker by the table, steps times
int darker(int n, int steps) {
  int c = n;
  for (int i = 0; i < steps; i++) c = DARKER[c];
  return c;
}

// the picture darkened by the hour, except what gives light
int shade(ivec2 p) {
  int n = at(p);
  // what gives light (a lit window, a lantern's flame) keeps its colour at every hour
  if (otherAt(p) != 0) return n;
  // how dark this hour is, in sixteenths of a step: the whole steps, and what is left over
  int depth = DUSK[wrap(hour, 24)] * night;
  int steps = depth >> 4;
  // what is left over is mixed in by the pattern: that many of every 16 pixels go one step further
  if ((depth & 15) > BAYER[(p.y & 3) * 4 + (p.x & 3)]) steps++;
  return darker(n, steps);
}
// ---- 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 hour;  // the hour of the day, 0 to 23: 12 is noon, 0 is midnight
uniform int night; // how many steps darker the picture is in the middle of the night

// how much of the night's dark each hour has, in sixteenths: 0 by day, 16 in the night
const int DUSK[24] = int[24](16, 16, 16, 16, 14, 10, 6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 10, 14, 16, 16, 16);
// 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);
// the next darker colour of the palette for each number. [0] is nothing.
const int DARKER[26] = int[26](0, 24, 25, 2, 3, 15, 7, 20, 9, 20, 21, 10, 13, 25, 12, 16, 14, 25, 17, 18, 21, 24, 25, 22, 24, 24);

// a colour made darker by the table, steps times
int darker(int n, int steps) {
  int c = n;
  for (int i = 0; i < steps; i++) c = DARKER[c];
  return c;
}

// the picture darkened by the hour, except what gives light
int shade(ivec2 p) {
  int n = at(p);
  // what gives light (a lit window, a lantern's flame) keeps its colour at every hour
  if (otherAt(p) != 0) return n;
  // how dark this hour is, in sixteenths of a step: the whole steps, and what is left over
  int depth = DUSK[wrap(hour, 24)] * night;
  int steps = depth >> 4;
  // what is left over is mixed in by the pattern: that many of every 16 pixels go one step further
  if ((depth & 15) > BAYER[(p.y & 3) * 4 + (p.x & 3)]) steps++;
  return darker(n, steps);
}
// ---- 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, 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 sand wall (7) with a lit window of honey (8) in a dark frame (1), a hive of the same honey on the
// right, and slate stones (2) below
const STREET = picture([
  "7777777",
  "7881777",
  "7881777",
  "7777887",
  "2222222",
]);
// what gives light: the window's panes only
const GLOWS = picture([
  "0000000",
  "0880000",
  "0880000",
  "0000000",
  "0000000",
]);

const BLOCK = (digit: string) => picture(["", "", "", ""].map(() => digit.repeat(4)));
const when = (hour: number, night = DEFAULTS.night) => ({ ...DEFAULTS, hour, night });

test("by day every pixel keeps its colour", () => {
  for (const hour of [8, 12, 16]) {
    for (let y = 0; y < STREET.height; y++) {
      for (let x = 0; x < STREET.width; x++) assert.equal(shade(x, y, 0, STREET, when(hour), GLOWS), STREET.index[y * STREET.width + x]);
    }
  }
});

test("at midnight a colour is as many steps darker as `night` says, by the table", () => {
  // sand goes darker as wood (20), then dark wood (21); slate as night, a shade lighter (25)
  assert.equal(shade(0, 0, 0, STREET, when(0, 1), GLOWS), 20);
  assert.equal(shade(0, 0, 0, STREET, when(0, 2), GLOWS), 21);
  assert.equal(shade(0, 4, 0, STREET, when(0, 1), GLOWS), 25);
});

test("what gives light keeps its colour at every hour", () => {
  for (let hour = 0; hour < 24; hour++) {
    assert.equal(shade(1, 1, 0, STREET, when(hour), GLOWS), 8, `at ${hour} o'clock`);
    assert.equal(shade(2, 2, 0, STREET, when(hour), GLOWS), 8, `at ${hour} o'clock`);
  }
});

test("the picture of what gives light decides, not the colour: the same honey on the hive goes dark", () => {
  assert.equal(shade(1, 1, 0, STREET, when(0, 2), GLOWS), 8);
  assert.equal(shade(4, 3, 0, STREET, when(0, 2), GLOWS), 20);
  // the window's dark frame is not in the picture of what gives light either
  assert.equal(shade(3, 1, 0, STREET, when(0, 2), GLOWS), 24);
});

test("dusk comes in sixteenths: at 17 o'clock 6 of every 16 pixels are one step darker", () => {
  const sand = BLOCK("7");
  const answers: number[] = [];
  for (let y = 0; y < 4; y++) for (let x = 0; x < 4; x++) answers.push(shade(x, y, 0, sand, when(17, 3)));
  assert.equal(answers.filter((n) => n === 20).length, 6);
  assert.equal(answers.filter((n) => n === 7).length, 10);
});

test("the evening only gets darker, hour by hour, and the morning only lighter", () => {
  // white goes darker as palest blue, sky, light blue, blue, deep blue, night: its place in that list is its steps
  const RAMP = [5, 15, 16, 14, 12, 13, 25, 24];
  const white = BLOCK("5");
  const steps = (hour: number) => {
    let sum = 0;
    for (let y = 0; y < 4; y++) for (let x = 0; x < 4; x++) sum += RAMP.indexOf(shade(x, y, 0, white, when(hour, 3)));
    return sum;
  };
  const evening = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0].map(steps);
  const morning = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map(steps);
  for (let i = 1; i < evening.length; i++) assert.ok(evening[i] >= evening[i - 1], `the evening got lighter: ${evening.join(", ")}`);
  for (let i = 1; i < morning.length; i++) assert.ok(morning[i] <= morning[i - 1], `the morning got darker: ${morning.join(", ")}`);
  assert.ok(evening[0] === 0 && evening[12] === 16 * 3);
});

test("an empty pixel stays empty at every hour", () => {
  const holes = picture(["070", "000"]);
  for (let hour = 0; hour < 24; hour++) assert.equal(shade(0, 0, 0, holes, when(hour)), 0);
});
Was wir geprüft haben
  • 7 Tests bestehen mit der Regel.
  • Mit dem eingebauten Fehler schlagen 2 davon fehl: "what gives light keeps its colour at every hour", "the picture of what gives light decides, not the colour: the same honey on the hive goes dark".
  • 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

Die Dorfstraße ist einmal gezeichnet, bei Tag. Wie macht die Regel dieser Lektion daraus die Nacht?

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

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

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