BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

fix: discard chunk-editor drafts so they cannot overwrite another chunk
timfa project_85689633_bot_782f591ee30607a5698798444cb41267 · pushed by timfa · 2 months ago
dbb8218b History
main.js 71.9 KiB Download Raw
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, STATIC_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 isItemSpawnerConfig,
27 defaultItemSpawnerConfig,
28 normalizeItemSpawnerConfig,
29 itemSpawnerPreviewSpriteName,
30 itemSpawnerContainerSpriteName
31 } from "/shared/definitions/itemSpawners.js";
32import
33{
34 computeNeighborConnectMask,
35 composeNeighborConnectState,
36 definitionUsesNeighborConnect,
37 neighborConnectBlocksMatch,
38 neighborConnectRefreshTiles,
39 worldTileToChunkLocal
40} from "/shared/world/neighborConnect.js";
41import { GameSocket, defaultSocketUrl } from "../net/socket.js";
42import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
43import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
44import { WorldView } from "../render/worldView.js";
45import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
46import { initPaletteModal } from "./paletteModal.js";
47import { initTileConfigModal } from "./tileConfigModal.js";
48import { initQuestsModal } from "./questsModal.js";
49import { initDialoguesModal } from "./dialoguesModal.js";
50import { initGiftsModal } from "./giftsModal.js";
51import { initDimensionPickerModal } from "./dimensionPickerModal.js";
52import
53{
54 OVERWORLD_ID,
55 normalizeDimensionId,
56 isOverworld
57} from "/shared/world/dimensions.js";
58import { normalizeDoorConfig } from "/shared/world/doorRequirements.js";
59import
60{
61 editorChunkSaveKey,
62 editorDirtyChunk,
63 editorDraftOwner,
64 sameEditorChunk,
65 shouldApplySelectedEditorChunk
66} from "./saveAck.js";
67
68const game = new Game();
69let socket;
70let scene;
71let view;
72let draft = null;
73/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
74let draftBaseline = null;
75/**
76 * Chunk the current `draft` belongs to. Navigation may update `chunkX`/`chunkY`
77 * (viewed chunk) before save/discard; save must still write to this owner.
78 * @type {{ dimensionId: string, chunkX: number, chunkY: number }|null}
79 */
80let draftOwner = null;
81/** @type {ReturnType<typeof cloneDraftContents>|null} In-memory chunk clipboard for copy/paste. */
82let chunkClipboard = null;
83/**
84 * Neighbor chunks whose connect masks were updated while editing the selected chunk.
85 * Key `"chunkX,chunkY"` → `{ open, grounds, blocks, spawners }`.
86 * @type {Map<string, { open: boolean, grounds: object[], blocks: object[], spawners: object[] }>}
87 */
88let dirtyNeighborChunks = new Map();
89/** Spawners for loaded non-selected chunks (needed when saving edge-mask fixes). */
90let neighborSpawnersByChunk = new Map();
91/** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */
92let pendingNavigate = null;
93/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
94let navigateAfterSave = false;
95/** Keys (`dimensionId:chunkX,chunkY`) for in-flight `EDITOR_SAVE_CHUNK` acks. */
96const pendingSaveAcks = new Set();
97let chunkX = 0;
98let chunkY = 0;
99let selectedDimensionId = OVERWORLD_ID;
100/** @type {string|null} */
101let pendingCreatedDimensionId = null;
102/** @type {Map<string, object>} */
103let dimensionsById = new Map();
104let dimensionPicker = null;
105let dimensionSettings = null;
106let tool = { kind: "ground", typeId: GroundType.grass, state: null };
107let settingsModal;
108let paletteModal;
109let tileConfigModal;
110let questsModal;
111let dialoguesModal;
112let giftsModal;
113let catalog = { grounds: {}, blocks: {}, images: [] };
114let imageUrlByName = new Map();
115let hoverLocal = null;
116let editorZoom = null;
117let activeRevisionId = null;
118let pendingRevisionId = null;
119let applyInFlight = false;
120/** @type {string|null} */
121let sessionAuthSubject = null;
122/** True after the first successful SESSION message for this page load. */
123let sessionReady = false;
124/** Display label for #who while reconnecting. */
125let accountWhoLabel = "Editor";
126const EDITOR_DRAFT_STORAGE_PREFIX = "questward-editor-draft:";
127const EDITOR_ZOOM_MIN = 0.25;
128const EDITOR_ZOOM_MAX = 8;
129const EDITOR_ZOOM_STEP = 1.12;
130const CONSOLE_MAX_LINES = 2000;
131
132function $ (id)
133{
134 return document.getElementById(id);
135}
136
137function formatConsoleTime (t)
138{
139 try
140 { return new Date(t).toLocaleTimeString(); }
141 catch
142 { return ""; }
143}
144
145function appendConsoleLine (entry, { scroll = true } = {})
146{
147 const pre = $("editor-console");
148 if (!pre || !entry)
149 { return; }
150 const line = document.createElement("div");
151 const level = entry.level || "info";
152 line.className = `console-${level}`;
153 line.textContent = `[${formatConsoleTime(entry.t)}] ${entry.text ?? ""}`;
154 pre.append(line);
155 while (pre.childElementCount > CONSOLE_MAX_LINES)
156 { pre.firstChild?.remove(); }
157 if (scroll)
158 { pre.scrollTop = pre.scrollHeight; }
159}
160
161function applyConsoleSnapshot (lines)
162{
163 const pre = $("editor-console");
164 if (!pre)
165 { return; }
166 pre.replaceChildren();
167 for (const entry of lines ?? [])
168 { appendConsoleLine(entry, { scroll: false }); }
169 pre.scrollTop = pre.scrollHeight;
170}
171
172function initSidePanelTabs ()
173{
174 const tabs = document.querySelectorAll(".side-panel-tab");
175 const bodies = document.querySelectorAll("[data-side-panel-body]");
176 function activate (name)
177 {
178 for (const tab of tabs)
179 {
180 const on = tab.dataset.sidePanel === name;
181 tab.classList.toggle("active", on);
182 tab.setAttribute("aria-selected", on ? "true" : "false");
183 }
184 for (const body of bodies)
185 { body.hidden = body.dataset.sidePanelBody !== name; }
186 if (name === "console")
187 {
188 const pre = $("editor-console");
189 if (pre)
190 { pre.scrollTop = pre.scrollHeight; }
191 }
192 }
193 for (const tab of tabs)
194 {
195 tab.addEventListener("click", () => activate(tab.dataset.sidePanel));
196 }
197 $("console-clear")?.addEventListener("click", () =>
198 {
199 const pre = $("editor-console");
200 if (pre)
201 { pre.replaceChildren(); }
202 });
203 activate("changelog");
204}
205
206function selectedToolLabel ()
207{
208 if (tool.kind === "erase")
209 { return "Erase block"; }
210 if (tool.kind === "spawner")
211 {
212 if (tool.spawnerKind === "item" || isItemSpawnerConfig(tool))
213 { return "Spawner · Item Spawner"; }
214 const def = mobDefinition(tool.mobTypeId);
215 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
216 }
217 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
218 const layer = tool.kind === "ground" ? "ground" : "block";
219 const states = statesForType(catalog, layer, def.key);
220 const state = resolveState(states, tool.state);
221 if (tool.kind === "block" && def.id === BlockType.flower)
222 { return "Flower"; }
223 if (tool.kind === "block" && def.id === BlockType.boulder)
224 {
225 const entry = listPlaceableBlockPaletteEntries(catalog)
226 .find((row) => row.typeId === def.id && row.state === state);
227 if (entry)
228 { return entry.displayName; }
229 }
230 if (states.length > 1)
231 { return `${def.displayName} (${state})`; }
232 return def.displayName;
233}
234
235function selectTool (next)
236{
237 if (next.kind === "erase")
238 {
239 tool = { kind: "erase" };
240 return;
241 }
242 if (next.kind === "spawner")
243 {
244 if (next.spawnerKind === "item")
245 { tool = { kind: "spawner", spawnerKind: "item" }; }
246 else
247 { tool = { kind: "spawner", mobTypeId: next.mobTypeId }; }
248 return;
249 }
250 const layer = next.kind === "ground" ? "ground" : "block";
251 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
252 tool = {
253 kind: next.kind,
254 typeId: next.typeId,
255 state: next.state ?? defaultStateForType(catalog, layer, def.key)
256 };
257}
258
259function placeableToolState ()
260{
261 if (tool.kind === "erase" || tool.kind === "spawner")
262 { return null; }
263 const layer = tool.kind === "ground" ? "ground" : "block";
264 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
265 return resolveState(statesForType(catalog, layer, def.key), tool.state);
266}
267
268function previewFromTool ()
269{
270 if (tool.kind === "erase")
271 { return { block: null }; }
272 if (tool.kind === "spawner")
273 { return {}; }
274 const state = placeableToolState();
275 if (tool.kind === "ground")
276 { return { ground: { typeId: tool.typeId, state } }; }
277 return { block: { typeId: tool.typeId, state, config: null } };
278}
279
280/** Editor map neighborhood (Chebyshev); 2 → 5×5 chunks around the selection. */
281const EDITOR_VIEW_CHUNK_RADIUS = STATIC_CHUNK_RADIUS;
282
283function inEditorView (x, y)
284{
285 return Math.abs(x - chunkX) <= EDITOR_VIEW_CHUNK_RADIUS && Math.abs(y - chunkY) <= EDITOR_VIEW_CHUNK_RADIUS;
286}
287
288function neighborhoodCoords (centerX, centerY)
289{
290 const coords = [];
291 for (let dy = -EDITOR_VIEW_CHUNK_RADIUS; dy <= EDITOR_VIEW_CHUNK_RADIUS; dy++)
292 {
293 for (let dx = -EDITOR_VIEW_CHUNK_RADIUS; dx <= EDITOR_VIEW_CHUNK_RADIUS; dx++)
294 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
295 }
296 return coords;
297}
298
299function snapshotFromPayload (payload)
300{
301 return {
302 chunkX: payload.chunkX,
303 chunkY: payload.chunkY,
304 open: payload.data.open,
305 closedEdges: payload.closedEdges,
306 grounds: payload.data.grounds,
307 blocks: payload.data.blocks,
308 light: payload.data.light,
309 enclosed: payload.data.enclosed,
310 entities: []
311 };
312}
313
314function syncSpawnersOverlay (cx, cy, spawners)
315{
316 view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
317}
318
319function spawnerAt (localX, localY)
320{
321 return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
322}
323
324function draftPersistable ()
325{
326 if (!draft)
327 { return null; }
328 return {
329 open: !!draft.open,
330 grounds: draft.grounds,
331 blocks: draft.blocks,
332 spawners: draft.spawners ?? []
333 };
334}
335
336function isSelectedChunkDirty ()
337{
338 if (!draft || draftBaseline == null)
339 { return false; }
340 return JSON.stringify(draftPersistable()) !== draftBaseline;
341}
342
343function draftStorageKey (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId, subject = sessionAuthSubject)
344{
345 const who = subject ?? "anon";
346 return `${EDITOR_DRAFT_STORAGE_PREFIX}${who}:${normalizeDimensionId(dimensionId)}:${cx},${cy}`;
347}
348
349function viewedChunkOwner ()
350{
351 return editorDraftOwner(selectedDimensionId, chunkX, chunkY);
352}
353
354function persistDirtyDraftBackup ()
355{
356 if (!draft || !isSelectedChunkDirty())
357 { return; }
358 const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
359 try
360 {
361 const payload = {
362 savedAt: Date.now(),
363 dimensionId: owner.dimensionId,
364 chunkX: owner.chunkX,
365 chunkY: owner.chunkY,
366 authSubject: sessionAuthSubject,
367 open: !!draft.open,
368 grounds: draft.grounds,
369 blocks: draft.blocks,
370 spawners: draft.spawners ?? [],
371 light: draft.light,
372 enclosed: draft.enclosed,
373 baseline: draftBaseline
374 };
375 sessionStorage.setItem(
376 draftStorageKey(owner.chunkX, owner.chunkY, owner.dimensionId),
377 JSON.stringify(payload)
378 );
379 }
380 catch
381 { /* quota / private mode */ }
382}
383
384function clearDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)
385{
386 try
387 { sessionStorage.removeItem(draftStorageKey(cx, cy, dimensionId)); }
388 catch
389 { /* ignore */ }
390}
391
392function readDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)
393{
394 try
395 {
396 const raw = sessionStorage.getItem(draftStorageKey(cx, cy, dimensionId));
397 if (!raw)
398 { return null; }
399 const parsed = JSON.parse(raw);
400 if (!parsed || !Array.isArray(parsed.grounds) || !Array.isArray(parsed.blocks))
401 { return null; }
402 return parsed;
403 }
404 catch
405 { return null; }
406}
407
408function applyRestoredDraftBackup (backup)
409{
410 if (!backup || !draft)
411 { return false; }
412 draft.open = !!backup.open;
413 draft.grounds = backup.grounds.map((ground) => normalizeGround(ground));
414 draft.blocks = backup.blocks.map((block) => (block
415 ? { ...block, config: block.config ?? null }
416 : null));
417 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
418 draft.light = Array.isArray(backup.light) && backup.light.length === tileCount
419 ? backup.light.slice()
420 : (draft.light ?? new Array(tileCount).fill(0));
421 draft.enclosed = Array.isArray(backup.enclosed) && backup.enclosed.length === tileCount
422 ? backup.enclosed.slice().map((v) => (v ? 1 : 0))
423 : (draft.enclosed ?? new Array(tileCount).fill(0));
424 draft.spawners = (backup.spawners ?? []).map((entry) => ({
425 localX: entry.localX | 0,
426 localY: entry.localY | 0,
427 config: { ...(entry.config ?? {}) }
428 }));
429 if (typeof backup.baseline === "string")
430 { draftBaseline = backup.baseline; }
431 $("open").checked = draft.open;
432 const existing = view?.chunks.get(chunkKey(chunkX, chunkY));
433 view.applySnapshot({
434 chunkX,
435 chunkY,
436 open: draft.open,
437 closedEdges: existing?.closedEdges,
438 grounds: draft.grounds,
439 blocks: draft.blocks,
440 light: draft.light,
441 enclosed: draft.enclosed,
442 entities: []
443 });
444 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
445 syncSaveButton();
446 return true;
447}
448
449function tryRestoreDraftBackupAfterServerLoad (payload)
450{
451 const dim = normalizeDimensionId(payload.dimensionId ?? selectedDimensionId);
452 const backup = readDraftBackup(payload.chunkX, payload.chunkY, dim);
453 if (!backup)
454 { return false; }
455 const serverPersistable = {
456 open: !!payload.data.open,
457 grounds: payload.data.grounds,
458 blocks: payload.data.blocks,
459 spawners: payload.data.spawners ?? []
460 };
461 const backupPersistable = {
462 open: !!backup.open,
463 grounds: backup.grounds,
464 blocks: backup.blocks,
465 spawners: backup.spawners ?? []
466 };
467 if (JSON.stringify(serverPersistable) === JSON.stringify(backupPersistable))
468 {
469 clearDraftBackup(payload.chunkX, payload.chunkY, dim);
470 return false;
471 }
472 // Treat server payload as the clean baseline so the restored paint stays dirty.
473 draftBaseline = JSON.stringify(serverPersistable);
474 return applyRestoredDraftBackup(backup);
475}
476
477function cloneDraftContents (source)
478{
479 if (!source)
480 { return null; }
481 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
482 return {
483 open: !!source.open,
484 grounds: (source.grounds ?? []).map((ground) => normalizeGround(ground)),
485 blocks: (source.blocks ?? []).map((block) => (block
486 ? {
487 ...block,
488 config: block.config != null ? structuredClone(block.config) : null
489 }
490 : null)),
491 light: Array.isArray(source.light) && source.light.length === tileCount
492 ? source.light.slice()
493 : new Array(tileCount).fill(0),
494 spawners: (source.spawners ?? []).map((entry) => ({
495 localX: entry.localX | 0,
496 localY: entry.localY | 0,
497 config: structuredClone(entry.config ?? {})
498 }))
499 };
500}
501
502function blankChunkContents ()
503{
504 const groundTypeId = dimensionsById.get(selectedDimensionId)?.defaultGroundTypeId
505 ?? GroundType.grass;
506 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
507 return {
508 open: false,
509 grounds: new Array(tileCount).fill(null).map(() => normalizeGround(groundTypeId, groundTypeId)),
510 blocks: new Array(tileCount).fill(null),
511 light: new Array(tileCount).fill(0),
512 spawners: []
513 };
514}
515
516function applyDraftContents (next)
517{
518 if (!draft || !next || isSelectedDimensionSoftDeleted())
519 { return; }
520 clearNeighborEditState();
521 draft.open = !!next.open;
522 draft.grounds = next.grounds.map((ground) => normalizeGround(ground));
523 draft.blocks = next.blocks.map((block) => (block
524 ? { ...block, config: block.config ?? null }
525 : null));
526 draft.light = Array.isArray(next.light) ? next.light.slice() : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
527 draft.enclosed = Array.isArray(next.enclosed)
528 ? next.enclosed.slice().map((v) => (v ? 1 : 0))
529 : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
530 draft.spawners = (next.spawners ?? []).map((entry) => ({
531 localX: entry.localX | 0,
532 localY: entry.localY | 0,
533 config: { ...(entry.config ?? {}) }
534 }));
535 $("open").checked = draft.open;
536 const existing = view?.chunks.get(chunkKey(chunkX, chunkY));
537 view.applySnapshot({
538 chunkX,
539 chunkY,
540 open: draft.open,
541 closedEdges: existing?.closedEdges,
542 grounds: draft.grounds,
543 blocks: draft.blocks,
544 light: draft.light,
545 enclosed: draft.enclosed,
546 entities: []
547 });
548 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
549 afterDraftMutation();
550}
551
552function syncChunkClipboardButtons ()
553{
554 const softDeleted = isSelectedDimensionSoftDeleted();
555 const copyBtn = $("copy-chunk");
556 const pasteBtn = $("paste-chunk");
557 const clearBtn = $("clear-chunk");
558 if (copyBtn)
559 {
560 copyBtn.disabled = !draft || softDeleted;
561 copyBtn.title = softDeleted
562 ? "Cannot copy while this dimension is soft-deleted"
563 : "Copy this chunk into the editor clipboard";
564 }
565 if (pasteBtn)
566 {
567 const canPaste = !!draft && !!chunkClipboard && !softDeleted;
568 pasteBtn.disabled = !canPaste;
569 pasteBtn.title = softDeleted
570 ? "Cannot paste while this dimension is soft-deleted"
571 : chunkClipboard
572 ? "Paste the copied chunk over the current draft (does not save)"
573 : "Copy a chunk first";
574 }
575 if (clearBtn)
576 {
577 clearBtn.disabled = !draft || softDeleted;
578 clearBtn.title = softDeleted
579 ? "Cannot clear while this dimension is soft-deleted"
580 : "Erase this chunk to a blank slate (does not save)";
581 }
582}
583
584function copySelectedChunk ()
585{
586 if (!draft || isSelectedDimensionSoftDeleted())
587 { return; }
588 chunkClipboard = cloneDraftContents(draft);
589 syncChunkClipboardButtons();
590}
591
592function pasteSelectedChunk ()
593{
594 if (!draft || !chunkClipboard || isSelectedDimensionSoftDeleted())
595 { return; }
596 const ok = window.confirm(
597 "This will replace your current chunk entirely with your copied chunk. Are you sure?"
598 );
599 if (!ok)
600 { return; }
601 applyDraftContents(cloneDraftContents(chunkClipboard));
602}
603
604function clearSelectedChunk ()
605{
606 if (!draft || isSelectedDimensionSoftDeleted())
607 { return; }
608 const ok = window.confirm(
609 "this will erase the chunk and reset it to a default blank slate. Are you certain?"
610 );
611 if (!ok)
612 { return; }
613 applyDraftContents(blankChunkContents());
614}
615
616function captureDraftBaseline ()
617{
618 const payload = draftPersistable();
619 draftBaseline = payload ? JSON.stringify(payload) : null;
620 const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
621 clearDraftBackup(owner.chunkX, owner.chunkY, owner.dimensionId);
622 syncSaveButton();
623}
624
625function discardUnsavedDraft ()
626{
627 const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
628 clearDraftBackup(owner.chunkX, owner.chunkY, owner.dimensionId);
629 clearNeighborEditState();
630 draft = null;
631 draftBaseline = null;
632 draftOwner = null;
633 syncSaveButton();
634}
635
636function chunkKey (cx, cy)
637{
638 return `${cx},${cy}`;
639}
640
641function isDraftDirty ()
642{
643 if (dirtyNeighborChunks.size > 0)
644 { return true; }
645 return isSelectedChunkDirty();
646}
647
648function syncSaveButton ()
649{
650 const btn = $("save");
651 if (!btn)
652 { return; }
653 const softDeleted = isSelectedDimensionSoftDeleted();
654 const dirty = isDraftDirty();
655 btn.disabled = !dirty || softDeleted;
656 btn.classList.toggle("save-dirty", dirty && !softDeleted);
657 btn.title = softDeleted
658 ? "Cannot save while this dimension is soft-deleted"
659 : dirty
660 ? "Save unsaved chunk changes"
661 : "No unsaved changes";
662 syncChunkClipboardButtons();
663}
664
665function afterDraftMutation ()
666{
667 syncSaveButton();
668 const owner = editorDirtyChunk(draftOwner, viewedChunkOwner());
669 if (isSelectedChunkDirty())
670 { persistDirtyDraftBackup(); }
671 else
672 { clearDraftBackup(owner.chunkX, owner.chunkY, owner.dimensionId); }
673}
674
675function clearNeighborEditState ()
676{
677 dirtyNeighborChunks.clear();
678}
679
680function groundAtWorld (tileX, tileY)
681{
682 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
683 const index = localY * CHUNK_SIZE + localX;
684 if (cx === chunkX && cy === chunkY && draft)
685 { return draft.grounds[index] ?? null; }
686 const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
687 if (dirty)
688 { return dirty.grounds[index] ?? null; }
689 const snapshot = view?.chunks.get(chunkKey(cx, cy));
690 return snapshot?.grounds?.[index] ?? null;
691}
692
693function spawnerAtWorld (tileX, tileY)
694{
695 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
696 if (cx === chunkX && cy === chunkY && draft)
697 { return spawnerAt(localX, localY); }
698 const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
699 if (dirty)
700 { return dirty.spawners?.find((entry) => entry.localX === localX && entry.localY === localY) ?? null; }
701 return (neighborSpawnersByChunk.get(chunkKey(cx, cy)) ?? [])
702 .find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
703}
704
705/** Human-readable summary of authored ground/block/spawner on a world tile. */
706function describeWorldTile (tileX, tileY, dimensionId = selectedDimensionId)
707{
708 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
709 if (dim !== selectedDimensionId)
710 {
711 return `Currently editing “${selectedDimensionId}”; switch to “${dim}” to inspect this tile.`;
712 }
713 const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
714 const key = chunkKey(cx, cy);
715 const loaded = (cx === chunkX && cy === chunkY && draft)
716 || dirtyNeighborChunks.has(key)
717 || view?.chunks?.has(key);
718 if (!loaded)
719 { return `Chunk (${cx}, ${cy}) not loaded — center on this tile to load it.`; }
720
721 const lines = [];
722 const ground = normalizeGround(groundAtWorld(tileX, tileY));
723 const groundDef = GROUND_DEFINITIONS[ground?.typeId];
724 lines.push(`Ground: ${groundDef?.displayName ?? `type ${ground?.typeId ?? "?"}`}`);
725 const block = normalizeBlock(blockAtWorld(tileX, tileY));
726 if (block)
727 {
728 const blockDef = BLOCK_DEFINITIONS[block.typeId];
729 lines.push(`Block: ${blockDef?.displayName ?? `type ${block.typeId}`}${block.state ? ` (${block.state})` : ""}`);
730 if (block.config && Object.keys(block.config).length)
731 {
732 for (const [keyName, value] of Object.entries(block.config))
733 { lines.push(` ${keyName}: ${value}`); }
734 }
735 }
736 else
737 { lines.push("Block: (none)"); }
738 const spawner = spawnerAtWorld(tileX, tileY);
739 if (spawner)
740 {
741 const config = normalizeSpawnerConfig(spawner.config, spawner.config?.spawnerId);
742 if (isItemSpawnerConfig(config))
743 { lines.push(`Spawner: Item Spawner (${config.spawnerId})`); }
744 else
745 {
746 const mob = mobDefinition(config.mobTypeId);
747 lines.push(`Spawner: ${mob?.displayName ?? config.mobTypeId} (${config.spawnerId})`);
748 }
749 }
750 else
751 { lines.push("Spawner: (none)"); }
752 return lines.join("\n");
753}
754
755/** Pan the editor to a world tile without closing other UI; loads its chunk neighborhood. */
756function centerEditorOnTile (tileX, tileY, dimensionId = selectedDimensionId)
757{
758 const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
759 const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX | 0, tileY | 0, CHUNK_SIZE);
760 if (dim !== selectedDimensionId)
761 {
762 if (isDraftDirty())
763 {
764 showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: dim });
765 return false;
766 }
767 selectedDimensionId = dim;
768 syncDimensionUi();
769 clearNeighborhoodView();
770 doLoadNeighborhood(cx, cy);
771 }
772 else if (cx !== chunkX || cy !== chunkY)
773 {
774 if (isDraftDirty())
775 {
776 showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: selectedDimensionId });
777 return false;
778 }
779 doLoadNeighborhood(cx, cy);
780 }
781 if (!view?.scene)
782 { return true; }
783 const size = view.tileSize();
784 view.followPlayer = false;
785 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - ((tileX | 0) + 0.5) * size;
786 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - ((tileY | 0) + 0.5) * size;
787 view.refreshViewport();
788 updateSelectionBorder();
789 return true;
790}
791
792function blockAtWorld (tileX, tileY)
793{
794 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
795 if (cx === chunkX && cy === chunkY && draft)
796 { return draft.blocks[localY * CHUNK_SIZE + localX] ?? null; }
797 const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
798 if (dirty)
799 { return dirty.blocks[localY * CHUNK_SIZE + localX] ?? null; }
800 const snapshot = view?.chunks.get(chunkKey(cx, cy));
801 return snapshot?.blocks?.[localY * CHUNK_SIZE + localX] ?? null;
802}
803
804function ensureDirtyNeighborChunk (cx, cy)
805{
806 const key = chunkKey(cx, cy);
807 let data = dirtyNeighborChunks.get(key);
808 if (data)
809 { return data; }
810 const snapshot = view?.chunks.get(key);
811 if (!snapshot)
812 { return null; }
813 data = {
814 open: !!snapshot.open,
815 grounds: (snapshot.grounds ?? []).map((ground) => normalizeGround(ground)),
816 blocks: (snapshot.blocks ?? []).map((block) => (block ? { ...block, config: block.config ?? null } : null)),
817 spawners: structuredClone(neighborSpawnersByChunk.get(key) ?? [])
818 };
819 dirtyNeighborChunks.set(key, data);
820 return data;
821}
822
823function writeBlockAtWorld (tileX, tileY, block)
824{
825 const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
826 const index = localY * CHUNK_SIZE + localX;
827 if (cx === chunkX && cy === chunkY && draft)
828 {
829 draft.blocks[index] = block;
830 view.updateAuthoredTile(cx, cy, localX, localY, {
831 ground: draft.grounds[index],
832 block: draft.blocks[index],
833 light: draft.light[index]
834 });
835 return true;
836 }
837 const data = ensureDirtyNeighborChunk(cx, cy);
838 if (!data)
839 { return false; }
840 data.blocks[index] = block;
841 const snapshot = view?.chunks.get(chunkKey(cx, cy));
842 const light = snapshot?.light?.[index];
843 view.updateAuthoredTile(cx, cy, localX, localY, {
844 ground: data.grounds[index],
845 block: data.blocks[index],
846 light
847 });
848 return true;
849}
850
851function showUnsavedModal (target)
852{
853 pendingNavigate = target;
854 $("unsaved-chunk-backdrop").hidden = false;
855 $("unsaved-chunk-modal").hidden = false;
856}
857
858function hideUnsavedModal ()
859{
860 $("unsaved-chunk-backdrop").hidden = true;
861 $("unsaved-chunk-modal").hidden = true;
862}
863
864function saveSelectedChunk ()
865{
866 if (!draft || !isDraftDirty())
867 { return false; }
868 if (isSelectedDimensionSoftDeleted())
869 {
870 $("error").textContent = "Cannot save while this dimension is soft-deleted.";
871 return false;
872 }
873 $("error").textContent = "";
874 $("apply-status").textContent = "";
875 $("apply-status").className = "hint";
876 const target = editorDirtyChunk(draftOwner, viewedChunkOwner());
877 const neighborSaves = [...dirtyNeighborChunks.entries()];
878 clearNeighborEditState();
879 const savedChunks = [{ chunkX: target.chunkX, chunkY: target.chunkY }];
880 pendingSaveAcks.add(editorChunkSaveKey(target.dimensionId, target.chunkX, target.chunkY));
881 socket.send({
882 type: MessageType.editorSaveChunk,
883 chunkX: target.chunkX,
884 chunkY: target.chunkY,
885 dimensionId: target.dimensionId,
886 draft: {
887 open: $("open").checked,
888 grounds: draft.grounds,
889 blocks: draft.blocks,
890 spawners: draft.spawners ?? []
891 }
892 });
893 for (const [key, data] of neighborSaves)
894 {
895 const [cx, cy] = key.split(",").map(Number);
896 savedChunks.push({ chunkX: cx, chunkY: cy });
897 pendingSaveAcks.add(editorChunkSaveKey(target.dimensionId, cx, cy));
898 socket.send({
899 type: MessageType.editorSaveChunk,
900 chunkX: cx,
901 chunkY: cy,
902 dimensionId: target.dimensionId,
903 draft: {
904 open: data.open,
905 grounds: data.grounds,
906 blocks: data.blocks,
907 spawners: data.spawners ?? []
908 }
909 });
910 }
911 view?.bakeNatureTintForChunks?.(savedChunks);
912 requestNeighbors();
913 return true;
914}
915
916function isSelectedDimensionSoftDeleted ()
917{
918 const record = dimensionsById.get(selectedDimensionId);
919 return record?.deletedAt != null;
920}
921
922function formatPurgeHint (record)
923{
924 if (!record?.purgeAfter)
925 { return "Soft-deleted — painting disabled."; }
926 const when = new Date(record.purgeAfter);
927 return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`;
928}
929
930function syncDimensionUi ()
931{
932 const record = dimensionsById.get(selectedDimensionId);
933 const softDeleted = record?.deletedAt != null;
934 const hint = $("dimension-purge-hint");
935 if (hint)
936 {
937 hint.hidden = !softDeleted;
938 hint.textContent = softDeleted ? formatPurgeHint(record) : "";
939 }
940 const openToggle = $("open");
941 if (openToggle)
942 { openToggle.disabled = softDeleted; }
943 dimensionPicker?.setValue(selectedDimensionId);
944 dimensionSettings?.refresh();
945 syncSaveButton();
946}
947
948function applyDimensionsList (payload)
949{
950 const list = Array.isArray(payload?.dimensions) ? payload.dimensions : [];
951 dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim]));
952 if (!dimensionsById.has(OVERWORLD_ID))
953 {
954 dimensionsById.set(OVERWORLD_ID, {
955 dimensionId: OVERWORLD_ID,
956 displayName: "Overworld",
957 lightingMode: "dayNight",
958 seasonMode: "auto",
959 defaultGroundTypeId: 1,
960 deletedAt: null,
961 purgeAfter: null
962 });
963 }
964 const options = [...dimensionsById.values()].map((dim) => ({
965 id: dim.dimensionId,
966 label: dim.displayName || dim.dimensionId,
967 disabled: dim.deletedAt != null,
968 hint: dim.deletedAt != null ? formatPurgeHint(dim) : null
969 }));
970 dimensionPicker?.setOptions(options);
971 const createdId = pendingCreatedDimensionId;
972 pendingCreatedDimensionId = null;
973 if (createdId && dimensionsById.has(createdId))
974 {
975 setRevisionState({
976 activeRevisionId: payload.activeRevisionId,
977 pendingRevisionId: payload.pendingRevisionId
978 });
979 selectDimension(createdId, { force: true });
980 return;
981 }
982 if (!dimensionsById.has(selectedDimensionId))
983 { selectedDimensionId = OVERWORLD_ID; }
984 setRevisionState({
985 activeRevisionId: payload.activeRevisionId,
986 pendingRevisionId: payload.pendingRevisionId
987 });
988 syncDimensionUi();
989 if (!isDraftDirty())
990 { requestChunks(neighborhoodCoords(chunkX, chunkY)); }
991}
992
993function requestDimensions ()
994{
995 socket.send({ type: MessageType.editorListDimensions });
996}
997
998function selectDimension (dimensionId, { force = false } = {})
999{
1000 const nextId = normalizeDimensionId(dimensionId);
1001 if (!force && nextId === selectedDimensionId)
1002 { return; }
1003 if (!force && isDraftDirty())
1004 {
1005 showUnsavedModal({ chunkX, chunkY, dimensionId: nextId });
1006 dimensionPicker?.setValue(selectedDimensionId);
1007 return;
1008 }
1009 selectedDimensionId = nextId;
1010 syncDimensionUi();
1011 clearNeighborhoodView();
1012 doLoadNeighborhood(chunkX, chunkY);
1013}
1014
1015function clearNeighborhoodView ()
1016{
1017 draft = null;
1018 draftBaseline = null;
1019 draftOwner = null;
1020 clearNeighborEditState();
1021 neighborSpawnersByChunk.clear();
1022 if (!view)
1023 { return; }
1024 for (const key of [...view.chunks.keys()])
1025 {
1026 const [x, y] = key.split(",").map(Number);
1027 view.removeChunk(x, y);
1028 }
1029 view.clearEditorSpawners?.();
1030 syncSaveButton();
1031}
1032
1033function paintAt (localX, localY)
1034{
1035 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1036 { return; }
1037 if (isSelectedDimensionSoftDeleted())
1038 { return; }
1039 const index = localY * CHUNK_SIZE + localX;
1040 const state = placeableToolState();
1041 if (tool.kind === "ground")
1042 { draft.grounds[index] = { typeId: tool.typeId, state }; }
1043 else if (tool.kind === "erase")
1044 {
1045 const removed = draft.blocks[index];
1046 draft.blocks[index] = null;
1047 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
1048 ground: draft.grounds[index],
1049 block: draft.blocks[index],
1050 light: draft.light[index]
1051 });
1052 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
1053 { refreshNeighborConnect(localX, localY, removed.typeId); }
1054 afterDraftMutation();
1055 return;
1056 }
1057 else if (tool.kind === "spawner")
1058 {
1059 const existing = spawnerAt(localX, localY);
1060 const spawnerId = existing?.config?.spawnerId
1061 ?? `${normalizeDimensionId(selectedDimensionId)}:${chunkX}:${chunkY}:${index}`;
1062 const config = tool.spawnerKind === "item"
1063 ? normalizeItemSpawnerConfig({
1064 ...defaultItemSpawnerConfig(spawnerId),
1065 ...(isItemSpawnerConfig(existing?.config) ? existing.config : {}),
1066 spawnerId
1067 }, spawnerId)
1068 : normalizeSpawnerConfig({
1069 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
1070 ...(existing?.config && !isItemSpawnerConfig(existing.config) ? existing.config : {}),
1071 spawnerId,
1072 mobTypeId: tool.mobTypeId
1073 }, spawnerId);
1074 const entry = { localX, localY, config };
1075 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
1076 draft.spawners.push(entry);
1077 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1078 afterDraftMutation();
1079 return;
1080 }
1081 else
1082 {
1083 const def = BLOCK_DEFINITIONS[tool.typeId];
1084 if (def?.id === BlockType.fishingSpot)
1085 {
1086 const groundType = draft.grounds[index]?.typeId;
1087 if (groundType !== GroundType.water && groundType !== GroundType.deepWater)
1088 { return; }
1089 }
1090 let nextState = definitionUsesNeighborConnect(def)
1091 ? composeNeighborConnectState(def, state, 0)
1092 : state;
1093 if (def?.id === BlockType.flower)
1094 { nextState = flowerBlockState(randomFlowerColorId()); }
1095 if (def?.id === BlockType.fishingSpot && !nextState)
1096 { nextState = "fishing-spot"; }
1097 const config = def?.id === BlockType.doorway
1098 ? {
1099 targetDimensionId: selectedDimensionId,
1100 tileX: chunkX * CHUNK_SIZE + localX,
1101 tileY: chunkY * CHUNK_SIZE + localY
1102 }
1103 : (def?.id === BlockType.fishingSpot
1104 ? { fishes: [] }
1105 : null);
1106 if (def?.id === BlockType.doorway && !nextState)
1107 { nextState = "door"; }
1108 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
1109 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
1110 ground: draft.grounds[index],
1111 block: draft.blocks[index],
1112 light: draft.light[index]
1113 });
1114 if (definitionUsesNeighborConnect(def))
1115 { refreshNeighborConnect(localX, localY, tool.typeId); }
1116 afterDraftMutation();
1117 return;
1118 }
1119 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
1120 ground: draft.grounds[index],
1121 block: draft.blocks[index],
1122 light: draft.light[index]
1123 });
1124 afterDraftMutation();
1125}
1126
1127/** Recompute neighbor-connect masks around a local tile, including across chunk edges. */
1128function refreshNeighborConnect (localX, localY, typeId)
1129{
1130 const def = BLOCK_DEFINITIONS[typeId];
1131 if (!draft || !definitionUsesNeighborConnect(def))
1132 { return; }
1133 const originTileX = chunkX * CHUNK_SIZE + localX;
1134 const originTileY = chunkY * CHUNK_SIZE + localY;
1135 for (const [tileX, tileY] of neighborConnectRefreshTiles(originTileX, originTileY))
1136 {
1137 const block = blockAtWorld(tileX, tileY);
1138 if (!block || block.typeId !== typeId)
1139 { continue; }
1140 const mask = computeNeighborConnectMask((dx, dy) =>
1141 {
1142 const neighbor = blockAtWorld(tileX + dx, tileY + dy);
1143 return neighborConnectBlocksMatch(block, neighbor, def);
1144 });
1145 const nextState = composeNeighborConnectState(def, block.state, mask);
1146 if (block.state === nextState)
1147 { continue; }
1148 writeBlockAtWorld(tileX, tileY, { ...block, state: nextState });
1149 }
1150}
1151
1152function updateRevisionUI ()
1153{
1154 const applyBtn = $("apply");
1155 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
1156 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
1157 if (applyBtn)
1158 {
1159 applyBtn.disabled = !pendingRevisionId || applyInFlight;
1160 applyBtn.title = pendingRevisionId
1161 ? "Reload the live world with the pending map revision"
1162 : "Save a chunk first to create a pending revision";
1163 }
1164}
1165
1166function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
1167{
1168 if (active != null)
1169 { activeRevisionId = active; }
1170 pendingRevisionId = pending ?? null;
1171 updateRevisionUI();
1172}
1173
1174function showSelectedChunk (payload, { isSaveAck = false } = {})
1175{
1176 const incoming = editorDraftOwner(
1177 payload.dimensionId ?? selectedDimensionId,
1178 payload.chunkX,
1179 payload.chunkY
1180 );
1181 const keepDirtyDraft = !shouldApplySelectedEditorChunk({
1182 isSaveAck,
1183 isDirty: !!draft && isSelectedChunkDirty(),
1184 incoming,
1185 draftOwner
1186 });
1187 if (!keepDirtyDraft)
1188 {
1189 if (draftOwner && !sameEditorChunk(incoming, draftOwner))
1190 { clearDraftBackup(draftOwner.chunkX, draftOwner.chunkY, draftOwner.dimensionId); }
1191 clearNeighborEditState();
1192 }
1193 if (keepDirtyDraft)
1194 {
1195 setRevisionState({
1196 activeRevisionId: payload.activeRevisionId,
1197 pendingRevisionId: payload.pendingRevisionId
1198 });
1199 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
1200 syncSaveButton();
1201 return;
1202 }
1203 draft = {
1204 open: payload.data.open,
1205 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
1206 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
1207 light: payload.data.light.slice(),
1208 enclosed: Array.isArray(payload.data.enclosed)
1209 ? payload.data.enclosed.slice().map((v) => (v ? 1 : 0))
1210 : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0),
1211 spawners: (payload.data.spawners ?? []).map((entry) => ({
1212 localX: entry.localX,
1213 localY: entry.localY,
1214 config: { ...entry.config }
1215 }))
1216 };
1217 draftOwner = incoming;
1218 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
1219 $("open").checked = draft.open;
1220 setRevisionState({
1221 activeRevisionId: payload.activeRevisionId,
1222 pendingRevisionId: payload.pendingRevisionId
1223 });
1224 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
1225 const log = $("changelog");
1226 log.innerHTML = "";
1227 for (const entry of payload.changelog ?? [])
1228 {
1229 const item = document.createElement("article");
1230 item.innerHTML = `<header>${entry.editorDisplayName || entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
1231 const list = document.createElement("ul");
1232 for (const bullet of entry.diffEntries)
1233 {
1234 const li = document.createElement("li");
1235 li.textContent = bullet;
1236 list.append(li);
1237 }
1238 item.append(list);
1239 log.append(item);
1240 }
1241 view.applySnapshot(snapshotFromPayload(payload));
1242 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
1243 const restored = isSaveAck ? false : tryRestoreDraftBackupAfterServerLoad(payload);
1244 if (!restored)
1245 { captureDraftBaseline(); }
1246 else
1247 { syncSaveButton(); }
1248 if (navigateAfterSave && pendingNavigate)
1249 {
1250 const next = pendingNavigate;
1251 navigateAfterSave = false;
1252 pendingNavigate = null;
1253 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1254 if (nextDim !== selectedDimensionId)
1255 {
1256 selectedDimensionId = nextDim;
1257 syncDimensionUi();
1258 clearNeighborhoodView();
1259 }
1260 doLoadNeighborhood(next.chunkX, next.chunkY);
1261 }
1262}
1263
1264function pruneView ()
1265{
1266 for (const key of [...view.chunks.keys()])
1267 {
1268 const [x, y] = key.split(",").map(Number);
1269 if (!inEditorView(x, y))
1270 {
1271 view.removeChunk(x, y);
1272 neighborSpawnersByChunk.delete(key);
1273 dirtyNeighborChunks.delete(key);
1274 }
1275 }
1276}
1277
1278function frameNeighborhood ()
1279{
1280 const size = view.tileSize();
1281 view.followPlayer = false;
1282 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
1283 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
1284 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
1285 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
1286 view.refreshViewport();
1287 updateSelectionBorder();
1288}
1289
1290function updateSelectionBorder ()
1291{
1292 const border = $("selection-border");
1293 const canvas = scene?.canvas;
1294 if (!border || !canvas)
1295 { return; }
1296
1297 const rect = canvas.getBoundingClientRect();
1298 const size = view.tileSize();
1299 const chunkPx = CHUNK_SIZE * size;
1300 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
1301 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
1302 border.style.left = `${rect.left + screenLeft}px`;
1303 border.style.top = `${rect.top + screenTop}px`;
1304 border.style.width = `${chunkPx}px`;
1305 border.style.height = `${chunkPx}px`;
1306}
1307
1308function layoutScene ()
1309{
1310 const header = document.querySelector("body > header");
1311 const aside = document.querySelector("body > aside");
1312 const sidePanels = $("side-panels") || $("changelog-wrap");
1313 const top = header.offsetHeight;
1314 aside.style.top = `${top}px`;
1315 sidePanels.style.top = `${top}px`;
1316 const left = aside.offsetWidth;
1317 const right = sidePanels.offsetWidth;
1318 const width = Math.max(64, window.innerWidth - left - right);
1319 const height = Math.max(64, window.innerHeight - top);
1320 scene.position.x = left;
1321 scene.position.y = top;
1322 scene.size.x = width;
1323 scene.size.y = height;
1324 scene.g_fixSize();
1325 useNearestNeighbour(scene, game.images);
1326 const fit = Math.min(width, height) / (CHUNK_SIZE * (EDITOR_VIEW_CHUNK_RADIUS * 2 + 1) * SPRITE_SIZE_PX);
1327 if (editorZoom == null)
1328 { editorZoom = fit; }
1329 else
1330 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
1331 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
1332 frameNeighborhood();
1333}
1334
1335function zoomEditor (direction)
1336{
1337 if (!view)
1338 { return; }
1339 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
1340 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
1341 scheduleEditorZoom();
1342}
1343
1344let editorZoomRaf = 0;
1345function scheduleEditorZoom ()
1346{
1347 if (editorZoomRaf)
1348 { return; }
1349 editorZoomRaf = requestAnimationFrame(() =>
1350 {
1351 editorZoomRaf = 0;
1352 if (!view)
1353 { return; }
1354 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
1355 frameNeighborhood();
1356 });
1357}
1358
1359function requestChunks (coords)
1360{
1361 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
1362 { return; }
1363 for (const coord of coords)
1364 {
1365 try
1366 {
1367 socket.send({
1368 type: MessageType.editorLoadChunk,
1369 chunkX: coord.chunkX,
1370 chunkY: coord.chunkY,
1371 dimensionId: selectedDimensionId
1372 });
1373 }
1374 catch (_)
1375 { break; }
1376 }
1377}
1378
1379function doLoadNeighborhood (x, y)
1380{
1381 chunkX = x;
1382 chunkY = y;
1383 $("coords").textContent = `${chunkX}, ${chunkY}`;
1384 requestChunks(neighborhoodCoords(x, y));
1385}
1386
1387function loadNeighborhood (x, y)
1388{
1389 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
1390 {
1391 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
1392 return;
1393 }
1394 doLoadNeighborhood(x, y);
1395}
1396
1397function requestNeighbors ()
1398{
1399 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
1400}
1401
1402function anyModalOpen ()
1403{
1404 return settingsModal?.isOpen()
1405 || paletteModal?.isOpen()
1406 || tileConfigModal?.isOpen()
1407 || questsModal?.isOpen()
1408 || dialoguesModal?.isOpen()
1409 || giftsModal?.isOpen()
1410 || dimensionPicker?.isOpen()
1411 || !$("unsaved-chunk-modal")?.hidden
1412 || !$("global-changelog-modal")?.hidden
1413 || !$("dimension-picker-modal")?.hidden;
1414}
1415
1416function updateHoverStatus (local)
1417{
1418 const el = $("hover-status-text");
1419 if (!el)
1420 { return; }
1421 if (!local)
1422 {
1423 el.textContent = "Hover a tile for coordinates";
1424 return;
1425 }
1426 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
1427 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
1428 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
1429}
1430
1431function updateTooltip (local, options = {})
1432{
1433 if (!options.keepStatus)
1434 { updateHoverStatus(local); }
1435 const tip = $("tile-tooltip");
1436 if (!tip || !local || !draft)
1437 {
1438 if (tip)
1439 { tip.hidden = true; }
1440 view?.clearSpawnRangeHighlight();
1441 return;
1442 }
1443 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
1444 const spawner = spawnerAt(local.x, local.y);
1445 const lines = [];
1446 if (block)
1447 {
1448 const def = BLOCK_DEFINITIONS[block.typeId];
1449 lines.push(def?.displayName ?? `Block ${block.typeId}`);
1450 if (block.config && Object.keys(block.config).length)
1451 {
1452 for (const [key, value] of Object.entries(block.config))
1453 { lines.push(`${key}: ${value}`); }
1454 }
1455 }
1456 if (spawner)
1457 {
1458 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
1459 if (isItemSpawnerConfig(config))
1460 {
1461 lines.push("Spawner · Item Spawner");
1462 lines.push(`appearance: ${config.appearance}`);
1463 lines.push(`items: ${(config.items ?? []).length}`);
1464 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1465 lines.push(`respawn: ${config.respawnDelaySeconds}s`);
1466 lines.push(`id: ${config.spawnerId}`);
1467 view.setSpawnRangeHighlight(
1468 local.tileX,
1469 local.tileY,
1470 config.spawnRangeTiles,
1471 config.spawnRangeTiles
1472 );
1473 }
1474 else
1475 {
1476 const mob = mobDefinition(config.mobTypeId);
1477 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
1478 lines.push(`maxAlive: ${config.maxAlive}`);
1479 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
1480 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
1481 lines.push(`id: ${config.spawnerId}`);
1482 view.setSpawnRangeHighlight(
1483 local.tileX,
1484 local.tileY,
1485 config.spawnRangeTiles,
1486 config.maxWanderRangeTiles
1487 );
1488 }
1489 }
1490 else
1491 { view.clearSpawnRangeHighlight(); }
1492 if (!lines.length)
1493 {
1494 tip.hidden = true;
1495 return;
1496 }
1497 tip.hidden = false;
1498 tip.textContent = lines.join("\n");
1499 const canvas = scene.canvas;
1500 const rect = canvas.getBoundingClientRect();
1501 const size = view.tileSize();
1502 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
1503 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
1504 tip.style.left = `${screenX}px`;
1505 tip.style.top = `${screenY}px`;
1506}
1507
1508async function main ()
1509{
1510 const authStatus = await fetchAuthStatus();
1511 const signIn = document.getElementById("auth-sign-in");
1512 const signOut = document.getElementById("auth-sign-out");
1513 if (signIn)
1514 {
1515 signIn.hidden = !!authStatus?.authenticated;
1516 signIn.href = loginUrl("/editor");
1517 }
1518 if (signOut)
1519 {
1520 signOut.hidden = !authStatus?.authenticated;
1521 signOut.href = logoutUrl("/editor");
1522 }
1523 if (!authStatus.authenticated)
1524 {
1525 $("who").textContent = "Sign in required";
1526 $("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
1527 return;
1528 }
1529
1530 const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in";
1531 $("who").textContent = `${accountLabel} · loading sprites…`;
1532
1533 catalog = await loadSpriteCatalog();
1534 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
1535 await preloadCatalogImages(game, catalog, {
1536 onProgress ({ loaded, total })
1537 {
1538 $("who").textContent = `${accountLabel} · loading sprites ${loaded}/${total}`;
1539 }
1540 });
1541 applySpriteSheets(game.images, catalog);
1542 scene = new Scene(250, 56, 64, 64);
1543 scene.backgroundColor.r = 0;
1544 scene.backgroundColor.g = 0;
1545 scene.backgroundColor.b = 0;
1546 game.loadScene(scene);
1547 view = new WorldView(game, scene, catalog);
1548 view.followPlayer = false;
1549 view.natureTintEnabled = false;
1550 view.setGraphicsPrefs(loadGraphicsSettings());
1551 syncSeasonControls(view.worldSeason ?? seasonIdAt());
1552 layoutScene();
1553 selectTool(tool);
1554 $("tool").textContent = selectedToolLabel();
1555
1556 paletteModal = initPaletteModal({
1557 catalog,
1558 imageUrlFor (name)
1559 {
1560 const sprite = game.images[name];
1561 const html = sprite?.g_image;
1562 if (html && typeof html.toDataURL === "function")
1563 {
1564 try
1565 { return html.toDataURL("image/png"); }
1566 catch (_)
1567 { /* fall through */ }
1568 }
1569 return imageUrlByName.get(name) ?? null;
1570 },
1571 onSelect (next)
1572 {
1573 selectTool(next);
1574 $("tool").textContent = selectedToolLabel();
1575 }
1576 });
1577
1578 tileConfigModal = initTileConfigModal({
1579 socket: {
1580 send (payload)
1581 {
1582 socket?.send(payload);
1583 }
1584 },
1585 MessageType,
1586 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
1587 getQuests: () => questsModal?.getQuests?.() ?? [],
1588 describeWorldTile,
1589 centerEditorOnTile,
1590 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1591 id: dim.dimensionId,
1592 label: dim.displayName || dim.dimensionId,
1593 disabled: !!dim.deletedAt,
1594 hint: dim.deletedAt ? "soft-deleted" : undefined
1595 })),
1596 onSave (ctx, config)
1597 {
1598 if (!draft)
1599 { return; }
1600 if (ctx.kind === "doorway")
1601 {
1602 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1603 draft.blocks[index] = {
1604 typeId: BlockType.doorway,
1605 state: config.state || "door",
1606 config: {
1607 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
1608 tileX: Number(config.tileX) || 0,
1609 tileY: Number(config.tileY) || 0
1610 }
1611 };
1612 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1613 ground: draft.grounds[index],
1614 block: draft.blocks[index],
1615 light: draft.light[index]
1616 });
1617 afterDraftMutation();
1618 return;
1619 }
1620 if (ctx.kind === "door")
1621 {
1622 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1623 const existing = draft.blocks[index];
1624 if (!existing || existing.typeId !== BlockType.door)
1625 { return; }
1626 const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
1627 const nextConfig = normalizeDoorConfig({
1628 ...prev,
1629 when: config.when,
1630 blockedMessage: config.blockedMessage
1631 });
1632 draft.blocks[index] = {
1633 typeId: BlockType.door,
1634 state: existing.state,
1635 config: nextConfig
1636 };
1637 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1638 ground: draft.grounds[index],
1639 block: draft.blocks[index],
1640 light: draft.light[index]
1641 });
1642 afterDraftMutation();
1643 return;
1644 }
1645 if (ctx.kind === "fishing-spot")
1646 {
1647 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1648 const existing = draft.blocks[index];
1649 draft.blocks[index] = {
1650 typeId: BlockType.fishingSpot,
1651 state: existing?.state === "exhausted" ? "exhausted" : "fishing-spot",
1652 config: { fishes: [...(config.fishes ?? [])] }
1653 };
1654 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1655 ground: draft.grounds[index],
1656 block: draft.blocks[index],
1657 light: draft.light[index]
1658 });
1659 afterDraftMutation();
1660 return;
1661 }
1662 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1663 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
1664 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1665 afterDraftMutation();
1666 },
1667 onRemove (ctx)
1668 {
1669 if (!draft)
1670 { return; }
1671 if (ctx.kind === "door")
1672 {
1673 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1674 const existing = draft.blocks[index];
1675 if (!existing || existing.typeId !== BlockType.door)
1676 { return; }
1677 const prev = existing.config && typeof existing.config === "object" ? { ...existing.config } : {};
1678 delete prev.when;
1679 delete prev.requirements;
1680 delete prev.blockedMessage;
1681 delete prev.denyMessage;
1682 draft.blocks[index] = {
1683 typeId: BlockType.door,
1684 state: existing.state,
1685 config: normalizeDoorConfig(prev)
1686 };
1687 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1688 ground: draft.grounds[index],
1689 block: draft.blocks[index],
1690 light: draft.light[index]
1691 });
1692 afterDraftMutation();
1693 return;
1694 }
1695 if (ctx.kind === "doorway")
1696 {
1697 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1698 draft.blocks[index] = null;
1699 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1700 ground: draft.grounds[index],
1701 block: draft.blocks[index],
1702 light: draft.light[index]
1703 });
1704 afterDraftMutation();
1705 return;
1706 }
1707 if (ctx.kind === "fishing-spot")
1708 {
1709 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
1710 draft.blocks[index] = null;
1711 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
1712 ground: draft.grounds[index],
1713 block: draft.blocks[index],
1714 light: draft.light[index]
1715 });
1716 afterDraftMutation();
1717 return;
1718 }
1719 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
1720 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
1721 afterDraftMutation();
1722 }
1723 });
1724
1725 const ticker = new GameObject(0, 0, null, 10);
1726 ticker.update = (dt) =>
1727 {
1728 hoverLocal = null;
1729 const canvas = scene.canvas;
1730 const rect = canvas.getBoundingClientRect();
1731 const mouseX = GameInput.mousePosition.x - rect.left;
1732 const mouseY = GameInput.mousePosition.y - rect.top;
1733 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
1734 if (overCanvas && draft && !anyModalOpen())
1735 {
1736 const tile = view.screenToTile(mouseX, mouseY);
1737 const localX = tile.tileX - chunkX * CHUNK_SIZE;
1738 const localY = tile.tileY - chunkY * CHUNK_SIZE;
1739 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
1740 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
1741 updateHoverStatus({
1742 tileX: tile.tileX,
1743 tileY: tile.tileY,
1744 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1745 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
1746 chunkX: hoverChunkX,
1747 chunkY: hoverChunkY
1748 });
1749 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
1750 {
1751 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
1752 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
1753 updateTooltip(hoverLocal);
1754 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
1755 { paintAt(localX, localY); }
1756 }
1757 else
1758 {
1759 hoverLocal = null;
1760 view.clearTilePreview();
1761 updateTooltip(null, { keepStatus: true });
1762 }
1763 }
1764 else
1765 {
1766 view.clearTilePreview();
1767 updateTooltip(null);
1768 }
1769 view.update(dt);
1770 frameNeighborhood();
1771 };
1772 scene.addObject(ticker);
1773 window.addEventListener("resize", layoutScene);
1774
1775 accountWhoLabel = accountLabel;
1776 $("who").textContent = `${accountLabel} · connecting…`;
1777
1778 function setWhoConnected (label, isAdmin)
1779 {
1780 accountWhoLabel = label;
1781 $("who").textContent = `${label}${isAdmin ? " · admin" : " · not admin"}`;
1782 }
1783
1784 function resubscribeEditorSession ({ reloadMap })
1785 {
1786 socket.send({ type: MessageType.editorLoadSettings });
1787 socket.send({ type: MessageType.editorLoadGameAdmins });
1788 socket.send({ type: MessageType.editorConsoleSubscribe });
1789 requestDimensions();
1790 if (reloadMap)
1791 {
1792 loadNeighborhood(chunkX, chunkY);
1793 return;
1794 }
1795 const coords = neighborhoodCoords(chunkX, chunkY).filter((coord) =>
1796 {
1797 if (coord.chunkX === chunkX && coord.chunkY === chunkY)
1798 { return !draft || !isSelectedChunkDirty(); }
1799 return !dirtyNeighborChunks.has(chunkKey(coord.chunkX, coord.chunkY));
1800 });
1801 requestChunks(coords);
1802 syncSaveButton();
1803 }
1804
1805 socket = new GameSocket(defaultSocketUrl(), (message) =>
1806 {
1807 if (message.type === MessageType.session)
1808 {
1809 const wasReady = sessionReady;
1810 sessionAuthSubject = message.authSubject ?? null;
1811 sessionReady = true;
1812 socket.notifySessionEstablished();
1813 const label = message.username ?? message.authSubject ?? "Unknown";
1814 setWhoConnected(label, !!message.isAdmin);
1815 if (!message.isAdmin)
1816 {
1817 $("error").textContent = "Admin access required.";
1818 return;
1819 }
1820 $("error").textContent = "";
1821 const restartBtn = document.getElementById("editor-restart-now");
1822 if (restartBtn)
1823 {
1824 restartBtn.hidden = false;
1825 restartBtn.disabled = false;
1826 }
1827 resubscribeEditorSession({ reloadMap: !wasReady });
1828 }
1829 else if (message.type === MessageType.editorSettings
1830 || message.type === MessageType.editorGameAdmins)
1831 { settingsModal.handleMessage(message); }
1832 else if (message.type === MessageType.editorConsoleSnapshot)
1833 { applyConsoleSnapshot(message.lines); }
1834 else if (message.type === MessageType.editorConsoleLine)
1835 { appendConsoleLine(message.line); }
1836 else if (message.type === MessageType.editorDimensions)
1837 {
1838 applyDimensionsList(message);
1839 }
1840 else if (message.type === MessageType.editorQuests)
1841 {
1842 questsModal?.handleMessage(message);
1843 settingsModal?.handleMessage(message);
1844 dialoguesModal?.handleMessage(message);
1845 tileConfigModal?.handleMessage(message);
1846 }
1847 else if (message.type === MessageType.editorDialogues)
1848 {
1849 dialoguesModal?.handleMessage(message);
1850 tileConfigModal?.handleMessage(message);
1851 questsModal?.handleMessage(message);
1852 }
1853 else if (message.type === MessageType.editorGiftCharacters
1854 || message.type === MessageType.editorGiftSent)
1855 { giftsModal?.handleMessage(message); }
1856 else if (message.type === MessageType.editorGlobalChangelog)
1857 { renderGlobalChangelog(message.changelog ?? []); }
1858 else if (message.type === MessageType.editorChunk)
1859 {
1860 const msgDim = normalizeDimensionId(message.dimensionId ?? selectedDimensionId);
1861 if (msgDim !== selectedDimensionId)
1862 { return; }
1863 const isSaveAck = pendingSaveAcks.delete(
1864 editorChunkSaveKey(msgDim, message.chunkX, message.chunkY)
1865 );
1866 if (message.settings)
1867 { view.setSettings(message.settings); }
1868 if (!inEditorView(message.chunkX, message.chunkY))
1869 { return; }
1870 if (message.chunkX === chunkX && message.chunkY === chunkY)
1871 { showSelectedChunk(message, { isSaveAck }); }
1872 else
1873 {
1874 const key = chunkKey(message.chunkX, message.chunkY);
1875 neighborSpawnersByChunk.set(key, message.data.spawners ?? []);
1876 if (!dirtyNeighborChunks.has(key))
1877 {
1878 view.applySnapshot(snapshotFromPayload(message));
1879 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
1880 }
1881 }
1882 pruneView();
1883 }
1884 else if (message.type === MessageType.editorRevisionApplied)
1885 {
1886 applyInFlight = false;
1887 setRevisionState({
1888 activeRevisionId: message.activeRevisionId,
1889 pendingRevisionId: message.pendingRevisionId
1890 });
1891 const status = $("apply-status");
1892 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
1893 status.className = "hint ok";
1894 requestDimensions();
1895 requestChunks(neighborhoodCoords(chunkX, chunkY));
1896 }
1897 else if (message.type === MessageType.forceLogout)
1898 {
1899 $("who").textContent = "Server restarting…";
1900 $("error").textContent = message.reason || "Server shutting down.";
1901 }
1902 else if (message.type === MessageType.error)
1903 {
1904 $("error").textContent = message.message;
1905 if (giftsModal?.isOpen())
1906 { giftsModal.handleError?.(message.message); }
1907 pendingCreatedDimensionId = null;
1908 pendingSaveAcks.clear();
1909 navigateAfterSave = false;
1910 dimensionPicker?.setValue(selectedDimensionId);
1911 if (applyInFlight)
1912 {
1913 applyInFlight = false;
1914 $("apply-status").textContent = "";
1915 $("apply-status").className = "hint";
1916 updateRevisionUI();
1917 }
1918 }
1919 }, {
1920 autoReconnect: true,
1921 onOpen ()
1922 {
1923 if (sessionReady)
1924 { $("who").textContent = `${accountWhoLabel} · reconnected, waiting for session…`; }
1925 },
1926 onReconnecting ({ attempt, delayMs })
1927 {
1928 $("who").textContent = `${accountWhoLabel} · reconnecting…`;
1929 if (sessionReady)
1930 {
1931 $("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept."
1932 + ` (attempt ${attempt}, retry in ${Math.round(delayMs / 100) / 10}s)`;
1933 }
1934 },
1935 onClose (event)
1936 {
1937 if (event.code === 1000)
1938 { return; }
1939 const authOrRestart = {
1940 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1941 1011: "Server could not verify your account with auth.timfalken.com.",
1942 1001: "Server is restarting. Reload this page in a moment."
1943 };
1944 if (authOrRestart[event.code])
1945 {
1946 sessionReady = false;
1947 $("who").textContent = "Connection failed";
1948 $("error").textContent = authOrRestart[event.code];
1949 return;
1950 }
1951 if (sessionReady)
1952 {
1953 $("who").textContent = `${accountWhoLabel} · reconnecting…`;
1954 $("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";
1955 persistDirtyDraftBackup();
1956 return;
1957 }
1958 const reasons = {
1959 1006: "Connection dropped before the editor session started."
1960 };
1961 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1962 $("who").textContent = "Connection failed";
1963 $("error").textContent = detail;
1964 },
1965 onError ()
1966 {
1967 if (sessionReady)
1968 {
1969 $("who").textContent = `${accountWhoLabel} · reconnecting…`;
1970 $("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";
1971 return;
1972 }
1973 $("who").textContent = "Connection failed";
1974 $("error").textContent = "Could not open a live connection to the server.";
1975 }
1976 });
1977 settingsModal = initSettingsModal({
1978 socket,
1979 MessageType,
1980 getAuthSubject: () => sessionAuthSubject,
1981 onApplied (settings)
1982 {
1983 view.setSettings(settings);
1984 },
1985 onPreviewNight (hour)
1986 {
1987 view.nightPreview = hour;
1988 $("night").value = String(hour);
1989 $("night-label").textContent = Number(hour).toFixed(1);
1990 }
1991 });
1992 dimensionPicker = initDimensionPickerModal({
1993 onSelect (id)
1994 {
1995 selectDimension(id);
1996 },
1997 onCreate (rawId, displayName)
1998 {
1999 const id = normalizeDimensionId(rawId);
2000 $("error").textContent = "";
2001 pendingCreatedDimensionId = id;
2002 socket.send({
2003 type: MessageType.editorCreateDimension,
2004 dimensionId: id,
2005 displayName: displayName ?? rawId.trim()
2006 });
2007 }
2008 });
2009 dimensionPicker.setOptions([{
2010 id: OVERWORLD_ID,
2011 label: "Overworld"
2012 }]);
2013 dimensionPicker.setValue(OVERWORLD_ID);
2014 dimensionSettings = initDimensionSettings({
2015 socket,
2016 MessageType,
2017 GROUND_DEFINITIONS,
2018 OVERWORLD_ID,
2019 getSelectedDimensionId: () => selectedDimensionId,
2020 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
2021 isOverworld
2022 });
2023
2024function collectEditorSpawners ()
2025{
2026 const byId = new Map();
2027 function add (row)
2028 {
2029 const id = String(row?.spawnerId ?? "").trim();
2030 if (!id)
2031 { return; }
2032 byId.set(id, {
2033 spawnerId: id,
2034 mobTypeId: row.mobTypeId ?? null,
2035 dimensionId: row.dimensionId ?? OVERWORLD_ID,
2036 tileX: row.tileX | 0,
2037 tileY: row.tileY | 0
2038 });
2039 }
2040 for (const row of questsModal?.getServerSpawners?.() ?? [])
2041 { add(row); }
2042 function addChunk (cx, cy, dim, spawners)
2043 {
2044 for (const entry of spawners ?? [])
2045 {
2046 const config = normalizeSpawnerConfig(entry.config, entry.config?.spawnerId);
2047 if (isItemSpawnerConfig(config))
2048 { continue; }
2049 add({
2050 spawnerId: config.spawnerId,
2051 mobTypeId: config.mobTypeId,
2052 dimensionId: dim,
2053 tileX: cx * CHUNK_SIZE + (entry.localX | 0),
2054 tileY: cy * CHUNK_SIZE + (entry.localY | 0)
2055 });
2056 }
2057 }
2058 if (draft)
2059 { addChunk(chunkX, chunkY, selectedDimensionId, draft.spawners); }
2060 for (const [key, data] of dirtyNeighborChunks)
2061 {
2062 const [cx, cy] = key.split(",").map(Number);
2063 if (!Number.isFinite(cx) || !Number.isFinite(cy))
2064 { continue; }
2065 addChunk(cx, cy, selectedDimensionId, data.spawners);
2066 }
2067 for (const [key, spawners] of neighborSpawnersByChunk)
2068 {
2069 const [cx, cy] = key.split(",").map(Number);
2070 if (!Number.isFinite(cx) || !Number.isFinite(cy))
2071 { continue; }
2072 addChunk(cx, cy, selectedDimensionId, spawners);
2073 }
2074 return [...byId.values()].sort((a, b) => a.spawnerId.localeCompare(b.spawnerId));
2075}
2076
2077 questsModal = initQuestsModal({
2078 socket,
2079 MessageType,
2080 describeWorldTile,
2081 centerEditorOnTile,
2082 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
2083 id: dim.dimensionId,
2084 label: dim.displayName || dim.dimensionId,
2085 disabled: dim.deletedAt != null,
2086 hint: dim.deletedAt != null ? "soft-deleted" : null
2087 })),
2088 getSpawnerOptions: (mobTypeId) => collectEditorSpawners().filter((row) =>
2089 !mobTypeId || String(row.mobTypeId) === String(mobTypeId)
2090 )
2091 });
2092 dialoguesModal = initDialoguesModal({
2093 socket,
2094 MessageType,
2095 describeWorldTile,
2096 centerEditorOnTile,
2097 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
2098 id: dim.dimensionId,
2099 label: dim.displayName || dim.dimensionId,
2100 disabled: dim.deletedAt != null,
2101 hint: dim.deletedAt != null ? "soft-deleted" : null
2102 })),
2103 getSpawnerOptions: (mobTypeId) => collectEditorSpawners().filter((row) =>
2104 !mobTypeId || String(row.mobTypeId) === String(mobTypeId)
2105 )
2106 });
2107 giftsModal = initGiftsModal({ socket, MessageType });
2108 initSidePanelTabs();
2109 game.startGame();
2110 useNearestNeighbour(scene, game.images);
2111 try
2112 { await socket.connect(); }
2113 catch (error)
2114 {
2115 // autoReconnect keeps retrying; surface the first failure without aborting the editor UI
2116 if (!sessionReady)
2117 {
2118 $("who").textContent = "Connection failed";
2119 $("error").textContent = error?.message || "Could not open a live connection to the server.";
2120 }
2121 }
2122}
2123
2124$("tool").textContent = selectedToolLabel();
2125$("tool-erase").addEventListener("click", () =>
2126{
2127 selectTool({ kind: "erase" });
2128 $("tool").textContent = selectedToolLabel();
2129});
2130
2131$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
2132$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
2133$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
2134$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
2135$("copy-chunk")?.addEventListener("click", () => copySelectedChunk());
2136$("paste-chunk")?.addEventListener("click", () => pasteSelectedChunk());
2137$("clear-chunk")?.addEventListener("click", () => clearSelectedChunk());
2138
2139function isTypingTarget (target)
2140{
2141 if (!(target instanceof Element))
2142 { return false; }
2143 const tag = target.tagName;
2144 if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT")
2145 { return true; }
2146 return !!target.closest("[contenteditable='true']");
2147}
2148
2149window.addEventListener("keydown", (event) =>
2150{
2151 if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)
2152 { return; }
2153 if (anyModalOpen() || isTypingTarget(event.target))
2154 { return; }
2155 if (event.key === "ArrowUp")
2156 {
2157 event.preventDefault();
2158 loadNeighborhood(chunkX, chunkY - 1);
2159 }
2160 else if (event.key === "ArrowDown")
2161 {
2162 event.preventDefault();
2163 loadNeighborhood(chunkX, chunkY + 1);
2164 }
2165 else if (event.key === "ArrowLeft")
2166 {
2167 event.preventDefault();
2168 loadNeighborhood(chunkX - 1, chunkY);
2169 }
2170 else if (event.key === "ArrowRight")
2171 {
2172 event.preventDefault();
2173 loadNeighborhood(chunkX + 1, chunkY);
2174 }
2175});
2176$("open").addEventListener("change", () =>
2177{
2178 if (isSelectedDimensionSoftDeleted())
2179 {
2180 $("open").checked = !!draft?.open;
2181 return;
2182 }
2183 if (draft)
2184 {
2185 draft.open = $("open").checked;
2186 view.setChunkOpen(chunkX, chunkY, draft.open);
2187 afterDraftMutation();
2188 }
2189});
2190$("save").addEventListener("click", () =>
2191{
2192 saveSelectedChunk();
2193});
2194$("unsaved-chunk-cancel")?.addEventListener("click", () =>
2195{
2196 pendingNavigate = null;
2197 navigateAfterSave = false;
2198 hideUnsavedModal();
2199});
2200$("unsaved-chunk-backdrop")?.addEventListener("click", () =>
2201{
2202 pendingNavigate = null;
2203 navigateAfterSave = false;
2204 hideUnsavedModal();
2205});
2206$("unsaved-chunk-discard")?.addEventListener("click", () =>
2207{
2208 const next = pendingNavigate;
2209 hideUnsavedModal();
2210 pendingNavigate = null;
2211 navigateAfterSave = false;
2212 discardUnsavedDraft();
2213 if (!next)
2214 { return; }
2215 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
2216 if (nextDim !== selectedDimensionId)
2217 {
2218 selectedDimensionId = nextDim;
2219 syncDimensionUi();
2220 clearNeighborhoodView();
2221 }
2222 doLoadNeighborhood(next.chunkX, next.chunkY);
2223});
2224$("unsaved-chunk-save")?.addEventListener("click", () =>
2225{
2226 hideUnsavedModal();
2227 if (!pendingNavigate)
2228 { return; }
2229 navigateAfterSave = true;
2230 if (!saveSelectedChunk())
2231 {
2232 navigateAfterSave = false;
2233 const next = pendingNavigate;
2234 pendingNavigate = null;
2235 if (next)
2236 {
2237 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
2238 if (nextDim !== selectedDimensionId)
2239 {
2240 selectedDimensionId = nextDim;
2241 syncDimensionUi();
2242 clearNeighborhoodView();
2243 }
2244 doLoadNeighborhood(next.chunkX, next.chunkY);
2245 }
2246 }
2247});
2248$("apply").addEventListener("click", () =>
2249{
2250 if (!pendingRevisionId || applyInFlight)
2251 { return; }
2252 $("error").textContent = "";
2253 const status = $("apply-status");
2254 status.textContent = "Applying…";
2255 status.className = "hint";
2256 applyInFlight = true;
2257 updateRevisionUI();
2258 socket.send({ type: MessageType.editorApplyRevision });
2259});
2260document.getElementById("editor-restart-now")?.addEventListener("click", () =>
2261{
2262 if (!socket)
2263 { return; }
2264 const ok = window.confirm(
2265 "Restart the server now?\n\nAll players and editor sessions will disconnect. "
2266 + "systemd will start a fresh process and pull the latest code from git."
2267 );
2268 if (!ok)
2269 { return; }
2270 const restartBtn = document.getElementById("editor-restart-now");
2271 if (restartBtn)
2272 { restartBtn.disabled = true; }
2273 $("who").textContent = "Restarting server…";
2274 $("error").textContent = "";
2275 socket.send({ type: MessageType.editorRestartNow });
2276});
2277$("night").addEventListener("input", () =>
2278{
2279 view.nightPreview = Number($("night").value);
2280 $("night-label").textContent = view.nightPreview.toFixed(1);
2281});
2282$("season").addEventListener("change", () =>
2283{
2284 applySeasonPreview($("season").value);
2285});
2286
2287function showGlobalChangelog (visible)
2288{
2289 const backdrop = $("global-changelog-backdrop");
2290 const modal = $("global-changelog-modal");
2291 if (backdrop)
2292 { backdrop.hidden = !visible; }
2293 if (modal)
2294 { modal.hidden = !visible; }
2295}
2296
2297function renderGlobalChangelog (changelog)
2298{
2299 const log = $("global-changelog");
2300 if (!log)
2301 { return; }
2302 log.innerHTML = "";
2303 if (!changelog.length)
2304 {
2305 log.innerHTML = "<p class=\"hint\">No edits logged yet.</p>";
2306 return;
2307 }
2308 const kindLabel = {
2309 chunk: "Chunk",
2310 settings: "Settings",
2311 quest: "Quest",
2312 dialogue: "Dialogue"
2313 };
2314 for (const entry of changelog)
2315 {
2316 const item = document.createElement("article");
2317 const who = entry.editorDisplayName || entry.editor_admin_id;
2318 const kind = kindLabel[entry.kind] || entry.kind || "Edit";
2319 const scope = entry.scope ? ` · ${entry.scope}` : "";
2320 item.innerHTML = `<header>${kind}${scope} · ${who} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
2321 const list = document.createElement("ul");
2322 for (const bullet of entry.diffEntries ?? [])
2323 {
2324 const li = document.createElement("li");
2325 li.textContent = bullet;
2326 list.append(li);
2327 }
2328 item.append(list);
2329 log.append(item);
2330 }
2331 log.scrollTop = 0;
2332}
2333
2334document.getElementById("open-global-changelog")?.addEventListener("click", () =>
2335{
2336 const log = $("global-changelog");
2337 if (log)
2338 { log.innerHTML = "<p class=\"hint\">Loading…</p>"; }
2339 showGlobalChangelog(true);
2340 socket.send({ type: MessageType.editorLoadGlobalChangelog });
2341});
2342document.getElementById("global-changelog-close")?.addEventListener("click", () => showGlobalChangelog(false));
2343document.getElementById("global-changelog-backdrop")?.addEventListener("click", () => showGlobalChangelog(false));
2344
2345function syncSeasonControls (season)
2346{
2347 const next = season === SeasonId.spring
2348 || season === SeasonId.fall
2349 || season === SeasonId.winter
2350 || season === SeasonId.summer
2351 ? season
2352 : seasonIdAt();
2353 $("season").value = next;
2354 view?.setWorldSeason(next);
2355}
2356
2357function applySeasonPreview (season)
2358{
2359 syncSeasonControls(season);
2360}
2361
2362function cycleToolState (direction)
2363{
2364 if (tool.kind === "erase" || tool.kind === "spawner")
2365 { return; }
2366 const layer = tool.kind === "ground" ? "ground" : "block";
2367 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
2368 if (definitionUsesNeighborConnect(def))
2369 { return; }
2370 if (tool.kind === "block" && def?.id === BlockType.flower)
2371 { return; }
2372 const allStates = statesForType(catalog, layer, def.key);
2373 const seasonal = seasonalCycleStates(allStates);
2374 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
2375 if (states.length < 2)
2376 { return; }
2377 tool.state = cycleState(states, tool.state, direction);
2378 $("tool").textContent = selectedToolLabel();
2379 const season = seasonIdFromVisualState(tool.state);
2380 if (season)
2381 { applySeasonPreview(season); }
2382 if (!draft || !hoverLocal)
2383 { return; }
2384 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
2385 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
2386 { paintAt(hoverLocal.x, hoverLocal.y); }
2387 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
2388 { paintAt(hoverLocal.x, hoverLocal.y); }
2389}
2390
2391document.addEventListener("wheel", (event) =>
2392{
2393 if (!scene?.canvas || anyModalOpen())
2394 { return; }
2395 const rect = scene.canvas.getBoundingClientRect();
2396 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
2397 { return; }
2398 event.preventDefault();
2399 if (event.shiftKey)
2400 {
2401 cycleToolState(event.deltaY < 0 ? 1 : -1);
2402 if (hoverLocal)
2403 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
2404 return;
2405 }
2406 zoomEditor(event.deltaY < 0 ? 1 : -1);
2407}, { passive: false });
2408
2409document.addEventListener("contextmenu", (event) =>
2410{
2411 if (!scene?.canvas || anyModalOpen() || !draft)
2412 { return; }
2413 const rect = scene.canvas.getBoundingClientRect();
2414 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
2415 { return; }
2416 event.preventDefault();
2417 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
2418 const localX = tile.tileX - chunkX * CHUNK_SIZE;
2419 const localY = tile.tileY - chunkY * CHUNK_SIZE;
2420 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
2421 { return; }
2422 const spawner = spawnerAt(localX, localY);
2423 if (spawner)
2424 {
2425 const ctx = {
2426 localX,
2427 localY,
2428 tileX: tile.tileX,
2429 tileY: tile.tileY,
2430 config: { ...spawner.config }
2431 };
2432 if (isItemSpawnerConfig(spawner.config))
2433 { tileConfigModal.openItemSpawner(ctx); }
2434 else
2435 { tileConfigModal.openSpawner(ctx); }
2436 return;
2437 }
2438 const index = localY * CHUNK_SIZE + localX;
2439 const block = draft.blocks[index];
2440 if (block?.typeId === BlockType.doorway)
2441 {
2442 tileConfigModal.openDoorway({
2443 localX,
2444 localY,
2445 tileX: tile.tileX,
2446 tileY: tile.tileY,
2447 state: block.state ?? "door",
2448 config: block.config ? { ...block.config } : {}
2449 });
2450 return;
2451 }
2452 if (block?.typeId === BlockType.door)
2453 {
2454 tileConfigModal.openDoor({
2455 localX,
2456 localY,
2457 tileX: tile.tileX,
2458 tileY: tile.tileY,
2459 state: block.state,
2460 config: block.config ? { ...block.config } : {}
2461 });
2462 return;
2463 }
2464 if (block?.typeId === BlockType.fishingSpot)
2465 {
2466 tileConfigModal.openFishingSpot({
2467 localX,
2468 localY,
2469 tileX: tile.tileX,
2470 tileY: tile.tileY,
2471 config: block.config ? { ...block.config } : { fishes: [] }
2472 });
2473 }
2474});
2475
2476main().catch((error) =>
2477{
2478 $("error").textContent = error.message;
2479 console.error(error);
2480});