BlueGit

timfa raytracer

Files

raytracer / build / game.js

game.js

game.js 89.9 KiB Download Raw
1
2/*
3 * Start File:
4 * /workspace/raytracer-work/src/textureColumn.js
5 */
6/**
7 * Texture-column helpers for Wolfenstein-style wall strips.
8 * Each screen column samples exactly one source pixel column.
9 */
10function textureColumnIndex (tileX, texWidth)
11{
12 if (!(texWidth > 0))
13 { return 0; }
14
15 var sx = Math.floor(Number(tileX) * texWidth);
16 if (sx < 0)
17 { sx = 0; }
18 if (sx > texWidth - 1)
19 { sx = texWidth - 1; }
20 return sx;
21}
22
23function textureColumnUv (tileX, texWidth)
24{
25 var sx = textureColumnIndex(tileX, texWidth);
26 var w = texWidth > 0 ? texWidth : 1;
27 return {
28 sx: sx,
29 sw: 1,
30 u0: sx / w,
31 u1: (sx + 1) / w,
32 v0: 0,
33 v1: 1
34 };
35}
36
37/** Face U from hit position within a cell (no +1 bias). */
38function faceTileX (hitCoord, cellSize, face)
39{
40 var local = hitCoord % cellSize;
41 if (local < 0)
42 { local += cellSize; }
43 var t = local / cellSize;
44 switch (face)
45 {
46 case "north": return t;
47 case "south": return 1 - t;
48 case "east": return 1 - t;
49 case "west": return t;
50 default: return t;
51 }
52}
53
54if (typeof module !== "undefined" && module.exports)
55{
56 module.exports = {
57 textureColumnIndex: textureColumnIndex,
58 textureColumnUv: textureColumnUv,
59 faceTileX: faceTileX
60 };
61}
62
63/*
64 * End File:
65 * /workspace/raytracer-work/src/textureColumn.js
66 */
67
68/*
69 * Start File:
70 * /workspace/raytracer-work/src/ppda/depthDecode.js
71 */
72/**
73 * Depth encodings matching Paperdoll Renderer camera::DepthFormat.
74 * Canonical compositor sample is u16 gray + u16 alpha (0..65535).
75 */
76var DepthDecode =
77{
78 EPSILON_U16: 1,
79
80 parseFormat: function (encoding, bits)
81 {
82 var enc = encoding || "gray";
83 var b = bits == null ? 16 : Number(bits);
84 if (b !== 8 && b !== 16)
85 { throw new Error("depth_bits moet 8 of 16 zijn, kreeg " + bits); }
86 if (enc !== "gray" && enc !== "rgb_bands" && enc !== "rgb_packed")
87 { throw new Error("depth_encoding onbekend: " + enc); }
88 return { encoding: enc, bits: b };
89 },
90
91 max: function (fmt)
92 { return (1 << fmt.bits) - 1; },
93
94 levels: function (fmt)
95 {
96 var m = this.max(fmt);
97 if (fmt.encoding === "gray")
98 { return m; }
99 if (fmt.encoding === "rgb_bands")
100 { return 3 * m; }
101 return Math.pow(2, 3 * fmt.bits) - 1;
102 },
103
104 decodeValue: function (fmt, c0, c1, c2)
105 {
106 var m = this.max(fmt);
107 var b = m + 1;
108 var v;
109 if (fmt.encoding === "gray")
110 { v = c0; }
111 else if (fmt.encoding === "rgb_bands")
112 { v = c0 + c1 + c2; }
113 else
114 { v = c0 * b * b + c1 * b + c2; }
115 return v / this.levels(fmt);
116 },
117
118 encodeValue: function (fmt, t)
119 {
120 t = Math.max(0, Math.min(1, Number(t) || 0));
121 var m = this.max(fmt);
122 var v = Math.round(t * this.levels(fmt));
123 if (fmt.encoding === "gray")
124 { return [v, 0, 0]; }
125 if (fmt.encoding === "rgb_bands")
126 {
127 return [
128 Math.min(v, m),
129 Math.min(Math.max(v - m, 0), m),
130 Math.min(Math.max(v - 2 * m, 0), m)
131 ];
132 }
133 var b = m + 1;
134 return [Math.floor(v / (b * b)), Math.floor(v / b) % b, v % b];
135 },
136
137 /**
138 * Decode one pixel channel tuple to canonical u16 (gray, alpha).
139 * channels: [c0,c1,c2,a] in native bit depth units.
140 */
141 decodePixelChannels: function (fmt, channels)
142 {
143 var c0 = channels[0] || 0;
144 var c1 = channels[1] || 0;
145 var c2 = channels[2] || 0;
146 var a = channels[3] != null ? channels[3] : this.max(fmt);
147 if (fmt.encoding === "rgb_bands")
148 {
149 var m = this.max(fmt);
150 if ((c1 > 0 && c0 !== m) || (c2 > 0 && c1 !== m))
151 { throw new Error("depth rgb_bands: ongeldige bandvolgorde"); }
152 }
153 var t = this.decodeValue(fmt, c0, c1, c2);
154 var scale = 65535 / this.max(fmt);
155 return {
156 gray: Math.round(t * 65535),
157 alpha: Math.round(a * scale)
158 };
159 },
160
161 /** Meters from camera using near/far and normalized t (0..1 from gray/65535). */
162 distanceMeters: function (grayU16, near, far)
163 {
164 var t = (grayU16 & 0xffff) / 65535;
165 return near + t * (far - near);
166 }
167};
168
169if (typeof module !== "undefined" && module.exports)
170{ module.exports = DepthDecode; }
171
172/*
173 * End File:
174 * /workspace/raytracer-work/src/ppda/depthDecode.js
175 */
176
177/*
178 * Start File:
179 * /workspace/raytracer-work/src/ppda/viewFrame.js
180 */
181/**
182 * Choose paperdoll view (yaw/pitch) and animation frame.
183 * Yaw 0 = character front (Paperdoll/glTF convention).
184 */
185var PpdaViewFrame =
186{
187 /**
188 * Relative viewing yaw in degrees [0,360): direction from NPC to player,
189 * minus the NPC's facing yaw (degrees, 0 = faces +X/east in world… mapped
190 * so that when the player looks at the NPC's front, relative yaw ≈ 0).
191 *
192 * World: +X east, +Y south (legacy raycaster). NPC facingYawDeg: 0 looks
193 * toward +X. Paperdoll yaw 0 is front. We map world facing so that the
194 * camera looking opposite to facing sees front.
195 */
196 relativeYawDeg: function (playerX, playerY, npcX, npcY, npcFacingDeg)
197 {
198 var dx = playerX - npcX;
199 var dy = playerY - npcY;
200 // Angle of vector NPC→player in world degrees (0=+X, 90=+Y).
201 var toPlayer = Math.atan2(dy, dx) * 180 / Math.PI;
202 if (toPlayer < 0)
203 { toPlayer += 360; }
204 // When player stands in front of NPC, toPlayer ≈ npcFacing → rel 0.
205 // Yaw 90 = model LEFT. Walking around counterclockwise (front→NPC left
206 // →back) must yield 0→90→180. That is facing - toPlayer (not the reverse,
207 // which mirrored left/right).
208 var rel = (npcFacingDeg || 0) - toPlayer;
209 rel = ((rel % 360) + 360) % 360;
210 return rel;
211 },
212
213 nearestInList: function (value, list, circular360)
214 {
215 if (!list || !list.length)
216 { return 0; }
217 var best = list[0];
218 var bestD = Infinity;
219 for (var i = 0; i < list.length; i++)
220 {
221 var v = list[i];
222 var d = Math.abs(value - v);
223 if (circular360)
224 { d = Math.min(d, 360 - d); }
225 if (d < bestD)
226 {
227 bestD = d;
228 best = v;
229 }
230 }
231 return best;
232 },
233
234 pickYaw: function (relativeYawDeg, yaws)
235 {
236 return this.nearestInList(((relativeYawDeg % 360) + 360) % 360, yaws || [0], true);
237 },
238
239 pickPitch: function (playerPitchRad, pitches)
240 {
241 // Legacy: map look-pitch. Prefer pickPitchFromHeight for billboards so
242 // looking up/down does not tilt the NPC atlas.
243 var deg = -(playerPitchRad || 0) * 180 / Math.PI;
244 return this.nearestInList(deg, pitches || [0]);
245 },
246
247 /**
248 * Atlas pitch from height difference only (not player look pitch).
249 * playerEyeZ / npcCenterZ in world units; dist = horizontal distance.
250 * Paperdoll: positive pitch = viewed from above.
251 */
252 pickPitchFromHeight: function (playerEyeZ, npcCenterZ, horizDist, pitches)
253 {
254 var d = Math.max(0.01, horizDist || 0.01);
255 // Positive paperdoll pitch = from above → when NPC is lower than the eye.
256 var deg = Math.atan2((playerEyeZ || 0) - (npcCenterZ || 0), d) * 180 / Math.PI;
257 return this.nearestInList(deg, pitches || [0]);
258 },
259
260 frameIndex: function (timeSec, fps, frameCount)
261 {
262 var n = Math.max(1, frameCount | 0);
263 var f = Math.max(1, fps | 0);
264 var idx = Math.floor((timeSec || 0) * f);
265 idx %= n;
266 if (idx < 0)
267 { idx += n; }
268 return idx;
269 },
270
271 findClip: function (ppda, clipTokenOrName)
272 {
273 var clips = ppda && ppda.clips || [];
274 for (var i = 0; i < clips.length; i++)
275 {
276 if (clips[i].token === clipTokenOrName || clips[i].name === clipTokenOrName)
277 { return clips[i]; }
278 }
279 return clips[0] || null;
280 },
281
282 findView: function (frame, pitch, yaw)
283 {
284 var views = frame && frame.views || [];
285 for (var i = 0; i < views.length; i++)
286 {
287 if (views[i].pitch === pitch && views[i].yaw === yaw)
288 { return views[i]; }
289 }
290 return null;
291 },
292
293 uvRect: function (view, atlasW, atlasH)
294 {
295 if (!view)
296 { return { u0: 0, v0: 0, u1: 1, v1: 1, x: 0, y: 0, w: 0, h: 0 }; }
297 var w = atlasW || 1;
298 var h = atlasH || 1;
299 return {
300 x: view.x,
301 y: view.y,
302 w: view.w,
303 h: view.h,
304 u0: view.x / w,
305 v0: view.y / h,
306 u1: (view.x + view.w) / w,
307 v1: (view.y + view.h) / h
308 };
309 }
310};
311
312if (typeof module !== "undefined" && module.exports)
313{ module.exports = PpdaViewFrame; }
314
315/*
316 * End File:
317 * /workspace/raytracer-work/src/ppda/viewFrame.js
318 */
319
320/*
321 * Start File:
322 * /workspace/raytracer-work/src/ppda/compositor.js
323 */
324/**
325 * Live body+equipment compositor — port of compositor.rs compose().
326 * Per pixel: nearest valid depth wins; ties keep lower layer index (body first).
327 * Valid = depth alpha ≠ 0 AND diffuse alpha ≠ 0.
328 */
329var PpdaCompositor =
330{
331 DEPTH_EPSILON_U16: 1,
332
333 /**
334 * @param {Array<{width,height,diffuse:Uint8ClampedArray|Uint8Array,depthGray:Uint16Array,depthAlpha:Uint16Array,normal?:Uint8Array,specular?:Uint8Array}>} layers
335 */
336 compose: function (layers)
337 {
338 if (!layers || !layers.length)
339 { throw new Error("geen lagen om te composeren"); }
340 var width = layers[0].width;
341 var height = layers[0].height;
342 var pixels = width * height;
343 if (!pixels)
344 { throw new Error("lege afmetingen"); }
345 for (var li = 0; li < layers.length; li++)
346 {
347 var L = layers[li];
348 if (L.width !== width || L.height !== height)
349 { throw new Error("laag " + li + " heeft andere afmetingen"); }
350 if (L.diffuse.length !== pixels * 4 || L.depthGray.length !== pixels || L.depthAlpha.length !== pixels)
351 { throw new Error("laag " + li + " inconsistente buffers"); }
352 }
353
354 var diffuse = new Uint8ClampedArray(pixels * 4);
355 var normal = new Uint8ClampedArray(pixels * 4);
356 var specular = new Uint8ClampedArray(pixels * 4);
357 var depthGray = new Uint16Array(pixels);
358 var depthAlpha = new Uint16Array(pixels);
359 var winner = new Uint8Array(pixels);
360 for (var i = 0; i < pixels; i++)
361 { winner[i] = 255; }
362
363 var eps = this.DEPTH_EPSILON_U16;
364 for (var i = 0; i < pixels; i++)
365 {
366 var bestDepth = null;
367 var bestLayer = null;
368 for (var layerIdx = 0; layerIdx < layers.length; layerIdx++)
369 {
370 var layer = layers[layerIdx];
371 if (layer.depthAlpha[i] === 0 || layer.diffuse[i * 4 + 3] === 0)
372 { continue; }
373 var gray = layer.depthGray[i];
374 if (bestDepth == null)
375 {
376 bestDepth = gray;
377 bestLayer = layerIdx;
378 }
379 else if (gray + eps < bestDepth)
380 {
381 bestDepth = gray;
382 bestLayer = layerIdx;
383 }
384 else if (gray <= bestDepth + eps)
385 {
386 /* tie: keep lower index */
387 }
388 }
389 if (bestLayer != null)
390 {
391 var src = layers[bestLayer];
392 var o = i * 4;
393 diffuse[o] = src.diffuse[o];
394 diffuse[o + 1] = src.diffuse[o + 1];
395 diffuse[o + 2] = src.diffuse[o + 2];
396 diffuse[o + 3] = src.diffuse[o + 3];
397 if (src.normal)
398 {
399 normal[o] = src.normal[o];
400 normal[o + 1] = src.normal[o + 1];
401 normal[o + 2] = src.normal[o + 2];
402 normal[o + 3] = src.normal[o + 3];
403 }
404 if (src.specular)
405 {
406 specular[o] = src.specular[o];
407 specular[o + 1] = src.specular[o + 1];
408 specular[o + 2] = src.specular[o + 2];
409 specular[o + 3] = src.specular[o + 3];
410 }
411 depthGray[i] = src.depthGray[i];
412 depthAlpha[i] = src.depthAlpha[i];
413 winner[i] = bestLayer;
414 }
415 }
416
417 return {
418 width: width,
419 height: height,
420 diffuse: diffuse,
421 normal: normal,
422 specular: specular,
423 depthGray: depthGray,
424 depthAlpha: depthAlpha,
425 winner: winner
426 };
427 },
428
429 /** Simple ambient+Lambert approx for preview (Preview2d-achtig, licht). */
430 relightDiffuse: function (composed, lightAmt)
431 {
432 lightAmt = lightAmt == null ? 1 : lightAmt;
433 var out = new Uint8ClampedArray(composed.diffuse.length);
434 for (var i = 0; i < composed.diffuse.length; i += 4)
435 {
436 var a = composed.diffuse[i + 3];
437 if (a === 0)
438 { continue; }
439 var ndot = 0.75;
440 if (composed.normal && composed.normal[i + 3])
441 {
442 var nx = composed.normal[i] / 255 * 2 - 1;
443 var ny = composed.normal[i + 1] / 255 * 2 - 1;
444 var nz = composed.normal[i + 2] / 255 * 2 - 1;
445 ndot = Math.max(0, nx * 0.3 + ny * 0.2 + nz * 0.9);
446 }
447 var shade = Math.min(1, 0.35 + 0.65 * ndot) * lightAmt;
448 out[i] = Math.min(255, Math.round(composed.diffuse[i] * shade));
449 out[i + 1] = Math.min(255, Math.round(composed.diffuse[i + 1] * shade));
450 out[i + 2] = Math.min(255, Math.round(composed.diffuse[i + 2] * shade));
451 out[i + 3] = a;
452 }
453 return out;
454 }
455};
456
457if (typeof module !== "undefined" && module.exports)
458{ module.exports = PpdaCompositor; }
459
460/*
461 * End File:
462 * /workspace/raytracer-work/src/ppda/compositor.js
463 */
464
465/*
466 * Start File:
467 * /workspace/raytracer-work/src/ppda/loadPpda.js
468 */
469/**
470 * Strict-enough .ppda loader for formats 1–5 (Paperdoll AtlasSet consumer).
471 */
472var PpdaLoader =
473{
474 SUPPORTED_FORMATS: [1, 2, 3, 4, 5],
475
476 parse: function (jsonText, options)
477 {
478 options = options || {};
479 var doc;
480 try
481 { doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; }
482 catch (e)
483 { throw new Error("ppda: ongeldige JSON (" + e.message + ")"); }
484
485 if (!doc || typeof doc !== "object")
486 { throw new Error("ppda: root moet een object zijn"); }
487
488 var ver = doc.format_version;
489 if (this.SUPPORTED_FORMATS.indexOf(ver) < 0)
490 { throw new Error("ppda: format_version " + ver + " niet ondersteund (wel: " + this.SUPPORTED_FORMATS.join(",") + ")"); }
491
492 if (!doc.sex || !doc.settype)
493 { throw new Error("ppda: sex/settype verplicht"); }
494 if (!doc.fps || doc.fps < 1)
495 { throw new Error("ppda: fps ongeldig"); }
496 if (!doc.cell_width || !doc.cell_height)
497 { throw new Error("ppda: cell_width/height verplicht"); }
498 if (!Array.isArray(doc.pitches) || !Array.isArray(doc.yaws) || !doc.pitches.length || !doc.yaws.length)
499 { throw new Error("ppda: pitches/yaws verplicht"); }
500 if (!doc.maps || typeof doc.maps !== "object")
501 { throw new Error("ppda: maps verplicht"); }
502 ["diffuse", "depth"].forEach(function (k)
503 {
504 if (!doc.maps[k] || !doc.maps[k].file)
505 { throw new Error("ppda: maps." + k + ".file verplicht"); }
506 if (String(doc.maps[k].file).indexOf("..") >= 0 || String(doc.maps[k].file).indexOf("/") >= 0 || String(doc.maps[k].file).indexOf("\\") >= 0)
507 { throw new Error("ppda: maps." + k + ".file mag geen pad bevatten"); }
508 });
509 if (!Array.isArray(doc.clips) || !doc.clips.length)
510 { throw new Error("ppda: clips verplicht"); }
511
512 for (var ci = 0; ci < doc.clips.length; ci++)
513 {
514 var clip = doc.clips[ci];
515 if (!clip.frames || clip.frames.length !== clip.frame_count)
516 { throw new Error("ppda: clip '" + (clip.name || ci) + "' frames≠frame_count"); }
517 for (var fi = 0; fi < clip.frames.length; fi++)
518 {
519 var fr = clip.frames[fi];
520 if (!fr.views || !fr.views.length)
521 { throw new Error("ppda: frame zonder views"); }
522 for (var vi = 0; vi < fr.views.length; vi++)
523 {
524 var v = fr.views[vi];
525 if (v.w == null || v.h == null || v.x == null || v.y == null)
526 { throw new Error("ppda: view mist x/y/w/h"); }
527 }
528 }
529 }
530
531 var encoding = doc.depth_encoding;
532 var bits = doc.depth_bits;
533 if (!encoding)
534 {
535 // v1 / legacy long text in identity.depth → gray16
536 encoding = "gray";
537 bits = bits || 16;
538 }
539 else if (/gray/i.test(encoding) && encoding.indexOf("rgb_") < 0)
540 {
541 encoding = "gray";
542 }
543 else if (encoding.indexOf("rgb_bands") >= 0)
544 { encoding = "rgb_bands"; }
545 else if (encoding.indexOf("rgb_packed") >= 0)
546 { encoding = "rgb_packed"; }
547
548 var near = doc.depth_near != null ? doc.depth_near : (doc.identity && doc.identity.near);
549 var far = doc.depth_far != null ? doc.depth_far : (doc.identity && doc.identity.far);
550 if (near == null || far == null)
551 { throw new Error("ppda: depth_near/far of identity.near/far verplicht"); }
552
553 var fmt = DepthDecode.parseFormat(encoding, bits || 16);
554
555 return {
556 format_version: ver,
557 sex: doc.sex,
558 settype: doc.settype,
559 fps: doc.fps,
560 cell_width: doc.cell_width,
561 cell_height: doc.cell_height,
562 pitches: doc.pitches.slice(),
563 yaws: doc.yaws.slice(),
564 maps: doc.maps,
565 clips: doc.clips,
566 identity: doc.identity || null,
567 project: doc.project || null,
568 depth_near: Number(near),
569 depth_far: Number(far),
570 depth_format: fmt,
571 camera_distance: doc.identity && doc.identity.camera_distance != null
572 ? Number(doc.identity.camera_distance)
573 : 10,
574 height_milli: doc.identity && doc.identity.framing
575 ? doc.identity.framing.height_milli
576 : 2600,
577 raw: doc
578 };
579 },
580
581 compatKey: function (ppda)
582 {
583 var id = ppda.identity || {};
584 return {
585 sex: ppda.sex,
586 body_model_sha256: id.body_model_sha256 || "",
587 fps: ppda.fps,
588 cell_width: ppda.cell_width,
589 cell_height: ppda.cell_height,
590 pitches: ppda.pitches.join(","),
591 yaws: ppda.yaws.join(","),
592 near: ppda.depth_near,
593 far: ppda.depth_far
594 };
595 },
596
597 assertCompatible: function (a, b)
598 {
599 var ka = this.compatKey(a);
600 var kb = this.compatKey(b);
601 var keys = Object.keys(ka);
602 for (var i = 0; i < keys.length; i++)
603 {
604 var k = keys[i];
605 if (String(ka[k]) !== String(kb[k]))
606 { throw new Error("ppda incompatible: " + k + " (" + ka[k] + " vs " + kb[k] + ")"); }
607 }
608 }
609};
610
611if (typeof module !== "undefined" && module.exports)
612{ module.exports = PpdaLoader; }
613
614/*
615 * End File:
616 * /workspace/raytracer-work/src/ppda/loadPpda.js
617 */
618
619/*
620 * Start File:
621 * /workspace/raytracer-work/src/ppda/atlasRuntime.js
622 */
623/**
624 * Browser/runtime atlas set: loads PNG diffuse/normal/specular + u16 depth,
625 * extracts cells, composes body+gear on CPU (cell is 32×48 — cheap).
626 */
627var PpdaAtlasRuntime =
628{
629 _canvas: null,
630 _ctx: null,
631
632 _ensureCanvas: function ()
633 {
634 if (typeof document === "undefined")
635 { return null; }
636 if (!this._canvas)
637 {
638 this._canvas = document.createElement("canvas");
639 this._ctx = this._canvas.getContext("2d", { willReadFrequently: true });
640 }
641 return this._ctx;
642 },
643
644 loadImage: function (url)
645 {
646 return new Promise(function (resolve, reject)
647 {
648 var img = new Image();
649 img.onload = function ()
650 { resolve(img); };
651 img.onerror = function ()
652 { reject(new Error("image load failed: " + url)); };
653 img.src = url;
654 });
655 },
656
657 loadU16Depth: function (url, expectW, expectH)
658 {
659 return fetch(url).then(function (r)
660 {
661 if (!r.ok)
662 { throw new Error("depth fetch " + r.status + " " + url); }
663 return r.arrayBuffer();
664 }).then(function (buf)
665 {
666 var need = expectW * expectH * 4;
667 if (buf.byteLength < need)
668 { throw new Error("depth u16 te kort: " + buf.byteLength + " < " + need); }
669 return new Uint16Array(buf.slice(0, need));
670 });
671 },
672
673 /**
674 * @returns {Promise<{ppda, images, depthU16, baseUrl}>}
675 */
676 loadSet: function (baseUrl, ppdaFile)
677 {
678 var self = this;
679 baseUrl = baseUrl.replace(/\/?$/, "/");
680 return fetch(baseUrl + ppdaFile).then(function (r)
681 {
682 if (!r.ok)
683 { throw new Error("ppda fetch " + r.status); }
684 return r.text();
685 }).then(function (text)
686 {
687 var ppda = PpdaLoader.parse(text);
688 var maps = ppda.maps;
689 var jobs = [
690 self.loadImage(baseUrl + maps.diffuse.file),
691 maps.normal ? self.loadImage(baseUrl + maps.normal.file) : Promise.resolve(null),
692 maps.specular ? self.loadImage(baseUrl + maps.specular.file) : Promise.resolve(null)
693 ];
694 var depthFile = maps.depth.file;
695 var dw = maps.depth.width || maps.diffuse.width;
696 var dh = maps.depth.height || maps.diffuse.height;
697 if (maps.depth.storage === "u16le_ga" || /\.u16$/i.test(depthFile))
698 { jobs.push(self.loadU16Depth(baseUrl + depthFile, dw, dh)); }
699 else
700 { throw new Error("browser-loader verwacht depth als .u16 (storage=u16le_ga); got " + depthFile); }
701
702 return Promise.all(jobs).then(function (parts)
703 {
704 return {
705 ppda: ppda,
706 baseUrl: baseUrl,
707 diffuseImg: parts[0],
708 normalImg: parts[1],
709 specularImg: parts[2],
710 depthU16: parts[3],
711 depthW: dw,
712 depthH: dh
713 };
714 });
715 });
716 },
717
718 extractRgbaCell: function (img, view)
719 {
720 var ctx = this._ensureCanvas();
721 if (!ctx)
722 { throw new Error("geen canvas voor cell extract"); }
723 this._canvas.width = view.w;
724 this._canvas.height = view.h;
725 ctx.clearRect(0, 0, view.w, view.h);
726 ctx.drawImage(img, view.x, view.y, view.w, view.h, 0, 0, view.w, view.h);
727 return ctx.getImageData(0, 0, view.w, view.h).data;
728 },
729
730 extractDepthCell: function (depthU16, atlasW, view)
731 {
732 var n = view.w * view.h;
733 var gray = new Uint16Array(n);
734 var alpha = new Uint16Array(n);
735 for (var y = 0; y < view.h; y++)
736 {
737 for (var x = 0; x < view.w; x++)
738 {
739 var si = ((view.y + y) * atlasW + (view.x + x)) * 2;
740 var di = y * view.w + x;
741 gray[di] = depthU16[si];
742 alpha[di] = depthU16[si + 1];
743 }
744 }
745 return { depthGray: gray, depthAlpha: alpha };
746 },
747
748 layerFromSet: function (set, clipToken, frameIndex, pitch, yaw)
749 {
750 var clip = PpdaViewFrame.findClip(set.ppda, clipToken);
751 if (!clip)
752 { throw new Error("clip niet gevonden: " + clipToken); }
753 var frame = clip.frames[frameIndex];
754 if (!frame)
755 { throw new Error("frame " + frameIndex + " ontbreekt"); }
756 var view = PpdaViewFrame.findView(frame, pitch, yaw);
757 if (!view)
758 { throw new Error("view p" + pitch + " y" + yaw + " ontbreekt"); }
759 if (view.empty)
760 {
761 var emptyN = view.w * view.h;
762 return {
763 width: view.w,
764 height: view.h,
765 diffuse: new Uint8ClampedArray(emptyN * 4),
766 normal: new Uint8ClampedArray(emptyN * 4),
767 specular: new Uint8ClampedArray(emptyN * 4),
768 depthGray: new Uint16Array(emptyN),
769 depthAlpha: new Uint16Array(emptyN),
770 view: view
771 };
772 }
773 var diffuse = this.extractRgbaCell(set.diffuseImg, view);
774 var normal = set.normalImg ? this.extractRgbaCell(set.normalImg, view) : null;
775 var specular = set.specularImg ? this.extractRgbaCell(set.specularImg, view) : null;
776 var depth = this.extractDepthCell(set.depthU16, set.depthW, view);
777 return {
778 width: view.w,
779 height: view.h,
780 diffuse: diffuse,
781 normal: normal,
782 specular: specular,
783 depthGray: depth.depthGray,
784 depthAlpha: depth.depthAlpha,
785 view: view
786 };
787 },
788
789 composeView: function (bodySet, gearSet, clipToken, frameIndex, pitch, yaw)
790 {
791 var body = this.layerFromSet(bodySet, clipToken, frameIndex, pitch, yaw);
792 var layers = [body];
793 if (gearSet)
794 {
795 PpdaLoader.assertCompatible(bodySet.ppda, gearSet.ppda);
796 layers.push(this.layerFromSet(gearSet, clipToken, frameIndex, pitch, yaw));
797 }
798 var composed = PpdaCompositor.compose(layers);
799 composed.view = body.view;
800 composed.lit = PpdaCompositor.relightDiffuse(composed, 1);
801 return composed;
802 }
803};
804
805if (typeof module !== "undefined" && module.exports)
806{ module.exports = PpdaAtlasRuntime; }
807
808/*
809 * End File:
810 * /workspace/raytracer-work/src/ppda/atlasRuntime.js
811 */
812
813/*
814 * Start File:
815 * /workspace/raytracer-work/src/levelFormat.js
816 */
817/**
818 * Level pack format for raytracer + editor.
819 * v1: walls/floors/ceilings/npcs/lights[] (empty reserved)
820 * v2: lights fully specified + per-level ambient; migrate v1→v2.
821 */
822var LevelFormat =
823{
824 CURRENT_VERSION: 2,
825 MAX_SIZE: 128,
826 MAX_LEVELS: 64,
827 MAX_LIGHTS: 32,
828 KNOWN_TEXTURES: ["stone", "wood"],
829 DEFAULT_AMBIENT: 0.38,
830
831 emptyLight: function (x, y)
832 {
833 return {
834 id: "light-" + Date.now().toString(36),
835 x: x == null ? 48 : x,
836 y: y == null ? 48 : y,
837 z: 20,
838 color: [1, 0.9, 0.7],
839 intensity: 1.2,
840 range: 96,
841 falloff: 2
842 };
843 },
844
845 emptyLevel: function (name, width, height)
846 {
847 width = Math.max(3, Math.min(this.MAX_SIZE, width || 10));
848 height = Math.max(3, Math.min(this.MAX_SIZE, height || 10));
849 var n = width * height;
850 var walls = [];
851 var floors = [];
852 var ceilings = [];
853 for (var i = 0; i < n; i++)
854 {
855 var x = i % width;
856 var y = Math.floor(i / width);
857 var border = x === 0 || y === 0 || x === width - 1 || y === height - 1;
858 walls.push(border ? 1 : 0);
859 floors.push(border ? null : "stone");
860 ceilings.push(border ? null : "stone");
861 }
862 return {
863 id: "level-" + Date.now().toString(36),
864 name: name || "Nieuw level",
865 width: width,
866 height: height,
867 cellSize: 32,
868 ambient: this.DEFAULT_AMBIENT,
869 spawn: { tileX: 1, tileY: 1, yawRad: 0 },
870 walls: walls,
871 floors: floors,
872 ceilings: ceilings,
873 npcs: [],
874 lights: []
875 };
876 },
877
878 defaultPack: function ()
879 {
880 return {
881 format_version: this.CURRENT_VERSION,
882 textures: [
883 { id: "stone", url: "images/stone.png" },
884 { id: "wood", url: "images/wood.png" }
885 ],
886 levels: []
887 };
888 },
889
890 fromLegacyLevels: function (legacyArr, npcsByLevel)
891 {
892 var pack = this.defaultPack();
893 for (var i = 0; i < (legacyArr || []).length; i++)
894 {
895 var L = legacyArr[i];
896 var n = L.width * L.height;
897 var floors = [];
898 var ceilings = [];
899 for (var t = 0; t < n; t++)
900 {
901 var solid = L.tiles[t] === 1 || L.tiles[t] === 3;
902 floors.push(solid ? null : "stone");
903 ceilings.push(solid ? null : "stone");
904 }
905 pack.levels.push({
906 id: "level-" + (i + 1),
907 name: L.name || ("Level " + (i + 1)),
908 width: L.width,
909 height: L.height,
910 cellSize: 32,
911 ambient: this.DEFAULT_AMBIENT,
912 spawn: { tileX: L.spawnX, tileY: L.spawnY, yawRad: 0 },
913 walls: L.tiles.slice(),
914 floors: floors,
915 ceilings: ceilings,
916 npcs: (npcsByLevel && npcsByLevel[i]) || [],
917 lights: []
918 });
919 }
920 return pack;
921 },
922
923 migratePack: function (pack)
924 {
925 if (!pack || typeof pack !== "object")
926 { throw new Error("pack: root moet een object zijn"); }
927 var ver = pack.format_version;
928 if (ver === this.CURRENT_VERSION)
929 { return pack; }
930 if (ver === 1)
931 {
932 pack.format_version = 2;
933 for (var i = 0; i < (pack.levels || []).length; i++)
934 {
935 var L = pack.levels[i];
936 if (typeof L.ambient !== "number")
937 { L.ambient = this.DEFAULT_AMBIENT; }
938 if (!Array.isArray(L.lights))
939 { L.lights = []; }
940 for (var li = 0; li < L.lights.length; li++)
941 { this.normalizeLight(L.lights[li]); }
942 }
943 return pack;
944 }
945 throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1..2)");
946 },
947
948 normalizeLight: function (light)
949 {
950 if (!light || typeof light !== "object")
951 { throw new Error("light: moet een object zijn"); }
952 if (typeof light.x !== "number" || typeof light.y !== "number")
953 { throw new Error("light: x/y verplicht"); }
954 if (typeof light.z !== "number")
955 { light.z = 20; }
956 if (!Array.isArray(light.color) || light.color.length < 3)
957 { light.color = [1, 0.9, 0.7]; }
958 for (var c = 0; c < 3; c++)
959 {
960 var v = Number(light.color[c]);
961 if (!(v >= 0))
962 { v = 0; }
963 // allow 0–255 UI values
964 if (v > 1)
965 { v = v / 255; }
966 light.color[c] = v;
967 }
968 if (typeof light.intensity !== "number")
969 { light.intensity = 1; }
970 if (typeof light.range !== "number" || light.range <= 0)
971 { light.range = 96; }
972 if (typeof light.falloff !== "number")
973 { light.falloff = 2; }
974 if (!light.id || typeof light.id !== "string")
975 { light.id = "light-" + Math.floor(light.x) + "-" + Math.floor(light.y); }
976 return light;
977 },
978
979 validateTextureId: function (tex, allowNull)
980 {
981 if (tex == null || tex === "")
982 { return !!allowNull; }
983 return this.KNOWN_TEXTURES.indexOf(tex) >= 0;
984 },
985
986 validateLight: function (light, index, levelPrefix)
987 {
988 var prefix = (levelPrefix || "level") + ".lights[" + (index == null ? "?" : index) + "]";
989 try
990 { this.normalizeLight(light); }
991 catch (e)
992 { throw new Error(prefix + ": " + e.message); }
993 if (light.intensity < 0 || light.intensity > 20)
994 { throw new Error(prefix + ": intensity 0..20"); }
995 if (light.range > 2048)
996 { throw new Error(prefix + ": range te groot"); }
997 if (light.falloff < 0.5 || light.falloff > 8)
998 { throw new Error(prefix + ": falloff 0.5..8"); }
999 return light;
1000 },
1001
1002 validateLevel: function (level, index)
1003 {
1004 var prefix = "level[" + (index == null ? "?" : index) + "]";
1005 if (!level || typeof level !== "object")
1006 { throw new Error(prefix + ": moet een object zijn"); }
1007 if (!level.id || typeof level.id !== "string")
1008 { throw new Error(prefix + ": id verplicht"); }
1009 if (!level.name || typeof level.name !== "string")
1010 { throw new Error(prefix + ": name verplicht"); }
1011 var w = level.width | 0;
1012 var h = level.height | 0;
1013 if (w < 3 || h < 3 || w > this.MAX_SIZE || h > this.MAX_SIZE)
1014 { throw new Error(prefix + ": width/height 3.." + this.MAX_SIZE); }
1015 var n = w * h;
1016 if (!Array.isArray(level.walls) || level.walls.length !== n)
1017 { throw new Error(prefix + ": walls lengte ≠ width*height"); }
1018 if (!Array.isArray(level.floors) || level.floors.length !== n)
1019 { throw new Error(prefix + ": floors lengte ≠ width*height"); }
1020 if (!Array.isArray(level.ceilings) || level.ceilings.length !== n)
1021 { throw new Error(prefix + ": ceilings lengte ≠ width*height"); }
1022 for (var i = 0; i < n; i++)
1023 {
1024 var wall = level.walls[i];
1025 if (typeof wall !== "number" || wall !== (wall | 0) || wall < 0 || wall > 3)
1026 { throw new Error(prefix + ": walls[" + i + "] ongeldig"); }
1027 if (!this.validateTextureId(level.floors[i], true))
1028 { throw new Error(prefix + ": floors[" + i + "] onbekende textuur"); }
1029 if (!this.validateTextureId(level.ceilings[i], true))
1030 { throw new Error(prefix + ": ceilings[" + i + "] onbekende textuur"); }
1031 }
1032 if (!level.spawn || typeof level.spawn.tileX !== "number" || typeof level.spawn.tileY !== "number")
1033 { throw new Error(prefix + ": spawn.tileX/tileY verplicht"); }
1034 if (level.spawn.tileX < 0 || level.spawn.tileY < 0 || level.spawn.tileX >= w || level.spawn.tileY >= h)
1035 { throw new Error(prefix + ": spawn buiten de map"); }
1036 if (typeof level.spawn.yawRad !== "number")
1037 { level.spawn.yawRad = 0; }
1038 if (!Array.isArray(level.npcs))
1039 { throw new Error(prefix + ": npcs moet een array zijn"); }
1040 if (!Array.isArray(level.lights))
1041 { level.lights = []; }
1042 if (level.lights.length > this.MAX_LIGHTS)
1043 { throw new Error(prefix + ": te veel lights"); }
1044 for (var li = 0; li < level.lights.length; li++)
1045 { this.validateLight(level.lights[li], li, prefix); }
1046 if (typeof level.ambient !== "number")
1047 { level.ambient = this.DEFAULT_AMBIENT; }
1048 if (level.ambient < 0 || level.ambient > 1)
1049 { throw new Error(prefix + ": ambient 0..1"); }
1050 if (level.cellSize == null)
1051 { level.cellSize = 32; }
1052 return level;
1053 },
1054
1055 validatePack: function (pack)
1056 {
1057 pack = this.migratePack(pack);
1058 if (pack.format_version !== this.CURRENT_VERSION)
1059 { throw new Error("pack: format_version " + pack.format_version + " niet ondersteund (wel: " + this.CURRENT_VERSION + ")"); }
1060 if (!Array.isArray(pack.levels))
1061 { throw new Error("pack: levels moet een array zijn"); }
1062 if (pack.levels.length > this.MAX_LEVELS)
1063 { throw new Error("pack: te veel levels"); }
1064 if (pack.levels.length < 1)
1065 { throw new Error("pack: minstens één level"); }
1066 var ids = {};
1067 for (var i = 0; i < pack.levels.length; i++)
1068 {
1069 this.validateLevel(pack.levels[i], i);
1070 if (ids[pack.levels[i].id])
1071 { throw new Error("pack: dubbele level-id " + pack.levels[i].id); }
1072 ids[pack.levels[i].id] = true;
1073 }
1074 if (!Array.isArray(pack.textures))
1075 { pack.textures = this.defaultPack().textures; }
1076 return pack;
1077 },
1078
1079 parse: function (jsonText)
1080 {
1081 var doc;
1082 try
1083 { doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; }
1084 catch (e)
1085 { throw new Error("levels.json: ongeldige JSON (" + e.message + ")"); }
1086 return this.validatePack(doc);
1087 },
1088
1089 toRuntimeLevel: function (level)
1090 {
1091 return {
1092 id: level.id,
1093 name: level.name,
1094 width: level.width,
1095 height: level.height,
1096 cellSize: level.cellSize || 32,
1097 ambient: typeof level.ambient === "number" ? level.ambient : this.DEFAULT_AMBIENT,
1098 spawnX: level.spawn.tileX,
1099 spawnY: level.spawn.tileY,
1100 spawnYaw: level.spawn.yawRad || 0,
1101 tiles: level.walls,
1102 floors: level.floors,
1103 ceilings: level.ceilings,
1104 npcs: level.npcs || [],
1105 lights: level.lights || []
1106 };
1107 },
1108
1109 findLevelIndex: function (pack, query)
1110 {
1111 if (query == null || query === "")
1112 { return 0; }
1113 var asNum = Number(query);
1114 if (!isNaN(asNum) && asNum === (asNum | 0) && asNum >= 0 && asNum < pack.levels.length)
1115 { return asNum; }
1116 for (var i = 0; i < pack.levels.length; i++)
1117 {
1118 if (pack.levels[i].id === query || pack.levels[i].name === query)
1119 { return i; }
1120 }
1121 return -1;
1122 },
1123
1124 cloneLevel: function (level)
1125 {
1126 return JSON.parse(JSON.stringify(level));
1127 }
1128};
1129
1130if (typeof module !== "undefined" && module.exports)
1131{ module.exports = LevelFormat; }
1132
1133/*
1134 * End File:
1135 * /workspace/raytracer-work/src/levelFormat.js
1136 */
1137
1138/*
1139 * Start File:
1140 * /workspace/raytracer-work/src/camera.js
1141 */
1142/**
1143 * Shared camera-plane projection (FOV 90°).
1144 * Rays use dir + plane*camX (camX in [-1,1]); depths are perpendicular
1145 * (along forward), so walls/floor/sprites/z-buffer stay consistent and
1146 * fish-eye from equal-angle rays + Euclidean depth is avoided.
1147 */
1148var Camera =
1149{
1150 /** Half FOV in radians (π/4 → full FOV 90°). */
1151 HALF_FOV: Math.PI / 4,
1152
1153 tanHalfFov: function ()
1154 {
1155 return Math.tan(this.HALF_FOV);
1156 },
1157
1158 forward: function (rot)
1159 {
1160 return { x: Math.cos(rot), y: Math.sin(rot) };
1161 },
1162
1163 /**
1164 * Camera plane vector (perpendicular to forward, length = tan(halfFov)).
1165 * World +Y is south; left-handed screen: +plane = screen right.
1166 */
1167 plane: function (rot)
1168 {
1169 var t = this.tanHalfFov();
1170 var fx = Math.cos(rot);
1171 var fy = Math.sin(rot);
1172 // right = (-fy, fx) so that forward×right points "up" in XY…
1173 // For +X east +Y south, facing +X: right should be +Y (south) = screen right when looking east?
1174 // Looking east (+X): screen right = south (+Y). right=(-fy,fx)=(0,1). plane = right * tan.
1175 return { x: -fy * t, y: fx * t };
1176 },
1177
1178 /** camX in [-1,1] from screen x / column index. */
1179 camXFromScreen: function (sx, screenW)
1180 {
1181 return (2 * sx / screenW) - 1;
1182 },
1183
1184 camXFromColumn: function (col, cols)
1185 {
1186 return -1 + (2 * (col + 0.5) / cols);
1187 },
1188
1189 /** Unnormalized ray direction for camera-plane casting. */
1190 rayDir: function (rot, camX)
1191 {
1192 var f = this.forward(rot);
1193 var p = this.plane(rot);
1194 return { x: f.x + p.x * camX, y: f.y + p.y * camX };
1195 },
1196
1197 /** Angle of camera-plane ray (for World.rayCast which takes a radian). */
1198 rayAngle: function (rot, camX)
1199 {
1200 var d = this.rayDir(rot, camX);
1201 return Math.atan2(d.y, d.x);
1202 },
1203
1204 /**
1205 * Perpendicular depth of a world point relative to the camera.
1206 * Positive in front; use for sprite size, z-buffer, occlusion.
1207 */
1208 perpDepth: function (worldX, worldY, playerX, playerY, rot)
1209 {
1210 var f = this.forward(rot);
1211 return (worldX - playerX) * f.x + (worldY - playerY) * f.y;
1212 },
1213
1214 /**
1215 * Perp depth from Euclidean ray length and the ray's camX
1216 * (euclid * cos(atan(camX*tanHalf)) = euclid / length(rayDir) * …).
1217 * For a hit along rayDir: perp = euclid * (forward·normalize(rayDir)).
1218 */
1219 perpFromEuclid: function (euclidDist, rot, camX)
1220 {
1221 var d = this.rayDir(rot, camX);
1222 var len = Math.sqrt(d.x * d.x + d.y * d.y);
1223 if (len < 1e-8)
1224 { return euclidDist; }
1225 var f = this.forward(rot);
1226 var cosA = (d.x * f.x + d.y * f.y) / len;
1227 return euclidDist * cosA;
1228 },
1229
1230 /**
1231 * Project world point to screen X (pixels) and perp depth.
1232 * Returns null if behind camera.
1233 */
1234 projectSprite: function (worldX, worldY, playerX, playerY, rot, screenW)
1235 {
1236 var depth = this.perpDepth(worldX, worldY, playerX, playerY, rot);
1237 if (depth <= 0.05)
1238 { return null; }
1239 var f = this.forward(rot);
1240 var t = this.tanHalfFov();
1241 // screen-right axis (= plane / tanHalf)
1242 var rx = -f.y;
1243 var ry = f.x;
1244 var lat = (worldX - playerX) * rx + (worldY - playerY) * ry;
1245 var screenX = (screenW / 2) * (1 + (lat / depth) / t);
1246 return { screenX: screenX, depth: depth, lat: lat };
1247 }
1248};
1249
1250if (typeof module !== "undefined" && module.exports)
1251{ module.exports = Camera; }
1252
1253/*
1254 * End File:
1255 * /workspace/raytracer-work/src/camera.js
1256 */
1257
1258/*
1259 * Start File:
1260 * /workspace/raytracer-work/src/floorCast.js
1261 */
1262/**
1263 * Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.
1264 * Rays use Camera plane (dir+plane*camX); rowDist is perpendicular depth.
1265 * Chosen over a grid data-texture shader because frameworkv3 is WebGL1 sprites
1266 * without a shared depth buffer; one ImageData upload stays simple and keeps
1267 * wall/NPC draw order unchanged (floor under walls).
1268 *
1269 * posZ must match wall projection: wallH = (cellSize * screenH) / dist, so the
1270 * floor at distance d sits at p = (cellSize/2 * screenH) / d from the horizon.
1271 * Using posZ = screenH/2 made rowDist ≈ 1–2 across the whole floor (one flat
1272 * texel of a 400² texture).
1273 */
1274var FloorCast =
1275{
1276 /** Camera height in projection units: (cellSize/2) * screenH. */
1277 posZ: function (screenH, cellSize)
1278 {
1279 return (cellSize * 0.5) * screenH;
1280 },
1281
1282 /**
1283 * World-space floor hit for screen pixel (sx, sy).
1284 * @returns {{wx:number,wy:number,rowDist:number,isCeiling:boolean}|null}
1285 */
1286 floorHit: function (sx, sy, screenW, screenH, playerX, playerY, rot, pitch, posZ, cellSize)
1287 {
1288 cellSize = cellSize || 32;
1289 var mid = screenH / 2 + (-pitch * screenH * 0.25);
1290 var p = sy - mid;
1291 if (p === 0)
1292 { return null; }
1293 if (posZ == null)
1294 { posZ = this.posZ(screenH, cellSize); }
1295 var rowDist = posZ / Math.abs(p);
1296 var camX = (typeof Camera !== "undefined")
1297 ? Camera.camXFromScreen(sx, screenW)
1298 : (2 * sx / screenW) - 1;
1299 var dir;
1300 if (typeof Camera !== "undefined")
1301 { dir = Camera.rayDir(rot, camX); }
1302 else
1303 {
1304 var rayAngle = rot + camX * (Math.PI / 4);
1305 dir = { x: Math.cos(rayAngle), y: Math.sin(rayAngle) };
1306 }
1307 return {
1308 wx: playerX + dir.x * rowDist,
1309 wy: playerY + dir.y * rowDist,
1310 rowDist: rowDist,
1311 isCeiling: p < 0
1312 };
1313 },
1314
1315 /**
1316 * Sample NEAREST from RGBA Uint8ClampedArray tex (tw×th).
1317 * u,v in [0,1) tile space (or any real; wraps).
1318 */
1319 sampleNearest: function (rgba, tw, th, u, v)
1320 {
1321 var tx = Math.floor(((u % 1) + 1) % 1 * tw);
1322 var ty = Math.floor(((v % 1) + 1) % 1 * th);
1323 if (tx < 0) tx = 0;
1324 if (ty < 0) ty = 0;
1325 if (tx >= tw) tx = tw - 1;
1326 if (ty >= th) ty = th - 1;
1327 var o = (ty * tw + tx) * 4;
1328 return [rgba[o], rgba[o + 1], rgba[o + 2], rgba[o + 3]];
1329 },
1330
1331 /**
1332 * Count unique RGB triples in ImageData (optionally only in a rect).
1333 * Useful for tests: textured floor must not collapse to 1–2 colours.
1334 */
1335 countUniqueRgb: function (imgData, screenW, screenH, x0, y0, x1, y1)
1336 {
1337 x0 = x0 == null ? 0 : x0;
1338 y0 = y0 == null ? 0 : y0;
1339 x1 = x1 == null ? screenW : x1;
1340 y1 = y1 == null ? screenH : y1;
1341 var data = imgData.data;
1342 var seen = Object.create(null);
1343 var n = 0;
1344 for (var y = y0; y < y1; y++)
1345 {
1346 for (var x = x0; x < x1; x++)
1347 {
1348 var o = (y * screenW + x) * 4;
1349 var key = data[o] + "," + data[o + 1] + "," + data[o + 2];
1350 if (!seen[key])
1351 {
1352 seen[key] = 1;
1353 n++;
1354 }
1355 }
1356 }
1357 return n;
1358 },
1359
1360 /**
1361 * Fill ImageData with floor (below horizon) and ceiling (above).
1362 * texMap: { stone: {rgba,w,h}, wood: {...} }
1363 * level: runtime level with floors[], ceilings[], width, height, cellSize
1364 */
1365 render: function (imgData, screenW, screenH, player, level, texMap, cellSize)
1366 {
1367 cellSize = cellSize || 32;
1368 var data = imgData.data;
1369 var mid = screenH / 2 + (-player.pitch * screenH * 0.25);
1370 var posZ = this.posZ(screenH, cellSize);
1371 var lw = level.width;
1372 var lh = level.height;
1373 var floors = level.floors;
1374 var ceilings = level.ceilings;
1375
1376 // Step 2×2: NEAREST block fill — ~4× sneller, nog steeds pixelig.
1377 var step = 2;
1378 for (var sy = 0; sy < screenH; sy += step)
1379 {
1380 var p = (sy + step * 0.5) - mid;
1381 if (Math.abs(p) < 0.5)
1382 { continue; }
1383 var isCeil = p < 0;
1384 var rowDist = posZ / Math.abs(p);
1385 // Mild distance shade; keep texel contrast readable.
1386 var shade = Math.max(0.45, Math.min(1, 1.05 - rowDist / (cellSize * 40)));
1387 for (var sx = 0; sx < screenW; sx += step)
1388 {
1389 var camX = (typeof Camera !== "undefined")
1390 ? Camera.camXFromScreen(sx + step * 0.5, screenW)
1391 : (2 * (sx + step * 0.5) / screenW) - 1;
1392 var rdir = (typeof Camera !== "undefined")
1393 ? Camera.rayDir(player.rotation, camX)
1394 : { x: Math.cos(player.rotation + camX * (Math.PI / 4)),
1395 y: Math.sin(player.rotation + camX * (Math.PI / 4)) };
1396 var wx = player.x + rdir.x * rowDist;
1397 var wy = player.y + rdir.y * rowDist;
1398 var cx = Math.floor(wx / cellSize);
1399 var cy = Math.floor(wy / cellSize);
1400 var r = 0, g = 0, b = 0;
1401 if (cx >= 0 && cy >= 0 && cx < lw && cy < lh)
1402 {
1403 var idx = cx + cy * lw;
1404 var texId = isCeil ? ceilings[idx] : floors[idx];
1405 // Solid wall cells store null floor/ceiling; still sample a default
1406 // so perspective rays that hit that XY don't punch a black hole
1407 // next to lit open floor (looks like a hard vertical seam).
1408 if (!texId && level.tiles)
1409 {
1410 var tid = level.tiles[idx];
1411 if (tid === 1 || tid === 3)
1412 { texId = tid === 3 ? "wood" : "stone"; }
1413 }
1414 if (texId && texMap[texId])
1415 {
1416 var tex = texMap[texId];
1417 var u = wx / cellSize;
1418 var vv = wy / cellSize;
1419 var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);
1420 var wz = isCeil ? cellSize : 0;
1421 var nrm = isCeil
1422 ? { x: 0, y: 0, z: -1 }
1423 : { x: 0, y: 0, z: 1 };
1424 var lights = level.lights || [];
1425 var ambient = level.ambient != null ? level.ambient : 0.38;
1426 var lit;
1427 if (typeof Lighting !== "undefined" && lights.length)
1428 {
1429 // No grid LOS on floors/ceilings — avoids hard screen-space seams.
1430 lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, null);
1431 }
1432 else
1433 {
1434 // No lamps: keep previous distance shade look.
1435 lit = { r: shade, g: shade, b: shade };
1436 }
1437 r = Math.min(255, (c[0] * lit.r) | 0);
1438 g = Math.min(255, (c[1] * lit.g) | 0);
1439 b = Math.min(255, (c[2] * lit.b) | 0);
1440 }
1441 }
1442 for (var dy = 0; dy < step && sy + dy < screenH; dy++)
1443 {
1444 for (var dx = 0; dx < step && sx + dx < screenW; dx++)
1445 {
1446 var o = ((sy + dy) * screenW + (sx + dx)) * 4;
1447 data[o] = r;
1448 data[o + 1] = g;
1449 data[o + 2] = b;
1450 data[o + 3] = 255;
1451 }
1452 }
1453 }
1454 }
1455 return imgData;
1456 }
1457};
1458
1459if (typeof module !== "undefined" && module.exports)
1460{ module.exports = FloorCast; }
1461
1462/*
1463 * End File:
1464 * /workspace/raytracer-work/src/floorCast.js
1465 */
1466
1467/*
1468 * Start File:
1469 * /workspace/raytracer-work/src/floorGpu.js
1470 */
1471/**
1472 * GPU floor/ceiling + point lights (WebGL1 fragment shader via frameworkv3 drawSprite).
1473 * Uses the same camera-plane rays + perp rowDist as Camera / FloorCast (no fish-eye).
1474 */
1475var FloorGpu =
1476{
1477 MAX_LIGHTS: 8,
1478 _shader: null,
1479 _whiteTex: null,
1480 _gridTex: null,
1481 _gridW: 0,
1482 _gridH: 0,
1483 _gridKey: "",
1484 _stoneTex: null,
1485 _woodTex: null,
1486 _stoneSrc: null,
1487 _woodSrc: null,
1488
1489 _ensureShader: function ()
1490 {
1491 if (this._shader)
1492 { return this._shader; }
1493 var frag = [
1494 "precision mediump float;",
1495 "uniform sampler2D u_texture;",
1496 "uniform sampler2D u_stone;",
1497 "uniform sampler2D u_wood;",
1498 "uniform sampler2D u_grid;",
1499 "uniform float u_alpha;",
1500 "uniform vec2 u_resolution;",
1501 "uniform vec2 u_player;",
1502 "uniform vec2 u_dir;",
1503 "uniform vec2 u_plane;",
1504 "uniform float u_pitch;",
1505 "uniform float u_cellSize;",
1506 "uniform float u_posZ;",
1507 "uniform vec2 u_levelSize;",
1508 "uniform float u_ambient;",
1509 "uniform float u_lightCount;",
1510 "uniform vec4 u_l0;",
1511 "uniform vec4 u_l1;",
1512 "uniform vec4 u_l2;",
1513 "uniform vec4 u_l3;",
1514 "uniform vec4 u_l4;",
1515 "uniform vec4 u_l5;",
1516 "uniform vec4 u_l6;",
1517 "uniform vec4 u_l7;",
1518 "uniform vec3 u_c0;",
1519 "uniform vec3 u_c1;",
1520 "uniform vec3 u_c2;",
1521 "uniform vec3 u_c3;",
1522 "uniform vec3 u_c4;",
1523 "uniform vec3 u_c5;",
1524 "uniform vec3 u_c6;",
1525 "uniform vec3 u_c7;",
1526 "uniform vec2 u_a0;",
1527 "uniform vec2 u_a1;",
1528 "uniform vec2 u_a2;",
1529 "uniform vec2 u_a3;",
1530 "uniform vec2 u_a4;",
1531 "uniform vec2 u_a5;",
1532 "uniform vec2 u_a6;",
1533 "uniform vec2 u_a7;",
1534 "varying vec2 v_texCoord;",
1535 "vec4 lightPos(int i) {",
1536 " if (i==0) return u_l0; if (i==1) return u_l1; if (i==2) return u_l2; if (i==3) return u_l3;",
1537 " if (i==4) return u_l4; if (i==5) return u_l5; if (i==6) return u_l6; return u_l7;",
1538 "}",
1539 "vec3 lightCol(int i) {",
1540 " if (i==0) return u_c0; if (i==1) return u_c1; if (i==2) return u_c2; if (i==3) return u_c3;",
1541 " if (i==4) return u_c4; if (i==5) return u_c5; if (i==6) return u_c6; return u_c7;",
1542 "}",
1543 "vec2 lightAtt(int i) {",
1544 " if (i==0) return u_a0; if (i==1) return u_a1; if (i==2) return u_a2; if (i==3) return u_a3;",
1545 " if (i==4) return u_a4; if (i==5) return u_a5; if (i==6) return u_a6; return u_a7;",
1546 "}",
1547 "void main() {",
1548 " float sx = gl_FragCoord.x;",
1549 " float sy = u_resolution.y - gl_FragCoord.y;",
1550 " float mid = u_resolution.y * 0.5 + (-u_pitch * u_resolution.y * 0.25);",
1551 " float p = sy - mid;",
1552 " if (abs(p) < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return; }",
1553 " float isCeil = step(p, 0.0);",
1554 " float rowDist = u_posZ / abs(p);",
1555 " float camX = (2.0 * sx / u_resolution.x) - 1.0;",
1556 " vec2 rayDir = u_dir + u_plane * camX;",
1557 " float wx = u_player.x + rayDir.x * rowDist;",
1558 " float wy = u_player.y + rayDir.y * rowDist;",
1559 " float cx = floor(wx / u_cellSize);",
1560 " float cy = floor(wy / u_cellSize);",
1561 " if (cx < 0.0 || cy < 0.0 || cx >= u_levelSize.x || cy >= u_levelSize.y) {",
1562 " gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return;",
1563 " }",
1564 " vec2 guv = (vec2(cx, cy) + 0.5) / u_levelSize;",
1565 " vec4 cell = texture2D(u_grid, guv);",
1566 " float floorId = floor(cell.r * 255.0 + 0.5);",
1567 " float ceilId = floor(cell.g * 255.0 + 0.5);",
1568 " float tileId = floor(cell.b * 255.0 + 0.5);",
1569 " float texId = mix(floorId, ceilId, isCeil);",
1570 " if (texId < 0.5) {",
1571 " if (tileId > 2.5) texId = 2.0;",
1572 " else if (tileId > 0.5) texId = 1.0;",
1573 " }",
1574 " if (texId < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return; }",
1575 " vec2 tuv = fract(vec2(wx, wy) / u_cellSize);",
1576 " vec3 albedo = mix(texture2D(u_stone, tuv).rgb, texture2D(u_wood, tuv).rgb, step(1.5, texId));",
1577 " float wz = mix(0.0, u_cellSize, isCeil);",
1578 " vec3 nrm = mix(vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, -1.0), isCeil);",
1579 " vec3 lit = vec3(u_ambient);",
1580 " for (int i = 0; i < 8; i++) {",
1581 " if (float(i) >= u_lightCount) break;",
1582 " vec4 Lp = lightPos(i);",
1583 " vec3 toL = Lp.xyz - vec3(wx, wy, wz);",
1584 " float dist = length(toL);",
1585 " vec2 attP = lightAtt(i);",
1586 " float t = 1.0 - dist / max(attP.x, 0.001);",
1587 " if (t <= 0.0) continue;",
1588 " float att = t;",
1589 " if (attP.y > 1.5) att = t * t;",
1590 " if (attP.y > 2.5) att = att * t;",
1591 " vec3 ld = toL / max(dist, 0.0001);",
1592 " float ndotl = dot(nrm, ld);",
1593 " if (ndotl <= 0.0) continue;",
1594 " lit += Lp.w * att * ndotl * lightCol(i);",
1595 " }",
1596 " gl_FragColor = vec4(min(albedo * lit, vec3(1.0)), u_alpha);",
1597 "}"
1598 ].join("\n");
1599 this._shader = new Shader(Shader.DEFAULT_VERT, frag);
1600 return this._shader;
1601 },
1602
1603 _texIdByte: function (id)
1604 {
1605 if (id === "stone") return 1;
1606 if (id === "wood") return 2;
1607 return 0;
1608 },
1609
1610 _uploadGrid: function (gl, level)
1611 {
1612 var w = level.width;
1613 var h = level.height;
1614 var key = (level.id || "") + "|" + w + "x" + h + "|" + (level._rev || 0);
1615 if (this._gridTex && this._gridKey === key && this._gridW === w && this._gridH === h)
1616 { return; }
1617 var data = new Uint8Array(w * h * 4);
1618 var floors = level.floors || [];
1619 var ceilings = level.ceilings || [];
1620 var tiles = level.tiles || [];
1621 for (var y = 0; y < h; y++)
1622 {
1623 for (var x = 0; x < w; x++)
1624 {
1625 var i = x + y * w;
1626 var o = i * 4;
1627 data[o] = this._texIdByte(floors[i]);
1628 data[o + 1] = this._texIdByte(ceilings[i]);
1629 data[o + 2] = tiles[i] || 0;
1630 data[o + 3] = 255;
1631 }
1632 }
1633 if (!this._gridTex)
1634 { this._gridTex = gl.createTexture(); }
1635 gl.bindTexture(gl.TEXTURE_2D, this._gridTex);
1636 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
1637 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1638 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1639 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1640 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1641 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
1642 this._gridW = w;
1643 this._gridH = h;
1644 this._gridKey = key;
1645 },
1646
1647 _uploadAlbedo: function (gl, htmlImg, which)
1648 {
1649 var prev = which === "stone" ? this._stoneSrc : this._woodSrc;
1650 var tex = which === "stone" ? this._stoneTex : this._woodTex;
1651 if (tex && prev === htmlImg)
1652 { return tex; }
1653 if (!tex)
1654 { tex = gl.createTexture(); }
1655 gl.bindTexture(gl.TEXTURE_2D, tex);
1656 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
1657 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1658 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1659 // CLAMP + fract() in shader: WebGL1 forbids REPEAT on NPOT (stone 400²).
1660 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1661 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1662 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImg);
1663 if (which === "stone")
1664 {
1665 this._stoneTex = tex;
1666 this._stoneSrc = htmlImg;
1667 }
1668 else
1669 {
1670 this._woodTex = tex;
1671 this._woodSrc = htmlImg;
1672 }
1673 return tex;
1674 },
1675
1676 _ensureWhite: function (glc)
1677 {
1678 if (this._whiteTex)
1679 { return this._whiteTex; }
1680 var c = document.createElement("canvas");
1681 c.width = 1;
1682 c.height = 1;
1683 var ctx = c.getContext("2d");
1684 ctx.fillStyle = "#ffffff";
1685 ctx.fillRect(0, 0, 1, 1);
1686 this._whiteTex = glc.getTexture(c);
1687 return this._whiteTex;
1688 },
1689
1690 invalidateGrid: function ()
1691 {
1692 this._gridKey = "";
1693 },
1694
1695 draw: function (glc, screenW, screenH, player, level, floorImages, cellSize)
1696 {
1697 if (!glc || !level || !floorImages || !floorImages.stone || !floorImages.wood)
1698 { return false; }
1699 if (typeof Shader === "undefined")
1700 { return false; }
1701 cellSize = cellSize || 32;
1702 var gl = glc.gl;
1703 var shader = this._ensureShader();
1704 this._uploadGrid(gl, level);
1705 this._uploadAlbedo(gl, floorImages.stone, "stone");
1706 this._uploadAlbedo(gl, floorImages.wood, "wood");
1707 var white = this._ensureWhite(glc);
1708
1709 var f = Camera.forward(player.rotation);
1710 var plane = Camera.plane(player.rotation);
1711 var lights = level.lights || [];
1712 var n = Math.min(lights.length, this.MAX_LIGHTS);
1713 var uniforms = {
1714 u_resolution: [screenW, screenH],
1715 u_player: [player.x, player.y],
1716 u_dir: [f.x, f.y],
1717 u_plane: [plane.x, plane.y],
1718 u_pitch: player.pitch || 0,
1719 u_cellSize: cellSize,
1720 u_posZ: (typeof FloorCast !== "undefined")
1721 ? FloorCast.posZ(screenH, cellSize)
1722 : (cellSize * 0.5) * screenH,
1723 u_levelSize: [level.width, level.height],
1724 u_ambient: level.ambient != null ? level.ambient : 0.38,
1725 u_lightCount: n
1726 };
1727 var i;
1728 for (i = 0; i < this.MAX_LIGHTS; i++)
1729 {
1730 if (i < n)
1731 {
1732 var L = lights[i];
1733 uniforms["u_l" + i] = [
1734 L.x, L.y, L.z != null ? L.z : 16,
1735 L.intensity == null ? 1 : L.intensity
1736 ];
1737 uniforms["u_c" + i] = [
1738 L.color ? L.color[0] : 1,
1739 L.color ? L.color[1] : 1,
1740 L.color ? L.color[2] : 1
1741 ];
1742 uniforms["u_a" + i] = [
1743 L.range || 64,
1744 L.falloff == null ? 2 : L.falloff
1745 ];
1746 }
1747 else
1748 {
1749 uniforms["u_l" + i] = [0, 0, 0, 0];
1750 uniforms["u_c" + i] = [0, 0, 0];
1751 uniforms["u_a" + i] = [1, 2];
1752 }
1753 }
1754
1755 glc.drawSprite({
1756 texture: white,
1757 shader: shader,
1758 x: screenW / 2,
1759 y: screenH / 2,
1760 w: screenW,
1761 h: screenH,
1762 rotationDeg: 0,
1763 alpha: 1,
1764 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
1765 textures: {
1766 u_stone: this._stoneTex,
1767 u_wood: this._woodTex,
1768 u_grid: this._gridTex
1769 },
1770 uniforms: uniforms
1771 });
1772 return true;
1773 }
1774};
1775
1776if (typeof module !== "undefined" && module.exports)
1777{ module.exports = FloorGpu; }
1778
1779/*
1780 * End File:
1781 * /workspace/raytracer-work/src/floorGpu.js
1782 */
1783
1784/*
1785 * Start File:
1786 * /workspace/raytracer-work/src/lighting.js
1787 */
1788/**
1789 * Point lights for the raycaster (CPU).
1790 * Walls/floor/ceiling: Lambertian N·L + distance falloff; walls also grid LOS.
1791 * Paperdolls: view-space normals from .ppda (RGB = n*0.5+0.5, view=+Z) with L
1792 * transformed into the chosen yaw view; Half-Lambert so side lights still
1793 * reach front-facing atlas normals, plus a slight geometric X tilt from u.
1794 *
1795 * Floor/ceiling skip grid LOS: tile Bresenham casts hard vertical shadow
1796 * seams in screen space; distance falloff is enough there. Walls keep LOS
1797 * with the sample nudged into open space so the hit cell is not a blocker.
1798 */
1799var Lighting =
1800{
1801 DEFAULT_AMBIENT: 0.38,
1802 MAX_LIGHTS: 32,
1803
1804 normalize3: function (x, y, z)
1805 {
1806 var len = Math.sqrt(x * x + y * y + z * z);
1807 if (len < 1e-8)
1808 { return { x: 0, y: 0, z: 1 }; }
1809 return { x: x / len, y: y / len, z: z / len };
1810 },
1811
1812 decodeNormalRgb: function (r, g, b)
1813 {
1814 return this.normalize3(
1815 r / 255 * 2 - 1,
1816 g / 255 * 2 - 1,
1817 b / 255 * 2 - 1
1818 );
1819 },
1820
1821 /** intensity * saturate(1 - dist/range)^falloff */
1822 attenuation: function (dist, range, falloff)
1823 {
1824 if (range <= 0)
1825 { return 0; }
1826 var t = 1 - dist / range;
1827 if (t <= 0)
1828 { return 0; }
1829 var f = falloff == null ? 2 : falloff;
1830 if (f === 1)
1831 { return t; }
1832 if (f === 2)
1833 { return t * t; }
1834 return Math.pow(t, f);
1835 },
1836
1837 /**
1838 * Outward normal of the visible wall face.
1839 * Raycaster `dir` = travel direction of the casting ray when it hit:
1840 * "west" → ray went east, visible face is the west face → normal (-1,0,0)
1841 * "east" → ray went west, visible face is the east face → normal (+1,0,0)
1842 * "north" → ray went north (−Y), visible face is the south face → (+Y)
1843 * "south" → ray went south (+Y), visible face is the north face → (−Y)
1844 */
1845 faceNormal: function (dir)
1846 {
1847 switch (dir)
1848 {
1849 case "north": return { x: 0, y: 1, z: 0 };
1850 case "south": return { x: 0, y: -1, z: 0 };
1851 case "east": return { x: 1, y: 0, z: 0 };
1852 case "west": return { x: -1, y: 0, z: 0 };
1853 case "floor": return { x: 0, y: 0, z: 1 };
1854 case "ceiling": return { x: 0, y: 0, z: -1 };
1855 default: return { x: 0, y: 0, z: 1 };
1856 }
1857 },
1858
1859 /**
1860 * Grid LOS (Bresenham). Skips start+end tiles. Optional corner check so
1861 * diagonal steps cannot slip through a wall corner unnoticed.
1862 */
1863 hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
1864 {
1865 cellSize = cellSize || 32;
1866 var tx0 = Math.floor(x0 / cellSize);
1867 var ty0 = Math.floor(y0 / cellSize);
1868 var tx1 = Math.floor(x1 / cellSize);
1869 var ty1 = Math.floor(y1 / cellSize);
1870 if (tx0 === tx1 && ty0 === ty1)
1871 { return true; }
1872 var dx = Math.abs(tx1 - tx0);
1873 var dy = Math.abs(ty1 - ty0);
1874 var sx = tx0 < tx1 ? 1 : -1;
1875 var sy = ty0 < ty1 ? 1 : -1;
1876 var err = dx - dy;
1877 var x = tx0;
1878 var y = ty0;
1879 var steps = 0;
1880 var maxSteps = dx + dy + 2;
1881 while (steps < maxSteps)
1882 {
1883 steps++;
1884 var e2 = 2 * err;
1885 var movedX = false, movedY = false;
1886 if (e2 > -dy) { err -= dy; x += sx; movedX = true; }
1887 if (e2 < dx) { err += dx; y += sy; movedY = true; }
1888 if (x === tx1 && y === ty1)
1889 { return true; }
1890 if (x < 0 || y < 0 || x >= mapW || y >= mapH)
1891 { return false; }
1892 var id = tiles[x + y * mapW];
1893 if (id === 1 || id === 3)
1894 { return false; }
1895 // Diagonal: also block if cutting a corner through a solid.
1896 if (movedX && movedY)
1897 {
1898 var a = tiles[(x - sx) + y * mapW];
1899 var b = tiles[x + (y - sy) * mapW];
1900 if ((a === 1 || a === 3) && (b === 1 || b === 3))
1901 { return false; }
1902 }
1903 }
1904 return true;
1905 },
1906
1907 /**
1908 * RGB multipliers. los: {tiles,width,height,cellSize} or null.
1909 * For walls pass sample already nudged into open space along the outward normal.
1910 */
1911 shadeRgb: function (pos, normal, lights, ambient, los)
1912 {
1913 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
1914 var r = ambient;
1915 var g = ambient;
1916 var b = ambient;
1917 if (!lights || !lights.length)
1918 { return { r: r, g: g, b: b }; }
1919 var n = Math.min(lights.length, this.MAX_LIGHTS);
1920 for (var i = 0; i < n; i++)
1921 {
1922 var L = lights[i];
1923 var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;
1924 var dx = lx - pos.x;
1925 var dy = ly - pos.y;
1926 var dz = lz - pos.z;
1927 var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
1928 var att = this.attenuation(dist, L.range || 64, L.falloff);
1929 if (att <= 0.001)
1930 { continue; }
1931 if (los && !this.hasLineOfSight(lx, ly, pos.x, pos.y, los.tiles, los.width, los.height, los.cellSize))
1932 { continue; }
1933 var ld = this.normalize3(dx, dy, dz);
1934 var ndotl = normal.x * ld.x + normal.y * ld.y + normal.z * ld.z;
1935 if (ndotl <= 0)
1936 { continue; }
1937 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
1938 var cr = L.color ? L.color[0] : 1;
1939 var cg = L.color ? L.color[1] : 1;
1940 var cb = L.color ? L.color[2] : 1;
1941 r += inten * cr;
1942 g += inten * cg;
1943 b += inten * cb;
1944 }
1945 return { r: r, g: g, b: b };
1946 },
1947
1948 /**
1949 * World direction (toward light) → paperdoll view space for yawDeg.
1950 * Yaw 0: camera on character +Z (front); view +Z toward camera, +Y up,
1951 * +X = camera right = character right at yaw 0.
1952 */
1953 worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
1954 {
1955 var face = (facingDeg || 0) * Math.PI / 180;
1956 var yaw = (yawDeg || 0) * Math.PI / 180;
1957 var frontX = Math.cos(face);
1958 var frontY = Math.sin(face);
1959 var rightX = -Math.sin(face);
1960 var rightY = Math.cos(face);
1961 // Camera offset in character space: yaw 0 → +Z (front)
1962 var camCX = Math.sin(yaw);
1963 var camCZ = Math.cos(yaw);
1964 var camX = rightX * camCX + frontX * camCZ;
1965 var camY = rightY * camCX + frontY * camCZ;
1966 // viewZ = toward camera (in XY), viewY = up, viewX = cross(viewY, viewZ)
1967 var viewXx = -camY;
1968 var viewXy = camX;
1969 var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
1970 if (vlen > 1e-8)
1971 { viewXx /= vlen; viewXy /= vlen; }
1972 return this.normalize3(
1973 dirX * viewXx + dirY * viewXy,
1974 dirZ,
1975 dirX * camX + dirY * camY
1976 );
1977 },
1978
1979 /**
1980 * Half-Lambert wrap so front-facing atlas normals still receive side light;
1981 * geoTiltX nudges the normal toward the billboard side (u 0..1 → -1..+1).
1982 */
1983 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg, geoTiltX)
1984 {
1985 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
1986 var n = this.decodeNormalRgb(nr, ng, nb);
1987 if (geoTiltX)
1988 {
1989 n = this.normalize3(n.x + geoTiltX * 0.85, n.y, n.z + 0.15);
1990 }
1991 var r = ambient * albedoR;
1992 var g = ambient * albedoG;
1993 var b = ambient * albedoB;
1994 if (!lights || !lights.length)
1995 {
1996 var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);
1997 var shade = Math.min(1, 0.35 + 0.65 * nd);
1998 return {
1999 r: Math.min(255, Math.round(albedoR * shade)),
2000 g: Math.min(255, Math.round(albedoG * shade)),
2001 b: Math.min(255, Math.round(albedoB * shade))
2002 };
2003 }
2004 var count = Math.min(lights.length, this.MAX_LIGHTS);
2005 for (var i = 0; i < count; i++)
2006 {
2007 var L = lights[i];
2008 var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;
2009 var dx = lx - pixelWorld.x;
2010 var dy = ly - pixelWorld.y;
2011 var dz = lz - pixelWorld.z;
2012 var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
2013 var att = this.attenuation(dist, L.range || 64, L.falloff);
2014 if (att <= 0.001)
2015 { continue; }
2016 var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);
2017 var raw = n.x * lv.x + n.y * lv.y + n.z * lv.z;
2018 // Half-Lambert: side lights still reach front-facing .ppda normals.
2019 var ndotl = raw * 0.5 + 0.5;
2020 if (ndotl <= 0.02)
2021 { continue; }
2022 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
2023 var cr = L.color ? L.color[0] : 1;
2024 var cg = L.color ? L.color[1] : 1;
2025 var cb = L.color ? L.color[2] : 1;
2026 r += albedoR * inten * cr;
2027 g += albedoG * inten * cg;
2028 b += albedoB * inten * cb;
2029 }
2030 return {
2031 r: Math.min(255, Math.round(r)),
2032 g: Math.min(255, Math.round(g)),
2033 b: Math.min(255, Math.round(b))
2034 };
2035 },
2036
2037 legacyFaceShade: function (dir)
2038 {
2039 switch (dir)
2040 {
2041 case "east": return 0.9;
2042 case "west": return 0.8;
2043 case "south": return 0.7;
2044 default: return 1.0;
2045 }
2046 },
2047
2048 /** Max |Δ| between consecutive column means in a row range (for seam tests). */
2049 maxColumnJump: function (getColumnMean, width)
2050 {
2051 var best = 0;
2052 var prev = getColumnMean(0);
2053 for (var x = 1; x < width; x++)
2054 {
2055 var v = getColumnMean(x);
2056 var d = Math.abs(v - prev);
2057 if (d > best)
2058 { best = d; }
2059 prev = v;
2060 }
2061 return best;
2062 }
2063};
2064
2065if (typeof module !== "undefined" && module.exports)
2066{ module.exports = Lighting; }
2067
2068/*
2069 * End File:
2070 * /workspace/raytracer-work/src/lighting.js
2071 */
2072
2073/*
2074 * Start File:
2075 * /workspace/raytracer-work/src/levels.js
2076 */
2077var Levels =
2078[
2079 {
2080 name: "Level 1",
2081 width: 10,
2082 height: 10,
2083 spawnX: 1,
2084 spawnY: 1,
2085 tiles:
2086 [
2087 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2088 1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2089 1, 0, 1, 1, 0, 0, 3, 3, 0, 1,
2090 1, 0, 0, 1, 0, 0, 0, 0, 0, 1,
2091 1, 0, 0, 0, 0, 1, 0, 1, 0, 1,
2092 1, 0, 0, 0, 0, 1, 0, 1, 0, 1,
2093 1, 0, 0, 0, 0, 1, 2, 1, 0, 1,
2094 1, 0, 1, 0, 0, 1, 3, 1, 0, 1,
2095 1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2096 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
2097 ]
2098 }
2099];
2100
2101/*
2102 * End File:
2103 * /workspace/raytracer-work/src/levels.js
2104 */
2105
2106/*
2107 * Start File:
2108 * /workspace/raytracer-work/src/tiles.js
2109 */
2110/** Tile table; Image fields filled after preload. */
2111var Tiles =
2112{
2113 Nothing:
2114 {
2115 ID: 0,
2116 Color: { R: 255, G: 255, B: 255 },
2117 Solid: false,
2118 ImageName: null
2119 },
2120 Stone:
2121 {
2122 ID: 1,
2123 Color: { R: 155, G: 155, B: 155 },
2124 Solid: true,
2125 ImageName: "stone"
2126 },
2127 Finish:
2128 {
2129 ID: 2,
2130 Color: { R: 255, G: 255, B: 0 },
2131 Solid: false,
2132 ImageName: null
2133 },
2134 Wood:
2135 {
2136 ID: 3,
2137 Color: { R: 168, G: 102, B: 50 },
2138 Solid: true,
2139 ImageName: "wood"
2140 },
2141 findByID: function (id)
2142 {
2143 for (var key in Tiles)
2144 {
2145 if (!Object.prototype.hasOwnProperty.call(Tiles, key))
2146 { continue; }
2147 var value = Tiles[key];
2148 if (value && value.ID === id)
2149 { return value; }
2150 }
2151 return null;
2152 },
2153 bindImages: function (images)
2154 {
2155 for (var key in Tiles)
2156 {
2157 if (!Object.prototype.hasOwnProperty.call(Tiles, key))
2158 { continue; }
2159 var tile = Tiles[key];
2160 if (tile && tile.ImageName && images[tile.ImageName])
2161 { tile.Image = images[tile.ImageName]; }
2162 }
2163 }
2164};
2165
2166/*
2167 * End File:
2168 * /workspace/raytracer-work/src/tiles.js
2169 */
2170
2171/*
2172 * Start File:
2173 * /workspace/raytracer-work/src/world.js
2174 */
2175var World =
2176{
2177 size: 32,
2178 level: null,
2179 pack: null,
2180 levelIndex: 0,
2181
2182 loadPack: function (pack)
2183 {
2184 this.pack = pack;
2185 },
2186
2187 loadLevel: function (indexOrId)
2188 {
2189 if (!this.pack)
2190 { throw new Error("World: geen level-pack geladen"); }
2191 var idx = typeof indexOrId === "number"
2192 ? indexOrId
2193 : LevelFormat.findLevelIndex(this.pack, indexOrId);
2194 if (idx < 0 || idx >= this.pack.levels.length)
2195 { throw new Error("World: level niet gevonden: " + indexOrId); }
2196 this.levelIndex = idx;
2197 this.level = LevelFormat.toRuntimeLevel(this.pack.levels[idx]);
2198 this.size = this.level.cellSize || 32;
2199 },
2200
2201 spawnPoint: function ()
2202 {
2203 return {
2204 x: this.level.spawnX * this.size + this.size / 2,
2205 y: this.level.spawnY * this.size + this.size / 2,
2206 yaw: this.level.spawnYaw || 0
2207 };
2208 },
2209
2210 rayCast: function (x, y, radian)
2211 {
2212 var maxDist = this.level.width + this.level.height;
2213 var cell = this.size;
2214 var tileXpercentage = 0;
2215 var tileXp = 0;
2216 var tileYp = 0;
2217
2218 var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit;
2219 var hDir = "north";
2220 distDone = 0;
2221 var aTan = -1 / Math.tan(radian);
2222
2223 if (radian > Math.PI)
2224 {
2225 hrayY = Math.floor(y / cell) * cell - 0.01;
2226 hrayX = (y - hrayY) * aTan + x;
2227 hoffY = -cell;
2228 hoffX = -hoffY * aTan;
2229 }
2230 else if (radian < Math.PI)
2231 {
2232 hrayY = Math.floor(y / cell) * cell + cell;
2233 hrayX = (y - hrayY) * aTan + x;
2234 hoffY = cell;
2235 hoffX = -hoffY * aTan;
2236 hDir = "south";
2237 }
2238 else
2239 {
2240 hrayX = x;
2241 hrayY = y;
2242 distDone = maxDist;
2243 }
2244
2245 while (distDone < maxDist)
2246 {
2247 tileXp = ((hrayX % cell) + cell) % cell / cell;
2248 tileYp = ((hrayY % cell) + cell) % cell / cell;
2249 hmapX = Math.floor(hrayX / cell);
2250 hmapY = Math.floor(hrayY / cell);
2251 var htileHitId = this.level.tiles[hmapX + hmapY * this.level.width];
2252 htileHit = Tiles.findByID(htileHitId);
2253 if (htileHit && htileHit.Solid)
2254 { distDone = maxDist; }
2255 else
2256 {
2257 hrayX += hoffX;
2258 hrayY += hoffY;
2259 distDone += 1;
2260 }
2261 }
2262
2263 switch (hDir)
2264 {
2265 case "north": tileXpercentage = tileXp; break;
2266 case "south": tileXpercentage = 1 - tileXp; break;
2267 case "east": tileXpercentage = 1 - tileYp; break;
2268 case "west": tileXpercentage = tileYp; break;
2269 }
2270
2271 var hResult = {
2272 tile: htileHit,
2273 tileX: tileXpercentage,
2274 endX: hrayX,
2275 endY: hrayY,
2276 dir: hDir
2277 };
2278
2279 var rayX, rayY, offX, offY, mapX, mapY, tileHit;
2280 var vDir = "east";
2281 var nTan = -Math.tan(radian);
2282 distDone = 0;
2283
2284 if (radian > Math.PI / 2 && radian < Math.PI * 1.5)
2285 {
2286 rayX = Math.floor(x / cell) * cell - 0.01;
2287 rayY = (x - rayX) * nTan + y;
2288 offX = -cell;
2289 offY = -offX * nTan;
2290 }
2291 else if (radian < Math.PI / 2 || radian > Math.PI * 1.5)
2292 {
2293 rayX = Math.floor(x / cell) * cell + cell;
2294 rayY = (x - rayX) * nTan + y;
2295 offX = cell;
2296 offY = -offX * nTan;
2297 vDir = "west";
2298 }
2299 else
2300 {
2301 rayX = x;
2302 rayY = y;
2303 distDone = maxDist;
2304 }
2305
2306 while (distDone < maxDist)
2307 {
2308 tileXp = ((rayX % cell) + cell) % cell / cell;
2309 tileYp = ((rayY % cell) + cell) % cell / cell;
2310 mapX = Math.floor(rayX / cell);
2311 mapY = Math.floor(rayY / cell);
2312 var tileHitId = this.level.tiles[mapX + mapY * this.level.width];
2313 tileHit = Tiles.findByID(tileHitId);
2314 if (tileHit && tileHit.Solid)
2315 { distDone = maxDist; }
2316 else
2317 {
2318 rayX += offX;
2319 rayY += offY;
2320 distDone += 1;
2321 }
2322 }
2323
2324 switch (vDir)
2325 {
2326 case "north": tileXpercentage = tileXp; break;
2327 case "south": tileXpercentage = 1 - tileXp; break;
2328 case "east": tileXpercentage = 1 - tileYp; break;
2329 case "west": tileXpercentage = tileYp; break;
2330 }
2331
2332 var vResult = {
2333 tile: tileHit,
2334 tileX: tileXpercentage,
2335 endX: rayX,
2336 endY: rayY,
2337 dir: vDir
2338 };
2339
2340 var dxH = hResult.endX - x;
2341 var dyH = hResult.endY - y;
2342 var dxV = vResult.endX - x;
2343 var dyV = vResult.endY - y;
2344 hResult.distance = Math.sqrt(dxH * dxH + dyH * dyH);
2345 vResult.distance = Math.sqrt(dxV * dxV + dyV * dyV);
2346
2347 if (hResult.distance < vResult.distance)
2348 { return hResult; }
2349 return vResult;
2350 }
2351};
2352
2353if (typeof module !== "undefined" && module.exports)
2354{
2355 module.exports = { World: World };
2356}
2357
2358/*
2359 * End File:
2360 * /workspace/raytracer-work/src/world.js
2361 */
2362
2363/*
2364 * Start File:
2365 * /workspace/raytracer-work/src/player.js
2366 */
2367var Player =
2368{
2369 x: 0,
2370 y: 0,
2371 rotation: 0,
2372 pitch: 0,
2373 /** Screen columns per frame. 240 is sharp on ~1080p and cheap (~240 drawSprite calls). */
2374 horizontalResolution: 240,
2375 gunX: 0.6,
2376 gunY: 0.6,
2377 currentGun: 0,
2378 guns: 3,
2379
2380 resetToSpawn: function ()
2381 {
2382 var spawn = World.spawnPoint();
2383 this.x = spawn.x;
2384 this.y = spawn.y;
2385 this.rotation = spawn.yaw != null ? spawn.yaw : 0;
2386 this.pitch = 0;
2387 },
2388
2389 applyLookDelta: function (movementX, movementY)
2390 {
2391 this.pitch += movementY * 0.01;
2392 this.rotation += movementX * 0.001;
2393 if (this.pitch > Math.PI)
2394 { this.pitch = Math.PI; }
2395 if (this.pitch < -Math.PI)
2396 { this.pitch = -Math.PI; }
2397 if (this.rotation > Math.PI * 2)
2398 { this.rotation -= Math.PI * 2; }
2399 if (this.rotation < 0)
2400 { this.rotation += Math.PI * 2; }
2401 },
2402
2403 /** Legacy angles: 0 = +X (east), increases toward +Y. */
2404 forwardVector: function (radian)
2405 {
2406 return { x: Math.cos(radian), y: Math.sin(radian) };
2407 },
2408
2409 tryMove: function (rot, speed, deltaTime)
2410 {
2411 if (World.rayCast(this.x, this.y, rot).distance <= 5)
2412 { return; }
2413 var forward = this.forwardVector(rot);
2414 this.x += forward.x * deltaTime * speed;
2415 this.y += forward.y * deltaTime * speed;
2416 },
2417
2418 update: function (deltaTime)
2419 {
2420 if (GameInput.isHeld(37) || GameInput.isHeld(65))
2421 {
2422 var rotL = this.rotation - Math.PI / 2;
2423 if (rotL < 0) { rotL += Math.PI * 2; }
2424 this.tryMove(rotL, 60, deltaTime);
2425 }
2426 if (GameInput.isHeld(39) || GameInput.isHeld(68))
2427 {
2428 var rotR = this.rotation + Math.PI / 2;
2429 if (rotR > Math.PI * 2) { rotR -= Math.PI * 2; }
2430 this.tryMove(rotR, 60, deltaTime);
2431 }
2432 if (GameInput.isHeld(38) || GameInput.isHeld(87))
2433 { this.tryMove(this.rotation, 60, deltaTime); }
2434 if (GameInput.isHeld(40) || GameInput.isHeld(83))
2435 {
2436 var rotB = this.rotation + Math.PI;
2437 if (rotB > Math.PI * 2) { rotB -= Math.PI * 2; }
2438 if (World.rayCast(this.x, this.y, rotB).distance > 5)
2439 {
2440 var forward = this.forwardVector(this.rotation);
2441 this.x -= forward.x * deltaTime * 40;
2442 this.y -= forward.y * deltaTime * 40;
2443 }
2444 }
2445 if (GameInput.isHeld(188))
2446 {
2447 this.horizontalResolution -= this.horizontalResolution * 0.1 * deltaTime;
2448 if (this.horizontalResolution < 30)
2449 { this.horizontalResolution = 30; }
2450 }
2451 if (GameInput.isHeld(190))
2452 {
2453 this.horizontalResolution += this.horizontalResolution * 0.1 * deltaTime;
2454 }
2455 }
2456};
2457
2458/*
2459 * End File:
2460 * /workspace/raytracer-work/src/player.js
2461 */
2462
2463/*
2464 * Start File:
2465 * /workspace/raytracer-work/src/npc.js
2466 */
2467/**
2468 * Paperdoll NPC billboards.
2469 * Compose body+gear on CPU when view/frame changes (cell ~32×48).
2470 * Relight once in cell space per (npc, view, light fingerprint), then project
2471 * with per-pixel depth into an offscreen RGBA buffer + z-buffer (perp depth,
2472 * same space as walls). One WebGL textured quad — no per-screen-pixel shade.
2473 */
2474var NpcSystem =
2475{
2476 npcs: [],
2477 bodySet: null,
2478 gearSet: null,
2479 ready: false,
2480 cache: {},
2481 litCache: {},
2482 worldScale: 32,
2483 _overlay: null,
2484 _overlayCtx: null,
2485 _overlayImg: null,
2486 _zbuf: null,
2487 _zbufW: 0,
2488 _zbufH: 0,
2489
2490 initEmpty: function ()
2491 {
2492 this.npcs = [];
2493 this.cache = {};
2494 this.litCache = {};
2495 this.ready = false;
2496 },
2497
2498 addNpc: function (opts)
2499 {
2500 this.npcs.push({
2501 x: opts.x,
2502 y: opts.y,
2503 z: opts.z != null ? opts.z : 0,
2504 facingDeg: opts.facingDeg || 0,
2505 clip: opts.clip || "walk",
2506 animating: opts.animating !== false,
2507 time: opts.time || 0,
2508 label: opts.label || "npc"
2509 });
2510 },
2511
2512 load: function (bodyBase, bodyPpda, gearBase, gearPpda)
2513 {
2514 var self = this;
2515 return PpdaAtlasRuntime.loadSet(bodyBase, bodyPpda).then(function (body)
2516 {
2517 self.bodySet = body;
2518 if (!gearBase)
2519 {
2520 self.ready = true;
2521 return body;
2522 }
2523 return PpdaAtlasRuntime.loadSet(gearBase, gearPpda).then(function (gear)
2524 {
2525 PpdaLoader.assertCompatible(body.ppda, gear.ppda);
2526 self.gearSet = gear;
2527 self.ready = true;
2528 return body;
2529 });
2530 });
2531 },
2532
2533 update: function (dt)
2534 {
2535 for (var i = 0; i < this.npcs.length; i++)
2536 {
2537 if (this.npcs[i].animating)
2538 { this.npcs[i].time += dt; }
2539 }
2540 },
2541
2542 composedFor: function (npc, pitch, yaw)
2543 {
2544 if (!this.bodySet)
2545 { return null; }
2546 var clip = PpdaViewFrame.findClip(this.bodySet.ppda, npc.clip);
2547 var frameCount = clip ? clip.frame_count : 1;
2548 var frame = PpdaViewFrame.frameIndex(npc.time, this.bodySet.ppda.fps, frameCount);
2549 var key = npc.clip + "|" + frame + "|" + pitch + "|" + yaw;
2550 if (this.cache[key])
2551 { return this.cache[key]; }
2552 var composed = PpdaAtlasRuntime.composeView(
2553 this.bodySet,
2554 this.gearSet,
2555 npc.clip,
2556 frame,
2557 pitch,
2558 yaw
2559 );
2560 this.cache[key] = composed;
2561 var keys = Object.keys(this.cache);
2562 if (keys.length > 96)
2563 { delete this.cache[keys[0]]; }
2564 return composed;
2565 },
2566
2567 _lightFingerprint: function (lights, ambient)
2568 {
2569 var s = String(ambient == null ? 0.38 : ambient);
2570 if (!lights || !lights.length)
2571 { return s; }
2572 var n = Math.min(lights.length, 8);
2573 for (var i = 0; i < n; i++)
2574 {
2575 var L = lights[i];
2576 s += "|" + (L.x | 0) + "," + (L.y | 0) + "," + ((L.z != null ? L.z : 16) | 0)
2577 + "," + ((L.intensity == null ? 1 : L.intensity) * 10 | 0)
2578 + "," + ((L.range || 64) | 0);
2579 }
2580 return s;
2581 },
2582
2583 /**
2584 * Shade the composed cell once (32×48) into a lit RGBA buffer.
2585 * Screen projection only samples this — no per-pixel Lighting on the sprite.
2586 */
2587 litCellFor: function (composed, npc, yaw, lights, ambient, heightM, metersToWorld, camDist, near, far)
2588 {
2589 var fp = this._lightFingerprint(lights, ambient);
2590 var key = (composed._cacheKey || "") + "|" + (npc.facingDeg || 0) + "|" + yaw
2591 + "|" + (npc.x | 0) + "," + (npc.y | 0) + "|" + fp;
2592 if (this.litCache[key])
2593 { return this.litCache[key]; }
2594
2595 var w = composed.width;
2596 var h = composed.height;
2597 var out = new Uint8ClampedArray(w * h * 4);
2598 var face = (npc.facingDeg || 0) * Math.PI / 180;
2599 var yawR = (yaw || 0) * Math.PI / 180;
2600 var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
2601 var frontX = Math.cos(face), frontY = Math.sin(face);
2602 var rightX = -Math.sin(face), rightY = Math.cos(face);
2603 var camX = rightX * camCX + frontX * camCZ;
2604 var camY = rightY * camCX + frontY * camCZ;
2605 var viewRightX = -camY;
2606 var viewRightY = camX;
2607
2608 for (var ty = 0; ty < h; ty++)
2609 {
2610 for (var tx = 0; tx < w; tx++)
2611 {
2612 var pi = ty * w + tx;
2613 var o = pi * 4;
2614 var a = composed.diffuse[o + 3];
2615 if (!a || composed.depthAlpha[pi] === 0)
2616 {
2617 out[o + 3] = 0;
2618 continue;
2619 }
2620 var u = (tx + 0.5) / w;
2621 var ar = composed.diffuse[o];
2622 var ag = composed.diffuse[o + 1];
2623 var ab = composed.diffuse[o + 2];
2624 var heightFrac = 1 - (ty + 0.5) / h;
2625 var pxZ = heightFrac * heightM * metersToWorld * 0.5;
2626 var depthM = near + (composed.depthGray[pi] / 65535) * (far - near);
2627 var depthOff = (depthM - camDist) * metersToWorld;
2628 var lat = (u - 0.5) * (heightM * metersToWorld * 0.45);
2629 var pxWorld = {
2630 x: npc.x + viewRightX * lat + camX * depthOff,
2631 y: npc.y + viewRightY * lat + camY * depthOff,
2632 z: pxZ + (npc.z || 0)
2633 };
2634 var nr = composed.normal ? composed.normal[o] : 128;
2635 var ng = composed.normal ? composed.normal[o + 1] : 128;
2636 var nb = composed.normal ? composed.normal[o + 2] : 255;
2637 var geoTiltX = (u - 0.5) * 2;
2638 var shaded;
2639 if (typeof Lighting !== "undefined")
2640 {
2641 shaded = Lighting.shadePaperdollPixel(
2642 ar, ag, ab, nr, ng, nb, pxWorld,
2643 lights || [], ambient, yaw, npc.facingDeg || 0, geoTiltX
2644 );
2645 }
2646 else
2647 {
2648 shaded = { r: ar, g: ag, b: ab };
2649 }
2650 out[o] = shaded.r;
2651 out[o + 1] = shaded.g;
2652 out[o + 2] = shaded.b;
2653 out[o + 3] = a;
2654 }
2655 }
2656 this.litCache[key] = out;
2657 var keys = Object.keys(this.litCache);
2658 if (keys.length > 64)
2659 { delete this.litCache[keys[0]]; }
2660 return out;
2661 },
2662
2663 _ensureOverlay: function (w, h)
2664 {
2665 if (!this._overlay || this._overlay.width !== w || this._overlay.height !== h)
2666 {
2667 this._overlay = document.createElement("canvas");
2668 this._overlay.width = w;
2669 this._overlay.height = h;
2670 this._overlayCtx = this._overlay.getContext("2d");
2671 this._overlayImg = null;
2672 this._overlayTex = null;
2673 this._zbuf = new Float32Array(w * h);
2674 this._zbufW = w;
2675 this._zbufH = h;
2676 }
2677 },
2678
2679 /**
2680 * @param {Float32Array} wallDepthPerCol length = screen width (perp depths)
2681 */
2682 draw: function (scene, player, wallDepthPerCol)
2683 {
2684 if (!this.ready || !this.bodySet)
2685 { return; }
2686
2687 var w = Math.round(scene.real_size.x);
2688 var h = Math.round(scene.real_size.y);
2689 this._ensureOverlay(w, h);
2690 var ctx = this._overlayCtx;
2691 ctx.clearRect(0, 0, w, h);
2692 var img = ctx.createImageData(w, h);
2693 var data = img.data;
2694 var zbuf = this._zbuf;
2695 var i;
2696 for (i = 0; i < w * h; i++)
2697 {
2698 var col = i % w;
2699 zbuf[i] = wallDepthPerCol[col];
2700 }
2701
2702 var ppda = this.bodySet.ppda;
2703 var heightM = (ppda.height_milli || 2600) / 1000;
2704 var camDist = ppda.camera_distance || 10;
2705 var near = ppda.depth_near;
2706 var far = ppda.depth_far;
2707 var metersToWorld = this.worldScale;
2708 var lights = World.level && World.level.lights;
2709 var ambient = World.level && World.level.ambient != null
2710 ? World.level.ambient : 0.38;
2711 var playerEyeZ = World.size * 0.5;
2712
2713 var list = this.npcs.slice().sort(function (a, b)
2714 {
2715 var da = Camera.perpDepth(a.x, a.y, player.x, player.y, player.rotation);
2716 var db = Camera.perpDepth(b.x, b.y, player.x, player.y, player.rotation);
2717 return db - da;
2718 });
2719
2720 for (var ni = 0; ni < list.length; ni++)
2721 {
2722 var npc = list[ni];
2723 var proj = Camera.projectSprite(npc.x, npc.y, player.x, player.y, player.rotation, w);
2724 if (!proj)
2725 { continue; }
2726 var dist = proj.depth;
2727 if (dist < 0.5 || dist > 800)
2728 { continue; }
2729 // Off-screen cull (allow some margin)
2730 if (proj.screenX < -w * 0.5 || proj.screenX > w * 1.5)
2731 { continue; }
2732
2733 var horiz = Math.sqrt(
2734 (npc.x - player.x) * (npc.x - player.x) +
2735 (npc.y - player.y) * (npc.y - player.y)
2736 );
2737 var npcCenterZ = (npc.z || 0) + heightM * metersToWorld * 0.25;
2738 var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg);
2739 var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws);
2740 // Pitch from height difference only — looking up/down must not tilt sprites.
2741 var pitch = PpdaViewFrame.pickPitchFromHeight(
2742 playerEyeZ, npcCenterZ, horiz, ppda.pitches
2743 );
2744
2745 var clipInfo = PpdaViewFrame.findClip(ppda, npc.clip);
2746 var frame = PpdaViewFrame.frameIndex(
2747 npc.time, ppda.fps, clipInfo ? clipInfo.frame_count : 1
2748 );
2749 var composed = this.composedFor(npc, pitch, yaw);
2750 if (!composed)
2751 { continue; }
2752 composed._cacheKey = npc.clip + "|" + frame + "|" + pitch + "|" + yaw;
2753
2754 var lit = this.litCellFor(
2755 composed, npc, yaw, lights || [], ambient,
2756 heightM, metersToWorld, camDist, near, far
2757 );
2758
2759 var spriteH = (World.size * heightM) * (h / dist) * 0.5;
2760 var aspect = composed.width / Math.max(1, composed.height);
2761 var spriteW = spriteH * aspect;
2762 var screenX = proj.screenX;
2763 // Horizon uses look pitch for floor alignment; atlas pitch does not.
2764 var mid = h / 2 + (-player.pitch * h * 0.25);
2765 var floorY = mid + (World.size * 0.5 * h) / dist;
2766 var left = screenX - spriteW / 2;
2767
2768 var feetRow = composed.height - 1;
2769 var feetH = composed.height;
2770 var feetW = composed.width;
2771 var feetAlpha = composed.diffuse;
2772 try
2773 {
2774 var bodyLayer = PpdaAtlasRuntime.layerFromSet(
2775 this.bodySet, npc.clip, frame, pitch, yaw
2776 );
2777 feetAlpha = bodyLayer.diffuse;
2778 feetW = bodyLayer.width;
2779 feetH = bodyLayer.height;
2780 feetRow = feetH - 1;
2781 }
2782 catch (e) { /* fallback: composed */ }
2783 for (var fy = feetH - 1; fy >= 0; fy--)
2784 {
2785 var rowHit = false;
2786 for (var fx = 0; fx < feetW; fx++)
2787 {
2788 if (feetAlpha[(fy * feetW + fx) * 4 + 3] > 10)
2789 { rowHit = true; break; }
2790 }
2791 if (rowHit)
2792 { feetRow = fy; break; }
2793 }
2794 var top = floorY - ((feetRow + 0.5) / feetH) * spriteH;
2795 var cols = Math.max(1, Math.ceil(spriteW));
2796
2797 for (var c = 0; c < cols; c++)
2798 {
2799 var sx = Math.floor(left + c);
2800 if (sx < 0 || sx >= w)
2801 { continue; }
2802 var u = (c + 0.5) / cols;
2803 var texX = Math.min(composed.width - 1, Math.max(0, Math.floor(u * composed.width)));
2804 var y0 = Math.floor(top);
2805 var y1 = Math.ceil(top + spriteH);
2806
2807 for (var sy = y0; sy < y1; sy++)
2808 {
2809 if (sy < 0 || sy >= h)
2810 { continue; }
2811 var v = (sy - top + 0.5) / spriteH;
2812 if (v < 0 || v >= 1)
2813 { continue; }
2814 var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
2815 var pi = texY * composed.width + texX;
2816 var a = lit[pi * 4 + 3];
2817 if (!a || composed.depthAlpha[pi] === 0)
2818 { continue; }
2819
2820 var depthM = near + (composed.depthGray[pi] / 65535) * (far - near);
2821 var pixelDist = dist + (depthM - camDist) * metersToWorld;
2822 if (pixelDist < 0.05)
2823 { pixelDist = 0.05; }
2824
2825 var zi = sy * w + sx;
2826 if (pixelDist >= zbuf[zi])
2827 { continue; }
2828 zbuf[zi] = pixelDist;
2829
2830 var o = zi * 4;
2831 data[o] = lit[pi * 4];
2832 data[o + 1] = lit[pi * 4 + 1];
2833 data[o + 2] = lit[pi * 4 + 2];
2834 data[o + 3] = a;
2835 }
2836 }
2837 }
2838
2839 ctx.putImageData(img, 0, 0);
2840 var glc = scene.glContext;
2841 if (this._overlayTex)
2842 {
2843 var gl = glc.gl;
2844 gl.bindTexture(gl.TEXTURE_2D, this._overlayTex);
2845 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._overlay);
2846 }
2847 else
2848 {
2849 var prevMin = glc.textureMinFilter;
2850 var prevMag = glc.textureMagFilter;
2851 glc.setDefaultTextureFilter(glc.gl.NEAREST, glc.gl.NEAREST);
2852 this._overlayTex = glc.getTexture(this._overlay);
2853 glc.textureMinFilter = prevMin;
2854 glc.textureMagFilter = prevMag;
2855 }
2856
2857 glc.drawSprite({
2858 texture: this._overlayTex,
2859 x: w / 2,
2860 y: h / 2,
2861 w: w,
2862 h: h,
2863 rotationDeg: 0,
2864 alpha: 1,
2865 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 }
2866 });
2867 }
2868};
2869
2870/*
2871 * End File:
2872 * /workspace/raytracer-work/src/npc.js
2873 */
2874
2875/*
2876 * Start File:
2877 * /workspace/raytracer-work/src/raycastScene.js
2878 */
2879/**
2880 * Fullscreen WebGL raycast view on frameworkv3.
2881 * Wall strips: one source texel column per screen column, NEAREST, tinted for shading.
2882 */
2883class RaycastScene extends Scene
2884{
2885 constructor (width, height)
2886 {
2887 super(0, 0, width, height, Scene.DisplayModes.absolute);
2888 this.backgroundColor = { r: 0, g: 0, b: 0 };
2889 this.tintShader = null;
2890 this.solidTexture = null;
2891 this.gunImages = null;
2892 this._lookBound = false;
2893 this.floorTexMap = null;
2894 this.floorImages = null;
2895 this._floorCanvas = null;
2896 this._floorCtx = null;
2897 this._floorTex = null;
2898 }
2899
2900 onLoad ()
2901 {
2902 const gl = this.glContext.gl;
2903 this.glContext.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);
2904
2905 this.tintShader = new Shader(Shader.DEFAULT_VERT, [
2906 "precision mediump float;",
2907 "uniform sampler2D u_texture;",
2908 "uniform float u_alpha;",
2909 "uniform vec3 u_tint;",
2910 "varying vec2 v_texCoord;",
2911 "void main() {",
2912 " vec4 color = texture2D(u_texture, v_texCoord);",
2913 " gl_FragColor = vec4(color.rgb * u_tint, color.a * u_alpha);",
2914 "}"
2915 ].join("\n"));
2916
2917 // 1x1 white for solid (untextured) walls.
2918 const c = document.createElement("canvas");
2919 c.width = 1;
2920 c.height = 1;
2921 const ctx = c.getContext("2d");
2922 ctx.fillStyle = "#ffffff";
2923 ctx.fillRect(0, 0, 1, 1);
2924 this.solidTexture = this.glContext.getTexture(c);
2925
2926 this.bindPointerLock();
2927 }
2928
2929 bindPointerLock ()
2930 {
2931 if (this._lookBound)
2932 { return; }
2933 this._lookBound = true;
2934 const canvas = this.cv_canvas;
2935 canvas.addEventListener("click", function ()
2936 {
2937 if (canvas.requestPointerLock)
2938 { canvas.requestPointerLock(); }
2939 });
2940 document.addEventListener("mousemove", function (e)
2941 {
2942 if (document.pointerLockElement === canvas)
2943 { Player.applyLookDelta(e.movementX || 0, e.movementY || 0); }
2944 });
2945 }
2946
2947 update (deltaTime)
2948 {
2949 super.update(deltaTime);
2950 Player.update(deltaTime);
2951 if (typeof NpcSystem !== "undefined")
2952 { NpcSystem.update(deltaTime); }
2953 if (Player.horizontalResolution > this.real_size.x)
2954 { Player.horizontalResolution = this.real_size.x; }
2955 }
2956
2957 draw ()
2958 {
2959 if (this.destroyed || !this.glContext)
2960 { return; }
2961
2962 this.g_fixSize();
2963 const glc = this.glContext;
2964 glc.endOffscreenPass();
2965 glc.clear(0, 0, 0, 1);
2966
2967 this.drawFloorCeiling();
2968 const wallDepth = this.drawColumns();
2969 if (typeof NpcSystem !== "undefined" && NpcSystem.ready)
2970 { NpcSystem.draw(this, Player, wallDepth); }
2971 this.drawGun();
2972 }
2973
2974
2975 setFloorTextures (texMap)
2976 {
2977 this.floorTexMap = texMap;
2978 }
2979
2980 setFloorImages (imgs)
2981 {
2982 this.floorImages = imgs;
2983 if (typeof FloorGpu !== "undefined")
2984 { FloorGpu.invalidateGrid(); }
2985 }
2986
2987 drawFloorCeiling ()
2988 {
2989 if (!World.level || !World.level.floors)
2990 { return; }
2991 const w = Math.max(1, Math.round(this.real_size.x));
2992 const h = Math.max(1, Math.round(this.real_size.y));
2993 const glc = this.glContext;
2994 if (typeof FloorGpu !== "undefined" && this.floorImages
2995 && FloorGpu.draw(glc, w, h, Player, World.level, this.floorImages, World.size))
2996 { return; }
2997 // CPU fallback (tests / missing GPU sources)
2998 if (!this.floorTexMap)
2999 { return; }
3000 if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)
3001 {
3002 this._floorCanvas = document.createElement("canvas");
3003 this._floorCanvas.width = w;
3004 this._floorCanvas.height = h;
3005 this._floorCtx = this._floorCanvas.getContext("2d");
3006 this._floorTex = null;
3007 }
3008 const img = this._floorCtx.createImageData(w, h);
3009 FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);
3010 this._floorCtx.putImageData(img, 0, 0);
3011 const gl = glc.gl;
3012 if (this._floorTex)
3013 {
3014 gl.bindTexture(gl.TEXTURE_2D, this._floorTex);
3015 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._floorCanvas);
3016 }
3017 else
3018 {
3019 glc.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);
3020 this._floorTex = glc.getTexture(this._floorCanvas);
3021 }
3022 glc.drawSprite({
3023 texture: this._floorTex,
3024 x: w / 2,
3025 y: h / 2,
3026 w: w,
3027 h: h,
3028 rotationDeg: 0,
3029 alpha: 1,
3030 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 }
3031 });
3032 }
3033
3034 faceLight (dir)
3035 {
3036 switch (dir)
3037 {
3038 case "east": return 0.9;
3039 case "west": return 0.8;
3040 case "south": return 0.7;
3041 default: return 1.0;
3042 }
3043 }
3044
3045 drawColumns ()
3046 {
3047 const glc = this.glContext;
3048 const w = this.real_size.x;
3049 const h = this.real_size.y;
3050 const cols = Math.max(1, Math.floor(Player.horizontalResolution));
3051 const widthLine = w / cols;
3052 const wallDepth = new Float32Array(Math.max(1, Math.round(w)));
3053 for (var zi = 0; zi < wallDepth.length; zi++)
3054 { wallDepth[zi] = 1e9; }
3055
3056 for (var i = 0; i < cols; i++)
3057 {
3058 var camX = Camera.camXFromColumn(i, cols);
3059 var rot = Camera.rayAngle(Player.rotation, camX);
3060 if (rot < 0) { rot += Math.PI * 2; }
3061 if (rot > Math.PI * 2) { rot -= Math.PI * 2; }
3062
3063 var rayHit = World.rayCast(Player.x, Player.y, rot);
3064 if (!rayHit || !rayHit.tile)
3065 { continue; }
3066
3067 // Perpendicular (camera-plane) depth — same space as NPC z-buffer.
3068 var dist = Camera.perpFromEuclid(rayHit.distance, Player.rotation, camX);
3069 if (dist < 0.0001)
3070 { dist = 0.0001; }
3071
3072 var xLine = i * widthLine;
3073 var wallH = (World.size * h) / dist;
3074 // Same horizon/pitch as FloorCast + NPC feet.
3075 var yCenter = (h / 2) + (-Player.pitch * h * 0.25);
3076
3077 var tint;
3078 var lights = World.level && World.level.lights;
3079 if (typeof Lighting !== "undefined" && lights && lights.length)
3080 {
3081 var nrm = Lighting.faceNormal(rayHit.dir);
3082 // Nudge into open space so LOS does not treat the wall cell as a blocker.
3083 var hitPos = {
3084 x: rayHit.endX + nrm.x * 0.6,
3085 y: rayHit.endY + nrm.y * 0.6,
3086 z: World.size * 0.5
3087 };
3088 var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;
3089 var los = {
3090 tiles: World.level.tiles,
3091 width: World.level.width,
3092 height: World.level.height,
3093 cellSize: World.size
3094 };
3095 var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);
3096 var face = this.faceLight(rayHit.dir);
3097 tint = [
3098 Math.min(2.2, lit.r * (0.65 + 0.35 * face)),
3099 Math.min(2.2, lit.g * (0.65 + 0.35 * face)),
3100 Math.min(2.2, lit.b * (0.65 + 0.35 * face))
3101 ];
3102 }
3103 else
3104 {
3105 var light = this.faceLight(rayHit.dir);
3106 tint = [light, light, light];
3107 }
3108 var htmlImage = null;
3109 var texW = 1;
3110
3111 // Z-buffer for NPC occlusion (per screen pixel column).
3112 var x0 = Math.max(0, Math.floor(xLine));
3113 var x1 = Math.min(wallDepth.length, Math.ceil(xLine + widthLine));
3114 for (var xz = x0; xz < x1; xz++)
3115 {
3116 if (dist < wallDepth[xz])
3117 { wallDepth[xz] = dist; }
3118 }
3119
3120 if (rayHit.tile.Image && rayHit.tile.Image.g_image)
3121 {
3122 htmlImage = rayHit.tile.Image.g_image;
3123 texW = htmlImage.width || 1;
3124 var uv = textureColumnUv(rayHit.tileX, texW);
3125 glc.drawSprite({
3126 texture: glc.getTexture(htmlImage),
3127 x: xLine + widthLine / 2,
3128 y: yCenter,
3129 w: widthLine,
3130 h: wallH,
3131 rotationDeg: 0,
3132 alpha: 1,
3133 uvRect: { u0: uv.u0, v0: uv.v0, u1: uv.u1, v1: uv.v1 },
3134 shader: this.tintShader,
3135 uniforms: { u_tint: tint }
3136 });
3137 }
3138 else
3139 {
3140 var c = rayHit.tile.Color || { R: 255, G: 255, B: 255 };
3141 tint = [(c.R / 255) * light, (c.G / 255) * light, (c.B / 255) * light];
3142 glc.drawSprite({
3143 texture: this.solidTexture,
3144 x: xLine + widthLine / 2,
3145 y: yCenter,
3146 w: widthLine,
3147 h: wallH,
3148 rotationDeg: 0,
3149 alpha: 1,
3150 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
3151 shader: this.tintShader,
3152 uniforms: { u_tint: tint }
3153 });
3154 }
3155 }
3156 return wallDepth;
3157 }
3158
3159 drawGun ()
3160 {
3161 const images = this.game && this.game.images;
3162 if (!images)
3163 { return; }
3164 var gunImg = null;
3165 switch (Player.currentGun)
3166 {
3167 case 0: gunImg = images.shotgun; break;
3168 case 1: gunImg = images.machinegun; break;
3169 case 2: gunImg = images.pulserifle; break;
3170 }
3171 if (!gunImg || !gunImg.g_image)
3172 { return; }
3173
3174 var p = this.real_size.y / 1080;
3175 var gw = p * gunImg.g_image.width;
3176 var gh = p * gunImg.g_image.height;
3177 var gx = this.real_size.x * Player.gunX + gw / 2;
3178 var gy = this.real_size.y * Player.gunY + gh / 2;
3179
3180 gunImg.draw(
3181 this,
3182 gx,
3183 gy,
3184 gw,
3185 gh,
3186 0,
3187 false,
3188 false,
3189 1,
3190 0
3191 );
3192 }
3193}
3194
3195/*
3196 * End File:
3197 * /workspace/raytracer-work/src/raycastScene.js
3198 */
3199
3200/*
3201 * Start File:
3202 * /workspace/raytracer-work/src/main.js
3203 */
3204console.log("Raytracer starting");
3205var game = new Game();
3206var levelPack = null;
3207
3208function queryLevelParam ()
3209{
3210 try
3211 {
3212 var q = new URLSearchParams(window.location.search);
3213 return q.get("level");
3214 }
3215 catch (e)
3216 { return null; }
3217}
3218
3219function extractTexPixels (img)
3220{
3221 var c = document.createElement("canvas");
3222 c.width = img.width;
3223 c.height = img.height;
3224 var ctx = c.getContext("2d");
3225 ctx.drawImage(img, 0, 0);
3226 return { rgba: ctx.getImageData(0, 0, c.width, c.height).data, w: c.width, h: c.height };
3227}
3228
3229function applyLevel (pack, indexOrId, scene)
3230{
3231 World.loadPack(pack);
3232 World.loadLevel(indexOrId);
3233 Player.resetToSpawn();
3234 NpcSystem.initEmpty();
3235 var npcs = World.level.npcs || [];
3236 for (var i = 0; i < npcs.length; i++)
3237 { NpcSystem.addNpc(npcs[i]); }
3238
3239 var body = npcs[0] && npcs[0].body ? npcs[0].body : "paperdolls/male-body/";
3240 var bodyPpda = npcs[0] && npcs[0].bodyPpda ? npcs[0].bodyPpda : "male-body-atlas.ppda";
3241 var gear = npcs[0] && npcs[0].gear ? npcs[0].gear : "paperdolls/male-sword/";
3242 var gearPpda = npcs[0] && npcs[0].gearPpda ? npcs[0].gearPpda : "male-sword-atlas.ppda";
3243 if (npcs.length)
3244 {
3245 NpcSystem.load(body, bodyPpda, gear, gearPpda).catch(function (err)
3246 { console.error("Paperdoll load failed", err); });
3247 }
3248 var title = document.getElementById("level-label");
3249 if (title)
3250 { title.textContent = World.level.name + " (" + (World.levelIndex + 1) + "/" + pack.levels.length + ")"; }
3251}
3252
3253window.onload = function ()
3254{
3255 game.preloadImagesThenStart(
3256 [
3257 { name: "stone", url: "images/stone.png" },
3258 { name: "wood", url: "images/wood.png" },
3259 { name: "shotgun", url: "images/shotgun.png" },
3260 { name: "machinegun", url: "images/machinegun.png" },
3261 { name: "pulserifle", url: "images/pulserifle.png" }
3262 ],
3263 function ()
3264 {
3265 Tiles.bindImages(game.images);
3266
3267 var packPromise;
3268 var q = null;
3269 try { q = new URLSearchParams(window.location.search); } catch (e) {}
3270 if (q && q.get("playtest") === "1")
3271 {
3272 packPromise = Promise.resolve().then(function ()
3273 {
3274 var raw = localStorage.getItem("raytracer-levels-v1");
3275 if (!raw) throw new Error("Geen editor-playtest in localStorage");
3276 return raw;
3277 });
3278 }
3279 else
3280 {
3281 packPromise = fetch("levels.json").then(function (r)
3282 {
3283 if (!r.ok)
3284 { throw new Error("levels.json HTTP " + r.status); }
3285 return r.text();
3286 });
3287 }
3288 packPromise.then(function (text)
3289 {
3290 levelPack = LevelFormat.parse(text);
3291 var w = Math.max(320, window.innerWidth - 2);
3292 var h = Math.max(240, window.innerHeight - 2);
3293 var scene = new RaycastScene(w, h);
3294 scene.npcLight = 1;
3295 scene.setFloorTextures({
3296 stone: extractTexPixels(game.images.stone.g_image),
3297 wood: extractTexPixels(game.images.wood.g_image)
3298 });
3299 scene.setFloorImages({
3300 stone: game.images.stone.g_image,
3301 wood: game.images.wood.g_image
3302 });
3303 game.loadScene(scene);
3304
3305 var want = queryLevelParam();
3306 var idx = LevelFormat.findLevelIndex(levelPack, want);
3307 if (idx < 0)
3308 { idx = 0; }
3309 applyLevel(levelPack, idx, scene);
3310
3311 window.addEventListener("resize", function ()
3312 {
3313 scene.size.x = Math.max(320, window.innerWidth - 2);
3314 scene.size.y = Math.max(240, window.innerHeight - 2);
3315 });
3316
3317 var prev = document.getElementById("btn-prev-level");
3318 var next = document.getElementById("btn-next-level");
3319 if (prev)
3320 {
3321 prev.onclick = function ()
3322 {
3323 var i = (World.levelIndex - 1 + levelPack.levels.length) % levelPack.levels.length;
3324 applyLevel(levelPack, i, scene);
3325 };
3326 }
3327 if (next)
3328 {
3329 next.onclick = function ()
3330 {
3331 var i = (World.levelIndex + 1) % levelPack.levels.length;
3332 applyLevel(levelPack, i, scene);
3333 };
3334 }
3335 }).catch(function (err)
3336 {
3337 console.error(err);
3338 alert("Kon levels.json niet laden: " + err.message);
3339 });
3340 }
3341 );
3342};
3343
3344/*
3345 * End File:
3346 * /workspace/raytracer-work/src/main.js
3347 */