BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 5.9 KiB Download Raw
1import { MessageType, CHUNK_SIZE } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, BlockType } from "/shared/definitions/tiles.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { PLAY_IMAGES, assertSpriteSizes, 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 paintAt (localX, localY)
31{
32 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
33 { return; }
34 const index = localY * CHUNK_SIZE + localX;
35 if (tool.kind === "ground")
36 { draft.grounds[index] = tool.typeId; }
37 else if (tool.kind === "erase")
38 { draft.blocks[index] = null; }
39 else
40 { draft.blocks[index] = { typeId: tool.typeId, config: null }; }
41 view.applySnapshot({
42 chunkX,
43 chunkY,
44 grounds: draft.grounds,
45 blocks: draft.blocks,
46 light: draft.light,
47 entities: []
48 });
49}
50
51function showChunk (payload)
52{
53 draft = {
54 open: payload.data.open,
55 grounds: payload.data.grounds.slice(),
56 blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)),
57 light: payload.data.light.slice()
58 };
59 chunkX = payload.chunkX;
60 chunkY = payload.chunkY;
61 $("coords").textContent = `${chunkX}, ${chunkY}`;
62 $("open").checked = draft.open;
63 $("revision").textContent = `active ${payload.activeRevisionId}` +
64 (payload.pendingRevisionId ? ` · pending ${payload.pendingRevisionId}` : " · no pending revision");
65 $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)";
66 const log = $("changelog");
67 log.innerHTML = "";
68 for (const entry of payload.changelog ?? [])
69 {
70 const item = document.createElement("article");
71 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
72 const list = document.createElement("ul");
73 for (const bullet of entry.diffEntries)
74 {
75 const li = document.createElement("li");
76 li.textContent = bullet;
77 list.append(li);
78 }
79 item.append(list);
80 log.append(item);
81 }
82 view.applySnapshot({
83 chunkX,
84 chunkY,
85 grounds: draft.grounds,
86 blocks: draft.blocks,
87 light: draft.light,
88 entities: []
89 });
90 frameChunk();
91}
92
93function frameChunk ()
94{
95 const size = view.tileSize();
96 view.followPlayer = false;
97 view.scene.cameraPosition.x = 24 - (chunkX * CHUNK_SIZE * size);
98 view.scene.cameraPosition.y = 24 - (chunkY * CHUNK_SIZE * size);
99}
100
101function loadChunk (x, y)
102{
103 socket.send({ type: MessageType.editorLoadChunk, chunkX: x, chunkY: y });
104}
105
106async function main ()
107{
108 await game.preloadImages(PLAY_IMAGES);
109 assertSpriteSizes(game.images);
110 const canvasSize = CHUNK_SIZE * 16 * 2 + 48;
111 scene = new Scene(260, 56, canvasSize, canvasSize);
112 game.loadScene(scene);
113 useNearestNeighbour(scene, game.images);
114 view = new WorldView(game, scene);
115 view.followPlayer = false;
116 view.setZoom(2);
117 const ticker = new GameObject(0, 0, null, 10);
118 ticker.update = (dt) =>
119 {
120 if (GameInput.mouseHeld(GameInput.MouseButtons.Left) && draft)
121 {
122 const canvas = scene.canvas;
123 const rect = canvas.getBoundingClientRect();
124 const mouseX = GameInput.mousePosition.x - rect.left;
125 const mouseY = GameInput.mousePosition.y - rect.top;
126 if (mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height)
127 {
128 const tile = view.screenToTile(mouseX, mouseY);
129 paintAt(tile.tileX - chunkX * CHUNK_SIZE, tile.tileY - chunkY * CHUNK_SIZE);
130 }
131 }
132 view.update(dt);
133 frameChunk();
134 };
135 scene.addObject(ticker);
136 game.startGame();
137
138 socket = new GameSocket(defaultSocketUrl(), (message) =>
139 {
140 if (message.type === MessageType.session)
141 {
142 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
143 loadChunk(0, 0);
144 }
145 else if (message.type === MessageType.editorChunk)
146 {
147 if (message.settingsSaved)
148 {
149 $("revision").textContent = `settings saved on pending ${message.settingsSaved.revisionId}`;
150 return;
151 }
152 showChunk(message);
153 }
154 else if (message.type === MessageType.error)
155 { $("error").textContent = message.message; }
156 });
157 await socket.connect();
158}
159
160$("tool").textContent = selectedToolLabel();
161document.querySelectorAll("[data-tool]").forEach((button) =>
162{
163 button.addEventListener("click", () =>
164 {
165 tool = JSON.parse(button.dataset.tool);
166 $("tool").textContent = selectedToolLabel();
167 });
168});
169
170$("north").addEventListener("click", () => loadChunk(chunkX, chunkY - 1));
171$("south").addEventListener("click", () => loadChunk(chunkX, chunkY + 1));
172$("west").addEventListener("click", () => loadChunk(chunkX - 1, chunkY));
173$("east").addEventListener("click", () => loadChunk(chunkX + 1, chunkY));
174$("open").addEventListener("change", () =>
175{
176 if (draft)
177 { draft.open = $("open").checked; }
178});
179$("save").addEventListener("click", () =>
180{
181 $("error").textContent = "";
182 socket.send({
183 type: MessageType.editorSaveChunk,
184 chunkX,
185 chunkY,
186 draft: { open: $("open").checked, grounds: draft.grounds, blocks: draft.blocks }
187 });
188});
189$("apply").addEventListener("click", () => socket.send({ type: MessageType.editorApplyRevision }));
190$("night").addEventListener("input", () =>
191{
192 view.nightPreview = Number($("night").value);
193 $("night-label").textContent = view.nightPreview.toFixed(1);
194});
195$("save-settings").addEventListener("click", () =>
196{
197 socket.send({
198 type: MessageType.editorSaveSettings,
199 settings: {
200 walkTilesPerSecond: Number($("walk-speed").value),
201 simulationTickHz: Number($("tick-hz").value)
202 }
203 });
204});
205
206main().catch((error) =>
207{
208 $("error").textContent = error.message;
209 console.error(error);
210});