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