BlueGit

timfa questward

Files

questward / shared / lighting / raycast.js

raycast.js

raycast.js 2.0 KiB Download Raw
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}