BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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