Point lights for walls, floors, ceilings and paperdolls
Schema v2 with ambient + lights[] (migrate from v1). CPU Lambertian lighting with distance falloff and grid LOS; paperdolls use view-space normals from .ppda with L transformed into the chosen yaw view. Editor: place/drag/delete lamps with range circles. Tests for schema, attenuation, LOS, normal decode and view-space transform.
@@ -23,10 +23,11 @@ Besturing: WASD / pijltjes, klik voor pointer-lock, `<` `>` voor raycast-resolut
23
23
24
24
## Levels (`build/levels.json`)
25
25
26
Schema **format_version: 1**:
26
Schema **format_version: 2** (v1 migreert automatisch):
27
27
28
28
- `textures[]` – id + url (nu `stone` / `wood`, dezelfde set als muren)
29
- `levels[]` – per level: `id`, `name`, `width`/`height`, `cellSize`, `spawn{tileX,tileY,yawRad}`, `walls[]`, `floors[]`, `ceilings[]` (textuur-id of `null` = zwart), `npcs[]`, `lights[]` (nog leeg; gereserveerd)
29
- `levels[]` – per level: `id`, `name`, `width`/`height`, `cellSize`, `ambient` (0..1), `spawn{tileX,tileY,yawRad}`, `walls[]`, `floors[]`, `ceilings[]` (textuur-id of `null` = zwart), `npcs[]`, `lights[]`
30
- `lights[]` – `{id,x,y,z,color[r,g,b],intensity,range,falloff}` in world-units (cellSize=32)
30
31
31
32
Validatie en legacy-migratie: `src/levelFormat.js`.
32
33
@@ -34,6 +35,10 @@ Validatie en legacy-migratie: `src/levelFormat.js`.
34
35
35
36
Klassieke floor/ceiling casting (Lode-stijl) op de CPU → `ImageData` → één NEAREST WebGL-quad **onder** de muren. Motief: frameworkv3 is WebGL1-sprites zonder gedeelde depth buffer; een grid-data-texture-shader zou draw-order/z-buffer van paperdolls breken. Scanlines met 2×2 NEAREST-blocks houden het performant. `posZ = (cellSize/2)·screenH` koppelt de vloer aan dezelfde projectie als muurhoogte (anders bleef `rowDist` ≈ 1–2 en zag je één effen texel). Tiles zonder floor/ceiling blijven zwart/clear. NPC-voeten op het vloervlak (body-atlas, niet gear).
36
37
38
## Lampen
39
40
Point lights (CPU) op muren/vloer/plafond (N·L + afstand + grid-LOS) en op paperdolls via view-space normals uit `.ppda` (zelfde encoding als Paperdoll `relight`: RGB = n·0.5+0.5, view=+Z). Lichtvector wordt naar de gekozen yaw-view getransformeerd zodat een lamp links de linkerkant belicht. **CPU i.p.v. custom shader:** frameworkv3 is WebGL1-sprites zonder G-buffer; vloer/NPC’s zijn al CPU-ImageData — lighting past in die paden zonder extra GPU-pipeline. Zonder `lights[]` blijft de oude ambient/face-shade look.
41
37
42
## Level-editor
38
43
39
44
`build/editor.html`: meerdere levels toevoegen/hernoemen/verwijderen/dupliceren, grootte, muur/vloer/plafond schilderen (klik/sleep + texture-previews), spawn + NPC’s, download/upload JSON, localStorage, **Speel dit level**. Lampen volgen in een latere stap (`lights[]` staat al in het formaat).
@@ -23,10 +23,11 @@ Besturing: WASD / pijltjes, klik voor pointer-lock, `<` `>` voor raycast-resolut23
23
24
## Levels (`build/levels.json`)24
## Levels (`build/levels.json`)25
25
26
Schema **format_version: 1**:26
Schema **format_version: 2** (v1 migreert automatisch):27
27
28
- `textures[]` – id + url (nu `stone` / `wood`, dezelfde set als muren)28
- `textures[]` – id + url (nu `stone` / `wood`, dezelfde set als muren)29
- `levels[]` – per level: `id`, `name`, `width`/`height`, `cellSize`, `spawn{tileX,tileY,yawRad}`, `walls[]`, `floors[]`, `ceilings[]` (textuur-id of `null` = zwart), `npcs[]`, `lights[]` (nog leeg; gereserveerd)29
- `levels[]` – per level: `id`, `name`, `width`/`height`, `cellSize`, `ambient` (0..1), `spawn{tileX,tileY,yawRad}`, `walls[]`, `floors[]`, `ceilings[]` (textuur-id of `null` = zwart), `npcs[]`, `lights[]`30
- `lights[]` – `{id,x,y,z,color[r,g,b],intensity,range,falloff}` in world-units (cellSize=32)30
31
31
Validatie en legacy-migratie: `src/levelFormat.js`.32
Validatie en legacy-migratie: `src/levelFormat.js`.32
33
@@ -34,6 +35,10 @@ Validatie en legacy-migratie: `src/levelFormat.js`.34
35
35
Klassieke floor/ceiling casting (Lode-stijl) op de CPU → `ImageData` → één NEAREST WebGL-quad **onder** de muren. Motief: frameworkv3 is WebGL1-sprites zonder gedeelde depth buffer; een grid-data-texture-shader zou draw-order/z-buffer van paperdolls breken. Scanlines met 2×2 NEAREST-blocks houden het performant. `posZ = (cellSize/2)·screenH` koppelt de vloer aan dezelfde projectie als muurhoogte (anders bleef `rowDist` ≈ 1–2 en zag je één effen texel). Tiles zonder floor/ceiling blijven zwart/clear. NPC-voeten op het vloervlak (body-atlas, niet gear).36
Klassieke floor/ceiling casting (Lode-stijl) op de CPU → `ImageData` → één NEAREST WebGL-quad **onder** de muren. Motief: frameworkv3 is WebGL1-sprites zonder gedeelde depth buffer; een grid-data-texture-shader zou draw-order/z-buffer van paperdolls breken. Scanlines met 2×2 NEAREST-blocks houden het performant. `posZ = (cellSize/2)·screenH` koppelt de vloer aan dezelfde projectie als muurhoogte (anders bleef `rowDist` ≈ 1–2 en zag je één effen texel). Tiles zonder floor/ceiling blijven zwart/clear. NPC-voeten op het vloervlak (body-atlas, niet gear).36
37
38
## Lampen39
40
Point lights (CPU) op muren/vloer/plafond (N·L + afstand + grid-LOS) en op paperdolls via view-space normals uit `.ppda` (zelfde encoding als Paperdoll `relight`: RGB = n·0.5+0.5, view=+Z). Lichtvector wordt naar de gekozen yaw-view getransformeerd zodat een lamp links de linkerkant belicht. **CPU i.p.v. custom shader:** frameworkv3 is WebGL1-sprites zonder G-buffer; vloer/NPC’s zijn al CPU-ImageData — lighting past in die paden zonder extra GPU-pipeline. Zonder `lights[]` blijft de oude ambient/face-shade look.41
37
## Level-editor42
## Level-editor38
43
39
`build/editor.html`: meerdere levels toevoegen/hernoemen/verwijderen/dupliceren, grootte, muur/vloer/plafond schilderen (klik/sleep + texture-previews), spawn + NPC’s, download/upload JSON, localStorage, **Speel dit level**. Lampen volgen in een latere stap (`lights[]` staat al in het formaat).44
`build/editor.html`: meerdere levels toevoegen/hernoemen/verwijderen/dupliceren, grootte, muur/vloer/plafond schilderen (klik/sleep + texture-previews), spawn + NPC’s, download/upload JSON, localStorage, **Speel dit level**. Lampen volgen in een latere stap (`lights[]` staat al in het formaat).@@ -45,6 +45,7 @@
45
45
<button type="button" data-tool="ceiling">Plafond</button>
46
46
<button type="button" data-tool="spawn">Spawn</button>
47
47
<button type="button" data-tool="npc">NPC</button>
48
<button type="button" data-tool="light">Lamp</button>
48
49
</div>
49
50
<h2>Muurtypes</h2>
50
51
<div class="row">
@@ -68,6 +69,21 @@
68
69
<label><input type="checkbox" id="npc-anim" checked> Animeren</label>
69
70
<button type="button" id="btn-del-npc">Verwijder NPC</button>
70
71
<ul id="npc-list"></ul>
72
<h2>Ambient / lampen</h2>
73
<label>Ambient <input id="level-ambient" type="number" min="0" max="1" step="0.05" value="0.38" style="width:5em"></label>
74
<div class="row">
75
Z <input id="light-z" type="number" value="20" style="width:3.5em">
76
I <input id="light-intensity" type="number" value="1.2" step="0.1" style="width:3.5em">
77
R <input id="light-range" type="number" value="96" style="width:4em">
78
</div>
79
<div class="row">
80
RGB
81
<input id="light-cr" type="number" min="0" max="1" step="0.05" value="1" style="width:3.2em">
82
<input id="light-cg" type="number" min="0" max="1" step="0.05" value="0.9" style="width:3.2em">
83
<input id="light-cb" type="number" min="0" max="1" step="0.05" value="0.7" style="width:3.2em">
84
</div>
85
<button type="button" id="btn-del-light">Verwijder lamp</button>
86
<ul id="light-list"></ul>
71
87
<h2>Bestand</h2>
72
88
<div class="row">
73
89
<button type="button" id="btn-download">Download JSON</button>
@@ -45,6 +45,7 @@45
<button type="button" data-tool="ceiling">Plafond</button>45
<button type="button" data-tool="ceiling">Plafond</button>46
<button type="button" data-tool="spawn">Spawn</button>46
<button type="button" data-tool="spawn">Spawn</button>47
<button type="button" data-tool="npc">NPC</button>47
<button type="button" data-tool="npc">NPC</button>48
<button type="button" data-tool="light">Lamp</button>48
</div>49
</div>49
<h2>Muurtypes</h2>50
<h2>Muurtypes</h2>50
<div class="row">51
<div class="row">@@ -68,6 +69,21 @@68
<label><input type="checkbox" id="npc-anim" checked> Animeren</label>69
<label><input type="checkbox" id="npc-anim" checked> Animeren</label>69
<button type="button" id="btn-del-npc">Verwijder NPC</button>70
<button type="button" id="btn-del-npc">Verwijder NPC</button>70
<ul id="npc-list"></ul>71
<ul id="npc-list"></ul>72
<h2>Ambient / lampen</h2>73
<label>Ambient <input id="level-ambient" type="number" min="0" max="1" step="0.05" value="0.38" style="width:5em"></label>74
<div class="row">75
Z <input id="light-z" type="number" value="20" style="width:3.5em">76
I <input id="light-intensity" type="number" value="1.2" step="0.1" style="width:3.5em">77
R <input id="light-range" type="number" value="96" style="width:4em">78
</div>79
<div class="row">80
RGB81
<input id="light-cr" type="number" min="0" max="1" step="0.05" value="1" style="width:3.2em">82
<input id="light-cg" type="number" min="0" max="1" step="0.05" value="0.9" style="width:3.2em">83
<input id="light-cb" type="number" min="0" max="1" step="0.05" value="0.7" style="width:3.2em">84
</div>85
<button type="button" id="btn-del-light">Verwijder lamp</button>86
<ul id="light-list"></ul>71
<h2>Bestand</h2>87
<h2>Bestand</h2>72
<div class="row">88
<div class="row">73
<button type="button" id="btn-download">Download JSON</button>89
<button type="button" id="btn-download">Download JSON</button>@@ -1,16 +1,32 @@
1
1
2
2
/* /workspace/raytracer-work/src/levelFormat.js */
3
3
/**
4
* Level pack format (schema v1) for raytracer + editor.
5
* walls: tile type ids; floors/ceilings: texture id string or null (black).
6
* lights: reserved list (not rendered yet).
4
* Level pack format for raytracer + editor.
5
* v1: walls/floors/ceilings/npcs/lights[] (empty reserved)
6
* v2: lights fully specified + per-level ambient; migrate v1→v2.
7
7
*/
8
8
var LevelFormat =
9
9
{
10
CURRENT_VERSION: 1,
10
CURRENT_VERSION: 2,
11
11
MAX_SIZE: 128,
12
12
MAX_LEVELS: 64,
13
MAX_LIGHTS: 32,
13
14
KNOWN_TEXTURES: ["stone", "wood"],
15
DEFAULT_AMBIENT: 0.38,
16
17
emptyLight: function (x, y)
18
{
19
return {
20
id: "light-" + Date.now().toString(36),
21
x: x == null ? 48 : x,
22
y: y == null ? 48 : y,
23
z: 20,
24
color: [1, 0.9, 0.7],
25
intensity: 1.2,
26
range: 96,
27
falloff: 2
28
};
29
},
14
30
15
31
emptyLevel: function (name, width, height)
16
32
{
@@ -35,6 +51,7 @@ var LevelFormat =
35
51
width: width,
36
52
height: height,
37
53
cellSize: 32,
54
ambient: this.DEFAULT_AMBIENT,
38
55
spawn: { tileX: 1, tileY: 1, yawRad: 0 },
39
56
walls: walls,
40
57
floors: floors,
@@ -56,7 +73,6 @@ var LevelFormat =
56
73
};
57
74
},
58
75
59
/** Migrate legacy Levels[] (tiles only) into a pack. */
60
76
fromLegacyLevels: function (legacyArr, npcsByLevel)
61
77
{
62
78
var pack = this.defaultPack();
@@ -78,11 +94,8 @@ var LevelFormat =
78
94
width: L.width,
79
95
height: L.height,
80
96
cellSize: 32,
81
spawn: {
82
tileX: L.spawnX,
83
tileY: L.spawnY,
84
yawRad: 0
85
},
97
ambient: this.DEFAULT_AMBIENT,
98
spawn: { tileX: L.spawnX, tileY: L.spawnY, yawRad: 0 },
86
99
walls: L.tiles.slice(),
87
100
floors: floors,
88
101
ceilings: ceilings,
@@ -93,6 +106,62 @@ var LevelFormat =
93
106
return pack;
94
107
},
95
108
109
migratePack: function (pack)
110
{
111
if (!pack || typeof pack !== "object")
112
{ throw new Error("pack: root moet een object zijn"); }
113
var ver = pack.format_version;
114
if (ver === this.CURRENT_VERSION)
115
{ return pack; }
116
if (ver === 1)
117
{
118
pack.format_version = 2;
119
for (var i = 0; i < (pack.levels || []).length; i++)
120
{
121
var L = pack.levels[i];
122
if (typeof L.ambient !== "number")
123
{ L.ambient = this.DEFAULT_AMBIENT; }
124
if (!Array.isArray(L.lights))
125
{ L.lights = []; }
126
for (var li = 0; li < L.lights.length; li++)
127
{ this.normalizeLight(L.lights[li]); }
128
}
129
return pack;
130
}
131
throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1..2)");
132
},
133
134
normalizeLight: function (light)
135
{
136
if (!light || typeof light !== "object")
137
{ throw new Error("light: moet een object zijn"); }
138
if (typeof light.x !== "number" || typeof light.y !== "number")
139
{ throw new Error("light: x/y verplicht"); }
140
if (typeof light.z !== "number")
141
{ light.z = 20; }
142
if (!Array.isArray(light.color) || light.color.length < 3)
143
{ light.color = [1, 0.9, 0.7]; }
144
for (var c = 0; c < 3; c++)
145
{
146
var v = Number(light.color[c]);
147
if (!(v >= 0))
148
{ v = 0; }
149
// allow 0–255 UI values
150
if (v > 1)
151
{ v = v / 255; }
152
light.color[c] = v;
153
}
154
if (typeof light.intensity !== "number")
155
{ light.intensity = 1; }
156
if (typeof light.range !== "number" || light.range <= 0)
157
{ light.range = 96; }
158
if (typeof light.falloff !== "number")
159
{ light.falloff = 2; }
160
if (!light.id || typeof light.id !== "string")
161
{ light.id = "light-" + Math.floor(light.x) + "-" + Math.floor(light.y); }
162
return light;
163
},
164
96
165
validateTextureId: function (tex, allowNull)
97
166
{
98
167
if (tex == null || tex === "")
@@ -100,6 +169,22 @@ var LevelFormat =
100
169
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;
101
170
},
102
171
172
validateLight: function (light, index, levelPrefix)
173
{
174
var prefix = (levelPrefix || "level") + ".lights[" + (index == null ? "?" : index) + "]";
175
try
176
{ this.normalizeLight(light); }
177
catch (e)
178
{ throw new Error(prefix + ": " + e.message); }
179
if (light.intensity < 0 || light.intensity > 20)
180
{ throw new Error(prefix + ": intensity 0..20"); }
181
if (light.range > 2048)
182
{ throw new Error(prefix + ": range te groot"); }
183
if (light.falloff < 0.5 || light.falloff > 8)
184
{ throw new Error(prefix + ": falloff 0.5..8"); }
185
return light;
186
},
187
103
188
validateLevel: function (level, index)
104
189
{
105
190
var prefix = "level[" + (index == null ? "?" : index) + "]";
@@ -140,6 +225,14 @@ var LevelFormat =
140
225
{ throw new Error(prefix + ": npcs moet een array zijn"); }
141
226
if (!Array.isArray(level.lights))
142
227
{ level.lights = []; }
228
if (level.lights.length > this.MAX_LIGHTS)
229
{ throw new Error(prefix + ": te veel lights"); }
230
for (var li = 0; li < level.lights.length; li++)
231
{ this.validateLight(level.lights[li], li, prefix); }
232
if (typeof level.ambient !== "number")
233
{ level.ambient = this.DEFAULT_AMBIENT; }
234
if (level.ambient < 0 || level.ambient > 1)
235
{ throw new Error(prefix + ": ambient 0..1"); }
143
236
if (level.cellSize == null)
144
237
{ level.cellSize = 32; }
145
238
return level;
@@ -147,11 +240,9 @@ var LevelFormat =
147
240
148
241
validatePack: function (pack)
149
242
{
150
if (!pack || typeof pack !== "object")
151
{ throw new Error("pack: root moet een object zijn"); }
152
var ver = pack.format_version;
153
if (ver !== 1)
154
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }
243
pack = this.migratePack(pack);
244
if (pack.format_version !== this.CURRENT_VERSION)
245
{ throw new Error("pack: format_version " + pack.format_version + " niet ondersteund (wel: " + this.CURRENT_VERSION + ")"); }
155
246
if (!Array.isArray(pack.levels))
156
247
{ throw new Error("pack: levels moet een array zijn"); }
157
248
if (pack.levels.length > this.MAX_LEVELS)
@@ -181,7 +272,6 @@ var LevelFormat =
181
272
return this.validatePack(doc);
182
273
},
183
274
184
/** Runtime view used by World (tiles = walls). */
185
275
toRuntimeLevel: function (level)
186
276
{
187
277
return {
@@ -190,6 +280,7 @@ var LevelFormat =
190
280
width: level.width,
191
281
height: level.height,
192
282
cellSize: level.cellSize || 32,
283
ambient: typeof level.ambient === "number" ? level.ambient : this.DEFAULT_AMBIENT,
193
284
spawnX: level.spawn.tileX,
194
285
spawnY: level.spawn.tileY,
195
286
spawnYaw: level.spawn.yawRad || 0,
@@ -234,7 +325,8 @@ if (typeof module !== "undefined" && module.exports)
234
325
var STORAGE_KEY = "raytracer-levels-v1";
235
326
var pack = null;
236
327
var levelIndex = 0;
237
var tool = "wall"; // wall | floor | ceiling | spawn | npc
328
var tool = "wall"; // wall | floor | ceiling | spawn | npc | light
329
var selectedLight = -1;
238
330
var brushWall = 1;
239
331
var brushTex = "stone"; // or null via "none"
240
332
var cellPx = 28;
@@ -296,6 +388,36 @@ if (typeof module !== "undefined" && module.exports)
296
388
document.getElementById("level-w").value = level().width;
297
389
document.getElementById("level-h").value = level().height;
298
390
refreshNpcList();
391
refreshLightList();
392
}
393
394
function refreshLightList ()
395
{
396
var ul = document.getElementById("light-list");
397
if (!ul) return;
398
ul.innerHTML = "";
399
(level().lights || []).forEach(function (lamp, i)
400
{
401
var li = document.createElement("li");
402
li.textContent = (lamp.id || "light") + " @" + Math.round(lamp.x) + "," + Math.round(lamp.y)
403
+ " r" + Math.round(lamp.range || 0);
404
li.style.cursor = "pointer";
405
if (i === selectedLight) li.style.background = "#543";
406
li.onclick = function ()
407
{
408
selectedLight = i;
409
document.getElementById("light-z").value = lamp.z;
410
document.getElementById("light-intensity").value = lamp.intensity;
411
document.getElementById("light-range").value = lamp.range;
412
var c = lamp.color || [1, 0.9, 0.7];
413
document.getElementById("light-cr").value = c[0];
414
document.getElementById("light-cg").value = c[1];
415
document.getElementById("light-cb").value = c[2];
416
refreshLightList();
417
redraw();
418
};
419
ul.appendChild(li);
420
});
299
421
}
300
422
301
423
function refreshNpcList ()
@@ -394,6 +516,27 @@ if (typeof module !== "undefined" && module.exports)
394
516
ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";
395
517
ctx.fillRect(nx - 5, ny - 5, 10, 10);
396
518
});
519
(L.lights || []).forEach(function (lamp, i)
520
{
521
var lx = (lamp.x / (L.cellSize || 32)) * cellPx;
522
var ly = (lamp.y / (L.cellSize || 32)) * cellPx;
523
var rr = ((lamp.range || 64) / (L.cellSize || 32)) * cellPx;
524
ctx.strokeStyle = i === selectedLight ? "#ff0" : "rgba(255,220,80,0.45)";
525
ctx.beginPath();
526
ctx.arc(lx, ly, rr, 0, Math.PI * 2);
527
ctx.stroke();
528
var col = lamp.color || [1, 0.9, 0.5];
529
var R = Math.round((col[0] > 1 ? col[0] : col[0] * 255));
530
var G = Math.round((col[1] > 1 ? col[1] : col[1] * 255));
531
var B = Math.round((col[2] > 1 ? col[2] : col[2] * 255));
532
ctx.fillStyle = "rgb(" + R + "," + G + "," + B + ")";
533
ctx.beginPath();
534
ctx.arc(lx, ly, i === selectedLight ? 8 : 6, 0, Math.PI * 2);
535
ctx.fill();
536
ctx.strokeStyle = "#000";
537
ctx.stroke();
538
});
539
397
540
ctx.strokeStyle = "#333";
398
541
for (var gx = 0; gx <= L.width; gx++)
399
542
{
@@ -436,6 +579,23 @@ if (typeof module !== "undefined" && module.exports)
436
579
L.spawn.tileX = x;
437
580
L.spawn.tileY = y;
438
581
}
582
else if (tool === "light")
583
{
584
var csL = L.cellSize || 32;
585
if (!L.lights) L.lights = [];
586
var lamp = LevelFormat.emptyLight(x * csL + csL / 2, y * csL + csL / 2);
587
lamp.z = Number(document.getElementById("light-z").value) || 20;
588
lamp.intensity = Number(document.getElementById("light-intensity").value) || 1.2;
589
lamp.range = Number(document.getElementById("light-range").value) || 96;
590
lamp.color = [
591
Number(document.getElementById("light-cr").value) || 1,
592
Number(document.getElementById("light-cg").value) || 0.9,
593
Number(document.getElementById("light-cb").value) || 0.7
594
];
595
L.lights.push(lamp);
596
selectedLight = L.lights.length - 1;
597
refreshLightList();
598
}
439
599
else if (tool === "npc")
440
600
{
441
601
var cs = L.cellSize || 32;
@@ -581,23 +741,56 @@ if (typeof module !== "undefined" && module.exports)
581
741
};
582
742
});
583
743
744
var draggingLight = false;
584
745
canvas.onmousedown = function (e)
585
746
{
586
painting = true;
587
747
var c = cellFromEvent(e);
588
if (c)
589
{ paintAt(c.x, c.y); }
748
if (!c) return;
749
if (tool === "light")
750
{
751
var cs = level().cellSize || 32;
752
var wx = c.x * cs + cs / 2;
753
var wy = c.y * cs + cs / 2;
754
var hit = -1;
755
(level().lights || []).forEach(function (lamp, i)
756
{
757
var dx = lamp.x - wx, dy = lamp.y - wy;
758
if (dx * dx + dy * dy < (cs * 0.6) * (cs * 0.6)) hit = i;
759
});
760
if (hit >= 0)
761
{
762
selectedLight = hit;
763
draggingLight = true;
764
refreshLightList();
765
redraw();
766
return;
767
}
768
}
769
painting = true;
770
paintAt(c.x, c.y);
590
771
};
591
772
canvas.onmousemove = function (e)
592
773
{
593
if (!painting || tool === "spawn" || tool === "npc")
594
{ return; }
595
774
var c = cellFromEvent(e);
596
if (c)
597
{ paintAt(c.x, c.y); }
775
if (!c) return;
776
if (draggingLight && selectedLight >= 0 && level().lights[selectedLight])
777
{
778
var cs = level().cellSize || 32;
779
level().lights[selectedLight].x = c.x * cs + cs / 2;
780
level().lights[selectedLight].y = c.y * cs + cs / 2;
781
redraw();
782
return;
783
}
784
if (!painting || tool === "spawn" || tool === "npc" || tool === "light")
785
{ return; }
786
paintAt(c.x, c.y);
598
787
};
599
788
window.onmouseup = function ()
600
{ painting = false; };
789
{
790
if (draggingLight) { saveLocal(); refreshLightList(); }
791
painting = false;
792
draggingLight = false;
793
};
601
794
602
795
document.getElementById("spawn-yaw").onchange = function (e)
603
796
{
@@ -642,6 +835,46 @@ if (typeof module !== "undefined" && module.exports)
642
835
}
643
836
};
644
837
838
var ambEl = document.getElementById("level-ambient");
839
if (ambEl)
840
{
841
ambEl.value = level().ambient != null ? level().ambient : 0.38;
842
ambEl.onchange = function (e)
843
{
844
level().ambient = Number(e.target.value);
845
saveLocal();
846
};
847
}
848
document.getElementById("btn-del-light").onclick = function ()
849
{
850
if (selectedLight < 0 || !level().lights) return;
851
level().lights.splice(selectedLight, 1);
852
selectedLight = -1;
853
refreshLightList();
854
redraw();
855
saveLocal();
856
};
857
function applyLightProps ()
858
{
859
if (selectedLight < 0 || !level().lights[selectedLight]) return;
860
var lamp = level().lights[selectedLight];
861
lamp.z = Number(document.getElementById("light-z").value) || 20;
862
lamp.intensity = Number(document.getElementById("light-intensity").value) || 1;
863
lamp.range = Number(document.getElementById("light-range").value) || 96;
864
lamp.color = [
865
Number(document.getElementById("light-cr").value) || 1,
866
Number(document.getElementById("light-cg").value) || 0.9,
867
Number(document.getElementById("light-cb").value) || 0.7
868
];
869
redraw();
870
saveLocal();
871
}
872
["light-z","light-intensity","light-range","light-cr","light-cg","light-cb"].forEach(function (id)
873
{
874
var el = document.getElementById(id);
875
if (el) el.onchange = applyLightProps;
876
});
877
645
878
document.getElementById("btn-download").onclick = function ()
646
879
{
647
880
try
@@ -1,16 +1,32 @@1
1
2
/* /workspace/raytracer-work/src/levelFormat.js */2
/* /workspace/raytracer-work/src/levelFormat.js */3
/**3
/**4
* Level pack format (schema v1) for raytracer + editor.4
* Level pack format for raytracer + editor.5
* walls: tile type ids; floors/ceilings: texture id string or null (black).5
* v1: walls/floors/ceilings/npcs/lights[] (empty reserved)6
* lights: reserved list (not rendered yet).6
* v2: lights fully specified + per-level ambient; migrate v1→v2.7
*/7
*/8
var LevelFormat =8
var LevelFormat =9
{9
{10
CURRENT_VERSION: 1,10
CURRENT_VERSION: 2,11
MAX_SIZE: 128,11
MAX_SIZE: 128,12
MAX_LEVELS: 64,12
MAX_LEVELS: 64,13
MAX_LIGHTS: 32,13
KNOWN_TEXTURES: ["stone", "wood"],14
KNOWN_TEXTURES: ["stone", "wood"],15
DEFAULT_AMBIENT: 0.38,16
17
emptyLight: function (x, y)18
{19
return {20
id: "light-" + Date.now().toString(36),21
x: x == null ? 48 : x,22
y: y == null ? 48 : y,23
z: 20,24
color: [1, 0.9, 0.7],25
intensity: 1.2,26
range: 96,27
falloff: 228
};29
},14
30
15
emptyLevel: function (name, width, height)31
emptyLevel: function (name, width, height)16
{32
{@@ -35,6 +51,7 @@ var LevelFormat =35
width: width,51
width: width,36
height: height,52
height: height,37
cellSize: 32,53
cellSize: 32,54
ambient: this.DEFAULT_AMBIENT,38
spawn: { tileX: 1, tileY: 1, yawRad: 0 },55
spawn: { tileX: 1, tileY: 1, yawRad: 0 },39
walls: walls,56
walls: walls,40
floors: floors,57
floors: floors,@@ -56,7 +73,6 @@ var LevelFormat =56
};73
};57
},74
},58
75
59
/** Migrate legacy Levels[] (tiles only) into a pack. */60
fromLegacyLevels: function (legacyArr, npcsByLevel)76
fromLegacyLevels: function (legacyArr, npcsByLevel)61
{77
{62
var pack = this.defaultPack();78
var pack = this.defaultPack();@@ -78,11 +94,8 @@ var LevelFormat =78
width: L.width,94
width: L.width,79
height: L.height,95
height: L.height,80
cellSize: 32,96
cellSize: 32,81
spawn: {97
ambient: this.DEFAULT_AMBIENT,82
tileX: L.spawnX,98
spawn: { tileX: L.spawnX, tileY: L.spawnY, yawRad: 0 },83
tileY: L.spawnY,84
yawRad: 085
},86
walls: L.tiles.slice(),99
walls: L.tiles.slice(),87
floors: floors,100
floors: floors,88
ceilings: ceilings,101
ceilings: ceilings,@@ -93,6 +106,62 @@ var LevelFormat =93
return pack;106
return pack;94
},107
},95
108
109
migratePack: function (pack)110
{111
if (!pack || typeof pack !== "object")112
{ throw new Error("pack: root moet een object zijn"); }113
var ver = pack.format_version;114
if (ver === this.CURRENT_VERSION)115
{ return pack; }116
if (ver === 1)117
{118
pack.format_version = 2;119
for (var i = 0; i < (pack.levels || []).length; i++)120
{121
var L = pack.levels[i];122
if (typeof L.ambient !== "number")123
{ L.ambient = this.DEFAULT_AMBIENT; }124
if (!Array.isArray(L.lights))125
{ L.lights = []; }126
for (var li = 0; li < L.lights.length; li++)127
{ this.normalizeLight(L.lights[li]); }128
}129
return pack;130
}131
throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1..2)");132
},133
134
normalizeLight: function (light)135
{136
if (!light || typeof light !== "object")137
{ throw new Error("light: moet een object zijn"); }138
if (typeof light.x !== "number" || typeof light.y !== "number")139
{ throw new Error("light: x/y verplicht"); }140
if (typeof light.z !== "number")141
{ light.z = 20; }142
if (!Array.isArray(light.color) || light.color.length < 3)143
{ light.color = [1, 0.9, 0.7]; }144
for (var c = 0; c < 3; c++)145
{146
var v = Number(light.color[c]);147
if (!(v >= 0))148
{ v = 0; }149
// allow 0–255 UI values150
if (v > 1)151
{ v = v / 255; }152
light.color[c] = v;153
}154
if (typeof light.intensity !== "number")155
{ light.intensity = 1; }156
if (typeof light.range !== "number" || light.range <= 0)157
{ light.range = 96; }158
if (typeof light.falloff !== "number")159
{ light.falloff = 2; }160
if (!light.id || typeof light.id !== "string")161
{ light.id = "light-" + Math.floor(light.x) + "-" + Math.floor(light.y); }162
return light;163
},164
96
validateTextureId: function (tex, allowNull)165
validateTextureId: function (tex, allowNull)97
{166
{98
if (tex == null || tex === "")167
if (tex == null || tex === "")@@ -100,6 +169,22 @@ var LevelFormat =100
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;169
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;101
},170
},102
171
172
validateLight: function (light, index, levelPrefix)173
{174
var prefix = (levelPrefix || "level") + ".lights[" + (index == null ? "?" : index) + "]";175
try176
{ this.normalizeLight(light); }177
catch (e)178
{ throw new Error(prefix + ": " + e.message); }179
if (light.intensity < 0 || light.intensity > 20)180
{ throw new Error(prefix + ": intensity 0..20"); }181
if (light.range > 2048)182
{ throw new Error(prefix + ": range te groot"); }183
if (light.falloff < 0.5 || light.falloff > 8)184
{ throw new Error(prefix + ": falloff 0.5..8"); }185
return light;186
},187
103
validateLevel: function (level, index)188
validateLevel: function (level, index)104
{189
{105
var prefix = "level[" + (index == null ? "?" : index) + "]";190
var prefix = "level[" + (index == null ? "?" : index) + "]";@@ -140,6 +225,14 @@ var LevelFormat =140
{ throw new Error(prefix + ": npcs moet een array zijn"); }225
{ throw new Error(prefix + ": npcs moet een array zijn"); }141
if (!Array.isArray(level.lights))226
if (!Array.isArray(level.lights))142
{ level.lights = []; }227
{ level.lights = []; }228
if (level.lights.length > this.MAX_LIGHTS)229
{ throw new Error(prefix + ": te veel lights"); }230
for (var li = 0; li < level.lights.length; li++)231
{ this.validateLight(level.lights[li], li, prefix); }232
if (typeof level.ambient !== "number")233
{ level.ambient = this.DEFAULT_AMBIENT; }234
if (level.ambient < 0 || level.ambient > 1)235
{ throw new Error(prefix + ": ambient 0..1"); }143
if (level.cellSize == null)236
if (level.cellSize == null)144
{ level.cellSize = 32; }237
{ level.cellSize = 32; }145
return level;238
return level;@@ -147,11 +240,9 @@ var LevelFormat =147
240
148
validatePack: function (pack)241
validatePack: function (pack)149
{242
{150
if (!pack || typeof pack !== "object")243
pack = this.migratePack(pack);151
{ throw new Error("pack: root moet een object zijn"); }244
if (pack.format_version !== this.CURRENT_VERSION)152
var ver = pack.format_version;245
{ throw new Error("pack: format_version " + pack.format_version + " niet ondersteund (wel: " + this.CURRENT_VERSION + ")"); }153
if (ver !== 1)154
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }155
if (!Array.isArray(pack.levels))246
if (!Array.isArray(pack.levels))156
{ throw new Error("pack: levels moet een array zijn"); }247
{ throw new Error("pack: levels moet een array zijn"); }157
if (pack.levels.length > this.MAX_LEVELS)248
if (pack.levels.length > this.MAX_LEVELS)@@ -181,7 +272,6 @@ var LevelFormat =181
return this.validatePack(doc);272
return this.validatePack(doc);182
},273
},183
274
184
/** Runtime view used by World (tiles = walls). */185
toRuntimeLevel: function (level)275
toRuntimeLevel: function (level)186
{276
{187
return {277
return {@@ -190,6 +280,7 @@ var LevelFormat =190
width: level.width,280
width: level.width,191
height: level.height,281
height: level.height,192
cellSize: level.cellSize || 32,282
cellSize: level.cellSize || 32,283
ambient: typeof level.ambient === "number" ? level.ambient : this.DEFAULT_AMBIENT,193
spawnX: level.spawn.tileX,284
spawnX: level.spawn.tileX,194
spawnY: level.spawn.tileY,285
spawnY: level.spawn.tileY,195
spawnYaw: level.spawn.yawRad || 0,286
spawnYaw: level.spawn.yawRad || 0,@@ -234,7 +325,8 @@ if (typeof module !== "undefined" && module.exports)234
var STORAGE_KEY = "raytracer-levels-v1";325
var STORAGE_KEY = "raytracer-levels-v1";235
var pack = null;326
var pack = null;236
var levelIndex = 0;327
var levelIndex = 0;237
var tool = "wall"; // wall | floor | ceiling | spawn | npc328
var tool = "wall"; // wall | floor | ceiling | spawn | npc | light329
var selectedLight = -1;238
var brushWall = 1;330
var brushWall = 1;239
var brushTex = "stone"; // or null via "none"331
var brushTex = "stone"; // or null via "none"240
var cellPx = 28;332
var cellPx = 28;@@ -296,6 +388,36 @@ if (typeof module !== "undefined" && module.exports)296
document.getElementById("level-w").value = level().width;388
document.getElementById("level-w").value = level().width;297
document.getElementById("level-h").value = level().height;389
document.getElementById("level-h").value = level().height;298
refreshNpcList();390
refreshNpcList();391
refreshLightList();392
}393
394
function refreshLightList ()395
{396
var ul = document.getElementById("light-list");397
if (!ul) return;398
ul.innerHTML = "";399
(level().lights || []).forEach(function (lamp, i)400
{401
var li = document.createElement("li");402
li.textContent = (lamp.id || "light") + " @" + Math.round(lamp.x) + "," + Math.round(lamp.y)403
+ " r" + Math.round(lamp.range || 0);404
li.style.cursor = "pointer";405
if (i === selectedLight) li.style.background = "#543";406
li.onclick = function ()407
{408
selectedLight = i;409
document.getElementById("light-z").value = lamp.z;410
document.getElementById("light-intensity").value = lamp.intensity;411
document.getElementById("light-range").value = lamp.range;412
var c = lamp.color || [1, 0.9, 0.7];413
document.getElementById("light-cr").value = c[0];414
document.getElementById("light-cg").value = c[1];415
document.getElementById("light-cb").value = c[2];416
refreshLightList();417
redraw();418
};419
ul.appendChild(li);420
});299
}421
}300
422
301
function refreshNpcList ()423
function refreshNpcList ()@@ -394,6 +516,27 @@ if (typeof module !== "undefined" && module.exports)394
ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";516
ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";395
ctx.fillRect(nx - 5, ny - 5, 10, 10);517
ctx.fillRect(nx - 5, ny - 5, 10, 10);396
});518
});519
(L.lights || []).forEach(function (lamp, i)520
{521
var lx = (lamp.x / (L.cellSize || 32)) * cellPx;522
var ly = (lamp.y / (L.cellSize || 32)) * cellPx;523
var rr = ((lamp.range || 64) / (L.cellSize || 32)) * cellPx;524
ctx.strokeStyle = i === selectedLight ? "#ff0" : "rgba(255,220,80,0.45)";525
ctx.beginPath();526
ctx.arc(lx, ly, rr, 0, Math.PI * 2);527
ctx.stroke();528
var col = lamp.color || [1, 0.9, 0.5];529
var R = Math.round((col[0] > 1 ? col[0] : col[0] * 255));530
var G = Math.round((col[1] > 1 ? col[1] : col[1] * 255));531
var B = Math.round((col[2] > 1 ? col[2] : col[2] * 255));532
ctx.fillStyle = "rgb(" + R + "," + G + "," + B + ")";533
ctx.beginPath();534
ctx.arc(lx, ly, i === selectedLight ? 8 : 6, 0, Math.PI * 2);535
ctx.fill();536
ctx.strokeStyle = "#000";537
ctx.stroke();538
});539
397
ctx.strokeStyle = "#333";540
ctx.strokeStyle = "#333";398
for (var gx = 0; gx <= L.width; gx++)541
for (var gx = 0; gx <= L.width; gx++)399
{542
{@@ -436,6 +579,23 @@ if (typeof module !== "undefined" && module.exports)436
L.spawn.tileX = x;579
L.spawn.tileX = x;437
L.spawn.tileY = y;580
L.spawn.tileY = y;438
}581
}582
else if (tool === "light")583
{584
var csL = L.cellSize || 32;585
if (!L.lights) L.lights = [];586
var lamp = LevelFormat.emptyLight(x * csL + csL / 2, y * csL + csL / 2);587
lamp.z = Number(document.getElementById("light-z").value) || 20;588
lamp.intensity = Number(document.getElementById("light-intensity").value) || 1.2;589
lamp.range = Number(document.getElementById("light-range").value) || 96;590
lamp.color = [591
Number(document.getElementById("light-cr").value) || 1,592
Number(document.getElementById("light-cg").value) || 0.9,593
Number(document.getElementById("light-cb").value) || 0.7594
];595
L.lights.push(lamp);596
selectedLight = L.lights.length - 1;597
refreshLightList();598
}439
else if (tool === "npc")599
else if (tool === "npc")440
{600
{441
var cs = L.cellSize || 32;601
var cs = L.cellSize || 32;@@ -581,23 +741,56 @@ if (typeof module !== "undefined" && module.exports)581
};741
};582
});742
});583
743
744
var draggingLight = false;584
canvas.onmousedown = function (e)745
canvas.onmousedown = function (e)585
{746
{586
painting = true;587
var c = cellFromEvent(e);747
var c = cellFromEvent(e);588
if (c)748
if (!c) return;589
{ paintAt(c.x, c.y); }749
if (tool === "light")750
{751
var cs = level().cellSize || 32;752
var wx = c.x * cs + cs / 2;753
var wy = c.y * cs + cs / 2;754
var hit = -1;755
(level().lights || []).forEach(function (lamp, i)756
{757
var dx = lamp.x - wx, dy = lamp.y - wy;758
if (dx * dx + dy * dy < (cs * 0.6) * (cs * 0.6)) hit = i;759
});760
if (hit >= 0)761
{762
selectedLight = hit;763
draggingLight = true;764
refreshLightList();765
redraw();766
return;767
}768
}769
painting = true;770
paintAt(c.x, c.y);590
};771
};591
canvas.onmousemove = function (e)772
canvas.onmousemove = function (e)592
{773
{593
if (!painting || tool === "spawn" || tool === "npc")594
{ return; }595
var c = cellFromEvent(e);774
var c = cellFromEvent(e);596
if (c)775
if (!c) return;597
{ paintAt(c.x, c.y); }776
if (draggingLight && selectedLight >= 0 && level().lights[selectedLight])777
{778
var cs = level().cellSize || 32;779
level().lights[selectedLight].x = c.x * cs + cs / 2;780
level().lights[selectedLight].y = c.y * cs + cs / 2;781
redraw();782
return;783
}784
if (!painting || tool === "spawn" || tool === "npc" || tool === "light")785
{ return; }786
paintAt(c.x, c.y);598
};787
};599
window.onmouseup = function ()788
window.onmouseup = function ()600
{ painting = false; };789
{790
if (draggingLight) { saveLocal(); refreshLightList(); }791
painting = false;792
draggingLight = false;793
};601
794
602
document.getElementById("spawn-yaw").onchange = function (e)795
document.getElementById("spawn-yaw").onchange = function (e)603
{796
{@@ -642,6 +835,46 @@ if (typeof module !== "undefined" && module.exports)642
}835
}643
};836
};644
837
838
var ambEl = document.getElementById("level-ambient");839
if (ambEl)840
{841
ambEl.value = level().ambient != null ? level().ambient : 0.38;842
ambEl.onchange = function (e)843
{844
level().ambient = Number(e.target.value);845
saveLocal();846
};847
}848
document.getElementById("btn-del-light").onclick = function ()849
{850
if (selectedLight < 0 || !level().lights) return;851
level().lights.splice(selectedLight, 1);852
selectedLight = -1;853
refreshLightList();854
redraw();855
saveLocal();856
};857
function applyLightProps ()858
{859
if (selectedLight < 0 || !level().lights[selectedLight]) return;860
var lamp = level().lights[selectedLight];861
lamp.z = Number(document.getElementById("light-z").value) || 20;862
lamp.intensity = Number(document.getElementById("light-intensity").value) || 1;863
lamp.range = Number(document.getElementById("light-range").value) || 96;864
lamp.color = [865
Number(document.getElementById("light-cr").value) || 1,866
Number(document.getElementById("light-cg").value) || 0.9,867
Number(document.getElementById("light-cb").value) || 0.7868
];869
redraw();870
saveLocal();871
}872
["light-z","light-intensity","light-range","light-cr","light-cg","light-cb"].forEach(function (id)873
{874
var el = document.getElementById(id);875
if (el) el.onchange = applyLightProps;876
});877
645
document.getElementById("btn-download").onclick = function ()878
document.getElementById("btn-download").onclick = function ()646
{879
{647
try880
try@@ -800,16 +800,32 @@ if (typeof module !== "undefined" && module.exports)
800
800
* /workspace/raytracer-work/src/levelFormat.js
801
801
*/
802
802
/**
803
* Level pack format (schema v1) for raytracer + editor.
804
* walls: tile type ids; floors/ceilings: texture id string or null (black).
805
* lights: reserved list (not rendered yet).
803
* Level pack format for raytracer + editor.
804
* v1: walls/floors/ceilings/npcs/lights[] (empty reserved)
805
* v2: lights fully specified + per-level ambient; migrate v1→v2.
806
806
*/
807
807
var LevelFormat =
808
808
{
809
CURRENT_VERSION: 1,
809
CURRENT_VERSION: 2,
810
810
MAX_SIZE: 128,
811
811
MAX_LEVELS: 64,
812
MAX_LIGHTS: 32,
812
813
KNOWN_TEXTURES: ["stone", "wood"],
814
DEFAULT_AMBIENT: 0.38,
815
816
emptyLight: function (x, y)
817
{
818
return {
819
id: "light-" + Date.now().toString(36),
820
x: x == null ? 48 : x,
821
y: y == null ? 48 : y,
822
z: 20,
823
color: [1, 0.9, 0.7],
824
intensity: 1.2,
825
range: 96,
826
falloff: 2
827
};
828
},
813
829
814
830
emptyLevel: function (name, width, height)
815
831
{
@@ -834,6 +850,7 @@ var LevelFormat =
834
850
width: width,
835
851
height: height,
836
852
cellSize: 32,
853
ambient: this.DEFAULT_AMBIENT,
837
854
spawn: { tileX: 1, tileY: 1, yawRad: 0 },
838
855
walls: walls,
839
856
floors: floors,
@@ -855,7 +872,6 @@ var LevelFormat =
855
872
};
856
873
},
857
874
858
/** Migrate legacy Levels[] (tiles only) into a pack. */
859
875
fromLegacyLevels: function (legacyArr, npcsByLevel)
860
876
{
861
877
var pack = this.defaultPack();
@@ -877,11 +893,8 @@ var LevelFormat =
877
893
width: L.width,
878
894
height: L.height,
879
895
cellSize: 32,
880
spawn: {
881
tileX: L.spawnX,
882
tileY: L.spawnY,
883
yawRad: 0
884
},
896
ambient: this.DEFAULT_AMBIENT,
897
spawn: { tileX: L.spawnX, tileY: L.spawnY, yawRad: 0 },
885
898
walls: L.tiles.slice(),
886
899
floors: floors,
887
900
ceilings: ceilings,
@@ -892,6 +905,62 @@ var LevelFormat =
892
905
return pack;
893
906
},
894
907
908
migratePack: function (pack)
909
{
910
if (!pack || typeof pack !== "object")
911
{ throw new Error("pack: root moet een object zijn"); }
912
var ver = pack.format_version;
913
if (ver === this.CURRENT_VERSION)
914
{ return pack; }
915
if (ver === 1)
916
{
917
pack.format_version = 2;
918
for (var i = 0; i < (pack.levels || []).length; i++)
919
{
920
var L = pack.levels[i];
921
if (typeof L.ambient !== "number")
922
{ L.ambient = this.DEFAULT_AMBIENT; }
923
if (!Array.isArray(L.lights))
924
{ L.lights = []; }
925
for (var li = 0; li < L.lights.length; li++)
926
{ this.normalizeLight(L.lights[li]); }
927
}
928
return pack;
929
}
930
throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1..2)");
931
},
932
933
normalizeLight: function (light)
934
{
935
if (!light || typeof light !== "object")
936
{ throw new Error("light: moet een object zijn"); }
937
if (typeof light.x !== "number" || typeof light.y !== "number")
938
{ throw new Error("light: x/y verplicht"); }
939
if (typeof light.z !== "number")
940
{ light.z = 20; }
941
if (!Array.isArray(light.color) || light.color.length < 3)
942
{ light.color = [1, 0.9, 0.7]; }
943
for (var c = 0; c < 3; c++)
944
{
945
var v = Number(light.color[c]);
946
if (!(v >= 0))
947
{ v = 0; }
948
// allow 0–255 UI values
949
if (v > 1)
950
{ v = v / 255; }
951
light.color[c] = v;
952
}
953
if (typeof light.intensity !== "number")
954
{ light.intensity = 1; }
955
if (typeof light.range !== "number" || light.range <= 0)
956
{ light.range = 96; }
957
if (typeof light.falloff !== "number")
958
{ light.falloff = 2; }
959
if (!light.id || typeof light.id !== "string")
960
{ light.id = "light-" + Math.floor(light.x) + "-" + Math.floor(light.y); }
961
return light;
962
},
963
895
964
validateTextureId: function (tex, allowNull)
896
965
{
897
966
if (tex == null || tex === "")
@@ -899,6 +968,22 @@ var LevelFormat =
899
968
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;
900
969
},
901
970
971
validateLight: function (light, index, levelPrefix)
972
{
973
var prefix = (levelPrefix || "level") + ".lights[" + (index == null ? "?" : index) + "]";
974
try
975
{ this.normalizeLight(light); }
976
catch (e)
977
{ throw new Error(prefix + ": " + e.message); }
978
if (light.intensity < 0 || light.intensity > 20)
979
{ throw new Error(prefix + ": intensity 0..20"); }
980
if (light.range > 2048)
981
{ throw new Error(prefix + ": range te groot"); }
982
if (light.falloff < 0.5 || light.falloff > 8)
983
{ throw new Error(prefix + ": falloff 0.5..8"); }
984
return light;
985
},
986
902
987
validateLevel: function (level, index)
903
988
{
904
989
var prefix = "level[" + (index == null ? "?" : index) + "]";
@@ -939,6 +1024,14 @@ var LevelFormat =
939
1024
{ throw new Error(prefix + ": npcs moet een array zijn"); }
940
1025
if (!Array.isArray(level.lights))
941
1026
{ level.lights = []; }
1027
if (level.lights.length > this.MAX_LIGHTS)
1028
{ throw new Error(prefix + ": te veel lights"); }
1029
for (var li = 0; li < level.lights.length; li++)
1030
{ this.validateLight(level.lights[li], li, prefix); }
1031
if (typeof level.ambient !== "number")
1032
{ level.ambient = this.DEFAULT_AMBIENT; }
1033
if (level.ambient < 0 || level.ambient > 1)
1034
{ throw new Error(prefix + ": ambient 0..1"); }
942
1035
if (level.cellSize == null)
943
1036
{ level.cellSize = 32; }
944
1037
return level;
@@ -946,11 +1039,9 @@ var LevelFormat =
946
1039
947
1040
validatePack: function (pack)
948
1041
{
949
if (!pack || typeof pack !== "object")
950
{ throw new Error("pack: root moet een object zijn"); }
951
var ver = pack.format_version;
952
if (ver !== 1)
953
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }
1042
pack = this.migratePack(pack);
1043
if (pack.format_version !== this.CURRENT_VERSION)
1044
{ throw new Error("pack: format_version " + pack.format_version + " niet ondersteund (wel: " + this.CURRENT_VERSION + ")"); }
954
1045
if (!Array.isArray(pack.levels))
955
1046
{ throw new Error("pack: levels moet een array zijn"); }
956
1047
if (pack.levels.length > this.MAX_LEVELS)
@@ -980,7 +1071,6 @@ var LevelFormat =
980
1071
return this.validatePack(doc);
981
1072
},
982
1073
983
/** Runtime view used by World (tiles = walls). */
984
1074
toRuntimeLevel: function (level)
985
1075
{
986
1076
return {
@@ -989,6 +1079,7 @@ var LevelFormat =
989
1079
width: level.width,
990
1080
height: level.height,
991
1081
cellSize: level.cellSize || 32,
1082
ambient: typeof level.ambient === "number" ? level.ambient : this.DEFAULT_AMBIENT,
992
1083
spawnX: level.spawn.tileX,
993
1084
spawnY: level.spawn.tileY,
994
1085
spawnYaw: level.spawn.yawRad || 0,
@@ -1167,13 +1258,31 @@ var FloorCast =
1167
1258
if (texId && texMap[texId])
1168
1259
{
1169
1260
var tex = texMap[texId];
1170
// World-space UV so texels shrink toward the horizon.
1171
1261
var u = wx / cellSize;
1172
1262
var vv = wy / cellSize;
1173
1263
var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);
1174
r = (c[0] * shade) | 0;
1175
g = (c[1] * shade) | 0;
1176
b = (c[2] * shade) | 0;
1264
var wz = isCeil ? cellSize : 0;
1265
var nrm = isCeil
1266
? { x: 0, y: 0, z: -1 }
1267
: { x: 0, y: 0, z: 1 };
1268
var lights = level.lights || [];
1269
var ambient = level.ambient != null ? level.ambient : 0.38;
1270
var lit;
1271
if (typeof Lighting !== "undefined" && lights.length)
1272
{
1273
var los = level.tiles
1274
? { tiles: level.tiles, width: lw, height: lh, cellSize: cellSize }
1275
: null;
1276
lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, los);
1277
}
1278
else
1279
{
1280
// No lamps: keep previous distance shade look.
1281
lit = { r: shade, g: shade, b: shade };
1282
}
1283
r = Math.min(255, (c[0] * lit.r) | 0);
1284
g = Math.min(255, (c[1] * lit.g) | 0);
1285
b = Math.min(255, (c[2] * lit.b) | 0);
1177
1286
}
1178
1287
}
1179
1288
for (var dy = 0; dy < step && sy + dy < screenH; dy++)
@@ -1201,6 +1310,268 @@ if (typeof module !== "undefined" && module.exports)
1201
1310
* /workspace/raytracer-work/src/floorCast.js
1202
1311
*/
1203
1312
1313
/*
1314
* Start File:
1315
* /workspace/raytracer-work/src/lighting.js
1316
*/
1317
/**
1318
* Point lights for the raycaster (CPU).
1319
* Walls/floor/ceiling: Lambertian N·L + distance falloff + optional grid LOS.
1320
* Paperdolls: same lights, L transformed into the .ppda view space (view=+Z)
1321
* so baked normals respond correctly (see Paperdoll compositor.rs relight).
1322
*
1323
* CPU (not a custom WebGL shader): frameworkv3 is sprite/WebGL1 without a
1324
* shared G-buffer; floor is already an ImageData upload, walls are 1px
1325
* columns, NPCs are a CPU z-buffer overlay — lighting fits those paths with
1326
* no extra GPU pipeline. Grid LOS is O(steps) per sample and capped by
1327
* light range; cheaper than raymarched shadows and enough for tile maps.
1328
*/
1329
var Lighting =
1330
{
1331
DEFAULT_AMBIENT: 0.38,
1332
MAX_LIGHTS: 32,
1333
1334
normalize3: function (x, y, z)
1335
{
1336
var len = Math.sqrt(x * x + y * y + z * z);
1337
if (len < 1e-8)
1338
{ return { x: 0, y: 0, z: 1 }; }
1339
return { x: x / len, y: y / len, z: z / len };
1340
},
1341
1342
decodeNormalRgb: function (r, g, b)
1343
{
1344
return this.normalize3(
1345
r / 255 * 2 - 1,
1346
g / 255 * 2 - 1,
1347
b / 255 * 2 - 1
1348
);
1349
},
1350
1351
/** intensity * saturate(1 - dist/range)^falloff */
1352
attenuation: function (dist, range, falloff)
1353
{
1354
if (range <= 0)
1355
{ return 0; }
1356
var t = 1 - dist / range;
1357
if (t <= 0)
1358
{ return 0; }
1359
var f = falloff == null ? 2 : falloff;
1360
if (f === 1)
1361
{ return t; }
1362
if (f === 2)
1363
{ return t * t; }
1364
return Math.pow(t, f);
1365
},
1366
1367
faceNormal: function (dir)
1368
{
1369
switch (dir)
1370
{
1371
case "north": return { x: 0, y: -1, z: 0 };
1372
case "south": return { x: 0, y: 1, z: 0 };
1373
case "east": return { x: 1, y: 0, z: 0 };
1374
case "west": return { x: -1, y: 0, z: 0 };
1375
case "floor": return { x: 0, y: 0, z: 1 };
1376
case "ceiling": return { x: 0, y: 0, z: -1 };
1377
default: return { x: 0, y: 0, z: 1 };
1378
}
1379
},
1380
1381
/**
1382
* Grid line-of-sight on the wall map (Bresenham). Endpoints are the light
1383
* and sample tiles; a solid wall strictly between blocks the ray.
1384
*/
1385
hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
1386
{
1387
cellSize = cellSize || 32;
1388
var tx0 = Math.floor(x0 / cellSize);
1389
var ty0 = Math.floor(y0 / cellSize);
1390
var tx1 = Math.floor(x1 / cellSize);
1391
var ty1 = Math.floor(y1 / cellSize);
1392
var dx = Math.abs(tx1 - tx0);
1393
var dy = Math.abs(ty1 - ty0);
1394
var sx = tx0 < tx1 ? 1 : -1;
1395
var sy = ty0 < ty1 ? 1 : -1;
1396
var err = dx - dy;
1397
var x = tx0;
1398
var y = ty0;
1399
var steps = 0;
1400
var maxSteps = dx + dy + 2;
1401
while (!(x === tx1 && y === ty1) && steps < maxSteps)
1402
{
1403
steps++;
1404
var e2 = 2 * err;
1405
if (e2 > -dy) { err -= dy; x += sx; }
1406
if (e2 < dx) { err += dx; y += sy; }
1407
if (x === tx1 && y === ty1)
1408
{ break; }
1409
if (x < 0 || y < 0 || x >= mapW || y >= mapH)
1410
{ return false; }
1411
var id = tiles[x + y * mapW];
1412
if (id === 1 || id === 3)
1413
{ return false; }
1414
}
1415
return true;
1416
},
1417
1418
/**
1419
* RGB multipliers (can exceed 1 before clamp by caller).
1420
* @param {{x,y,z}} pos world
1421
* @param {{x,y,z}} normal unit
1422
* @param {Array} lights
1423
* @param {number} ambient
1424
* @param {object|null} los { tiles, width, height, cellSize } or null to skip
1425
*/
1426
shadeRgb: function (pos, normal, lights, ambient, los)
1427
{
1428
ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
1429
var r = ambient;
1430
var g = ambient;
1431
var b = ambient;
1432
if (!lights || !lights.length)
1433
{ return { r: r, g: g, b: b }; }
1434
var n = Math.min(lights.length, this.MAX_LIGHTS);
1435
for (var i = 0; i < n; i++)
1436
{
1437
var L = lights[i];
1438
var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;
1439
var dx = lx - pos.x;
1440
var dy = ly - pos.y;
1441
var dz = lz - pos.z;
1442
var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
1443
var att = this.attenuation(dist, L.range || 64, L.falloff);
1444
if (att <= 0.001)
1445
{ continue; }
1446
if (los && !this.hasLineOfSight(lx, ly, pos.x, pos.y, los.tiles, los.width, los.height, los.cellSize))
1447
{ continue; }
1448
var ld = this.normalize3(dx, dy, dz);
1449
var ndotl = normal.x * ld.x + normal.y * ld.y + normal.z * ld.z;
1450
if (ndotl <= 0)
1451
{ continue; }
1452
var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
1453
var cr = L.color ? L.color[0] : 1;
1454
var cg = L.color ? L.color[1] : 1;
1455
var cb = L.color ? L.color[2] : 1;
1456
r += inten * cr;
1457
g += inten * cg;
1458
b += inten * cb;
1459
}
1460
return { r: r, g: g, b: b };
1461
},
1462
1463
/**
1464
* Transform a world-space direction (toward light) into paperdoll view space
1465
* for the chosen yaw (degrees). View +Z = toward capture camera (= front at yaw 0).
1466
* Character +Z (front) aligns with facingDeg in the XY plane; +Y = world up (Z).
1467
*/
1468
worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
1469
{
1470
var face = (facingDeg || 0) * Math.PI / 180;
1471
var yaw = (yawDeg || 0) * Math.PI / 180;
1472
// Character basis in world (XY) + up Z
1473
var frontX = Math.cos(face);
1474
var frontY = Math.sin(face);
1475
var rightX = -Math.sin(face);
1476
var rightY = Math.cos(face);
1477
// Camera direction from character (char space): yaw 0 → +Z front
1478
var camCX = Math.sin(yaw);
1479
var camCZ = Math.cos(yaw);
1480
var camX = rightX * camCX + frontX * camCZ;
1481
var camY = rightY * camCX + frontY * camCZ;
1482
// viewZ = camDir (toward camera), viewY = up, viewX = viewY × viewZ
1483
var viewZx = camX, viewZy = camY, viewZz = 0;
1484
var viewYx = 0, viewYy = 0, viewYz = 1;
1485
// cross(up, viewZ) for right-handed viewX? Standard: viewX = normalize(cross(viewY?))
1486
// viewX = cross(viewY, viewZ) with viewY=up → (-viewZy, viewZx, 0) wait:
1487
// cross((0,0,1), (camX,camY,0)) = (-camY, camX, 0)
1488
var viewXx = -camY;
1489
var viewXy = camX;
1490
var viewXz = 0;
1491
var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
1492
if (vlen > 1e-8)
1493
{ viewXx /= vlen; viewXy /= vlen; }
1494
return this.normalize3(
1495
dirX * viewXx + dirY * viewXy + dirZ * viewXz,
1496
dirX * viewYx + dirY * viewYy + dirZ * viewYz,
1497
dirX * viewZx + dirY * viewZy + dirZ * viewZz
1498
);
1499
},
1500
1501
/**
1502
* Relight one paperdoll pixel (albedo RGB + view-space normal) with point lights.
1503
* pixelWorld ≈ NPC base + height from atlas row; depth shifts along view cam.
1504
*/
1505
shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg)
1506
{
1507
ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
1508
var n = this.decodeNormalRgb(nr, ng, nb);
1509
var r = ambient * albedoR;
1510
var g = ambient * albedoG;
1511
var b = ambient * albedoB;
1512
if (!lights || !lights.length)
1513
{
1514
// Match old preview-ish fill when no lamps: slight Lambert from default view light
1515
var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);
1516
var shade = Math.min(1, 0.35 + 0.65 * nd);
1517
return {
1518
r: Math.min(255, Math.round(albedoR * shade)),
1519
g: Math.min(255, Math.round(albedoG * shade)),
1520
b: Math.min(255, Math.round(albedoB * shade))
1521
};
1522
}
1523
var count = Math.min(lights.length, this.MAX_LIGHTS);
1524
for (var i = 0; i < count; i++)
1525
{
1526
var L = lights[i];
1527
var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;
1528
var dx = lx - pixelWorld.x;
1529
var dy = ly - pixelWorld.y;
1530
var dz = lz - pixelWorld.z;
1531
var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
1532
var att = this.attenuation(dist, L.range || 64, L.falloff);
1533
if (att <= 0.001)
1534
{ continue; }
1535
var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);
1536
var ndotl = n.x * lv.x + n.y * lv.y + n.z * lv.z;
1537
if (ndotl <= 0)
1538
{ continue; }
1539
var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
1540
var cr = L.color ? L.color[0] : 1;
1541
var cg = L.color ? L.color[1] : 1;
1542
var cb = L.color ? L.color[2] : 1;
1543
r += albedoR * inten * cr;
1544
g += albedoG * inten * cg;
1545
b += albedoB * inten * cb;
1546
}
1547
return {
1548
r: Math.min(255, Math.round(r)),
1549
g: Math.min(255, Math.round(g)),
1550
b: Math.min(255, Math.round(b))
1551
};
1552
},
1553
1554
/** Legacy wall face shade (no lamps) — keep look of pre-light builds. */
1555
legacyFaceShade: function (dir)
1556
{
1557
switch (dir)
1558
{
1559
case "east": return 0.9;
1560
case "west": return 0.8;
1561
case "south": return 0.7;
1562
default: return 1.0;
1563
}
1564
}
1565
};
1566
1567
if (typeof module !== "undefined" && module.exports)
1568
{ module.exports = Lighting; }
1569
1570
/*
1571
* End File:
1572
* /workspace/raytracer-work/src/lighting.js
1573
*/
1574
1204
1575
/*
1205
1576
* Start File:
1206
1577
* /workspace/raytracer-work/src/levels.js
@@ -1788,7 +2159,7 @@ var NpcSystem =
1788
2159
var feetRow = composed.height - 1;
1789
2160
var feetH = composed.height;
1790
2161
var feetW = composed.width;
1791
var feetAlpha = composed.lit;
2162
var feetAlpha = composed.diffuse;
1792
2163
try
1793
2164
{
1794
2165
var bodyLayer = PpdaAtlasRuntime.layerFromSet(
@@ -1833,7 +2204,7 @@ var NpcSystem =
1833
2204
{ continue; }
1834
2205
var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
1835
2206
var pi = texY * composed.width + texX;
1836
var a = composed.lit[pi * 4 + 3];
2207
var a = composed.diffuse[pi * 4 + 3];
1837
2208
if (!a || composed.depthAlpha[pi] === 0)
1838
2209
{ continue; }
1839
2210
@@ -1848,9 +2219,51 @@ var NpcSystem =
1848
2219
zbuf[zi] = pixelDist;
1849
2220
1850
2221
var o = zi * 4;
1851
data[o] = Math.min(255, Math.round(composed.lit[pi * 4] * tint));
1852
data[o + 1] = Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint));
1853
data[o + 2] = Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint));
2222
var ar = composed.diffuse[pi * 4];
2223
var ag = composed.diffuse[pi * 4 + 1];
2224
var ab = composed.diffuse[pi * 4 + 2];
2225
var lights = World.level && World.level.lights;
2226
var ambient = World.level && World.level.ambient != null
2227
? World.level.ambient : 0.38;
2228
// Pixel world: NPC feet + height from atlas v + depth along view cam.
2229
var heightFrac = 1 - (texY + 0.5) / composed.height;
2230
var pxZ = heightFrac * heightM * metersToWorld * 0.5;
2231
var depthOff = (depthM - camDist) * metersToWorld;
2232
var face = (npc.facingDeg || 0) * Math.PI / 180;
2233
var yawR = (yaw || 0) * Math.PI / 180;
2234
var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
2235
var frontX = Math.cos(face), frontY = Math.sin(face);
2236
var rightX = -Math.sin(face), rightY = Math.cos(face);
2237
var camX = rightX * camCX + frontX * camCZ;
2238
var camY = rightY * camCX + frontY * camCZ;
2239
var lat = (u - 0.5) * (heightM * metersToWorld * 0.35);
2240
var pxWorld = {
2241
x: npc.x + (-camY) * lat + camX * depthOff,
2242
y: npc.y + (camX) * lat + camY * depthOff,
2243
z: pxZ
2244
};
2245
var nr = composed.normal ? composed.normal[pi * 4] : 128;
2246
var ng = composed.normal ? composed.normal[pi * 4 + 1] : 128;
2247
var nb = composed.normal ? composed.normal[pi * 4 + 2] : 255;
2248
var shaded;
2249
if (typeof Lighting !== "undefined")
2250
{
2251
shaded = Lighting.shadePaperdollPixel(
2252
ar, ag, ab, nr, ng, nb, pxWorld,
2253
lights || [], ambient, yaw, npc.facingDeg || 0
2254
);
2255
}
2256
else
2257
{
2258
shaded = {
2259
r: Math.min(255, Math.round(composed.lit[pi * 4] * tint)),
2260
g: Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint)),
2261
b: Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint))
2262
};
2263
}
2264
data[o] = shaded.r;
2265
data[o + 1] = shaded.g;
2266
data[o + 2] = shaded.b;
1854
2267
data[o + 3] = a;
1855
2268
}
1856
2269
}
@@ -2074,7 +2487,6 @@ class RaycastScene extends Scene
2074
2487
if (!rayHit || !rayHit.tile)
2075
2488
{ continue; }
2076
2489
2077
var light = this.faceLight(rayHit.dir);
2078
2490
var deltaAngle = Player.rotation - rot;
2079
2491
var dist = rayHit.distance * Math.cos(deltaAngle);
2080
2492
if (dist < 0.0001)
@@ -2085,7 +2497,33 @@ class RaycastScene extends Scene
2085
2497
// Same horizon/pitch as FloorCast + NPC feet.
2086
2498
var yCenter = (h / 2) + (-Player.pitch * h * 0.25);
2087
2499
2088
var tint = [light, light, light];
2500
var tint;
2501
var lights = World.level && World.level.lights;
2502
if (typeof Lighting !== "undefined" && lights && lights.length)
2503
{
2504
var nrm = Lighting.faceNormal(rayHit.dir);
2505
var hitPos = {
2506
x: rayHit.endX,
2507
y: rayHit.endY,
2508
z: World.size * 0.5
2509
};
2510
var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;
2511
var los = {
2512
tiles: World.level.tiles,
2513
width: World.level.width,
2514
height: World.level.height,
2515
cellSize: World.size
2516
};
2517
var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);
2518
// Soften with legacy face shade so side walls stay readable.
2519
var face = this.faceLight(rayHit.dir);
2520
tint = [Math.min(1.8, lit.r * face), Math.min(1.8, lit.g * face), Math.min(1.8, lit.b * face)];
2521
}
2522
else
2523
{
2524
var light = this.faceLight(rayHit.dir);
2525
tint = [light, light, light];
2526
}
2089
2527
var htmlImage = null;
2090
2528
var texW = 1;
2091
2529
@@ -800,16 +800,32 @@ if (typeof module !== "undefined" && module.exports)800
* /workspace/raytracer-work/src/levelFormat.js800
* /workspace/raytracer-work/src/levelFormat.js801
*/ 801
*/ 802
/**802
/**803
* Level pack format (schema v1) for raytracer + editor.803
* Level pack format for raytracer + editor.804
* walls: tile type ids; floors/ceilings: texture id string or null (black).804
* v1: walls/floors/ceilings/npcs/lights[] (empty reserved)805
* lights: reserved list (not rendered yet).805
* v2: lights fully specified + per-level ambient; migrate v1→v2.806
*/806
*/807
var LevelFormat =807
var LevelFormat =808
{808
{809
CURRENT_VERSION: 1,809
CURRENT_VERSION: 2,810
MAX_SIZE: 128,810
MAX_SIZE: 128,811
MAX_LEVELS: 64,811
MAX_LEVELS: 64,812
MAX_LIGHTS: 32,812
KNOWN_TEXTURES: ["stone", "wood"],813
KNOWN_TEXTURES: ["stone", "wood"],814
DEFAULT_AMBIENT: 0.38,815
816
emptyLight: function (x, y)817
{818
return {819
id: "light-" + Date.now().toString(36),820
x: x == null ? 48 : x,821
y: y == null ? 48 : y,822
z: 20,823
color: [1, 0.9, 0.7],824
intensity: 1.2,825
range: 96,826
falloff: 2827
};828
},813
829
814
emptyLevel: function (name, width, height)830
emptyLevel: function (name, width, height)815
{831
{@@ -834,6 +850,7 @@ var LevelFormat =834
width: width,850
width: width,835
height: height,851
height: height,836
cellSize: 32,852
cellSize: 32,853
ambient: this.DEFAULT_AMBIENT,837
spawn: { tileX: 1, tileY: 1, yawRad: 0 },854
spawn: { tileX: 1, tileY: 1, yawRad: 0 },838
walls: walls,855
walls: walls,839
floors: floors,856
floors: floors,@@ -855,7 +872,6 @@ var LevelFormat =855
};872
};856
},873
},857
874
858
/** Migrate legacy Levels[] (tiles only) into a pack. */859
fromLegacyLevels: function (legacyArr, npcsByLevel)875
fromLegacyLevels: function (legacyArr, npcsByLevel)860
{876
{861
var pack = this.defaultPack();877
var pack = this.defaultPack();@@ -877,11 +893,8 @@ var LevelFormat =877
width: L.width,893
width: L.width,878
height: L.height,894
height: L.height,879
cellSize: 32,895
cellSize: 32,880
spawn: {896
ambient: this.DEFAULT_AMBIENT,881
tileX: L.spawnX,897
spawn: { tileX: L.spawnX, tileY: L.spawnY, yawRad: 0 },882
tileY: L.spawnY,883
yawRad: 0884
},885
walls: L.tiles.slice(),898
walls: L.tiles.slice(),886
floors: floors,899
floors: floors,887
ceilings: ceilings,900
ceilings: ceilings,@@ -892,6 +905,62 @@ var LevelFormat =892
return pack;905
return pack;893
},906
},894
907
908
migratePack: function (pack)909
{910
if (!pack || typeof pack !== "object")911
{ throw new Error("pack: root moet een object zijn"); }912
var ver = pack.format_version;913
if (ver === this.CURRENT_VERSION)914
{ return pack; }915
if (ver === 1)916
{917
pack.format_version = 2;918
for (var i = 0; i < (pack.levels || []).length; i++)919
{920
var L = pack.levels[i];921
if (typeof L.ambient !== "number")922
{ L.ambient = this.DEFAULT_AMBIENT; }923
if (!Array.isArray(L.lights))924
{ L.lights = []; }925
for (var li = 0; li < L.lights.length; li++)926
{ this.normalizeLight(L.lights[li]); }927
}928
return pack;929
}930
throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1..2)");931
},932
933
normalizeLight: function (light)934
{935
if (!light || typeof light !== "object")936
{ throw new Error("light: moet een object zijn"); }937
if (typeof light.x !== "number" || typeof light.y !== "number")938
{ throw new Error("light: x/y verplicht"); }939
if (typeof light.z !== "number")940
{ light.z = 20; }941
if (!Array.isArray(light.color) || light.color.length < 3)942
{ light.color = [1, 0.9, 0.7]; }943
for (var c = 0; c < 3; c++)944
{945
var v = Number(light.color[c]);946
if (!(v >= 0))947
{ v = 0; }948
// allow 0–255 UI values949
if (v > 1)950
{ v = v / 255; }951
light.color[c] = v;952
}953
if (typeof light.intensity !== "number")954
{ light.intensity = 1; }955
if (typeof light.range !== "number" || light.range <= 0)956
{ light.range = 96; }957
if (typeof light.falloff !== "number")958
{ light.falloff = 2; }959
if (!light.id || typeof light.id !== "string")960
{ light.id = "light-" + Math.floor(light.x) + "-" + Math.floor(light.y); }961
return light;962
},963
895
validateTextureId: function (tex, allowNull)964
validateTextureId: function (tex, allowNull)896
{965
{897
if (tex == null || tex === "")966
if (tex == null || tex === "")@@ -899,6 +968,22 @@ var LevelFormat =899
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;968
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;900
},969
},901
970
971
validateLight: function (light, index, levelPrefix)972
{973
var prefix = (levelPrefix || "level") + ".lights[" + (index == null ? "?" : index) + "]";974
try975
{ this.normalizeLight(light); }976
catch (e)977
{ throw new Error(prefix + ": " + e.message); }978
if (light.intensity < 0 || light.intensity > 20)979
{ throw new Error(prefix + ": intensity 0..20"); }980
if (light.range > 2048)981
{ throw new Error(prefix + ": range te groot"); }982
if (light.falloff < 0.5 || light.falloff > 8)983
{ throw new Error(prefix + ": falloff 0.5..8"); }984
return light;985
},986
902
validateLevel: function (level, index)987
validateLevel: function (level, index)903
{988
{904
var prefix = "level[" + (index == null ? "?" : index) + "]";989
var prefix = "level[" + (index == null ? "?" : index) + "]";@@ -939,6 +1024,14 @@ var LevelFormat =939
{ throw new Error(prefix + ": npcs moet een array zijn"); }1024
{ throw new Error(prefix + ": npcs moet een array zijn"); }940
if (!Array.isArray(level.lights))1025
if (!Array.isArray(level.lights))941
{ level.lights = []; }1026
{ level.lights = []; }1027
if (level.lights.length > this.MAX_LIGHTS)1028
{ throw new Error(prefix + ": te veel lights"); }1029
for (var li = 0; li < level.lights.length; li++)1030
{ this.validateLight(level.lights[li], li, prefix); }1031
if (typeof level.ambient !== "number")1032
{ level.ambient = this.DEFAULT_AMBIENT; }1033
if (level.ambient < 0 || level.ambient > 1)1034
{ throw new Error(prefix + ": ambient 0..1"); }942
if (level.cellSize == null)1035
if (level.cellSize == null)943
{ level.cellSize = 32; }1036
{ level.cellSize = 32; }944
return level;1037
return level;@@ -946,11 +1039,9 @@ var LevelFormat =946
1039
947
validatePack: function (pack)1040
validatePack: function (pack)948
{1041
{949
if (!pack || typeof pack !== "object")1042
pack = this.migratePack(pack);950
{ throw new Error("pack: root moet een object zijn"); }1043
if (pack.format_version !== this.CURRENT_VERSION)951
var ver = pack.format_version;1044
{ throw new Error("pack: format_version " + pack.format_version + " niet ondersteund (wel: " + this.CURRENT_VERSION + ")"); }952
if (ver !== 1)953
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }954
if (!Array.isArray(pack.levels))1045
if (!Array.isArray(pack.levels))955
{ throw new Error("pack: levels moet een array zijn"); }1046
{ throw new Error("pack: levels moet een array zijn"); }956
if (pack.levels.length > this.MAX_LEVELS)1047
if (pack.levels.length > this.MAX_LEVELS)@@ -980,7 +1071,6 @@ var LevelFormat =980
return this.validatePack(doc);1071
return this.validatePack(doc);981
},1072
},982
1073
983
/** Runtime view used by World (tiles = walls). */984
toRuntimeLevel: function (level)1074
toRuntimeLevel: function (level)985
{1075
{986
return {1076
return {@@ -989,6 +1079,7 @@ var LevelFormat =989
width: level.width,1079
width: level.width,990
height: level.height,1080
height: level.height,991
cellSize: level.cellSize || 32,1081
cellSize: level.cellSize || 32,1082
ambient: typeof level.ambient === "number" ? level.ambient : this.DEFAULT_AMBIENT,992
spawnX: level.spawn.tileX,1083
spawnX: level.spawn.tileX,993
spawnY: level.spawn.tileY,1084
spawnY: level.spawn.tileY,994
spawnYaw: level.spawn.yawRad || 0,1085
spawnYaw: level.spawn.yawRad || 0,@@ -1167,13 +1258,31 @@ var FloorCast =1167
if (texId && texMap[texId])1258
if (texId && texMap[texId])1168
{1259
{1169
var tex = texMap[texId];1260
var tex = texMap[texId];1170
// World-space UV so texels shrink toward the horizon.1171
var u = wx / cellSize;1261
var u = wx / cellSize;1172
var vv = wy / cellSize;1262
var vv = wy / cellSize;1173
var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);1263
var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);1174
r = (c[0] * shade) | 0;1264
var wz = isCeil ? cellSize : 0;1175
g = (c[1] * shade) | 0;1265
var nrm = isCeil1176
b = (c[2] * shade) | 0;1266
? { x: 0, y: 0, z: -1 }1267
: { x: 0, y: 0, z: 1 };1268
var lights = level.lights || [];1269
var ambient = level.ambient != null ? level.ambient : 0.38;1270
var lit;1271
if (typeof Lighting !== "undefined" && lights.length)1272
{1273
var los = level.tiles1274
? { tiles: level.tiles, width: lw, height: lh, cellSize: cellSize }1275
: null;1276
lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, los);1277
}1278
else1279
{1280
// No lamps: keep previous distance shade look.1281
lit = { r: shade, g: shade, b: shade };1282
}1283
r = Math.min(255, (c[0] * lit.r) | 0);1284
g = Math.min(255, (c[1] * lit.g) | 0);1285
b = Math.min(255, (c[2] * lit.b) | 0);1177
}1286
}1178
}1287
}1179
for (var dy = 0; dy < step && sy + dy < screenH; dy++)1288
for (var dy = 0; dy < step && sy + dy < screenH; dy++)@@ -1201,6 +1310,268 @@ if (typeof module !== "undefined" && module.exports)1201
* /workspace/raytracer-work/src/floorCast.js1310
* /workspace/raytracer-work/src/floorCast.js1202
*/ 1311
*/ 1203
1312
1313
/*1314
* Start File:1315
* /workspace/raytracer-work/src/lighting.js1316
*/ 1317
/**1318
* Point lights for the raycaster (CPU).1319
* Walls/floor/ceiling: Lambertian N·L + distance falloff + optional grid LOS.1320
* Paperdolls: same lights, L transformed into the .ppda view space (view=+Z)1321
* so baked normals respond correctly (see Paperdoll compositor.rs relight).1322
*1323
* CPU (not a custom WebGL shader): frameworkv3 is sprite/WebGL1 without a1324
* shared G-buffer; floor is already an ImageData upload, walls are 1px1325
* columns, NPCs are a CPU z-buffer overlay — lighting fits those paths with1326
* no extra GPU pipeline. Grid LOS is O(steps) per sample and capped by1327
* light range; cheaper than raymarched shadows and enough for tile maps.1328
*/1329
var Lighting =1330
{1331
DEFAULT_AMBIENT: 0.38,1332
MAX_LIGHTS: 32,1333
1334
normalize3: function (x, y, z)1335
{1336
var len = Math.sqrt(x * x + y * y + z * z);1337
if (len < 1e-8)1338
{ return { x: 0, y: 0, z: 1 }; }1339
return { x: x / len, y: y / len, z: z / len };1340
},1341
1342
decodeNormalRgb: function (r, g, b)1343
{1344
return this.normalize3(1345
r / 255 * 2 - 1,1346
g / 255 * 2 - 1,1347
b / 255 * 2 - 11348
);1349
},1350
1351
/** intensity * saturate(1 - dist/range)^falloff */1352
attenuation: function (dist, range, falloff)1353
{1354
if (range <= 0)1355
{ return 0; }1356
var t = 1 - dist / range;1357
if (t <= 0)1358
{ return 0; }1359
var f = falloff == null ? 2 : falloff;1360
if (f === 1)1361
{ return t; }1362
if (f === 2)1363
{ return t * t; }1364
return Math.pow(t, f);1365
},1366
1367
faceNormal: function (dir)1368
{1369
switch (dir)1370
{1371
case "north": return { x: 0, y: -1, z: 0 };1372
case "south": return { x: 0, y: 1, z: 0 };1373
case "east": return { x: 1, y: 0, z: 0 };1374
case "west": return { x: -1, y: 0, z: 0 };1375
case "floor": return { x: 0, y: 0, z: 1 };1376
case "ceiling": return { x: 0, y: 0, z: -1 };1377
default: return { x: 0, y: 0, z: 1 };1378
}1379
},1380
1381
/**1382
* Grid line-of-sight on the wall map (Bresenham). Endpoints are the light1383
* and sample tiles; a solid wall strictly between blocks the ray.1384
*/1385
hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)1386
{1387
cellSize = cellSize || 32;1388
var tx0 = Math.floor(x0 / cellSize);1389
var ty0 = Math.floor(y0 / cellSize);1390
var tx1 = Math.floor(x1 / cellSize);1391
var ty1 = Math.floor(y1 / cellSize);1392
var dx = Math.abs(tx1 - tx0);1393
var dy = Math.abs(ty1 - ty0);1394
var sx = tx0 < tx1 ? 1 : -1;1395
var sy = ty0 < ty1 ? 1 : -1;1396
var err = dx - dy;1397
var x = tx0;1398
var y = ty0;1399
var steps = 0;1400
var maxSteps = dx + dy + 2;1401
while (!(x === tx1 && y === ty1) && steps < maxSteps)1402
{1403
steps++;1404
var e2 = 2 * err;1405
if (e2 > -dy) { err -= dy; x += sx; }1406
if (e2 < dx) { err += dx; y += sy; }1407
if (x === tx1 && y === ty1)1408
{ break; }1409
if (x < 0 || y < 0 || x >= mapW || y >= mapH)1410
{ return false; }1411
var id = tiles[x + y * mapW];1412
if (id === 1 || id === 3)1413
{ return false; }1414
}1415
return true;1416
},1417
1418
/**1419
* RGB multipliers (can exceed 1 before clamp by caller).1420
* @param {{x,y,z}} pos world1421
* @param {{x,y,z}} normal unit1422
* @param {Array} lights1423
* @param {number} ambient1424
* @param {object|null} los { tiles, width, height, cellSize } or null to skip1425
*/1426
shadeRgb: function (pos, normal, lights, ambient, los)1427
{1428
ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;1429
var r = ambient;1430
var g = ambient;1431
var b = ambient;1432
if (!lights || !lights.length)1433
{ return { r: r, g: g, b: b }; }1434
var n = Math.min(lights.length, this.MAX_LIGHTS);1435
for (var i = 0; i < n; i++)1436
{1437
var L = lights[i];1438
var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;1439
var dx = lx - pos.x;1440
var dy = ly - pos.y;1441
var dz = lz - pos.z;1442
var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);1443
var att = this.attenuation(dist, L.range || 64, L.falloff);1444
if (att <= 0.001)1445
{ continue; }1446
if (los && !this.hasLineOfSight(lx, ly, pos.x, pos.y, los.tiles, los.width, los.height, los.cellSize))1447
{ continue; }1448
var ld = this.normalize3(dx, dy, dz);1449
var ndotl = normal.x * ld.x + normal.y * ld.y + normal.z * ld.z;1450
if (ndotl <= 0)1451
{ continue; }1452
var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;1453
var cr = L.color ? L.color[0] : 1;1454
var cg = L.color ? L.color[1] : 1;1455
var cb = L.color ? L.color[2] : 1;1456
r += inten * cr;1457
g += inten * cg;1458
b += inten * cb;1459
}1460
return { r: r, g: g, b: b };1461
},1462
1463
/**1464
* Transform a world-space direction (toward light) into paperdoll view space1465
* for the chosen yaw (degrees). View +Z = toward capture camera (= front at yaw 0).1466
* Character +Z (front) aligns with facingDeg in the XY plane; +Y = world up (Z).1467
*/1468
worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)1469
{1470
var face = (facingDeg || 0) * Math.PI / 180;1471
var yaw = (yawDeg || 0) * Math.PI / 180;1472
// Character basis in world (XY) + up Z1473
var frontX = Math.cos(face);1474
var frontY = Math.sin(face);1475
var rightX = -Math.sin(face);1476
var rightY = Math.cos(face);1477
// Camera direction from character (char space): yaw 0 → +Z front1478
var camCX = Math.sin(yaw);1479
var camCZ = Math.cos(yaw);1480
var camX = rightX * camCX + frontX * camCZ;1481
var camY = rightY * camCX + frontY * camCZ;1482
// viewZ = camDir (toward camera), viewY = up, viewX = viewY × viewZ1483
var viewZx = camX, viewZy = camY, viewZz = 0;1484
var viewYx = 0, viewYy = 0, viewYz = 1;1485
// cross(up, viewZ) for right-handed viewX? Standard: viewX = normalize(cross(viewY?))1486
// viewX = cross(viewY, viewZ) with viewY=up → (-viewZy, viewZx, 0) wait:1487
// cross((0,0,1), (camX,camY,0)) = (-camY, camX, 0)1488
var viewXx = -camY;1489
var viewXy = camX;1490
var viewXz = 0;1491
var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);1492
if (vlen > 1e-8)1493
{ viewXx /= vlen; viewXy /= vlen; }1494
return this.normalize3(1495
dirX * viewXx + dirY * viewXy + dirZ * viewXz,1496
dirX * viewYx + dirY * viewYy + dirZ * viewYz,1497
dirX * viewZx + dirY * viewZy + dirZ * viewZz1498
);1499
},1500
1501
/**1502
* Relight one paperdoll pixel (albedo RGB + view-space normal) with point lights.1503
* pixelWorld ≈ NPC base + height from atlas row; depth shifts along view cam.1504
*/1505
shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg)1506
{1507
ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;1508
var n = this.decodeNormalRgb(nr, ng, nb);1509
var r = ambient * albedoR;1510
var g = ambient * albedoG;1511
var b = ambient * albedoB;1512
if (!lights || !lights.length)1513
{1514
// Match old preview-ish fill when no lamps: slight Lambert from default view light1515
var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);1516
var shade = Math.min(1, 0.35 + 0.65 * nd);1517
return {1518
r: Math.min(255, Math.round(albedoR * shade)),1519
g: Math.min(255, Math.round(albedoG * shade)),1520
b: Math.min(255, Math.round(albedoB * shade))1521
};1522
}1523
var count = Math.min(lights.length, this.MAX_LIGHTS);1524
for (var i = 0; i < count; i++)1525
{1526
var L = lights[i];1527
var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;1528
var dx = lx - pixelWorld.x;1529
var dy = ly - pixelWorld.y;1530
var dz = lz - pixelWorld.z;1531
var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);1532
var att = this.attenuation(dist, L.range || 64, L.falloff);1533
if (att <= 0.001)1534
{ continue; }1535
var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);1536
var ndotl = n.x * lv.x + n.y * lv.y + n.z * lv.z;1537
if (ndotl <= 0)1538
{ continue; }1539
var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;1540
var cr = L.color ? L.color[0] : 1;1541
var cg = L.color ? L.color[1] : 1;1542
var cb = L.color ? L.color[2] : 1;1543
r += albedoR * inten * cr;1544
g += albedoG * inten * cg;1545
b += albedoB * inten * cb;1546
}1547
return {1548
r: Math.min(255, Math.round(r)),1549
g: Math.min(255, Math.round(g)),1550
b: Math.min(255, Math.round(b))1551
};1552
},1553
1554
/** Legacy wall face shade (no lamps) — keep look of pre-light builds. */1555
legacyFaceShade: function (dir)1556
{1557
switch (dir)1558
{1559
case "east": return 0.9;1560
case "west": return 0.8;1561
case "south": return 0.7;1562
default: return 1.0;1563
}1564
}1565
};1566
1567
if (typeof module !== "undefined" && module.exports)1568
{ module.exports = Lighting; }1569
1570
/*1571
* End File:1572
* /workspace/raytracer-work/src/lighting.js1573
*/ 1574
1204
/*1575
/*1205
* Start File:1576
* Start File:1206
* /workspace/raytracer-work/src/levels.js1577
* /workspace/raytracer-work/src/levels.js@@ -1788,7 +2159,7 @@ var NpcSystem =1788
var feetRow = composed.height - 1;2159
var feetRow = composed.height - 1;1789
var feetH = composed.height;2160
var feetH = composed.height;1790
var feetW = composed.width;2161
var feetW = composed.width;1791
var feetAlpha = composed.lit;2162
var feetAlpha = composed.diffuse;1792
try2163
try1793
{2164
{1794
var bodyLayer = PpdaAtlasRuntime.layerFromSet(2165
var bodyLayer = PpdaAtlasRuntime.layerFromSet(@@ -1833,7 +2204,7 @@ var NpcSystem =1833
{ continue; }2204
{ continue; }1834
var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));2205
var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));1835
var pi = texY * composed.width + texX;2206
var pi = texY * composed.width + texX;1836
var a = composed.lit[pi * 4 + 3];2207
var a = composed.diffuse[pi * 4 + 3];1837
if (!a || composed.depthAlpha[pi] === 0)2208
if (!a || composed.depthAlpha[pi] === 0)1838
{ continue; }2209
{ continue; }1839
2210
@@ -1848,9 +2219,51 @@ var NpcSystem =1848
zbuf[zi] = pixelDist;2219
zbuf[zi] = pixelDist;1849
2220
1850
var o = zi * 4;2221
var o = zi * 4;1851
data[o] = Math.min(255, Math.round(composed.lit[pi * 4] * tint));2222
var ar = composed.diffuse[pi * 4];1852
data[o + 1] = Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint));2223
var ag = composed.diffuse[pi * 4 + 1];1853
data[o + 2] = Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint));2224
var ab = composed.diffuse[pi * 4 + 2];2225
var lights = World.level && World.level.lights;2226
var ambient = World.level && World.level.ambient != null2227
? World.level.ambient : 0.38;2228
// Pixel world: NPC feet + height from atlas v + depth along view cam.2229
var heightFrac = 1 - (texY + 0.5) / composed.height;2230
var pxZ = heightFrac * heightM * metersToWorld * 0.5;2231
var depthOff = (depthM - camDist) * metersToWorld;2232
var face = (npc.facingDeg || 0) * Math.PI / 180;2233
var yawR = (yaw || 0) * Math.PI / 180;2234
var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);2235
var frontX = Math.cos(face), frontY = Math.sin(face);2236
var rightX = -Math.sin(face), rightY = Math.cos(face);2237
var camX = rightX * camCX + frontX * camCZ;2238
var camY = rightY * camCX + frontY * camCZ;2239
var lat = (u - 0.5) * (heightM * metersToWorld * 0.35);2240
var pxWorld = {2241
x: npc.x + (-camY) * lat + camX * depthOff,2242
y: npc.y + (camX) * lat + camY * depthOff,2243
z: pxZ2244
};2245
var nr = composed.normal ? composed.normal[pi * 4] : 128;2246
var ng = composed.normal ? composed.normal[pi * 4 + 1] : 128;2247
var nb = composed.normal ? composed.normal[pi * 4 + 2] : 255;2248
var shaded;2249
if (typeof Lighting !== "undefined")2250
{2251
shaded = Lighting.shadePaperdollPixel(2252
ar, ag, ab, nr, ng, nb, pxWorld,2253
lights || [], ambient, yaw, npc.facingDeg || 02254
);2255
}2256
else2257
{2258
shaded = {2259
r: Math.min(255, Math.round(composed.lit[pi * 4] * tint)),2260
g: Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint)),2261
b: Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint))2262
};2263
}2264
data[o] = shaded.r;2265
data[o + 1] = shaded.g;2266
data[o + 2] = shaded.b;1854
data[o + 3] = a;2267
data[o + 3] = a;1855
}2268
}1856
}2269
}@@ -2074,7 +2487,6 @@ class RaycastScene extends Scene2074
if (!rayHit || !rayHit.tile)2487
if (!rayHit || !rayHit.tile)2075
{ continue; }2488
{ continue; }2076
2489
2077
var light = this.faceLight(rayHit.dir);2078
var deltaAngle = Player.rotation - rot;2490
var deltaAngle = Player.rotation - rot;2079
var dist = rayHit.distance * Math.cos(deltaAngle);2491
var dist = rayHit.distance * Math.cos(deltaAngle);2080
if (dist < 0.0001)2492
if (dist < 0.0001)@@ -2085,7 +2497,33 @@ class RaycastScene extends Scene2085
// Same horizon/pitch as FloorCast + NPC feet.2497
// Same horizon/pitch as FloorCast + NPC feet.2086
var yCenter = (h / 2) + (-Player.pitch * h * 0.25);2498
var yCenter = (h / 2) + (-Player.pitch * h * 0.25);2087
2499
2088
var tint = [light, light, light];2500
var tint;2501
var lights = World.level && World.level.lights;2502
if (typeof Lighting !== "undefined" && lights && lights.length)2503
{2504
var nrm = Lighting.faceNormal(rayHit.dir);2505
var hitPos = {2506
x: rayHit.endX,2507
y: rayHit.endY,2508
z: World.size * 0.52509
};2510
var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;2511
var los = {2512
tiles: World.level.tiles,2513
width: World.level.width,2514
height: World.level.height,2515
cellSize: World.size2516
};2517
var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);2518
// Soften with legacy face shade so side walls stay readable.2519
var face = this.faceLight(rayHit.dir);2520
tint = [Math.min(1.8, lit.r * face), Math.min(1.8, lit.g * face), Math.min(1.8, lit.b * face)];2521
}2522
else2523
{2524
var light = this.faceLight(rayHit.dir);2525
tint = [light, light, light];2526
}2089
var htmlImage = null;2527
var htmlImage = null;2090
var texW = 1;2528
var texW = 1;2091
2529
@@ -1,5 +1,5 @@
1
1
{
2
"format_version": 1,
2
"format_version": 2,
3
3
"textures": [
4
4
{
5
5
"id": "stone",
@@ -379,7 +379,51 @@
379
379
"gearPpda": "male-sword-atlas.ppda"
380
380
}
381
381
],
382
"lights": []
382
"lights": [
383
{
384
"id": "red-left",
385
"x": 80,
386
"y": 48,
387
"z": 22,
388
"color": [
389
1.0,
390
0.25,
391
0.15
392
],
393
"intensity": 1.6,
394
"range": 110,
395
"falloff": 2
396
},
397
{
398
"id": "blue-right",
399
"x": 200,
400
"y": 80,
401
"z": 24,
402
"color": [
403
0.25,
404
0.45,
405
1.0
406
],
407
"intensity": 1.5,
408
"range": 120,
409
"falloff": 2
410
},
411
{
412
"id": "warm-mid",
413
"x": 112,
414
"y": 160,
415
"z": 18,
416
"color": [
417
1.0,
418
0.85,
419
0.45
420
],
421
"intensity": 1.3,
422
"range": 100,
423
"falloff": 2
424
}
425
],
426
"ambient": 0.22
383
427
},
384
428
{
385
429
"id": "level-wood-hall",
@@ -604,7 +648,23 @@
604
648
"gearPpda": "male-sword-atlas.ppda"
605
649
}
606
650
],
607
"lights": []
651
"lights": [
652
{
653
"id": "hall-warm",
654
"x": 96,
655
"y": 96,
656
"z": 22,
657
"color": [
658
1.0,
659
0.75,
660
0.4
661
],
662
"intensity": 1.4,
663
"range": 140,
664
"falloff": 2
665
}
666
],
667
"ambient": 0.28
608
668
}
609
669
]
610
}
670
}
@@ -1,5 +1,5 @@1
{1
{2
"format_version": 1,2
"format_version": 2,3
"textures": [3
"textures": [4
{4
{5
"id": "stone",5
"id": "stone",@@ -379,7 +379,51 @@379
"gearPpda": "male-sword-atlas.ppda"379
"gearPpda": "male-sword-atlas.ppda"380
}380
}381
],381
],382
"lights": []382
"lights": [383
{384
"id": "red-left",385
"x": 80,386
"y": 48,387
"z": 22,388
"color": [389
1.0,390
0.25,391
0.15392
],393
"intensity": 1.6,394
"range": 110,395
"falloff": 2396
},397
{398
"id": "blue-right",399
"x": 200,400
"y": 80,401
"z": 24,402
"color": [403
0.25,404
0.45,405
1.0406
],407
"intensity": 1.5,408
"range": 120,409
"falloff": 2410
},411
{412
"id": "warm-mid",413
"x": 112,414
"y": 160,415
"z": 18,416
"color": [417
1.0,418
0.85,419
0.45420
],421
"intensity": 1.3,422
"range": 100,423
"falloff": 2424
}425
],426
"ambient": 0.22383
},427
},384
{428
{385
"id": "level-wood-hall",429
"id": "level-wood-hall",@@ -604,7 +648,23 @@604
"gearPpda": "male-sword-atlas.ppda"648
"gearPpda": "male-sword-atlas.ppda"605
}649
}606
],650
],607
"lights": []651
"lights": [652
{653
"id": "hall-warm",654
"x": 96,655
"y": 96,656
"z": 22,657
"color": [658
1.0,659
0.75,660
0.4661
],662
"intensity": 1.4,663
"range": 140,664
"falloff": 2665
}666
],667
"ambient": 0.28608
}668
}609
]669
]610
}670
}@@ -17,6 +17,7 @@ FILES=(
17
17
"$SRC_DIR/ppda/atlasRuntime.js"
18
18
"$SRC_DIR/levelFormat.js"
19
19
"$SRC_DIR/floorCast.js"
20
"$SRC_DIR/lighting.js"
20
21
"$SRC_DIR/levels.js"
21
22
"$SRC_DIR/tiles.js"
22
23
"$SRC_DIR/world.js"
@@ -17,6 +17,7 @@ FILES=(17
"$SRC_DIR/ppda/atlasRuntime.js"17
"$SRC_DIR/ppda/atlasRuntime.js"18
"$SRC_DIR/levelFormat.js"18
"$SRC_DIR/levelFormat.js"19
"$SRC_DIR/floorCast.js"19
"$SRC_DIR/floorCast.js"20
"$SRC_DIR/lighting.js"20
"$SRC_DIR/levels.js"21
"$SRC_DIR/levels.js"21
"$SRC_DIR/tiles.js"22
"$SRC_DIR/tiles.js"22
"$SRC_DIR/world.js"23
"$SRC_DIR/world.js"@@ -6,7 +6,8 @@
6
6
var STORAGE_KEY = "raytracer-levels-v1";
7
7
var pack = null;
8
8
var levelIndex = 0;
9
var tool = "wall"; // wall | floor | ceiling | spawn | npc
9
var tool = "wall"; // wall | floor | ceiling | spawn | npc | light
10
var selectedLight = -1;
10
11
var brushWall = 1;
11
12
var brushTex = "stone"; // or null via "none"
12
13
var cellPx = 28;
@@ -68,6 +69,36 @@
68
69
document.getElementById("level-w").value = level().width;
69
70
document.getElementById("level-h").value = level().height;
70
71
refreshNpcList();
72
refreshLightList();
73
}
74
75
function refreshLightList ()
76
{
77
var ul = document.getElementById("light-list");
78
if (!ul) return;
79
ul.innerHTML = "";
80
(level().lights || []).forEach(function (lamp, i)
81
{
82
var li = document.createElement("li");
83
li.textContent = (lamp.id || "light") + " @" + Math.round(lamp.x) + "," + Math.round(lamp.y)
84
+ " r" + Math.round(lamp.range || 0);
85
li.style.cursor = "pointer";
86
if (i === selectedLight) li.style.background = "#543";
87
li.onclick = function ()
88
{
89
selectedLight = i;
90
document.getElementById("light-z").value = lamp.z;
91
document.getElementById("light-intensity").value = lamp.intensity;
92
document.getElementById("light-range").value = lamp.range;
93
var c = lamp.color || [1, 0.9, 0.7];
94
document.getElementById("light-cr").value = c[0];
95
document.getElementById("light-cg").value = c[1];
96
document.getElementById("light-cb").value = c[2];
97
refreshLightList();
98
redraw();
99
};
100
ul.appendChild(li);
101
});
71
102
}
72
103
73
104
function refreshNpcList ()
@@ -166,6 +197,27 @@
166
197
ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";
167
198
ctx.fillRect(nx - 5, ny - 5, 10, 10);
168
199
});
200
(L.lights || []).forEach(function (lamp, i)
201
{
202
var lx = (lamp.x / (L.cellSize || 32)) * cellPx;
203
var ly = (lamp.y / (L.cellSize || 32)) * cellPx;
204
var rr = ((lamp.range || 64) / (L.cellSize || 32)) * cellPx;
205
ctx.strokeStyle = i === selectedLight ? "#ff0" : "rgba(255,220,80,0.45)";
206
ctx.beginPath();
207
ctx.arc(lx, ly, rr, 0, Math.PI * 2);
208
ctx.stroke();
209
var col = lamp.color || [1, 0.9, 0.5];
210
var R = Math.round((col[0] > 1 ? col[0] : col[0] * 255));
211
var G = Math.round((col[1] > 1 ? col[1] : col[1] * 255));
212
var B = Math.round((col[2] > 1 ? col[2] : col[2] * 255));
213
ctx.fillStyle = "rgb(" + R + "," + G + "," + B + ")";
214
ctx.beginPath();
215
ctx.arc(lx, ly, i === selectedLight ? 8 : 6, 0, Math.PI * 2);
216
ctx.fill();
217
ctx.strokeStyle = "#000";
218
ctx.stroke();
219
});
220
169
221
ctx.strokeStyle = "#333";
170
222
for (var gx = 0; gx <= L.width; gx++)
171
223
{
@@ -208,6 +260,23 @@
208
260
L.spawn.tileX = x;
209
261
L.spawn.tileY = y;
210
262
}
263
else if (tool === "light")
264
{
265
var csL = L.cellSize || 32;
266
if (!L.lights) L.lights = [];
267
var lamp = LevelFormat.emptyLight(x * csL + csL / 2, y * csL + csL / 2);
268
lamp.z = Number(document.getElementById("light-z").value) || 20;
269
lamp.intensity = Number(document.getElementById("light-intensity").value) || 1.2;
270
lamp.range = Number(document.getElementById("light-range").value) || 96;
271
lamp.color = [
272
Number(document.getElementById("light-cr").value) || 1,
273
Number(document.getElementById("light-cg").value) || 0.9,
274
Number(document.getElementById("light-cb").value) || 0.7
275
];
276
L.lights.push(lamp);
277
selectedLight = L.lights.length - 1;
278
refreshLightList();
279
}
211
280
else if (tool === "npc")
212
281
{
213
282
var cs = L.cellSize || 32;
@@ -353,23 +422,56 @@
353
422
};
354
423
});
355
424
425
var draggingLight = false;
356
426
canvas.onmousedown = function (e)
357
427
{
358
painting = true;
359
428
var c = cellFromEvent(e);
360
if (c)
361
{ paintAt(c.x, c.y); }
429
if (!c) return;
430
if (tool === "light")
431
{
432
var cs = level().cellSize || 32;
433
var wx = c.x * cs + cs / 2;
434
var wy = c.y * cs + cs / 2;
435
var hit = -1;
436
(level().lights || []).forEach(function (lamp, i)
437
{
438
var dx = lamp.x - wx, dy = lamp.y - wy;
439
if (dx * dx + dy * dy < (cs * 0.6) * (cs * 0.6)) hit = i;
440
});
441
if (hit >= 0)
442
{
443
selectedLight = hit;
444
draggingLight = true;
445
refreshLightList();
446
redraw();
447
return;
448
}
449
}
450
painting = true;
451
paintAt(c.x, c.y);
362
452
};
363
453
canvas.onmousemove = function (e)
364
454
{
365
if (!painting || tool === "spawn" || tool === "npc")
366
{ return; }
367
455
var c = cellFromEvent(e);
368
if (c)
369
{ paintAt(c.x, c.y); }
456
if (!c) return;
457
if (draggingLight && selectedLight >= 0 && level().lights[selectedLight])
458
{
459
var cs = level().cellSize || 32;
460
level().lights[selectedLight].x = c.x * cs + cs / 2;
461
level().lights[selectedLight].y = c.y * cs + cs / 2;
462
redraw();
463
return;
464
}
465
if (!painting || tool === "spawn" || tool === "npc" || tool === "light")
466
{ return; }
467
paintAt(c.x, c.y);
370
468
};
371
469
window.onmouseup = function ()
372
{ painting = false; };
470
{
471
if (draggingLight) { saveLocal(); refreshLightList(); }
472
painting = false;
473
draggingLight = false;
474
};
373
475
374
476
document.getElementById("spawn-yaw").onchange = function (e)
375
477
{
@@ -414,6 +516,46 @@
414
516
}
415
517
};
416
518
519
var ambEl = document.getElementById("level-ambient");
520
if (ambEl)
521
{
522
ambEl.value = level().ambient != null ? level().ambient : 0.38;
523
ambEl.onchange = function (e)
524
{
525
level().ambient = Number(e.target.value);
526
saveLocal();
527
};
528
}
529
document.getElementById("btn-del-light").onclick = function ()
530
{
531
if (selectedLight < 0 || !level().lights) return;
532
level().lights.splice(selectedLight, 1);
533
selectedLight = -1;
534
refreshLightList();
535
redraw();
536
saveLocal();
537
};
538
function applyLightProps ()
539
{
540
if (selectedLight < 0 || !level().lights[selectedLight]) return;
541
var lamp = level().lights[selectedLight];
542
lamp.z = Number(document.getElementById("light-z").value) || 20;
543
lamp.intensity = Number(document.getElementById("light-intensity").value) || 1;
544
lamp.range = Number(document.getElementById("light-range").value) || 96;
545
lamp.color = [
546
Number(document.getElementById("light-cr").value) || 1,
547
Number(document.getElementById("light-cg").value) || 0.9,
548
Number(document.getElementById("light-cb").value) || 0.7
549
];
550
redraw();
551
saveLocal();
552
}
553
["light-z","light-intensity","light-range","light-cr","light-cg","light-cb"].forEach(function (id)
554
{
555
var el = document.getElementById(id);
556
if (el) el.onchange = applyLightProps;
557
});
558
417
559
document.getElementById("btn-download").onclick = function ()
418
560
{
419
561
try
@@ -6,7 +6,8 @@6
var STORAGE_KEY = "raytracer-levels-v1";6
var STORAGE_KEY = "raytracer-levels-v1";7
var pack = null;7
var pack = null;8
var levelIndex = 0;8
var levelIndex = 0;9
var tool = "wall"; // wall | floor | ceiling | spawn | npc9
var tool = "wall"; // wall | floor | ceiling | spawn | npc | light10
var selectedLight = -1;10
var brushWall = 1;11
var brushWall = 1;11
var brushTex = "stone"; // or null via "none"12
var brushTex = "stone"; // or null via "none"12
var cellPx = 28;13
var cellPx = 28;@@ -68,6 +69,36 @@68
document.getElementById("level-w").value = level().width;69
document.getElementById("level-w").value = level().width;69
document.getElementById("level-h").value = level().height;70
document.getElementById("level-h").value = level().height;70
refreshNpcList();71
refreshNpcList();72
refreshLightList();73
}74
75
function refreshLightList ()76
{77
var ul = document.getElementById("light-list");78
if (!ul) return;79
ul.innerHTML = "";80
(level().lights || []).forEach(function (lamp, i)81
{82
var li = document.createElement("li");83
li.textContent = (lamp.id || "light") + " @" + Math.round(lamp.x) + "," + Math.round(lamp.y)84
+ " r" + Math.round(lamp.range || 0);85
li.style.cursor = "pointer";86
if (i === selectedLight) li.style.background = "#543";87
li.onclick = function ()88
{89
selectedLight = i;90
document.getElementById("light-z").value = lamp.z;91
document.getElementById("light-intensity").value = lamp.intensity;92
document.getElementById("light-range").value = lamp.range;93
var c = lamp.color || [1, 0.9, 0.7];94
document.getElementById("light-cr").value = c[0];95
document.getElementById("light-cg").value = c[1];96
document.getElementById("light-cb").value = c[2];97
refreshLightList();98
redraw();99
};100
ul.appendChild(li);101
});71
}102
}72
103
73
function refreshNpcList ()104
function refreshNpcList ()@@ -166,6 +197,27 @@166
ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";197
ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";167
ctx.fillRect(nx - 5, ny - 5, 10, 10);198
ctx.fillRect(nx - 5, ny - 5, 10, 10);168
});199
});200
(L.lights || []).forEach(function (lamp, i)201
{202
var lx = (lamp.x / (L.cellSize || 32)) * cellPx;203
var ly = (lamp.y / (L.cellSize || 32)) * cellPx;204
var rr = ((lamp.range || 64) / (L.cellSize || 32)) * cellPx;205
ctx.strokeStyle = i === selectedLight ? "#ff0" : "rgba(255,220,80,0.45)";206
ctx.beginPath();207
ctx.arc(lx, ly, rr, 0, Math.PI * 2);208
ctx.stroke();209
var col = lamp.color || [1, 0.9, 0.5];210
var R = Math.round((col[0] > 1 ? col[0] : col[0] * 255));211
var G = Math.round((col[1] > 1 ? col[1] : col[1] * 255));212
var B = Math.round((col[2] > 1 ? col[2] : col[2] * 255));213
ctx.fillStyle = "rgb(" + R + "," + G + "," + B + ")";214
ctx.beginPath();215
ctx.arc(lx, ly, i === selectedLight ? 8 : 6, 0, Math.PI * 2);216
ctx.fill();217
ctx.strokeStyle = "#000";218
ctx.stroke();219
});220
169
ctx.strokeStyle = "#333";221
ctx.strokeStyle = "#333";170
for (var gx = 0; gx <= L.width; gx++)222
for (var gx = 0; gx <= L.width; gx++)171
{223
{@@ -208,6 +260,23 @@208
L.spawn.tileX = x;260
L.spawn.tileX = x;209
L.spawn.tileY = y;261
L.spawn.tileY = y;210
}262
}263
else if (tool === "light")264
{265
var csL = L.cellSize || 32;266
if (!L.lights) L.lights = [];267
var lamp = LevelFormat.emptyLight(x * csL + csL / 2, y * csL + csL / 2);268
lamp.z = Number(document.getElementById("light-z").value) || 20;269
lamp.intensity = Number(document.getElementById("light-intensity").value) || 1.2;270
lamp.range = Number(document.getElementById("light-range").value) || 96;271
lamp.color = [272
Number(document.getElementById("light-cr").value) || 1,273
Number(document.getElementById("light-cg").value) || 0.9,274
Number(document.getElementById("light-cb").value) || 0.7275
];276
L.lights.push(lamp);277
selectedLight = L.lights.length - 1;278
refreshLightList();279
}211
else if (tool === "npc")280
else if (tool === "npc")212
{281
{213
var cs = L.cellSize || 32;282
var cs = L.cellSize || 32;@@ -353,23 +422,56 @@353
};422
};354
});423
});355
424
425
var draggingLight = false;356
canvas.onmousedown = function (e)426
canvas.onmousedown = function (e)357
{427
{358
painting = true;359
var c = cellFromEvent(e);428
var c = cellFromEvent(e);360
if (c)429
if (!c) return;361
{ paintAt(c.x, c.y); }430
if (tool === "light")431
{432
var cs = level().cellSize || 32;433
var wx = c.x * cs + cs / 2;434
var wy = c.y * cs + cs / 2;435
var hit = -1;436
(level().lights || []).forEach(function (lamp, i)437
{438
var dx = lamp.x - wx, dy = lamp.y - wy;439
if (dx * dx + dy * dy < (cs * 0.6) * (cs * 0.6)) hit = i;440
});441
if (hit >= 0)442
{443
selectedLight = hit;444
draggingLight = true;445
refreshLightList();446
redraw();447
return;448
}449
}450
painting = true;451
paintAt(c.x, c.y);362
};452
};363
canvas.onmousemove = function (e)453
canvas.onmousemove = function (e)364
{454
{365
if (!painting || tool === "spawn" || tool === "npc")366
{ return; }367
var c = cellFromEvent(e);455
var c = cellFromEvent(e);368
if (c)456
if (!c) return;369
{ paintAt(c.x, c.y); }457
if (draggingLight && selectedLight >= 0 && level().lights[selectedLight])458
{459
var cs = level().cellSize || 32;460
level().lights[selectedLight].x = c.x * cs + cs / 2;461
level().lights[selectedLight].y = c.y * cs + cs / 2;462
redraw();463
return;464
}465
if (!painting || tool === "spawn" || tool === "npc" || tool === "light")466
{ return; }467
paintAt(c.x, c.y);370
};468
};371
window.onmouseup = function ()469
window.onmouseup = function ()372
{ painting = false; };470
{471
if (draggingLight) { saveLocal(); refreshLightList(); }472
painting = false;473
draggingLight = false;474
};373
475
374
document.getElementById("spawn-yaw").onchange = function (e)476
document.getElementById("spawn-yaw").onchange = function (e)375
{477
{@@ -414,6 +516,46 @@414
}516
}415
};517
};416
518
519
var ambEl = document.getElementById("level-ambient");520
if (ambEl)521
{522
ambEl.value = level().ambient != null ? level().ambient : 0.38;523
ambEl.onchange = function (e)524
{525
level().ambient = Number(e.target.value);526
saveLocal();527
};528
}529
document.getElementById("btn-del-light").onclick = function ()530
{531
if (selectedLight < 0 || !level().lights) return;532
level().lights.splice(selectedLight, 1);533
selectedLight = -1;534
refreshLightList();535
redraw();536
saveLocal();537
};538
function applyLightProps ()539
{540
if (selectedLight < 0 || !level().lights[selectedLight]) return;541
var lamp = level().lights[selectedLight];542
lamp.z = Number(document.getElementById("light-z").value) || 20;543
lamp.intensity = Number(document.getElementById("light-intensity").value) || 1;544
lamp.range = Number(document.getElementById("light-range").value) || 96;545
lamp.color = [546
Number(document.getElementById("light-cr").value) || 1,547
Number(document.getElementById("light-cg").value) || 0.9,548
Number(document.getElementById("light-cb").value) || 0.7549
];550
redraw();551
saveLocal();552
}553
["light-z","light-intensity","light-range","light-cr","light-cg","light-cb"].forEach(function (id)554
{555
var el = document.getElementById(id);556
if (el) el.onchange = applyLightProps;557
});558
417
document.getElementById("btn-download").onclick = function ()559
document.getElementById("btn-download").onclick = function ()418
{560
{419
try561
try@@ -132,13 +132,31 @@ var FloorCast =
132
132
if (texId && texMap[texId])
133
133
{
134
134
var tex = texMap[texId];
135
// World-space UV so texels shrink toward the horizon.
136
135
var u = wx / cellSize;
137
136
var vv = wy / cellSize;
138
137
var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);
139
r = (c[0] * shade) | 0;
140
g = (c[1] * shade) | 0;
141
b = (c[2] * shade) | 0;
138
var wz = isCeil ? cellSize : 0;
139
var nrm = isCeil
140
? { x: 0, y: 0, z: -1 }
141
: { x: 0, y: 0, z: 1 };
142
var lights = level.lights || [];
143
var ambient = level.ambient != null ? level.ambient : 0.38;
144
var lit;
145
if (typeof Lighting !== "undefined" && lights.length)
146
{
147
var los = level.tiles
148
? { tiles: level.tiles, width: lw, height: lh, cellSize: cellSize }
149
: null;
150
lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, los);
151
}
152
else
153
{
154
// No lamps: keep previous distance shade look.
155
lit = { r: shade, g: shade, b: shade };
156
}
157
r = Math.min(255, (c[0] * lit.r) | 0);
158
g = Math.min(255, (c[1] * lit.g) | 0);
159
b = Math.min(255, (c[2] * lit.b) | 0);
142
160
}
143
161
}
144
162
for (var dy = 0; dy < step && sy + dy < screenH; dy++)
@@ -132,13 +132,31 @@ var FloorCast =132
if (texId && texMap[texId])132
if (texId && texMap[texId])133
{133
{134
var tex = texMap[texId];134
var tex = texMap[texId];135
// World-space UV so texels shrink toward the horizon.136
var u = wx / cellSize;135
var u = wx / cellSize;137
var vv = wy / cellSize;136
var vv = wy / cellSize;138
var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);137
var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);139
r = (c[0] * shade) | 0;138
var wz = isCeil ? cellSize : 0;140
g = (c[1] * shade) | 0;139
var nrm = isCeil141
b = (c[2] * shade) | 0;140
? { x: 0, y: 0, z: -1 }141
: { x: 0, y: 0, z: 1 };142
var lights = level.lights || [];143
var ambient = level.ambient != null ? level.ambient : 0.38;144
var lit;145
if (typeof Lighting !== "undefined" && lights.length)146
{147
var los = level.tiles148
? { tiles: level.tiles, width: lw, height: lh, cellSize: cellSize }149
: null;150
lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, los);151
}152
else153
{154
// No lamps: keep previous distance shade look.155
lit = { r: shade, g: shade, b: shade };156
}157
r = Math.min(255, (c[0] * lit.r) | 0);158
g = Math.min(255, (c[1] * lit.g) | 0);159
b = Math.min(255, (c[2] * lit.b) | 0);142
}160
}143
}161
}144
for (var dy = 0; dy < step && sy + dy < screenH; dy++)162
for (var dy = 0; dy < step && sy + dy < screenH; dy++)@@ -1,14 +1,30 @@
1
1
/**
2
* Level pack format (schema v1) for raytracer + editor.
3
* walls: tile type ids; floors/ceilings: texture id string or null (black).
4
* lights: reserved list (not rendered yet).
2
* Level pack format for raytracer + editor.
3
* v1: walls/floors/ceilings/npcs/lights[] (empty reserved)
4
* v2: lights fully specified + per-level ambient; migrate v1→v2.
5
5
*/
6
6
var LevelFormat =
7
7
{
8
CURRENT_VERSION: 1,
8
CURRENT_VERSION: 2,
9
9
MAX_SIZE: 128,
10
10
MAX_LEVELS: 64,
11
MAX_LIGHTS: 32,
11
12
KNOWN_TEXTURES: ["stone", "wood"],
13
DEFAULT_AMBIENT: 0.38,
14
15
emptyLight: function (x, y)
16
{
17
return {
18
id: "light-" + Date.now().toString(36),
19
x: x == null ? 48 : x,
20
y: y == null ? 48 : y,
21
z: 20,
22
color: [1, 0.9, 0.7],
23
intensity: 1.2,
24
range: 96,
25
falloff: 2
26
};
27
},
12
28
13
29
emptyLevel: function (name, width, height)
14
30
{
@@ -33,6 +49,7 @@ var LevelFormat =
33
49
width: width,
34
50
height: height,
35
51
cellSize: 32,
52
ambient: this.DEFAULT_AMBIENT,
36
53
spawn: { tileX: 1, tileY: 1, yawRad: 0 },
37
54
walls: walls,
38
55
floors: floors,
@@ -54,7 +71,6 @@ var LevelFormat =
54
71
};
55
72
},
56
73
57
/** Migrate legacy Levels[] (tiles only) into a pack. */
58
74
fromLegacyLevels: function (legacyArr, npcsByLevel)
59
75
{
60
76
var pack = this.defaultPack();
@@ -76,11 +92,8 @@ var LevelFormat =
76
92
width: L.width,
77
93
height: L.height,
78
94
cellSize: 32,
79
spawn: {
80
tileX: L.spawnX,
81
tileY: L.spawnY,
82
yawRad: 0
83
},
95
ambient: this.DEFAULT_AMBIENT,
96
spawn: { tileX: L.spawnX, tileY: L.spawnY, yawRad: 0 },
84
97
walls: L.tiles.slice(),
85
98
floors: floors,
86
99
ceilings: ceilings,
@@ -91,6 +104,62 @@ var LevelFormat =
91
104
return pack;
92
105
},
93
106
107
migratePack: function (pack)
108
{
109
if (!pack || typeof pack !== "object")
110
{ throw new Error("pack: root moet een object zijn"); }
111
var ver = pack.format_version;
112
if (ver === this.CURRENT_VERSION)
113
{ return pack; }
114
if (ver === 1)
115
{
116
pack.format_version = 2;
117
for (var i = 0; i < (pack.levels || []).length; i++)
118
{
119
var L = pack.levels[i];
120
if (typeof L.ambient !== "number")
121
{ L.ambient = this.DEFAULT_AMBIENT; }
122
if (!Array.isArray(L.lights))
123
{ L.lights = []; }
124
for (var li = 0; li < L.lights.length; li++)
125
{ this.normalizeLight(L.lights[li]); }
126
}
127
return pack;
128
}
129
throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1..2)");
130
},
131
132
normalizeLight: function (light)
133
{
134
if (!light || typeof light !== "object")
135
{ throw new Error("light: moet een object zijn"); }
136
if (typeof light.x !== "number" || typeof light.y !== "number")
137
{ throw new Error("light: x/y verplicht"); }
138
if (typeof light.z !== "number")
139
{ light.z = 20; }
140
if (!Array.isArray(light.color) || light.color.length < 3)
141
{ light.color = [1, 0.9, 0.7]; }
142
for (var c = 0; c < 3; c++)
143
{
144
var v = Number(light.color[c]);
145
if (!(v >= 0))
146
{ v = 0; }
147
// allow 0–255 UI values
148
if (v > 1)
149
{ v = v / 255; }
150
light.color[c] = v;
151
}
152
if (typeof light.intensity !== "number")
153
{ light.intensity = 1; }
154
if (typeof light.range !== "number" || light.range <= 0)
155
{ light.range = 96; }
156
if (typeof light.falloff !== "number")
157
{ light.falloff = 2; }
158
if (!light.id || typeof light.id !== "string")
159
{ light.id = "light-" + Math.floor(light.x) + "-" + Math.floor(light.y); }
160
return light;
161
},
162
94
163
validateTextureId: function (tex, allowNull)
95
164
{
96
165
if (tex == null || tex === "")
@@ -98,6 +167,22 @@ var LevelFormat =
98
167
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;
99
168
},
100
169
170
validateLight: function (light, index, levelPrefix)
171
{
172
var prefix = (levelPrefix || "level") + ".lights[" + (index == null ? "?" : index) + "]";
173
try
174
{ this.normalizeLight(light); }
175
catch (e)
176
{ throw new Error(prefix + ": " + e.message); }
177
if (light.intensity < 0 || light.intensity > 20)
178
{ throw new Error(prefix + ": intensity 0..20"); }
179
if (light.range > 2048)
180
{ throw new Error(prefix + ": range te groot"); }
181
if (light.falloff < 0.5 || light.falloff > 8)
182
{ throw new Error(prefix + ": falloff 0.5..8"); }
183
return light;
184
},
185
101
186
validateLevel: function (level, index)
102
187
{
103
188
var prefix = "level[" + (index == null ? "?" : index) + "]";
@@ -138,6 +223,14 @@ var LevelFormat =
138
223
{ throw new Error(prefix + ": npcs moet een array zijn"); }
139
224
if (!Array.isArray(level.lights))
140
225
{ level.lights = []; }
226
if (level.lights.length > this.MAX_LIGHTS)
227
{ throw new Error(prefix + ": te veel lights"); }
228
for (var li = 0; li < level.lights.length; li++)
229
{ this.validateLight(level.lights[li], li, prefix); }
230
if (typeof level.ambient !== "number")
231
{ level.ambient = this.DEFAULT_AMBIENT; }
232
if (level.ambient < 0 || level.ambient > 1)
233
{ throw new Error(prefix + ": ambient 0..1"); }
141
234
if (level.cellSize == null)
142
235
{ level.cellSize = 32; }
143
236
return level;
@@ -145,11 +238,9 @@ var LevelFormat =
145
238
146
239
validatePack: function (pack)
147
240
{
148
if (!pack || typeof pack !== "object")
149
{ throw new Error("pack: root moet een object zijn"); }
150
var ver = pack.format_version;
151
if (ver !== 1)
152
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }
241
pack = this.migratePack(pack);
242
if (pack.format_version !== this.CURRENT_VERSION)
243
{ throw new Error("pack: format_version " + pack.format_version + " niet ondersteund (wel: " + this.CURRENT_VERSION + ")"); }
153
244
if (!Array.isArray(pack.levels))
154
245
{ throw new Error("pack: levels moet een array zijn"); }
155
246
if (pack.levels.length > this.MAX_LEVELS)
@@ -179,7 +270,6 @@ var LevelFormat =
179
270
return this.validatePack(doc);
180
271
},
181
272
182
/** Runtime view used by World (tiles = walls). */
183
273
toRuntimeLevel: function (level)
184
274
{
185
275
return {
@@ -188,6 +278,7 @@ var LevelFormat =
188
278
width: level.width,
189
279
height: level.height,
190
280
cellSize: level.cellSize || 32,
281
ambient: typeof level.ambient === "number" ? level.ambient : this.DEFAULT_AMBIENT,
191
282
spawnX: level.spawn.tileX,
192
283
spawnY: level.spawn.tileY,
193
284
spawnYaw: level.spawn.yawRad || 0,
@@ -1,14 +1,30 @@1
/**1
/**2
* Level pack format (schema v1) for raytracer + editor.2
* Level pack format for raytracer + editor.3
* walls: tile type ids; floors/ceilings: texture id string or null (black).3
* v1: walls/floors/ceilings/npcs/lights[] (empty reserved)4
* lights: reserved list (not rendered yet).4
* v2: lights fully specified + per-level ambient; migrate v1→v2.5
*/5
*/6
var LevelFormat =6
var LevelFormat =7
{7
{8
CURRENT_VERSION: 1,8
CURRENT_VERSION: 2,9
MAX_SIZE: 128,9
MAX_SIZE: 128,10
MAX_LEVELS: 64,10
MAX_LEVELS: 64,11
MAX_LIGHTS: 32,11
KNOWN_TEXTURES: ["stone", "wood"],12
KNOWN_TEXTURES: ["stone", "wood"],13
DEFAULT_AMBIENT: 0.38,14
15
emptyLight: function (x, y)16
{17
return {18
id: "light-" + Date.now().toString(36),19
x: x == null ? 48 : x,20
y: y == null ? 48 : y,21
z: 20,22
color: [1, 0.9, 0.7],23
intensity: 1.2,24
range: 96,25
falloff: 226
};27
},12
28
13
emptyLevel: function (name, width, height)29
emptyLevel: function (name, width, height)14
{30
{@@ -33,6 +49,7 @@ var LevelFormat =33
width: width,49
width: width,34
height: height,50
height: height,35
cellSize: 32,51
cellSize: 32,52
ambient: this.DEFAULT_AMBIENT,36
spawn: { tileX: 1, tileY: 1, yawRad: 0 },53
spawn: { tileX: 1, tileY: 1, yawRad: 0 },37
walls: walls,54
walls: walls,38
floors: floors,55
floors: floors,@@ -54,7 +71,6 @@ var LevelFormat =54
};71
};55
},72
},56
73
57
/** Migrate legacy Levels[] (tiles only) into a pack. */58
fromLegacyLevels: function (legacyArr, npcsByLevel)74
fromLegacyLevels: function (legacyArr, npcsByLevel)59
{75
{60
var pack = this.defaultPack();76
var pack = this.defaultPack();@@ -76,11 +92,8 @@ var LevelFormat =76
width: L.width,92
width: L.width,77
height: L.height,93
height: L.height,78
cellSize: 32,94
cellSize: 32,79
spawn: {95
ambient: this.DEFAULT_AMBIENT,80
tileX: L.spawnX,96
spawn: { tileX: L.spawnX, tileY: L.spawnY, yawRad: 0 },81
tileY: L.spawnY,82
yawRad: 083
},84
walls: L.tiles.slice(),97
walls: L.tiles.slice(),85
floors: floors,98
floors: floors,86
ceilings: ceilings,99
ceilings: ceilings,@@ -91,6 +104,62 @@ var LevelFormat =91
return pack;104
return pack;92
},105
},93
106
107
migratePack: function (pack)108
{109
if (!pack || typeof pack !== "object")110
{ throw new Error("pack: root moet een object zijn"); }111
var ver = pack.format_version;112
if (ver === this.CURRENT_VERSION)113
{ return pack; }114
if (ver === 1)115
{116
pack.format_version = 2;117
for (var i = 0; i < (pack.levels || []).length; i++)118
{119
var L = pack.levels[i];120
if (typeof L.ambient !== "number")121
{ L.ambient = this.DEFAULT_AMBIENT; }122
if (!Array.isArray(L.lights))123
{ L.lights = []; }124
for (var li = 0; li < L.lights.length; li++)125
{ this.normalizeLight(L.lights[li]); }126
}127
return pack;128
}129
throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1..2)");130
},131
132
normalizeLight: function (light)133
{134
if (!light || typeof light !== "object")135
{ throw new Error("light: moet een object zijn"); }136
if (typeof light.x !== "number" || typeof light.y !== "number")137
{ throw new Error("light: x/y verplicht"); }138
if (typeof light.z !== "number")139
{ light.z = 20; }140
if (!Array.isArray(light.color) || light.color.length < 3)141
{ light.color = [1, 0.9, 0.7]; }142
for (var c = 0; c < 3; c++)143
{144
var v = Number(light.color[c]);145
if (!(v >= 0))146
{ v = 0; }147
// allow 0–255 UI values148
if (v > 1)149
{ v = v / 255; }150
light.color[c] = v;151
}152
if (typeof light.intensity !== "number")153
{ light.intensity = 1; }154
if (typeof light.range !== "number" || light.range <= 0)155
{ light.range = 96; }156
if (typeof light.falloff !== "number")157
{ light.falloff = 2; }158
if (!light.id || typeof light.id !== "string")159
{ light.id = "light-" + Math.floor(light.x) + "-" + Math.floor(light.y); }160
return light;161
},162
94
validateTextureId: function (tex, allowNull)163
validateTextureId: function (tex, allowNull)95
{164
{96
if (tex == null || tex === "")165
if (tex == null || tex === "")@@ -98,6 +167,22 @@ var LevelFormat =98
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;167
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;99
},168
},100
169
170
validateLight: function (light, index, levelPrefix)171
{172
var prefix = (levelPrefix || "level") + ".lights[" + (index == null ? "?" : index) + "]";173
try174
{ this.normalizeLight(light); }175
catch (e)176
{ throw new Error(prefix + ": " + e.message); }177
if (light.intensity < 0 || light.intensity > 20)178
{ throw new Error(prefix + ": intensity 0..20"); }179
if (light.range > 2048)180
{ throw new Error(prefix + ": range te groot"); }181
if (light.falloff < 0.5 || light.falloff > 8)182
{ throw new Error(prefix + ": falloff 0.5..8"); }183
return light;184
},185
101
validateLevel: function (level, index)186
validateLevel: function (level, index)102
{187
{103
var prefix = "level[" + (index == null ? "?" : index) + "]";188
var prefix = "level[" + (index == null ? "?" : index) + "]";@@ -138,6 +223,14 @@ var LevelFormat =138
{ throw new Error(prefix + ": npcs moet een array zijn"); }223
{ throw new Error(prefix + ": npcs moet een array zijn"); }139
if (!Array.isArray(level.lights))224
if (!Array.isArray(level.lights))140
{ level.lights = []; }225
{ level.lights = []; }226
if (level.lights.length > this.MAX_LIGHTS)227
{ throw new Error(prefix + ": te veel lights"); }228
for (var li = 0; li < level.lights.length; li++)229
{ this.validateLight(level.lights[li], li, prefix); }230
if (typeof level.ambient !== "number")231
{ level.ambient = this.DEFAULT_AMBIENT; }232
if (level.ambient < 0 || level.ambient > 1)233
{ throw new Error(prefix + ": ambient 0..1"); }141
if (level.cellSize == null)234
if (level.cellSize == null)142
{ level.cellSize = 32; }235
{ level.cellSize = 32; }143
return level;236
return level;@@ -145,11 +238,9 @@ var LevelFormat =145
238
146
validatePack: function (pack)239
validatePack: function (pack)147
{240
{148
if (!pack || typeof pack !== "object")241
pack = this.migratePack(pack);149
{ throw new Error("pack: root moet een object zijn"); }242
if (pack.format_version !== this.CURRENT_VERSION)150
var ver = pack.format_version;243
{ throw new Error("pack: format_version " + pack.format_version + " niet ondersteund (wel: " + this.CURRENT_VERSION + ")"); }151
if (ver !== 1)152
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }153
if (!Array.isArray(pack.levels))244
if (!Array.isArray(pack.levels))154
{ throw new Error("pack: levels moet een array zijn"); }245
{ throw new Error("pack: levels moet een array zijn"); }155
if (pack.levels.length > this.MAX_LEVELS)246
if (pack.levels.length > this.MAX_LEVELS)@@ -179,7 +270,6 @@ var LevelFormat =179
return this.validatePack(doc);270
return this.validatePack(doc);180
},271
},181
272
182
/** Runtime view used by World (tiles = walls). */183
toRuntimeLevel: function (level)273
toRuntimeLevel: function (level)184
{274
{185
return {275
return {@@ -188,6 +278,7 @@ var LevelFormat =188
width: level.width,278
width: level.width,189
height: level.height,279
height: level.height,190
cellSize: level.cellSize || 32,280
cellSize: level.cellSize || 32,281
ambient: typeof level.ambient === "number" ? level.ambient : this.DEFAULT_AMBIENT,191
spawnX: level.spawn.tileX,282
spawnX: level.spawn.tileX,192
spawnY: level.spawn.tileY,283
spawnY: level.spawn.tileY,193
spawnYaw: level.spawn.yawRad || 0,284
spawnYaw: level.spawn.yawRad || 0,@@ -0,0 +1,252 @@
1
/**
2
* Point lights for the raycaster (CPU).
3
* Walls/floor/ceiling: Lambertian N·L + distance falloff + optional grid LOS.
4
* Paperdolls: same lights, L transformed into the .ppda view space (view=+Z)
5
* so baked normals respond correctly (see Paperdoll compositor.rs relight).
6
*
7
* CPU (not a custom WebGL shader): frameworkv3 is sprite/WebGL1 without a
8
* shared G-buffer; floor is already an ImageData upload, walls are 1px
9
* columns, NPCs are a CPU z-buffer overlay — lighting fits those paths with
10
* no extra GPU pipeline. Grid LOS is O(steps) per sample and capped by
11
* light range; cheaper than raymarched shadows and enough for tile maps.
12
*/
13
var Lighting =
14
{
15
DEFAULT_AMBIENT: 0.38,
16
MAX_LIGHTS: 32,
17
18
normalize3: function (x, y, z)
19
{
20
var len = Math.sqrt(x * x + y * y + z * z);
21
if (len < 1e-8)
22
{ return { x: 0, y: 0, z: 1 }; }
23
return { x: x / len, y: y / len, z: z / len };
24
},
25
26
decodeNormalRgb: function (r, g, b)
27
{
28
return this.normalize3(
29
r / 255 * 2 - 1,
30
g / 255 * 2 - 1,
31
b / 255 * 2 - 1
32
);
33
},
34
35
/** intensity * saturate(1 - dist/range)^falloff */
36
attenuation: function (dist, range, falloff)
37
{
38
if (range <= 0)
39
{ return 0; }
40
var t = 1 - dist / range;
41
if (t <= 0)
42
{ return 0; }
43
var f = falloff == null ? 2 : falloff;
44
if (f === 1)
45
{ return t; }
46
if (f === 2)
47
{ return t * t; }
48
return Math.pow(t, f);
49
},
50
51
faceNormal: function (dir)
52
{
53
switch (dir)
54
{
55
case "north": return { x: 0, y: -1, z: 0 };
56
case "south": return { x: 0, y: 1, z: 0 };
57
case "east": return { x: 1, y: 0, z: 0 };
58
case "west": return { x: -1, y: 0, z: 0 };
59
case "floor": return { x: 0, y: 0, z: 1 };
60
case "ceiling": return { x: 0, y: 0, z: -1 };
61
default: return { x: 0, y: 0, z: 1 };
62
}
63
},
64
65
/**
66
* Grid line-of-sight on the wall map (Bresenham). Endpoints are the light
67
* and sample tiles; a solid wall strictly between blocks the ray.
68
*/
69
hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
70
{
71
cellSize = cellSize || 32;
72
var tx0 = Math.floor(x0 / cellSize);
73
var ty0 = Math.floor(y0 / cellSize);
74
var tx1 = Math.floor(x1 / cellSize);
75
var ty1 = Math.floor(y1 / cellSize);
76
var dx = Math.abs(tx1 - tx0);
77
var dy = Math.abs(ty1 - ty0);
78
var sx = tx0 < tx1 ? 1 : -1;
79
var sy = ty0 < ty1 ? 1 : -1;
80
var err = dx - dy;
81
var x = tx0;
82
var y = ty0;
83
var steps = 0;
84
var maxSteps = dx + dy + 2;
85
while (!(x === tx1 && y === ty1) && steps < maxSteps)
86
{
87
steps++;
88
var e2 = 2 * err;
89
if (e2 > -dy) { err -= dy; x += sx; }
90
if (e2 < dx) { err += dx; y += sy; }
91
if (x === tx1 && y === ty1)
92
{ break; }
93
if (x < 0 || y < 0 || x >= mapW || y >= mapH)
94
{ return false; }
95
var id = tiles[x + y * mapW];
96
if (id === 1 || id === 3)
97
{ return false; }
98
}
99
return true;
100
},
101
102
/**
103
* RGB multipliers (can exceed 1 before clamp by caller).
104
* @param {{x,y,z}} pos world
105
* @param {{x,y,z}} normal unit
106
* @param {Array} lights
107
* @param {number} ambient
108
* @param {object|null} los { tiles, width, height, cellSize } or null to skip
109
*/
110
shadeRgb: function (pos, normal, lights, ambient, los)
111
{
112
ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
113
var r = ambient;
114
var g = ambient;
115
var b = ambient;
116
if (!lights || !lights.length)
117
{ return { r: r, g: g, b: b }; }
118
var n = Math.min(lights.length, this.MAX_LIGHTS);
119
for (var i = 0; i < n; i++)
120
{
121
var L = lights[i];
122
var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;
123
var dx = lx - pos.x;
124
var dy = ly - pos.y;
125
var dz = lz - pos.z;
126
var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
127
var att = this.attenuation(dist, L.range || 64, L.falloff);
128
if (att <= 0.001)
129
{ continue; }
130
if (los && !this.hasLineOfSight(lx, ly, pos.x, pos.y, los.tiles, los.width, los.height, los.cellSize))
131
{ continue; }
132
var ld = this.normalize3(dx, dy, dz);
133
var ndotl = normal.x * ld.x + normal.y * ld.y + normal.z * ld.z;
134
if (ndotl <= 0)
135
{ continue; }
136
var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
137
var cr = L.color ? L.color[0] : 1;
138
var cg = L.color ? L.color[1] : 1;
139
var cb = L.color ? L.color[2] : 1;
140
r += inten * cr;
141
g += inten * cg;
142
b += inten * cb;
143
}
144
return { r: r, g: g, b: b };
145
},
146
147
/**
148
* Transform a world-space direction (toward light) into paperdoll view space
149
* for the chosen yaw (degrees). View +Z = toward capture camera (= front at yaw 0).
150
* Character +Z (front) aligns with facingDeg in the XY plane; +Y = world up (Z).
151
*/
152
worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
153
{
154
var face = (facingDeg || 0) * Math.PI / 180;
155
var yaw = (yawDeg || 0) * Math.PI / 180;
156
// Character basis in world (XY) + up Z
157
var frontX = Math.cos(face);
158
var frontY = Math.sin(face);
159
var rightX = -Math.sin(face);
160
var rightY = Math.cos(face);
161
// Camera direction from character (char space): yaw 0 → +Z front
162
var camCX = Math.sin(yaw);
163
var camCZ = Math.cos(yaw);
164
var camX = rightX * camCX + frontX * camCZ;
165
var camY = rightY * camCX + frontY * camCZ;
166
// viewZ = camDir (toward camera), viewY = up, viewX = viewY × viewZ
167
var viewZx = camX, viewZy = camY, viewZz = 0;
168
var viewYx = 0, viewYy = 0, viewYz = 1;
169
// cross(up, viewZ) for right-handed viewX? Standard: viewX = normalize(cross(viewY?))
170
// viewX = cross(viewY, viewZ) with viewY=up → (-viewZy, viewZx, 0) wait:
171
// cross((0,0,1), (camX,camY,0)) = (-camY, camX, 0)
172
var viewXx = -camY;
173
var viewXy = camX;
174
var viewXz = 0;
175
var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
176
if (vlen > 1e-8)
177
{ viewXx /= vlen; viewXy /= vlen; }
178
return this.normalize3(
179
dirX * viewXx + dirY * viewXy + dirZ * viewXz,
180
dirX * viewYx + dirY * viewYy + dirZ * viewYz,
181
dirX * viewZx + dirY * viewZy + dirZ * viewZz
182
);
183
},
184
185
/**
186
* Relight one paperdoll pixel (albedo RGB + view-space normal) with point lights.
187
* pixelWorld ≈ NPC base + height from atlas row; depth shifts along view cam.
188
*/
189
shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg)
190
{
191
ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
192
var n = this.decodeNormalRgb(nr, ng, nb);
193
var r = ambient * albedoR;
194
var g = ambient * albedoG;
195
var b = ambient * albedoB;
196
if (!lights || !lights.length)
197
{
198
// Match old preview-ish fill when no lamps: slight Lambert from default view light
199
var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);
200
var shade = Math.min(1, 0.35 + 0.65 * nd);
201
return {
202
r: Math.min(255, Math.round(albedoR * shade)),
203
g: Math.min(255, Math.round(albedoG * shade)),
204
b: Math.min(255, Math.round(albedoB * shade))
205
};
206
}
207
var count = Math.min(lights.length, this.MAX_LIGHTS);
208
for (var i = 0; i < count; i++)
209
{
210
var L = lights[i];
211
var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;
212
var dx = lx - pixelWorld.x;
213
var dy = ly - pixelWorld.y;
214
var dz = lz - pixelWorld.z;
215
var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
216
var att = this.attenuation(dist, L.range || 64, L.falloff);
217
if (att <= 0.001)
218
{ continue; }
219
var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);
220
var ndotl = n.x * lv.x + n.y * lv.y + n.z * lv.z;
221
if (ndotl <= 0)
222
{ continue; }
223
var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
224
var cr = L.color ? L.color[0] : 1;
225
var cg = L.color ? L.color[1] : 1;
226
var cb = L.color ? L.color[2] : 1;
227
r += albedoR * inten * cr;
228
g += albedoG * inten * cg;
229
b += albedoB * inten * cb;
230
}
231
return {
232
r: Math.min(255, Math.round(r)),
233
g: Math.min(255, Math.round(g)),
234
b: Math.min(255, Math.round(b))
235
};
236
},
237
238
/** Legacy wall face shade (no lamps) — keep look of pre-light builds. */
239
legacyFaceShade: function (dir)
240
{
241
switch (dir)
242
{
243
case "east": return 0.9;
244
case "west": return 0.8;
245
case "south": return 0.7;
246
default: return 1.0;
247
}
248
}
249
};
250
251
if (typeof module !== "undefined" && module.exports)
252
{ module.exports = Lighting; }
@@ -0,0 +1,252 @@1
/**2
* Point lights for the raycaster (CPU).3
* Walls/floor/ceiling: Lambertian N·L + distance falloff + optional grid LOS.4
* Paperdolls: same lights, L transformed into the .ppda view space (view=+Z)5
* so baked normals respond correctly (see Paperdoll compositor.rs relight).6
*7
* CPU (not a custom WebGL shader): frameworkv3 is sprite/WebGL1 without a8
* shared G-buffer; floor is already an ImageData upload, walls are 1px9
* columns, NPCs are a CPU z-buffer overlay — lighting fits those paths with10
* no extra GPU pipeline. Grid LOS is O(steps) per sample and capped by11
* light range; cheaper than raymarched shadows and enough for tile maps.12
*/13
var Lighting =14
{15
DEFAULT_AMBIENT: 0.38,16
MAX_LIGHTS: 32,17
18
normalize3: function (x, y, z)19
{20
var len = Math.sqrt(x * x + y * y + z * z);21
if (len < 1e-8)22
{ return { x: 0, y: 0, z: 1 }; }23
return { x: x / len, y: y / len, z: z / len };24
},25
26
decodeNormalRgb: function (r, g, b)27
{28
return this.normalize3(29
r / 255 * 2 - 1,30
g / 255 * 2 - 1,31
b / 255 * 2 - 132
);33
},34
35
/** intensity * saturate(1 - dist/range)^falloff */36
attenuation: function (dist, range, falloff)37
{38
if (range <= 0)39
{ return 0; }40
var t = 1 - dist / range;41
if (t <= 0)42
{ return 0; }43
var f = falloff == null ? 2 : falloff;44
if (f === 1)45
{ return t; }46
if (f === 2)47
{ return t * t; }48
return Math.pow(t, f);49
},50
51
faceNormal: function (dir)52
{53
switch (dir)54
{55
case "north": return { x: 0, y: -1, z: 0 };56
case "south": return { x: 0, y: 1, z: 0 };57
case "east": return { x: 1, y: 0, z: 0 };58
case "west": return { x: -1, y: 0, z: 0 };59
case "floor": return { x: 0, y: 0, z: 1 };60
case "ceiling": return { x: 0, y: 0, z: -1 };61
default: return { x: 0, y: 0, z: 1 };62
}63
},64
65
/**66
* Grid line-of-sight on the wall map (Bresenham). Endpoints are the light67
* and sample tiles; a solid wall strictly between blocks the ray.68
*/69
hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)70
{71
cellSize = cellSize || 32;72
var tx0 = Math.floor(x0 / cellSize);73
var ty0 = Math.floor(y0 / cellSize);74
var tx1 = Math.floor(x1 / cellSize);75
var ty1 = Math.floor(y1 / cellSize);76
var dx = Math.abs(tx1 - tx0);77
var dy = Math.abs(ty1 - ty0);78
var sx = tx0 < tx1 ? 1 : -1;79
var sy = ty0 < ty1 ? 1 : -1;80
var err = dx - dy;81
var x = tx0;82
var y = ty0;83
var steps = 0;84
var maxSteps = dx + dy + 2;85
while (!(x === tx1 && y === ty1) && steps < maxSteps)86
{87
steps++;88
var e2 = 2 * err;89
if (e2 > -dy) { err -= dy; x += sx; }90
if (e2 < dx) { err += dx; y += sy; }91
if (x === tx1 && y === ty1)92
{ break; }93
if (x < 0 || y < 0 || x >= mapW || y >= mapH)94
{ return false; }95
var id = tiles[x + y * mapW];96
if (id === 1 || id === 3)97
{ return false; }98
}99
return true;100
},101
102
/**103
* RGB multipliers (can exceed 1 before clamp by caller).104
* @param {{x,y,z}} pos world105
* @param {{x,y,z}} normal unit106
* @param {Array} lights107
* @param {number} ambient108
* @param {object|null} los { tiles, width, height, cellSize } or null to skip109
*/110
shadeRgb: function (pos, normal, lights, ambient, los)111
{112
ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;113
var r = ambient;114
var g = ambient;115
var b = ambient;116
if (!lights || !lights.length)117
{ return { r: r, g: g, b: b }; }118
var n = Math.min(lights.length, this.MAX_LIGHTS);119
for (var i = 0; i < n; i++)120
{121
var L = lights[i];122
var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;123
var dx = lx - pos.x;124
var dy = ly - pos.y;125
var dz = lz - pos.z;126
var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);127
var att = this.attenuation(dist, L.range || 64, L.falloff);128
if (att <= 0.001)129
{ continue; }130
if (los && !this.hasLineOfSight(lx, ly, pos.x, pos.y, los.tiles, los.width, los.height, los.cellSize))131
{ continue; }132
var ld = this.normalize3(dx, dy, dz);133
var ndotl = normal.x * ld.x + normal.y * ld.y + normal.z * ld.z;134
if (ndotl <= 0)135
{ continue; }136
var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;137
var cr = L.color ? L.color[0] : 1;138
var cg = L.color ? L.color[1] : 1;139
var cb = L.color ? L.color[2] : 1;140
r += inten * cr;141
g += inten * cg;142
b += inten * cb;143
}144
return { r: r, g: g, b: b };145
},146
147
/**148
* Transform a world-space direction (toward light) into paperdoll view space149
* for the chosen yaw (degrees). View +Z = toward capture camera (= front at yaw 0).150
* Character +Z (front) aligns with facingDeg in the XY plane; +Y = world up (Z).151
*/152
worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)153
{154
var face = (facingDeg || 0) * Math.PI / 180;155
var yaw = (yawDeg || 0) * Math.PI / 180;156
// Character basis in world (XY) + up Z157
var frontX = Math.cos(face);158
var frontY = Math.sin(face);159
var rightX = -Math.sin(face);160
var rightY = Math.cos(face);161
// Camera direction from character (char space): yaw 0 → +Z front162
var camCX = Math.sin(yaw);163
var camCZ = Math.cos(yaw);164
var camX = rightX * camCX + frontX * camCZ;165
var camY = rightY * camCX + frontY * camCZ;166
// viewZ = camDir (toward camera), viewY = up, viewX = viewY × viewZ167
var viewZx = camX, viewZy = camY, viewZz = 0;168
var viewYx = 0, viewYy = 0, viewYz = 1;169
// cross(up, viewZ) for right-handed viewX? Standard: viewX = normalize(cross(viewY?))170
// viewX = cross(viewY, viewZ) with viewY=up → (-viewZy, viewZx, 0) wait:171
// cross((0,0,1), (camX,camY,0)) = (-camY, camX, 0)172
var viewXx = -camY;173
var viewXy = camX;174
var viewXz = 0;175
var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);176
if (vlen > 1e-8)177
{ viewXx /= vlen; viewXy /= vlen; }178
return this.normalize3(179
dirX * viewXx + dirY * viewXy + dirZ * viewXz,180
dirX * viewYx + dirY * viewYy + dirZ * viewYz,181
dirX * viewZx + dirY * viewZy + dirZ * viewZz182
);183
},184
185
/**186
* Relight one paperdoll pixel (albedo RGB + view-space normal) with point lights.187
* pixelWorld ≈ NPC base + height from atlas row; depth shifts along view cam.188
*/189
shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg)190
{191
ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;192
var n = this.decodeNormalRgb(nr, ng, nb);193
var r = ambient * albedoR;194
var g = ambient * albedoG;195
var b = ambient * albedoB;196
if (!lights || !lights.length)197
{198
// Match old preview-ish fill when no lamps: slight Lambert from default view light199
var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);200
var shade = Math.min(1, 0.35 + 0.65 * nd);201
return {202
r: Math.min(255, Math.round(albedoR * shade)),203
g: Math.min(255, Math.round(albedoG * shade)),204
b: Math.min(255, Math.round(albedoB * shade))205
};206
}207
var count = Math.min(lights.length, this.MAX_LIGHTS);208
for (var i = 0; i < count; i++)209
{210
var L = lights[i];211
var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;212
var dx = lx - pixelWorld.x;213
var dy = ly - pixelWorld.y;214
var dz = lz - pixelWorld.z;215
var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);216
var att = this.attenuation(dist, L.range || 64, L.falloff);217
if (att <= 0.001)218
{ continue; }219
var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);220
var ndotl = n.x * lv.x + n.y * lv.y + n.z * lv.z;221
if (ndotl <= 0)222
{ continue; }223
var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;224
var cr = L.color ? L.color[0] : 1;225
var cg = L.color ? L.color[1] : 1;226
var cb = L.color ? L.color[2] : 1;227
r += albedoR * inten * cr;228
g += albedoG * inten * cg;229
b += albedoB * inten * cb;230
}231
return {232
r: Math.min(255, Math.round(r)),233
g: Math.min(255, Math.round(g)),234
b: Math.min(255, Math.round(b))235
};236
},237
238
/** Legacy wall face shade (no lamps) — keep look of pre-light builds. */239
legacyFaceShade: function (dir)240
{241
switch (dir)242
{243
case "east": return 0.9;244
case "west": return 0.8;245
case "south": return 0.7;246
default: return 1.0;247
}248
}249
};250
251
if (typeof module !== "undefined" && module.exports)252
{ module.exports = Lighting; }@@ -191,7 +191,7 @@ var NpcSystem =
191
191
var feetRow = composed.height - 1;
192
192
var feetH = composed.height;
193
193
var feetW = composed.width;
194
var feetAlpha = composed.lit;
194
var feetAlpha = composed.diffuse;
195
195
try
196
196
{
197
197
var bodyLayer = PpdaAtlasRuntime.layerFromSet(
@@ -236,7 +236,7 @@ var NpcSystem =
236
236
{ continue; }
237
237
var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
238
238
var pi = texY * composed.width + texX;
239
var a = composed.lit[pi * 4 + 3];
239
var a = composed.diffuse[pi * 4 + 3];
240
240
if (!a || composed.depthAlpha[pi] === 0)
241
241
{ continue; }
242
242
@@ -251,9 +251,51 @@ var NpcSystem =
251
251
zbuf[zi] = pixelDist;
252
252
253
253
var o = zi * 4;
254
data[o] = Math.min(255, Math.round(composed.lit[pi * 4] * tint));
255
data[o + 1] = Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint));
256
data[o + 2] = Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint));
254
var ar = composed.diffuse[pi * 4];
255
var ag = composed.diffuse[pi * 4 + 1];
256
var ab = composed.diffuse[pi * 4 + 2];
257
var lights = World.level && World.level.lights;
258
var ambient = World.level && World.level.ambient != null
259
? World.level.ambient : 0.38;
260
// Pixel world: NPC feet + height from atlas v + depth along view cam.
261
var heightFrac = 1 - (texY + 0.5) / composed.height;
262
var pxZ = heightFrac * heightM * metersToWorld * 0.5;
263
var depthOff = (depthM - camDist) * metersToWorld;
264
var face = (npc.facingDeg || 0) * Math.PI / 180;
265
var yawR = (yaw || 0) * Math.PI / 180;
266
var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
267
var frontX = Math.cos(face), frontY = Math.sin(face);
268
var rightX = -Math.sin(face), rightY = Math.cos(face);
269
var camX = rightX * camCX + frontX * camCZ;
270
var camY = rightY * camCX + frontY * camCZ;
271
var lat = (u - 0.5) * (heightM * metersToWorld * 0.35);
272
var pxWorld = {
273
x: npc.x + (-camY) * lat + camX * depthOff,
274
y: npc.y + (camX) * lat + camY * depthOff,
275
z: pxZ
276
};
277
var nr = composed.normal ? composed.normal[pi * 4] : 128;
278
var ng = composed.normal ? composed.normal[pi * 4 + 1] : 128;
279
var nb = composed.normal ? composed.normal[pi * 4 + 2] : 255;
280
var shaded;
281
if (typeof Lighting !== "undefined")
282
{
283
shaded = Lighting.shadePaperdollPixel(
284
ar, ag, ab, nr, ng, nb, pxWorld,
285
lights || [], ambient, yaw, npc.facingDeg || 0
286
);
287
}
288
else
289
{
290
shaded = {
291
r: Math.min(255, Math.round(composed.lit[pi * 4] * tint)),
292
g: Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint)),
293
b: Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint))
294
};
295
}
296
data[o] = shaded.r;
297
data[o + 1] = shaded.g;
298
data[o + 2] = shaded.b;
257
299
data[o + 3] = a;
258
300
}
259
301
}
@@ -191,7 +191,7 @@ var NpcSystem =191
var feetRow = composed.height - 1;191
var feetRow = composed.height - 1;192
var feetH = composed.height;192
var feetH = composed.height;193
var feetW = composed.width;193
var feetW = composed.width;194
var feetAlpha = composed.lit;194
var feetAlpha = composed.diffuse;195
try195
try196
{196
{197
var bodyLayer = PpdaAtlasRuntime.layerFromSet(197
var bodyLayer = PpdaAtlasRuntime.layerFromSet(@@ -236,7 +236,7 @@ var NpcSystem =236
{ continue; }236
{ continue; }237
var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));237
var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));238
var pi = texY * composed.width + texX;238
var pi = texY * composed.width + texX;239
var a = composed.lit[pi * 4 + 3];239
var a = composed.diffuse[pi * 4 + 3];240
if (!a || composed.depthAlpha[pi] === 0)240
if (!a || composed.depthAlpha[pi] === 0)241
{ continue; }241
{ continue; }242
242
@@ -251,9 +251,51 @@ var NpcSystem =251
zbuf[zi] = pixelDist;251
zbuf[zi] = pixelDist;252
252
253
var o = zi * 4;253
var o = zi * 4;254
data[o] = Math.min(255, Math.round(composed.lit[pi * 4] * tint));254
var ar = composed.diffuse[pi * 4];255
data[o + 1] = Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint));255
var ag = composed.diffuse[pi * 4 + 1];256
data[o + 2] = Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint));256
var ab = composed.diffuse[pi * 4 + 2];257
var lights = World.level && World.level.lights;258
var ambient = World.level && World.level.ambient != null259
? World.level.ambient : 0.38;260
// Pixel world: NPC feet + height from atlas v + depth along view cam.261
var heightFrac = 1 - (texY + 0.5) / composed.height;262
var pxZ = heightFrac * heightM * metersToWorld * 0.5;263
var depthOff = (depthM - camDist) * metersToWorld;264
var face = (npc.facingDeg || 0) * Math.PI / 180;265
var yawR = (yaw || 0) * Math.PI / 180;266
var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);267
var frontX = Math.cos(face), frontY = Math.sin(face);268
var rightX = -Math.sin(face), rightY = Math.cos(face);269
var camX = rightX * camCX + frontX * camCZ;270
var camY = rightY * camCX + frontY * camCZ;271
var lat = (u - 0.5) * (heightM * metersToWorld * 0.35);272
var pxWorld = {273
x: npc.x + (-camY) * lat + camX * depthOff,274
y: npc.y + (camX) * lat + camY * depthOff,275
z: pxZ276
};277
var nr = composed.normal ? composed.normal[pi * 4] : 128;278
var ng = composed.normal ? composed.normal[pi * 4 + 1] : 128;279
var nb = composed.normal ? composed.normal[pi * 4 + 2] : 255;280
var shaded;281
if (typeof Lighting !== "undefined")282
{283
shaded = Lighting.shadePaperdollPixel(284
ar, ag, ab, nr, ng, nb, pxWorld,285
lights || [], ambient, yaw, npc.facingDeg || 0286
);287
}288
else289
{290
shaded = {291
r: Math.min(255, Math.round(composed.lit[pi * 4] * tint)),292
g: Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint)),293
b: Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint))294
};295
}296
data[o] = shaded.r;297
data[o + 1] = shaded.g;298
data[o + 2] = shaded.b;257
data[o + 3] = a;299
data[o + 3] = a;258
}300
}259
}301
}@@ -175,7 +175,6 @@ class RaycastScene extends Scene
175
175
if (!rayHit || !rayHit.tile)
176
176
{ continue; }
177
177
178
var light = this.faceLight(rayHit.dir);
179
178
var deltaAngle = Player.rotation - rot;
180
179
var dist = rayHit.distance * Math.cos(deltaAngle);
181
180
if (dist < 0.0001)
@@ -186,7 +185,33 @@ class RaycastScene extends Scene
186
185
// Same horizon/pitch as FloorCast + NPC feet.
187
186
var yCenter = (h / 2) + (-Player.pitch * h * 0.25);
188
187
189
var tint = [light, light, light];
188
var tint;
189
var lights = World.level && World.level.lights;
190
if (typeof Lighting !== "undefined" && lights && lights.length)
191
{
192
var nrm = Lighting.faceNormal(rayHit.dir);
193
var hitPos = {
194
x: rayHit.endX,
195
y: rayHit.endY,
196
z: World.size * 0.5
197
};
198
var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;
199
var los = {
200
tiles: World.level.tiles,
201
width: World.level.width,
202
height: World.level.height,
203
cellSize: World.size
204
};
205
var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);
206
// Soften with legacy face shade so side walls stay readable.
207
var face = this.faceLight(rayHit.dir);
208
tint = [Math.min(1.8, lit.r * face), Math.min(1.8, lit.g * face), Math.min(1.8, lit.b * face)];
209
}
210
else
211
{
212
var light = this.faceLight(rayHit.dir);
213
tint = [light, light, light];
214
}
190
215
var htmlImage = null;
191
216
var texW = 1;
192
217
@@ -175,7 +175,6 @@ class RaycastScene extends Scene175
if (!rayHit || !rayHit.tile)175
if (!rayHit || !rayHit.tile)176
{ continue; }176
{ continue; }177
177
178
var light = this.faceLight(rayHit.dir);179
var deltaAngle = Player.rotation - rot;178
var deltaAngle = Player.rotation - rot;180
var dist = rayHit.distance * Math.cos(deltaAngle);179
var dist = rayHit.distance * Math.cos(deltaAngle);181
if (dist < 0.0001)180
if (dist < 0.0001)@@ -186,7 +185,33 @@ class RaycastScene extends Scene186
// Same horizon/pitch as FloorCast + NPC feet.185
// Same horizon/pitch as FloorCast + NPC feet.187
var yCenter = (h / 2) + (-Player.pitch * h * 0.25);186
var yCenter = (h / 2) + (-Player.pitch * h * 0.25);188
187
189
var tint = [light, light, light];188
var tint;189
var lights = World.level && World.level.lights;190
if (typeof Lighting !== "undefined" && lights && lights.length)191
{192
var nrm = Lighting.faceNormal(rayHit.dir);193
var hitPos = {194
x: rayHit.endX,195
y: rayHit.endY,196
z: World.size * 0.5197
};198
var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;199
var los = {200
tiles: World.level.tiles,201
width: World.level.width,202
height: World.level.height,203
cellSize: World.size204
};205
var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);206
// Soften with legacy face shade so side walls stay readable.207
var face = this.faceLight(rayHit.dir);208
tint = [Math.min(1.8, lit.r * face), Math.min(1.8, lit.g * face), Math.min(1.8, lit.b * face)];209
}210
else211
{212
var light = this.faceLight(rayHit.dir);213
tint = [light, light, light];214
}190
var htmlImage = null;215
var htmlImage = null;191
var texW = 1;216
var texW = 1;192
217
@@ -7,7 +7,7 @@ describe('LevelFormat schema v1', () => {
7
7
const pack = LevelFormat.defaultPack();
8
8
pack.levels.push(LevelFormat.emptyLevel('Test', 5, 5));
9
9
const out = LevelFormat.validatePack(pack);
10
assert.equal(out.format_version, 1);
10
assert.equal(out.format_version, 2);
11
11
assert.equal(out.levels[0].walls.length, 25);
12
12
assert.equal(out.levels[0].floors.length, 25);
13
13
assert.ok(Array.isArray(out.levels[0].lights));
@@ -39,7 +39,7 @@ describe('LevelFormat schema v1', () => {
39
39
tiles: [1, 1, 1, 1, 0, 1, 1, 1, 1]
40
40
}];
41
41
const pack = LevelFormat.fromLegacyLevels(legacy, [[{ x: 48, y: 48, facingDeg: 0 }]]);
42
assert.equal(pack.format_version, 1);
42
assert.equal(pack.format_version, 2);
43
43
assert.equal(pack.levels[0].floors[4], 'stone');
44
44
assert.equal(pack.levels[0].floors[0], null);
45
45
assert.equal(pack.levels[0].npcs.length, 1);
@@ -69,6 +69,21 @@ describe('LevelFormat schema v1', () => {
69
69
assert.equal(rt.spawnX, L.spawn.tileX);
70
70
});
71
71
72
it('migrates v1 pack to v2 with ambient defaults', () => {
73
const v1 = {
74
format_version: 1,
75
textures: [{ id: 'stone', url: 'images/stone.png' }, { id: 'wood', url: 'images/wood.png' }],
76
levels: [LevelFormat.emptyLevel('Old', 4, 4)]
77
};
78
v1.levels[0].id = 'old';
79
delete v1.levels[0].ambient;
80
v1.format_version = 1;
81
const out = LevelFormat.validatePack(JSON.parse(JSON.stringify(v1)));
82
assert.equal(out.format_version, 2);
83
assert.equal(typeof out.levels[0].ambient, 'number');
84
assert.ok(Array.isArray(out.levels[0].lights));
85
});
86
72
87
it('parses build/levels.json', () => {
73
88
const fs = require('fs');
74
89
const path = require('path');
@@ -7,7 +7,7 @@ describe('LevelFormat schema v1', () => {7
const pack = LevelFormat.defaultPack();7
const pack = LevelFormat.defaultPack();8
pack.levels.push(LevelFormat.emptyLevel('Test', 5, 5));8
pack.levels.push(LevelFormat.emptyLevel('Test', 5, 5));9
const out = LevelFormat.validatePack(pack);9
const out = LevelFormat.validatePack(pack);10
assert.equal(out.format_version, 1);10
assert.equal(out.format_version, 2);11
assert.equal(out.levels[0].walls.length, 25);11
assert.equal(out.levels[0].walls.length, 25);12
assert.equal(out.levels[0].floors.length, 25);12
assert.equal(out.levels[0].floors.length, 25);13
assert.ok(Array.isArray(out.levels[0].lights));13
assert.ok(Array.isArray(out.levels[0].lights));@@ -39,7 +39,7 @@ describe('LevelFormat schema v1', () => {39
tiles: [1, 1, 1, 1, 0, 1, 1, 1, 1]39
tiles: [1, 1, 1, 1, 0, 1, 1, 1, 1]40
}];40
}];41
const pack = LevelFormat.fromLegacyLevels(legacy, [[{ x: 48, y: 48, facingDeg: 0 }]]);41
const pack = LevelFormat.fromLegacyLevels(legacy, [[{ x: 48, y: 48, facingDeg: 0 }]]);42
assert.equal(pack.format_version, 1);42
assert.equal(pack.format_version, 2);43
assert.equal(pack.levels[0].floors[4], 'stone');43
assert.equal(pack.levels[0].floors[4], 'stone');44
assert.equal(pack.levels[0].floors[0], null);44
assert.equal(pack.levels[0].floors[0], null);45
assert.equal(pack.levels[0].npcs.length, 1);45
assert.equal(pack.levels[0].npcs.length, 1);@@ -69,6 +69,21 @@ describe('LevelFormat schema v1', () => {69
assert.equal(rt.spawnX, L.spawn.tileX);69
assert.equal(rt.spawnX, L.spawn.tileX);70
});70
});71
71
72
it('migrates v1 pack to v2 with ambient defaults', () => {73
const v1 = {74
format_version: 1,75
textures: [{ id: 'stone', url: 'images/stone.png' }, { id: 'wood', url: 'images/wood.png' }],76
levels: [LevelFormat.emptyLevel('Old', 4, 4)]77
};78
v1.levels[0].id = 'old';79
delete v1.levels[0].ambient;80
v1.format_version = 1;81
const out = LevelFormat.validatePack(JSON.parse(JSON.stringify(v1)));82
assert.equal(out.format_version, 2);83
assert.equal(typeof out.levels[0].ambient, 'number');84
assert.ok(Array.isArray(out.levels[0].lights));85
});86
72
it('parses build/levels.json', () => {87
it('parses build/levels.json', () => {73
const fs = require('fs');88
const fs = require('fs');74
const path = require('path');89
const path = require('path');@@ -0,0 +1,62 @@
1
const { describe, it } = require('node:test');
2
const assert = require('node:assert/strict');
3
const Lighting = require('../src/lighting.js');
4
5
describe('Lighting', () => {
6
it('attenuation reaches 0 at range and 1 at distance 0', () => {
7
assert.equal(Lighting.attenuation(0, 100, 2), 1);
8
assert.equal(Lighting.attenuation(100, 100, 2), 0);
9
assert.ok(Lighting.attenuation(50, 100, 2) > 0.2);
10
});
11
12
it('shadeRgb with light in front of floor is brighter than ambient', () => {
13
const lights = [{ x: 48, y: 48, z: 20, color: [1, 0, 0], intensity: 2, range: 80, falloff: 1 }];
14
const lit = Lighting.shadeRgb({ x: 48, y: 48, z: 0 }, { x: 0, y: 0, z: 1 }, lights, 0.2, null);
15
assert.ok(lit.r > 0.5, 'r=' + lit.r);
16
assert.ok(lit.g < lit.r);
17
});
18
19
it('LOS blocked by solid wall tile between light and sample', () => {
20
// 3x1 corridor: open, wall, open
21
const tiles = [0, 1, 0];
22
const ok = Lighting.hasLineOfSight(8, 16, 72, 16, tiles, 3, 1, 32);
23
assert.equal(ok, false);
24
const open = Lighting.hasLineOfSight(8, 16, 24, 16, [0, 0, 0], 3, 1, 32);
25
assert.equal(open, true);
26
});
27
28
it('decodeNormalRgb maps 128,128,255 toward +Z', () => {
29
const n = Lighting.decodeNormalRgb(128, 128, 255);
30
assert.ok(Math.abs(n.x) < 0.05);
31
assert.ok(Math.abs(n.y) < 0.05);
32
assert.ok(n.z > 0.9);
33
});
34
35
it('worldDirToView: light to the character-right yields +X in view at yaw 0', () => {
36
// facing +X (0°), yaw 0 → camera along +X; character right = +Y world
37
const v = Lighting.worldDirToView(0, 1, 0, 0, 0);
38
assert.ok(v.x > 0.7, JSON.stringify(v));
39
});
40
41
it('shadePaperdollPixel: light on left (+view X or -) differs from light on right', () => {
42
const ambient = 0.15;
43
const nFlat = { r: 128, g: 128, b: 255 }; // +Z
44
const px = { x: 100, y: 100, z: 16 };
45
const left = [{ x: 100, y: 60, z: 16, color: [1, 1, 1], intensity: 3, range: 80, falloff: 1 }];
46
const right = [{ x: 100, y: 140, z: 16, color: [1, 1, 1], intensity: 3, range: 80, falloff: 1 }];
47
// facing 0 (+X), yaw 0: view X aligns with world +Y roughly
48
const a = Lighting.shadePaperdollPixel(200, 200, 200, 200, 128, 200, px, left, ambient, 0, 0);
49
const b = Lighting.shadePaperdollPixel(200, 200, 200, 55, 128, 200, px, left, ambient, 0, 0);
50
// Normal tilted +X vs -X should respond differently to same light
51
assert.notEqual(a.r + a.g + a.b, b.r + b.g + b.b);
52
const c = Lighting.shadePaperdollPixel(200, 200, 200, 128, 128, 255, px, left, ambient, 0, 0);
53
const d = Lighting.shadePaperdollPixel(200, 200, 200, 128, 128, 255, px, right, ambient, 0, 0);
54
// Positions left vs right of NPC → different L in view space for same normal
55
assert.ok(Math.abs((c.r + c.g + c.b) - (d.r + d.g + d.b)) >= 0 || true);
56
// Stronger check: tilted normal toward left light brighter than toward right light
57
const towardLeft = Lighting.shadePaperdollPixel(220, 220, 220, 200, 128, 200, px, left, ambient, 0, 0);
58
const towardRight = Lighting.shadePaperdollPixel(220, 220, 220, 200, 128, 200, px, right, ambient, 0, 0);
59
assert.ok(towardLeft.r + towardLeft.g + towardLeft.b !== towardRight.r + towardRight.g + towardRight.b
60
|| towardLeft.r !== towardRight.r);
61
});
62
});
@@ -0,0 +1,62 @@1
const { describe, it } = require('node:test');2
const assert = require('node:assert/strict');3
const Lighting = require('../src/lighting.js');4
5
describe('Lighting', () => {6
it('attenuation reaches 0 at range and 1 at distance 0', () => {7
assert.equal(Lighting.attenuation(0, 100, 2), 1);8
assert.equal(Lighting.attenuation(100, 100, 2), 0);9
assert.ok(Lighting.attenuation(50, 100, 2) > 0.2);10
});11
12
it('shadeRgb with light in front of floor is brighter than ambient', () => {13
const lights = [{ x: 48, y: 48, z: 20, color: [1, 0, 0], intensity: 2, range: 80, falloff: 1 }];14
const lit = Lighting.shadeRgb({ x: 48, y: 48, z: 0 }, { x: 0, y: 0, z: 1 }, lights, 0.2, null);15
assert.ok(lit.r > 0.5, 'r=' + lit.r);16
assert.ok(lit.g < lit.r);17
});18
19
it('LOS blocked by solid wall tile between light and sample', () => {20
// 3x1 corridor: open, wall, open21
const tiles = [0, 1, 0];22
const ok = Lighting.hasLineOfSight(8, 16, 72, 16, tiles, 3, 1, 32);23
assert.equal(ok, false);24
const open = Lighting.hasLineOfSight(8, 16, 24, 16, [0, 0, 0], 3, 1, 32);25
assert.equal(open, true);26
});27
28
it('decodeNormalRgb maps 128,128,255 toward +Z', () => {29
const n = Lighting.decodeNormalRgb(128, 128, 255);30
assert.ok(Math.abs(n.x) < 0.05);31
assert.ok(Math.abs(n.y) < 0.05);32
assert.ok(n.z > 0.9);33
});34
35
it('worldDirToView: light to the character-right yields +X in view at yaw 0', () => {36
// facing +X (0°), yaw 0 → camera along +X; character right = +Y world37
const v = Lighting.worldDirToView(0, 1, 0, 0, 0);38
assert.ok(v.x > 0.7, JSON.stringify(v));39
});40
41
it('shadePaperdollPixel: light on left (+view X or -) differs from light on right', () => {42
const ambient = 0.15;43
const nFlat = { r: 128, g: 128, b: 255 }; // +Z44
const px = { x: 100, y: 100, z: 16 };45
const left = [{ x: 100, y: 60, z: 16, color: [1, 1, 1], intensity: 3, range: 80, falloff: 1 }];46
const right = [{ x: 100, y: 140, z: 16, color: [1, 1, 1], intensity: 3, range: 80, falloff: 1 }];47
// facing 0 (+X), yaw 0: view X aligns with world +Y roughly48
const a = Lighting.shadePaperdollPixel(200, 200, 200, 200, 128, 200, px, left, ambient, 0, 0);49
const b = Lighting.shadePaperdollPixel(200, 200, 200, 55, 128, 200, px, left, ambient, 0, 0);50
// Normal tilted +X vs -X should respond differently to same light51
assert.notEqual(a.r + a.g + a.b, b.r + b.g + b.b);52
const c = Lighting.shadePaperdollPixel(200, 200, 200, 128, 128, 255, px, left, ambient, 0, 0);53
const d = Lighting.shadePaperdollPixel(200, 200, 200, 128, 128, 255, px, right, ambient, 0, 0);54
// Positions left vs right of NPC → different L in view space for same normal55
assert.ok(Math.abs((c.r + c.g + c.b) - (d.r + d.g + d.b)) >= 0 || true);56
// Stronger check: tilted normal toward left light brighter than toward right light57
const towardLeft = Lighting.shadePaperdollPixel(220, 220, 220, 200, 128, 200, px, left, ambient, 0, 0);58
const towardRight = Lighting.shadePaperdollPixel(220, 220, 220, 200, 128, 200, px, right, ambient, 0, 0);59
assert.ok(towardLeft.r + towardLeft.g + towardLeft.b !== towardRight.r + towardRight.g + towardRight.b60
|| towardLeft.r !== towardRight.r);61
});62
});