From cbc9edfd60960125a71d12ae98ace437c85d8f8e Mon Sep 17 00:00:00 2001 From: paulaboks Date: Wed, 30 Sep 2026 16:56:55 -0300 Subject: [PATCH] Lighting for entities --- client/level/client_level.ts | 20 ++++++++++ client/renderer/core.ts | 10 +++++ client/rendering/entity_light.ts | 19 ++++++++++ client/rendering/entity_renderer.ts | 8 ++-- client/rendering/game_renderer.ts | 2 +- client/rendering/hand_renderer.ts | 11 ++++-- client/rendering/item_renderer.ts | 27 ++++++++----- client/rendering/level_renderer.ts | 4 +- client/workers/chunk_messages.ts | 3 ++ client/workers/chunk_worker.ts | 18 +++++++++ tests/entity_light_test.ts | 59 +++++++++++++++++++++++++++++ 11 files changed, 163 insertions(+), 18 deletions(-) create mode 100644 client/rendering/entity_light.ts create mode 100644 tests/entity_light_test.ts diff --git a/client/level/client_level.ts b/client/level/client_level.ts index 234ca3d..8a4679d 100644 --- a/client/level/client_level.ts +++ b/client/level/client_level.ts @@ -45,6 +45,8 @@ export interface Chunk { translucent_sort?: TranslucentSort; // each column's biome grass color, x then z, then each column's foliage color biome_colors: Uint32Array; + // from its last mesh, see get_light. undefined until it's been meshed + light?: Uint8Array; } export interface ChunkMesh { @@ -85,6 +87,8 @@ const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-1, -1], [1, -1], [-1, 1], [ // how far past the view distance chunks are kept, like minecraft's ClientChunkCache. the server tells the client // which ones to forget, this only catches the ones it didn't const STORAGE_MARGIN = 3; +// block light 0 and sky light 15, packed like Chunk.light +export const FULL_SKY_LIGHT = 15; // what minecraft calls the ClientLevel: this client's copy of the world, its chunks and the entities in it. the // chunks are what the server sent, see common/chunk_streaming.ts @@ -246,6 +250,21 @@ export class ClientLevel { this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, nid); } + // block light << 4 | sky light there, as of its chunk's last mesh. full sky light above the world and where it isn't + // known yet, so entities don't go dark while their chunk loads + get_light(x: number, y: number, z: number): number { + const block_y = Math.floor(y); + if (block_y >= CHUNK_HEIGHT) return FULL_SKY_LIGHT; + if (block_y < 0) return 0; + const chunk_x = Math.floor(x / CHUNK_SIZE); + const chunk_z = Math.floor(z / CHUNK_SIZE); + const light = this.get_chunk(chunk_x, chunk_z)?.light; + if (!light) return FULL_SKY_LIGHT; + const lx = Math.floor(x) - chunk_x * CHUNK_SIZE; + const lz = Math.floor(z) - chunk_z * CHUNK_SIZE; + return light[block_y * CHUNK_AREA + lz * CHUNK_SIZE + lx]; + } + // the id with its state bits, VOID outside loaded chunks get_block_value(x: number, y: number, z: number) { const chunk_x = Math.floor(x / CHUNK_SIZE); @@ -493,6 +512,7 @@ export class ClientLevel { } this.delete_chunk_mesh(chunk); + chunk.light = message.light; chunk.min_y = message.min_y; chunk.max_y = message.max_y; diff --git a/client/renderer/core.ts b/client/renderer/core.ts index 7932fcf..4ede117 100644 --- a/client/renderer/core.ts +++ b/client/renderer/core.ts @@ -32,6 +32,8 @@ 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; +// the same colors on the cpu, r g b from 0 to 1 by sky * 16 + block, for lighting entities, see light_color +const lightmap_colors = new Float32Array(16 * 16 * 3); const vertex_data = new Float32Array(MAX_SPRITES * VERTS_PER_SPRITE * FLOATS_PER_VERT); let vert_index = 0; @@ -257,6 +259,7 @@ export function update_lightmap(daylight = 1) { pixels[i + 1] = Math.round(color[1] * 255); pixels[i + 2] = Math.round(color[2] * 255); pixels[i + 3] = 255; + for (let c = 0; c < 3; c++) lightmap_colors[(sky * 16 + block) * 3 + c] = pixels[i + c] / 255; } } device.queue.writeTexture({ texture: lightmap }, pixels, { bytesPerRow: 16 * 4 }, [16, 16]); @@ -348,6 +351,13 @@ export function begin_view_model(fov: number) { write_mvp(); } +// the lightmap's color for light packed as block light << 4 | sky light (see ClientLevel.get_light), what terrain +// lit like that is multiplied by. entities multiply it into their vertex colors, like minecraft's packed light coords +export function light_color(packed: number): [number, number, number] { + const i = ((packed & 15) * 16 + (packed >> 4)) * 3; + return [lightmap_colors[i], lightmap_colors[i + 1], lightmap_colors[i + 2]]; +} + export function end_mode_3d() { if (!mode3d) { return; diff --git a/client/rendering/entity_light.ts b/client/rendering/entity_light.ts new file mode 100644 index 0000000..31053c2 --- /dev/null +++ b/client/rendering/entity_light.ts @@ -0,0 +1,19 @@ +// lighting entities like minecraft: one light level per entity each frame, at its eyes, looked up in the same lightmap +// as terrain and multiplied into its vertex colors. burning ones have full block light +import type { Entity } from "$/client/entity/entity.ts"; +import type { ClientLevel } from "$/client/level/client_level.ts"; +import { light_color } from "$/client/renderer/mod.ts"; +import type { Vec3 } from "./player_renderer.ts"; + +// the color for the light at a point, times tint (like the hurt flash) +export function light_tint(level: ClientLevel, x: number, y: number, z: number, tint?: Vec3, on_fire = false): Vec3 { + let packed = level.get_light(x, y, z); + if (on_fire) packed |= 15 << 4; + const [r, g, b] = light_color(packed); + return tint ? [r * tint[0], g * tint[1], b * tint[2]] : [r, g, b]; +} + +export function entity_tint(entity: Entity, partial_tick: number, tint?: Vec3, on_fire = false): Vec3 { + const { x, y, z } = entity.render_position(partial_tick); + return light_tint(entity.level, x, y + entity.render_eye_height(partial_tick), z, tint, on_fire); +} diff --git a/client/rendering/entity_renderer.ts b/client/rendering/entity_renderer.ts index f144b6b..511207f 100644 --- a/client/rendering/entity_renderer.ts +++ b/client/rendering/entity_renderer.ts @@ -10,6 +10,7 @@ import type { SpriteRegion } from "$/common/constants.ts"; import { EverythingRegistry } from "$/common/everything_registry.ts"; import type { EntityBoneJson, EntityJson, EntityModelJson } from "$/common/mod_data.ts"; import { HURT_TINT, push_box, type Vec3 } from "./player_renderer.ts"; +import { entity_tint } from "./entity_light.ts"; // models are in texture pixels, 16 to a block const PIXEL = 1 / 16; @@ -20,8 +21,10 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_ if (!json) return; const atlas = AssetManager.instance.get("bworld:textures"); const region = get_sprite_region(json.texture); + const hurt = entity.hurt_time > 0 || entity.dead ? HURT_TINT : undefined; + const tint = entity_tint(entity, partial_tick, hurt, entity.data.on_fire === true); if (json.model === undefined) { - render_sprite(entity, camera, atlas, region, partial_tick); + render_sprite(entity, camera, atlas, region, partial_tick, tint); return; } const model = EverythingRegistry.get("entity_models", json.model); @@ -35,7 +38,6 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_ const { x, y, z } = entity.render_position(partial_tick); const yaw_sin = Math.sin(entity.yaw); const yaw_cos = Math.cos(entity.yaw); - const tint = entity.hurt_time > 0 || entity.dead ? HURT_TINT : undefined; const bones = new Map(); for (const bone of model.bones) { @@ -70,6 +72,7 @@ function render_sprite( atlas: Texture, region: SpriteRegion, partial_tick: number, + [r, g, b]: Vec3, ) { const { x, y, z } = entity.render_position(partial_tick); const cy = y + entity.height / 2; @@ -80,7 +83,6 @@ function render_sprite( const [pitch_sin, pitch_cos] = [Math.sin(camera.pitch), Math.cos(camera.pitch)]; const right: Vec3 = [yaw_cos * half_width, 0, -yaw_sin * half_width]; const up: Vec3 = [yaw_sin * pitch_sin * half_height, pitch_cos * half_height, yaw_cos * pitch_sin * half_height]; - const [r, g, b] = entity.hurt_time > 0 || entity.dead ? HURT_TINT : [1, 1, 1]; const u0 = region.x / atlas.width; const v0 = region.y / atlas.height; diff --git a/client/rendering/game_renderer.ts b/client/rendering/game_renderer.ts index 89e5860..2822070 100644 --- a/client/rendering/game_renderer.ts +++ b/client/rendering/game_renderer.ts @@ -45,7 +45,7 @@ export class GameRenderer { this.level_renderer.render_entities(client.level, camera, client.player, partial_tick); this.level_renderer.render_translucent(client.level, camera); end_mode_3d(); - this.hand.render(client.player); + this.hand.render(client.player, partial_tick); this.hud.render(client); client.screen?.on_render(); diff --git a/client/rendering/hand_renderer.ts b/client/rendering/hand_renderer.ts index dfa7801..230b89b 100644 --- a/client/rendering/hand_renderer.ts +++ b/client/rendering/hand_renderer.ts @@ -8,6 +8,7 @@ import type { LocalPlayer } from "$/client/entity/local_player.ts"; import { begin_view_model, end_mode_3d, flush_batch, set_current_texture, Texture } from "$/client/renderer/mod.ts"; import { item_block, push_item } from "./item_renderer.ts"; import { push_cube, right_arm, type Vec3 } from "./player_renderer.ts"; +import { entity_tint } from "./entity_light.ts"; // wider than the world's field of view, like minecraft's fixed 70 degrees for the hand const FOV = 70 * Math.PI / 180; @@ -34,7 +35,7 @@ export class HandRenderer { } } - render(player: LocalPlayer) { + render(player: LocalPlayer, partial_tick: number) { const inventories = player.inventories; const item = inventories.inventory.get_item(inventories.hotbar_selected); const held = item ? `${inventories.hotbar_selected} ${item.type_id}` : ""; @@ -47,18 +48,20 @@ export class HandRenderer { const equip = Math.min(1, (now - this.#equipped_at) / EQUIP_MS); const swing_progress = Math.min(1, (now - this.#swung_at) / SWING_MS); + // the light where the player's eyes are, like every other entity + const tint = entity_tint(player, partial_tick); begin_view_model(FOV); if (item) { const atlas = AssetManager.instance.get("bworld:textures"); set_current_texture(atlas.tex); - push_item(atlas, item, pose(item, (1 - equip) * 0.6, Math.sin(swing_progress * Math.PI))); + push_item(atlas, item, pose(item, (1 - equip) * 0.6, Math.sin(swing_progress * Math.PI)), tint); } else { const skin = player.skin ?? AssetManager.instance.get("bworld:skin"); const arm = right_arm(player.slim); const transform = arm_pose(arm.pivot, 1 - equip, swing_progress); set_current_texture(skin.tex); - push_cube(skin, arm, arm.texture, 0, transform); - push_cube(skin, arm, arm.overlay, arm.inflate, transform); + push_cube(skin, arm, arm.texture, 0, transform, tint); + push_cube(skin, arm, arm.overlay, arm.inflate, transform, tint); } flush_batch(); end_mode_3d(); diff --git a/client/rendering/item_renderer.ts b/client/rendering/item_renderer.ts index 9039565..ceadbed 100644 --- a/client/rendering/item_renderer.ts +++ b/client/rendering/item_renderer.ts @@ -4,12 +4,14 @@ import { AssetManager } from "$/client/assets.ts"; import { get_sprite_region } from "$/client/sprites.ts"; import type { ItemEntity } from "$/client/entity/item_entity.ts"; import type { ItemStack } from "$/common/inventory.ts"; -import { push_vertex, Texture } from "$/client/renderer/mod.ts"; +import { light_color, push_vertex, Texture } from "$/client/renderer/mod.ts"; import { block_item_texture, block_variant, cube_face_texture, cube_face_tint } from "$/common/block_models.ts"; import { item_model } from "./item_model.ts"; import { get_state_value, item_texture } from "$/common/utils.ts"; import { ID_MASK, TEXTURE_SIZE } from "$/common/constants.ts"; import type { ClientLevel } from "$/client/level/client_level.ts"; +import { entity_tint } from "./entity_light.ts"; +import type { Vec3 } from "./player_renderer.ts"; // how big items on the ground are drawn, minecraft's ground transform const BLOCK_SCALE = 0.25; @@ -65,6 +67,7 @@ export function render_item_entity(entity: ItemEntity, partial_tick: number) { const cos = Math.cos(angle); const scale = item_block(entity.item) ? BLOCK_SCALE : ITEM_SCALE; + const tint = entity_tint(entity, partial_tick); for (let i = 0; i < copies(entity.item.amount); i++) { const [ox, oy, oz] = COPY_OFFSETS[i]; const bx = x + ox * scale; @@ -74,7 +77,7 @@ export function render_item_entity(entity: ItemEntity, partial_tick: number) { bx + (lx * cos - lz * sin) * scale, by + ly * scale, bz + (lx * sin + lz * cos) * scale, - ]); + ], tint); } } @@ -89,7 +92,11 @@ export function render_block_items(level: ClientLevel) { const value = level.get_block_value(x, y, z); const block = blocks[value & ID_MASK]; if (!block?.item_display) continue; - push_shown_item(atlas, block, value, item, x, y, z); + // the block's own light, or the one above for blocks light doesn't get into, since the items sit on top + const here = level.get_light(x, y, z); + const above = level.get_light(x, y + 1, z); + const tint = light_color((Math.max(here >> 4, above >> 4) << 4) | Math.max(here & 15, above & 15)); + push_shown_item(atlas, block, value, item, x, y, z, tint); } } } @@ -102,6 +109,7 @@ function push_shown_item( x: number, y: number, z: number, + tint: Vec3, ) { const states: Record = {}; for (const state of block.states ?? []) states[state.name] = get_state_value(value, block, state.name)!; @@ -133,7 +141,7 @@ function push_shown_item( cx + (rx * lx - bx * lz) * scale, bottom + ly * scale, cz + (rz * lx - bz * lz) * scale, - ]); + ], tint); } else { // lying face up, its top away from whoever it faces so they read it the right way round const half = scale / TEXTURE_SIZE / 2; @@ -141,7 +149,7 @@ function push_shown_item( cx + (rx * lx + bx * (ly - 0.5)) * scale, bottom + half + lz * scale, cz + (rz * lx + bz * (ly - 0.5)) * scale, - ]); + ], tint); } } } @@ -166,15 +174,16 @@ export function item_block(item: ItemStack): BlockRegistry | undefined { return block && block_item_texture(block) === undefined ? block : undefined; } -// an item's model: a cube for blocks, its sprite made 3d for everything else (see item_model.ts) -export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransform) { +// an item's model: a cube for blocks, its sprite made 3d for everything else (see item_model.ts). tint multiplies its +// colors, like the light it's in +export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransform, [tr, tg, tb]: Vec3 = [1, 1, 1]) { const block = item_block(item); if (block) { for (const face of CUBE_FACES) { const region = get_sprite_region(cube_face_texture(block, face.texture)); const corners = face.corners.map(([cx, cy, cz]) => transform(cx - 0.5, cy, cz - 0.5)); const [r, g, b] = cube_face_tint(block, face.texture); - push_textured_quad(atlas, region, corners, [face.shade * r, face.shade * g, face.shade * b]); + push_textured_quad(atlas, region, corners, [face.shade * r * tr, face.shade * g * tg, face.shade * b * tb]); } return; } @@ -187,7 +196,7 @@ export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransf for (const i of [0, 1, 2, 0, 2, 3]) { const [px, py, pz] = transform(...quad.corners[i]); const [pu, pv] = quad.uvs[i]; - push_vertex(px, py, pz, u(pu), v(pv), quad.shade, quad.shade, quad.shade, 1); + push_vertex(px, py, pz, u(pu), v(pv), quad.shade * tr, quad.shade * tg, quad.shade * tb, 1); } } } diff --git a/client/rendering/level_renderer.ts b/client/rendering/level_renderer.ts index 7f96515..31668a3 100644 --- a/client/rendering/level_renderer.ts +++ b/client/rendering/level_renderer.ts @@ -9,6 +9,7 @@ import { ItemEntity } from "$/client/entity/item_entity.ts"; import { render_block_items, render_item_entity } from "./item_renderer.ts"; import { HURT_TINT, render_player } from "./player_renderer.ts"; import { render_mod_entity } from "./entity_renderer.ts"; +import { entity_tint } from "./entity_light.ts"; import { RemoteEntity } from "$/client/entity/remote_entity.ts"; import { draw_terrain, @@ -104,7 +105,8 @@ export class LevelRenderer { flush_batch(); set_current_texture(skin.tex); } - render_player(entity, skin, partial_tick, entity.hurt_time > 0 ? HURT_TINT : undefined); + const tint = entity_tint(entity, partial_tick, entity.hurt_time > 0 ? HURT_TINT : undefined); + render_player(entity, skin, partial_tick, tint); } } flush_batch(); diff --git a/client/workers/chunk_messages.ts b/client/workers/chunk_messages.ts index 60c0d7e..f379b1b 100644 --- a/client/workers/chunk_messages.ts +++ b/client/workers/chunk_messages.ts @@ -83,6 +83,9 @@ export type FromChunkWorker = planes: [Float32Array, Float32Array, Float32Array]; }; camera: number[]; + // the chunk's light, one byte per block indexed like its blocks: block light << 4 | sky light, like sodium's + // packed light data. entities are lit from it + light: Uint8Array; } | { type: "sorted"; diff --git a/client/workers/chunk_worker.ts b/client/workers/chunk_worker.ts index d93fa55..15773ce 100644 --- a/client/workers/chunk_worker.ts +++ b/client/workers/chunk_worker.ts @@ -141,6 +141,7 @@ self.onmessage = (event: MessageEvent) => { message.chunks[4]!, message.camera, ); + const light = chunk_light(); post( { type: "meshed", @@ -153,8 +154,10 @@ self.onmessage = (event: MessageEvent) => { cutout, translucent, camera: message.camera, + light, }, [ + light.buffer, solid.vertices.buffer, cutout.vertices.buffer, translucent.vertices.buffer, @@ -181,6 +184,21 @@ self.onmessage = (event: MessageEvent) => { } }; +// the middle chunk of the light region, packed for the main thread, see "meshed" +function chunk_light() { + const light = new Uint8Array(CHUNK_AREA * CHUNK_HEIGHT); + for (let y = 0; y < CHUNK_HEIGHT; y++) { + for (let z = 0; z < CHUNK_SIZE; z++) { + const from = y * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE; + const to = y * CHUNK_AREA + z * CHUNK_SIZE; + for (let x = 0; x < CHUNK_SIZE; x++) { + light[to + x] = (region.block_light[from + x] << 4) | region.sky[from + x]; + } + } + } + return light; +} + function post(message: FromChunkWorker, transfer: Transferable[]) { self.postMessage(message, transfer); } diff --git a/tests/entity_light_test.ts b/tests/entity_light_test.ts new file mode 100644 index 0000000..c135c16 --- /dev/null +++ b/tests/entity_light_test.ts @@ -0,0 +1,59 @@ +// entities are lit from the light the chunk worker sends back with each mesh, one byte per block: block << 4 | sky +import { assertEquals } from "@std/assert"; +import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts"; +import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts"; +import { test_game } from "./helpers.ts"; + +// the middle chunk's light, with a stone roof at y 20 over x 0-7 and a light block at 12, 5, 8 +async function mesh_light() { + await test_game("mods"); + const blocks = EverythingRegistry.get_registry("blocks"); + const nid = (id: string) => blocks.findIndex((b) => b?.id === id); + const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" }); + worker.postMessage({ + type: "init", + blocks_registry: JSON.parse(JSON.stringify(blocks)), + models: {}, + textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } }, + image: { width: 1024, height: 1024 }, + }); + + const chunk = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT); + const at = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x; + for (let x = 0; x < 8; x++) { + for (let z = 0; z < CHUNK_SIZE; z++) chunk[at(x, 20, z)] = nid("bworld:stone"); + } + chunk[at(12, 5, 8)] = nid("bworld:light"); + const empty = () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT); + const chunks = [empty(), empty(), empty(), empty(), chunk, empty(), empty(), empty(), empty()]; + + const meshed = await new Promise<{ light: Uint8Array }>((resolve) => { + worker.onmessage = (e) => resolve(e.data); + worker.postMessage({ + type: "mesh", + chunk_x: 0, + chunk_z: 0, + version: 1, + chunks, + biome_colors: chunks.map(() => null), + camera: [0, 0, 0], + }); + }); + worker.terminate(); + const light = (x: number, y: number, z: number) => { + const packed = meshed.light[at(x, y, z)]; + return { block: packed >> 4, sky: packed & 15 }; + }; + return { light, size: meshed.light.length }; +} + +Deno.test("each mesh comes with its chunk's block and sky light, packed a byte per block", async () => { + const { light, size } = await mesh_light(); + assertEquals(size, CHUNK_AREA * CHUNK_HEIGHT); + assertEquals(light(12, 30, 8), { block: 0, sky: 15 }, "open sky"); + assertEquals(light(12, 6, 8), { block: 13, sky: 15 }, "next to the light block"); + // under the roof, sky light comes in sideways from the open side, a level less each block + assertEquals(light(7, 10, 8).sky, 14); + assertEquals(light(4, 10, 8).sky, 11); + assertEquals(light(4, 20, 8), { block: 0, sky: 0 }, "inside the stone"); +});