Lighting system

This commit is contained in:
2026-09-25 15:40:09 -03:00
parent 25f8c683bb
commit 4539898c58
12 changed files with 634 additions and 349 deletions
+149 -23
View File
@@ -1,6 +1,7 @@
import { Camera } from "../components/camera.ts";
import { mat4 } from "gl-matrix";
import type { RenderLayer } from "$/common/everything_registry.ts";
import { TERRAIN_VERTEX_FLOATS } from "../workers/chunk_messages.ts";
export let device: GPUDevice;
export let canvas: HTMLCanvasElement;
@@ -28,6 +29,9 @@ let quad_index_capacity = 0;
let uniform_layout: GPUBindGroupLayout;
let texture_layout: GPUBindGroupLayout;
let sampler: GPUSampler;
// minecraft's lightmap: the color for every block light (x) and sky light (y) pair, see update_lightmap
let lightmap: GPUTexture;
let lightmap_bind_group: GPUBindGroup;
const vertex_data = new Float32Array(MAX_SPRITES * VERTS_PER_SPRITE * FLOATS_PER_VERT);
let vert_index = 0;
@@ -106,22 +110,73 @@ fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
}
return color;
}
`;
const terrain_shader_src = /* wgsl */ `
struct Uniforms {
mvp: mat4x4<f32>,
}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(1) @binding(0) var texture0: texture_2d<f32>;
@group(1) @binding(1) var sampler0: sampler;
@group(2) @binding(0) var lightmap: texture_2d<f32>;
@group(2) @binding(1) var lightmap_sampler: sampler;
struct VertexOut {
@builtin(position) position: vec4<f32>,
@location(0) @interpolate(perspective, centroid) tex_coord: vec2<f32>,
// directional shade times ambient occlusion, and alpha
@location(1) @interpolate(perspective, centroid) color: vec4<f32>,
// block light, sky light, as lightmap coordinates
@location(2) @interpolate(perspective, centroid) light: vec2<f32>,
}
@vertex
fn vs_terrain(
@location(0) position: vec3<f32>,
@location(1) tex_coord: vec2<f32>,
@location(2) color: vec4<f32>,
@location(3) light: vec2<f32>,
) -> VertexOut {
var out: VertexOut;
out.position = uniforms.mvp * vec4<f32>(position, 1.0);
out.tex_coord = tex_coord;
out.color = color;
out.light = light;
return out;
}
fn lit(in: VertexOut) -> vec4<f32> {
let texel = textureSample(texture0, sampler0, in.tex_coord);
let light = textureSample(lightmap, lightmap_sampler, in.light).rgb;
return vec4<f32>(texel.rgb * in.color.rgb * light, texel.a * in.color.a);
}
// no discard, so the gpu can reject hidden fragments before running the shader
@fragment
fn fs_solid(in: VertexOut) -> @location(0) vec4<f32> {
return vec4<f32>((textureSample(texture0, sampler0, in.tex_coord) * in.color).rgb, 1.0);
return vec4<f32>(lit(in).rgb, 1.0);
}
// alpha tested instead of blended, so it doesn't need sorting
@fragment
fn fs_cutout(in: VertexOut) -> @location(0) vec4<f32> {
let color = textureSample(texture0, sampler0, in.tex_coord) * in.color;
let color = lit(in);
if (color.a < 0.1) {
discard;
}
return vec4<f32>(color.rgb, 1.0);
}
@fragment
fn fs_translucent(in: VertexOut) -> @location(0) vec4<f32> {
let color = lit(in);
if (color.a < 0.01) {
discard;
}
return color;
}
`;
export async function init_window(canvas_element: HTMLCanvasElement) {
@@ -164,6 +219,47 @@ export async function init_window(canvas_element: HTMLCanvasElement) {
create_uniform_buffer(64);
create_white_texture();
create_lightmap();
}
// how bright the sky is, 1 at noon. only the lightmap changes, the chunk meshes stay the same
export function update_lightmap(daylight = 1) {
// minecraft's LightTexture, with its default brightness setting and no flicker
const gamma = 0.5;
const brightness = (level: number) => {
const f = level / 15;
return f / (4 - 3 * f);
};
const lerp = (from: number, to: number, t: number) => from + (to - from) * t;
const clamp = (value: number) => Math.min(1, Math.max(0, value));
const not_gamma = (value: number) => 1 - (1 - value) ** 4;
const sky_factor = daylight * 0.95 + 0.05;
// sky light turns blue as it gets dark
const sky_color = [lerp(daylight, 1, 0.35), lerp(daylight, 1, 0.35), 1];
const block_boost = 1.5;
const pixels = new Uint8Array(16 * 16 * 4);
for (let sky = 0; sky < 16; sky++) {
for (let block = 0; block < 16; block++) {
const s = brightness(sky) * sky_factor;
// block light is warm, it loses blue and green faster as it dims
const b = brightness(block) * block_boost;
const color = [
b + sky_color[0] * s,
b * ((b * 0.6 + 0.4) * 0.6 + 0.4) + sky_color[1] * s,
b * (b * b * 0.6 + 0.4) + sky_color[2] * s,
].map((c) => clamp(lerp(c, 0.75, 0.04)))
.map((c) => clamp(lerp(lerp(c, not_gamma(c), gamma), 0.75, 0.04)));
const i = (sky * 16 + block) * 4;
pixels[i] = Math.round(color[0] * 255);
pixels[i + 1] = Math.round(color[1] * 255);
pixels[i + 2] = Math.round(color[2] * 255);
pixels[i + 3] = 255;
}
}
device.queue.writeTexture({ texture: lightmap }, pixels, { bytesPerRow: 16 * 4 }, [16, 16]);
}
export function begin_drawing() {
@@ -303,6 +399,7 @@ export function draw_terrain(
render_pass.setBindGroup(0, uniform_bind_group, [uniform_slot * UNIFORM_SLOT_SIZE]);
render_pass.setBindGroup(1, get_texture_bind_group(current_texture));
render_pass.setBindGroup(2, lightmap_bind_group);
render_pass.setVertexBuffer(0, vertex_buffer);
render_pass.setIndexBuffer(index_buffer, "uint32");
render_pass.drawIndexed(quad_count * 6);
@@ -657,31 +754,41 @@ function create_pipelines() {
depthStencil: depth_3d,
});
const terrain_module = device.createShaderModule({ code: terrain_shader_src });
const terrain_layout = device.createPipelineLayout({
bindGroupLayouts: [uniform_layout, texture_layout, texture_layout],
});
const terrain_vertex: GPUVertexState = {
module: terrain_module,
entryPoint: "vs_terrain",
buffers: [{
arrayStride: TERRAIN_VERTEX_FLOATS * 4,
attributes: [
{ shaderLocation: 0, offset: 0, format: "float32x3" },
{ shaderLocation: 1, offset: 12, format: "float32x2" },
{ shaderLocation: 2, offset: 20, format: "float32x4" },
{ shaderLocation: 3, offset: 36, format: "float32x2" },
],
}],
};
// like sodium and vanilla: solid and cutout don't blend, translucent blends and still writes depth
// since it's drawn sorted back to front
const unblended = (entryPoint: string): GPUFragmentState => ({
module,
entryPoint,
targets: [{ format: canvas_format }],
});
const terrain_pipeline = (entryPoint: string, blend?: GPUBlendState) =>
device.createRenderPipeline({
layout: terrain_layout,
vertex: terrain_vertex,
fragment: { module: terrain_module, entryPoint, targets: [{ format: canvas_format, blend }] },
multisample,
primitive: primitive_3d,
depthStencil: depth_3d,
});
terrain_pipelines = {
solid: device.createRenderPipeline({
layout,
vertex,
fragment: unblended("fs_solid"),
multisample,
primitive: primitive_3d,
depthStencil: depth_3d,
solid: terrain_pipeline("fs_solid"),
cutout: terrain_pipeline("fs_cutout"),
translucent: terrain_pipeline("fs_translucent", {
color: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
alpha: { srcFactor: "src-alpha", dstFactor: "one-minus-src-alpha", operation: "add" },
}),
cutout: device.createRenderPipeline({
layout,
vertex,
fragment: unblended("fs_cutout"),
multisample,
primitive: primitive_3d,
depthStencil: depth_3d,
}),
translucent: pipeline_3d,
};
}
@@ -715,6 +822,25 @@ function get_texture_bind_group(texture: GPUTexture) {
return bind_group;
}
function create_lightmap() {
lightmap = create_texture(16, 16);
// linear, so light fades smoothly between levels across a face like in minecraft
const lightmap_sampler = device.createSampler({
magFilter: "linear",
minFilter: "linear",
addressModeU: "clamp-to-edge",
addressModeV: "clamp-to-edge",
});
lightmap_bind_group = device.createBindGroup({
layout: texture_layout,
entries: [
{ binding: 0, resource: lightmap.createView() },
{ binding: 1, resource: lightmap_sampler },
],
});
update_lightmap();
}
function create_white_texture() {
const tex = create_texture(1, 1);
device.queue.writeTexture({ texture: tex }, new Uint8Array([255, 255, 255, 255]), { bytesPerRow: 4 }, [1, 1]);