Move your pointer to move the light.

0:01 / 0:30
Playback speed

Normal map

Sweep the light across one groove. Which edge brightens first? Repeat with the normal map off.

Interactive demo#LightAndGlow

A second image telling the game which way each pixel’s surface faces.

With that information, a flat sprite can be lit as if it had bumps and grooves: pixels facing the light get brighter, pixels facing away get darker. Turn it off to see the same wall lit as a flat sheet.

Code

src/demos/normal_map.goose
namespace normal_map_lesson;
import stage;
import std;
import math;

var heights: f64[16000] = [0.0;16000];
var pixels: u8[64000] = [0;64000];
var ready = false;
fn build_heights() {
    for y in 100 {
        for x in 160 {
            let bx = (x + ((y / 16) % 2) * 16) % 32;
            let by = y % 16;
            let edge = min(min(bx, 31 - bx), min(by, 15 - by));
            let grain = sin(x * 12.9898 + y * 78.233) * 43758.5453;
            let bevel = min(1.0, edge / 3.0);
            let ridge = max(0.0, 1 - abs(abs(bx - 15.5) * 0.38 + abs(by - 7.5) - 4.1));
            heights[y * 160 + x] = if edge < 1 { 0.0 } else { bevel + ridge * 0.48 + (grain - floor(grain)) * 0.065 };
        }
    }
}

export "normal-map" fn draw(time: f64, dt: f64, px: f64, py: f64, hover: bool) {
    if !ready {
        build_heights();
        ready = true;
    }
    let on = toggle("on");
    for y in 100 {
        for x in 160 {
            let index = y * 160 + x;
            var nx = 0.0;
            var ny = 0.0;
            if on {
                nx = (heights[y * 160 + max(0, x - 1)] - heights[y * 160 + min(159, x + 1)]) * 2.4;
                ny = (heights[max(0, y - 1) * 160 + x] - heights[min(99, y + 1) * 160 + x]) * 2.4;
            }
            let dx = px - x;
            let dy = py - y;
            let distance = sqrt(dx * dx + dy * dy + 22.0 * 22.0);
            let normal = sqrt(nx * nx + ny * ny + 1);
            let diffuse = max(0.0, (nx * dx + ny * dy + 22) / (normal * distance));
            let light = 0.16 + diffuse * clamp(1.25 - distance / 110, 0.0, 1.0) * 1.25;
            let kiln = 0.91 + 0.08 * sin(floor(x / 32.0) * 3.8 + floor(y / 16.0) * 5.2);
            let tile = ((x + ((y / 16) % 2) * 16) / 32 + y / 16) % 3;
            let rgb = if heights[index] < 0.2 { [145.0, 135.0, 112.0] }
                      else if tile == 0 { [87.0 * kiln, 158.0 * kiln, 148.0 * kiln] }
                      else { [218.0 * kiln, 149.0 * kiln, 99.0 * kiln] };
            for channel in 3 {
                pixels[index * 4 + channel] = clamp(floor(rgb[channel] * light + 0.5), 0.0, 255.0) as u8;
            }
            pixels[index * 4 + 3] = 255;
        }
    }
    pixel_buffer(pixels[..], 160, 100);
    lamp(px, py);
}

Stage drawing helpers · All demos on GitHub

Comments

No comments yet.