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