BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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