BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 35.6 KiB Download Raw
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import {
3 GROUND_DEFINITIONS,
4 BLOCK_DEFINITIONS,
5 GroundType,
6 BlockType,
7 normalizeGround,
8 normalizeBlock,
9 listPlaceableBlockPaletteEntries
10} from "/shared/definitions/tiles.js";
11import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
12import {
13 SeasonId,
14 seasonIdAt,
15 seasonalCycleStates,
16 seasonIdFromVisualState,
17 placeableStatesForType
18} from "/shared/world/season.js";
19import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
20import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
21import {
22 computeNeighborConnectMask,
23 composeNeighborConnectState,
24 definitionUsesNeighborConnect,
25 neighborConnectBlocksMatch
26} from "/shared/world/neighborConnect.js";
27import { GameSocket, defaultSocketUrl } from "../net/socket.js";
28import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
29import { WorldView } from "../render/worldView.js";
30import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
31import { initPaletteModal } from "./paletteModal.js";
32import { initTileConfigModal } from "./tileConfigModal.js";
33import { initQuestsModal } from "./questsModal.js";
34import { initDialoguesModal } from "./dialoguesModal.js";
35import { createDimensionCombobox } from "./dimensionCombobox.js";
36import {
37 OVERWORLD_ID,
38 normalizeDimensionId,
39 isOverworld
40} from "/shared/world/dimensions.js";
41
42const game = new Game();
43let socket;
44let scene;
45let view;
46let draft = null;
47/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
48let draftBaseline = null;
49/** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */
50let pendingNavigate = null;
51/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
52let navigateAfterSave = false;
53let chunkX = 0;
54let chunkY = 0;
55let selectedDimensionId = OVERWORLD_ID;
56/** @type {string|null} */
57let pendingCreatedDimensionId = null;
58/** @type {Map<string, object>} */
59let dimensionsById = new Map();
60let dimensionCombo = null;
61let dimensionSettings = null;
62let tool = { kind: "ground", typeId: GroundType.grass, state: null };
63let settingsModal;
64let paletteModal;
65let tileConfigModal;
66let questsModal;
67let dialoguesModal;
68let catalog = { grounds: {}, blocks: {}, images: [] };
69let imageUrlByName = new Map();
70let hoverLocal = null;
71let editorZoom = null;
72let activeRevisionId = null;
73let pendingRevisionId = null;
74let applyInFlight = false;
75const EDITOR_ZOOM_MIN = 0.25;
76const EDITOR_ZOOM_MAX = 8;
77const EDITOR_ZOOM_STEP = 1.12;
78
79function $ (id)
80{
81 return document.getElementById(id);
82}
83
84function selectedToolLabel ()
85{
86 if (tool.kind === "erase")
87 { return "Erase block"; }
88 if (tool.kind === "spawner")
89 {
90 const def = mobDefinition(tool.mobTypeId);
91 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
92 }
93 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
94 const layer = tool.kind === "ground" ? "ground" : "block";
95 const states = statesForType(catalog, layer, def.key);
96 const state = resolveState(states, tool.state);
97 if (tool.kind === "block" && def.id === BlockType.flower)
98 { return "Flower"; }
99 if (tool.kind === "block" && def.id === BlockType.boulder)
100 {
101 const entry = listPlaceableBlockPaletteEntries(catalog)
102 .find((row) => row.typeId === def.id && row.state === state);
103 if (entry)
104 { return entry.displayName; }
105 }
106 if (states.length > 1)
107 { return `${def.displayName} (${state})`; }
108 return def.displayName;
109}
110
111function selectTool (next)
112{
113 if (next.kind === "erase")
114 {
115 tool = { kind: "erase" };
116 return;
117 }
118 if (next.kind === "spawner")
119 {
120 tool = { kind: "spawner", mobTypeId: next.mobTypeId };
121 return;
122 }
123 const layer = next.kind === "ground" ? "ground" : "block";
124 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
125 tool = {
126 kind: next.kind,
127 typeId: next.typeId,
128 state: next.state ?? defaultStateForType(catalog, layer, def.key)
129 };
130}
131
132function placeableToolState ()
133{
134 if (tool.kind === "erase" || tool.kind === "spawner")
135 { return null; }
136 const layer = tool.kind === "ground" ? "ground" : "block";
137 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
138 return resolveState(statesForType(catalog, layer, def.key), tool.state);
139}
140
141function previewFromTool ()
142{
143 if (tool.kind === "erase")
144 { return { block: null }; }
145 if (tool.kind === "spawner")
146 { return {}; }
147 const state = placeableToolState();
148 if (tool.kind === "ground")
149 { return { ground: { typeId: tool.typeId, state } }; }
150 return { block: { typeId: tool.typeId, state, config: null } };
151}
152
153function inEditorView (x, y)
154{
155 return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS;
156}
157
158function neighborhoodCoords (centerX, centerY)
159{
160 const coords = [];
161 for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++)
162 {
163 for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++)
164 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
165 }
166 return coords;
167}
168
169function snapshotFromPayload (payload)
170{
171 return {
172 chunkX: payload.chunkX,
173 chunkY: payload.chunkY,
174 open: payload.data.open,
175 closedEdges: payload.closedEdges,
176 grounds: payload.data.grounds,
177 blocks: payload.data.blocks,
178 light: payload.data.light,
179 entities: []
180 };
181}
182
183function syncSpawnersOverlay (cx, cy, spawners)
184{
185 view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
186}
187
188function spawnerAt (localX, localY)
189{
190 return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
191}
192
193function draftPersistable ()
194{
195 if (!draft)
196 { return null; }
197 return {
198 open: !!draft.open,
199 grounds: draft.grounds,
200 blocks: draft.blocks,
201 spawners: draft.spawners ?? []
202 };
203}
204
205function captureDraftBaseline ()
206{
207 const payload = draftPersistable();
208 draftBaseline = payload ? JSON.stringify(payload) : null;
209 syncSaveButton();
210}
211
212function isDraftDirty ()
213{
214 if (!draft || draftBaseline == null)
215 { return false; }
216 return JSON.stringify(draftPersistable()) !== draftBaseline;
217}
218
219function syncSaveButton ()
220{
221 const btn = $("save");
222 if (!btn)
223 { return; }
224 const softDeleted = isSelectedDimensionSoftDeleted();
225 const dirty = isDraftDirty();
226 btn.disabled = !dirty || softDeleted;
227 btn.classList.toggle("save-dirty", dirty && !softDeleted);
228 btn.title = softDeleted
229 ? "Cannot save while this dimension is soft-deleted"
230 : dirty
231 ? "Save unsaved chunk changes"
232 : "No unsaved changes";
233}
234
235function afterDraftMutation ()
236{
237 syncSaveButton();
238}
239
240function showUnsavedModal (target)
241{
242 pendingNavigate = target;
243 $("unsaved-chunk-backdrop").hidden = false;
244 $("unsaved-chunk-modal").hidden = false;
245}
246
247function hideUnsavedModal ()
248{
249 $("unsaved-chunk-backdrop").hidden = true;
250 $("unsaved-chunk-modal").hidden = true;
251}
252
253function saveSelectedChunk ()
254{
255 if (!draft || !isDraftDirty())
256 { return false; }
257 if (isSelectedDimensionSoftDeleted())
258 {
259 $("error").textContent = "Cannot save while this dimension is soft-deleted.";
260 return false;
261 }
262 $("error").textContent = "";
263 $("apply-status").textContent = "";
264 $("apply-status").className = "hint";
265 socket.send({
266 type: MessageType.editorSaveChunk,
267 chunkX,
268 chunkY,
269 dimensionId: selectedDimensionId,
270 draft: {
271 open: $("open").checked,
272 grounds: draft.grounds,
273 blocks: draft.blocks,
274 spawners: draft.spawners ?? []
275 }
276 });
277 requestNeighbors();
278 return true;
279}
280
281function isSelectedDimensionSoftDeleted ()
282{
283 const record = dimensionsById.get(selectedDimensionId);
284 return record?.deletedAt != null;
285}
286
287function formatPurgeHint (record)
288{
289 if (!record?.purgeAfter)
290 { return "Soft-deleted — painting disabled."; }
291 const when = new Date(record.purgeAfter);
292 return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`;
293}
294
295function syncDimensionUi ()
296{
297 const record = dimensionsById.get(selectedDimensionId);
298 const softDeleted = record?.deletedAt != null;
299 const hint = $("dimension-purge-hint");
300 if (hint)
301 {
302 hint.hidden = !softDeleted;
303 hint.textContent = softDeleted ? formatPurgeHint(record) : "";
304 }
305 const openToggle = $("open");
306 if (openToggle)
307 { openToggle.disabled = softDeleted; }
308 dimensionCombo?.setValue(selectedDimensionId);
309 dimensionSettings?.refresh();
310 syncSaveButton();
311}
312
313function applyDimensionsList (payload)
314{
315 const list = Array.isArray(payload?.dimensions) ? payload.dimensions : [];
316 dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim]));
317 if (!dimensionsById.has(OVERWORLD_ID))
318 {
319 dimensionsById.set(OVERWORLD_ID, {
320 dimensionId: OVERWORLD_ID,
321 displayName: "Overworld",
322 lightingMode: "dayNight",
323 seasonMode: "auto",
324 defaultGroundTypeId: 1,
325 deletedAt: null,
326 purgeAfter: null
327 });
328 }
329 const options = [...dimensionsById.values()].map((dim) => ({
330 id: dim.dimensionId,
331 label: dim.displayName || dim.dimensionId,
332 disabled: dim.deletedAt != null,
333 hint: dim.deletedAt != null ? formatPurgeHint(dim) : null
334 }));
335 dimensionCombo?.setOptions(options);
336 const createdId = pendingCreatedDimensionId;
337 pendingCreatedDimensionId = null;
338 if (createdId && dimensionsById.has(createdId))
339 {
340 setRevisionState({
341 activeRevisionId: payload.activeRevisionId,
342 pendingRevisionId: payload.pendingRevisionId
343 });
344 selectDimension(createdId, { force: true });
345 return;
346 }
347 if (!dimensionsById.has(selectedDimensionId))
348 { selectedDimensionId = OVERWORLD_ID; }
349 setRevisionState({
350 activeRevisionId: payload.activeRevisionId,
351 pendingRevisionId: payload.pendingRevisionId
352 });
353 syncDimensionUi();
354 if (!isDraftDirty())
355 { requestChunks(neighborhoodCoords(chunkX, chunkY)); }
356}
357
358function requestDimensions ()
359{
360 socket.send({ type: MessageType.editorListDimensions });
361}
362
363function selectDimension (dimensionId, { force = false } = {})
364{
365 const nextId = normalizeDimensionId(dimensionId);
366 if (!force && nextId === selectedDimensionId)
367 { return; }
368 if (!force && isDraftDirty())
369 {
370 showUnsavedModal({ chunkX, chunkY, dimensionId: nextId });
371 dimensionCombo?.setValue(selectedDimensionId);
372 return;
373 }
374 selectedDimensionId = nextId;
375 syncDimensionUi();
376 clearNeighborhoodView();
377 doLoadNeighborhood(chunkX, chunkY);
378}
379
380function clearNeighborhoodView ()
381{
382 draft = null;
383 draftBaseline = null;
384 if (!view)
385 { return; }
386 for (const key of [...view.chunks.keys()])
387 {
388 const [x, y] = key.split(",").map(Number);
389 view.removeChunk(x, y);
390 }
391 view.clearEditorSpawners?.();
392 syncSaveButton();
393}
394
395function paintAt (localX, localY)
396{
397 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
398 { return; }
399 if (isSelectedDimensionSoftDeleted())
400 { return; }
401 const index = localY * CHUNK_SIZE + localX;
402 const state = placeableToolState();
403 if (tool.kind === "ground")
404 { draft.grounds[index] = { typeId: tool.typeId, state }; }
405 else if (tool.kind === "erase")
406 {
407 const removed = draft.blocks[index];
408 draft.blocks[index] = null;
409 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
410 ground: draft.grounds[index],
411 block: draft.blocks[index],
412 light: draft.light[index]
413 });
414 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
415 { refreshNeighborConnect(localX, localY, removed.typeId); }
416 afterDraftMutation();
417 return;
418 }
419 else if (tool.kind === "spawner")
420 {
421 const existing = spawnerAt(localX, localY);
422 const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`;
423 const entry = {
424 localX,
425 localY,
426 config: normalizeSpawnerConfig({
427 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
428 ...(existing?.config ?? {}),
429 spawnerId,
430 mobTypeId: tool.mobTypeId
431 }, spawnerId)
432 };
433 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
434 draft.spawners.push(entry);
435 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
436 afterDraftMutation();
437 return;
438 }
439 else
440 {
441 const def = BLOCK_DEFINITIONS[tool.typeId];
442 let nextState = definitionUsesNeighborConnect(def)
443 ? composeNeighborConnectState(def, state, 0)
444 : state;
445 if (def?.id === BlockType.flower)
446 { nextState = flowerBlockState(randomFlowerColorId()); }
447 const config = def?.id === BlockType.doorway
448 ? {
449 targetDimensionId: selectedDimensionId,
450 tileX: chunkX * CHUNK_SIZE + localX,
451 tileY: chunkY * CHUNK_SIZE + localY
452 }
453 : null;
454 if (def?.id === BlockType.doorway && !nextState)
455 { nextState = "door"; }
456 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
457 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
458 ground: draft.grounds[index],
459 block: draft.blocks[index],
460 light: draft.light[index]
461 });
462 if (definitionUsesNeighborConnect(def))
463 { refreshNeighborConnect(localX, localY, tool.typeId); }
464 afterDraftMutation();
465 return;
466 }
467 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
468 ground: draft.grounds[index],
469 block: draft.blocks[index],
470 light: draft.light[index]
471 });
472 afterDraftMutation();
473}
474
475/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */
476function refreshNeighborConnect (localX, localY, typeId)
477{
478 const def = BLOCK_DEFINITIONS[typeId];
479 if (!draft || !definitionUsesNeighborConnect(def))
480 { return; }
481 const cells = [[localX, localY]];
482 for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]])
483 { cells.push([localX + dx, localY + dy]); }
484 for (const [lx, ly] of cells)
485 {
486 if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE)
487 { continue; }
488 const index = ly * CHUNK_SIZE + lx;
489 const block = draft.blocks[index];
490 if (!block || block.typeId !== typeId)
491 { continue; }
492 const mask = computeNeighborConnectMask((dx, dy) =>
493 {
494 const nx = lx + dx;
495 const ny = ly + dy;
496 if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE)
497 { return false; }
498 const neighbor = draft.blocks[ny * CHUNK_SIZE + nx];
499 return neighborConnectBlocksMatch(block, neighbor, def);
500 });
501 block.state = composeNeighborConnectState(def, block.state, mask);
502 view.updateAuthoredTile(chunkX, chunkY, lx, ly, {
503 ground: draft.grounds[index],
504 block: draft.blocks[index],
505 light: draft.light[index]
506 });
507 }
508}
509
510function updateRevisionUI ()
511{
512 const applyBtn = $("apply");
513 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
514 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
515 if (applyBtn)
516 {
517 applyBtn.disabled = !pendingRevisionId || applyInFlight;
518 applyBtn.title = pendingRevisionId
519 ? "Reload the live world with the pending map revision"
520 : "Save a chunk first to create a pending revision";
521 }
522}
523
524function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
525{
526 if (active != null)
527 { activeRevisionId = active; }
528 pendingRevisionId = pending ?? null;
529 updateRevisionUI();
530}
531
532function showSelectedChunk (payload)
533{
534 draft = {
535 open: payload.data.open,
536 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
537 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
538 light: payload.data.light.slice(),
539 spawners: (payload.data.spawners ?? []).map((entry) => ({
540 localX: entry.localX,
541 localY: entry.localY,
542 config: { ...entry.config }
543 }))
544 };
545 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
546 $("open").checked = draft.open;
547 setRevisionState({
548 activeRevisionId: payload.activeRevisionId,
549 pendingRevisionId: payload.pendingRevisionId
550 });
551 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
552 const log = $("changelog");
553 log.innerHTML = "";
554 for (const entry of payload.changelog ?? [])
555 {
556 const item = document.createElement("article");
557 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
558 const list = document.createElement("ul");
559 for (const bullet of entry.diffEntries)
560 {
561 const li = document.createElement("li");
562 li.textContent = bullet;
563 list.append(li);
564 }
565 item.append(list);
566 log.append(item);
567 }
568 view.applySnapshot(snapshotFromPayload(payload));
569 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
570 captureDraftBaseline();
571 if (navigateAfterSave && pendingNavigate)
572 {
573 const next = pendingNavigate;
574 navigateAfterSave = false;
575 pendingNavigate = null;
576 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
577 if (nextDim !== selectedDimensionId)
578 {
579 selectedDimensionId = nextDim;
580 syncDimensionUi();
581 clearNeighborhoodView();
582 }
583 doLoadNeighborhood(next.chunkX, next.chunkY);
584 }
585}
586
587function pruneView ()
588{
589 for (const key of [...view.chunks.keys()])
590 {
591 const [x, y] = key.split(",").map(Number);
592 if (!inEditorView(x, y))
593 { view.removeChunk(x, y); }
594 }
595}
596
597function frameNeighborhood ()
598{
599 const size = view.tileSize();
600 view.followPlayer = false;
601 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
602 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
603 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
604 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
605 updateSelectionBorder();
606}
607
608function updateSelectionBorder ()
609{
610 const border = $("selection-border");
611 const canvas = scene?.canvas;
612 if (!border || !canvas)
613 { return; }
614
615 const rect = canvas.getBoundingClientRect();
616 const size = view.tileSize();
617 const chunkPx = CHUNK_SIZE * size;
618 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
619 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
620 border.style.left = `${rect.left + screenLeft}px`;
621 border.style.top = `${rect.top + screenTop}px`;
622 border.style.width = `${chunkPx}px`;
623 border.style.height = `${chunkPx}px`;
624}
625
626function layoutScene ()
627{
628 const header = document.querySelector("body > header");
629 const aside = document.querySelector("body > aside");
630 const changelog = $("changelog-wrap");
631 const top = header.offsetHeight;
632 aside.style.top = `${top}px`;
633 changelog.style.top = `${top}px`;
634 const left = aside.offsetWidth;
635 const right = changelog.offsetWidth;
636 const width = Math.max(64, window.innerWidth - left - right);
637 const height = Math.max(64, window.innerHeight - top);
638 scene.position.x = left;
639 scene.position.y = top;
640 scene.size.x = width;
641 scene.size.y = height;
642 scene.g_fixSize();
643 useNearestNeighbour(scene, game.images);
644 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
645 if (editorZoom == null)
646 { editorZoom = fit; }
647 else
648 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
649 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
650 frameNeighborhood();
651}
652
653function zoomEditor (direction)
654{
655 if (!view)
656 { return; }
657 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
658 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
659 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
660 useNearestNeighbour(scene, game.images);
661 frameNeighborhood();
662}
663
664function requestChunks (coords)
665{
666 for (const coord of coords)
667 {
668 socket.send({
669 type: MessageType.editorLoadChunk,
670 chunkX: coord.chunkX,
671 chunkY: coord.chunkY,
672 dimensionId: selectedDimensionId
673 });
674 }
675}
676
677function doLoadNeighborhood (x, y)
678{
679 chunkX = x;
680 chunkY = y;
681 $("coords").textContent = `${chunkX}, ${chunkY}`;
682 requestChunks(neighborhoodCoords(x, y));
683}
684
685function loadNeighborhood (x, y)
686{
687 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
688 {
689 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
690 return;
691 }
692 doLoadNeighborhood(x, y);
693}
694
695function requestNeighbors ()
696{
697 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
698}
699
700function anyModalOpen ()
701{
702 return settingsModal?.isOpen()
703 || paletteModal?.isOpen()
704 || tileConfigModal?.isOpen()
705 || questsModal?.isOpen()
706 || dialoguesModal?.isOpen()
707 || !$("unsaved-chunk-modal")?.hidden;
708}
709
710function updateHoverStatus (local)
711{
712 const el = $("hover-status-text");
713 if (!el)
714 { return; }
715 if (!local)
716 {
717 el.textContent = "Hover a tile for coordinates";
718 return;
719 }
720 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
721 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
722 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
723}
724
725function updateTooltip (local, options = {})
726{
727 if (!options.keepStatus)
728 { updateHoverStatus(local); }
729 const tip = $("tile-tooltip");
730 if (!tip || !local || !draft)
731 {
732 if (tip)
733 { tip.hidden = true; }
734 view?.clearSpawnRangeHighlight();
735 return;
736 }
737 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
738 const spawner = spawnerAt(local.x, local.y);
739 const lines = [];
740 if (block)
741 {
742 const def = BLOCK_DEFINITIONS[block.typeId];
743 lines.push(def?.displayName ?? `Block ${block.typeId}`);
744 if (block.config && Object.keys(block.config).length)
745 {
746 for (const [key, value] of Object.entries(block.config))
747 { lines.push(`${key}: ${value}`); }
748 }
749 }
750 if (spawner)
751 {
752 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
753 const mob = mobDefinition(config.mobTypeId);
754 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
755 lines.push(`maxAlive: ${config.maxAlive}`);
756 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
757 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
758 lines.push(`id: ${config.spawnerId}`);
759 view.setSpawnRangeHighlight(
760 local.tileX,
761 local.tileY,
762 config.spawnRangeTiles,
763 config.maxWanderRangeTiles
764 );
765 }
766 else
767 { view.clearSpawnRangeHighlight(); }
768 if (!lines.length)
769 {
770 tip.hidden = true;
771 return;
772 }
773 tip.hidden = false;
774 tip.textContent = lines.join("\n");
775 const canvas = scene.canvas;
776 const rect = canvas.getBoundingClientRect();
777 const size = view.tileSize();
778 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
779 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
780 tip.style.left = `${screenX}px`;
781 tip.style.top = `${screenY}px`;
782}
783
784async function main ()
785{
786 catalog = await loadSpriteCatalog();
787 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
788 await preloadCatalogImages(game, catalog);
789 applySpriteSheets(game.images, catalog);
790 scene = new Scene(250, 56, 64, 64);
791 game.loadScene(scene);
792 useNearestNeighbour(scene, game.images);
793 view = new WorldView(game, scene, catalog);
794 view.followPlayer = false;
795 syncSeasonControls(view.worldSeason ?? seasonIdAt());
796 layoutScene();
797 selectTool(tool);
798 $("tool").textContent = selectedToolLabel();
799
800 paletteModal = initPaletteModal({
801 catalog,
802 imageUrlFor (name)
803 {
804 const sprite = game.images[name];
805 const html = sprite?.g_image;
806 if (html && typeof html.toDataURL === "function")
807 {
808 try
809 { return html.toDataURL("image/png"); }
810 catch (_)
811 { /* fall through */ }
812 }
813 return imageUrlByName.get(name) ?? null;
814 },
815 onSelect (next)
816 {
817 selectTool(next);
818 $("tool").textContent = selectedToolLabel();
819 }
820 });
821
822 tileConfigModal = initTileConfigModal({
823 socket: {
824 send (payload)
825 {
826 socket?.send(payload);
827 }
828 },
829 MessageType,
830 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
831 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
832 id: dim.dimensionId,
833 label: dim.displayName || dim.dimensionId,
834 disabled: !!dim.deletedAt,
835 hint: dim.deletedAt ? "soft-deleted" : undefined
836 })),
837 onSave (ctx, config)
838 {
839 if (!draft)
840 { return; }
841 if (ctx.kind === "doorway")
842 {
843 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
844 draft.blocks[index] = {
845 typeId: BlockType.doorway,
846 state: config.state || "door",
847 config: {
848 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
849 tileX: Number(config.tileX) || 0,
850 tileY: Number(config.tileY) || 0
851 }
852 };
853 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
854 ground: draft.grounds[index],
855 block: draft.blocks[index],
856 light: draft.light[index]
857 });
858 afterDraftMutation();
859 return;
860 }
861 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
862 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
863 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
864 afterDraftMutation();
865 },
866 onRemove (ctx)
867 {
868 if (!draft)
869 { return; }
870 if (ctx.kind === "doorway")
871 {
872 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
873 draft.blocks[index] = null;
874 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
875 ground: draft.grounds[index],
876 block: draft.blocks[index],
877 light: draft.light[index]
878 });
879 afterDraftMutation();
880 return;
881 }
882 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
883 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
884 afterDraftMutation();
885 }
886 });
887
888 const ticker = new GameObject(0, 0, null, 10);
889 ticker.update = (dt) =>
890 {
891 hoverLocal = null;
892 const canvas = scene.canvas;
893 const rect = canvas.getBoundingClientRect();
894 const mouseX = GameInput.mousePosition.x - rect.left;
895 const mouseY = GameInput.mousePosition.y - rect.top;
896 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
897 if (overCanvas && draft && !anyModalOpen())
898 {
899 const tile = view.screenToTile(mouseX, mouseY);
900 const localX = tile.tileX - chunkX * CHUNK_SIZE;
901 const localY = tile.tileY - chunkY * CHUNK_SIZE;
902 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
903 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
904 updateHoverStatus({
905 tileX: tile.tileX,
906 tileY: tile.tileY,
907 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
908 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
909 chunkX: hoverChunkX,
910 chunkY: hoverChunkY
911 });
912 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
913 {
914 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
915 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
916 updateTooltip(hoverLocal);
917 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
918 { paintAt(localX, localY); }
919 }
920 else
921 {
922 hoverLocal = null;
923 view.clearTilePreview();
924 updateTooltip(null, { keepStatus: true });
925 }
926 }
927 else
928 {
929 view.clearTilePreview();
930 updateTooltip(null);
931 }
932 view.update(dt);
933 frameNeighborhood();
934 };
935 scene.addObject(ticker);
936 window.addEventListener("resize", layoutScene);
937
938 socket = new GameSocket(defaultSocketUrl(), (message) =>
939 {
940 if (message.type === MessageType.session)
941 {
942 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
943 socket.send({ type: MessageType.editorLoadSettings });
944 requestDimensions();
945 loadNeighborhood(0, 0);
946 }
947 else if (message.type === MessageType.editorSettings)
948 { settingsModal.handleMessage(message); }
949 else if (message.type === MessageType.editorDimensions)
950 {
951 applyDimensionsList(message);
952 }
953 else if (message.type === MessageType.editorQuests)
954 { questsModal?.handleMessage(message); }
955 else if (message.type === MessageType.editorDialogues)
956 {
957 dialoguesModal?.handleMessage(message);
958 tileConfigModal?.handleMessage(message);
959 }
960 else if (message.type === MessageType.editorChunk)
961 {
962 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
963 if (msgDim !== selectedDimensionId)
964 { return; }
965 if (message.settings)
966 { view.setSettings(message.settings); }
967 if (!inEditorView(message.chunkX, message.chunkY))
968 { return; }
969 if (message.chunkX === chunkX && message.chunkY === chunkY)
970 { showSelectedChunk(message); }
971 else
972 {
973 view.applySnapshot(snapshotFromPayload(message));
974 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
975 }
976 pruneView();
977 }
978 else if (message.type === MessageType.editorRevisionApplied)
979 {
980 applyInFlight = false;
981 setRevisionState({
982 activeRevisionId: message.activeRevisionId,
983 pendingRevisionId: message.pendingRevisionId
984 });
985 const status = $("apply-status");
986 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
987 status.className = "hint ok";
988 requestDimensions();
989 requestChunks(neighborhoodCoords(chunkX, chunkY));
990 }
991 else if (message.type === MessageType.error)
992 {
993 $("error").textContent = message.message;
994 pendingCreatedDimensionId = null;
995 navigateAfterSave = false;
996 dimensionCombo?.setValue(selectedDimensionId);
997 if (applyInFlight)
998 {
999 applyInFlight = false;
1000 $("apply-status").textContent = "";
1001 $("apply-status").className = "hint";
1002 updateRevisionUI();
1003 }
1004 }
1005 });
1006 settingsModal = initSettingsModal({
1007 socket,
1008 MessageType,
1009 onApplied (settings)
1010 {
1011 view.setSettings(settings);
1012 },
1013 onPreviewNight (hour)
1014 {
1015 view.nightPreview = hour;
1016 $("night").value = String(hour);
1017 $("night-label").textContent = Number(hour).toFixed(1);
1018 }
1019 });
1020 dimensionCombo = createDimensionCombobox({
1021 root: $("dimension-combo"),
1022 allowCreate: true,
1023 placeholder: "Search or create dimension…",
1024 onSelect (id)
1025 {
1026 selectDimension(id);
1027 },
1028 onCreate (rawId)
1029 {
1030 const id = normalizeDimensionId(rawId);
1031 $("error").textContent = "";
1032 pendingCreatedDimensionId = id;
1033 socket.send({
1034 type: MessageType.editorCreateDimension,
1035 dimensionId: id,
1036 displayName: rawId.trim()
1037 });
1038 }
1039 });
1040 dimensionSettings = initDimensionSettings({
1041 socket,
1042 MessageType,
1043 GROUND_DEFINITIONS,
1044 OVERWORLD_ID,
1045 getSelectedDimensionId: () => selectedDimensionId,
1046 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1047 isOverworld
1048 });
1049 questsModal = initQuestsModal({ socket, MessageType });
1050 dialoguesModal = initDialoguesModal({ socket, MessageType });
1051 game.startGame();
1052 await socket.connect();
1053}
1054
1055$("tool").textContent = selectedToolLabel();
1056$("tool-erase").addEventListener("click", () =>
1057{
1058 selectTool({ kind: "erase" });
1059 $("tool").textContent = selectedToolLabel();
1060});
1061
1062$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
1063$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
1064$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
1065$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
1066$("open").addEventListener("change", () =>
1067{
1068 if (isSelectedDimensionSoftDeleted())
1069 {
1070 $("open").checked = !!draft?.open;
1071 return;
1072 }
1073 if (draft)
1074 {
1075 draft.open = $("open").checked;
1076 view.setChunkOpen(chunkX, chunkY, draft.open);
1077 afterDraftMutation();
1078 }
1079});
1080$("save").addEventListener("click", () =>
1081{
1082 saveSelectedChunk();
1083});
1084$("unsaved-chunk-cancel")?.addEventListener("click", () =>
1085{
1086 pendingNavigate = null;
1087 navigateAfterSave = false;
1088 hideUnsavedModal();
1089});
1090$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
1091{
1092 pendingNavigate = null;
1093 navigateAfterSave = false;
1094 hideUnsavedModal();
1095});
1096$("unsaved-chunk-discard")?.addEventListener("click", () =>
1097{
1098 const next = pendingNavigate;
1099 hideUnsavedModal();
1100 pendingNavigate = null;
1101 navigateAfterSave = false;
1102 if (!next)
1103 { return; }
1104 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1105 if (nextDim !== selectedDimensionId)
1106 {
1107 selectedDimensionId = nextDim;
1108 syncDimensionUi();
1109 clearNeighborhoodView();
1110 }
1111 doLoadNeighborhood(next.chunkX, next.chunkY);
1112});
1113$("unsaved-chunk-save")?.addEventListener("click", () =>
1114{
1115 hideUnsavedModal();
1116 if (!pendingNavigate)
1117 { return; }
1118 navigateAfterSave = true;
1119 if (!saveSelectedChunk())
1120 {
1121 navigateAfterSave = false;
1122 const next = pendingNavigate;
1123 pendingNavigate = null;
1124 if (next)
1125 {
1126 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1127 if (nextDim !== selectedDimensionId)
1128 {
1129 selectedDimensionId = nextDim;
1130 syncDimensionUi();
1131 clearNeighborhoodView();
1132 }
1133 doLoadNeighborhood(next.chunkX, next.chunkY);
1134 }
1135 }
1136});
1137$("apply").addEventListener("click", () =>
1138{
1139 if (!pendingRevisionId || applyInFlight)
1140 { return; }
1141 $("error").textContent = "";
1142 const status = $("apply-status");
1143 status.textContent = "Applying…";
1144 status.className = "hint";
1145 applyInFlight = true;
1146 updateRevisionUI();
1147 socket.send({ type: MessageType.editorApplyRevision });
1148});
1149$("night").addEventListener("input", () =>
1150{
1151 view.nightPreview = Number($("night").value);
1152 $("night-label").textContent = view.nightPreview.toFixed(1);
1153});
1154$("season").addEventListener("change", () =>
1155{
1156 applySeasonPreview($("season").value);
1157});
1158
1159function syncSeasonControls (season)
1160{
1161 const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
1162 ? season
1163 : seasonIdAt();
1164 $("season").value = next;
1165 view?.setWorldSeason(next);
1166}
1167
1168function applySeasonPreview (season)
1169{
1170 syncSeasonControls(season);
1171}
1172
1173function cycleToolState (direction)
1174{
1175 if (tool.kind === "erase" || tool.kind === "spawner")
1176 { return; }
1177 const layer = tool.kind === "ground" ? "ground" : "block";
1178 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
1179 if (definitionUsesNeighborConnect(def))
1180 { return; }
1181 if (tool.kind === "block" && def?.id === BlockType.flower)
1182 { return; }
1183 const allStates = statesForType(catalog, layer, def.key);
1184 const seasonal = seasonalCycleStates(allStates);
1185 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
1186 if (states.length < 2)
1187 { return; }
1188 tool.state = cycleState(states, tool.state, direction);
1189 $("tool").textContent = selectedToolLabel();
1190 const season = seasonIdFromVisualState(tool.state);
1191 if (season)
1192 { applySeasonPreview(season); }
1193 if (!draft || !hoverLocal)
1194 { return; }
1195 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
1196 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
1197 { paintAt(hoverLocal.x, hoverLocal.y); }
1198 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
1199 { paintAt(hoverLocal.x, hoverLocal.y); }
1200}
1201
1202document.addEventListener("wheel", (event) =>
1203{
1204 if (!scene?.canvas || anyModalOpen())
1205 { return; }
1206 const rect = scene.canvas.getBoundingClientRect();
1207 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1208 { return; }
1209 event.preventDefault();
1210 if (event.shiftKey)
1211 {
1212 cycleToolState(event.deltaY < 0 ? 1 : -1);
1213 if (hoverLocal)
1214 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
1215 return;
1216 }
1217 zoomEditor(event.deltaY < 0 ? 1 : -1);
1218}, { passive: false });
1219
1220document.addEventListener("contextmenu", (event) =>
1221{
1222 if (!scene?.canvas || anyModalOpen() || !draft)
1223 { return; }
1224 const rect = scene.canvas.getBoundingClientRect();
1225 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1226 { return; }
1227 event.preventDefault();
1228 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
1229 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1230 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1231 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1232 { return; }
1233 const spawner = spawnerAt(localX, localY);
1234 if (spawner)
1235 {
1236 tileConfigModal.openSpawner({
1237 localX,
1238 localY,
1239 tileX: tile.tileX,
1240 tileY: tile.tileY,
1241 config: { ...spawner.config }
1242 });
1243 return;
1244 }
1245 const index = localY * CHUNK_SIZE + localX;
1246 const block = draft.blocks[index];
1247 if (block?.typeId === BlockType.doorway)
1248 {
1249 tileConfigModal.openDoorway({
1250 localX,
1251 localY,
1252 tileX: tile.tileX,
1253 tileY: tile.tileY,
1254 state: block.state ?? "door",
1255 config: block.config ? { ...block.config } : {}
1256 });
1257 }
1258});
1259
1260main().catch((error) =>
1261{
1262 $("error").textContent = error.message;
1263 console.error(error);
1264});