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