BlueGit

timfa raytracer

Files

raytracer / src / editorApp.js

editorApp.js

editorApp.js 16.9 KiB Download Raw
1/**
2 * Simple grid level editor (2D canvas). Uses LevelFormat for validation.
3 */
4(function ()
5{
6 var STORAGE_KEY = "raytracer-levels-v1";
7 var pack = null;
8 var levelIndex = 0;
9 var tool = "wall"; // wall | floor | ceiling | spawn | npc | light
10var selectedLight = -1;
11 var brushWall = 1;
12 var brushTex = "stone"; // or null via "none"
13 var cellPx = 28;
14 var painting = false;
15 var selectedNpc = -1;
16
17 var canvas = null;
18 var ctx = null;
19 var texPreviews = {};
20
21 function level ()
22 { return pack.levels[levelIndex]; }
23
24 function idx (x, y)
25 { return x + y * level().width; }
26
27 function loadPreviews ()
28 {
29 ["stone", "wood"].forEach(function (id)
30 {
31 var img = new Image();
32 img.onload = function ()
33 { texPreviews[id] = img; redraw(); };
34 img.src = "images/" + id + ".png";
35 });
36 }
37
38 function ensurePack (raw)
39 {
40 pack = LevelFormat.validatePack(raw);
41 if (levelIndex >= pack.levels.length)
42 { levelIndex = 0; }
43 refreshLevelSelect();
44 redraw();
45 saveLocal();
46 }
47
48 function saveLocal ()
49 {
50 try
51 { localStorage.setItem(STORAGE_KEY, JSON.stringify(pack)); }
52 catch (e) { /* ignore */ }
53 }
54
55 function refreshLevelSelect ()
56 {
57 var sel = document.getElementById("level-select");
58 sel.innerHTML = "";
59 pack.levels.forEach(function (L, i)
60 {
61 var o = document.createElement("option");
62 o.value = String(i);
63 o.textContent = L.name;
64 if (i === levelIndex)
65 { o.selected = true; }
66 sel.appendChild(o);
67 });
68 document.getElementById("level-name").value = level().name;
69 document.getElementById("level-w").value = level().width;
70 document.getElementById("level-h").value = level().height;
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 });
102 }
103
104 function refreshNpcList ()
105 {
106 var ul = document.getElementById("npc-list");
107 ul.innerHTML = "";
108 (level().npcs || []).forEach(function (n, i)
109 {
110 var li = document.createElement("li");
111 li.textContent = (n.label || "npc") + " @" + Math.round(n.x) + "," + Math.round(n.y) + " yaw " + n.facingDeg;
112 li.style.cursor = "pointer";
113 if (i === selectedNpc)
114 { li.style.background = "#345"; }
115 li.onclick = function ()
116 {
117 selectedNpc = i;
118 document.getElementById("npc-yaw").value = n.facingDeg;
119 document.getElementById("npc-clip").value = n.clip || "walk";
120 document.getElementById("npc-anim").checked = !!n.animating;
121 refreshNpcList();
122 redraw();
123 };
124 ul.appendChild(li);
125 });
126 }
127
128 function redraw ()
129 {
130 var L = level();
131 canvas.width = L.width * cellPx;
132 canvas.height = L.height * cellPx;
133 ctx.fillStyle = "#111";
134 ctx.fillRect(0, 0, canvas.width, canvas.height);
135 for (var y = 0; y < L.height; y++)
136 {
137 for (var x = 0; x < L.width; x++)
138 {
139 var i = idx(x, y);
140 var px = x * cellPx;
141 var py = y * cellPx;
142 var floor = L.floors[i];
143 if (floor && texPreviews[floor])
144 { ctx.drawImage(texPreviews[floor], px, py, cellPx, cellPx); }
145 else if (floor)
146 {
147 ctx.fillStyle = floor === "wood" ? "#a66" : "#888";
148 ctx.fillRect(px, py, cellPx, cellPx);
149 }
150 var wall = L.walls[i];
151 if (wall === 1 || wall === 3)
152 {
153 ctx.globalAlpha = 0.85;
154 var tid = wall === 3 ? "wood" : "stone";
155 if (texPreviews[tid])
156 { ctx.drawImage(texPreviews[tid], px, py, cellPx, cellPx); }
157 else
158 {
159 ctx.fillStyle = wall === 3 ? "#84a" : "#555";
160 ctx.fillRect(px, py, cellPx, cellPx);
161 }
162 ctx.globalAlpha = 1;
163 ctx.strokeStyle = "#fff";
164 ctx.strokeRect(px + 0.5, py + 0.5, cellPx - 1, cellPx - 1);
165 }
166 else if (wall === 2)
167 {
168 ctx.fillStyle = "rgba(255,220,0,0.35)";
169 ctx.fillRect(px, py, cellPx, cellPx);
170 }
171 if (L.ceilings[i])
172 {
173 ctx.fillStyle = "rgba(100,160,255,0.15)";
174 ctx.fillRect(px, py, cellPx, 4);
175 }
176 }
177 }
178 // spawn
179 ctx.fillStyle = "#0f0";
180 ctx.beginPath();
181 ctx.arc(L.spawn.tileX * cellPx + cellPx / 2, L.spawn.tileY * cellPx + cellPx / 2, 6, 0, Math.PI * 2);
182 ctx.fill();
183 var ang = L.spawn.yawRad || 0;
184 ctx.strokeStyle = "#0f0";
185 ctx.beginPath();
186 ctx.moveTo(L.spawn.tileX * cellPx + cellPx / 2, L.spawn.tileY * cellPx + cellPx / 2);
187 ctx.lineTo(
188 L.spawn.tileX * cellPx + cellPx / 2 + Math.cos(ang) * 14,
189 L.spawn.tileY * cellPx + cellPx / 2 + Math.sin(ang) * 14
190 );
191 ctx.stroke();
192 // npcs
193 (L.npcs || []).forEach(function (n, i)
194 {
195 var nx = (n.x / (L.cellSize || 32)) * cellPx;
196 var ny = (n.y / (L.cellSize || 32)) * cellPx;
197 ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";
198 ctx.fillRect(nx - 5, ny - 5, 10, 10);
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
221 ctx.strokeStyle = "#333";
222 for (var gx = 0; gx <= L.width; gx++)
223 {
224 ctx.beginPath();
225 ctx.moveTo(gx * cellPx + 0.5, 0);
226 ctx.lineTo(gx * cellPx + 0.5, canvas.height);
227 ctx.stroke();
228 }
229 for (var gy = 0; gy <= L.height; gy++)
230 {
231 ctx.beginPath();
232 ctx.moveTo(0, gy * cellPx + 0.5);
233 ctx.lineTo(canvas.width, gy * cellPx + 0.5);
234 ctx.stroke();
235 }
236 }
237
238 function cellFromEvent (e)
239 {
240 var r = canvas.getBoundingClientRect();
241 var x = Math.floor((e.clientX - r.left) / cellPx);
242 var y = Math.floor((e.clientY - r.top) / cellPx);
243 if (x < 0 || y < 0 || x >= level().width || y >= level().height)
244 { return null; }
245 return { x: x, y: y };
246 }
247
248 function paintAt (x, y)
249 {
250 var L = level();
251 var i = idx(x, y);
252 if (tool === "wall")
253 { L.walls[i] = brushWall; }
254 else if (tool === "floor")
255 { L.floors[i] = brushTex === "none" ? null : brushTex; }
256 else if (tool === "ceiling")
257 { L.ceilings[i] = brushTex === "none" ? null : brushTex; }
258 else if (tool === "spawn")
259 {
260 L.spawn.tileX = x;
261 L.spawn.tileY = y;
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 }
280 else if (tool === "npc")
281 {
282 var cs = L.cellSize || 32;
283 L.npcs.push({
284 x: x * cs + cs / 2,
285 y: y * cs + cs / 2,
286 facingDeg: Number(document.getElementById("npc-yaw").value) || 0,
287 clip: document.getElementById("npc-clip").value || "walk",
288 animating: document.getElementById("npc-anim").checked,
289 label: "npc" + (L.npcs.length + 1),
290 body: "paperdolls/male-body/",
291 bodyPpda: "male-body-atlas.ppda",
292 gear: "paperdolls/male-sword/",
293 gearPpda: "male-sword-atlas.ppda"
294 });
295 selectedNpc = L.npcs.length - 1;
296 refreshNpcList();
297 }
298 redraw();
299 saveLocal();
300 }
301
302 function resizeLevel (nw, nh)
303 {
304 var L = level();
305 nw = Math.max(3, Math.min(LevelFormat.MAX_SIZE, nw | 0));
306 nh = Math.max(3, Math.min(LevelFormat.MAX_SIZE, nh | 0));
307 var walls = [];
308 var floors = [];
309 var ceilings = [];
310 for (var y = 0; y < nh; y++)
311 {
312 for (var x = 0; x < nw; x++)
313 {
314 if (x < L.width && y < L.height)
315 {
316 var i = idx(x, y);
317 walls.push(L.walls[i]);
318 floors.push(L.floors[i]);
319 ceilings.push(L.ceilings[i]);
320 }
321 else
322 {
323 var border = x === 0 || y === 0 || x === nw - 1 || y === nh - 1;
324 walls.push(border ? 1 : 0);
325 floors.push(border ? null : "stone");
326 ceilings.push(border ? null : "stone");
327 }
328 }
329 }
330 L.width = nw;
331 L.height = nh;
332 L.walls = walls;
333 L.floors = floors;
334 L.ceilings = ceilings;
335 if (L.spawn.tileX >= nw) L.spawn.tileX = nw - 2;
336 if (L.spawn.tileY >= nh) L.spawn.tileY = nh - 2;
337 refreshLevelSelect();
338 redraw();
339 saveLocal();
340 }
341
342 function boot (initial)
343 {
344 canvas = document.getElementById("grid");
345 ctx = canvas.getContext("2d");
346 ensurePack(initial);
347 loadPreviews();
348
349 document.getElementById("level-select").onchange = function (e)
350 {
351 levelIndex = Number(e.target.value) | 0;
352 selectedNpc = -1;
353 refreshLevelSelect();
354 redraw();
355 };
356 document.getElementById("level-name").onchange = function (e)
357 {
358 level().name = e.target.value || level().name;
359 refreshLevelSelect();
360 saveLocal();
361 };
362 document.getElementById("btn-add-level").onclick = function ()
363 {
364 pack.levels.push(LevelFormat.emptyLevel("Level " + (pack.levels.length + 1), 10, 10));
365 levelIndex = pack.levels.length - 1;
366 refreshLevelSelect();
367 redraw();
368 saveLocal();
369 };
370 document.getElementById("btn-dup-level").onclick = function ()
371 {
372 var c = LevelFormat.cloneLevel(level());
373 c.id = "level-" + Date.now().toString(36);
374 c.name = level().name + " (kopie)";
375 pack.levels.push(c);
376 levelIndex = pack.levels.length - 1;
377 refreshLevelSelect();
378 redraw();
379 saveLocal();
380 };
381 document.getElementById("btn-del-level").onclick = function ()
382 {
383 if (pack.levels.length <= 1)
384 { return alert("Minstens één level houden"); }
385 if (!confirm("Level verwijderen?"))
386 { return; }
387 pack.levels.splice(levelIndex, 1);
388 levelIndex = Math.min(levelIndex, pack.levels.length - 1);
389 refreshLevelSelect();
390 redraw();
391 saveLocal();
392 };
393 document.getElementById("btn-resize").onclick = function ()
394 {
395 resizeLevel(Number(document.getElementById("level-w").value), Number(document.getElementById("level-h").value));
396 };
397
398 document.querySelectorAll("[data-tool]").forEach(function (el)
399 {
400 el.onclick = function ()
401 {
402 tool = el.getAttribute("data-tool");
403 document.querySelectorAll("[data-tool]").forEach(function (b)
404 { b.classList.toggle("active", b === el); });
405 };
406 });
407 document.querySelectorAll("[data-wall]").forEach(function (el)
408 {
409 el.onclick = function ()
410 {
411 brushWall = Number(el.getAttribute("data-wall"));
412 tool = "wall";
413 };
414 });
415 document.querySelectorAll("[data-tex]").forEach(function (el)
416 {
417 el.onclick = function ()
418 {
419 brushTex = el.getAttribute("data-tex");
420 if (brushTex === "none")
421 { brushTex = "none"; }
422 };
423 });
424
425 var draggingLight = false;
426 canvas.onmousedown = function (e)
427 {
428 var c = cellFromEvent(e);
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);
452 };
453 canvas.onmousemove = function (e)
454 {
455 var c = cellFromEvent(e);
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);
468 };
469 window.onmouseup = function ()
470 {
471 if (draggingLight) { saveLocal(); refreshLightList(); }
472 painting = false;
473 draggingLight = false;
474 };
475
476 document.getElementById("spawn-yaw").onchange = function (e)
477 {
478 level().spawn.yawRad = (Number(e.target.value) || 0) * Math.PI / 180;
479 redraw();
480 saveLocal();
481 };
482 document.getElementById("btn-del-npc").onclick = function ()
483 {
484 if (selectedNpc < 0)
485 { return; }
486 level().npcs.splice(selectedNpc, 1);
487 selectedNpc = -1;
488 refreshNpcList();
489 redraw();
490 saveLocal();
491 };
492 document.getElementById("npc-yaw").onchange = function (e)
493 {
494 if (selectedNpc >= 0)
495 {
496 level().npcs[selectedNpc].facingDeg = Number(e.target.value) || 0;
497 refreshNpcList();
498 redraw();
499 saveLocal();
500 }
501 };
502 document.getElementById("npc-clip").onchange = function (e)
503 {
504 if (selectedNpc >= 0)
505 {
506 level().npcs[selectedNpc].clip = e.target.value;
507 saveLocal();
508 }
509 };
510 document.getElementById("npc-anim").onchange = function (e)
511 {
512 if (selectedNpc >= 0)
513 {
514 level().npcs[selectedNpc].animating = e.target.checked;
515 saveLocal();
516 }
517 };
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
559 document.getElementById("btn-download").onclick = function ()
560 {
561 try
562 { LevelFormat.validatePack(pack); }
563 catch (err)
564 { return alert(err.message); }
565 var blob = new Blob([JSON.stringify(pack, null, 2)], { type: "application/json" });
566 var a = document.createElement("a");
567 a.href = URL.createObjectURL(blob);
568 a.download = "levels.json";
569 a.click();
570 };
571 document.getElementById("file-upload").onchange = function (e)
572 {
573 var f = e.target.files[0];
574 if (!f)
575 { return; }
576 var reader = new FileReader();
577 reader.onload = function ()
578 {
579 try
580 { ensurePack(LevelFormat.parse(String(reader.result))); }
581 catch (err)
582 { alert(err.message); }
583 };
584 reader.readAsText(f);
585 };
586 document.getElementById("btn-play").onclick = function ()
587 {
588 try
589 { LevelFormat.validatePack(pack); }
590 catch (err)
591 { return alert(err.message); }
592 saveLocal();
593 window.location.href = "index.html?playtest=1&level=" + encodeURIComponent(level().id);
594 };
595 document.getElementById("btn-reload-repo").onclick = function ()
596 {
597 fetch("levels.json").then(function (r)
598 { return r.text(); }).then(function (t)
599 { ensurePack(LevelFormat.parse(t)); }).catch(function (e)
600 { alert(e.message); });
601 };
602 }
603
604 window.EditorApp = {
605 start: function ()
606 {
607 var local = null;
608 try
609 { local = localStorage.getItem(STORAGE_KEY); }
610 catch (e) { /* */ }
611 var bootFrom = function (text)
612 { boot(LevelFormat.parse(text)); };
613 if (local)
614 {
615 try
616 { return boot(LevelFormat.parse(local)); }
617 catch (e)
618 { console.warn("localStorage levels ongeldig, repo laden", e); }
619 }
620 fetch("levels.json").then(function (r)
621 { return r.text(); }).then(bootFrom).catch(function (e)
622 {
623 alert("Kon levels niet laden: " + e.message);
624 boot(LevelFormat.defaultPack());
625 pack.levels.push(LevelFormat.emptyLevel("Level 1", 10, 10));
626 ensurePack(pack);
627 });
628 }
629 };
630})();