BlueGit

timfa questward

Apply baked-light raycasts to dynamic lights and fix lantern unequip.

Share Bresenham LOS and smooth falloff between server bake and client runtime lighting, forward lightRadiusTiles on appearance updates, and clear equipped lantern light immediately on unequip.

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
dbb944ff8e4db3122897f17f19a002fdd647f567
Parent
2920dd06
6 files changed +155 −102
client/src/render/worldView.js +30 −29
@@ -1,4 +1,6 @@
1 1 import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
2 import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3 import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
2 4 import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
3 5 import { itemSpriteName } from "/shared/definitions/items.js";
4 6 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
@@ -268,7 +270,7 @@ export class WorldView
268 270 const existing = this.entities.get(payload.entityId);
269 271 if (!existing)
270 272 { return; }
271 existing.lightRadiusTiles = payload.lightRadiusTiles ?? existing.lightRadiusTiles ?? 0;
273 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
272 274 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
273 275 this.#placeEntity(existing);
274 276 }
@@ -555,12 +557,12 @@ export class WorldView
555 557 });
556 558 }
557 559
558 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
560 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
559 561 {
560 562 this.dynamicLights.push({
561 worldX,
562 worldY,
563 radiusTiles,
563 tileX: Math.floor(worldX),
564 tileY: Math.floor(worldY),
565 range: radiusTiles,
564 566 intensity,
565 567 until: performance.now() + durationMs
566 568 });
@@ -1228,20 +1230,22 @@ export class WorldView
1228 1230 const tileSize = this.tileSize();
1229 1231 for (const entity of this.entities.values())
1230 1232 {
1231 const radius = entity.lightRadiusTiles ?? 0;
1232 if (radius <= 0)
1233 const range = entity.lightRadiusTiles ?? 0;
1234 if (range <= 0)
1233 1235 { continue; }
1234 1236 activeLights.push({
1235 worldX: entity.visualX / tileSize,
1236 worldY: entity.visualY / tileSize,
1237 radiusTiles: radius,
1238 intensity: 0.85
1237 tileX: Math.floor(entity.visualX / tileSize),
1238 tileY: Math.floor(entity.visualY / tileSize),
1239 range,
1240 intensity: 1
1239 1241 });
1240 1242 }
1241 1243
1244 const isPassable = makeSnapshotPassable(this.chunks);
1245
1242 1246 for (const objects of this.tiles.values())
1243 1247 {
1244 const intensity = this.#tileLightIntensity(objects, activeLights);
1248 const intensity = this.#tileLightIntensity(objects, activeLights, isPassable);
1245 1249 objects.shadeAlpha = ambientDark * (1 - intensity);
1246 1250 if (objects.block)
1247 1251 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
@@ -1249,7 +1253,7 @@ export class WorldView
1249 1253
1250 1254 for (const baked of this.bakedChunks.values())
1251 1255 {
1252 this.#writeChunkLightmap(baked, activeLights);
1256 this.#writeChunkLightmap(baked, activeLights, isPassable);
1253 1257 if (baked.groundObject?.renderer?.shaderUniforms)
1254 1258 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1255 1259 for (const object of baked.blockObjects ?? [])
@@ -1266,24 +1270,19 @@ export class WorldView
1266 1270 }
1267 1271 }
1268 1272
1269 #tileLightIntensity (objects, activeLights)
1273 #tileLightIntensity (objects, activeLights, isPassable)
1270 1274 {
1271 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
1272 let dynamic = 0;
1273 for (const light of activeLights)
1274 {
1275 const dx = (objects.tileX + 0.5) - light.worldX;
1276 const dy = (objects.tileY + 0.5) - light.worldY;
1277 const dist = Math.hypot(dx, dy);
1278 if (dist >= light.radiusTiles)
1279 { continue; }
1280 const falloff = 1 - dist / light.radiusTiles;
1281 dynamic = Math.max(dynamic, falloff * light.intensity);
1282 }
1275 const baked = lightIntensity(objects.light ?? 0);
1276 const dynamic = dynamicLightAtTile(
1277 objects.tileX,
1278 objects.tileY,
1279 activeLights,
1280 isPassable
1281 );
1283 1282 return Math.max(baked, dynamic);
1284 1283 }
1285 1284
1286 #writeChunkLightmap (baked, activeLights)
1285 #writeChunkLightmap (baked, activeLights, isPassable)
1287 1286 {
1288 1287 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
1289 1288 if (!snapshot)
@@ -1304,11 +1303,13 @@ export class WorldView
1304 1303 let intensity;
1305 1304 if (tileObjects)
1306 1305 {
1307 intensity = this.#tileLightIntensity(tileObjects, activeLights);
1306 intensity = this.#tileLightIntensity(tileObjects, activeLights, isPassable);
1308 1307 }
1309 1308 else
1310 1309 {
1311 intensity = Math.min(1, Math.max(0, (snapshot.light[index] ?? 0) / 255));
1310 const baked = lightIntensity(snapshot.light[index] ?? 0);
1311 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, isPassable);
1312 intensity = Math.max(baked, dynamic);
1312 1313 }
1313 1314 const value = Math.round(Math.min(1, intensity) * 255);
1314 1315 const baseX = localX * SPRITE_SIZE_PX;
@@ -1,4 +1,6 @@
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
2import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
3import { itemSpriteName } from "/shared/definitions/items.js";
5import { itemSpriteName } from "/shared/definitions/items.js";
4import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
6import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
@@ -268,7 +270,7 @@ export class WorldView
268 const existing = this.entities.get(payload.entityId);
270 const existing = this.entities.get(payload.entityId);
269 if (!existing)
271 if (!existing)
270 { return; }
272 { return; }
271 existing.lightRadiusTiles = payload.lightRadiusTiles ?? existing.lightRadiusTiles ?? 0;
273 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
272 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
274 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
273 this.#placeEntity(existing);
275 this.#placeEntity(existing);
274 }
276 }
@@ -555,12 +557,12 @@ export class WorldView
555 });
557 });
556 }
558 }
557
559
558 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
560 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
559 {
561 {
560 this.dynamicLights.push({
562 this.dynamicLights.push({
561 worldX,
563 tileX: Math.floor(worldX),
562 worldY,
564 tileY: Math.floor(worldY),
563 radiusTiles,
565 range: radiusTiles,
564 intensity,
566 intensity,
565 until: performance.now() + durationMs
567 until: performance.now() + durationMs
566 });
568 });
@@ -1228,20 +1230,22 @@ export class WorldView
1228 const tileSize = this.tileSize();
1230 const tileSize = this.tileSize();
1229 for (const entity of this.entities.values())
1231 for (const entity of this.entities.values())
1230 {
1232 {
1231 const radius = entity.lightRadiusTiles ?? 0;
1233 const range = entity.lightRadiusTiles ?? 0;
1232 if (radius <= 0)
1234 if (range <= 0)
1233 { continue; }
1235 { continue; }
1234 activeLights.push({
1236 activeLights.push({
1235 worldX: entity.visualX / tileSize,
1237 tileX: Math.floor(entity.visualX / tileSize),
1236 worldY: entity.visualY / tileSize,
1238 tileY: Math.floor(entity.visualY / tileSize),
1237 radiusTiles: radius,
1239 range,
1238 intensity: 0.85
1240 intensity: 1
1239 });
1241 });
1240 }
1242 }
1241
1243
1244 const isPassable = makeSnapshotPassable(this.chunks);
1245
1242 for (const objects of this.tiles.values())
1246 for (const objects of this.tiles.values())
1243 {
1247 {
1244 const intensity = this.#tileLightIntensity(objects, activeLights);
1248 const intensity = this.#tileLightIntensity(objects, activeLights, isPassable);
1245 objects.shadeAlpha = ambientDark * (1 - intensity);
1249 objects.shadeAlpha = ambientDark * (1 - intensity);
1246 if (objects.block)
1250 if (objects.block)
1247 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1251 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
@@ -1249,7 +1253,7 @@ export class WorldView
1249
1253
1250 for (const baked of this.bakedChunks.values())
1254 for (const baked of this.bakedChunks.values())
1251 {
1255 {
1252 this.#writeChunkLightmap(baked, activeLights);
1256 this.#writeChunkLightmap(baked, activeLights, isPassable);
1253 if (baked.groundObject?.renderer?.shaderUniforms)
1257 if (baked.groundObject?.renderer?.shaderUniforms)
1254 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1258 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1255 for (const object of baked.blockObjects ?? [])
1259 for (const object of baked.blockObjects ?? [])
@@ -1266,24 +1270,19 @@ export class WorldView
1266 }
1270 }
1267 }
1271 }
1268
1272
1269 #tileLightIntensity (objects, activeLights)
1273 #tileLightIntensity (objects, activeLights, isPassable)
1270 {
1274 {
1271 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
1275 const baked = lightIntensity(objects.light ?? 0);
1272 let dynamic = 0;
1276 const dynamic = dynamicLightAtTile(
1273 for (const light of activeLights)
1277 objects.tileX,
1274 {
1278 objects.tileY,
1275 const dx = (objects.tileX + 0.5) - light.worldX;
1279 activeLights,
1276 const dy = (objects.tileY + 0.5) - light.worldY;
1280 isPassable
1277 const dist = Math.hypot(dx, dy);
1281 );
1278 if (dist >= light.radiusTiles)
1279 { continue; }
1280 const falloff = 1 - dist / light.radiusTiles;
1281 dynamic = Math.max(dynamic, falloff * light.intensity);
1282 }
1283 return Math.max(baked, dynamic);
1282 return Math.max(baked, dynamic);
1284 }
1283 }
1285
1284
1286 #writeChunkLightmap (baked, activeLights)
1285 #writeChunkLightmap (baked, activeLights, isPassable)
1287 {
1286 {
1288 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
1287 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
1289 if (!snapshot)
1288 if (!snapshot)
@@ -1304,11 +1303,13 @@ export class WorldView
1304 let intensity;
1303 let intensity;
1305 if (tileObjects)
1304 if (tileObjects)
1306 {
1305 {
1307 intensity = this.#tileLightIntensity(tileObjects, activeLights);
1306 intensity = this.#tileLightIntensity(tileObjects, activeLights, isPassable);
1308 }
1307 }
1309 else
1308 else
1310 {
1309 {
1311 intensity = Math.min(1, Math.max(0, (snapshot.light[index] ?? 0) / 255));
1310 const baked = lightIntensity(snapshot.light[index] ?? 0);
1311 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, isPassable);
1312 intensity = Math.max(baked, dynamic);
1312 }
1313 }
1313 const value = Math.round(Math.min(1, intensity) * 255);
1314 const value = Math.round(Math.min(1, intensity) * 255);
1314 const baseX = localX * SPRITE_SIZE_PX;
1315 const baseX = localX * SPRITE_SIZE_PX;
server/src/gateway/websocket.js +4 −2
@@ -642,7 +642,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
642 642 type: MessageType.entityAppearance,
643 643 entityId: event.entityId,
644 644 sprite: event.sprite,
645 layers: event.layers ?? []
645 layers: event.layers ?? [],
646 lightRadiusTiles: event.lightRadiusTiles ?? 0
646 647 });
647 648 continue;
648 649 }
@@ -737,7 +738,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
737 738 untargetable: !!(record.untargetable ?? event.untargetable),
738 739 freeFlight: !!(record.freeFlight ?? event.freeFlight),
739 740 health: record.health ?? event.health,
740 maxHealth: record.maxHealth ?? event.maxHealth
741 maxHealth: record.maxHealth ?? event.maxHealth,
742 lightRadiusTiles: record.lightRadiusTiles ?? event.lightRadiusTiles ?? 0
741 743 };
742 744 }
743 745
@@ -642,7 +642,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
642 type: MessageType.entityAppearance,
642 type: MessageType.entityAppearance,
643 entityId: event.entityId,
643 entityId: event.entityId,
644 sprite: event.sprite,
644 sprite: event.sprite,
645 layers: event.layers ?? []
645 layers: event.layers ?? [],
646 lightRadiusTiles: event.lightRadiusTiles ?? 0
646 });
647 });
647 continue;
648 continue;
648 }
649 }
@@ -737,7 +738,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
737 untargetable: !!(record.untargetable ?? event.untargetable),
738 untargetable: !!(record.untargetable ?? event.untargetable),
738 freeFlight: !!(record.freeFlight ?? event.freeFlight),
739 freeFlight: !!(record.freeFlight ?? event.freeFlight),
739 health: record.health ?? event.health,
740 health: record.health ?? event.health,
740 maxHealth: record.maxHealth ?? event.maxHealth
741 maxHealth: record.maxHealth ?? event.maxHealth,
742 lightRadiusTiles: record.lightRadiusTiles ?? event.lightRadiusTiles ?? 0
741 };
743 };
742 }
744 }
743
745
server/src/lighting/baker.js +2 −70
@@ -1,77 +1,9 @@
1 1 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2 import { encodeLight, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
2 3 import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
3 4 import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
4 5
5 export function bresenhamTiles (x0, y0, x1, y1)
6 {
7 const tiles = [];
8 let x = x0;
9 let y = y0;
10 const dx = Math.abs(x1 - x0);
11 const dy = Math.abs(y1 - y0);
12 const sx = x0 < x1 ? 1 : -1;
13 const sy = y0 < y1 ? 1 : -1;
14 let err = dx - dy;
15
16 while (true)
17 {
18 tiles.push({ x, y });
19 if (x === x1 && y === y1)
20 { break; }
21
22 const e2 = 2 * err;
23 if (e2 > -dy)
24 {
25 err -= dy;
26 x += sx;
27 }
28 if (e2 < dx)
29 {
30 err += dx;
31 y += sy;
32 }
33 }
34 return tiles;
35 }
36
37 export function rayReaches (fromX, fromY, toX, toY, isPassable)
38 {
39 if (fromX === toX && fromY === toY)
40 { return isPassable(toX, toY); }
41
42 const tiles = bresenhamTiles(fromX, fromY, toX, toY);
43 // Only tiles strictly between source and target can occlude. The destination
44 // may be an impassable block that still catches light on its facing surface.
45 for (let i = 1; i < tiles.length - 1; i++)
46 {
47 if (!isPassable(tiles[i].x, tiles[i].y))
48 { return false; }
49 }
50 return true;
51 }
52
53 export function falloffAtDistance (dist, range)
54 {
55 if (range <= 0 || dist > range)
56 { return 0; }
57
58 const t = 1 - dist / range;
59 return t * t * (3 - 2 * t);
60 }
61
62 export function encodeLight (dist, range)
63 {
64 const falloff = falloffAtDistance(dist, range);
65 if (falloff <= 0)
66 { return 0; }
67
68 return Math.max(1, Math.round(255 * falloff));
69 }
70
71 export function lightIntensity (encoded)
72 {
73 return Math.min(1, Math.max(0, (encoded ?? 0) / 255));
74 }
6 export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
75 7
76 8 export function maxDefinitionLightRange (blockDefs)
77 9 {
@@ -1,77 +1,9 @@
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { encodeLight, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
2import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
3import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
3import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
4import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
4
5
5export function bresenhamTiles (x0, y0, x1, y1)
6export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
6{
7 const tiles = [];
8 let x = x0;
9 let y = y0;
10 const dx = Math.abs(x1 - x0);
11 const dy = Math.abs(y1 - y0);
12 const sx = x0 < x1 ? 1 : -1;
13 const sy = y0 < y1 ? 1 : -1;
14 let err = dx - dy;
15
16 while (true)
17 {
18 tiles.push({ x, y });
19 if (x === x1 && y === y1)
20 { break; }
21
22 const e2 = 2 * err;
23 if (e2 > -dy)
24 {
25 err -= dy;
26 x += sx;
27 }
28 if (e2 < dx)
29 {
30 err += dx;
31 y += sy;
32 }
33 }
34 return tiles;
35}
36
37export function rayReaches (fromX, fromY, toX, toY, isPassable)
38{
39 if (fromX === toX && fromY === toY)
40 { return isPassable(toX, toY); }
41
42 const tiles = bresenhamTiles(fromX, fromY, toX, toY);
43 // Only tiles strictly between source and target can occlude. The destination
44 // may be an impassable block that still catches light on its facing surface.
45 for (let i = 1; i < tiles.length - 1; i++)
46 {
47 if (!isPassable(tiles[i].x, tiles[i].y))
48 { return false; }
49 }
50 return true;
51}
52
53export function falloffAtDistance (dist, range)
54{
55 if (range <= 0 || dist > range)
56 { return 0; }
57
58 const t = 1 - dist / range;
59 return t * t * (3 - 2 * t);
60}
61
62export function encodeLight (dist, range)
63{
64 const falloff = falloffAtDistance(dist, range);
65 if (falloff <= 0)
66 { return 0; }
67
68 return Math.max(1, Math.round(255 * falloff));
69}
70
71export function lightIntensity (encoded)
72{
73 return Math.min(1, Math.max(0, (encoded ?? 0) / 255));
74}
75
7
76export function maxDefinitionLightRange (blockDefs)
8export function maxDefinitionLightRange (blockDefs)
77{
9{
server/tests/lighting.test.js +11 −1
@@ -1,7 +1,8 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { createEmptyChunkData } from "../src/world/chunkData.js";
4 import { bakeLightMaps, rayReaches, bresenhamTiles } from "../src/lighting/baker.js";
4 import { bakeLightMaps } from "../src/lighting/baker.js";
5 import { bresenhamTiles, dynamicLightAtTile, rayReaches } from "../../shared/lighting/raycast.js";
5 6 import { BlockType } from "../../shared/definitions/tiles.js";
6 7 import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
7 8
@@ -45,3 +46,12 @@ test("a torch lights passable tiles, facing walls, and not tiles behind walls",
45 46 assert.equal(self.light[3], 0, "tile behind wall is unlit");
46 47 assert.equal(self.light.length, CHUNK_SIZE * CHUNK_SIZE);
47 48 });
49
50 test("dynamic lights use the same wall occlusion as baked light", () =>
51 {
52 const blocked = (x, y) => !(x === 1 && y === 0);
53 const sources = [{ tileX: 0, tileY: 0, range: 8, intensity: 1 }];
54 assert.equal(dynamicLightAtTile(2, 0, sources, blocked), 0);
55 assert.ok(dynamicLightAtTile(1, 0, sources, () => true) > 0);
56 assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0);
57 });
@@ -1,7 +1,8 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { createEmptyChunkData } from "../src/world/chunkData.js";
3import { createEmptyChunkData } from "../src/world/chunkData.js";
4import { bakeLightMaps, rayReaches, bresenhamTiles } from "../src/lighting/baker.js";
4import { bakeLightMaps } from "../src/lighting/baker.js";
5import { bresenhamTiles, dynamicLightAtTile, rayReaches } from "../../shared/lighting/raycast.js";
5import { BlockType } from "../../shared/definitions/tiles.js";
6import { BlockType } from "../../shared/definitions/tiles.js";
6import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
7import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
7
8
@@ -45,3 +46,12 @@ test("a torch lights passable tiles, facing walls, and not tiles behind walls",
45 assert.equal(self.light[3], 0, "tile behind wall is unlit");
46 assert.equal(self.light[3], 0, "tile behind wall is unlit");
46 assert.equal(self.light.length, CHUNK_SIZE * CHUNK_SIZE);
47 assert.equal(self.light.length, CHUNK_SIZE * CHUNK_SIZE);
47});
48});
49
50test("dynamic lights use the same wall occlusion as baked light", () =>
51{
52 const blocked = (x, y) => !(x === 1 && y === 0);
53 const sources = [{ tileX: 0, tileY: 0, range: 8, intensity: 1 }];
54 assert.equal(dynamicLightAtTile(2, 0, sources, blocked), 0);
55 assert.ok(dynamicLightAtTile(1, 0, sources, () => true) > 0);
56 assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0);
57});
shared/lighting/raycast.js added +88 −0
@@ -0,0 +1,88 @@
1 /** Shared lighting raycast and falloff — used by server bake and client dynamic lights. */
2
3 export function bresenhamTiles (x0, y0, x1, y1)
4 {
5 const tiles = [];
6 let x = x0;
7 let y = y0;
8 const dx = Math.abs(x1 - x0);
9 const dy = Math.abs(y1 - y0);
10 const sx = x0 < x1 ? 1 : -1;
11 const sy = y0 < y1 ? 1 : -1;
12 let err = dx - dy;
13
14 while (true)
15 {
16 tiles.push({ x, y });
17 if (x === x1 && y === y1)
18 { break; }
19
20 const e2 = 2 * err;
21 if (e2 > -dy)
22 {
23 err -= dy;
24 x += sx;
25 }
26 if (e2 < dx)
27 {
28 err += dx;
29 y += sy;
30 }
31 }
32 return tiles;
33 }
34
35 export function rayReaches (fromX, fromY, toX, toY, isPassable)
36 {
37 if (fromX === toX && fromY === toY)
38 { return isPassable(toX, toY); }
39
40 const tiles = bresenhamTiles(fromX, fromY, toX, toY);
41 // Only tiles strictly between source and target can occlude. The destination
42 // may be an impassable block that still catches light on its facing surface.
43 for (let i = 1; i < tiles.length - 1; i++)
44 {
45 if (!isPassable(tiles[i].x, tiles[i].y))
46 { return false; }
47 }
48 return true;
49 }
50
51 export function falloffAtDistance (dist, range)
52 {
53 if (range <= 0 || dist > range)
54 { return 0; }
55
56 const t = 1 - dist / range;
57 return t * t * (3 - 2 * t);
58 }
59
60 export function encodeLight (dist, range)
61 {
62 const falloff = falloffAtDistance(dist, range);
63 if (falloff <= 0)
64 { return 0; }
65
66 return Math.max(1, Math.round(255 * falloff));
67 }
68
69 export function lightIntensity (encoded)
70 {
71 return Math.min(1, Math.max(0, (encoded ?? 0) / 255));
72 }
73
74 /** Sum dynamic light sources at an integer tile (0–1), matching baked light rules. */
75 export function dynamicLightAtTile (tileX, tileY, sources, isPassable)
76 {
77 let best = 0;
78 for (const source of sources)
79 {
80 const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY);
81 if (dist > source.range)
82 { continue; }
83 if (!rayReaches(source.tileX, source.tileY, tileX, tileY, isPassable))
84 { continue; }
85 best = Math.max(best, falloffAtDistance(dist, source.range) * (source.intensity ?? 1));
86 }
87 return best;
88 }
@@ -0,0 +1,88 @@
1/** Shared lighting raycast and falloff — used by server bake and client dynamic lights. */
2
3export function bresenhamTiles (x0, y0, x1, y1)
4{
5 const tiles = [];
6 let x = x0;
7 let y = y0;
8 const dx = Math.abs(x1 - x0);
9 const dy = Math.abs(y1 - y0);
10 const sx = x0 < x1 ? 1 : -1;
11 const sy = y0 < y1 ? 1 : -1;
12 let err = dx - dy;
13
14 while (true)
15 {
16 tiles.push({ x, y });
17 if (x === x1 && y === y1)
18 { break; }
19
20 const e2 = 2 * err;
21 if (e2 > -dy)
22 {
23 err -= dy;
24 x += sx;
25 }
26 if (e2 < dx)
27 {
28 err += dx;
29 y += sy;
30 }
31 }
32 return tiles;
33}
34
35export function rayReaches (fromX, fromY, toX, toY, isPassable)
36{
37 if (fromX === toX && fromY === toY)
38 { return isPassable(toX, toY); }
39
40 const tiles = bresenhamTiles(fromX, fromY, toX, toY);
41 // Only tiles strictly between source and target can occlude. The destination
42 // may be an impassable block that still catches light on its facing surface.
43 for (let i = 1; i < tiles.length - 1; i++)
44 {
45 if (!isPassable(tiles[i].x, tiles[i].y))
46 { return false; }
47 }
48 return true;
49}
50
51export function falloffAtDistance (dist, range)
52{
53 if (range <= 0 || dist > range)
54 { return 0; }
55
56 const t = 1 - dist / range;
57 return t * t * (3 - 2 * t);
58}
59
60export function encodeLight (dist, range)
61{
62 const falloff = falloffAtDistance(dist, range);
63 if (falloff <= 0)
64 { return 0; }
65
66 return Math.max(1, Math.round(255 * falloff));
67}
68
69export function lightIntensity (encoded)
70{
71 return Math.min(1, Math.max(0, (encoded ?? 0) / 255));
72}
73
74/** Sum dynamic light sources at an integer tile (0–1), matching baked light rules. */
75export function dynamicLightAtTile (tileX, tileY, sources, isPassable)
76{
77 let best = 0;
78 for (const source of sources)
79 {
80 const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY);
81 if (dist > source.range)
82 { continue; }
83 if (!rayReaches(source.tileX, source.tileY, tileX, tileY, isPassable))
84 { continue; }
85 best = Math.max(best, falloffAtDistance(dist, source.range) * (source.intensity ?? 1));
86 }
87 return best;
88}
shared/lighting/tilePassable.js added +20 −0
@@ -0,0 +1,20 @@
1 import { CHUNK_SIZE } from "../protocol/constants.js";
2 import { isBlockPassable } from "../definitions/tiles.js";
3
4 /** Passability from a chunk snapshot map keyed by "chunkX,chunkY". */
5 export function makeSnapshotPassable (chunks)
6 {
7 return (tileX, tileY) =>
8 {
9 const chunkX = Math.floor(tileX / CHUNK_SIZE);
10 const chunkY = Math.floor(tileY / CHUNK_SIZE);
11 const snapshot = chunks.get(`${chunkX},${chunkY}`);
12 if (!snapshot)
13 { return true; }
14 const localX = tileX - chunkX * CHUNK_SIZE;
15 const localY = tileY - chunkY * CHUNK_SIZE;
16 const index = localY * CHUNK_SIZE + localX;
17 const block = snapshot.blocks?.[index];
18 return isBlockPassable(block?.typeId ?? null);
19 };
20 }
@@ -0,0 +1,20 @@
1import { CHUNK_SIZE } from "../protocol/constants.js";
2import { isBlockPassable } from "../definitions/tiles.js";
3
4/** Passability from a chunk snapshot map keyed by "chunkX,chunkY". */
5export function makeSnapshotPassable (chunks)
6{
7 return (tileX, tileY) =>
8 {
9 const chunkX = Math.floor(tileX / CHUNK_SIZE);
10 const chunkY = Math.floor(tileY / CHUNK_SIZE);
11 const snapshot = chunks.get(`${chunkX},${chunkY}`);
12 if (!snapshot)
13 { return true; }
14 const localX = tileX - chunkX * CHUNK_SIZE;
15 const localY = tileY - chunkY * CHUNK_SIZE;
16 const index = localY * CHUNK_SIZE + localX;
17 const block = snapshot.blocks?.[index];
18 return isBlockPassable(block?.typeId ?? null);
19 };
20}