BlueGit

timfa raytracer

Files

raytracer / src / lighting.js

lighting.js

lighting.js 8.3 KiB Download Raw
1/**
2 * Point lights for the raycaster (CPU).
3 * Walls/floor/ceiling: Lambertian N·L + distance falloff; walls also grid LOS.
4 * Paperdolls: view-space normals from .ppda (RGB = n*0.5+0.5, view=+Z) with L
5 * transformed into the chosen yaw view; Half-Lambert so side lights still
6 * reach front-facing atlas normals, plus a slight geometric X tilt from u.
7 *
8 * Floor/ceiling skip grid LOS: tile Bresenham casts hard vertical shadow
9 * seams in screen space; distance falloff is enough there. Walls keep LOS
10 * with the sample nudged into open space so the hit cell is not a blocker.
11 */
12var Lighting =
13{
14 DEFAULT_AMBIENT: 0.38,
15 MAX_LIGHTS: 32,
16
17 normalize3: function (x, y, z)
18 {
19 var len = Math.sqrt(x * x + y * y + z * z);
20 if (len < 1e-8)
21 { return { x: 0, y: 0, z: 1 }; }
22 return { x: x / len, y: y / len, z: z / len };
23 },
24
25 decodeNormalRgb: function (r, g, b)
26 {
27 return this.normalize3(
28 r / 255 * 2 - 1,
29 g / 255 * 2 - 1,
30 b / 255 * 2 - 1
31 );
32 },
33
34 /** intensity * saturate(1 - dist/range)^falloff */
35 attenuation: function (dist, range, falloff)
36 {
37 if (range <= 0)
38 { return 0; }
39 var t = 1 - dist / range;
40 if (t <= 0)
41 { return 0; }
42 var f = falloff == null ? 2 : falloff;
43 if (f === 1)
44 { return t; }
45 if (f === 2)
46 { return t * t; }
47 return Math.pow(t, f);
48 },
49
50 /**
51 * Outward normal of the visible wall face.
52 * Raycaster `dir` = travel direction of the casting ray when it hit:
53 * "west" → ray went east, visible face is the west face → normal (-1,0,0)
54 * "east" → ray went west, visible face is the east face → normal (+1,0,0)
55 * "north" → ray went north (−Y), visible face is the south face → (+Y)
56 * "south" → ray went south (+Y), visible face is the north face → (−Y)
57 */
58 faceNormal: function (dir)
59 {
60 switch (dir)
61 {
62 case "north": return { x: 0, y: 1, z: 0 };
63 case "south": return { x: 0, y: -1, z: 0 };
64 case "east": return { x: 1, y: 0, z: 0 };
65 case "west": return { x: -1, y: 0, z: 0 };
66 case "floor": return { x: 0, y: 0, z: 1 };
67 case "ceiling": return { x: 0, y: 0, z: -1 };
68 default: return { x: 0, y: 0, z: 1 };
69 }
70 },
71
72 /**
73 * Grid LOS (Bresenham). Skips start+end tiles. Optional corner check so
74 * diagonal steps cannot slip through a wall corner unnoticed.
75 */
76 hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
77 {
78 cellSize = cellSize || 32;
79 var tx0 = Math.floor(x0 / cellSize);
80 var ty0 = Math.floor(y0 / cellSize);
81 var tx1 = Math.floor(x1 / cellSize);
82 var ty1 = Math.floor(y1 / cellSize);
83 if (tx0 === tx1 && ty0 === ty1)
84 { return true; }
85 var dx = Math.abs(tx1 - tx0);
86 var dy = Math.abs(ty1 - ty0);
87 var sx = tx0 < tx1 ? 1 : -1;
88 var sy = ty0 < ty1 ? 1 : -1;
89 var err = dx - dy;
90 var x = tx0;
91 var y = ty0;
92 var steps = 0;
93 var maxSteps = dx + dy + 2;
94 while (steps < maxSteps)
95 {
96 steps++;
97 var e2 = 2 * err;
98 var movedX = false, movedY = false;
99 if (e2 > -dy) { err -= dy; x += sx; movedX = true; }
100 if (e2 < dx) { err += dx; y += sy; movedY = true; }
101 if (x === tx1 && y === ty1)
102 { return true; }
103 if (x < 0 || y < 0 || x >= mapW || y >= mapH)
104 { return false; }
105 var id = tiles[x + y * mapW];
106 if (id === 1 || id === 3)
107 { return false; }
108 // Diagonal: also block if cutting a corner through a solid.
109 if (movedX && movedY)
110 {
111 var a = tiles[(x - sx) + y * mapW];
112 var b = tiles[x + (y - sy) * mapW];
113 if ((a === 1 || a === 3) && (b === 1 || b === 3))
114 { return false; }
115 }
116 }
117 return true;
118 },
119
120 /**
121 * RGB multipliers. los: {tiles,width,height,cellSize} or null.
122 * For walls pass sample already nudged into open space along the outward normal.
123 */
124 shadeRgb: function (pos, normal, lights, ambient, los)
125 {
126 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
127 var r = ambient;
128 var g = ambient;
129 var b = ambient;
130 if (!lights || !lights.length)
131 { return { r: r, g: g, b: b }; }
132 var n = Math.min(lights.length, this.MAX_LIGHTS);
133 for (var i = 0; i < n; i++)
134 {
135 var L = lights[i];
136 var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;
137 var dx = lx - pos.x;
138 var dy = ly - pos.y;
139 var dz = lz - pos.z;
140 var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
141 var att = this.attenuation(dist, L.range || 64, L.falloff);
142 if (att <= 0.001)
143 { continue; }
144 if (los && !this.hasLineOfSight(lx, ly, pos.x, pos.y, los.tiles, los.width, los.height, los.cellSize))
145 { continue; }
146 var ld = this.normalize3(dx, dy, dz);
147 var ndotl = normal.x * ld.x + normal.y * ld.y + normal.z * ld.z;
148 if (ndotl <= 0)
149 { continue; }
150 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
151 var cr = L.color ? L.color[0] : 1;
152 var cg = L.color ? L.color[1] : 1;
153 var cb = L.color ? L.color[2] : 1;
154 r += inten * cr;
155 g += inten * cg;
156 b += inten * cb;
157 }
158 return { r: r, g: g, b: b };
159 },
160
161 /**
162 * World direction (toward light) → paperdoll view space for yawDeg.
163 * Yaw 0: camera on character +Z (front); view +Z toward camera, +Y up,
164 * +X = camera right = character right at yaw 0.
165 */
166 worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
167 {
168 var face = (facingDeg || 0) * Math.PI / 180;
169 var yaw = (yawDeg || 0) * Math.PI / 180;
170 var frontX = Math.cos(face);
171 var frontY = Math.sin(face);
172 var rightX = -Math.sin(face);
173 var rightY = Math.cos(face);
174 // Camera offset in character space: yaw 0 → +Z (front)
175 var camCX = Math.sin(yaw);
176 var camCZ = Math.cos(yaw);
177 var camX = rightX * camCX + frontX * camCZ;
178 var camY = rightY * camCX + frontY * camCZ;
179 // viewZ = toward camera (in XY), viewY = up, viewX = cross(viewY, viewZ)
180 var viewXx = -camY;
181 var viewXy = camX;
182 var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
183 if (vlen > 1e-8)
184 { viewXx /= vlen; viewXy /= vlen; }
185 return this.normalize3(
186 dirX * viewXx + dirY * viewXy,
187 dirZ,
188 dirX * camX + dirY * camY
189 );
190 },
191
192 /**
193 * Half-Lambert wrap so front-facing atlas normals still receive side light;
194 * geoTiltX nudges the normal toward the billboard side (u 0..1 → -1..+1).
195 */
196 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg, geoTiltX)
197 {
198 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
199 var n = this.decodeNormalRgb(nr, ng, nb);
200 if (geoTiltX)
201 {
202 n = this.normalize3(n.x + geoTiltX * 0.85, n.y, n.z + 0.15);
203 }
204 var r = ambient * albedoR;
205 var g = ambient * albedoG;
206 var b = ambient * albedoB;
207 if (!lights || !lights.length)
208 {
209 var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);
210 var shade = Math.min(1, 0.35 + 0.65 * nd);
211 return {
212 r: Math.min(255, Math.round(albedoR * shade)),
213 g: Math.min(255, Math.round(albedoG * shade)),
214 b: Math.min(255, Math.round(albedoB * shade))
215 };
216 }
217 var count = Math.min(lights.length, this.MAX_LIGHTS);
218 for (var i = 0; i < count; i++)
219 {
220 var L = lights[i];
221 var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;
222 var dx = lx - pixelWorld.x;
223 var dy = ly - pixelWorld.y;
224 var dz = lz - pixelWorld.z;
225 var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
226 var att = this.attenuation(dist, L.range || 64, L.falloff);
227 if (att <= 0.001)
228 { continue; }
229 var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);
230 var raw = n.x * lv.x + n.y * lv.y + n.z * lv.z;
231 // Half-Lambert: side lights still reach front-facing .ppda normals.
232 var ndotl = raw * 0.5 + 0.5;
233 if (ndotl <= 0.02)
234 { continue; }
235 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
236 var cr = L.color ? L.color[0] : 1;
237 var cg = L.color ? L.color[1] : 1;
238 var cb = L.color ? L.color[2] : 1;
239 r += albedoR * inten * cr;
240 g += albedoG * inten * cg;
241 b += albedoB * inten * cb;
242 }
243 return {
244 r: Math.min(255, Math.round(r)),
245 g: Math.min(255, Math.round(g)),
246 b: Math.min(255, Math.round(b))
247 };
248 },
249
250 legacyFaceShade: function (dir)
251 {
252 switch (dir)
253 {
254 case "east": return 0.9;
255 case "west": return 0.8;
256 case "south": return 0.7;
257 default: return 1.0;
258 }
259 },
260
261 /** Max |Δ| between consecutive column means in a row range (for seam tests). */
262 maxColumnJump: function (getColumnMean, width)
263 {
264 var best = 0;
265 var prev = getColumnMean(0);
266 for (var x = 1; x < width; x++)
267 {
268 var v = getColumnMean(x);
269 var d = Math.abs(v - prev);
270 if (d > best)
271 { best = d; }
272 prev = v;
273 }
274 return best;
275 }
276};
277
278if (typeof module !== "undefined" && module.exports)
279{ module.exports = Lighting; }