BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

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