BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 46.8 KiB Download Raw
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import
3{
4 GROUND_DEFINITIONS,
5 BLOCK_DEFINITIONS,
6 GroundType,
7 BlockType,
8 normalizeGround,
9 normalizeBlock,
10 listPlaceableBlockPaletteEntries
11} from "/shared/definitions/tiles.js";
12import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
13import
14{
15 SeasonId,
16 seasonIdAt,
17 seasonalCycleStates,
18 seasonIdFromVisualState,
19 placeableStatesForType
20} from "/shared/world/season.js";
21import { loadGraphicsSettings } from "/shared/graphics/settings.js";
22import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
23import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
24import
25{
26 computeNeighborConnectMask,
27 composeNeighborConnectState,
28 definitionUsesNeighborConnect,
29 neighborConnectBlocksMatch,
30 neighborConnectRefreshTiles,
31 worldTileToChunkLocal
32} from "/shared/world/neighborConnect.js";
33import { GameSocket, defaultSocketUrl } from "../net/socket.js";
34import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
35import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
36import { WorldView } from "../render/worldView.js";
37import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
38import { initPaletteModal } from "./paletteModal.js";
39import { initTileConfigModal } from "./tileConfigModal.js";
40import { initQuestsModal } from "./questsModal.js";
41import { initDialoguesModal } from "./dialoguesModal.js";
42import { initGiftsModal } from "./giftsModal.js";
43import { createDimensionCombobox } from "./dimensionCombobox.js";
44import
45{
46 OVERWORLD_ID,
47 normalizeDimensionId,
48 isOverworld
49} from "/shared/world/dimensions.js";
50
51const game = new Game();
52let socket;
53let scene;
54let view;
55let draft = null;
56/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
57let draftBaseline = null;
58/**
59 * Neighbor chunks whose connect masks were updated while editing the selected chunk.
60 * Key `"chunkX,chunkY"` → `{ open, grounds, blocks, spawners }`.
61 * @type {Map<string, { open: boolean, grounds: object[], blocks: object[], spawners: object[] }>}
62 */
63let dirtyNeighborChunks = new Map();
64/** Spawners for loaded non-selected chunks (needed when saving edge-mask fixes). */
65let neighborSpawnersByChunk = new Map();
66/** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */
67let pendingNavigate = null;
68/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
69let navigateAfterSave = false;
70let chunkX = 0;
71let chunkY = 0;
72let selectedDimensionId = OVERWORLD_ID;
73/** @type {string|null} */
74let pendingCreatedDimensionId = null;
75/** @type {Map<string, object>} */
76let dimensionsById = new Map();
77let dimensionCombo = null;
78let dimensionSettings = null;
79let tool = { kind: "ground", typeId: GroundType.grass, state: null };
80let settingsModal;
81let paletteModal;
82let tileConfigModal;
83let questsModal;
84let dialoguesModal;
85let giftsModal;
86let catalog = { grounds: {}, blocks: {}, images: [] };
87let imageUrlByName = new Map();
88let hoverLocal = null;
89let editorZoom = null;
90let activeRevisionId = null;
91let pendingRevisionId = null;
92let applyInFlight = false;
93/** @type {string|null} */
94let sessionAuthSubject = null;
95const EDITOR_ZOOM_MIN = 0.25;
96const EDITOR_ZOOM_MAX = 8;
97const EDITOR_ZOOM_STEP = 1.12;
98const CONSOLE_MAX_LINES = 2000;
99
100function $ (id)
101{
102 return document.getElementById(id);
103}
104
105function formatConsoleTime (t)
106{
107 try
108 { return new Date(t).toLocaleTimeString(); }
109 catch
110 { return ""; }
111}
112
113function appendConsoleLine (entry, { scroll = true } = {})
114{
115 const pre = $("editor-console");
116 if (!pre || !entry)
117 { return; }
118 const line = document.createElement("div");
119 const level = entry.level || "info";
120 line.className = `console-${level}`;
121 line.textContent = `[${formatConsoleTime(entry.t)}] ${entry.text ?? ""}`;
122 pre.append(line);
123 while (pre.childElementCount > CONSOLE_MAX_LINES)
124 { pre.firstChild?.remove(); }
125 if (scroll)
126 { pre.scrollTop = pre.scrollHeight; }
127}
128
129function applyConsoleSnapshot (lines)
130{
131 const pre = $("editor-console");
132 if (!pre)
133 { return; }
134 pre.replaceChildren();
135 for (const entry of lines ?? [])
136 { appendConsoleLine(entry, { scroll: false }); }
137 pre.scrollTop = pre.scrollHeight;
138}
139
140function initSidePanelTabs ()
141{
142 const tabs = document.querySelectorAll(".side-panel-tab");
143 const bodies = document.querySelectorAll("[data-side-panel-body]");
144 function activate (name)
145 {
146 for (const tab of tabs)
147 {
148 const on = tab.dataset.sidePanel === name;
149 tab.classList.toggle("active", on);
150 tab.setAttribute("aria-selected", on ? "true" : "false");
151 }
152 for (const body of bodies)
153 { body.hidden = body.dataset.sidePanelBody !== name; }
154 if (name === "console")
155 {
156 const pre = $("editor-console");
157 if (pre)
158 { pre.scrollTop = pre.scrollHeight; }
159 }
160 }
161 for (const tab of tabs)
162 {
163 tab.addEventListener("click", () => activate(tab.dataset.sidePanel));
164 }
165 $("console-clear")?.addEventListener("click", () =>
166 {
167 const pre = $("editor-console");
168 if (pre)
169 { pre.replaceChildren(); }
170 });
171 activate("changelog");
172}
173
174function selectedToolLabel ()
175{
176 if (tool.kind === "erase")
177 { return "Erase block"; }
178 if (tool.kind === "spawner")
179 {
180 const def = mobDefinition(tool.mobTypeId);
181 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
182 }
183 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
184 const layer = tool.kind === "ground" ? "ground" : "block";
185 const states = statesForType(catalog, layer, def.key);
186 const state = resolveState(states, tool.state);
187 if (tool.kind === "block" && def.id === BlockType.flower)
188 { return "Flower"; }
189 if (tool.kind === "block" && def.id === BlockType.boulder)
190 {
191 const entry = listPlaceableBlockPaletteEntries(catalog)
192 .find((row) => row.typeId === def.id && row.state === state);
193 if (entry)
194 { return entry.displayName; }
195 }
196 if (states.length > 1)
197 { return `${def.displayName} (${state})`; }
198 return def.displayName;
199}
200
201function selectTool (next)
202{
203 if (next.kind === "erase")
204 {
205 tool = { kind: "erase" };
206 return;
207 }
208 if (next.kind === "spawner")
209 {
210 tool = { kind: "spawner", mobTypeId: next.mobTypeId };
211 return;
212 }
213 const layer = next.kind === "ground" ? "ground" : "block";
214 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
215 tool = {
216 kind: next.kind,
217 typeId: next.typeId,
218 state: next.state ?? defaultStateForType(catalog, layer, def.key)
219 };
220}
221
222function placeableToolState ()
223{
224 if (tool.kind === "erase" || tool.kind === "spawner")
225 { return null; }
226 const layer = tool.kind === "ground" ? "ground" : "block";
227 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
228 return resolveState(statesForType(catalog, layer, def.key), tool.state);
229}
230
231function previewFromTool ()
232{
233 if (tool.kind === "erase")
234 { return { block: null }; }
235 if (tool.kind === "spawner")
236 { return {}; }
237 const state = placeableToolState();
238 if (tool.kind === "ground")
239 { return { ground: { typeId: tool.typeId, state } }; }
240 return { block: { typeId: tool.typeId, state, config: null } };
241}
242
243function inEditorView (x, y)
244{
245 return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS;
246}
247
248function neighborhoodCoords (centerX, centerY)
249{
250 const coords = [];
251 for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++)
252 {
253 for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++)
254 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
255 }
256 return coords;
257}
258
259function snapshotFromPayload (payload)
260{
261 return {
262 chunkX: payload.chunkX,
263 chunkY: payload.chunkY,
264 open: payload.data.open,
265 closedEdges: payload.closedEdges,
266 grounds: payload.data.grounds,
267 blocks: payload.data.blocks,
268 light: payload.data.light,
269 entities: []
270 };
271}
272
273function syncSpawnersOverlay (cx, cy, spawners)
274{
275 view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
276}
277
278function spawnerAt (localX, localY)
279{
280 return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
281}
282
283function draftPersistable ()
284{
285 if (!draft)
286 { return null; }
287 return {
288 open: !!draft.open,
289 grounds: draft.grounds,
290 blocks: draft.blocks,
291 spawners: draft.spawners ?? []
292 };
293}
294
295function captureDraftBaseline ()
296{
297 const payload = draftPersistable();
298 draftBaseline = payload ? JSON.stringify(payload) : null;
299 syncSaveButton();
300}
301
302function chunkKey (cx, cy)
303{
304 return `${cx},${cy}`;
305}
306
307function isDraftDirty ()
308{
309 if (dirtyNeighborChunks.size > 0)
310 { return true; }
311 if (!draft || draftBaseline == null)
312 { return false; }
313 return JSON.stringify(draftPersistable()) !== draftBaseline;
314}
315
316function syncSaveButton ()
317{
318 const btn = $("save");
319 if (!btn)
320 { return; }
321 const softDeleted = isSelectedDimensionSoftDeleted();
322 const dirty = isDraftDirty();
323 btn.disabled = !dirty || softDeleted;
324 btn.classList.toggle("save-dirty", dirty && !softDeleted);
325 btn.title = softDeleted
326 ? "Cannot save while this dimension is soft-deleted"
327 : dirty
328 ? "Save unsaved chunk changes"
329 : "No unsaved changes";
330}
331
332function afterDraftMutation ()
333{
334 syncSaveButton();
335}
336
337function clearNeighborEditState ()
338{
339 dirtyNeighborChunks.clear();
340}
341
342function blockAtWorld (tileX, tileY)
343{
344 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
345 if (cx === chunkX && cy === chunkY && draft)
346 { return draft.blocks[localY * CHUNK_SIZE + localX] ?? null; }
347 const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
348 if (dirty)
349 { return dirty.blocks[localY * CHUNK_SIZE + localX] ?? null; }
350 const snapshot = view?.chunks.get(chunkKey(cx, cy));
351 return snapshot?.blocks?.[localY * CHUNK_SIZE + localX] ?? null;
352}
353
354function ensureDirtyNeighborChunk (cx, cy)
355{
356 const key = chunkKey(cx, cy);
357 let data = dirtyNeighborChunks.get(key);
358 if (data)
359 { return data; }
360 const snapshot = view?.chunks.get(key);
361 if (!snapshot)
362 { return null; }
363 data = {
364 open: !!snapshot.open,
365 grounds: (snapshot.grounds ?? []).map((ground) => normalizeGround(ground)),
366 blocks: (snapshot.blocks ?? []).map((block) => (block ? { ...block, config: block.config ?? null } : null)),
367 spawners: structuredClone(neighborSpawnersByChunk.get(key) ?? [])
368 };
369 dirtyNeighborChunks.set(key, data);
370 return data;
371}
372
373function writeBlockAtWorld (tileX, tileY, block)
374{
375 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
376 const index = localY * CHUNK_SIZE + localX;
377 if (cx === chunkX && cy === chunkY && draft)
378 {
379 draft.blocks[index] = block;
380 view.updateAuthoredTile(cx, cy, localX, localY, {
381 ground: draft.grounds[index],
382 block: draft.blocks[index],
383 light: draft.light[index]
384 });
385 return true;
386 }
387 const data = ensureDirtyNeighborChunk(cx, cy);
388 if (!data)
389 { return false; }
390 data.blocks[index] = block;
391 const snapshot = view?.chunks.get(chunkKey(cx, cy));
392 const light = snapshot?.light?.[index];
393 view.updateAuthoredTile(cx, cy, localX, localY, {
394 ground: data.grounds[index],
395 block: data.blocks[index],
396 light
397 });
398 return true;
399}
400
401function showUnsavedModal (target)
402{
403 pendingNavigate = target;
404 $("unsaved-chunk-backdrop").hidden = false;
405 $("unsaved-chunk-modal").hidden = false;
406}
407
408function hideUnsavedModal ()
409{
410 $("unsaved-chunk-backdrop").hidden = true;
411 $("unsaved-chunk-modal").hidden = true;
412}
413
414function saveSelectedChunk ()
415{
416 if (!draft || !isDraftDirty())
417 { return false; }
418 if (isSelectedDimensionSoftDeleted())
419 {
420 $("error").textContent = "Cannot save while this dimension is soft-deleted.";
421 return false;
422 }
423 $("error").textContent = "";
424 $("apply-status").textContent = "";
425 $("apply-status").className = "hint";
426 const neighborSaves = [...dirtyNeighborChunks.entries()];
427 clearNeighborEditState();
428 const savedChunks = [{ chunkX, chunkY }];
429 socket.send({
430 type: MessageType.editorSaveChunk,
431 chunkX,
432 chunkY,
433 dimensionId: selectedDimensionId,
434 draft: {
435 open: $("open").checked,
436 grounds: draft.grounds,
437 blocks: draft.blocks,
438 spawners: draft.spawners ?? []
439 }
440 });
441 for (const [key, data] of neighborSaves)
442 {
443 const [cx, cy] = key.split(",").map(Number);
444 savedChunks.push({ chunkX: cx, chunkY: cy });
445 socket.send({
446 type: MessageType.editorSaveChunk,
447 chunkX: cx,
448 chunkY: cy,
449 dimensionId: selectedDimensionId,
450 draft: {
451 open: data.open,
452 grounds: data.grounds,
453 blocks: data.blocks,
454 spawners: data.spawners ?? []
455 }
456 });
457 }
458 view?.bakeNatureTintForChunks?.(savedChunks);
459 requestNeighbors();
460 return true;
461}
462
463function isSelectedDimensionSoftDeleted ()
464{
465 const record = dimensionsById.get(selectedDimensionId);
466 return record?.deletedAt != null;
467}
468
469function formatPurgeHint (record)
470{
471 if (!record?.purgeAfter)
472 { return "Soft-deleted — painting disabled."; }
473 const when = new Date(record.purgeAfter);
474 return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`;
475}
476
477function syncDimensionUi ()
478{
479 const record = dimensionsById.get(selectedDimensionId);
480 const softDeleted = record?.deletedAt != null;
481 const hint = $("dimension-purge-hint");
482 if (hint)
483 {
484 hint.hidden = !softDeleted;
485 hint.textContent = softDeleted ? formatPurgeHint(record) : "";
486 }
487 const openToggle = $("open");
488 if (openToggle)
489 { openToggle.disabled = softDeleted; }
490 dimensionCombo?.setValue(selectedDimensionId);
491 dimensionSettings?.refresh();
492 syncSaveButton();
493}
494
495function applyDimensionsList (payload)
496{
497 const list = Array.isArray(payload?.dimensions) ? payload.dimensions : [];
498 dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim]));
499 if (!dimensionsById.has(OVERWORLD_ID))
500 {
501 dimensionsById.set(OVERWORLD_ID, {
502 dimensionId: OVERWORLD_ID,
503 displayName: "Overworld",
504 lightingMode: "dayNight",
505 seasonMode: "auto",
506 defaultGroundTypeId: 1,
507 deletedAt: null,
508 purgeAfter: null
509 });
510 }
511 const options = [...dimensionsById.values()].map((dim) => ({
512 id: dim.dimensionId,
513 label: dim.displayName || dim.dimensionId,
514 disabled: dim.deletedAt != null,
515 hint: dim.deletedAt != null ? formatPurgeHint(dim) : null
516 }));
517 dimensionCombo?.setOptions(options);
518 const createdId = pendingCreatedDimensionId;
519 pendingCreatedDimensionId = null;
520 if (createdId && dimensionsById.has(createdId))
521 {
522 setRevisionState({
523 activeRevisionId: payload.activeRevisionId,
524 pendingRevisionId: payload.pendingRevisionId
525 });
526 selectDimension(createdId, { force: true });
527 return;
528 }
529 if (!dimensionsById.has(selectedDimensionId))
530 { selectedDimensionId = OVERWORLD_ID; }
531 setRevisionState({
532 activeRevisionId: payload.activeRevisionId,
533 pendingRevisionId: payload.pendingRevisionId
534 });
535 syncDimensionUi();
536 if (!isDraftDirty())
537 { requestChunks(neighborhoodCoords(chunkX, chunkY)); }
538}
539
540function requestDimensions ()
541{
542 socket.send({ type: MessageType.editorListDimensions });
543}
544
545function selectDimension (dimensionId, { force = false } = {})
546{
547 const nextId = normalizeDimensionId(dimensionId);
548 if (!force && nextId === selectedDimensionId)
549 { return; }
550 if (!force && isDraftDirty())
551 {
552 showUnsavedModal({ chunkX, chunkY, dimensionId: nextId });
553 dimensionCombo?.setValue(selectedDimensionId);
554 return;
555 }
556 selectedDimensionId = nextId;
557 syncDimensionUi();
558 clearNeighborhoodView();
559 doLoadNeighborhood(chunkX, chunkY);
560}
561
562function clearNeighborhoodView ()
563{
564 draft = null;
565 draftBaseline = null;
566 clearNeighborEditState();
567 neighborSpawnersByChunk.clear();
568 if (!view)
569 { return; }
570 for (const key of [...view.chunks.keys()])
571 {
572 const [x, y] = key.split(",").map(Number);
573 view.removeChunk(x, y);
574 }
575 view.clearEditorSpawners?.();
576 syncSaveButton();
577}
578
579function paintAt (localX, localY)
580{
581 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
582 { return; }
583 if (isSelectedDimensionSoftDeleted())
584 { return; }
585 const index = localY * CHUNK_SIZE + localX;
586 const state = placeableToolState();
587 if (tool.kind === "ground")
588 { draft.grounds[index] = { typeId: tool.typeId, state }; }
589 else if (tool.kind === "erase")
590 {
591 const removed = draft.blocks[index];
592 draft.blocks[index] = null;
593 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
594 ground: draft.grounds[index],
595 block: draft.blocks[index],
596 light: draft.light[index]
597 });
598 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
599 { refreshNeighborConnect(localX, localY, removed.typeId); }
600 afterDraftMutation();
601 return;
602 }
603 else if (tool.kind === "spawner")
604 {
605 const existing = spawnerAt(localX, localY);
606 const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`;
607 const entry = {
608 localX,
609 localY,
610 config: normalizeSpawnerConfig({
611 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
612 ...(existing?.config ?? {}),
613 spawnerId,
614 mobTypeId: tool.mobTypeId
615 }, spawnerId)
616 };
617 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
618 draft.spawners.push(entry);
619 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
620 afterDraftMutation();
621 return;
622 }
623 else
624 {
625 const def = BLOCK_DEFINITIONS[tool.typeId];
626 if (def?.id === BlockType.fishingSpot)
627 {
628 const groundType = draft.grounds[index]?.typeId;
629 if (groundType !== GroundType.water && groundType !== GroundType.deepWater)
630 { return; }
631 }
632 let nextState = definitionUsesNeighborConnect(def)
633 ? composeNeighborConnectState(def, state, 0)
634 : state;
635 if (def?.id === BlockType.flower)
636 { nextState = flowerBlockState(randomFlowerColorId()); }
637 if (def?.id === BlockType.fishingSpot && !nextState)
638 { nextState = "fishing-spot"; }
639 const config = def?.id === BlockType.doorway
640 ? {
641 targetDimensionId: selectedDimensionId,
642 tileX: chunkX * CHUNK_SIZE + localX,
643 tileY: chunkY * CHUNK_SIZE + localY
644 }
645 : (def?.id === BlockType.fishingSpot
646 ? { fishes: [] }
647 : null);
648 if (def?.id === BlockType.doorway && !nextState)
649 { nextState = "door"; }
650 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
651 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
652 ground: draft.grounds[index],
653 block: draft.blocks[index],
654 light: draft.light[index]
655 });
656 if (definitionUsesNeighborConnect(def))
657 { refreshNeighborConnect(localX, localY, tool.typeId); }
658 afterDraftMutation();
659 return;
660 }
661 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
662 ground: draft.grounds[index],
663 block: draft.blocks[index],
664 light: draft.light[index]
665 });
666 afterDraftMutation();
667}
668
669/** Recompute neighbor-connect masks around a local tile, including across chunk edges. */
670function refreshNeighborConnect (localX, localY, typeId)
671{
672 const def = BLOCK_DEFINITIONS[typeId];
673 if (!draft || !definitionUsesNeighborConnect(def))
674 { return; }
675 const originTileX = chunkX * CHUNK_SIZE + localX;
676 const originTileY = chunkY * CHUNK_SIZE + localY;
677 for (const [tileX, tileY] of neighborConnectRefreshTiles(originTileX, originTileY))
678 {
679 const block = blockAtWorld(tileX, tileY);
680 if (!block || block.typeId !== typeId)
681 { continue; }
682 const mask = computeNeighborConnectMask((dx, dy) =>
683 {
684 const neighbor = blockAtWorld(tileX + dx, tileY + dy);
685 return neighborConnectBlocksMatch(block, neighbor, def);
686 });
687 const nextState = composeNeighborConnectState(def, block.state, mask);
688 if (block.state === nextState)
689 { continue; }
690 writeBlockAtWorld(tileX, tileY, { ...block, state: nextState });
691 }
692}
693
694/** Fix legacy/wrong connect states (e.g. old diagonal masks saved as nesw) from live neighbors. */
695function recomputeAllNeighborConnectInDraft ()
696{
697 if (!draft)
698 { return; }
699 for (let localY = 0; localY < CHUNK_SIZE; localY++)
700 {
701 for (let localX = 0; localX < CHUNK_SIZE; localX++)
702 {
703 const block = draft.blocks[localY * CHUNK_SIZE + localX];
704 if (!block)
705 { continue; }
706 const def = BLOCK_DEFINITIONS[block.typeId];
707 if (!definitionUsesNeighborConnect(def))
708 { continue; }
709 refreshNeighborConnect(localX, localY, block.typeId);
710 }
711 }
712}
713
714function updateRevisionUI ()
715{
716 const applyBtn = $("apply");
717 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
718 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
719 if (applyBtn)
720 {
721 applyBtn.disabled = !pendingRevisionId || applyInFlight;
722 applyBtn.title = pendingRevisionId
723 ? "Reload the live world with the pending map revision"
724 : "Save a chunk first to create a pending revision";
725 }
726}
727
728function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
729{
730 if (active != null)
731 { activeRevisionId = active; }
732 pendingRevisionId = pending ?? null;
733 updateRevisionUI();
734}
735
736function showSelectedChunk (payload)
737{
738 clearNeighborEditState();
739 draft = {
740 open: payload.data.open,
741 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
742 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
743 light: payload.data.light.slice(),
744 spawners: (payload.data.spawners ?? []).map((entry) => ({
745 localX: entry.localX,
746 localY: entry.localY,
747 config: { ...entry.config }
748 }))
749 };
750 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
751 $("open").checked = draft.open;
752 setRevisionState({
753 activeRevisionId: payload.activeRevisionId,
754 pendingRevisionId: payload.pendingRevisionId
755 });
756 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
757 const log = $("changelog");
758 log.innerHTML = "";
759 for (const entry of payload.changelog ?? [])
760 {
761 const item = document.createElement("article");
762 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
763 const list = document.createElement("ul");
764 for (const bullet of entry.diffEntries)
765 {
766 const li = document.createElement("li");
767 li.textContent = bullet;
768 list.append(li);
769 }
770 item.append(list);
771 log.append(item);
772 }
773 view.applySnapshot(snapshotFromPayload(payload));
774 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
775 captureDraftBaseline();
776 recomputeAllNeighborConnectInDraft();
777 syncSaveButton();
778 if (navigateAfterSave && pendingNavigate)
779 {
780 const next = pendingNavigate;
781 navigateAfterSave = false;
782 pendingNavigate = null;
783 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
784 if (nextDim !== selectedDimensionId)
785 {
786 selectedDimensionId = nextDim;
787 syncDimensionUi();
788 clearNeighborhoodView();
789 }
790 doLoadNeighborhood(next.chunkX, next.chunkY);
791 }
792}
793
794function pruneView ()
795{
796 for (const key of [...view.chunks.keys()])
797 {
798 const [x, y] = key.split(",").map(Number);
799 if (!inEditorView(x, y))
800 {
801 view.removeChunk(x, y);
802 neighborSpawnersByChunk.delete(key);
803 dirtyNeighborChunks.delete(key);
804 }
805 }
806}
807
808function frameNeighborhood ()
809{
810 const size = view.tileSize();
811 view.followPlayer = false;
812 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
813 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
814 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
815 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
816 view.refreshViewport();
817 updateSelectionBorder();
818}
819
820function updateSelectionBorder ()
821{
822 const border = $("selection-border");
823 const canvas = scene?.canvas;
824 if (!border || !canvas)
825 { return; }
826
827 const rect = canvas.getBoundingClientRect();
828 const size = view.tileSize();
829 const chunkPx = CHUNK_SIZE * size;
830 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
831 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
832 border.style.left = `${rect.left + screenLeft}px`;
833 border.style.top = `${rect.top + screenTop}px`;
834 border.style.width = `${chunkPx}px`;
835 border.style.height = `${chunkPx}px`;
836}
837
838function layoutScene ()
839{
840 const header = document.querySelector("body > header");
841 const aside = document.querySelector("body > aside");
842 const sidePanels = $("side-panels") || $("changelog-wrap");
843 const top = header.offsetHeight;
844 aside.style.top = `${top}px`;
845 sidePanels.style.top = `${top}px`;
846 const left = aside.offsetWidth;
847 const right = sidePanels.offsetWidth;
848 const width = Math.max(64, window.innerWidth - left - right);
849 const height = Math.max(64, window.innerHeight - top);
850 scene.position.x = left;
851 scene.position.y = top;
852 scene.size.x = width;
853 scene.size.y = height;
854 scene.g_fixSize();
855 useNearestNeighbour(scene, game.images);
856 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
857 if (editorZoom == null)
858 { editorZoom = fit; }
859 else
860 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
861 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
862 frameNeighborhood();
863}
864
865function zoomEditor (direction)
866{
867 if (!view)
868 { return; }
869 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
870 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
871 scheduleEditorZoom();
872}
873
874let editorZoomRaf = 0;
875function scheduleEditorZoom ()
876{
877 if (editorZoomRaf)
878 { return; }
879 editorZoomRaf = requestAnimationFrame(() =>
880 {
881 editorZoomRaf = 0;
882 if (!view)
883 { return; }
884 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
885 frameNeighborhood();
886 });
887}
888
889function requestChunks (coords)
890{
891 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
892 { return; }
893 for (const coord of coords)
894 {
895 try
896 {
897 socket.send({
898 type: MessageType.editorLoadChunk,
899 chunkX: coord.chunkX,
900 chunkY: coord.chunkY,
901 dimensionId: selectedDimensionId
902 });
903 }
904 catch (_)
905 { break; }
906 }
907}
908
909function doLoadNeighborhood (x, y)
910{
911 chunkX = x;
912 chunkY = y;
913 $("coords").textContent = `${chunkX}, ${chunkY}`;
914 requestChunks(neighborhoodCoords(x, y));
915}
916
917function loadNeighborhood (x, y)
918{
919 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
920 {
921 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
922 return;
923 }
924 doLoadNeighborhood(x, y);
925}
926
927function requestNeighbors ()
928{
929 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
930}
931
932function anyModalOpen ()
933{
934 return settingsModal?.isOpen()
935 || paletteModal?.isOpen()
936 || tileConfigModal?.isOpen()
937 || questsModal?.isOpen()
938 || dialoguesModal?.isOpen()
939 || giftsModal?.isOpen()
940 || !$("unsaved-chunk-modal")?.hidden;
941}
942
943function updateHoverStatus (local)
944{
945 const el = $("hover-status-text");
946 if (!el)
947 { return; }
948 if (!local)
949 {
950 el.textContent = "Hover a tile for coordinates";
951 return;
952 }
953 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
954 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
955 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
956}
957
958function updateTooltip (local, options = {})
959{
960 if (!options.keepStatus)
961 { updateHoverStatus(local); }
962 const tip = $("tile-tooltip");
963 if (!tip || !local || !draft)
964 {
965 if (tip)
966 { tip.hidden = true; }
967 view?.clearSpawnRangeHighlight();
968 return;
969 }
970 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
971 const spawner = spawnerAt(local.x, local.y);
972 const lines = [];
973 if (block)
974 {
975 const def = BLOCK_DEFINITIONS[block.typeId];
976 lines.push(def?.displayName ?? `Block ${block.typeId}`);
977 if (block.config && Object.keys(block.config).length)
978 {
979 for (const [key, value] of Object.entries(block.config))
980 { lines.push(`${key}: ${value}`); }
981 }
982 }
983 if (spawner)
984 {
985 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
986 const mob = mobDefinition(config.mobTypeId);
987 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
988 lines.push(`maxAlive: ${config.maxAlive}`);
989 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
990 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
991 lines.push(`id: ${config.spawnerId}`);
992 view.setSpawnRangeHighlight(
993 local.tileX,
994 local.tileY,
995 config.spawnRangeTiles,
996 config.maxWanderRangeTiles
997 );
998 }
999 else
1000 { view.clearSpawnRangeHighlight(); }
1001 if (!lines.length)
1002 {
1003 tip.hidden = true;
1004 return;
1005 }
1006 tip.hidden = false;
1007 tip.textContent = lines.join("\n");
1008 const canvas = scene.canvas;
1009 const rect = canvas.getBoundingClientRect();
1010 const size = view.tileSize();
1011 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
1012 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
1013 tip.style.left = `${screenX}px`;
1014 tip.style.top = `${screenY}px`;
1015}
1016
1017async function main ()
1018{
1019 const authStatus = await fetchAuthStatus();
1020 const signIn = document.getElementById("auth-sign-in");
1021 const signOut = document.getElementById("auth-sign-out");
1022 if (signIn)
1023 {
1024 signIn.hidden = !!authStatus?.authenticated;
1025 signIn.href = loginUrl("/editor");
1026 }
1027 if (signOut)
1028 {
1029 signOut.hidden = !authStatus?.authenticated;
1030 signOut.href = logoutUrl("/editor");
1031 }
1032 if (!authStatus.authenticated)
1033 {
1034 $("who").textContent = "Sign in required";
1035 $("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
1036 return;
1037 }
1038
1039 const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in";
1040 $("who").textContent = `${accountLabel} · loading sprites…`;
1041
1042 catalog = await loadSpriteCatalog();
1043 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
1044 await preloadCatalogImages(game, catalog, {
1045 onProgress ({ loaded, total })
1046 {
1047 $("who").textContent = `${accountLabel} · loading sprites ${loaded}/${total}`;
1048 }
1049 });
1050 applySpriteSheets(game.images, catalog);
1051 scene = new Scene(250, 56, 64, 64);
1052 game.loadScene(scene);
1053 view = new WorldView(game, scene, catalog);
1054 view.followPlayer = false;
1055 view.natureTintEnabled = false;
1056 view.setGraphicsPrefs(loadGraphicsSettings());
1057 syncSeasonControls(view.worldSeason ?? seasonIdAt());
1058 layoutScene();
1059 selectTool(tool);
1060 $("tool").textContent = selectedToolLabel();
1061
1062 paletteModal = initPaletteModal({
1063 catalog,
1064 imageUrlFor (name)
1065 {
1066 const sprite = game.images[name];
1067 const html = sprite?.g_image;
1068 if (html && typeof html.toDataURL === "function")
1069 {
1070 try
1071 { return html.toDataURL("image/png"); }
1072 catch (_)
1073 { /* fall through */ }
1074 }
1075 return imageUrlByName.get(name) ?? null;
1076 },
1077 onSelect (next)
1078 {
1079 selectTool(next);
1080 $("tool").textContent = selectedToolLabel();
1081 }
1082 });
1083
1084 tileConfigModal = initTileConfigModal({
1085 socket: {
1086 send (payload)
1087 {
1088 socket?.send(payload);
1089 }
1090 },
1091 MessageType,
1092 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
1093 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1094 id: dim.dimensionId,
1095 label: dim.displayName || dim.dimensionId,
1096 disabled: !!dim.deletedAt,
1097 hint: dim.deletedAt ? "soft-deleted" : undefined
1098 })),
1099 onSave (ctx, config)
1100 {
1101 if (!draft)
1102 { return; }
1103 if (ctx.kind === "doorway")
1104 {
1105 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1106 draft.blocks[index] = {
1107 typeId: BlockType.doorway,
1108 state: config.state || "door",
1109 config: {
1110 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
1111 tileX: Number(config.tileX) || 0,
1112 tileY: Number(config.tileY) || 0
1113 }
1114 };
1115 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1116 ground: draft.grounds[index],
1117 block: draft.blocks[index],
1118 light: draft.light[index]
1119 });
1120 afterDraftMutation();
1121 return;
1122 }
1123 if (ctx.kind === "fishing-spot")
1124 {
1125 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1126 const existing = draft.blocks[index];
1127 draft.blocks[index] = {
1128 typeId: BlockType.fishingSpot,
1129 state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
1130 config: { fishes: [...(config.fishes ?? [])] }
1131 };
1132 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1133 ground: draft.grounds[index],
1134 block: draft.blocks[index],
1135 light: draft.light[index]
1136 });
1137 afterDraftMutation();
1138 return;
1139 }
1140 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1141 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
1142 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1143 afterDraftMutation();
1144 },
1145 onRemove (ctx)
1146 {
1147 if (!draft)
1148 { return; }
1149 if (ctx.kind === "doorway")
1150 {
1151 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1152 draft.blocks[index] = null;
1153 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1154 ground: draft.grounds[index],
1155 block: draft.blocks[index],
1156 light: draft.light[index]
1157 });
1158 afterDraftMutation();
1159 return;
1160 }
1161 if (ctx.kind === "fishing-spot")
1162 {
1163 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1164 draft.blocks[index] = null;
1165 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1166 ground: draft.grounds[index],
1167 block: draft.blocks[index],
1168 light: draft.light[index]
1169 });
1170 afterDraftMutation();
1171 return;
1172 }
1173 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1174 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1175 afterDraftMutation();
1176 }
1177 });
1178
1179 const ticker = new GameObject(0, 0, null, 10);
1180 ticker.update = (dt) =>
1181 {
1182 hoverLocal = null;
1183 const canvas = scene.canvas;
1184 const rect = canvas.getBoundingClientRect();
1185 const mouseX = GameInput.mousePosition.x - rect.left;
1186 const mouseY = GameInput.mousePosition.y - rect.top;
1187 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
1188 if (overCanvas && draft && !anyModalOpen())
1189 {
1190 const tile = view.screenToTile(mouseX, mouseY);
1191 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1192 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1193 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
1194 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
1195 updateHoverStatus({
1196 tileX: tile.tileX,
1197 tileY: tile.tileY,
1198 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1199 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1200 chunkX: hoverChunkX,
1201 chunkY: hoverChunkY
1202 });
1203 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
1204 {
1205 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
1206 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
1207 updateTooltip(hoverLocal);
1208 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
1209 { paintAt(localX, localY); }
1210 }
1211 else
1212 {
1213 hoverLocal = null;
1214 view.clearTilePreview();
1215 updateTooltip(null, { keepStatus: true });
1216 }
1217 }
1218 else
1219 {
1220 view.clearTilePreview();
1221 updateTooltip(null);
1222 }
1223 view.update(dt);
1224 frameNeighborhood();
1225 };
1226 scene.addObject(ticker);
1227 window.addEventListener("resize", layoutScene);
1228
1229 $("who").textContent = `${accountLabel} · connecting…`;
1230
1231 socket = new GameSocket(defaultSocketUrl(), (message) =>
1232 {
1233 if (message.type === MessageType.session)
1234 {
1235 sessionAuthSubject = message.authSubject ?? null;
1236 const label = message.username ?? message.authSubject ?? "Unknown";
1237 $("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1238 if (!message.isAdmin)
1239 {
1240 $("error").textContent = "Admin access required.";
1241 return;
1242 }
1243 $("error").textContent = "";
1244 const restartBtn = document.getElementById("editor-restart-now");
1245 if (restartBtn)
1246 {
1247 restartBtn.hidden = false;
1248 restartBtn.disabled = false;
1249 }
1250 socket.send({ type: MessageType.editorLoadSettings });
1251 socket.send({ type: MessageType.editorLoadGameAdmins });
1252 socket.send({ type: MessageType.editorConsoleSubscribe });
1253 requestDimensions();
1254 loadNeighborhood(0, 0);
1255 }
1256 else if (message.type === MessageType.editorSettings
1257 || message.type === MessageType.editorGameAdmins)
1258 { settingsModal.handleMessage(message); }
1259 else if (message.type === MessageType.editorConsoleSnapshot)
1260 { applyConsoleSnapshot(message.lines); }
1261 else if (message.type === MessageType.editorConsoleLine)
1262 { appendConsoleLine(message.line); }
1263 else if (message.type === MessageType.editorDimensions)
1264 {
1265 applyDimensionsList(message);
1266 }
1267 else if (message.type === MessageType.editorQuests)
1268 { questsModal?.handleMessage(message); }
1269 else if (message.type === MessageType.editorDialogues)
1270 {
1271 dialoguesModal?.handleMessage(message);
1272 tileConfigModal?.handleMessage(message);
1273 }
1274 else if (message.type === MessageType.editorGiftCharacters
1275 || message.type === MessageType.editorGiftSent)
1276 { giftsModal?.handleMessage(message); }
1277 else if (message.type === MessageType.editorChunk)
1278 {
1279 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1280 if (msgDim !== selectedDimensionId)
1281 { return; }
1282 if (message.settings)
1283 { view.setSettings(message.settings); }
1284 if (!inEditorView(message.chunkX, message.chunkY))
1285 { return; }
1286 if (message.chunkX === chunkX && message.chunkY === chunkY)
1287 { showSelectedChunk(message); }
1288 else
1289 {
1290 const key = chunkKey(message.chunkX, message.chunkY);
1291 neighborSpawnersByChunk.set(key, message.data.spawners ?? []);
1292 if (!dirtyNeighborChunks.has(key))
1293 {
1294 view.applySnapshot(snapshotFromPayload(message));
1295 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
1296 }
1297 }
1298 pruneView();
1299 }
1300 else if (message.type === MessageType.editorRevisionApplied)
1301 {
1302 applyInFlight = false;
1303 setRevisionState({
1304 activeRevisionId: message.activeRevisionId,
1305 pendingRevisionId: message.pendingRevisionId
1306 });
1307 const status = $("apply-status");
1308 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
1309 status.className = "hint ok";
1310 requestDimensions();
1311 requestChunks(neighborhoodCoords(chunkX, chunkY));
1312 }
1313 else if (message.type === MessageType.forceLogout)
1314 {
1315 $("who").textContent = "Server restarting…";
1316 $("error").textContent = message.reason || "Server shutting down.";
1317 }
1318 else if (message.type === MessageType.error)
1319 {
1320 $("error").textContent = message.message;
1321 if (giftsModal?.isOpen())
1322 { giftsModal.handleError?.(message.message); }
1323 pendingCreatedDimensionId = null;
1324 navigateAfterSave = false;
1325 dimensionCombo?.setValue(selectedDimensionId);
1326 if (applyInFlight)
1327 {
1328 applyInFlight = false;
1329 $("apply-status").textContent = "";
1330 $("apply-status").className = "hint";
1331 updateRevisionUI();
1332 }
1333 }
1334 }, {
1335 onClose (event)
1336 {
1337 if (event.code === 1000)
1338 { return; }
1339 const reasons = {
1340 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1341 1011: "Server could not verify your account with auth.timfalken.com.",
1342 1006: "Connection dropped before the editor session started.",
1343 1001: "Server is restarting. Reload this page in a moment."
1344 };
1345 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1346 $("who").textContent = "Connection failed";
1347 $("error").textContent = detail;
1348 },
1349 onError ()
1350 {
1351 $("who").textContent = "Connection failed";
1352 $("error").textContent = "Could not open a live connection to the server.";
1353 }
1354 });
1355 settingsModal = initSettingsModal({
1356 socket,
1357 MessageType,
1358 getAuthSubject: () => sessionAuthSubject,
1359 onApplied (settings)
1360 {
1361 view.setSettings(settings);
1362 },
1363 onPreviewNight (hour)
1364 {
1365 view.nightPreview = hour;
1366 $("night").value = String(hour);
1367 $("night-label").textContent = Number(hour).toFixed(1);
1368 }
1369 });
1370 dimensionCombo = createDimensionCombobox({
1371 root: $("dimension-combo"),
1372 allowCreate: true,
1373 placeholder: "Search or create dimension…",
1374 onSelect (id)
1375 {
1376 selectDimension(id);
1377 },
1378 onCreate (rawId)
1379 {
1380 const id = normalizeDimensionId(rawId);
1381 $("error").textContent = "";
1382 pendingCreatedDimensionId = id;
1383 socket.send({
1384 type: MessageType.editorCreateDimension,
1385 dimensionId: id,
1386 displayName: rawId.trim()
1387 });
1388 }
1389 });
1390 dimensionCombo.setOptions([{
1391 id: OVERWORLD_ID,
1392 label: "Overworld"
1393 }]);
1394 dimensionCombo.setValue(OVERWORLD_ID);
1395 dimensionSettings = initDimensionSettings({
1396 socket,
1397 MessageType,
1398 GROUND_DEFINITIONS,
1399 OVERWORLD_ID,
1400 getSelectedDimensionId: () => selectedDimensionId,
1401 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1402 isOverworld
1403 });
1404 questsModal = initQuestsModal({ socket, MessageType });
1405 dialoguesModal = initDialoguesModal({ socket, MessageType });
1406 giftsModal = initGiftsModal({ socket, MessageType });
1407 initSidePanelTabs();
1408 game.startGame();
1409 useNearestNeighbour(scene, game.images);
1410 await socket.connect();
1411}
1412
1413$("tool").textContent = selectedToolLabel();
1414$("tool-erase").addEventListener("click", () =>
1415{
1416 selectTool({ kind: "erase" });
1417 $("tool").textContent = selectedToolLabel();
1418});
1419
1420$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
1421$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
1422$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
1423$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
1424$("open").addEventListener("change", () =>
1425{
1426 if (isSelectedDimensionSoftDeleted())
1427 {
1428 $("open").checked = !!draft?.open;
1429 return;
1430 }
1431 if (draft)
1432 {
1433 draft.open = $("open").checked;
1434 view.setChunkOpen(chunkX, chunkY, draft.open);
1435 afterDraftMutation();
1436 }
1437});
1438$("save").addEventListener("click", () =>
1439{
1440 saveSelectedChunk();
1441});
1442$("unsaved-chunk-cancel")?.addEventListener("click", () =>
1443{
1444 pendingNavigate = null;
1445 navigateAfterSave = false;
1446 hideUnsavedModal();
1447});
1448$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
1449{
1450 pendingNavigate = null;
1451 navigateAfterSave = false;
1452 hideUnsavedModal();
1453});
1454$("unsaved-chunk-discard")?.addEventListener("click", () =>
1455{
1456 const next = pendingNavigate;
1457 hideUnsavedModal();
1458 pendingNavigate = null;
1459 navigateAfterSave = false;
1460 if (!next)
1461 { return; }
1462 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1463 if (nextDim !== selectedDimensionId)
1464 {
1465 selectedDimensionId = nextDim;
1466 syncDimensionUi();
1467 clearNeighborhoodView();
1468 }
1469 doLoadNeighborhood(next.chunkX, next.chunkY);
1470});
1471$("unsaved-chunk-save")?.addEventListener("click", () =>
1472{
1473 hideUnsavedModal();
1474 if (!pendingNavigate)
1475 { return; }
1476 navigateAfterSave = true;
1477 if (!saveSelectedChunk())
1478 {
1479 navigateAfterSave = false;
1480 const next = pendingNavigate;
1481 pendingNavigate = null;
1482 if (next)
1483 {
1484 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1485 if (nextDim !== selectedDimensionId)
1486 {
1487 selectedDimensionId = nextDim;
1488 syncDimensionUi();
1489 clearNeighborhoodView();
1490 }
1491 doLoadNeighborhood(next.chunkX, next.chunkY);
1492 }
1493 }
1494});
1495$("apply").addEventListener("click", () =>
1496{
1497 if (!pendingRevisionId || applyInFlight)
1498 { return; }
1499 $("error").textContent = "";
1500 const status = $("apply-status");
1501 status.textContent = "Applying…";
1502 status.className = "hint";
1503 applyInFlight = true;
1504 updateRevisionUI();
1505 socket.send({ type: MessageType.editorApplyRevision });
1506});
1507document.getElementById("editor-restart-now")?.addEventListener("click", () =>
1508{
1509 if (!socket)
1510 { return; }
1511 const ok = window.confirm(
1512 "Restart the server now?\n\nAll players and editor sessions will disconnect. "
1513 + "systemd will start a fresh process and pull the latest code from git."
1514 );
1515 if (!ok)
1516 { return; }
1517 const restartBtn = document.getElementById("editor-restart-now");
1518 if (restartBtn)
1519 { restartBtn.disabled = true; }
1520 $("who").textContent = "Restarting server…";
1521 $("error").textContent = "";
1522 socket.send({ type: MessageType.editorRestartNow });
1523});
1524$("night").addEventListener("input", () =>
1525{
1526 view.nightPreview = Number($("night").value);
1527 $("night-label").textContent = view.nightPreview.toFixed(1);
1528});
1529$("season").addEventListener("change", () =>
1530{
1531 applySeasonPreview($("season").value);
1532});
1533
1534function syncSeasonControls (season)
1535{
1536 const next = season === SeasonId.spring
1537 || season === SeasonId.fall
1538 || season === SeasonId.winter
1539 || season === SeasonId.summer
1540 ? season
1541 : seasonIdAt();
1542 $("season").value = next;
1543 view?.setWorldSeason(next);
1544}
1545
1546function applySeasonPreview (season)
1547{
1548 syncSeasonControls(season);
1549}
1550
1551function cycleToolState (direction)
1552{
1553 if (tool.kind === "erase" || tool.kind === "spawner")
1554 { return; }
1555 const layer = tool.kind === "ground" ? "ground" : "block";
1556 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
1557 if (definitionUsesNeighborConnect(def))
1558 { return; }
1559 if (tool.kind === "block" && def?.id === BlockType.flower)
1560 { return; }
1561 const allStates = statesForType(catalog, layer, def.key);
1562 const seasonal = seasonalCycleStates(allStates);
1563 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
1564 if (states.length < 2)
1565 { return; }
1566 tool.state = cycleState(states, tool.state, direction);
1567 $("tool").textContent = selectedToolLabel();
1568 const season = seasonIdFromVisualState(tool.state);
1569 if (season)
1570 { applySeasonPreview(season); }
1571 if (!draft || !hoverLocal)
1572 { return; }
1573 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
1574 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
1575 { paintAt(hoverLocal.x, hoverLocal.y); }
1576 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
1577 { paintAt(hoverLocal.x, hoverLocal.y); }
1578}
1579
1580document.addEventListener("wheel", (event) =>
1581{
1582 if (!scene?.canvas || anyModalOpen())
1583 { return; }
1584 const rect = scene.canvas.getBoundingClientRect();
1585 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1586 { return; }
1587 event.preventDefault();
1588 if (event.shiftKey)
1589 {
1590 cycleToolState(event.deltaY < 0 ? 1 : -1);
1591 if (hoverLocal)
1592 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
1593 return;
1594 }
1595 zoomEditor(event.deltaY < 0 ? 1 : -1);
1596}, { passive: false });
1597
1598document.addEventListener("contextmenu", (event) =>
1599{
1600 if (!scene?.canvas || anyModalOpen() || !draft)
1601 { return; }
1602 const rect = scene.canvas.getBoundingClientRect();
1603 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1604 { return; }
1605 event.preventDefault();
1606 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
1607 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1608 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1609 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1610 { return; }
1611 const spawner = spawnerAt(localX, localY);
1612 if (spawner)
1613 {
1614 tileConfigModal.openSpawner({
1615 localX,
1616 localY,
1617 tileX: tile.tileX,
1618 tileY: tile.tileY,
1619 config: { ...spawner.config }
1620 });
1621 return;
1622 }
1623 const index = localY * CHUNK_SIZE + localX;
1624 const block = draft.blocks[index];
1625 if (block?.typeId === BlockType.doorway)
1626 {
1627 tileConfigModal.openDoorway({
1628 localX,
1629 localY,
1630 tileX: tile.tileX,
1631 tileY: tile.tileY,
1632 state: block.state ?? "door",
1633 config: block.config ? { ...block.config } : {}
1634 });
1635 return;
1636 }
1637 if (block?.typeId === BlockType.fishingSpot)
1638 {
1639 tileConfigModal.openFishingSpot({
1640 localX,
1641 localY,
1642 tileX: tile.tileX,
1643 tileY: tile.tileY,
1644 config: block.config ? { ...block.config } : { fishes: [] }
1645 });
1646 }
1647});
1648
1649main().catch((error) =>
1650{
1651 $("error").textContent = error.message;
1652 console.error(error);
1653});