BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 46.6 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 socket.send({
429 type: MessageType.editorSaveChunk,
430 chunkX,
431 chunkY,
432 dimensionId: selectedDimensionId,
433 draft: {
434 open: $("open").checked,
435 grounds: draft.grounds,
436 blocks: draft.blocks,
437 spawners: draft.spawners ?? []
438 }
439 });
440 for (const [key, data] of neighborSaves)
441 {
442 const [cx, cy] = key.split(",").map(Number);
443 socket.send({
444 type: MessageType.editorSaveChunk,
445 chunkX: cx,
446 chunkY: cy,
447 dimensionId: selectedDimensionId,
448 draft: {
449 open: data.open,
450 grounds: data.grounds,
451 blocks: data.blocks,
452 spawners: data.spawners ?? []
453 }
454 });
455 }
456 requestNeighbors();
457 return true;
458}
459
460function isSelectedDimensionSoftDeleted ()
461{
462 const record = dimensionsById.get(selectedDimensionId);
463 return record?.deletedAt != null;
464}
465
466function formatPurgeHint (record)
467{
468 if (!record?.purgeAfter)
469 { return "Soft-deleted — painting disabled."; }
470 const when = new Date(record.purgeAfter);
471 return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`;
472}
473
474function syncDimensionUi ()
475{
476 const record = dimensionsById.get(selectedDimensionId);
477 const softDeleted = record?.deletedAt != null;
478 const hint = $("dimension-purge-hint");
479 if (hint)
480 {
481 hint.hidden = !softDeleted;
482 hint.textContent = softDeleted ? formatPurgeHint(record) : "";
483 }
484 const openToggle = $("open");
485 if (openToggle)
486 { openToggle.disabled = softDeleted; }
487 dimensionCombo?.setValue(selectedDimensionId);
488 dimensionSettings?.refresh();
489 syncSaveButton();
490}
491
492function applyDimensionsList (payload)
493{
494 const list = Array.isArray(payload?.dimensions) ? payload.dimensions : [];
495 dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim]));
496 if (!dimensionsById.has(OVERWORLD_ID))
497 {
498 dimensionsById.set(OVERWORLD_ID, {
499 dimensionId: OVERWORLD_ID,
500 displayName: "Overworld",
501 lightingMode: "dayNight",
502 seasonMode: "auto",
503 defaultGroundTypeId: 1,
504 deletedAt: null,
505 purgeAfter: null
506 });
507 }
508 const options = [...dimensionsById.values()].map((dim) => ({
509 id: dim.dimensionId,
510 label: dim.displayName || dim.dimensionId,
511 disabled: dim.deletedAt != null,
512 hint: dim.deletedAt != null ? formatPurgeHint(dim) : null
513 }));
514 dimensionCombo?.setOptions(options);
515 const createdId = pendingCreatedDimensionId;
516 pendingCreatedDimensionId = null;
517 if (createdId && dimensionsById.has(createdId))
518 {
519 setRevisionState({
520 activeRevisionId: payload.activeRevisionId,
521 pendingRevisionId: payload.pendingRevisionId
522 });
523 selectDimension(createdId, { force: true });
524 return;
525 }
526 if (!dimensionsById.has(selectedDimensionId))
527 { selectedDimensionId = OVERWORLD_ID; }
528 setRevisionState({
529 activeRevisionId: payload.activeRevisionId,
530 pendingRevisionId: payload.pendingRevisionId
531 });
532 syncDimensionUi();
533 if (!isDraftDirty())
534 { requestChunks(neighborhoodCoords(chunkX, chunkY)); }
535}
536
537function requestDimensions ()
538{
539 socket.send({ type: MessageType.editorListDimensions });
540}
541
542function selectDimension (dimensionId, { force = false } = {})
543{
544 const nextId = normalizeDimensionId(dimensionId);
545 if (!force && nextId === selectedDimensionId)
546 { return; }
547 if (!force && isDraftDirty())
548 {
549 showUnsavedModal({ chunkX, chunkY, dimensionId: nextId });
550 dimensionCombo?.setValue(selectedDimensionId);
551 return;
552 }
553 selectedDimensionId = nextId;
554 syncDimensionUi();
555 clearNeighborhoodView();
556 doLoadNeighborhood(chunkX, chunkY);
557}
558
559function clearNeighborhoodView ()
560{
561 draft = null;
562 draftBaseline = null;
563 clearNeighborEditState();
564 neighborSpawnersByChunk.clear();
565 if (!view)
566 { return; }
567 for (const key of [...view.chunks.keys()])
568 {
569 const [x, y] = key.split(",").map(Number);
570 view.removeChunk(x, y);
571 }
572 view.clearEditorSpawners?.();
573 syncSaveButton();
574}
575
576function paintAt (localX, localY)
577{
578 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
579 { return; }
580 if (isSelectedDimensionSoftDeleted())
581 { return; }
582 const index = localY * CHUNK_SIZE + localX;
583 const state = placeableToolState();
584 if (tool.kind === "ground")
585 { draft.grounds[index] = { typeId: tool.typeId, state }; }
586 else if (tool.kind === "erase")
587 {
588 const removed = draft.blocks[index];
589 draft.blocks[index] = null;
590 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
591 ground: draft.grounds[index],
592 block: draft.blocks[index],
593 light: draft.light[index]
594 });
595 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
596 { refreshNeighborConnect(localX, localY, removed.typeId); }
597 afterDraftMutation();
598 return;
599 }
600 else if (tool.kind === "spawner")
601 {
602 const existing = spawnerAt(localX, localY);
603 const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`;
604 const entry = {
605 localX,
606 localY,
607 config: normalizeSpawnerConfig({
608 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
609 ...(existing?.config ?? {}),
610 spawnerId,
611 mobTypeId: tool.mobTypeId
612 }, spawnerId)
613 };
614 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
615 draft.spawners.push(entry);
616 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
617 afterDraftMutation();
618 return;
619 }
620 else
621 {
622 const def = BLOCK_DEFINITIONS[tool.typeId];
623 if (def?.id === BlockType.fishingSpot)
624 {
625 const groundType = draft.grounds[index]?.typeId;
626 if (groundType !== GroundType.water && groundType !== GroundType.deepWater)
627 { return; }
628 }
629 let nextState = definitionUsesNeighborConnect(def)
630 ? composeNeighborConnectState(def, state, 0)
631 : state;
632 if (def?.id === BlockType.flower)
633 { nextState = flowerBlockState(randomFlowerColorId()); }
634 if (def?.id === BlockType.fishingSpot && !nextState)
635 { nextState = "fishing-spot"; }
636 const config = def?.id === BlockType.doorway
637 ? {
638 targetDimensionId: selectedDimensionId,
639 tileX: chunkX * CHUNK_SIZE + localX,
640 tileY: chunkY * CHUNK_SIZE + localY
641 }
642 : (def?.id === BlockType.fishingSpot
643 ? { fishes: [] }
644 : null);
645 if (def?.id === BlockType.doorway && !nextState)
646 { nextState = "door"; }
647 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
648 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
649 ground: draft.grounds[index],
650 block: draft.blocks[index],
651 light: draft.light[index]
652 });
653 if (definitionUsesNeighborConnect(def))
654 { refreshNeighborConnect(localX, localY, tool.typeId); }
655 afterDraftMutation();
656 return;
657 }
658 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
659 ground: draft.grounds[index],
660 block: draft.blocks[index],
661 light: draft.light[index]
662 });
663 afterDraftMutation();
664}
665
666/** Recompute neighbor-connect masks around a local tile, including across chunk edges. */
667function refreshNeighborConnect (localX, localY, typeId)
668{
669 const def = BLOCK_DEFINITIONS[typeId];
670 if (!draft || !definitionUsesNeighborConnect(def))
671 { return; }
672 const originTileX = chunkX * CHUNK_SIZE + localX;
673 const originTileY = chunkY * CHUNK_SIZE + localY;
674 for (const [tileX, tileY] of neighborConnectRefreshTiles(originTileX, originTileY))
675 {
676 const block = blockAtWorld(tileX, tileY);
677 if (!block || block.typeId !== typeId)
678 { continue; }
679 const mask = computeNeighborConnectMask((dx, dy) =>
680 {
681 const neighbor = blockAtWorld(tileX + dx, tileY + dy);
682 return neighborConnectBlocksMatch(block, neighbor, def);
683 });
684 const nextState = composeNeighborConnectState(def, block.state, mask);
685 if (block.state === nextState)
686 { continue; }
687 writeBlockAtWorld(tileX, tileY, { ...block, state: nextState });
688 }
689}
690
691/** Fix legacy/wrong connect states (e.g. old diagonal masks saved as nesw) from live neighbors. */
692function recomputeAllNeighborConnectInDraft ()
693{
694 if (!draft)
695 { return; }
696 for (let localY = 0; localY < CHUNK_SIZE; localY++)
697 {
698 for (let localX = 0; localX < CHUNK_SIZE; localX++)
699 {
700 const block = draft.blocks[localY * CHUNK_SIZE + localX];
701 if (!block)
702 { continue; }
703 const def = BLOCK_DEFINITIONS[block.typeId];
704 if (!definitionUsesNeighborConnect(def))
705 { continue; }
706 refreshNeighborConnect(localX, localY, block.typeId);
707 }
708 }
709}
710
711function updateRevisionUI ()
712{
713 const applyBtn = $("apply");
714 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
715 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
716 if (applyBtn)
717 {
718 applyBtn.disabled = !pendingRevisionId || applyInFlight;
719 applyBtn.title = pendingRevisionId
720 ? "Reload the live world with the pending map revision"
721 : "Save a chunk first to create a pending revision";
722 }
723}
724
725function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
726{
727 if (active != null)
728 { activeRevisionId = active; }
729 pendingRevisionId = pending ?? null;
730 updateRevisionUI();
731}
732
733function showSelectedChunk (payload)
734{
735 clearNeighborEditState();
736 draft = {
737 open: payload.data.open,
738 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
739 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
740 light: payload.data.light.slice(),
741 spawners: (payload.data.spawners ?? []).map((entry) => ({
742 localX: entry.localX,
743 localY: entry.localY,
744 config: { ...entry.config }
745 }))
746 };
747 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
748 $("open").checked = draft.open;
749 setRevisionState({
750 activeRevisionId: payload.activeRevisionId,
751 pendingRevisionId: payload.pendingRevisionId
752 });
753 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
754 const log = $("changelog");
755 log.innerHTML = "";
756 for (const entry of payload.changelog ?? [])
757 {
758 const item = document.createElement("article");
759 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
760 const list = document.createElement("ul");
761 for (const bullet of entry.diffEntries)
762 {
763 const li = document.createElement("li");
764 li.textContent = bullet;
765 list.append(li);
766 }
767 item.append(list);
768 log.append(item);
769 }
770 view.applySnapshot(snapshotFromPayload(payload));
771 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
772 captureDraftBaseline();
773 recomputeAllNeighborConnectInDraft();
774 syncSaveButton();
775 if (navigateAfterSave && pendingNavigate)
776 {
777 const next = pendingNavigate;
778 navigateAfterSave = false;
779 pendingNavigate = null;
780 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
781 if (nextDim !== selectedDimensionId)
782 {
783 selectedDimensionId = nextDim;
784 syncDimensionUi();
785 clearNeighborhoodView();
786 }
787 doLoadNeighborhood(next.chunkX, next.chunkY);
788 }
789}
790
791function pruneView ()
792{
793 for (const key of [...view.chunks.keys()])
794 {
795 const [x, y] = key.split(",").map(Number);
796 if (!inEditorView(x, y))
797 {
798 view.removeChunk(x, y);
799 neighborSpawnersByChunk.delete(key);
800 dirtyNeighborChunks.delete(key);
801 }
802 }
803}
804
805function frameNeighborhood ()
806{
807 const size = view.tileSize();
808 view.followPlayer = false;
809 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
810 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
811 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
812 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
813 view.refreshViewport();
814 updateSelectionBorder();
815}
816
817function updateSelectionBorder ()
818{
819 const border = $("selection-border");
820 const canvas = scene?.canvas;
821 if (!border || !canvas)
822 { return; }
823
824 const rect = canvas.getBoundingClientRect();
825 const size = view.tileSize();
826 const chunkPx = CHUNK_SIZE * size;
827 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
828 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
829 border.style.left = `${rect.left + screenLeft}px`;
830 border.style.top = `${rect.top + screenTop}px`;
831 border.style.width = `${chunkPx}px`;
832 border.style.height = `${chunkPx}px`;
833}
834
835function layoutScene ()
836{
837 const header = document.querySelector("body > header");
838 const aside = document.querySelector("body > aside");
839 const sidePanels = $("side-panels") || $("changelog-wrap");
840 const top = header.offsetHeight;
841 aside.style.top = `${top}px`;
842 sidePanels.style.top = `${top}px`;
843 const left = aside.offsetWidth;
844 const right = sidePanels.offsetWidth;
845 const width = Math.max(64, window.innerWidth - left - right);
846 const height = Math.max(64, window.innerHeight - top);
847 scene.position.x = left;
848 scene.position.y = top;
849 scene.size.x = width;
850 scene.size.y = height;
851 scene.g_fixSize();
852 useNearestNeighbour(scene, game.images);
853 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
854 if (editorZoom == null)
855 { editorZoom = fit; }
856 else
857 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
858 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
859 frameNeighborhood();
860}
861
862function zoomEditor (direction)
863{
864 if (!view)
865 { return; }
866 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
867 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
868 scheduleEditorZoom();
869}
870
871let editorZoomRaf = 0;
872function scheduleEditorZoom ()
873{
874 if (editorZoomRaf)
875 { return; }
876 editorZoomRaf = requestAnimationFrame(() =>
877 {
878 editorZoomRaf = 0;
879 if (!view)
880 { return; }
881 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
882 frameNeighborhood();
883 });
884}
885
886function requestChunks (coords)
887{
888 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
889 { return; }
890 for (const coord of coords)
891 {
892 try
893 {
894 socket.send({
895 type: MessageType.editorLoadChunk,
896 chunkX: coord.chunkX,
897 chunkY: coord.chunkY,
898 dimensionId: selectedDimensionId
899 });
900 }
901 catch (_)
902 { break; }
903 }
904}
905
906function doLoadNeighborhood (x, y)
907{
908 chunkX = x;
909 chunkY = y;
910 $("coords").textContent = `${chunkX}, ${chunkY}`;
911 requestChunks(neighborhoodCoords(x, y));
912}
913
914function loadNeighborhood (x, y)
915{
916 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
917 {
918 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
919 return;
920 }
921 doLoadNeighborhood(x, y);
922}
923
924function requestNeighbors ()
925{
926 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
927}
928
929function anyModalOpen ()
930{
931 return settingsModal?.isOpen()
932 || paletteModal?.isOpen()
933 || tileConfigModal?.isOpen()
934 || questsModal?.isOpen()
935 || dialoguesModal?.isOpen()
936 || giftsModal?.isOpen()
937 || !$("unsaved-chunk-modal")?.hidden;
938}
939
940function updateHoverStatus (local)
941{
942 const el = $("hover-status-text");
943 if (!el)
944 { return; }
945 if (!local)
946 {
947 el.textContent = "Hover a tile for coordinates";
948 return;
949 }
950 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
951 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
952 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
953}
954
955function updateTooltip (local, options = {})
956{
957 if (!options.keepStatus)
958 { updateHoverStatus(local); }
959 const tip = $("tile-tooltip");
960 if (!tip || !local || !draft)
961 {
962 if (tip)
963 { tip.hidden = true; }
964 view?.clearSpawnRangeHighlight();
965 return;
966 }
967 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
968 const spawner = spawnerAt(local.x, local.y);
969 const lines = [];
970 if (block)
971 {
972 const def = BLOCK_DEFINITIONS[block.typeId];
973 lines.push(def?.displayName ?? `Block ${block.typeId}`);
974 if (block.config && Object.keys(block.config).length)
975 {
976 for (const [key, value] of Object.entries(block.config))
977 { lines.push(`${key}: ${value}`); }
978 }
979 }
980 if (spawner)
981 {
982 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
983 const mob = mobDefinition(config.mobTypeId);
984 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
985 lines.push(`maxAlive: ${config.maxAlive}`);
986 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
987 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
988 lines.push(`id: ${config.spawnerId}`);
989 view.setSpawnRangeHighlight(
990 local.tileX,
991 local.tileY,
992 config.spawnRangeTiles,
993 config.maxWanderRangeTiles
994 );
995 }
996 else
997 { view.clearSpawnRangeHighlight(); }
998 if (!lines.length)
999 {
1000 tip.hidden = true;
1001 return;
1002 }
1003 tip.hidden = false;
1004 tip.textContent = lines.join("\n");
1005 const canvas = scene.canvas;
1006 const rect = canvas.getBoundingClientRect();
1007 const size = view.tileSize();
1008 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
1009 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
1010 tip.style.left = `${screenX}px`;
1011 tip.style.top = `${screenY}px`;
1012}
1013
1014async function main ()
1015{
1016 const authStatus = await fetchAuthStatus();
1017 const signIn = document.getElementById("auth-sign-in");
1018 const signOut = document.getElementById("auth-sign-out");
1019 if (signIn)
1020 {
1021 signIn.hidden = !!authStatus?.authenticated;
1022 signIn.href = loginUrl("/editor");
1023 }
1024 if (signOut)
1025 {
1026 signOut.hidden = !authStatus?.authenticated;
1027 signOut.href = logoutUrl("/editor");
1028 }
1029 if (!authStatus.authenticated)
1030 {
1031 $("who").textContent = "Sign in required";
1032 $("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
1033 return;
1034 }
1035
1036 const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in";
1037 $("who").textContent = `${accountLabel} · loading sprites…`;
1038
1039 catalog = await loadSpriteCatalog();
1040 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
1041 await preloadCatalogImages(game, catalog, {
1042 onProgress ({ loaded, total })
1043 {
1044 $("who").textContent = `${accountLabel} · loading sprites ${loaded}/${total}`;
1045 }
1046 });
1047 applySpriteSheets(game.images, catalog);
1048 scene = new Scene(250, 56, 64, 64);
1049 game.loadScene(scene);
1050 view = new WorldView(game, scene, catalog);
1051 view.followPlayer = false;
1052 view.setGraphicsPrefs(loadGraphicsSettings());
1053 syncSeasonControls(view.worldSeason ?? seasonIdAt());
1054 layoutScene();
1055 selectTool(tool);
1056 $("tool").textContent = selectedToolLabel();
1057
1058 paletteModal = initPaletteModal({
1059 catalog,
1060 imageUrlFor (name)
1061 {
1062 const sprite = game.images[name];
1063 const html = sprite?.g_image;
1064 if (html && typeof html.toDataURL === "function")
1065 {
1066 try
1067 { return html.toDataURL("image/png"); }
1068 catch (_)
1069 { /* fall through */ }
1070 }
1071 return imageUrlByName.get(name) ?? null;
1072 },
1073 onSelect (next)
1074 {
1075 selectTool(next);
1076 $("tool").textContent = selectedToolLabel();
1077 }
1078 });
1079
1080 tileConfigModal = initTileConfigModal({
1081 socket: {
1082 send (payload)
1083 {
1084 socket?.send(payload);
1085 }
1086 },
1087 MessageType,
1088 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
1089 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1090 id: dim.dimensionId,
1091 label: dim.displayName || dim.dimensionId,
1092 disabled: !!dim.deletedAt,
1093 hint: dim.deletedAt ? "soft-deleted" : undefined
1094 })),
1095 onSave (ctx, config)
1096 {
1097 if (!draft)
1098 { return; }
1099 if (ctx.kind === "doorway")
1100 {
1101 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1102 draft.blocks[index] = {
1103 typeId: BlockType.doorway,
1104 state: config.state || "door",
1105 config: {
1106 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
1107 tileX: Number(config.tileX) || 0,
1108 tileY: Number(config.tileY) || 0
1109 }
1110 };
1111 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1112 ground: draft.grounds[index],
1113 block: draft.blocks[index],
1114 light: draft.light[index]
1115 });
1116 afterDraftMutation();
1117 return;
1118 }
1119 if (ctx.kind === "fishing-spot")
1120 {
1121 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1122 const existing = draft.blocks[index];
1123 draft.blocks[index] = {
1124 typeId: BlockType.fishingSpot,
1125 state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
1126 config: { fishes: [...(config.fishes ?? [])] }
1127 };
1128 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1129 ground: draft.grounds[index],
1130 block: draft.blocks[index],
1131 light: draft.light[index]
1132 });
1133 afterDraftMutation();
1134 return;
1135 }
1136 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1137 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
1138 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1139 afterDraftMutation();
1140 },
1141 onRemove (ctx)
1142 {
1143 if (!draft)
1144 { return; }
1145 if (ctx.kind === "doorway")
1146 {
1147 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1148 draft.blocks[index] = null;
1149 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1150 ground: draft.grounds[index],
1151 block: draft.blocks[index],
1152 light: draft.light[index]
1153 });
1154 afterDraftMutation();
1155 return;
1156 }
1157 if (ctx.kind === "fishing-spot")
1158 {
1159 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1160 draft.blocks[index] = null;
1161 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1162 ground: draft.grounds[index],
1163 block: draft.blocks[index],
1164 light: draft.light[index]
1165 });
1166 afterDraftMutation();
1167 return;
1168 }
1169 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1170 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1171 afterDraftMutation();
1172 }
1173 });
1174
1175 const ticker = new GameObject(0, 0, null, 10);
1176 ticker.update = (dt) =>
1177 {
1178 hoverLocal = null;
1179 const canvas = scene.canvas;
1180 const rect = canvas.getBoundingClientRect();
1181 const mouseX = GameInput.mousePosition.x - rect.left;
1182 const mouseY = GameInput.mousePosition.y - rect.top;
1183 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
1184 if (overCanvas && draft && !anyModalOpen())
1185 {
1186 const tile = view.screenToTile(mouseX, mouseY);
1187 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1188 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1189 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
1190 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
1191 updateHoverStatus({
1192 tileX: tile.tileX,
1193 tileY: tile.tileY,
1194 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1195 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1196 chunkX: hoverChunkX,
1197 chunkY: hoverChunkY
1198 });
1199 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
1200 {
1201 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
1202 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
1203 updateTooltip(hoverLocal);
1204 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
1205 { paintAt(localX, localY); }
1206 }
1207 else
1208 {
1209 hoverLocal = null;
1210 view.clearTilePreview();
1211 updateTooltip(null, { keepStatus: true });
1212 }
1213 }
1214 else
1215 {
1216 view.clearTilePreview();
1217 updateTooltip(null);
1218 }
1219 view.update(dt);
1220 frameNeighborhood();
1221 };
1222 scene.addObject(ticker);
1223 window.addEventListener("resize", layoutScene);
1224
1225 $("who").textContent = `${accountLabel} · connecting…`;
1226
1227 socket = new GameSocket(defaultSocketUrl(), (message) =>
1228 {
1229 if (message.type === MessageType.session)
1230 {
1231 sessionAuthSubject = message.authSubject ?? null;
1232 const label = message.username ?? message.authSubject ?? "Unknown";
1233 $("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1234 if (!message.isAdmin)
1235 {
1236 $("error").textContent = "Admin access required.";
1237 return;
1238 }
1239 $("error").textContent = "";
1240 const restartBtn = document.getElementById("editor-restart-now");
1241 if (restartBtn)
1242 {
1243 restartBtn.hidden = false;
1244 restartBtn.disabled = false;
1245 }
1246 socket.send({ type: MessageType.editorLoadSettings });
1247 socket.send({ type: MessageType.editorLoadGameAdmins });
1248 socket.send({ type: MessageType.editorConsoleSubscribe });
1249 requestDimensions();
1250 loadNeighborhood(0, 0);
1251 }
1252 else if (message.type === MessageType.editorSettings
1253 || message.type === MessageType.editorGameAdmins)
1254 { settingsModal.handleMessage(message); }
1255 else if (message.type === MessageType.editorConsoleSnapshot)
1256 { applyConsoleSnapshot(message.lines); }
1257 else if (message.type === MessageType.editorConsoleLine)
1258 { appendConsoleLine(message.line); }
1259 else if (message.type === MessageType.editorDimensions)
1260 {
1261 applyDimensionsList(message);
1262 }
1263 else if (message.type === MessageType.editorQuests)
1264 { questsModal?.handleMessage(message); }
1265 else if (message.type === MessageType.editorDialogues)
1266 {
1267 dialoguesModal?.handleMessage(message);
1268 tileConfigModal?.handleMessage(message);
1269 }
1270 else if (message.type === MessageType.editorGiftCharacters
1271 || message.type === MessageType.editorGiftSent)
1272 { giftsModal?.handleMessage(message); }
1273 else if (message.type === MessageType.editorChunk)
1274 {
1275 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1276 if (msgDim !== selectedDimensionId)
1277 { return; }
1278 if (message.settings)
1279 { view.setSettings(message.settings); }
1280 if (!inEditorView(message.chunkX, message.chunkY))
1281 { return; }
1282 if (message.chunkX === chunkX && message.chunkY === chunkY)
1283 { showSelectedChunk(message); }
1284 else
1285 {
1286 const key = chunkKey(message.chunkX, message.chunkY);
1287 neighborSpawnersByChunk.set(key, message.data.spawners ?? []);
1288 if (!dirtyNeighborChunks.has(key))
1289 {
1290 view.applySnapshot(snapshotFromPayload(message));
1291 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
1292 }
1293 }
1294 pruneView();
1295 }
1296 else if (message.type === MessageType.editorRevisionApplied)
1297 {
1298 applyInFlight = false;
1299 setRevisionState({
1300 activeRevisionId: message.activeRevisionId,
1301 pendingRevisionId: message.pendingRevisionId
1302 });
1303 const status = $("apply-status");
1304 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
1305 status.className = "hint ok";
1306 requestDimensions();
1307 requestChunks(neighborhoodCoords(chunkX, chunkY));
1308 }
1309 else if (message.type === MessageType.forceLogout)
1310 {
1311 $("who").textContent = "Server restarting…";
1312 $("error").textContent = message.reason || "Server shutting down.";
1313 }
1314 else if (message.type === MessageType.error)
1315 {
1316 $("error").textContent = message.message;
1317 if (giftsModal?.isOpen())
1318 { giftsModal.handleError?.(message.message); }
1319 pendingCreatedDimensionId = null;
1320 navigateAfterSave = false;
1321 dimensionCombo?.setValue(selectedDimensionId);
1322 if (applyInFlight)
1323 {
1324 applyInFlight = false;
1325 $("apply-status").textContent = "";
1326 $("apply-status").className = "hint";
1327 updateRevisionUI();
1328 }
1329 }
1330 }, {
1331 onClose (event)
1332 {
1333 if (event.code === 1000)
1334 { return; }
1335 const reasons = {
1336 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1337 1011: "Server could not verify your account with auth.timfalken.com.",
1338 1006: "Connection dropped before the editor session started.",
1339 1001: "Server is restarting. Reload this page in a moment."
1340 };
1341 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1342 $("who").textContent = "Connection failed";
1343 $("error").textContent = detail;
1344 },
1345 onError ()
1346 {
1347 $("who").textContent = "Connection failed";
1348 $("error").textContent = "Could not open a live connection to the server.";
1349 }
1350 });
1351 settingsModal = initSettingsModal({
1352 socket,
1353 MessageType,
1354 getAuthSubject: () => sessionAuthSubject,
1355 onApplied (settings)
1356 {
1357 view.setSettings(settings);
1358 },
1359 onPreviewNight (hour)
1360 {
1361 view.nightPreview = hour;
1362 $("night").value = String(hour);
1363 $("night-label").textContent = Number(hour).toFixed(1);
1364 }
1365 });
1366 dimensionCombo = createDimensionCombobox({
1367 root: $("dimension-combo"),
1368 allowCreate: true,
1369 placeholder: "Search or create dimension…",
1370 onSelect (id)
1371 {
1372 selectDimension(id);
1373 },
1374 onCreate (rawId)
1375 {
1376 const id = normalizeDimensionId(rawId);
1377 $("error").textContent = "";
1378 pendingCreatedDimensionId = id;
1379 socket.send({
1380 type: MessageType.editorCreateDimension,
1381 dimensionId: id,
1382 displayName: rawId.trim()
1383 });
1384 }
1385 });
1386 dimensionCombo.setOptions([{
1387 id: OVERWORLD_ID,
1388 label: "Overworld"
1389 }]);
1390 dimensionCombo.setValue(OVERWORLD_ID);
1391 dimensionSettings = initDimensionSettings({
1392 socket,
1393 MessageType,
1394 GROUND_DEFINITIONS,
1395 OVERWORLD_ID,
1396 getSelectedDimensionId: () => selectedDimensionId,
1397 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1398 isOverworld
1399 });
1400 questsModal = initQuestsModal({ socket, MessageType });
1401 dialoguesModal = initDialoguesModal({ socket, MessageType });
1402 giftsModal = initGiftsModal({ socket, MessageType });
1403 initSidePanelTabs();
1404 game.startGame();
1405 useNearestNeighbour(scene, game.images);
1406 await socket.connect();
1407}
1408
1409$("tool").textContent = selectedToolLabel();
1410$("tool-erase").addEventListener("click", () =>
1411{
1412 selectTool({ kind: "erase" });
1413 $("tool").textContent = selectedToolLabel();
1414});
1415
1416$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
1417$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
1418$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
1419$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
1420$("open").addEventListener("change", () =>
1421{
1422 if (isSelectedDimensionSoftDeleted())
1423 {
1424 $("open").checked = !!draft?.open;
1425 return;
1426 }
1427 if (draft)
1428 {
1429 draft.open = $("open").checked;
1430 view.setChunkOpen(chunkX, chunkY, draft.open);
1431 afterDraftMutation();
1432 }
1433});
1434$("save").addEventListener("click", () =>
1435{
1436 saveSelectedChunk();
1437});
1438$("unsaved-chunk-cancel")?.addEventListener("click", () =>
1439{
1440 pendingNavigate = null;
1441 navigateAfterSave = false;
1442 hideUnsavedModal();
1443});
1444$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
1445{
1446 pendingNavigate = null;
1447 navigateAfterSave = false;
1448 hideUnsavedModal();
1449});
1450$("unsaved-chunk-discard")?.addEventListener("click", () =>
1451{
1452 const next = pendingNavigate;
1453 hideUnsavedModal();
1454 pendingNavigate = null;
1455 navigateAfterSave = false;
1456 if (!next)
1457 { return; }
1458 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1459 if (nextDim !== selectedDimensionId)
1460 {
1461 selectedDimensionId = nextDim;
1462 syncDimensionUi();
1463 clearNeighborhoodView();
1464 }
1465 doLoadNeighborhood(next.chunkX, next.chunkY);
1466});
1467$("unsaved-chunk-save")?.addEventListener("click", () =>
1468{
1469 hideUnsavedModal();
1470 if (!pendingNavigate)
1471 { return; }
1472 navigateAfterSave = true;
1473 if (!saveSelectedChunk())
1474 {
1475 navigateAfterSave = false;
1476 const next = pendingNavigate;
1477 pendingNavigate = null;
1478 if (next)
1479 {
1480 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1481 if (nextDim !== selectedDimensionId)
1482 {
1483 selectedDimensionId = nextDim;
1484 syncDimensionUi();
1485 clearNeighborhoodView();
1486 }
1487 doLoadNeighborhood(next.chunkX, next.chunkY);
1488 }
1489 }
1490});
1491$("apply").addEventListener("click", () =>
1492{
1493 if (!pendingRevisionId || applyInFlight)
1494 { return; }
1495 $("error").textContent = "";
1496 const status = $("apply-status");
1497 status.textContent = "Applying…";
1498 status.className = "hint";
1499 applyInFlight = true;
1500 updateRevisionUI();
1501 socket.send({ type: MessageType.editorApplyRevision });
1502});
1503document.getElementById("editor-restart-now")?.addEventListener("click", () =>
1504{
1505 if (!socket)
1506 { return; }
1507 const ok = window.confirm(
1508 "Restart the server now?\n\nAll players and editor sessions will disconnect. "
1509 + "systemd will start a fresh process and pull the latest code from git."
1510 );
1511 if (!ok)
1512 { return; }
1513 const restartBtn = document.getElementById("editor-restart-now");
1514 if (restartBtn)
1515 { restartBtn.disabled = true; }
1516 $("who").textContent = "Restarting server…";
1517 $("error").textContent = "";
1518 socket.send({ type: MessageType.editorRestartNow });
1519});
1520$("night").addEventListener("input", () =>
1521{
1522 view.nightPreview = Number($("night").value);
1523 $("night-label").textContent = view.nightPreview.toFixed(1);
1524});
1525$("season").addEventListener("change", () =>
1526{
1527 applySeasonPreview($("season").value);
1528});
1529
1530function syncSeasonControls (season)
1531{
1532 const next = season === SeasonId.spring
1533 || season === SeasonId.fall
1534 || season === SeasonId.winter
1535 || season === SeasonId.summer
1536 ? season
1537 : seasonIdAt();
1538 $("season").value = next;
1539 view?.setWorldSeason(next);
1540}
1541
1542function applySeasonPreview (season)
1543{
1544 syncSeasonControls(season);
1545}
1546
1547function cycleToolState (direction)
1548{
1549 if (tool.kind === "erase" || tool.kind === "spawner")
1550 { return; }
1551 const layer = tool.kind === "ground" ? "ground" : "block";
1552 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
1553 if (definitionUsesNeighborConnect(def))
1554 { return; }
1555 if (tool.kind === "block" && def?.id === BlockType.flower)
1556 { return; }
1557 const allStates = statesForType(catalog, layer, def.key);
1558 const seasonal = seasonalCycleStates(allStates);
1559 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
1560 if (states.length < 2)
1561 { return; }
1562 tool.state = cycleState(states, tool.state, direction);
1563 $("tool").textContent = selectedToolLabel();
1564 const season = seasonIdFromVisualState(tool.state);
1565 if (season)
1566 { applySeasonPreview(season); }
1567 if (!draft || !hoverLocal)
1568 { return; }
1569 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
1570 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
1571 { paintAt(hoverLocal.x, hoverLocal.y); }
1572 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
1573 { paintAt(hoverLocal.x, hoverLocal.y); }
1574}
1575
1576document.addEventListener("wheel", (event) =>
1577{
1578 if (!scene?.canvas || anyModalOpen())
1579 { return; }
1580 const rect = scene.canvas.getBoundingClientRect();
1581 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1582 { return; }
1583 event.preventDefault();
1584 if (event.shiftKey)
1585 {
1586 cycleToolState(event.deltaY < 0 ? 1 : -1);
1587 if (hoverLocal)
1588 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
1589 return;
1590 }
1591 zoomEditor(event.deltaY < 0 ? 1 : -1);
1592}, { passive: false });
1593
1594document.addEventListener("contextmenu", (event) =>
1595{
1596 if (!scene?.canvas || anyModalOpen() || !draft)
1597 { return; }
1598 const rect = scene.canvas.getBoundingClientRect();
1599 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1600 { return; }
1601 event.preventDefault();
1602 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
1603 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1604 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1605 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1606 { return; }
1607 const spawner = spawnerAt(localX, localY);
1608 if (spawner)
1609 {
1610 tileConfigModal.openSpawner({
1611 localX,
1612 localY,
1613 tileX: tile.tileX,
1614 tileY: tile.tileY,
1615 config: { ...spawner.config }
1616 });
1617 return;
1618 }
1619 const index = localY * CHUNK_SIZE + localX;
1620 const block = draft.blocks[index];
1621 if (block?.typeId === BlockType.doorway)
1622 {
1623 tileConfigModal.openDoorway({
1624 localX,
1625 localY,
1626 tileX: tile.tileX,
1627 tileY: tile.tileY,
1628 state: block.state ?? "door",
1629 config: block.config ? { ...block.config } : {}
1630 });
1631 return;
1632 }
1633 if (block?.typeId === BlockType.fishingSpot)
1634 {
1635 tileConfigModal.openFishingSpot({
1636 localX,
1637 localY,
1638 tileX: tile.tileX,
1639 tileY: tile.tileY,
1640 config: block.config ? { ...block.config } : { fishes: [] }
1641 });
1642 }
1643});
1644
1645main().catch((error) =>
1646{
1647 $("error").textContent = error.message;
1648 console.error(error);
1649});