BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 15.1 KiB Download Raw
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, BlockType, GroundType, normalizeGround } from "/shared/definitions/tiles.js";
3import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
4import { GameSocket, defaultSocketUrl } from "../net/socket.js";
5import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
6import { WorldView } from "../render/worldView.js";
7import { initSettingsModal } from "./settingsModal.js";
8
9const game = new Game();
10let socket;
11let scene;
12let view;
13let draft = null;
14let chunkX = 0;
15let chunkY = 0;
16let tool = { kind: "ground", typeId: GroundType.grass, state: null };
17let settingsModal;
18let catalog = { grounds: {}, blocks: {} };
19let hoverLocal = null;
20let editorZoom = null;
21let activeRevisionId = null;
22let pendingRevisionId = null;
23let applyInFlight = false;
24const EDITOR_ZOOM_MIN = 0.25;
25const EDITOR_ZOOM_MAX = 8;
26const EDITOR_ZOOM_STEP = 1.12;
27
28function $ (id)
29{
30 return document.getElementById(id);
31}
32
33function selectedToolLabel ()
34{
35 if (tool.kind === "erase")
36 { return "Erase block"; }
37 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
38 const layer = tool.kind === "ground" ? "ground" : "block";
39 const states = statesForType(catalog, layer, def.key);
40 const state = resolveState(states, tool.state);
41 if (states.length > 1)
42 { return `${def.displayName} (${state})`; }
43 return def.displayName;
44}
45
46function selectTool (next)
47{
48 if (next.kind === "erase")
49 {
50 tool = { kind: "erase" };
51 return;
52 }
53 const layer = next.kind === "ground" ? "ground" : "block";
54 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
55 tool = {
56 kind: next.kind,
57 typeId: next.typeId,
58 state: defaultStateForType(catalog, layer, def.key)
59 };
60}
61
62function placeableToolState ()
63{
64 if (tool.kind === "erase")
65 { return null; }
66 const layer = tool.kind === "ground" ? "ground" : "block";
67 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
68 return resolveState(statesForType(catalog, layer, def.key), tool.state);
69}
70
71function previewFromTool ()
72{
73 if (tool.kind === "erase")
74 { return { block: null }; }
75 const state = placeableToolState();
76 if (tool.kind === "ground")
77 { return { ground: { typeId: tool.typeId, state } }; }
78 return { block: { typeId: tool.typeId, state, config: null } };
79}
80
81function inEditorView (x, y)
82{
83 return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS;
84}
85
86function neighborhoodCoords (centerX, centerY)
87{
88 const coords = [];
89 for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++)
90 {
91 for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++)
92 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
93 }
94 return coords;
95}
96
97function snapshotFromPayload (payload)
98{
99 return {
100 chunkX: payload.chunkX,
101 chunkY: payload.chunkY,
102 open: payload.data.open,
103 closedEdges: payload.closedEdges,
104 grounds: payload.data.grounds,
105 blocks: payload.data.blocks,
106 light: payload.data.light,
107 entities: []
108 };
109}
110
111function paintAt (localX, localY)
112{
113 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
114 { return; }
115 const index = localY * CHUNK_SIZE + localX;
116 const state = placeableToolState();
117 if (tool.kind === "ground")
118 { draft.grounds[index] = { typeId: tool.typeId, state }; }
119 else if (tool.kind === "erase")
120 { draft.blocks[index] = null; }
121 else
122 {
123 const existing = draft.blocks[index];
124 let config = null;
125 if (tool.typeId === BlockType.spawner)
126 {
127 const spawnerId = existing?.typeId === BlockType.spawner && existing.config?.spawnerId
128 ? existing.config.spawnerId
129 : `${chunkX}:${chunkY}:${index}`;
130 config = {
131 spawnerId,
132 mobTypeId: $("spawner-mob")?.value || "deer",
133 maxAlive: Number($("spawner-max")?.value || 3),
134 spawnRangeTiles: Number($("spawner-range")?.value || 4)
135 };
136 }
137 draft.blocks[index] = { typeId: tool.typeId, state, config };
138 }
139 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
140 ground: draft.grounds[index],
141 block: draft.blocks[index],
142 light: draft.light[index]
143 });
144}
145
146function updateRevisionUI ()
147{
148 const applyBtn = $("apply");
149 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
150 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
151 if (applyBtn)
152 {
153 applyBtn.disabled = !pendingRevisionId || applyInFlight;
154 applyBtn.title = pendingRevisionId
155 ? "Reload the live world with the pending map revision"
156 : "Save a chunk first to create a pending revision";
157 }
158}
159
160function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
161{
162 if (active != null)
163 { activeRevisionId = active; }
164 pendingRevisionId = pending ?? null;
165 updateRevisionUI();
166}
167
168function showSelectedChunk (payload)
169{
170 draft = {
171 open: payload.data.open,
172 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
173 blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)),
174 light: payload.data.light.slice()
175 };
176 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
177 $("open").checked = draft.open;
178 setRevisionState({
179 activeRevisionId: payload.activeRevisionId,
180 pendingRevisionId: payload.pendingRevisionId
181 });
182 $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)";
183 const log = $("changelog");
184 log.innerHTML = "";
185 for (const entry of payload.changelog ?? [])
186 {
187 const item = document.createElement("article");
188 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
189 const list = document.createElement("ul");
190 for (const bullet of entry.diffEntries)
191 {
192 const li = document.createElement("li");
193 li.textContent = bullet;
194 list.append(li);
195 }
196 item.append(list);
197 log.append(item);
198 }
199 view.applySnapshot(snapshotFromPayload(payload));
200}
201
202function pruneView ()
203{
204 for (const key of [...view.chunks.keys()])
205 {
206 const [x, y] = key.split(",").map(Number);
207 if (!inEditorView(x, y))
208 { view.removeChunk(x, y); }
209 }
210}
211
212function frameNeighborhood ()
213{
214 const size = view.tileSize();
215 view.followPlayer = false;
216 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
217 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
218 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
219 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
220 updateSelectionBorder();
221}
222
223function updateSelectionBorder ()
224{
225 const border = $("selection-border");
226 const canvas = scene?.canvas;
227 if (!border || !canvas)
228 { return; }
229
230 const rect = canvas.getBoundingClientRect();
231 const size = view.tileSize();
232 const chunkPx = CHUNK_SIZE * size;
233 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
234 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
235 border.style.left = `${rect.left + screenLeft}px`;
236 border.style.top = `${rect.top + screenTop}px`;
237 border.style.width = `${chunkPx}px`;
238 border.style.height = `${chunkPx}px`;
239}
240
241function layoutScene ()
242{
243 const header = document.querySelector("body > header");
244 const aside = document.querySelector("body > aside");
245 const changelog = $("changelog-wrap");
246 const top = header.offsetHeight;
247 aside.style.top = `${top}px`;
248 changelog.style.top = `${top}px`;
249 const left = aside.offsetWidth;
250 const right = changelog.offsetWidth;
251 const width = Math.max(64, window.innerWidth - left - right);
252 const height = Math.max(64, window.innerHeight - top);
253 scene.position.x = left;
254 scene.position.y = top;
255 scene.size.x = width;
256 scene.size.y = height;
257 scene.g_fixSize();
258 useNearestNeighbour(scene, game.images);
259 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
260 if (editorZoom == null)
261 { editorZoom = fit; }
262 else
263 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
264 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
265 frameNeighborhood();
266}
267
268function zoomEditor (direction)
269{
270 if (!view)
271 { return; }
272 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
273 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
274 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
275 frameNeighborhood();
276}
277
278function requestChunks (coords)
279{
280 for (const coord of coords)
281 {
282 socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY });
283 }
284}
285
286function loadNeighborhood (x, y)
287{
288 chunkX = x;
289 chunkY = y;
290 $("coords").textContent = `${chunkX}, ${chunkY}`;
291 requestChunks(neighborhoodCoords(x, y));
292}
293
294function requestNeighbors ()
295{
296 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
297}
298
299async function main ()
300{
301 catalog = await loadSpriteCatalog();
302 await preloadCatalogImages(game, catalog);
303 applySpriteSheets(game.images, catalog);
304 scene = new Scene(250, 56, 64, 64);
305 game.loadScene(scene);
306 useNearestNeighbour(scene, game.images);
307 view = new WorldView(game, scene, catalog);
308 view.followPlayer = false;
309 layoutScene();
310 selectTool(tool);
311 $("tool").textContent = selectedToolLabel();
312 const ticker = new GameObject(0, 0, null, 10);
313 ticker.update = (dt) =>
314 {
315 hoverLocal = null;
316 const canvas = scene.canvas;
317 const rect = canvas.getBoundingClientRect();
318 const mouseX = GameInput.mousePosition.x - rect.left;
319 const mouseY = GameInput.mousePosition.y - rect.top;
320 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
321 if (overCanvas && draft && !settingsModal?.isOpen())
322 {
323 const tile = view.screenToTile(mouseX, mouseY);
324 const localX = tile.tileX - chunkX * CHUNK_SIZE;
325 const localY = tile.tileY - chunkY * CHUNK_SIZE;
326 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
327 {
328 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
329 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
330 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
331 { paintAt(localX, localY); }
332 }
333 else
334 { view.clearTilePreview(); }
335 }
336 else
337 { view.clearTilePreview(); }
338 view.update(dt);
339 frameNeighborhood();
340 };
341 scene.addObject(ticker);
342 window.addEventListener("resize", layoutScene);
343
344 socket = new GameSocket(defaultSocketUrl(), (message) =>
345 {
346 if (message.type === MessageType.session)
347 {
348 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
349 socket.send({ type: MessageType.editorLoadSettings });
350 loadNeighborhood(0, 0);
351 }
352 else if (message.type === MessageType.editorSettings)
353 { settingsModal.handleMessage(message); }
354 else if (message.type === MessageType.editorChunk)
355 {
356 if (message.settings)
357 { view.setSettings(message.settings); }
358 if (!inEditorView(message.chunkX, message.chunkY))
359 { return; }
360 if (message.chunkX === chunkX && message.chunkY === chunkY)
361 { showSelectedChunk(message); }
362 else
363 { view.applySnapshot(snapshotFromPayload(message)); }
364 pruneView();
365 }
366 else if (message.type === MessageType.editorRevisionApplied)
367 {
368 applyInFlight = false;
369 setRevisionState({
370 activeRevisionId: message.activeRevisionId,
371 pendingRevisionId: message.pendingRevisionId
372 });
373 const status = $("apply-status");
374 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
375 status.className = "hint ok";
376 requestChunks(neighborhoodCoords(chunkX, chunkY));
377 }
378 else if (message.type === MessageType.error)
379 {
380 $("error").textContent = message.message;
381 if (applyInFlight)
382 {
383 applyInFlight = false;
384 $("apply-status").textContent = "";
385 $("apply-status").className = "hint";
386 updateRevisionUI();
387 }
388 }
389 });
390 settingsModal = initSettingsModal({
391 socket,
392 MessageType,
393 onApplied (settings)
394 {
395 view.setSettings(settings);
396 },
397 onPreviewNight (hour)
398 {
399 view.nightPreview = hour;
400 $("night").value = String(hour);
401 $("night-label").textContent = Number(hour).toFixed(1);
402 }
403 });
404 game.startGame();
405 await socket.connect();
406}
407
408$("tool").textContent = selectedToolLabel();
409document.querySelectorAll("[data-tool]").forEach((button) =>
410{
411 button.addEventListener("click", () =>
412 {
413 selectTool(JSON.parse(button.dataset.tool));
414 $("tool").textContent = selectedToolLabel();
415 });
416});
417
418$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
419$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
420$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
421$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
422$("open").addEventListener("change", () =>
423{
424 if (draft)
425 {
426 draft.open = $("open").checked;
427 view.setChunkOpen(chunkX, chunkY, draft.open);
428 }
429});
430$("save").addEventListener("click", () =>
431{
432 $("error").textContent = "";
433 $("apply-status").textContent = "";
434 $("apply-status").className = "hint";
435 socket.send({
436 type: MessageType.editorSaveChunk,
437 chunkX,
438 chunkY,
439 draft: { open: $("open").checked, grounds: draft.grounds, blocks: draft.blocks }
440 });
441 requestNeighbors();
442});
443$("apply").addEventListener("click", () =>
444{
445 if (!pendingRevisionId || applyInFlight)
446 { return; }
447 $("error").textContent = "";
448 const status = $("apply-status");
449 status.textContent = "Applying…";
450 status.className = "hint";
451 applyInFlight = true;
452 updateRevisionUI();
453 socket.send({ type: MessageType.editorApplyRevision });
454});
455$("night").addEventListener("input", () =>
456{
457 view.nightPreview = Number($("night").value);
458 $("night-label").textContent = view.nightPreview.toFixed(1);
459});
460
461function cycleToolState (direction)
462{
463 if (tool.kind === "erase")
464 { return; }
465 const layer = tool.kind === "ground" ? "ground" : "block";
466 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
467 const states = statesForType(catalog, layer, def.key);
468 if (states.length < 2)
469 { return; }
470 tool.state = cycleState(states, tool.state, direction);
471 $("tool").textContent = selectedToolLabel();
472 if (!draft || !hoverLocal)
473 { return; }
474 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
475 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
476 { paintAt(hoverLocal.x, hoverLocal.y); }
477 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
478 { paintAt(hoverLocal.x, hoverLocal.y); }
479}
480
481document.addEventListener("wheel", (event) =>
482{
483 if (!scene?.canvas || settingsModal?.isOpen())
484 { return; }
485 const rect = scene.canvas.getBoundingClientRect();
486 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
487 { return; }
488 event.preventDefault();
489 if (event.shiftKey)
490 {
491 cycleToolState(event.deltaY < 0 ? 1 : -1);
492 if (hoverLocal)
493 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
494 return;
495 }
496 zoomEditor(event.deltaY < 0 ? 1 : -1);
497}, { passive: false });
498
499main().catch((error) =>
500{
501 $("error").textContent = error.message;
502 console.error(error);
503});