BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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