| 1 | import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js"; |
| 2 | import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround } from "/shared/definitions/tiles.js"; |
| 3 | import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js"; |
| 4 | import { GameSocket, defaultSocketUrl } from "../net/socket.js"; |
| 5 | import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js"; |
| 6 | import { WorldView } from "../render/worldView.js"; |
| 7 | import { initSettingsModal } from "./settingsModal.js"; |
| 8 | |
| 9 | const game = new Game(); |
| 10 | let socket; |
| 11 | let scene; |
| 12 | let view; |
| 13 | let draft = null; |
| 14 | let chunkX = 0; |
| 15 | let chunkY = 0; |
| 16 | let tool = { kind: "ground", typeId: GroundType.grass, state: null }; |
| 17 | let settingsModal; |
| 18 | let catalog = { grounds: {}, blocks: {} }; |
| 19 | let hoverLocal = null; |
| 20 | |
| 21 | function $ (id) |
| 22 | { |
| 23 | return document.getElementById(id); |
| 24 | } |
| 25 | |
| 26 | function selectedToolLabel () |
| 27 | { |
| 28 | if (tool.kind === "erase") |
| 29 | { return "Erase block"; } |
| 30 | const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; |
| 31 | const layer = tool.kind === "ground" ? "ground" : "block"; |
| 32 | const states = statesForType(catalog, layer, def.key); |
| 33 | const state = resolveState(states, tool.state); |
| 34 | if (states.length > 1) |
| 35 | { return `${def.displayName} (${state})`; } |
| 36 | return def.displayName; |
| 37 | } |
| 38 | |
| 39 | function selectTool (next) |
| 40 | { |
| 41 | if (next.kind === "erase") |
| 42 | { |
| 43 | tool = { kind: "erase" }; |
| 44 | return; |
| 45 | } |
| 46 | const layer = next.kind === "ground" ? "ground" : "block"; |
| 47 | const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId]; |
| 48 | tool = { |
| 49 | kind: next.kind, |
| 50 | typeId: next.typeId, |
| 51 | state: defaultStateForType(catalog, layer, def.key) |
| 52 | }; |
| 53 | } |
| 54 | |
| 55 | function previewFromTool () |
| 56 | { |
| 57 | if (tool.kind === "erase") |
| 58 | { return { block: null }; } |
| 59 | if (tool.kind === "ground") |
| 60 | { return { ground: { typeId: tool.typeId, state: tool.state } }; } |
| 61 | return { block: { typeId: tool.typeId, state: tool.state, config: null } }; |
| 62 | } |
| 63 | |
| 64 | function inEditorView (x, y) |
| 65 | { |
| 66 | return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS; |
| 67 | } |
| 68 | |
| 69 | function neighborhoodCoords (centerX, centerY) |
| 70 | { |
| 71 | const coords = []; |
| 72 | for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++) |
| 73 | { |
| 74 | for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++) |
| 75 | { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); } |
| 76 | } |
| 77 | return coords; |
| 78 | } |
| 79 | |
| 80 | function snapshotFromPayload (payload) |
| 81 | { |
| 82 | return { |
| 83 | chunkX: payload.chunkX, |
| 84 | chunkY: payload.chunkY, |
| 85 | open: payload.data.open, |
| 86 | closedEdges: payload.closedEdges, |
| 87 | grounds: payload.data.grounds, |
| 88 | blocks: payload.data.blocks, |
| 89 | light: payload.data.light, |
| 90 | entities: [] |
| 91 | }; |
| 92 | } |
| 93 | |
| 94 | function paintAt (localX, localY) |
| 95 | { |
| 96 | if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) |
| 97 | { return; } |
| 98 | const index = localY * CHUNK_SIZE + localX; |
| 99 | if (tool.kind === "ground") |
| 100 | { draft.grounds[index] = { typeId: tool.typeId, state: tool.state }; } |
| 101 | else if (tool.kind === "erase") |
| 102 | { draft.blocks[index] = null; } |
| 103 | else |
| 104 | { draft.blocks[index] = { typeId: tool.typeId, state: tool.state, config: null }; } |
| 105 | view.updateAuthoredTile(chunkX, chunkY, localX, localY, { |
| 106 | ground: draft.grounds[index], |
| 107 | block: draft.blocks[index], |
| 108 | light: draft.light[index] |
| 109 | }); |
| 110 | } |
| 111 | |
| 112 | function showSelectedChunk (payload) |
| 113 | { |
| 114 | draft = { |
| 115 | open: payload.data.open, |
| 116 | grounds: payload.data.grounds.map((ground) => normalizeGround(ground)), |
| 117 | blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)), |
| 118 | light: payload.data.light.slice() |
| 119 | }; |
| 120 | $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`; |
| 121 | $("open").checked = draft.open; |
| 122 | $("revision").textContent = `active ${payload.activeRevisionId}` + |
| 123 | (payload.pendingRevisionId ? ` · pending ${payload.pendingRevisionId}` : " · no pending revision"); |
| 124 | $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)"; |
| 125 | const log = $("changelog"); |
| 126 | log.innerHTML = ""; |
| 127 | for (const entry of payload.changelog ?? []) |
| 128 | { |
| 129 | const item = document.createElement("article"); |
| 130 | item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`; |
| 131 | const list = document.createElement("ul"); |
| 132 | for (const bullet of entry.diffEntries) |
| 133 | { |
| 134 | const li = document.createElement("li"); |
| 135 | li.textContent = bullet; |
| 136 | list.append(li); |
| 137 | } |
| 138 | item.append(list); |
| 139 | log.append(item); |
| 140 | } |
| 141 | view.applySnapshot(snapshotFromPayload(payload)); |
| 142 | } |
| 143 | |
| 144 | function pruneView () |
| 145 | { |
| 146 | for (const key of [...view.chunks.keys()]) |
| 147 | { |
| 148 | const [x, y] = key.split(",").map(Number); |
| 149 | if (!inEditorView(x, y)) |
| 150 | { view.removeChunk(x, y); } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | function frameNeighborhood () |
| 155 | { |
| 156 | const size = view.tileSize(); |
| 157 | view.followPlayer = false; |
| 158 | const centerX = (chunkX + 0.5) * CHUNK_SIZE * size; |
| 159 | const centerY = (chunkY + 0.5) * CHUNK_SIZE * size; |
| 160 | view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX; |
| 161 | view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY; |
| 162 | updateSelectionBorder(); |
| 163 | } |
| 164 | |
| 165 | function updateSelectionBorder () |
| 166 | { |
| 167 | const border = $("selection-border"); |
| 168 | const canvas = scene?.canvas; |
| 169 | if (!border || !canvas) |
| 170 | { return; } |
| 171 | |
| 172 | const rect = canvas.getBoundingClientRect(); |
| 173 | const size = view.tileSize(); |
| 174 | const chunkPx = CHUNK_SIZE * size; |
| 175 | const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x; |
| 176 | const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y; |
| 177 | border.style.left = `${rect.left + screenLeft}px`; |
| 178 | border.style.top = `${rect.top + screenTop}px`; |
| 179 | border.style.width = `${chunkPx}px`; |
| 180 | border.style.height = `${chunkPx}px`; |
| 181 | } |
| 182 | |
| 183 | function layoutScene () |
| 184 | { |
| 185 | const header = document.querySelector("body > header"); |
| 186 | const aside = document.querySelector("body > aside"); |
| 187 | const changelog = $("changelog-wrap"); |
| 188 | const top = header.offsetHeight; |
| 189 | aside.style.top = `${top}px`; |
| 190 | changelog.style.top = `${top}px`; |
| 191 | const left = aside.offsetWidth; |
| 192 | const right = changelog.offsetWidth; |
| 193 | const width = Math.max(64, window.innerWidth - left - right); |
| 194 | const height = Math.max(64, window.innerHeight - top); |
| 195 | scene.position.x = left; |
| 196 | scene.position.y = top; |
| 197 | scene.size.x = width; |
| 198 | scene.size.y = height; |
| 199 | scene.g_fixSize(); |
| 200 | useNearestNeighbour(scene, game.images); |
| 201 | const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX); |
| 202 | view.setZoom(fit, { min: 0.5, max: 4 }); |
| 203 | frameNeighborhood(); |
| 204 | } |
| 205 | |
| 206 | function requestChunks (coords) |
| 207 | { |
| 208 | for (const coord of coords) |
| 209 | { |
| 210 | socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY }); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | function loadNeighborhood (x, y) |
| 215 | { |
| 216 | chunkX = x; |
| 217 | chunkY = y; |
| 218 | $("coords").textContent = `${chunkX}, ${chunkY}`; |
| 219 | requestChunks(neighborhoodCoords(x, y)); |
| 220 | } |
| 221 | |
| 222 | function requestNeighbors () |
| 223 | { |
| 224 | requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY)); |
| 225 | } |
| 226 | |
| 227 | async function main () |
| 228 | { |
| 229 | catalog = await loadSpriteCatalog(); |
| 230 | await game.preloadImages(playImagesFromCatalog(catalog)); |
| 231 | applySpriteSheets(game.images, catalog); |
| 232 | scene = new Scene(250, 56, 64, 64); |
| 233 | game.loadScene(scene); |
| 234 | useNearestNeighbour(scene, game.images); |
| 235 | view = new WorldView(game, scene, catalog); |
| 236 | view.followPlayer = false; |
| 237 | layoutScene(); |
| 238 | selectTool(tool); |
| 239 | $("tool").textContent = selectedToolLabel(); |
| 240 | const ticker = new GameObject(0, 0, null, 10); |
| 241 | ticker.update = (dt) => |
| 242 | { |
| 243 | hoverLocal = null; |
| 244 | const canvas = scene.canvas; |
| 245 | const rect = canvas.getBoundingClientRect(); |
| 246 | const mouseX = GameInput.mousePosition.x - rect.left; |
| 247 | const mouseY = GameInput.mousePosition.y - rect.top; |
| 248 | const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height; |
| 249 | if (overCanvas && draft && !settingsModal?.isOpen()) |
| 250 | { |
| 251 | const tile = view.screenToTile(mouseX, mouseY); |
| 252 | const localX = tile.tileX - chunkX * CHUNK_SIZE; |
| 253 | const localY = tile.tileY - chunkY * CHUNK_SIZE; |
| 254 | if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE) |
| 255 | { |
| 256 | hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY }; |
| 257 | view.setTilePreview(tile.tileX, tile.tileY, previewFromTool()); |
| 258 | if (GameInput.mouseHeld(GameInput.MouseButtons.Left)) |
| 259 | { paintAt(localX, localY); } |
| 260 | } |
| 261 | else |
| 262 | { view.clearTilePreview(); } |
| 263 | } |
| 264 | else |
| 265 | { view.clearTilePreview(); } |
| 266 | view.update(dt); |
| 267 | frameNeighborhood(); |
| 268 | }; |
| 269 | scene.addObject(ticker); |
| 270 | window.addEventListener("resize", layoutScene); |
| 271 | |
| 272 | socket = new GameSocket(defaultSocketUrl(), (message) => |
| 273 | { |
| 274 | if (message.type === MessageType.session) |
| 275 | { |
| 276 | $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`; |
| 277 | socket.send({ type: MessageType.editorLoadSettings }); |
| 278 | loadNeighborhood(0, 0); |
| 279 | } |
| 280 | else if (message.type === MessageType.editorSettings) |
| 281 | { settingsModal.handleMessage(message); } |
| 282 | else if (message.type === MessageType.editorChunk) |
| 283 | { |
| 284 | if (message.settings) |
| 285 | { view.settings = message.settings; } |
| 286 | if (!inEditorView(message.chunkX, message.chunkY)) |
| 287 | { return; } |
| 288 | if (message.chunkX === chunkX && message.chunkY === chunkY) |
| 289 | { showSelectedChunk(message); } |
| 290 | else |
| 291 | { view.applySnapshot(snapshotFromPayload(message)); } |
| 292 | pruneView(); |
| 293 | } |
| 294 | else if (message.type === MessageType.error) |
| 295 | { $("error").textContent = message.message; } |
| 296 | }); |
| 297 | settingsModal = initSettingsModal({ |
| 298 | socket, |
| 299 | MessageType, |
| 300 | onApplied (settings) |
| 301 | { |
| 302 | view.settings = settings; |
| 303 | } |
| 304 | }); |
| 305 | game.startGame(); |
| 306 | await socket.connect(); |
| 307 | } |
| 308 | |
| 309 | $("tool").textContent = selectedToolLabel(); |
| 310 | document.querySelectorAll("[data-tool]").forEach((button) => |
| 311 | { |
| 312 | button.addEventListener("click", () => |
| 313 | { |
| 314 | selectTool(JSON.parse(button.dataset.tool)); |
| 315 | $("tool").textContent = selectedToolLabel(); |
| 316 | }); |
| 317 | }); |
| 318 | |
| 319 | $("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1)); |
| 320 | $("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1)); |
| 321 | $("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY)); |
| 322 | $("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY)); |
| 323 | $("open").addEventListener("change", () => |
| 324 | { |
| 325 | if (draft) |
| 326 | { |
| 327 | draft.open = $("open").checked; |
| 328 | view.setChunkOpen(chunkX, chunkY, draft.open); |
| 329 | } |
| 330 | }); |
| 331 | $("save").addEventListener("click", () => |
| 332 | { |
| 333 | $("error").textContent = ""; |
| 334 | socket.send({ |
| 335 | type: MessageType.editorSaveChunk, |
| 336 | chunkX, |
| 337 | chunkY, |
| 338 | draft: { open: $("open").checked, grounds: draft.grounds, blocks: draft.blocks } |
| 339 | }); |
| 340 | requestNeighbors(); |
| 341 | }); |
| 342 | $("apply").addEventListener("click", () => socket.send({ type: MessageType.editorApplyRevision })); |
| 343 | $("night").addEventListener("input", () => |
| 344 | { |
| 345 | view.nightPreview = Number($("night").value); |
| 346 | $("night-label").textContent = view.nightPreview.toFixed(1); |
| 347 | }); |
| 348 | |
| 349 | function cycleToolState (direction) |
| 350 | { |
| 351 | if (tool.kind === "erase") |
| 352 | { return; } |
| 353 | const layer = tool.kind === "ground" ? "ground" : "block"; |
| 354 | const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId]; |
| 355 | const states = statesForType(catalog, layer, def.key); |
| 356 | if (states.length < 2) |
| 357 | { return; } |
| 358 | tool.state = cycleState(states, tool.state, direction); |
| 359 | $("tool").textContent = selectedToolLabel(); |
| 360 | if (!draft || !hoverLocal) |
| 361 | { return; } |
| 362 | const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x; |
| 363 | if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId) |
| 364 | { paintAt(hoverLocal.x, hoverLocal.y); } |
| 365 | else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId) |
| 366 | { paintAt(hoverLocal.x, hoverLocal.y); } |
| 367 | } |
| 368 | |
| 369 | document.addEventListener("wheel", (event) => |
| 370 | { |
| 371 | if (!scene?.canvas || settingsModal?.isOpen()) |
| 372 | { return; } |
| 373 | const rect = scene.canvas.getBoundingClientRect(); |
| 374 | if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom) |
| 375 | { return; } |
| 376 | event.preventDefault(); |
| 377 | cycleToolState(event.deltaY < 0 ? 1 : -1); |
| 378 | if (hoverLocal) |
| 379 | { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); } |
| 380 | }, { passive: false }); |
| 381 | |
| 382 | main().catch((error) => |
| 383 | { |
| 384 | $("error").textContent = error.message; |
| 385 | console.error(error); |
| 386 | }); |