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 updateSelectionBorder();
814}
815
816function updateSelectionBorder ()
817{
818 const border = $("selection-border");
819 const canvas = scene?.canvas;
820 if (!border || !canvas)
821 { return; }
822
823 const rect = canvas.getBoundingClientRect();
824 const size = view.tileSize();
825 const chunkPx = CHUNK_SIZE * size;
826 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
827 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
828 border.style.left = `${rect.left + screenLeft}px`;
829 border.style.top = `${rect.top + screenTop}px`;
830 border.style.width = `${chunkPx}px`;
831 border.style.height = `${chunkPx}px`;
832}
833
834function layoutScene ()
835{
836 const header = document.querySelector("body > header");
837 const aside = document.querySelector("body > aside");
838 const sidePanels = $("side-panels") || $("changelog-wrap");
839 const top = header.offsetHeight;
840 aside.style.top = `${top}px`;
841 sidePanels.style.top = `${top}px`;
842 const left = aside.offsetWidth;
843 const right = sidePanels.offsetWidth;
844 const width = Math.max(64, window.innerWidth - left - right);
845 const height = Math.max(64, window.innerHeight - top);
846 scene.position.x = left;
847 scene.position.y = top;
848 scene.size.x = width;
849 scene.size.y = height;
850 scene.g_fixSize();
851 useNearestNeighbour(scene, game.images);
852 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
853 if (editorZoom == null)
854 { editorZoom = fit; }
855 else
856 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
857 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
858 frameNeighborhood();
859}
860
861function zoomEditor (direction)
862{
863 if (!view)
864 { return; }
865 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
866 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
867 scheduleEditorZoom();
868}
869
870let editorZoomRaf = 0;
871function scheduleEditorZoom ()
872{
873 if (editorZoomRaf)
874 { return; }
875 editorZoomRaf = requestAnimationFrame(() =>
876 {
877 editorZoomRaf = 0;
878 if (!view)
879 { return; }
880 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
881 frameNeighborhood();
882 });
883}
884
885function requestChunks (coords)
886{
887 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
888 { return; }
889 for (const coord of coords)
890 {
891 try
892 {
893 socket.send({
894 type: MessageType.editorLoadChunk,
895 chunkX: coord.chunkX,
896 chunkY: coord.chunkY,
897 dimensionId: selectedDimensionId
898 });
899 }
900 catch (_)
901 { break; }
902 }
903}
904
905function doLoadNeighborhood (x, y)
906{
907 chunkX = x;
908 chunkY = y;
909 $("coords").textContent = `${chunkX}, ${chunkY}`;
910 requestChunks(neighborhoodCoords(x, y));
911}
912
913function loadNeighborhood (x, y)
914{
915 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
916 {
917 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
918 return;
919 }
920 doLoadNeighborhood(x, y);
921}
922
923function requestNeighbors ()
924{
925 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
926}
927
928function anyModalOpen ()
929{
930 return settingsModal?.isOpen()
931 || paletteModal?.isOpen()
932 || tileConfigModal?.isOpen()
933 || questsModal?.isOpen()
934 || dialoguesModal?.isOpen()
935 || giftsModal?.isOpen()
936 || !$("unsaved-chunk-modal")?.hidden;
937}
938
939function updateHoverStatus (local)
940{
941 const el = $("hover-status-text");
942 if (!el)
943 { return; }
944 if (!local)
945 {
946 el.textContent = "Hover a tile for coordinates";
947 return;
948 }
949 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
950 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
951 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
952}
953
954function updateTooltip (local, options = {})
955{
956 if (!options.keepStatus)
957 { updateHoverStatus(local); }
958 const tip = $("tile-tooltip");
959 if (!tip || !local || !draft)
960 {
961 if (tip)
962 { tip.hidden = true; }
963 view?.clearSpawnRangeHighlight();
964 return;
965 }
966 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
967 const spawner = spawnerAt(local.x, local.y);
968 const lines = [];
969 if (block)
970 {
971 const def = BLOCK_DEFINITIONS[block.typeId];
972 lines.push(def?.displayName ?? `Block ${block.typeId}`);
973 if (block.config && Object.keys(block.config).length)
974 {
975 for (const [key, value] of Object.entries(block.config))
976 { lines.push(`${key}: ${value}`); }
977 }
978 }
979 if (spawner)
980 {
981 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
982 const mob = mobDefinition(config.mobTypeId);
983 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
984 lines.push(`maxAlive: ${config.maxAlive}`);
985 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
986 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
987 lines.push(`id: ${config.spawnerId}`);
988 view.setSpawnRangeHighlight(
989 local.tileX,
990 local.tileY,
991 config.spawnRangeTiles,
992 config.maxWanderRangeTiles
993 );
994 }
995 else
996 { view.clearSpawnRangeHighlight(); }
997 if (!lines.length)
998 {
999 tip.hidden = true;
1000 return;
1001 }
1002 tip.hidden = false;
1003 tip.textContent = lines.join("\n");
1004 const canvas = scene.canvas;
1005 const rect = canvas.getBoundingClientRect();
1006 const size = view.tileSize();
1007 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
1008 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
1009 tip.style.left = `${screenX}px`;
1010 tip.style.top = `${screenY}px`;
1011}
1012
1013async function main ()
1014{
1015 const authStatus = await fetchAuthStatus();
1016 const signIn = document.getElementById("auth-sign-in");
1017 const signOut = document.getElementById("auth-sign-out");
1018 if (signIn)
1019 {
1020 signIn.hidden = !!authStatus?.authenticated;
1021 signIn.href = loginUrl("/editor");
1022 }
1023 if (signOut)
1024 {
1025 signOut.hidden = !authStatus?.authenticated;
1026 signOut.href = logoutUrl("/editor");
1027 }
1028 if (!authStatus.authenticated)
1029 {
1030 $("who").textContent = "Sign in required";
1031 $("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
1032 return;
1033 }
1034
1035 const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in";
1036 $("who").textContent = `${accountLabel} · loading sprites…`;
1037
1038 catalog = await loadSpriteCatalog();
1039 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
1040 await preloadCatalogImages(game, catalog, {
1041 onProgress ({ loaded, total })
1042 {
1043 $("who").textContent = `${accountLabel} · loading sprites ${loaded}/${total}`;
1044 }
1045 });
1046 applySpriteSheets(game.images, catalog);
1047 scene = new Scene(250, 56, 64, 64);
1048 game.loadScene(scene);
1049 view = new WorldView(game, scene, catalog);
1050 view.followPlayer = false;
1051 view.setGraphicsPrefs(loadGraphicsSettings());
1052 syncSeasonControls(view.worldSeason ?? seasonIdAt());
1053 layoutScene();
1054 selectTool(tool);
1055 $("tool").textContent = selectedToolLabel();
1056
1057 paletteModal = initPaletteModal({
1058 catalog,
1059 imageUrlFor (name)
1060 {
1061 const sprite = game.images[name];
1062 const html = sprite?.g_image;
1063 if (html && typeof html.toDataURL === "function")
1064 {
1065 try
1066 { return html.toDataURL("image/png"); }
1067 catch (_)
1068 { /* fall through */ }
1069 }
1070 return imageUrlByName.get(name) ?? null;
1071 },
1072 onSelect (next)
1073 {
1074 selectTool(next);
1075 $("tool").textContent = selectedToolLabel();
1076 }
1077 });
1078
1079 tileConfigModal = initTileConfigModal({
1080 socket: {
1081 send (payload)
1082 {
1083 socket?.send(payload);
1084 }
1085 },
1086 MessageType,
1087 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
1088 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1089 id: dim.dimensionId,
1090 label: dim.displayName || dim.dimensionId,
1091 disabled: !!dim.deletedAt,
1092 hint: dim.deletedAt ? "soft-deleted" : undefined
1093 })),
1094 onSave (ctx, config)
1095 {
1096 if (!draft)
1097 { return; }
1098 if (ctx.kind === "doorway")
1099 {
1100 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1101 draft.blocks[index] = {
1102 typeId: BlockType.doorway,
1103 state: config.state || "door",
1104 config: {
1105 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
1106 tileX: Number(config.tileX) || 0,
1107 tileY: Number(config.tileY) || 0
1108 }
1109 };
1110 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1111 ground: draft.grounds[index],
1112 block: draft.blocks[index],
1113 light: draft.light[index]
1114 });
1115 afterDraftMutation();
1116 return;
1117 }
1118 if (ctx.kind === "fishing-spot")
1119 {
1120 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1121 const existing = draft.blocks[index];
1122 draft.blocks[index] = {
1123 typeId: BlockType.fishingSpot,
1124 state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
1125 config: { fishes: [...(config.fishes ?? [])] }
1126 };
1127 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1128 ground: draft.grounds[index],
1129 block: draft.blocks[index],
1130 light: draft.light[index]
1131 });
1132 afterDraftMutation();
1133 return;
1134 }
1135 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1136 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
1137 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1138 afterDraftMutation();
1139 },
1140 onRemove (ctx)
1141 {
1142 if (!draft)
1143 { return; }
1144 if (ctx.kind === "doorway")
1145 {
1146 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1147 draft.blocks[index] = null;
1148 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1149 ground: draft.grounds[index],
1150 block: draft.blocks[index],
1151 light: draft.light[index]
1152 });
1153 afterDraftMutation();
1154 return;
1155 }
1156 if (ctx.kind === "fishing-spot")
1157 {
1158 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1159 draft.blocks[index] = null;
1160 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1161 ground: draft.grounds[index],
1162 block: draft.blocks[index],
1163 light: draft.light[index]
1164 });
1165 afterDraftMutation();
1166 return;
1167 }
1168 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1169 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1170 afterDraftMutation();
1171 }
1172 });
1173
1174 const ticker = new GameObject(0, 0, null, 10);
1175 ticker.update = (dt) =>
1176 {
1177 hoverLocal = null;
1178 const canvas = scene.canvas;
1179 const rect = canvas.getBoundingClientRect();
1180 const mouseX = GameInput.mousePosition.x - rect.left;
1181 const mouseY = GameInput.mousePosition.y - rect.top;
1182 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
1183 if (overCanvas && draft && !anyModalOpen())
1184 {
1185 const tile = view.screenToTile(mouseX, mouseY);
1186 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1187 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1188 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
1189 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
1190 updateHoverStatus({
1191 tileX: tile.tileX,
1192 tileY: tile.tileY,
1193 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1194 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1195 chunkX: hoverChunkX,
1196 chunkY: hoverChunkY
1197 });
1198 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
1199 {
1200 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
1201 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
1202 updateTooltip(hoverLocal);
1203 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
1204 { paintAt(localX, localY); }
1205 }
1206 else
1207 {
1208 hoverLocal = null;
1209 view.clearTilePreview();
1210 updateTooltip(null, { keepStatus: true });
1211 }
1212 }
1213 else
1214 {
1215 view.clearTilePreview();
1216 updateTooltip(null);
1217 }
1218 view.update(dt);
1219 frameNeighborhood();
1220 };
1221 scene.addObject(ticker);
1222 window.addEventListener("resize", layoutScene);
1223
1224 $("who").textContent = `${accountLabel} · connecting…`;
1225
1226 socket = new GameSocket(defaultSocketUrl(), (message) =>
1227 {
1228 if (message.type === MessageType.session)
1229 {
1230 sessionAuthSubject = message.authSubject ?? null;
1231 const label = message.username ?? message.authSubject ?? "Unknown";
1232 $("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1233 if (!message.isAdmin)
1234 {
1235 $("error").textContent = "Admin access required.";
1236 return;
1237 }
1238 $("error").textContent = "";
1239 const restartBtn = document.getElementById("editor-restart-now");
1240 if (restartBtn)
1241 {
1242 restartBtn.hidden = false;
1243 restartBtn.disabled = false;
1244 }
1245 socket.send({ type: MessageType.editorLoadSettings });
1246 socket.send({ type: MessageType.editorLoadGameAdmins });
1247 socket.send({ type: MessageType.editorConsoleSubscribe });
1248 requestDimensions();
1249 loadNeighborhood(0, 0);
1250 }
1251 else if (message.type === MessageType.editorSettings
1252 || message.type === MessageType.editorGameAdmins)
1253 { settingsModal.handleMessage(message); }
1254 else if (message.type === MessageType.editorConsoleSnapshot)
1255 { applyConsoleSnapshot(message.lines); }
1256 else if (message.type === MessageType.editorConsoleLine)
1257 { appendConsoleLine(message.line); }
1258 else if (message.type === MessageType.editorDimensions)
1259 {
1260 applyDimensionsList(message);
1261 }
1262 else if (message.type === MessageType.editorQuests)
1263 { questsModal?.handleMessage(message); }
1264 else if (message.type === MessageType.editorDialogues)
1265 {
1266 dialoguesModal?.handleMessage(message);
1267 tileConfigModal?.handleMessage(message);
1268 }
1269 else if (message.type === MessageType.editorGiftCharacters
1270 || message.type === MessageType.editorGiftSent)
1271 { giftsModal?.handleMessage(message); }
1272 else if (message.type === MessageType.editorChunk)
1273 {
1274 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1275 if (msgDim !== selectedDimensionId)
1276 { return; }
1277 if (message.settings)
1278 { view.setSettings(message.settings); }
1279 if (!inEditorView(message.chunkX, message.chunkY))
1280 { return; }
1281 if (message.chunkX === chunkX && message.chunkY === chunkY)
1282 { showSelectedChunk(message); }
1283 else
1284 {
1285 const key = chunkKey(message.chunkX, message.chunkY);
1286 neighborSpawnersByChunk.set(key, message.data.spawners ?? []);
1287 if (!dirtyNeighborChunks.has(key))
1288 {
1289 view.applySnapshot(snapshotFromPayload(message));
1290 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
1291 }
1292 }
1293 pruneView();
1294 }
1295 else if (message.type === MessageType.editorRevisionApplied)
1296 {
1297 applyInFlight = false;
1298 setRevisionState({
1299 activeRevisionId: message.activeRevisionId,
1300 pendingRevisionId: message.pendingRevisionId
1301 });
1302 const status = $("apply-status");
1303 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
1304 status.className = "hint ok";
1305 requestDimensions();
1306 requestChunks(neighborhoodCoords(chunkX, chunkY));
1307 }
1308 else if (message.type === MessageType.forceLogout)
1309 {
1310 $("who").textContent = "Server restarting…";
1311 $("error").textContent = message.reason || "Server shutting down.";
1312 }
1313 else if (message.type === MessageType.error)
1314 {
1315 $("error").textContent = message.message;
1316 if (giftsModal?.isOpen())
1317 { giftsModal.handleError?.(message.message); }
1318 pendingCreatedDimensionId = null;
1319 navigateAfterSave = false;
1320 dimensionCombo?.setValue(selectedDimensionId);
1321 if (applyInFlight)
1322 {
1323 applyInFlight = false;
1324 $("apply-status").textContent = "";
1325 $("apply-status").className = "hint";
1326 updateRevisionUI();
1327 }
1328 }
1329 }, {
1330 onClose (event)
1331 {
1332 if (event.code === 1000)
1333 { return; }
1334 const reasons = {
1335 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1336 1011: "Server could not verify your account with auth.timfalken.com.",
1337 1006: "Connection dropped before the editor session started.",
1338 1001: "Server is restarting. Reload this page in a moment."
1339 };
1340 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1341 $("who").textContent = "Connection failed";
1342 $("error").textContent = detail;
1343 },
1344 onError ()
1345 {
1346 $("who").textContent = "Connection failed";
1347 $("error").textContent = "Could not open a live connection to the server.";
1348 }
1349 });
1350 settingsModal = initSettingsModal({
1351 socket,
1352 MessageType,
1353 getAuthSubject: () => sessionAuthSubject,
1354 onApplied (settings)
1355 {
1356 view.setSettings(settings);
1357 },
1358 onPreviewNight (hour)
1359 {
1360 view.nightPreview = hour;
1361 $("night").value = String(hour);
1362 $("night-label").textContent = Number(hour).toFixed(1);
1363 }
1364 });
1365 dimensionCombo = createDimensionCombobox({
1366 root: $("dimension-combo"),
1367 allowCreate: true,
1368 placeholder: "Search or create dimension…",
1369 onSelect (id)
1370 {
1371 selectDimension(id);
1372 },
1373 onCreate (rawId)
1374 {
1375 const id = normalizeDimensionId(rawId);
1376 $("error").textContent = "";
1377 pendingCreatedDimensionId = id;
1378 socket.send({
1379 type: MessageType.editorCreateDimension,
1380 dimensionId: id,
1381 displayName: rawId.trim()
1382 });
1383 }
1384 });
1385 dimensionCombo.setOptions([{
1386 id: OVERWORLD_ID,
1387 label: "Overworld"
1388 }]);
1389 dimensionCombo.setValue(OVERWORLD_ID);
1390 dimensionSettings = initDimensionSettings({
1391 socket,
1392 MessageType,
1393 GROUND_DEFINITIONS,
1394 OVERWORLD_ID,
1395 getSelectedDimensionId: () => selectedDimensionId,
1396 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1397 isOverworld
1398 });
1399 questsModal = initQuestsModal({ socket, MessageType });
1400 dialoguesModal = initDialoguesModal({ socket, MessageType });
1401 giftsModal = initGiftsModal({ socket, MessageType });
1402 initSidePanelTabs();
1403 game.startGame();
1404 useNearestNeighbour(scene, game.images);
1405 await socket.connect();
1406}
1407
1408$("tool").textContent = selectedToolLabel();
1409$("tool-erase").addEventListener("click", () =>
1410{
1411 selectTool({ kind: "erase" });
1412 $("tool").textContent = selectedToolLabel();
1413});
1414
1415$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
1416$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
1417$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
1418$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
1419$("open").addEventListener("change", () =>
1420{
1421 if (isSelectedDimensionSoftDeleted())
1422 {
1423 $("open").checked = !!draft?.open;
1424 return;
1425 }
1426 if (draft)
1427 {
1428 draft.open = $("open").checked;
1429 view.setChunkOpen(chunkX, chunkY, draft.open);
1430 afterDraftMutation();
1431 }
1432});
1433$("save").addEventListener("click", () =>
1434{
1435 saveSelectedChunk();
1436});
1437$("unsaved-chunk-cancel")?.addEventListener("click", () =>
1438{
1439 pendingNavigate = null;
1440 navigateAfterSave = false;
1441 hideUnsavedModal();
1442});
1443$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
1444{
1445 pendingNavigate = null;
1446 navigateAfterSave = false;
1447 hideUnsavedModal();
1448});
1449$("unsaved-chunk-discard")?.addEventListener("click", () =>
1450{
1451 const next = pendingNavigate;
1452 hideUnsavedModal();
1453 pendingNavigate = null;
1454 navigateAfterSave = false;
1455 if (!next)
1456 { return; }
1457 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1458 if (nextDim !== selectedDimensionId)
1459 {
1460 selectedDimensionId = nextDim;
1461 syncDimensionUi();
1462 clearNeighborhoodView();
1463 }
1464 doLoadNeighborhood(next.chunkX, next.chunkY);
1465});
1466$("unsaved-chunk-save")?.addEventListener("click", () =>
1467{
1468 hideUnsavedModal();
1469 if (!pendingNavigate)
1470 { return; }
1471 navigateAfterSave = true;
1472 if (!saveSelectedChunk())
1473 {
1474 navigateAfterSave = false;
1475 const next = pendingNavigate;
1476 pendingNavigate = null;
1477 if (next)
1478 {
1479 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1480 if (nextDim !== selectedDimensionId)
1481 {
1482 selectedDimensionId = nextDim;
1483 syncDimensionUi();
1484 clearNeighborhoodView();
1485 }
1486 doLoadNeighborhood(next.chunkX, next.chunkY);
1487 }
1488 }
1489});
1490$("apply").addEventListener("click", () =>
1491{
1492 if (!pendingRevisionId || applyInFlight)
1493 { return; }
1494 $("error").textContent = "";
1495 const status = $("apply-status");
1496 status.textContent = "Applying…";
1497 status.className = "hint";
1498 applyInFlight = true;
1499 updateRevisionUI();
1500 socket.send({ type: MessageType.editorApplyRevision });
1501});
1502document.getElementById("editor-restart-now")?.addEventListener("click", () =>
1503{
1504 if (!socket)
1505 { return; }
1506 const ok = window.confirm(
1507 "Restart the server now?\n\nAll players and editor sessions will disconnect. "
1508 + "systemd will start a fresh process and pull the latest code from git."
1509 );
1510 if (!ok)
1511 { return; }
1512 const restartBtn = document.getElementById("editor-restart-now");
1513 if (restartBtn)
1514 { restartBtn.disabled = true; }
1515 $("who").textContent = "Restarting server…";
1516 $("error").textContent = "";
1517 socket.send({ type: MessageType.editorRestartNow });
1518});
1519$("night").addEventListener("input", () =>
1520{
1521 view.nightPreview = Number($("night").value);
1522 $("night-label").textContent = view.nightPreview.toFixed(1);
1523});
1524$("season").addEventListener("change", () =>
1525{
1526 applySeasonPreview($("season").value);
1527});
1528
1529function syncSeasonControls (season)
1530{
1531 const next = season === SeasonId.spring
1532 || season === SeasonId.fall
1533 || season === SeasonId.winter
1534 || season === SeasonId.summer
1535 ? season
1536 : seasonIdAt();
1537 $("season").value = next;
1538 view?.setWorldSeason(next);
1539}
1540
1541function applySeasonPreview (season)
1542{
1543 syncSeasonControls(season);
1544}
1545
1546function cycleToolState (direction)
1547{
1548 if (tool.kind === "erase" || tool.kind === "spawner")
1549 { return; }
1550 const layer = tool.kind === "ground" ? "ground" : "block";
1551 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
1552 if (definitionUsesNeighborConnect(def))
1553 { return; }
1554 if (tool.kind === "block" && def?.id === BlockType.flower)
1555 { return; }
1556 const allStates = statesForType(catalog, layer, def.key);
1557 const seasonal = seasonalCycleStates(allStates);
1558 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
1559 if (states.length < 2)
1560 { return; }
1561 tool.state = cycleState(states, tool.state, direction);
1562 $("tool").textContent = selectedToolLabel();
1563 const season = seasonIdFromVisualState(tool.state);
1564 if (season)
1565 { applySeasonPreview(season); }
1566 if (!draft || !hoverLocal)
1567 { return; }
1568 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
1569 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
1570 { paintAt(hoverLocal.x, hoverLocal.y); }
1571 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
1572 { paintAt(hoverLocal.x, hoverLocal.y); }
1573}
1574
1575document.addEventListener("wheel", (event) =>
1576{
1577 if (!scene?.canvas || anyModalOpen())
1578 { return; }
1579 const rect = scene.canvas.getBoundingClientRect();
1580 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1581 { return; }
1582 event.preventDefault();
1583 if (event.shiftKey)
1584 {
1585 cycleToolState(event.deltaY < 0 ? 1 : -1);
1586 if (hoverLocal)
1587 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
1588 return;
1589 }
1590 zoomEditor(event.deltaY < 0 ? 1 : -1);
1591}, { passive: false });
1592
1593document.addEventListener("contextmenu", (event) =>
1594{
1595 if (!scene?.canvas || anyModalOpen() || !draft)
1596 { return; }
1597 const rect = scene.canvas.getBoundingClientRect();
1598 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
1599 { return; }
1600 event.preventDefault();
1601 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
1602 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1603 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1604 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1605 { return; }
1606 const spawner = spawnerAt(localX, localY);
1607 if (spawner)
1608 {
1609 tileConfigModal.openSpawner({
1610 localX,
1611 localY,
1612 tileX: tile.tileX,
1613 tileY: tile.tileY,
1614 config: { ...spawner.config }
1615 });
1616 return;
1617 }
1618 const index = localY * CHUNK_SIZE + localX;
1619 const block = draft.blocks[index];
1620 if (block?.typeId === BlockType.doorway)
1621 {
1622 tileConfigModal.openDoorway({
1623 localX,
1624 localY,
1625 tileX: tile.tileX,
1626 tileY: tile.tileY,
1627 state: block.state ?? "door",
1628 config: block.config ? { ...block.config } : {}
1629 });
1630 return;
1631 }
1632 if (block?.typeId === BlockType.fishingSpot)
1633 {
1634 tileConfigModal.openFishingSpot({
1635 localX,
1636 localY,
1637 tileX: tile.tileX,
1638 tileY: tile.tileY,
1639 config: block.config ? { ...block.config } : { fishes: [] }
1640 });
1641 }
1642});
1643
1644main().catch((error) =>
1645{
1646 $("error").textContent = error.message;
1647 console.error(error);
1648});