| 1 | import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js"; |
| 2 | import { |
| 3 | GROUND_DEFINITIONS, |
| 4 | BLOCK_DEFINITIONS, |
| 5 | GroundType, |
| 6 | BlockType, |
| 7 | normalizeGround, |
| 8 | normalizeBlock, |
| 9 | listPlaceableBlockPaletteEntries |
| 10 | } from "/shared/definitions/tiles.js"; |
| 11 | import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js"; |
| 12 | import { |
| 13 | SeasonId, |
| 14 | seasonIdAt, |
| 15 | seasonalCycleStates, |
| 16 | seasonIdFromVisualState, |
| 17 | placeableStatesForType |
| 18 | } from "/shared/world/season.js"; |
| 19 | import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js"; |
| 20 | import { GameSocket, defaultSocketUrl } from "../net/socket.js"; |
| 21 | import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js"; |
| 22 | import { WorldView } from "../render/worldView.js"; |
| 23 | import { initSettingsModal } from "./settingsModal.js"; |
| 24 | import { initPaletteModal } from "./paletteModal.js"; |
| 25 | import { initTileConfigModal } from "./tileConfigModal.js"; |
| 26 | |
| 27 | const game = new Game(); |
| 28 | let socket; |
| 29 | let scene; |
| 30 | let view; |
| 31 | let draft = null; |
| 32 | let chunkX = 0; |
| 33 | let chunkY = 0; |
| 34 | let tool = { kind: "ground", typeId: GroundType.grass, state: null }; |
| 35 | let settingsModal; |
| 36 | let paletteModal; |
| 37 | let tileConfigModal; |
| 38 | let catalog = { grounds: {}, blocks: {}, images: [] }; |
| 39 | let imageUrlByName = new Map(); |
| 40 | let hoverLocal = null; |
| 41 | let editorZoom = null; |
| 42 | let activeRevisionId = null; |
| 43 | let pendingRevisionId = null; |
| 44 | let applyInFlight = false; |
| 45 | const EDITOR_ZOOM_MIN = 0.25; |
| 46 | const EDITOR_ZOOM_MAX = 8; |
| 47 | const EDITOR_ZOOM_STEP = 1.12; |
| 48 | |
| 49 | function $ (id) |
| 50 | { |
| 51 | return document.getElementById(id); |
| 52 | } |
| 53 | |
| 54 | function selectedToolLabel () |
| 55 | { |
| 56 | if (tool.kind === "erase") |
| 57 | { return "Erase block"; } |
| 58 | if (tool.kind === "spawner") |
| 59 | { |
| 60 | const def = mobDefinition(tool.mobTypeId); |
| 61 | return `Spawner · ${def?.displayName ?? tool.mobTypeId}`; |
| 62 | } |
| 63 | const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; |
| 64 | const layer = tool.kind === "ground" ? "ground" : "block"; |
| 65 | const states = statesForType(catalog, layer, def.key); |
| 66 | const state = resolveState(states, tool.state); |
| 67 | if (tool.kind === "block" && def.id === BlockType.boulder) |
| 68 | { |
| 69 | const entry = listPlaceableBlockPaletteEntries(catalog) |
| 70 | .find((row) => row.typeId === def.id && row.state === state); |
| 71 | if (entry) |
| 72 | { return entry.displayName; } |
| 73 | } |
| 74 | if (states.length > 1) |
| 75 | { return `${def.displayName} (${state})`; } |
| 76 | return def.displayName; |
| 77 | } |
| 78 | |
| 79 | function selectTool (next) |
| 80 | { |
| 81 | if (next.kind === "erase") |
| 82 | { |
| 83 | tool = { kind: "erase" }; |
| 84 | return; |
| 85 | } |
| 86 | if (next.kind === "spawner") |
| 87 | { |
| 88 | tool = { kind: "spawner", mobTypeId: next.mobTypeId }; |
| 89 | return; |
| 90 | } |
| 91 | const layer = next.kind === "ground" ? "ground" : "block"; |
| 92 | const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId]; |
| 93 | tool = { |
| 94 | kind: next.kind, |
| 95 | typeId: next.typeId, |
| 96 | state: next.state ?? defaultStateForType(catalog, layer, def.key) |
| 97 | }; |
| 98 | } |
| 99 | |
| 100 | function placeableToolState () |
| 101 | { |
| 102 | if (tool.kind === "erase" || tool.kind === "spawner") |
| 103 | { return null; } |
| 104 | const layer = tool.kind === "ground" ? "ground" : "block"; |
| 105 | const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; |
| 106 | return resolveState(statesForType(catalog, layer, def.key), tool.state); |
| 107 | } |
| 108 | |
| 109 | function previewFromTool () |
| 110 | { |
| 111 | if (tool.kind === "erase") |
| 112 | { return { block: null }; } |
| 113 | if (tool.kind === "spawner") |
| 114 | { return {}; } |
| 115 | const state = placeableToolState(); |
| 116 | if (tool.kind === "ground") |
| 117 | { return { ground: { typeId: tool.typeId, state } }; } |
| 118 | return { block: { typeId: tool.typeId, state, config: null } }; |
| 119 | } |
| 120 | |
| 121 | function inEditorView (x, y) |
| 122 | { |
| 123 | return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS; |
| 124 | } |
| 125 | |
| 126 | function neighborhoodCoords (centerX, centerY) |
| 127 | { |
| 128 | const coords = []; |
| 129 | for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++) |
| 130 | { |
| 131 | for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++) |
| 132 | { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); } |
| 133 | } |
| 134 | return coords; |
| 135 | } |
| 136 | |
| 137 | function snapshotFromPayload (payload) |
| 138 | { |
| 139 | return { |
| 140 | chunkX: payload.chunkX, |
| 141 | chunkY: payload.chunkY, |
| 142 | open: payload.data.open, |
| 143 | closedEdges: payload.closedEdges, |
| 144 | grounds: payload.data.grounds, |
| 145 | blocks: payload.data.blocks, |
| 146 | light: payload.data.light, |
| 147 | entities: [] |
| 148 | }; |
| 149 | } |
| 150 | |
| 151 | function syncSpawnersOverlay (cx, cy, spawners) |
| 152 | { |
| 153 | view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId)); |
| 154 | } |
| 155 | |
| 156 | function spawnerAt (localX, localY) |
| 157 | { |
| 158 | return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null; |
| 159 | } |
| 160 | |
| 161 | function paintAt (localX, localY) |
| 162 | { |
| 163 | if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) |
| 164 | { return; } |
| 165 | const index = localY * CHUNK_SIZE + localX; |
| 166 | const state = placeableToolState(); |
| 167 | if (tool.kind === "ground") |
| 168 | { draft.grounds[index] = { typeId: tool.typeId, state }; } |
| 169 | else if (tool.kind === "erase") |
| 170 | { draft.blocks[index] = null; } |
| 171 | else if (tool.kind === "spawner") |
| 172 | { |
| 173 | const existing = spawnerAt(localX, localY); |
| 174 | const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`; |
| 175 | const entry = { |
| 176 | localX, |
| 177 | localY, |
| 178 | config: normalizeSpawnerConfig({ |
| 179 | ...defaultSpawnerConfig(spawnerId, tool.mobTypeId), |
| 180 | ...(existing?.config ?? {}), |
| 181 | spawnerId, |
| 182 | mobTypeId: tool.mobTypeId |
| 183 | }, spawnerId) |
| 184 | }; |
| 185 | draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY); |
| 186 | draft.spawners.push(entry); |
| 187 | syncSpawnersOverlay(chunkX, chunkY, draft.spawners); |
| 188 | return; |
| 189 | } |
| 190 | else |
| 191 | { draft.blocks[index] = { typeId: tool.typeId, state, config: null }; } |
| 192 | view.updateAuthoredTile(chunkX, chunkY, localX, localY, { |
| 193 | ground: draft.grounds[index], |
| 194 | block: draft.blocks[index], |
| 195 | light: draft.light[index] |
| 196 | }); |
| 197 | } |
| 198 | |
| 199 | function updateRevisionUI () |
| 200 | { |
| 201 | const applyBtn = $("apply"); |
| 202 | $("revision").textContent = `active ${activeRevisionId ?? "?"}` + |
| 203 | (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision"); |
| 204 | if (applyBtn) |
| 205 | { |
| 206 | applyBtn.disabled = !pendingRevisionId || applyInFlight; |
| 207 | applyBtn.title = pendingRevisionId |
| 208 | ? "Reload the live world with the pending map revision" |
| 209 | : "Save a chunk first to create a pending revision"; |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending }) |
| 214 | { |
| 215 | if (active != null) |
| 216 | { activeRevisionId = active; } |
| 217 | pendingRevisionId = pending ?? null; |
| 218 | updateRevisionUI(); |
| 219 | } |
| 220 | |
| 221 | function showSelectedChunk (payload) |
| 222 | { |
| 223 | draft = { |
| 224 | open: payload.data.open, |
| 225 | grounds: payload.data.grounds.map((ground) => normalizeGround(ground)), |
| 226 | blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)), |
| 227 | light: payload.data.light.slice(), |
| 228 | spawners: (payload.data.spawners ?? []).map((entry) => ({ |
| 229 | localX: entry.localX, |
| 230 | localY: entry.localY, |
| 231 | config: { ...entry.config } |
| 232 | })) |
| 233 | }; |
| 234 | $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`; |
| 235 | $("open").checked = draft.open; |
| 236 | setRevisionState({ |
| 237 | activeRevisionId: payload.activeRevisionId, |
| 238 | pendingRevisionId: payload.pendingRevisionId |
| 239 | }); |
| 240 | $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)"; |
| 241 | const log = $("changelog"); |
| 242 | log.innerHTML = ""; |
| 243 | for (const entry of payload.changelog ?? []) |
| 244 | { |
| 245 | const item = document.createElement("article"); |
| 246 | item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`; |
| 247 | const list = document.createElement("ul"); |
| 248 | for (const bullet of entry.diffEntries) |
| 249 | { |
| 250 | const li = document.createElement("li"); |
| 251 | li.textContent = bullet; |
| 252 | list.append(li); |
| 253 | } |
| 254 | item.append(list); |
| 255 | log.append(item); |
| 256 | } |
| 257 | view.applySnapshot(snapshotFromPayload(payload)); |
| 258 | syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners); |
| 259 | } |
| 260 | |
| 261 | function pruneView () |
| 262 | { |
| 263 | for (const key of [...view.chunks.keys()]) |
| 264 | { |
| 265 | const [x, y] = key.split(",").map(Number); |
| 266 | if (!inEditorView(x, y)) |
| 267 | { view.removeChunk(x, y); } |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | function frameNeighborhood () |
| 272 | { |
| 273 | const size = view.tileSize(); |
| 274 | view.followPlayer = false; |
| 275 | const centerX = (chunkX + 0.5) * CHUNK_SIZE * size; |
| 276 | const centerY = (chunkY + 0.5) * CHUNK_SIZE * size; |
| 277 | view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX; |
| 278 | view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY; |
| 279 | updateSelectionBorder(); |
| 280 | } |
| 281 | |
| 282 | function updateSelectionBorder () |
| 283 | { |
| 284 | const border = $("selection-border"); |
| 285 | const canvas = scene?.canvas; |
| 286 | if (!border || !canvas) |
| 287 | { return; } |
| 288 | |
| 289 | const rect = canvas.getBoundingClientRect(); |
| 290 | const size = view.tileSize(); |
| 291 | const chunkPx = CHUNK_SIZE * size; |
| 292 | const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x; |
| 293 | const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y; |
| 294 | border.style.left = `${rect.left + screenLeft}px`; |
| 295 | border.style.top = `${rect.top + screenTop}px`; |
| 296 | border.style.width = `${chunkPx}px`; |
| 297 | border.style.height = `${chunkPx}px`; |
| 298 | } |
| 299 | |
| 300 | function layoutScene () |
| 301 | { |
| 302 | const header = document.querySelector("body > header"); |
| 303 | const aside = document.querySelector("body > aside"); |
| 304 | const changelog = $("changelog-wrap"); |
| 305 | const top = header.offsetHeight; |
| 306 | aside.style.top = `${top}px`; |
| 307 | changelog.style.top = `${top}px`; |
| 308 | const left = aside.offsetWidth; |
| 309 | const right = changelog.offsetWidth; |
| 310 | const width = Math.max(64, window.innerWidth - left - right); |
| 311 | const height = Math.max(64, window.innerHeight - top); |
| 312 | scene.position.x = left; |
| 313 | scene.position.y = top; |
| 314 | scene.size.x = width; |
| 315 | scene.size.y = height; |
| 316 | scene.g_fixSize(); |
| 317 | useNearestNeighbour(scene, game.images); |
| 318 | const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX); |
| 319 | if (editorZoom == null) |
| 320 | { editorZoom = fit; } |
| 321 | else |
| 322 | { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); } |
| 323 | view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX }); |
| 324 | frameNeighborhood(); |
| 325 | } |
| 326 | |
| 327 | function zoomEditor (direction) |
| 328 | { |
| 329 | if (!view) |
| 330 | { return; } |
| 331 | const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP; |
| 332 | editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor)); |
| 333 | view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX }); |
| 334 | useNearestNeighbour(scene, game.images); |
| 335 | frameNeighborhood(); |
| 336 | } |
| 337 | |
| 338 | function requestChunks (coords) |
| 339 | { |
| 340 | for (const coord of coords) |
| 341 | { |
| 342 | socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY }); |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | function loadNeighborhood (x, y) |
| 347 | { |
| 348 | chunkX = x; |
| 349 | chunkY = y; |
| 350 | $("coords").textContent = `${chunkX}, ${chunkY}`; |
| 351 | requestChunks(neighborhoodCoords(x, y)); |
| 352 | } |
| 353 | |
| 354 | function requestNeighbors () |
| 355 | { |
| 356 | requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY)); |
| 357 | } |
| 358 | |
| 359 | function anyModalOpen () |
| 360 | { |
| 361 | return settingsModal?.isOpen() || paletteModal?.isOpen() || tileConfigModal?.isOpen(); |
| 362 | } |
| 363 | |
| 364 | function updateTooltip (local) |
| 365 | { |
| 366 | const tip = $("tile-tooltip"); |
| 367 | if (!tip || !local || !draft) |
| 368 | { |
| 369 | if (tip) |
| 370 | { tip.hidden = true; } |
| 371 | view?.clearSpawnRangeHighlight(); |
| 372 | return; |
| 373 | } |
| 374 | const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]); |
| 375 | const spawner = spawnerAt(local.x, local.y); |
| 376 | const lines = []; |
| 377 | if (block) |
| 378 | { |
| 379 | const def = BLOCK_DEFINITIONS[block.typeId]; |
| 380 | lines.push(def?.displayName ?? `Block ${block.typeId}`); |
| 381 | if (block.config && Object.keys(block.config).length) |
| 382 | { |
| 383 | for (const [key, value] of Object.entries(block.config)) |
| 384 | { lines.push(`${key}: ${value}`); } |
| 385 | } |
| 386 | } |
| 387 | if (spawner) |
| 388 | { |
| 389 | const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId); |
| 390 | const mob = mobDefinition(config.mobTypeId); |
| 391 | lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`); |
| 392 | lines.push(`maxAlive: ${config.maxAlive}`); |
| 393 | lines.push(`spawnRange: ${config.spawnRangeTiles}`); |
| 394 | lines.push(`wanderRange: ${config.maxWanderRangeTiles}`); |
| 395 | lines.push(`id: ${config.spawnerId}`); |
| 396 | view.setSpawnRangeHighlight( |
| 397 | local.tileX, |
| 398 | local.tileY, |
| 399 | config.spawnRangeTiles, |
| 400 | config.maxWanderRangeTiles |
| 401 | ); |
| 402 | } |
| 403 | else |
| 404 | { view.clearSpawnRangeHighlight(); } |
| 405 | if (!lines.length) |
| 406 | { |
| 407 | tip.hidden = true; |
| 408 | return; |
| 409 | } |
| 410 | tip.hidden = false; |
| 411 | tip.textContent = lines.join("\n"); |
| 412 | const canvas = scene.canvas; |
| 413 | const rect = canvas.getBoundingClientRect(); |
| 414 | const size = view.tileSize(); |
| 415 | const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size; |
| 416 | const screenY = local.tileY * size + scene.cameraPosition.y + rect.top; |
| 417 | tip.style.left = `${screenX}px`; |
| 418 | tip.style.top = `${screenY}px`; |
| 419 | } |
| 420 | |
| 421 | async function main () |
| 422 | { |
| 423 | catalog = await loadSpriteCatalog(); |
| 424 | imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url])); |
| 425 | await preloadCatalogImages(game, catalog); |
| 426 | applySpriteSheets(game.images, catalog); |
| 427 | scene = new Scene(250, 56, 64, 64); |
| 428 | game.loadScene(scene); |
| 429 | useNearestNeighbour(scene, game.images); |
| 430 | view = new WorldView(game, scene, catalog); |
| 431 | view.followPlayer = false; |
| 432 | syncSeasonControls(view.worldSeason ?? seasonIdAt()); |
| 433 | layoutScene(); |
| 434 | selectTool(tool); |
| 435 | $("tool").textContent = selectedToolLabel(); |
| 436 | |
| 437 | paletteModal = initPaletteModal({ |
| 438 | catalog, |
| 439 | imageUrlFor (name) |
| 440 | { |
| 441 | const sprite = game.images[name]; |
| 442 | const html = sprite?.g_image; |
| 443 | if (html && typeof html.toDataURL === "function") |
| 444 | { |
| 445 | try |
| 446 | { return html.toDataURL("image/png"); } |
| 447 | catch (_) |
| 448 | { /* fall through */ } |
| 449 | } |
| 450 | return imageUrlByName.get(name) ?? null; |
| 451 | }, |
| 452 | onSelect (next) |
| 453 | { |
| 454 | selectTool(next); |
| 455 | $("tool").textContent = selectedToolLabel(); |
| 456 | } |
| 457 | }); |
| 458 | |
| 459 | tileConfigModal = initTileConfigModal({ |
| 460 | onSave (ctx, config) |
| 461 | { |
| 462 | if (!draft) |
| 463 | { return; } |
| 464 | draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY); |
| 465 | draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config }); |
| 466 | syncSpawnersOverlay(chunkX, chunkY, draft.spawners); |
| 467 | }, |
| 468 | onRemove (ctx) |
| 469 | { |
| 470 | if (!draft) |
| 471 | { return; } |
| 472 | draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY); |
| 473 | syncSpawnersOverlay(chunkX, chunkY, draft.spawners); |
| 474 | } |
| 475 | }); |
| 476 | |
| 477 | const ticker = new GameObject(0, 0, null, 10); |
| 478 | ticker.update = (dt) => |
| 479 | { |
| 480 | hoverLocal = null; |
| 481 | const canvas = scene.canvas; |
| 482 | const rect = canvas.getBoundingClientRect(); |
| 483 | const mouseX = GameInput.mousePosition.x - rect.left; |
| 484 | const mouseY = GameInput.mousePosition.y - rect.top; |
| 485 | const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height; |
| 486 | if (overCanvas && draft && !anyModalOpen()) |
| 487 | { |
| 488 | const tile = view.screenToTile(mouseX, mouseY); |
| 489 | const localX = tile.tileX - chunkX * CHUNK_SIZE; |
| 490 | const localY = tile.tileY - chunkY * CHUNK_SIZE; |
| 491 | if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE) |
| 492 | { |
| 493 | hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY }; |
| 494 | view.setTilePreview(tile.tileX, tile.tileY, previewFromTool()); |
| 495 | updateTooltip(hoverLocal); |
| 496 | if (GameInput.mouseHeld(GameInput.MouseButtons.Left)) |
| 497 | { paintAt(localX, localY); } |
| 498 | } |
| 499 | else |
| 500 | { |
| 501 | view.clearTilePreview(); |
| 502 | updateTooltip(null); |
| 503 | } |
| 504 | } |
| 505 | else |
| 506 | { |
| 507 | view.clearTilePreview(); |
| 508 | updateTooltip(null); |
| 509 | } |
| 510 | view.update(dt); |
| 511 | frameNeighborhood(); |
| 512 | }; |
| 513 | scene.addObject(ticker); |
| 514 | window.addEventListener("resize", layoutScene); |
| 515 | |
| 516 | socket = new GameSocket(defaultSocketUrl(), (message) => |
| 517 | { |
| 518 | if (message.type === MessageType.session) |
| 519 | { |
| 520 | $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`; |
| 521 | socket.send({ type: MessageType.editorLoadSettings }); |
| 522 | loadNeighborhood(0, 0); |
| 523 | } |
| 524 | else if (message.type === MessageType.editorSettings) |
| 525 | { settingsModal.handleMessage(message); } |
| 526 | else if (message.type === MessageType.editorChunk) |
| 527 | { |
| 528 | if (message.settings) |
| 529 | { view.setSettings(message.settings); } |
| 530 | if (!inEditorView(message.chunkX, message.chunkY)) |
| 531 | { return; } |
| 532 | if (message.chunkX === chunkX && message.chunkY === chunkY) |
| 533 | { showSelectedChunk(message); } |
| 534 | else |
| 535 | { |
| 536 | view.applySnapshot(snapshotFromPayload(message)); |
| 537 | syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners); |
| 538 | } |
| 539 | pruneView(); |
| 540 | } |
| 541 | else if (message.type === MessageType.editorRevisionApplied) |
| 542 | { |
| 543 | applyInFlight = false; |
| 544 | setRevisionState({ |
| 545 | activeRevisionId: message.activeRevisionId, |
| 546 | pendingRevisionId: message.pendingRevisionId |
| 547 | }); |
| 548 | const status = $("apply-status"); |
| 549 | status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`; |
| 550 | status.className = "hint ok"; |
| 551 | requestChunks(neighborhoodCoords(chunkX, chunkY)); |
| 552 | } |
| 553 | else if (message.type === MessageType.error) |
| 554 | { |
| 555 | $("error").textContent = message.message; |
| 556 | if (applyInFlight) |
| 557 | { |
| 558 | applyInFlight = false; |
| 559 | $("apply-status").textContent = ""; |
| 560 | $("apply-status").className = "hint"; |
| 561 | updateRevisionUI(); |
| 562 | } |
| 563 | } |
| 564 | }); |
| 565 | settingsModal = initSettingsModal({ |
| 566 | socket, |
| 567 | MessageType, |
| 568 | onApplied (settings) |
| 569 | { |
| 570 | view.setSettings(settings); |
| 571 | }, |
| 572 | onPreviewNight (hour) |
| 573 | { |
| 574 | view.nightPreview = hour; |
| 575 | $("night").value = String(hour); |
| 576 | $("night-label").textContent = Number(hour).toFixed(1); |
| 577 | } |
| 578 | }); |
| 579 | game.startGame(); |
| 580 | await socket.connect(); |
| 581 | } |
| 582 | |
| 583 | $("tool").textContent = selectedToolLabel(); |
| 584 | $("tool-erase").addEventListener("click", () => |
| 585 | { |
| 586 | selectTool({ kind: "erase" }); |
| 587 | $("tool").textContent = selectedToolLabel(); |
| 588 | }); |
| 589 | |
| 590 | $("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1)); |
| 591 | $("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1)); |
| 592 | $("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY)); |
| 593 | $("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY)); |
| 594 | $("open").addEventListener("change", () => |
| 595 | { |
| 596 | if (draft) |
| 597 | { |
| 598 | draft.open = $("open").checked; |
| 599 | view.setChunkOpen(chunkX, chunkY, draft.open); |
| 600 | } |
| 601 | }); |
| 602 | $("save").addEventListener("click", () => |
| 603 | { |
| 604 | $("error").textContent = ""; |
| 605 | $("apply-status").textContent = ""; |
| 606 | $("apply-status").className = "hint"; |
| 607 | socket.send({ |
| 608 | type: MessageType.editorSaveChunk, |
| 609 | chunkX, |
| 610 | chunkY, |
| 611 | draft: { |
| 612 | open: $("open").checked, |
| 613 | grounds: draft.grounds, |
| 614 | blocks: draft.blocks, |
| 615 | spawners: draft.spawners ?? [] |
| 616 | } |
| 617 | }); |
| 618 | requestNeighbors(); |
| 619 | }); |
| 620 | $("apply").addEventListener("click", () => |
| 621 | { |
| 622 | if (!pendingRevisionId || applyInFlight) |
| 623 | { return; } |
| 624 | $("error").textContent = ""; |
| 625 | const status = $("apply-status"); |
| 626 | status.textContent = "Applying…"; |
| 627 | status.className = "hint"; |
| 628 | applyInFlight = true; |
| 629 | updateRevisionUI(); |
| 630 | socket.send({ type: MessageType.editorApplyRevision }); |
| 631 | }); |
| 632 | $("night").addEventListener("input", () => |
| 633 | { |
| 634 | view.nightPreview = Number($("night").value); |
| 635 | $("night-label").textContent = view.nightPreview.toFixed(1); |
| 636 | }); |
| 637 | $("season").addEventListener("change", () => |
| 638 | { |
| 639 | applySeasonPreview($("season").value); |
| 640 | }); |
| 641 | |
| 642 | function syncSeasonControls (season) |
| 643 | { |
| 644 | const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer |
| 645 | ? season |
| 646 | : seasonIdAt(); |
| 647 | $("season").value = next; |
| 648 | view?.setWorldSeason(next); |
| 649 | } |
| 650 | |
| 651 | function applySeasonPreview (season) |
| 652 | { |
| 653 | syncSeasonControls(season); |
| 654 | } |
| 655 | |
| 656 | function cycleToolState (direction) |
| 657 | { |
| 658 | if (tool.kind === "erase" || tool.kind === "spawner") |
| 659 | { return; } |
| 660 | const layer = tool.kind === "ground" ? "ground" : "block"; |
| 661 | const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; |
| 662 | const allStates = statesForType(catalog, layer, def.key); |
| 663 | const seasonal = seasonalCycleStates(allStates); |
| 664 | const states = seasonal ?? placeableStatesForType(catalog, layer, def.key); |
| 665 | if (states.length < 2) |
| 666 | { return; } |
| 667 | tool.state = cycleState(states, tool.state, direction); |
| 668 | $("tool").textContent = selectedToolLabel(); |
| 669 | const season = seasonIdFromVisualState(tool.state); |
| 670 | if (season) |
| 671 | { applySeasonPreview(season); } |
| 672 | if (!draft || !hoverLocal) |
| 673 | { return; } |
| 674 | const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x; |
| 675 | if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId) |
| 676 | { paintAt(hoverLocal.x, hoverLocal.y); } |
| 677 | else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId) |
| 678 | { paintAt(hoverLocal.x, hoverLocal.y); } |
| 679 | } |
| 680 | |
| 681 | document.addEventListener("wheel", (event) => |
| 682 | { |
| 683 | if (!scene?.canvas || anyModalOpen()) |
| 684 | { return; } |
| 685 | const rect = scene.canvas.getBoundingClientRect(); |
| 686 | if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom) |
| 687 | { return; } |
| 688 | event.preventDefault(); |
| 689 | if (event.shiftKey) |
| 690 | { |
| 691 | cycleToolState(event.deltaY < 0 ? 1 : -1); |
| 692 | if (hoverLocal) |
| 693 | { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); } |
| 694 | return; |
| 695 | } |
| 696 | zoomEditor(event.deltaY < 0 ? 1 : -1); |
| 697 | }, { passive: false }); |
| 698 | |
| 699 | document.addEventListener("contextmenu", (event) => |
| 700 | { |
| 701 | if (!scene?.canvas || anyModalOpen() || !draft) |
| 702 | { return; } |
| 703 | const rect = scene.canvas.getBoundingClientRect(); |
| 704 | if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom) |
| 705 | { return; } |
| 706 | event.preventDefault(); |
| 707 | const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top); |
| 708 | const localX = tile.tileX - chunkX * CHUNK_SIZE; |
| 709 | const localY = tile.tileY - chunkY * CHUNK_SIZE; |
| 710 | if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) |
| 711 | { return; } |
| 712 | const spawner = spawnerAt(localX, localY); |
| 713 | if (!spawner) |
| 714 | { return; } |
| 715 | tileConfigModal.openSpawner({ |
| 716 | localX, |
| 717 | localY, |
| 718 | tileX: tile.tileX, |
| 719 | tileY: tile.tileY, |
| 720 | config: { ...spawner.config } |
| 721 | }); |
| 722 | }); |
| 723 | |
| 724 | main().catch((error) => |
| 725 | { |
| 726 | $("error").textContent = error.message; |
| 727 | console.error(error); |
| 728 | }); |