Spielerando

Lektion 9 von 24Ein Sprite8 Min.Kostenlos

Rauschen im Shader für Pixel Art: auf jedem Gerät dieselben Sterne

Rauschen ist in einem Shader eine Zahl für jeden Pixel, die nach Zufall aussieht und keiner ist: Es ist der eigene Platz des Pixels, verwürfelt. Das Verwürfeln dieser Lektion kommt mit ganzen Zahlen aus, darum bekommt ein Platz auf jedem Gerät und bei jedem Start dieselbe Zahl, im Code des Spiels wie im Shader. Hier setzt es funkelnde Sterne in einen Nachthimmel.

Eine Nacht als Pixel Art: Eine Imkerin steht auf einem Hügel zwischen einem dunklen Baum und einer Reihe Bienenstöcke, rechts steht der Mond. Sterne füllen den Himmel, immer mehr, und jeder funkelt in seinem eigenen Takt; auf den Hügeln und dem Mond ist keiner.

Die ganze Szene geht an die Regel. Jeder Pixel des Nachthimmels bekommt eine verwürfelte Zahl von 0 bis 99, und wo sie unter der Einstellung liegt, steht ein Stern. Mehr Sterne behalten die, die schon da waren.

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

Die Idee

Spiele brauchen Dinge, die verstreut aussehen: Sterne, Körnung auf einer Steinmauer, die Grasbüschel, an denen eine Blume wächst, die Reihenfolge, in der eine Figur zerbröselt (die nächste Lektion). Echter Zufall ist dafür das falsche Werkzeug. Ein Shader hat keine Würfel, und würfelt das Spiel in jedem Bild neu, springen die Sterne herum; würfelt es einmal beim Start, hat jedes geladene Spiel einen anderen Himmel.

Also verwürfelt die Regel, was ein Pixel weiß, seine Spalte, seine Zeile und eine Startzahl, die das Spiel setzt, zu einer Zahl von 0 bis 99. Hinein geht derselbe Platz, also kommt dieselbe Zahl heraus.

Sie muss auch auf jedem Gerät gleich herauskommen. Eine bekannte Abkürzung in Shadern verwürfelt mit Bruchzahlen, etwa mit dem Sinus einer Zahl. Grafikkarten rechnen eine Bruchzahl nicht alle bis zur selben letzten Stelle aus, und den Sinus am wenigsten. Auf dem Handy einer Spielerin kann so ein Himmel darum anders aussehen als auf deinem Rechner. Summen, Produkte und Verschiebungen ganzer Zahlen kommen auf jeder Grafikkarte exakt gleich heraus. Darum lassen sich die einfache Funktion und der Shader Pixel für Pixel vergleichen, und darum kann der Code des Spiels ausrechnen, wo der Shader einen Stern oder eine Blume hingesetzt hat, und kommt zum selben Ergebnis.

So funktioniert es

Die Regel sieht zuerst auf die Farbe eines Pixels. Nur der Nachthimmel bekommt Sterne; die Einstellung night nennt seine Farbe, in der Palette die 24. Alles andere kommt zurück, wie es kam.

Ein Pixel des Himmels macht aus seinem Platz eine ganze Zahl: die Spalte, plus die Zeile mal 4099, plus die Startzahl mal 65537. Weil 4099 breiter ist als das Bild, beginnen keine zwei Plätze mit derselben Zahl. Das Verwürfeln verschiebt die Binärstellen dieser Zahl, mischt sie wieder hinein und multipliziert mit einer großen ungeraden Zahl, zweimal, und mischt am Ende noch einmal. Die letzten beiden Stellen des Ergebnisses sind die Zahl des Platzes von 0 bis 99. Wo sie unter dem Regler „Sterne“ liegt, steht ein Stern: bei 2 auf etwa zwei von hundert Plätzen.

Jeder Stern funkelt. Immer nach so vielen Ticks, wie der Regler „Takt“ sagt, am Anfang 30, also zweimal in der Sekunde, wählt er, wie hell er ist: Grauviolett, helles Schiefergrau oder Weiß, indem er seine Zahl zusammen mit der Zahl der Takte verwürfelt. Ein anderer Teil seiner verwürfelten Zahl legt fest, wann sein Takt fällt, also wechseln nicht alle Sterne zugleich. Ein Stern bewegt sich nie.

Der Regler „Startzahl“ wählt den Himmel: eine andere Startzahl, andere Plätze; dieselbe Startzahl, derselbe Himmel, Stern für Stern. Schiebst du „Sterne“ höher, bleiben die alten Sterne, denn eine Zahl unter 2 liegt auch unter 3.

Was schiefgeht

Bittest du eine KI um ein Verwürfeln mit ganzen Zahlen, schreibt sie oft eine einzige Multiplikation mit einer großen ungeraden Zahl. Das wirkt echt: Die Zahl ist riesig, und die ersten Ergebnisse scheinen wild zu springen. Aber eine Multiplikation behält die Ordnung der Plätze. Der Platz rechts daneben bekommt diese Zahl plus denselben großen Schritt, der nächste Platz wieder, und weil die Zahl oben überläuft und von vorn beginnt, gibt es den Schritt nur in zwei Größen. Auf die letzten beiden Stellen gekürzt, reihen sich diese gleichmäßigen Schritte über den Bildschirm.

Schalte das Bild auf „Mit dem Fehler“. Die Sterne stehen in schrägen Reihen mit gleichen Abständen, als hätte jemand den Himmel gekämmt. Das zeigt erst ein ganzes Bild, darum sieht es eine KI nicht, die eine Handvoll Zahlen prüft.

Zwei Tests fangen es. Der eine zählt die verschiedenen Schritte zwischen der Zahl eines Platzes und der seines Nachbarn: viele beim echten Verwürfeln, beim Fehler nur zwei („only 2 different steps to the neighbour on the right“). Der andere vergleicht ein paar Plätze mit Zahlen, die einmal aus dem echten Verwürfeln aufgeschrieben wurden; der Fehler gibt 73, wo 21 hingehört.

Der Fehler, Zeile für Zeile

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

- /* Noise you can trust, with the mistake: the scramble is one multiplication by a big odd number, the
-    shortcut an AI often writes when it is asked for a scramble in whole numbers. A multiplication keeps
-    the order of the places: the place to the right gets this place's number plus one of two steps,
-    again and again, so the stars line up in slanted stripes instead of lying anywhere.
+ /* Noise you can trust: every place of the picture gets a number from 0 to 99 by scrambling the
+    place's own numbers, its column and its row. The scramble is made of whole-number steps only, so it
+    gives the same number for the same place on every machine and at every run, in the game's code and
+    in the shader alike. Here it puts stars into a night sky: a place of the sky whose number is below
+    `stars` holds a star, and the same scramble, fed the time in whole steps, lets each star twinkle on
+    a beat of its own.

+    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 */
…
  }

- /** A whole number "scrambled", wrong: one multiplication by a big odd number, and nothing that mixes. */
+ /** A whole number scrambled into another, the same on every machine. */
  function hash(n: number): number {
-   return Math.imul(n, 0x9e3779b1) >>> 0;
+   n = Math.imul(n ^ (n >>> 16), 0x7feb352d);
+   n = Math.imul(n ^ (n >>> 15), 0x846ca68b);
+   return (n ^ (n >>> 16)) >>> 0;
  }

Was der Test zum Fehler sagt

✔ every place gets a number from 0 to 99, and each tenth of them comes about as often
✖ the scramble gives the numbers written down here, on every machine
    got 73, expected 21
✖ the step from a place to its neighbour comes in many sizes, so no stripes form
    only 2 different steps to the neighbour on the right
✔ a place of the sky is a star exactly when its number is below the setting
✔ the same seed gives the same sky every time it is asked, another seed another sky
✔ a star stays in its place: the ticks change only how bright it is
✔ only the sky gets stars: everything else stays as it came
7 tests: 5 passed, 2 failed

Das sagst du deiner KI

Schreib einen Shader, der funkelnde Sterne in den Nachthimmel meines Spiels setzt, mit einem Verwürfeln, auf das ich mich verlassen kann.

- Nur ganze Pixel und ganze Zahlen: keine Bruchzahlen, kein Sinus, keine Zufallszahlen. Die Zeit ist eine ganze Zahl von Ticks, die mein Spiel zählt, 60 in der Sekunde.
- Nimm genau dieses Verwürfeln, im Code des Spiels und im Shader: hash(n): n = (n xor (n >> 16)) * 0x7feb352d; n = (n xor (n >> 15)) * 0x846ca68b; return n xor (n >> 16). Jeder Schritt rechnet mit vorzeichenlosen ganzen 32-Bit-Zahlen, die überlaufen; hat die Sprache meines Spiels keine, behalte nach jedem Schritt die untersten 32 Bit.
- Die Zahl eines Platzes von 0 bis 99 ist hash(x + y * 4099 + seed * 65537) % 100. Ein Pixel in der Farbe meines Nachthimmels [die Farbe] trägt einen Stern, wo diese Zahl unter [Sterne je hundert Plätze, zum Beispiel 2] liegt. Jeder andere Pixel bleibt, wie er ist.
- Alle [Ticks, zum Beispiel 30] Ticks wählt jeder Stern in einem eigenen Moment, wie hell er ist, indem er seine Zahl zusammen mit der Zahl der Takte noch einmal verwürfelt. Sterne bewegen sich nie.

Schreib vor dem Shader dieselbe Regel als kleine, einfache Funktion und teste sie: hash(1) ist 1753845952, hash(2) ist 3507691905 und hash(65537) ist 2560066121; die Schritte zwischen den Zahlen benachbarter Plätze kommen in vielen Größen, nicht in einer oder zwei; dieselbe Startzahl gibt jedes Mal denselben Himmel. Zeig mir die Ausgabe des Tests. Schreib dann den Shader so, dass er genau das tut, was die Funktion tut, zeichne mit beiden ein Standbild und sag mir, wie viele Pixel sich unterscheiden.

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.

/* Noise you can trust: every place of the picture gets a number from 0 to 99 by scrambling the
   place's own numbers, its column and its row. The scramble is made of whole-number steps only, so it
   gives the same number for the same place on every machine and at every run, in the game's code and
   in the shader alike. Here it puts stars into a night sky: a place of the sky whose number is below
   `stars` holds a star, and the same scramble, fed the time in whole steps, lets each star twinkle on
   a beat of its own.

   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 many places of the sky in a hundred hold a star. */
  stars: 2,
  /** The ticks between two twinkles of one star: 60 is once a second. */
  pace: 30,
  /** Which sky: another number puts the stars in other places, and always in the same ones for that number. */
  seed: 1,
  /** The number of the night sky's colour in the palette: stars come only where it is. 24 is the night. */
  night: 24,
};
export type Params = typeof DEFAULTS;

/** 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 whole number scrambled into another, the same on every machine. */
function hash(n: number): number {
  n = Math.imul(n ^ (n >>> 16), 0x7feb352d);
  n = Math.imul(n ^ (n >>> 15), 0x846ca68b);
  return (n ^ (n >>> 16)) >>> 0;
}

/** The number from 0 to 99 for a place and a seed. */
export function noise(x: number, y: number, seed: number): number {
  return hash(x + y * 4099 + seed * 65537) % 100;
}

/** A star's colours from dim to bright: grey violet, light slate, white, white. */
const TWINKLE = [3, 4, 5, 5];

/** The rule: a place of the night sky whose number is below `stars` is a star; everything else stays as it came. */
export function shade(x: number, y: number, tick: number, src: Frame, p: Params = DEFAULTS): number {
  const here = at(src, x, y);
  if (here !== p.night) return here; // only the sky gets stars
  const place = hash(x + y * 4099 + p.seed * 65537); // the place, scrambled: noise() is its last two digits
  if (place % 100 >= p.stars) return here; // most places hold no star
  // every star twinkles on its own beat: another part of its scrambled number says when its beat starts
  const beat = Math.floor((tick + ((place >>> 8) % p.pace)) / p.pace);
  // the star's number and the beat's number, scrambled once more, pick how bright it is now
  return TWINKLE[hash(place + beat) % 4];
}

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 stars; // how many places of the sky in a hundred hold a star
uniform int pace;  // the ticks between two twinkles of one star: 60 is once a second
uniform int seed;  // which sky: another number puts the stars in other places, and always in the same ones for that number
uniform int night; // the number of the night sky's colour in the palette: stars come only where it is. 24 is the night

// a whole number scrambled into another, the same on every machine
uint hash(uint n) {
  n ^= n >> 16; n *= 0x7feb352du; n ^= n >> 15; n *= 0x846ca68bu; n ^= n >> 16;
  return n;
}

// the number from 0 to 99 for a place and a seed
int noise(ivec2 q, int s) {
  return int(hash(uint(q.x) + uint(q.y) * 4099u + uint(s) * 65537u) % 100u);
}

// a star's colours from dim to bright: grey violet, light slate, white, white
const int TWINKLE[4] = int[4](3, 4, 5, 5);

// a place of the night sky whose number is below stars is a star; everything else stays as it came
int shade(ivec2 p) {
  int here = at(p);
  if (here != night) return here; // only the sky gets stars
  uint place = hash(uint(p.x) + uint(p.y) * 4099u + uint(seed) * 65537u); // the place, scrambled: noise() is its last two digits
  if (int(place % 100u) >= stars) return here; // most places hold no star
  // every star twinkles on its own beat: another part of its scrambled number says when its beat starts
  int beat = (TICK + int((place >> 8u) % uint(pace))) / pace;
  // the star's number and the beat's number, scrambled once more, pick how bright it is now
  return TWINKLE[int(hash(place + uint(beat)) % 4u)];
}
// ---- 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 stars; // how many places of the sky in a hundred hold a star
uniform int pace;  // the ticks between two twinkles of one star: 60 is once a second
uniform int seed;  // which sky: another number puts the stars in other places, and always in the same ones for that number
uniform int night; // the number of the night sky's colour in the palette: stars come only where it is. 24 is the night

// a whole number scrambled into another, the same on every machine
uint hash(uint n) {
  n ^= n >> 16; n *= 0x7feb352du; n ^= n >> 15; n *= 0x846ca68bu; n ^= n >> 16;
  return n;
}

// the number from 0 to 99 for a place and a seed
int noise(ivec2 q, int s) {
  return int(hash(uint(q.x) + uint(q.y) * 4099u + uint(s) * 65537u) % 100u);
}

// a star's colours from dim to bright: grey violet, light slate, white, white
const int TWINKLE[4] = int[4](3, 4, 5, 5);

// a place of the night sky whose number is below stars is a star; everything else stays as it came
int shade(ivec2 p) {
  int here = at(p);
  if (here != night) return here; // only the sky gets stars
  uint place = hash(uint(p.x) + uint(p.y) * 4099u + uint(seed) * 65537u); // the place, scrambled: noise() is its last two digits
  if (int(place % 100u) >= stars) return here; // most places hold no star
  // every star twinkles on its own beat: another part of its scrambled number says when its beat starts
  int beat = (TICK + int((place >> 8u) % uint(pace))) / pace;
  // the star's number and the beat's number, scrambled once more, pick how bright it is now
  return TWINKLE[int(hash(place + uint(beat)) % 4u)];
}
// ---- 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, noise, 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 night sky of w by h pixels: every pixel is 24, the night's colour. */
function sky(w: number, h: number): Frame {
  return { width: w, height: h, index: new Uint8Array(w * h).fill(24) };
}

function whole(src: Frame, tick = 0, params = DEFAULTS): 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;
}

/** The places of a picture that the rule made into stars. */
const starsIn = (answers: number[]) => answers.flatMap((n, i) => (n !== 24 ? [i] : []));

test("every place gets a number from 0 to 99, and each tenth of them comes about as often", () => {
  const tenths = new Array(10).fill(0);
  for (let y = 0; y < 100; y++) {
    for (let x = 0; x < 100; x++) {
      const n = noise(x, y, 1);
      assert.ok(Number.isInteger(n) && n >= 0 && n <= 99, `noise(${x}, ${y}, 1) is ${n}`);
      tenths[Math.floor(n / 10)]++;
    }
  }
  // 10 000 places: a tenth of them is 1000, and none may be off by more than a tenth of that
  for (const count of tenths) assert.ok(count >= 900 && count <= 1100, `the tenths came ${tenths.join(", ")} times`);
});

test("the scramble gives the numbers written down here, on every machine", () => {
  assert.equal(noise(0, 0, 1), 21);
  assert.equal(noise(1, 0, 1), 83);
  assert.equal(noise(0, 1, 1), 31);
  assert.equal(noise(2, 3, 1), 75);
  assert.equal(noise(239, 134, 1), 33);
  assert.equal(noise(10, 20, 7), 12);
});

test("the step from a place to its neighbour comes in many sizes, so no stripes form", () => {
  const right = new Set<number>();
  const down = new Set<number>();
  for (let y = 0; y < 64; y++) {
    for (let x = 0; x < 64; x++) {
      right.add((noise(x + 1, y, 1) - noise(x, y, 1) + 100) % 100);
      down.add((noise(x, y + 1, 1) - noise(x, y, 1) + 100) % 100);
    }
  }
  assert.ok(right.size >= 50, `only ${right.size} different steps to the neighbour on the right`);
  assert.ok(down.size >= 50, `only ${down.size} different steps to the neighbour below`);
});

test("a place of the sky is a star exactly when its number is below the setting", () => {
  const night = sky(64, 64);
  for (const stars of [0, 3, 10, 50, 100]) {
    const answers = whole(night, 0, { ...DEFAULTS, stars });
    for (let i = 0; i < answers.length; i++) {
      const x = i % 64;
      const y = Math.floor(i / 64);
      assert.equal(answers[i] !== 24, noise(x, y, DEFAULTS.seed) < stars, `${x}, ${y} with stars ${stars}`);
    }
  }
});

test("the same seed gives the same sky every time it is asked, another seed another sky", () => {
  const night = sky(64, 64);
  const once = whole(night, 0, { ...DEFAULTS, seed: 1 });
  const again = whole(night, 0, { ...DEFAULTS, seed: 1 });
  const other = whole(night, 0, { ...DEFAULTS, seed: 2 });
  assert.deepEqual(again, once);
  assert.notDeepEqual(starsIn(other), starsIn(once));
});

test("a star stays in its place: the ticks change only how bright it is", () => {
  const night = sky(64, 64);
  const first = whole(night, 0);
  const places = starsIn(first);
  assert.ok(places.length > 0, "the sky has no star at all");
  let twinkled = 0;
  for (let tick = 1; tick <= 300; tick += 7) {
    const now = whole(night, tick);
    assert.deepEqual(starsIn(now), places, `at tick ${tick} the stars are in other places`);
    for (const i of places) if (now[i] !== first[i]) twinkled++;
  }
  assert.ok(twinkled > 0, "no star ever changed how bright it is");
});

test("only the sky gets stars: everything else stays as it came", () => {
  const hill = picture([
    "1111",
    "1191",
    "2662",
    "7777",
  ]);
  // with 1 as the sky's colour and every place of it a star, only the 1s change, and only into star colours
  const answers = whole(hill, 0, { ...DEFAULTS, night: 1, stars: 100 });
  hill.index.forEach((n, i) => {
    if (n === 1) assert.ok([3, 4, 5].includes(answers[i]), `the sky at ${i % 4}, ${Math.floor(i / 4)} became ${answers[i]}`);
    else assert.equal(answers[i], n);
  });
});
Was wir geprüft haben
  • 7 Tests bestehen mit der Regel.
  • Mit dem eingebauten Fehler schlagen 2 davon fehl: "the scramble gives the numbers written down here, on every machine", "the step from a place to its neighbour comes in many sizes, so no stripes form".
  • 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 14 Bildern und ergab in 453.600 von 453.600 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

Diese Lektion setzt mit Rauschen Sterne in einen Nachthimmel. Warum bleibt ein Stern von Bild zu Bild an seinem Platz und kommt nach dem Laden des Spiels genauso wieder?

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

Nächste Lektion Dissolve-Shader für Pixel Art: Zerbröseln ohne Flackern

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