import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js"; import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType } from "/shared/definitions/tiles.js"; import { GameSocket, defaultSocketUrl } from "../net/socket.js"; import { PLAY_IMAGES, assertSpriteSizes, useNearestNeighbour } from "../render/sprites.js"; import { WorldView } from "../render/worldView.js"; const game = new Game(); let socket; let scene; let view; let draft = null; let chunkX = 0; let chunkY = 0; let tool = { kind: "ground", typeId: GroundType.grass }; function $ (id) { return document.getElementById(id); } function selectedToolLabel () { if (tool.kind === "erase") { return "Erase block"; } if (tool.kind === "ground") { return GROUND_DEFINITIONS[tool.typeId].displayName; } return BLOCK_DEFINITIONS[tool.typeId].displayName; } function inEditorView (x, y) { return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS; } function neighborhoodCoords (centerX, centerY) { const coords = []; for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++) { for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++) { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); } } return coords; } function snapshotFromPayload (payload) { return { chunkX: payload.chunkX, chunkY: payload.chunkY, grounds: payload.data.grounds, blocks: payload.data.blocks, light: payload.data.light, entities: [] }; } function paintAt (localX, localY) { if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) { return; } const index = localY * CHUNK_SIZE + localX; if (tool.kind === "ground") { draft.grounds[index] = tool.typeId; } else if (tool.kind === "erase") { draft.blocks[index] = null; } else { draft.blocks[index] = { typeId: tool.typeId, config: null }; } view.applySnapshot({ chunkX, chunkY, grounds: draft.grounds, blocks: draft.blocks, light: draft.light, entities: [] }); } function showSelectedChunk (payload) { draft = { open: payload.data.open, grounds: payload.data.grounds.slice(), blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)), light: payload.data.light.slice() }; $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`; $("open").checked = draft.open; $("revision").textContent = `active ${payload.activeRevisionId}` + (payload.pendingRevisionId ? ` · pending ${payload.pendingRevisionId}` : " · no pending revision"); $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)"; const log = $("changelog"); log.innerHTML = ""; for (const entry of payload.changelog ?? []) { const item = document.createElement("article"); item.innerHTML = `
${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}
`; const list = document.createElement("ul"); for (const bullet of entry.diffEntries) { const li = document.createElement("li"); li.textContent = bullet; list.append(li); } item.append(list); log.append(item); } view.applySnapshot(snapshotFromPayload(payload)); } function pruneView () { for (const key of [...view.chunks.keys()]) { const [x, y] = key.split(",").map(Number); if (!inEditorView(x, y)) { view.removeChunk(x, y); } } } function frameNeighborhood () { const size = view.tileSize(); view.followPlayer = false; const centerX = (chunkX + 0.5) * CHUNK_SIZE * size; const centerY = (chunkY + 0.5) * CHUNK_SIZE * size; view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX; view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY; updateSelectionBorder(); } function updateSelectionBorder () { const border = $("selection-border"); const canvas = scene?.canvas; if (!border || !canvas) { return; } const rect = canvas.getBoundingClientRect(); const size = view.tileSize(); const chunkPx = CHUNK_SIZE * size; const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x; const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y; border.style.left = `${rect.left + screenLeft}px`; border.style.top = `${rect.top + screenTop}px`; border.style.width = `${chunkPx}px`; border.style.height = `${chunkPx}px`; } function layoutScene () { const header = document.querySelector("header"); const aside = document.querySelector("aside"); const changelog = $("changelog-wrap"); const top = header.offsetHeight; aside.style.top = `${top}px`; changelog.style.top = `${top}px`; const left = aside.offsetWidth; const right = changelog.offsetWidth; const width = Math.max(64, window.innerWidth - left - right); const height = Math.max(64, window.innerHeight - top); scene.position.x = left; scene.position.y = top; scene.size.x = width; scene.size.y = height; scene.g_fixSize(); useNearestNeighbour(scene, game.images); const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX); view.setZoom(fit, { min: 0.5, max: 4 }); frameNeighborhood(); } function requestChunks (coords) { for (const coord of coords) { socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY }); } } function loadNeighborhood (x, y) { chunkX = x; chunkY = y; $("coords").textContent = `${chunkX}, ${chunkY}`; requestChunks(neighborhoodCoords(x, y)); } function requestNeighbors () { requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY)); } async function main () { await game.preloadImages(PLAY_IMAGES); assertSpriteSizes(game.images); scene = new Scene(250, 56, 64, 64); game.loadScene(scene); useNearestNeighbour(scene, game.images); view = new WorldView(game, scene); view.followPlayer = false; layoutScene(); const ticker = new GameObject(0, 0, null, 10); ticker.update = (dt) => { if (GameInput.mouseHeld(GameInput.MouseButtons.Left) && draft) { const canvas = scene.canvas; const rect = canvas.getBoundingClientRect(); const mouseX = GameInput.mousePosition.x - rect.left; const mouseY = GameInput.mousePosition.y - rect.top; if (mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height) { const tile = view.screenToTile(mouseX, mouseY); paintAt(tile.tileX - chunkX * CHUNK_SIZE, tile.tileY - chunkY * CHUNK_SIZE); } } view.update(dt); frameNeighborhood(); }; scene.addObject(ticker); game.startGame(); window.addEventListener("resize", layoutScene); socket = new GameSocket(defaultSocketUrl(), (message) => { if (message.type === MessageType.session) { $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`; loadNeighborhood(0, 0); } else if (message.type === MessageType.editorChunk) { if (message.settingsSaved) { $("revision").textContent = `settings saved on pending ${message.settingsSaved.revisionId}`; return; } if (!inEditorView(message.chunkX, message.chunkY)) { return; } if (message.chunkX === chunkX && message.chunkY === chunkY) { showSelectedChunk(message); } else { view.applySnapshot(snapshotFromPayload(message)); } pruneView(); } else if (message.type === MessageType.error) { $("error").textContent = message.message; } }); await socket.connect(); } $("tool").textContent = selectedToolLabel(); document.querySelectorAll("[data-tool]").forEach((button) => { button.addEventListener("click", () => { tool = JSON.parse(button.dataset.tool); $("tool").textContent = selectedToolLabel(); }); }); $("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1)); $("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1)); $("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY)); $("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY)); $("open").addEventListener("change", () => { if (draft) { draft.open = $("open").checked; } }); $("save").addEventListener("click", () => { $("error").textContent = ""; socket.send({ type: MessageType.editorSaveChunk, chunkX, chunkY, draft: { open: $("open").checked, grounds: draft.grounds, blocks: draft.blocks } }); requestNeighbors(); }); $("apply").addEventListener("click", () => socket.send({ type: MessageType.editorApplyRevision })); $("night").addEventListener("input", () => { view.nightPreview = Number($("night").value); $("night-label").textContent = view.nightPreview.toFixed(1); }); $("save-settings").addEventListener("click", () => { socket.send({ type: MessageType.editorSaveSettings, settings: { walkTilesPerSecond: Number($("walk-speed").value), simulationTickHz: Number($("tick-hz").value) } }); }); main().catch((error) => { $("error").textContent = error.message; console.error(error); });