BlueGit

timfa questward

Files

questward / client / src / editor / main.js

main.js

main.js 23.7 KiB Download Raw
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import {
3 GROUND_DEFINITIONS,
4 BLOCK_DEFINITIONS,
5 GroundType,
6 BlockType,
7 normalizeGround,
8 normalizeBlock,
9 listPlaceableBlockPaletteEntries
10} from "/shared/definitions/tiles.js";
11import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
12import {
13 SeasonId,
14 seasonIdAt,
15 seasonalCycleStates,
16 seasonIdFromVisualState,
17 placeableStatesForType
18} from "/shared/world/season.js";
19import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
20import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
21import {
22 computeNeighborConnectMask,
23 composeNeighborConnectState,
24 definitionUsesNeighborConnect,
25 neighborConnectBlocksMatch
26} from "/shared/world/neighborConnect.js";
27import { GameSocket, defaultSocketUrl } from "../net/socket.js";
28import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
29import { WorldView } from "../render/worldView.js";
30import { initSettingsModal } from "./settingsModal.js";
31import { initPaletteModal } from "./paletteModal.js";
32import { initTileConfigModal } from "./tileConfigModal.js";
33
34const game = new Game();
35let socket;
36let scene;
37let view;
38let draft = null;
39let chunkX = 0;
40let chunkY = 0;
41let tool = { kind: "ground", typeId: GroundType.grass, state: null };
42let settingsModal;
43let paletteModal;
44let tileConfigModal;
45let catalog = { grounds: {}, blocks: {}, images: [] };
46let imageUrlByName = new Map();
47let hoverLocal = null;
48let editorZoom = null;
49let activeRevisionId = null;
50let pendingRevisionId = null;
51let applyInFlight = false;
52const EDITOR_ZOOM_MIN = 0.25;
53const EDITOR_ZOOM_MAX = 8;
54const EDITOR_ZOOM_STEP = 1.12;
55
56function $ (id)
57{
58 return document.getElementById(id);
59}
60
61function selectedToolLabel ()
62{
63 if (tool.kind === "erase")
64 { return "Erase block"; }
65 if (tool.kind === "spawner")
66 {
67 const def = mobDefinition(tool.mobTypeId);
68 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
69 }
70 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
71 const layer = tool.kind === "ground" ? "ground" : "block";
72 const states = statesForType(catalog, layer, def.key);
73 const state = resolveState(states, tool.state);
74 if (tool.kind === "block" && def.id === BlockType.flower)
75 { return "Flower"; }
76 if (tool.kind === "block" && def.id === BlockType.boulder)
77 {
78 const entry = listPlaceableBlockPaletteEntries(catalog)
79 .find((row) => row.typeId === def.id && row.state === state);
80 if (entry)
81 { return entry.displayName; }
82 }
83 if (states.length > 1)
84 { return `${def.displayName} (${state})`; }
85 return def.displayName;
86}
87
88function selectTool (next)
89{
90 if (next.kind === "erase")
91 {
92 tool = { kind: "erase" };
93 return;
94 }
95 if (next.kind === "spawner")
96 {
97 tool = { kind: "spawner", mobTypeId: next.mobTypeId };
98 return;
99 }
100 const layer = next.kind === "ground" ? "ground" : "block";
101 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
102 tool = {
103 kind: next.kind,
104 typeId: next.typeId,
105 state: next.state ?? defaultStateForType(catalog, layer, def.key)
106 };
107}
108
109function placeableToolState ()
110{
111 if (tool.kind === "erase" || tool.kind === "spawner")
112 { return null; }
113 const layer = tool.kind === "ground" ? "ground" : "block";
114 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
115 return resolveState(statesForType(catalog, layer, def.key), tool.state);
116}
117
118function previewFromTool ()
119{
120 if (tool.kind === "erase")
121 { return { block: null }; }
122 if (tool.kind === "spawner")
123 { return {}; }
124 const state = placeableToolState();
125 if (tool.kind === "ground")
126 { return { ground: { typeId: tool.typeId, state } }; }
127 return { block: { typeId: tool.typeId, state, config: null } };
128}
129
130function inEditorView (x, y)
131{
132 return Math.abs(x - chunkX) <= VISIBLE_CHUNK_RADIUS && Math.abs(y - chunkY) <= VISIBLE_CHUNK_RADIUS;
133}
134
135function neighborhoodCoords (centerX, centerY)
136{
137 const coords = [];
138 for (let dy = -VISIBLE_CHUNK_RADIUS; dy <= VISIBLE_CHUNK_RADIUS; dy++)
139 {
140 for (let dx = -VISIBLE_CHUNK_RADIUS; dx <= VISIBLE_CHUNK_RADIUS; dx++)
141 { coords.push({ chunkX: centerX + dx, chunkY: centerY + dy }); }
142 }
143 return coords;
144}
145
146function snapshotFromPayload (payload)
147{
148 return {
149 chunkX: payload.chunkX,
150 chunkY: payload.chunkY,
151 open: payload.data.open,
152 closedEdges: payload.closedEdges,
153 grounds: payload.data.grounds,
154 blocks: payload.data.blocks,
155 light: payload.data.light,
156 entities: []
157 };
158}
159
160function syncSpawnersOverlay (cx, cy, spawners)
161{
162 view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
163}
164
165function spawnerAt (localX, localY)
166{
167 return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
168}
169
170function paintAt (localX, localY)
171{
172 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
173 { return; }
174 const index = localY * CHUNK_SIZE + localX;
175 const state = placeableToolState();
176 if (tool.kind === "ground")
177 { draft.grounds[index] = { typeId: tool.typeId, state }; }
178 else if (tool.kind === "erase")
179 {
180 const removed = draft.blocks[index];
181 draft.blocks[index] = null;
182 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
183 ground: draft.grounds[index],
184 block: draft.blocks[index],
185 light: draft.light[index]
186 });
187 if (removed && definitionUsesNeighborConnect(BLOCK_DEFINITIONS[removed.typeId]))
188 { refreshNeighborConnect(localX, localY, removed.typeId); }
189 return;
190 }
191 else if (tool.kind === "spawner")
192 {
193 const existing = spawnerAt(localX, localY);
194 const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`;
195 const entry = {
196 localX,
197 localY,
198 config: normalizeSpawnerConfig({
199 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
200 ...(existing?.config ?? {}),
201 spawnerId,
202 mobTypeId: tool.mobTypeId
203 }, spawnerId)
204 };
205 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
206 draft.spawners.push(entry);
207 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
208 return;
209 }
210 else
211 {
212 const def = BLOCK_DEFINITIONS[tool.typeId];
213 let nextState = definitionUsesNeighborConnect(def)
214 ? composeNeighborConnectState(def, state, 0)
215 : state;
216 if (def?.id === BlockType.flower)
217 { nextState = flowerBlockState(randomFlowerColorId()); }
218 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null };
219 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
220 ground: draft.grounds[index],
221 block: draft.blocks[index],
222 light: draft.light[index]
223 });
224 if (definitionUsesNeighborConnect(def))
225 { refreshNeighborConnect(localX, localY, tool.typeId); }
226 return;
227 }
228 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
229 ground: draft.grounds[index],
230 block: draft.blocks[index],
231 light: draft.light[index]
232 });
233}
234
235/** Recompute neighbor-connect masks for a type around a local tile (same chunk). */
236function refreshNeighborConnect (localX, localY, typeId)
237{
238 const def = BLOCK_DEFINITIONS[typeId];
239 if (!draft || !definitionUsesNeighborConnect(def))
240 { return; }
241 const cells = [[localX, localY]];
242 for (const [dx, dy] of [[0, -1], [1, 0], [0, 1], [-1, 0]])
243 { cells.push([localX + dx, localY + dy]); }
244 for (const [lx, ly] of cells)
245 {
246 if (lx < 0 || ly < 0 || lx >= CHUNK_SIZE || ly >= CHUNK_SIZE)
247 { continue; }
248 const index = ly * CHUNK_SIZE + lx;
249 const block = draft.blocks[index];
250 if (!block || block.typeId !== typeId)
251 { continue; }
252 const mask = computeNeighborConnectMask((dx, dy) =>
253 {
254 const nx = lx + dx;
255 const ny = ly + dy;
256 if (nx < 0 || ny < 0 || nx >= CHUNK_SIZE || ny >= CHUNK_SIZE)
257 { return false; }
258 const neighbor = draft.blocks[ny * CHUNK_SIZE + nx];
259 return neighborConnectBlocksMatch(block, neighbor, def);
260 });
261 block.state = composeNeighborConnectState(def, block.state, mask);
262 view.updateAuthoredTile(chunkX, chunkY, lx, ly, {
263 ground: draft.grounds[index],
264 block: draft.blocks[index],
265 light: draft.light[index]
266 });
267 }
268}
269
270function updateRevisionUI ()
271{
272 const applyBtn = $("apply");
273 $("revision").textContent = `active ${activeRevisionId ?? "?"}` +
274 (pendingRevisionId ? ` · pending ${pendingRevisionId}` : " · no pending revision");
275 if (applyBtn)
276 {
277 applyBtn.disabled = !pendingRevisionId || applyInFlight;
278 applyBtn.title = pendingRevisionId
279 ? "Reload the live world with the pending map revision"
280 : "Save a chunk first to create a pending revision";
281 }
282}
283
284function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pending })
285{
286 if (active != null)
287 { activeRevisionId = active; }
288 pendingRevisionId = pending ?? null;
289 updateRevisionUI();
290}
291
292function showSelectedChunk (payload)
293{
294 draft = {
295 open: payload.data.open,
296 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
297 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
298 light: payload.data.light.slice(),
299 spawners: (payload.data.spawners ?? []).map((entry) => ({
300 localX: entry.localX,
301 localY: entry.localY,
302 config: { ...entry.config }
303 }))
304 };
305 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
306 $("open").checked = draft.open;
307 setRevisionState({
308 activeRevisionId: payload.activeRevisionId,
309 pendingRevisionId: payload.pendingRevisionId
310 });
311 $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)";
312 const log = $("changelog");
313 log.innerHTML = "";
314 for (const entry of payload.changelog ?? [])
315 {
316 const item = document.createElement("article");
317 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
318 const list = document.createElement("ul");
319 for (const bullet of entry.diffEntries)
320 {
321 const li = document.createElement("li");
322 li.textContent = bullet;
323 list.append(li);
324 }
325 item.append(list);
326 log.append(item);
327 }
328 view.applySnapshot(snapshotFromPayload(payload));
329 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
330}
331
332function pruneView ()
333{
334 for (const key of [...view.chunks.keys()])
335 {
336 const [x, y] = key.split(",").map(Number);
337 if (!inEditorView(x, y))
338 { view.removeChunk(x, y); }
339 }
340}
341
342function frameNeighborhood ()
343{
344 const size = view.tileSize();
345 view.followPlayer = false;
346 const centerX = (chunkX + 0.5) * CHUNK_SIZE * size;
347 const centerY = (chunkY + 0.5) * CHUNK_SIZE * size;
348 view.scene.cameraPosition.x = view.scene.real_size.x / 2 - centerX;
349 view.scene.cameraPosition.y = view.scene.real_size.y / 2 - centerY;
350 updateSelectionBorder();
351}
352
353function updateSelectionBorder ()
354{
355 const border = $("selection-border");
356 const canvas = scene?.canvas;
357 if (!border || !canvas)
358 { return; }
359
360 const rect = canvas.getBoundingClientRect();
361 const size = view.tileSize();
362 const chunkPx = CHUNK_SIZE * size;
363 const screenLeft = chunkX * CHUNK_SIZE * size + scene.cameraPosition.x;
364 const screenTop = chunkY * CHUNK_SIZE * size + scene.cameraPosition.y;
365 border.style.left = `${rect.left + screenLeft}px`;
366 border.style.top = `${rect.top + screenTop}px`;
367 border.style.width = `${chunkPx}px`;
368 border.style.height = `${chunkPx}px`;
369}
370
371function layoutScene ()
372{
373 const header = document.querySelector("body > header");
374 const aside = document.querySelector("body > aside");
375 const changelog = $("changelog-wrap");
376 const top = header.offsetHeight;
377 aside.style.top = `${top}px`;
378 changelog.style.top = `${top}px`;
379 const left = aside.offsetWidth;
380 const right = changelog.offsetWidth;
381 const width = Math.max(64, window.innerWidth - left - right);
382 const height = Math.max(64, window.innerHeight - top);
383 scene.position.x = left;
384 scene.position.y = top;
385 scene.size.x = width;
386 scene.size.y = height;
387 scene.g_fixSize();
388 useNearestNeighbour(scene, game.images);
389 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
390 if (editorZoom == null)
391 { editorZoom = fit; }
392 else
393 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
394 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
395 frameNeighborhood();
396}
397
398function zoomEditor (direction)
399{
400 if (!view)
401 { return; }
402 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
403 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
404 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
405 useNearestNeighbour(scene, game.images);
406 frameNeighborhood();
407}
408
409function requestChunks (coords)
410{
411 for (const coord of coords)
412 {
413 socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY });
414 }
415}
416
417function loadNeighborhood (x, y)
418{
419 chunkX = x;
420 chunkY = y;
421 $("coords").textContent = `${chunkX}, ${chunkY}`;
422 requestChunks(neighborhoodCoords(x, y));
423}
424
425function requestNeighbors ()
426{
427 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
428}
429
430function anyModalOpen ()
431{
432 return settingsModal?.isOpen() || paletteModal?.isOpen() || tileConfigModal?.isOpen();
433}
434
435function updateTooltip (local)
436{
437 const tip = $("tile-tooltip");
438 if (!tip || !local || !draft)
439 {
440 if (tip)
441 { tip.hidden = true; }
442 view?.clearSpawnRangeHighlight();
443 return;
444 }
445 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
446 const spawner = spawnerAt(local.x, local.y);
447 const lines = [];
448 if (block)
449 {
450 const def = BLOCK_DEFINITIONS[block.typeId];
451 lines.push(def?.displayName ?? `Block ${block.typeId}`);
452 if (block.config && Object.keys(block.config).length)
453 {
454 for (const [key, value] of Object.entries(block.config))
455 { lines.push(`${key}: ${value}`); }
456 }
457 }
458 if (spawner)
459 {
460 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
461 const mob = mobDefinition(config.mobTypeId);
462 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
463 lines.push(`maxAlive: ${config.maxAlive}`);
464 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
465 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
466 lines.push(`id: ${config.spawnerId}`);
467 view.setSpawnRangeHighlight(
468 local.tileX,
469 local.tileY,
470 config.spawnRangeTiles,
471 config.maxWanderRangeTiles
472 );
473 }
474 else
475 { view.clearSpawnRangeHighlight(); }
476 if (!lines.length)
477 {
478 tip.hidden = true;
479 return;
480 }
481 tip.hidden = false;
482 tip.textContent = lines.join("\n");
483 const canvas = scene.canvas;
484 const rect = canvas.getBoundingClientRect();
485 const size = view.tileSize();
486 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
487 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
488 tip.style.left = `${screenX}px`;
489 tip.style.top = `${screenY}px`;
490}
491
492async function main ()
493{
494 catalog = await loadSpriteCatalog();
495 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
496 await preloadCatalogImages(game, catalog);
497 applySpriteSheets(game.images, catalog);
498 scene = new Scene(250, 56, 64, 64);
499 game.loadScene(scene);
500 useNearestNeighbour(scene, game.images);
501 view = new WorldView(game, scene, catalog);
502 view.followPlayer = false;
503 syncSeasonControls(view.worldSeason ?? seasonIdAt());
504 layoutScene();
505 selectTool(tool);
506 $("tool").textContent = selectedToolLabel();
507
508 paletteModal = initPaletteModal({
509 catalog,
510 imageUrlFor (name)
511 {
512 const sprite = game.images[name];
513 const html = sprite?.g_image;
514 if (html && typeof html.toDataURL === "function")
515 {
516 try
517 { return html.toDataURL("image/png"); }
518 catch (_)
519 { /* fall through */ }
520 }
521 return imageUrlByName.get(name) ?? null;
522 },
523 onSelect (next)
524 {
525 selectTool(next);
526 $("tool").textContent = selectedToolLabel();
527 }
528 });
529
530 tileConfigModal = initTileConfigModal({
531 onSave (ctx, config)
532 {
533 if (!draft)
534 { return; }
535 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
536 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
537 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
538 },
539 onRemove (ctx)
540 {
541 if (!draft)
542 { return; }
543 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
544 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
545 }
546 });
547
548 const ticker = new GameObject(0, 0, null, 10);
549 ticker.update = (dt) =>
550 {
551 hoverLocal = null;
552 const canvas = scene.canvas;
553 const rect = canvas.getBoundingClientRect();
554 const mouseX = GameInput.mousePosition.x - rect.left;
555 const mouseY = GameInput.mousePosition.y - rect.top;
556 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
557 if (overCanvas && draft && !anyModalOpen())
558 {
559 const tile = view.screenToTile(mouseX, mouseY);
560 const localX = tile.tileX - chunkX * CHUNK_SIZE;
561 const localY = tile.tileY - chunkY * CHUNK_SIZE;
562 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
563 {
564 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
565 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
566 updateTooltip(hoverLocal);
567 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
568 { paintAt(localX, localY); }
569 }
570 else
571 {
572 view.clearTilePreview();
573 updateTooltip(null);
574 }
575 }
576 else
577 {
578 view.clearTilePreview();
579 updateTooltip(null);
580 }
581 view.update(dt);
582 frameNeighborhood();
583 };
584 scene.addObject(ticker);
585 window.addEventListener("resize", layoutScene);
586
587 socket = new GameSocket(defaultSocketUrl(), (message) =>
588 {
589 if (message.type === MessageType.session)
590 {
591 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
592 socket.send({ type: MessageType.editorLoadSettings });
593 loadNeighborhood(0, 0);
594 }
595 else if (message.type === MessageType.editorSettings)
596 { settingsModal.handleMessage(message); }
597 else if (message.type === MessageType.editorChunk)
598 {
599 if (message.settings)
600 { view.setSettings(message.settings); }
601 if (!inEditorView(message.chunkX, message.chunkY))
602 { return; }
603 if (message.chunkX === chunkX && message.chunkY === chunkY)
604 { showSelectedChunk(message); }
605 else
606 {
607 view.applySnapshot(snapshotFromPayload(message));
608 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
609 }
610 pruneView();
611 }
612 else if (message.type === MessageType.editorRevisionApplied)
613 {
614 applyInFlight = false;
615 setRevisionState({
616 activeRevisionId: message.activeRevisionId,
617 pendingRevisionId: message.pendingRevisionId
618 });
619 const status = $("apply-status");
620 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
621 status.className = "hint ok";
622 requestChunks(neighborhoodCoords(chunkX, chunkY));
623 }
624 else if (message.type === MessageType.error)
625 {
626 $("error").textContent = message.message;
627 if (applyInFlight)
628 {
629 applyInFlight = false;
630 $("apply-status").textContent = "";
631 $("apply-status").className = "hint";
632 updateRevisionUI();
633 }
634 }
635 });
636 settingsModal = initSettingsModal({
637 socket,
638 MessageType,
639 onApplied (settings)
640 {
641 view.setSettings(settings);
642 },
643 onPreviewNight (hour)
644 {
645 view.nightPreview = hour;
646 $("night").value = String(hour);
647 $("night-label").textContent = Number(hour).toFixed(1);
648 }
649 });
650 game.startGame();
651 await socket.connect();
652}
653
654$("tool").textContent = selectedToolLabel();
655$("tool-erase").addEventListener("click", () =>
656{
657 selectTool({ kind: "erase" });
658 $("tool").textContent = selectedToolLabel();
659});
660
661$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
662$("south").addEventListener("click", () => loadNeighborhood(chunkX, chunkY + 1));
663$("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
664$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
665$("open").addEventListener("change", () =>
666{
667 if (draft)
668 {
669 draft.open = $("open").checked;
670 view.setChunkOpen(chunkX, chunkY, draft.open);
671 }
672});
673$("save").addEventListener("click", () =>
674{
675 $("error").textContent = "";
676 $("apply-status").textContent = "";
677 $("apply-status").className = "hint";
678 socket.send({
679 type: MessageType.editorSaveChunk,
680 chunkX,
681 chunkY,
682 draft: {
683 open: $("open").checked,
684 grounds: draft.grounds,
685 blocks: draft.blocks,
686 spawners: draft.spawners ?? []
687 }
688 });
689 requestNeighbors();
690});
691$("apply").addEventListener("click", () =>
692{
693 if (!pendingRevisionId || applyInFlight)
694 { return; }
695 $("error").textContent = "";
696 const status = $("apply-status");
697 status.textContent = "Applying…";
698 status.className = "hint";
699 applyInFlight = true;
700 updateRevisionUI();
701 socket.send({ type: MessageType.editorApplyRevision });
702});
703$("night").addEventListener("input", () =>
704{
705 view.nightPreview = Number($("night").value);
706 $("night-label").textContent = view.nightPreview.toFixed(1);
707});
708$("season").addEventListener("change", () =>
709{
710 applySeasonPreview($("season").value);
711});
712
713function syncSeasonControls (season)
714{
715 const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
716 ? season
717 : seasonIdAt();
718 $("season").value = next;
719 view?.setWorldSeason(next);
720}
721
722function applySeasonPreview (season)
723{
724 syncSeasonControls(season);
725}
726
727function cycleToolState (direction)
728{
729 if (tool.kind === "erase" || tool.kind === "spawner")
730 { return; }
731 const layer = tool.kind === "ground" ? "ground" : "block";
732 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
733 if (definitionUsesNeighborConnect(def))
734 { return; }
735 if (tool.kind === "block" && def?.id === BlockType.flower)
736 { return; }
737 const allStates = statesForType(catalog, layer, def.key);
738 const seasonal = seasonalCycleStates(allStates);
739 const states = seasonal ?? placeableStatesForType(catalog, layer, def.key);
740 if (states.length < 2)
741 { return; }
742 tool.state = cycleState(states, tool.state, direction);
743 $("tool").textContent = selectedToolLabel();
744 const season = seasonIdFromVisualState(tool.state);
745 if (season)
746 { applySeasonPreview(season); }
747 if (!draft || !hoverLocal)
748 { return; }
749 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
750 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
751 { paintAt(hoverLocal.x, hoverLocal.y); }
752 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
753 { paintAt(hoverLocal.x, hoverLocal.y); }
754}
755
756document.addEventListener("wheel", (event) =>
757{
758 if (!scene?.canvas || anyModalOpen())
759 { return; }
760 const rect = scene.canvas.getBoundingClientRect();
761 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
762 { return; }
763 event.preventDefault();
764 if (event.shiftKey)
765 {
766 cycleToolState(event.deltaY < 0 ? 1 : -1);
767 if (hoverLocal)
768 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
769 return;
770 }
771 zoomEditor(event.deltaY < 0 ? 1 : -1);
772}, { passive: false });
773
774document.addEventListener("contextmenu", (event) =>
775{
776 if (!scene?.canvas || anyModalOpen() || !draft)
777 { return; }
778 const rect = scene.canvas.getBoundingClientRect();
779 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
780 { return; }
781 event.preventDefault();
782 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
783 const localX = tile.tileX - chunkX * CHUNK_SIZE;
784 const localY = tile.tileY - chunkY * CHUNK_SIZE;
785 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
786 { return; }
787 const spawner = spawnerAt(localX, localY);
788 if (!spawner)
789 { return; }
790 tileConfigModal.openSpawner({
791 localX,
792 localY,
793 tileX: tile.tileX,
794 tileY: tile.tileY,
795 config: { ...spawner.config }
796 });
797});
798
799main().catch((error) =>
800{
801 $("error").textContent = error.message;
802 console.error(error);
803});