BlueGit

timfa questward

spawner tweaks

timfa Tim Falken · pushed by timfa

Authored 2026-08-25 · 2 months ago

Hash
661b81e55b9e8dd77aac79d5093699767d967c41
Parent
42bfe4a2
23 files changed +1254 −117
.cursor/rules/server-authority.mdc added +38 −0
@@ -0,0 +1,38 @@
1 ---
2 description: Enforce pure server authority — clients send intents only; server owns all gameplay state and outcomes.
3 alwaysApply: true
4 ---
5
6 # Pure server authority
7
8 Gameplay is **server-authoritative**. Clients send **intents** only; the server validates, mutates state, and replicates outcomes. Never violate this.
9
10 ## Allowed on the client
11
12 - Send commands (`moveTo`, `attack`, `pickupItem`, craft cancel, `respawn`, …)
13 - Render snapshots / replication (positions, inventory, combat FX, death UI)
14 - Local presentation only (zoom, lerp, tooltips, editor overlays)
15 - Shared pure helpers for **UI preview** (e.g. recipe fit) — never as the source of truth
16
17 ## Forbidden on the client
18
19 - Deciding hits, damage, XP, inventory results, craft success, spawns, death, or final positions
20 - Trusting client-supplied outcomes (damage numbers, “I hit”, stack merges applied locally as fact)
21 - Predicting authoritative world mutations without a matching server apply path
22
23 ```text
24 # ❌ BAD — client applies combat / bag results
25 onClickAttack(target) { target.hp -= 5; inventory.push(loot); }
26
27 # ✅ GOOD — intent in; wait for server replication
28 socket.send({ type: MessageType.attack, targetEntityId });
29 // apply combatHit / inventory messages from the server
30 ```
31
32 ## Server / shared
33
34 - Simulation, combat rolls, pathfinding, spawners, banking, death/respawn live on the server
35 - `shared/` helpers may be imported by both sides for rules/display; **only the server applies them to live state**
36 - World editor saves are admin-authored map data, not a player-authority exception for play
37
38 When unsure: if a cheater changing the client could gain an advantage, the logic belongs on the server.
@@ -0,0 +1,38 @@
1---
2description: Enforce pure server authority — clients send intents only; server owns all gameplay state and outcomes.
3alwaysApply: true
4---
5
6# Pure server authority
7
8Gameplay is **server-authoritative**. Clients send **intents** only; the server validates, mutates state, and replicates outcomes. Never violate this.
9
10## Allowed on the client
11
12- Send commands (`moveTo`, `attack`, `pickupItem`, craft cancel, `respawn`, …)
13- Render snapshots / replication (positions, inventory, combat FX, death UI)
14- Local presentation only (zoom, lerp, tooltips, editor overlays)
15- Shared pure helpers for **UI preview** (e.g. recipe fit) — never as the source of truth
16
17## Forbidden on the client
18
19- Deciding hits, damage, XP, inventory results, craft success, spawns, death, or final positions
20- Trusting client-supplied outcomes (damage numbers, “I hit”, stack merges applied locally as fact)
21- Predicting authoritative world mutations without a matching server apply path
22
23```text
24# ❌ BAD — client applies combat / bag results
25onClickAttack(target) { target.hp -= 5; inventory.push(loot); }
26
27# ✅ GOOD — intent in; wait for server replication
28socket.send({ type: MessageType.attack, targetEntityId });
29// apply combatHit / inventory messages from the server
30```
31
32## Server / shared
33
34- Simulation, combat rolls, pathfinding, spawners, banking, death/respawn live on the server
35- `shared/` helpers may be imported by both sides for rules/display; **only the server applies them to live state**
36- World editor saves are admin-authored map data, not a player-authority exception for play
37
38When unsure: if a cheater changing the client could gain an advantage, the logic belongs on the server.
client/editor.html +26 −14
@@ -26,32 +26,22 @@
26 26 </div>
27 27 <p>Tool: <strong id="tool"></strong></p>
28 28 <div class="palette">
29 <button type="button" data-tool='{"kind":"ground","typeId":1}'>Grass</button>
30 <button type="button" data-tool='{"kind":"ground","typeId":2}'>Wood</button>
31 <button type="button" data-tool='{"kind":"block","typeId":1}'>Stone wall</button>
32 <button type="button" data-tool='{"kind":"block","typeId":2}'>Torch</button>
33 <button type="button" data-tool='{"kind":"block","typeId":3}'>Spawner</button>
34 <button type="button" data-tool='{"kind":"block","typeId":4}'>Bank</button>
35 <button type="button" data-tool='{"kind":"erase"}'>Erase block</button>
36 </div>
37 <div id="spawner-config">
38 <p>Spawner (used when painting a new spawner tile)</p>
39 <label>Mob <select id="spawner-mob"><option value="deer">Deer</option><option value="rat">Rat</option></select></label>
40 <label>Max alive <input id="spawner-max" type="number" min="1" max="20" value="3"></label>
41 <label>Range <input id="spawner-range" type="number" min="1" max="16" value="4"></label>
29 <button id="open-palette" type="button">Select block…</button>
30 <button type="button" id="tool-erase">Erase block</button>
42 31 </div>
43 32 <button id="save" type="button">Save chunk</button>
44 33 <button id="apply" type="button" disabled title="Save a chunk first to create a pending revision">Apply now</button>
45 34 <p id="apply-status" class="hint" aria-live="polite"></p>
46 35 <label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
47 36 <button id="open-settings" type="button">World settings</button>
48 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Hover previews the selected tool. Mouse wheel zooms (view stays centred on the selected chunk); Shift+wheel cycles visual states. Chunk saves write a pending revision; world settings apply immediately. Place a spawner or bank with the tools above (placeholder art until real sprites exist).</p>
37 <p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states.</p>
49 38 </aside>
50 39 <section id="changelog-wrap">
51 40 <h2>Changelog</h2>
52 41 <div id="changelog"></div>
53 42 </section>
54 43 <div id="selection-border" aria-hidden="true"></div>
44 <div id="tile-tooltip" hidden></div>
55 45 <div id="settings-backdrop" hidden></div>
56 46 <div id="settings-modal" hidden>
57 47 <div id="settings-main">
@@ -70,6 +60,28 @@
70 60 <div id="settings-log"></div>
71 61 </aside>
72 62 </div>
63 <div id="palette-backdrop" hidden></div>
64 <div id="palette-modal" hidden>
65 <header>
66 <h2>Select placeable</h2>
67 <button id="palette-close" type="button">Close</button>
68 </header>
69 <div id="palette-tabs" class="settings-tabs" role="tablist"></div>
70 <div id="palette-panels"></div>
71 </div>
72 <div id="tile-config-backdrop" hidden></div>
73 <div id="tile-config-modal" hidden>
74 <header>
75 <h2 id="tile-config-title">Tile config</h2>
76 <button id="tile-config-close" type="button">Close</button>
77 </header>
78 <form id="tile-config-form"></form>
79 <footer>
80 <button id="tile-config-remove" type="button">Remove</button>
81 <button id="tile-config-cancel" type="button">Cancel</button>
82 <button id="tile-config-save" type="button">Save</button>
83 </footer>
84 </div>
73 85 <script src="/framework/framework.js"></script>
74 86 <script type="module" src="/src/editor/main.js"></script>
75 87 </body>
@@ -26,32 +26,22 @@
26 </div>
26 </div>
27 <p>Tool: <strong id="tool"></strong></p>
27 <p>Tool: <strong id="tool"></strong></p>
28 <div class="palette">
28 <div class="palette">
29 <button type="button" data-tool='{"kind":"ground","typeId":1}'>Grass</button>
29 <button id="open-palette" type="button">Select block…</button>
30 <button type="button" data-tool='{"kind":"ground","typeId":2}'>Wood</button>
30 <button type="button" id="tool-erase">Erase block</button>
31 <button type="button" data-tool='{"kind":"block","typeId":1}'>Stone wall</button>
32 <button type="button" data-tool='{"kind":"block","typeId":2}'>Torch</button>
33 <button type="button" data-tool='{"kind":"block","typeId":3}'>Spawner</button>
34 <button type="button" data-tool='{"kind":"block","typeId":4}'>Bank</button>
35 <button type="button" data-tool='{"kind":"erase"}'>Erase block</button>
36 </div>
37 <div id="spawner-config">
38 <p>Spawner (used when painting a new spawner tile)</p>
39 <label>Mob <select id="spawner-mob"><option value="deer">Deer</option><option value="rat">Rat</option></select></label>
40 <label>Max alive <input id="spawner-max" type="number" min="1" max="20" value="3"></label>
41 <label>Range <input id="spawner-range" type="number" min="1" max="16" value="4"></label>
42 </div>
31 </div>
43 <button id="save" type="button">Save chunk</button>
32 <button id="save" type="button">Save chunk</button>
44 <button id="apply" type="button" disabled title="Save a chunk first to create a pending revision">Apply now</button>
33 <button id="apply" type="button" disabled title="Save a chunk first to create a pending revision">Apply now</button>
45 <p id="apply-status" class="hint" aria-live="polite"></p>
34 <p id="apply-status" class="hint" aria-live="polite"></p>
46 <label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
35 <label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
47 <button id="open-settings" type="button">World settings</button>
36 <button id="open-settings" type="button">World settings</button>
48 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Hover previews the selected tool. Mouse wheel zooms (view stays centred on the selected chunk); Shift+wheel cycles visual states. Chunk saves write a pending revision; world settings apply immediately. Place a spawner or bank with the tools above (placeholder art until real sprites exist).</p>
37 <p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states.</p>
49 </aside>
38 </aside>
50 <section id="changelog-wrap">
39 <section id="changelog-wrap">
51 <h2>Changelog</h2>
40 <h2>Changelog</h2>
52 <div id="changelog"></div>
41 <div id="changelog"></div>
53 </section>
42 </section>
54 <div id="selection-border" aria-hidden="true"></div>
43 <div id="selection-border" aria-hidden="true"></div>
44 <div id="tile-tooltip" hidden></div>
55 <div id="settings-backdrop" hidden></div>
45 <div id="settings-backdrop" hidden></div>
56 <div id="settings-modal" hidden>
46 <div id="settings-modal" hidden>
57 <div id="settings-main">
47 <div id="settings-main">
@@ -70,6 +60,28 @@
70 <div id="settings-log"></div>
60 <div id="settings-log"></div>
71 </aside>
61 </aside>
72 </div>
62 </div>
63 <div id="palette-backdrop" hidden></div>
64 <div id="palette-modal" hidden>
65 <header>
66 <h2>Select placeable</h2>
67 <button id="palette-close" type="button">Close</button>
68 </header>
69 <div id="palette-tabs" class="settings-tabs" role="tablist"></div>
70 <div id="palette-panels"></div>
71 </div>
72 <div id="tile-config-backdrop" hidden></div>
73 <div id="tile-config-modal" hidden>
74 <header>
75 <h2 id="tile-config-title">Tile config</h2>
76 <button id="tile-config-close" type="button">Close</button>
77 </header>
78 <form id="tile-config-form"></form>
79 <footer>
80 <button id="tile-config-remove" type="button">Remove</button>
81 <button id="tile-config-cancel" type="button">Cancel</button>
82 <button id="tile-config-save" type="button">Save</button>
83 </footer>
84 </div>
73 <script src="/framework/framework.js"></script>
85 <script src="/framework/framework.js"></script>
74 <script type="module" src="/src/editor/main.js"></script>
86 <script type="module" src="/src/editor/main.js"></script>
75</body>
87</body>
client/src/editor/main.js +205 −33
@@ -1,10 +1,19 @@
1 1 import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, BlockType, GroundType, normalizeGround } from "/shared/definitions/tiles.js";
2 import {
3 GROUND_DEFINITIONS,
4 BLOCK_DEFINITIONS,
5 GroundType,
6 normalizeGround,
7 normalizeBlock
8 } from "/shared/definitions/tiles.js";
3 9 import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
10 import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
4 11 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
5 12 import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
6 13 import { WorldView } from "../render/worldView.js";
7 14 import { initSettingsModal } from "./settingsModal.js";
15 import { initPaletteModal } from "./paletteModal.js";
16 import { initTileConfigModal } from "./tileConfigModal.js";
8 17
9 18 const game = new Game();
10 19 let socket;
@@ -15,7 +24,10 @@ let chunkX = 0;
15 24 let chunkY = 0;
16 25 let tool = { kind: "ground", typeId: GroundType.grass, state: null };
17 26 let settingsModal;
18 let catalog = { grounds: {}, blocks: {} };
27 let paletteModal;
28 let tileConfigModal;
29 let catalog = { grounds: {}, blocks: {}, images: [] };
30 let imageUrlByName = new Map();
19 31 let hoverLocal = null;
20 32 let editorZoom = null;
21 33 let activeRevisionId = null;
@@ -34,6 +46,11 @@ function selectedToolLabel ()
34 46 {
35 47 if (tool.kind === "erase")
36 48 { return "Erase block"; }
49 if (tool.kind === "spawner")
50 {
51 const def = mobDefinition(tool.mobTypeId);
52 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
53 }
37 54 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
38 55 const layer = tool.kind === "ground" ? "ground" : "block";
39 56 const states = statesForType(catalog, layer, def.key);
@@ -50,6 +67,11 @@ function selectTool (next)
50 67 tool = { kind: "erase" };
51 68 return;
52 69 }
70 if (next.kind === "spawner")
71 {
72 tool = { kind: "spawner", mobTypeId: next.mobTypeId };
73 return;
74 }
53 75 const layer = next.kind === "ground" ? "ground" : "block";
54 76 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
55 77 tool = {
@@ -61,7 +83,7 @@ function selectTool (next)
61 83
62 84 function placeableToolState ()
63 85 {
64 if (tool.kind === "erase")
86 if (tool.kind === "erase" || tool.kind === "spawner")
65 87 { return null; }
66 88 const layer = tool.kind === "ground" ? "ground" : "block";
67 89 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
@@ -72,6 +94,8 @@ function previewFromTool ()
72 94 {
73 95 if (tool.kind === "erase")
74 96 { return { block: null }; }
97 if (tool.kind === "spawner")
98 { return {}; }
75 99 const state = placeableToolState();
76 100 if (tool.kind === "ground")
77 101 { return { ground: { typeId: tool.typeId, state } }; }
@@ -108,6 +132,16 @@ function snapshotFromPayload (payload)
108 132 };
109 133 }
110 134
135 function syncSpawnersOverlay (cx, cy, spawners)
136 {
137 view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
138 }
139
140 function spawnerAt (localX, localY)
141 {
142 return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
143 }
144
111 145 function paintAt (localX, localY)
112 146 {
113 147 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
@@ -118,24 +152,27 @@ function paintAt (localX, localY)
118 152 { draft.grounds[index] = { typeId: tool.typeId, state }; }
119 153 else if (tool.kind === "erase")
120 154 { draft.blocks[index] = null; }
121 else
155 else if (tool.kind === "spawner")
122 156 {
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 = {
157 const existing = spawnerAt(localX, localY);
158 const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`;
159 const entry = {
160 localX,
161 localY,
162 config: normalizeSpawnerConfig({
163 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
164 ...(existing?.config ?? {}),
131 165 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 };
166 mobTypeId: tool.mobTypeId
167 }, spawnerId)
168 };
169 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
170 draft.spawners.push(entry);
171 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
172 return;
138 173 }
174 else
175 { draft.blocks[index] = { typeId: tool.typeId, state, config: null }; }
139 176 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
140 177 ground: draft.grounds[index],
141 178 block: draft.blocks[index],
@@ -170,8 +207,13 @@ function showSelectedChunk (payload)
170 207 draft = {
171 208 open: payload.data.open,
172 209 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
173 blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)),
174 light: payload.data.light.slice()
210 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
211 light: payload.data.light.slice(),
212 spawners: (payload.data.spawners ?? []).map((entry) => ({
213 localX: entry.localX,
214 localY: entry.localY,
215 config: { ...entry.config }
216 }))
175 217 };
176 218 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
177 219 $("open").checked = draft.open;
@@ -197,6 +239,7 @@ function showSelectedChunk (payload)
197 239 log.append(item);
198 240 }
199 241 view.applySnapshot(snapshotFromPayload(payload));
242 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
200 243 }
201 244
202 245 function pruneView ()
@@ -297,9 +340,72 @@ function requestNeighbors ()
297 340 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
298 341 }
299 342
343 function anyModalOpen ()
344 {
345 return settingsModal?.isOpen() || paletteModal?.isOpen() || tileConfigModal?.isOpen();
346 }
347
348 function updateTooltip (local)
349 {
350 const tip = $("tile-tooltip");
351 if (!tip || !local || !draft)
352 {
353 if (tip)
354 { tip.hidden = true; }
355 view?.clearSpawnRangeHighlight();
356 return;
357 }
358 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
359 const spawner = spawnerAt(local.x, local.y);
360 const lines = [];
361 if (block)
362 {
363 const def = BLOCK_DEFINITIONS[block.typeId];
364 lines.push(def?.displayName ?? `Block ${block.typeId}`);
365 if (block.config && Object.keys(block.config).length)
366 {
367 for (const [key, value] of Object.entries(block.config))
368 { lines.push(`${key}: ${value}`); }
369 }
370 }
371 if (spawner)
372 {
373 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
374 const mob = mobDefinition(config.mobTypeId);
375 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
376 lines.push(`maxAlive: ${config.maxAlive}`);
377 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
378 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
379 lines.push(`id: ${config.spawnerId}`);
380 view.setSpawnRangeHighlight(
381 local.tileX,
382 local.tileY,
383 config.spawnRangeTiles,
384 config.maxWanderRangeTiles
385 );
386 }
387 else
388 { view.clearSpawnRangeHighlight(); }
389 if (!lines.length)
390 {
391 tip.hidden = true;
392 return;
393 }
394 tip.hidden = false;
395 tip.textContent = lines.join("\n");
396 const canvas = scene.canvas;
397 const rect = canvas.getBoundingClientRect();
398 const size = view.tileSize();
399 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
400 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
401 tip.style.left = `${screenX}px`;
402 tip.style.top = `${screenY}px`;
403 }
404
300 405 async function main ()
301 406 {
302 407 catalog = await loadSpriteCatalog();
408 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
303 409 await preloadCatalogImages(game, catalog);
304 410 applySpriteSheets(game.images, catalog);
305 411 scene = new Scene(250, 56, 64, 64);
@@ -310,6 +416,35 @@ async function main ()
310 416 layoutScene();
311 417 selectTool(tool);
312 418 $("tool").textContent = selectedToolLabel();
419
420 paletteModal = initPaletteModal({
421 catalog,
422 imageUrlFor: (name) => imageUrlByName.get(name) ?? null,
423 onSelect (next)
424 {
425 selectTool(next);
426 $("tool").textContent = selectedToolLabel();
427 }
428 });
429
430 tileConfigModal = initTileConfigModal({
431 onSave (ctx, config)
432 {
433 if (!draft)
434 { return; }
435 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
436 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
437 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
438 },
439 onRemove (ctx)
440 {
441 if (!draft)
442 { return; }
443 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
444 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
445 }
446 });
447
313 448 const ticker = new GameObject(0, 0, null, 10);
314 449 ticker.update = (dt) =>
315 450 {
@@ -319,7 +454,7 @@ async function main ()
319 454 const mouseX = GameInput.mousePosition.x - rect.left;
320 455 const mouseY = GameInput.mousePosition.y - rect.top;
321 456 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
322 if (overCanvas && draft && !settingsModal?.isOpen())
457 if (overCanvas && draft && !anyModalOpen())
323 458 {
324 459 const tile = view.screenToTile(mouseX, mouseY);
325 460 const localX = tile.tileX - chunkX * CHUNK_SIZE;
@@ -328,14 +463,21 @@ async function main ()
328 463 {
329 464 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
330 465 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
466 updateTooltip(hoverLocal);
331 467 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
332 468 { paintAt(localX, localY); }
333 469 }
334 470 else
335 { view.clearTilePreview(); }
471 {
472 view.clearTilePreview();
473 updateTooltip(null);
474 }
336 475 }
337 476 else
338 { view.clearTilePreview(); }
477 {
478 view.clearTilePreview();
479 updateTooltip(null);
480 }
339 481 view.update(dt);
340 482 frameNeighborhood();
341 483 };
@@ -361,7 +503,10 @@ async function main ()
361 503 if (message.chunkX === chunkX && message.chunkY === chunkY)
362 504 { showSelectedChunk(message); }
363 505 else
364 { view.applySnapshot(snapshotFromPayload(message)); }
506 {
507 view.applySnapshot(snapshotFromPayload(message));
508 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
509 }
365 510 pruneView();
366 511 }
367 512 else if (message.type === MessageType.editorRevisionApplied)
@@ -407,13 +552,10 @@ async function main ()
407 552 }
408 553
409 554 $("tool").textContent = selectedToolLabel();
410 document.querySelectorAll("[data-tool]").forEach((button) =>
555 $("tool-erase").addEventListener("click", () =>
411 556 {
412 button.addEventListener("click", () =>
413 {
414 selectTool(JSON.parse(button.dataset.tool));
415 $("tool").textContent = selectedToolLabel();
416 });
557 selectTool({ kind: "erase" });
558 $("tool").textContent = selectedToolLabel();
417 559 });
418 560
419 561 $("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
@@ -437,7 +579,12 @@ $("save").addEventListener("click", () =>
437 579 type: MessageType.editorSaveChunk,
438 580 chunkX,
439 581 chunkY,
440 draft: { open: $("open").checked, grounds: draft.grounds, blocks: draft.blocks }
582 draft: {
583 open: $("open").checked,
584 grounds: draft.grounds,
585 blocks: draft.blocks,
586 spawners: draft.spawners ?? []
587 }
441 588 });
442 589 requestNeighbors();
443 590 });
@@ -461,7 +608,7 @@ $("night").addEventListener("input", () =>
461 608
462 609 function cycleToolState (direction)
463 610 {
464 if (tool.kind === "erase")
611 if (tool.kind === "erase" || tool.kind === "spawner")
465 612 { return; }
466 613 const layer = tool.kind === "ground" ? "ground" : "block";
467 614 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
@@ -481,7 +628,7 @@ function cycleToolState (direction)
481 628
482 629 document.addEventListener("wheel", (event) =>
483 630 {
484 if (!scene?.canvas || settingsModal?.isOpen())
631 if (!scene?.canvas || anyModalOpen())
485 632 { return; }
486 633 const rect = scene.canvas.getBoundingClientRect();
487 634 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
@@ -497,6 +644,31 @@ document.addEventListener("wheel", (event) =>
497 644 zoomEditor(event.deltaY < 0 ? 1 : -1);
498 645 }, { passive: false });
499 646
647 document.addEventListener("contextmenu", (event) =>
648 {
649 if (!scene?.canvas || anyModalOpen() || !draft)
650 { return; }
651 const rect = scene.canvas.getBoundingClientRect();
652 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
653 { return; }
654 event.preventDefault();
655 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
656 const localX = tile.tileX - chunkX * CHUNK_SIZE;
657 const localY = tile.tileY - chunkY * CHUNK_SIZE;
658 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
659 { return; }
660 const spawner = spawnerAt(localX, localY);
661 if (!spawner)
662 { return; }
663 tileConfigModal.openSpawner({
664 localX,
665 localY,
666 tileX: tile.tileX,
667 tileY: tile.tileY,
668 config: { ...spawner.config }
669 });
670 });
671
500 672 main().catch((error) =>
501 673 {
502 674 $("error").textContent = error.message;
@@ -1,10 +1,19 @@
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
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";
2import {
3 GROUND_DEFINITIONS,
4 BLOCK_DEFINITIONS,
5 GroundType,
6 normalizeGround,
7 normalizeBlock
8} from "/shared/definitions/tiles.js";
3import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
9import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
10import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
4import { GameSocket, defaultSocketUrl } from "../net/socket.js";
11import { GameSocket, defaultSocketUrl } from "../net/socket.js";
5import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
12import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
6import { WorldView } from "../render/worldView.js";
13import { WorldView } from "../render/worldView.js";
7import { initSettingsModal } from "./settingsModal.js";
14import { initSettingsModal } from "./settingsModal.js";
15import { initPaletteModal } from "./paletteModal.js";
16import { initTileConfigModal } from "./tileConfigModal.js";
8
17
9const game = new Game();
18const game = new Game();
10let socket;
19let socket;
@@ -15,7 +24,10 @@ let chunkX = 0;
15let chunkY = 0;
24let chunkY = 0;
16let tool = { kind: "ground", typeId: GroundType.grass, state: null };
25let tool = { kind: "ground", typeId: GroundType.grass, state: null };
17let settingsModal;
26let settingsModal;
18let catalog = { grounds: {}, blocks: {} };
27let paletteModal;
28let tileConfigModal;
29let catalog = { grounds: {}, blocks: {}, images: [] };
30let imageUrlByName = new Map();
19let hoverLocal = null;
31let hoverLocal = null;
20let editorZoom = null;
32let editorZoom = null;
21let activeRevisionId = null;
33let activeRevisionId = null;
@@ -34,6 +46,11 @@ function selectedToolLabel ()
34{
46{
35 if (tool.kind === "erase")
47 if (tool.kind === "erase")
36 { return "Erase block"; }
48 { return "Erase block"; }
49 if (tool.kind === "spawner")
50 {
51 const def = mobDefinition(tool.mobTypeId);
52 return `Spawner · ${def?.displayName ?? tool.mobTypeId}`;
53 }
37 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
54 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
38 const layer = tool.kind === "ground" ? "ground" : "block";
55 const layer = tool.kind === "ground" ? "ground" : "block";
39 const states = statesForType(catalog, layer, def.key);
56 const states = statesForType(catalog, layer, def.key);
@@ -50,6 +67,11 @@ function selectTool (next)
50 tool = { kind: "erase" };
67 tool = { kind: "erase" };
51 return;
68 return;
52 }
69 }
70 if (next.kind === "spawner")
71 {
72 tool = { kind: "spawner", mobTypeId: next.mobTypeId };
73 return;
74 }
53 const layer = next.kind === "ground" ? "ground" : "block";
75 const layer = next.kind === "ground" ? "ground" : "block";
54 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
76 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
55 tool = {
77 tool = {
@@ -61,7 +83,7 @@ function selectTool (next)
61
83
62function placeableToolState ()
84function placeableToolState ()
63{
85{
64 if (tool.kind === "erase")
86 if (tool.kind === "erase" || tool.kind === "spawner")
65 { return null; }
87 { return null; }
66 const layer = tool.kind === "ground" ? "ground" : "block";
88 const layer = tool.kind === "ground" ? "ground" : "block";
67 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
89 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
@@ -72,6 +94,8 @@ function previewFromTool ()
72{
94{
73 if (tool.kind === "erase")
95 if (tool.kind === "erase")
74 { return { block: null }; }
96 { return { block: null }; }
97 if (tool.kind === "spawner")
98 { return {}; }
75 const state = placeableToolState();
99 const state = placeableToolState();
76 if (tool.kind === "ground")
100 if (tool.kind === "ground")
77 { return { ground: { typeId: tool.typeId, state } }; }
101 { return { ground: { typeId: tool.typeId, state } }; }
@@ -108,6 +132,16 @@ function snapshotFromPayload (payload)
108 };
132 };
109}
133}
110
134
135function syncSpawnersOverlay (cx, cy, spawners)
136{
137 view.setEditorSpawners(cx, cy, spawners ?? [], (mobTypeId) => mobSpriteName(mobTypeId));
138}
139
140function spawnerAt (localX, localY)
141{
142 return (draft?.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
143}
144
111function paintAt (localX, localY)
145function paintAt (localX, localY)
112{
146{
113 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
147 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
@@ -118,24 +152,27 @@ function paintAt (localX, localY)
118 { draft.grounds[index] = { typeId: tool.typeId, state }; }
152 { draft.grounds[index] = { typeId: tool.typeId, state }; }
119 else if (tool.kind === "erase")
153 else if (tool.kind === "erase")
120 { draft.blocks[index] = null; }
154 { draft.blocks[index] = null; }
121 else
155 else if (tool.kind === "spawner")
122 {
156 {
123 const existing = draft.blocks[index];
157 const existing = spawnerAt(localX, localY);
124 let config = null;
158 const spawnerId = existing?.config?.spawnerId ?? `${chunkX}:${chunkY}:${index}`;
125 if (tool.typeId === BlockType.spawner)
159 const entry = {
126 {
160 localX,
127 const spawnerId = existing?.typeId === BlockType.spawner && existing.config?.spawnerId
161 localY,
128 ? existing.config.spawnerId
162 config: normalizeSpawnerConfig({
129 : `${chunkX}:${chunkY}:${index}`;
163 ...defaultSpawnerConfig(spawnerId, tool.mobTypeId),
130 config = {
164 ...(existing?.config ?? {}),
131 spawnerId,
165 spawnerId,
132 mobTypeId: $("spawner-mob")?.value || "deer",
166 mobTypeId: tool.mobTypeId
133 maxAlive: Number($("spawner-max")?.value || 3),
167 }, spawnerId)
134 spawnRangeTiles: Number($("spawner-range")?.value || 4)
168 };
135 };
169 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== localX || s.localY !== localY);
136 }
170 draft.spawners.push(entry);
137 draft.blocks[index] = { typeId: tool.typeId, state, config };
171 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
172 return;
138 }
173 }
174 else
175 { draft.blocks[index] = { typeId: tool.typeId, state, config: null }; }
139 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
176 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
140 ground: draft.grounds[index],
177 ground: draft.grounds[index],
141 block: draft.blocks[index],
178 block: draft.blocks[index],
@@ -170,8 +207,13 @@ function showSelectedChunk (payload)
170 draft = {
207 draft = {
171 open: payload.data.open,
208 open: payload.data.open,
172 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
209 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
173 blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)),
210 blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
174 light: payload.data.light.slice()
211 light: payload.data.light.slice(),
212 spawners: (payload.data.spawners ?? []).map((entry) => ({
213 localX: entry.localX,
214 localY: entry.localY,
215 config: { ...entry.config }
216 }))
175 };
217 };
176 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
218 $("coords").textContent = `${payload.chunkX}, ${payload.chunkY}`;
177 $("open").checked = draft.open;
219 $("open").checked = draft.open;
@@ -197,6 +239,7 @@ function showSelectedChunk (payload)
197 log.append(item);
239 log.append(item);
198 }
240 }
199 view.applySnapshot(snapshotFromPayload(payload));
241 view.applySnapshot(snapshotFromPayload(payload));
242 syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
200}
243}
201
244
202function pruneView ()
245function pruneView ()
@@ -297,9 +340,72 @@ function requestNeighbors ()
297 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
340 requestChunks(neighborhoodCoords(chunkX, chunkY).filter((coord) => coord.chunkX !== chunkX || coord.chunkY !== chunkY));
298}
341}
299
342
343function anyModalOpen ()
344{
345 return settingsModal?.isOpen() || paletteModal?.isOpen() || tileConfigModal?.isOpen();
346}
347
348function updateTooltip (local)
349{
350 const tip = $("tile-tooltip");
351 if (!tip || !local || !draft)
352 {
353 if (tip)
354 { tip.hidden = true; }
355 view?.clearSpawnRangeHighlight();
356 return;
357 }
358 const block = normalizeBlock(draft.blocks[local.y * CHUNK_SIZE + local.x]);
359 const spawner = spawnerAt(local.x, local.y);
360 const lines = [];
361 if (block)
362 {
363 const def = BLOCK_DEFINITIONS[block.typeId];
364 lines.push(def?.displayName ?? `Block ${block.typeId}`);
365 if (block.config && Object.keys(block.config).length)
366 {
367 for (const [key, value] of Object.entries(block.config))
368 { lines.push(`${key}: ${value}`); }
369 }
370 }
371 if (spawner)
372 {
373 const config = normalizeSpawnerConfig(spawner.config, spawner.config.spawnerId);
374 const mob = mobDefinition(config.mobTypeId);
375 lines.push(`Spawner · ${mob?.displayName ?? config.mobTypeId}`);
376 lines.push(`maxAlive: ${config.maxAlive}`);
377 lines.push(`spawnRange: ${config.spawnRangeTiles}`);
378 lines.push(`wanderRange: ${config.maxWanderRangeTiles}`);
379 lines.push(`id: ${config.spawnerId}`);
380 view.setSpawnRangeHighlight(
381 local.tileX,
382 local.tileY,
383 config.spawnRangeTiles,
384 config.maxWanderRangeTiles
385 );
386 }
387 else
388 { view.clearSpawnRangeHighlight(); }
389 if (!lines.length)
390 {
391 tip.hidden = true;
392 return;
393 }
394 tip.hidden = false;
395 tip.textContent = lines.join("\n");
396 const canvas = scene.canvas;
397 const rect = canvas.getBoundingClientRect();
398 const size = view.tileSize();
399 const screenX = local.tileX * size + scene.cameraPosition.x + rect.left + size;
400 const screenY = local.tileY * size + scene.cameraPosition.y + rect.top;
401 tip.style.left = `${screenX}px`;
402 tip.style.top = `${screenY}px`;
403}
404
300async function main ()
405async function main ()
301{
406{
302 catalog = await loadSpriteCatalog();
407 catalog = await loadSpriteCatalog();
408 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
303 await preloadCatalogImages(game, catalog);
409 await preloadCatalogImages(game, catalog);
304 applySpriteSheets(game.images, catalog);
410 applySpriteSheets(game.images, catalog);
305 scene = new Scene(250, 56, 64, 64);
411 scene = new Scene(250, 56, 64, 64);
@@ -310,6 +416,35 @@ async function main ()
310 layoutScene();
416 layoutScene();
311 selectTool(tool);
417 selectTool(tool);
312 $("tool").textContent = selectedToolLabel();
418 $("tool").textContent = selectedToolLabel();
419
420 paletteModal = initPaletteModal({
421 catalog,
422 imageUrlFor: (name) => imageUrlByName.get(name) ?? null,
423 onSelect (next)
424 {
425 selectTool(next);
426 $("tool").textContent = selectedToolLabel();
427 }
428 });
429
430 tileConfigModal = initTileConfigModal({
431 onSave (ctx, config)
432 {
433 if (!draft)
434 { return; }
435 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
436 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
437 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
438 },
439 onRemove (ctx)
440 {
441 if (!draft)
442 { return; }
443 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
444 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
445 }
446 });
447
313 const ticker = new GameObject(0, 0, null, 10);
448 const ticker = new GameObject(0, 0, null, 10);
314 ticker.update = (dt) =>
449 ticker.update = (dt) =>
315 {
450 {
@@ -319,7 +454,7 @@ async function main ()
319 const mouseX = GameInput.mousePosition.x - rect.left;
454 const mouseX = GameInput.mousePosition.x - rect.left;
320 const mouseY = GameInput.mousePosition.y - rect.top;
455 const mouseY = GameInput.mousePosition.y - rect.top;
321 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
456 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
322 if (overCanvas && draft && !settingsModal?.isOpen())
457 if (overCanvas && draft && !anyModalOpen())
323 {
458 {
324 const tile = view.screenToTile(mouseX, mouseY);
459 const tile = view.screenToTile(mouseX, mouseY);
325 const localX = tile.tileX - chunkX * CHUNK_SIZE;
460 const localX = tile.tileX - chunkX * CHUNK_SIZE;
@@ -328,14 +463,21 @@ async function main ()
328 {
463 {
329 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
464 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
330 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
465 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
466 updateTooltip(hoverLocal);
331 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
467 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
332 { paintAt(localX, localY); }
468 { paintAt(localX, localY); }
333 }
469 }
334 else
470 else
335 { view.clearTilePreview(); }
471 {
472 view.clearTilePreview();
473 updateTooltip(null);
474 }
336 }
475 }
337 else
476 else
338 { view.clearTilePreview(); }
477 {
478 view.clearTilePreview();
479 updateTooltip(null);
480 }
339 view.update(dt);
481 view.update(dt);
340 frameNeighborhood();
482 frameNeighborhood();
341 };
483 };
@@ -361,7 +503,10 @@ async function main ()
361 if (message.chunkX === chunkX && message.chunkY === chunkY)
503 if (message.chunkX === chunkX && message.chunkY === chunkY)
362 { showSelectedChunk(message); }
504 { showSelectedChunk(message); }
363 else
505 else
364 { view.applySnapshot(snapshotFromPayload(message)); }
506 {
507 view.applySnapshot(snapshotFromPayload(message));
508 syncSpawnersOverlay(message.chunkX, message.chunkY, message.data.spawners);
509 }
365 pruneView();
510 pruneView();
366 }
511 }
367 else if (message.type === MessageType.editorRevisionApplied)
512 else if (message.type === MessageType.editorRevisionApplied)
@@ -407,13 +552,10 @@ async function main ()
407}
552}
408
553
409$("tool").textContent = selectedToolLabel();
554$("tool").textContent = selectedToolLabel();
410document.querySelectorAll("[data-tool]").forEach((button) =>
555$("tool-erase").addEventListener("click", () =>
411{
556{
412 button.addEventListener("click", () =>
557 selectTool({ kind: "erase" });
413 {
558 $("tool").textContent = selectedToolLabel();
414 selectTool(JSON.parse(button.dataset.tool));
415 $("tool").textContent = selectedToolLabel();
416 });
417});
559});
418
560
419$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
561$("north").addEventListener("click", () => loadNeighborhood(chunkX, chunkY - 1));
@@ -437,7 +579,12 @@ $("save").addEventListener("click", () =>
437 type: MessageType.editorSaveChunk,
579 type: MessageType.editorSaveChunk,
438 chunkX,
580 chunkX,
439 chunkY,
581 chunkY,
440 draft: { open: $("open").checked, grounds: draft.grounds, blocks: draft.blocks }
582 draft: {
583 open: $("open").checked,
584 grounds: draft.grounds,
585 blocks: draft.blocks,
586 spawners: draft.spawners ?? []
587 }
441 });
588 });
442 requestNeighbors();
589 requestNeighbors();
443});
590});
@@ -461,7 +608,7 @@ $("night").addEventListener("input", () =>
461
608
462function cycleToolState (direction)
609function cycleToolState (direction)
463{
610{
464 if (tool.kind === "erase")
611 if (tool.kind === "erase" || tool.kind === "spawner")
465 { return; }
612 { return; }
466 const layer = tool.kind === "ground" ? "ground" : "block";
613 const layer = tool.kind === "ground" ? "ground" : "block";
467 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
614 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
@@ -481,7 +628,7 @@ function cycleToolState (direction)
481
628
482document.addEventListener("wheel", (event) =>
629document.addEventListener("wheel", (event) =>
483{
630{
484 if (!scene?.canvas || settingsModal?.isOpen())
631 if (!scene?.canvas || anyModalOpen())
485 { return; }
632 { return; }
486 const rect = scene.canvas.getBoundingClientRect();
633 const rect = scene.canvas.getBoundingClientRect();
487 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
634 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
@@ -497,6 +644,31 @@ document.addEventListener("wheel", (event) =>
497 zoomEditor(event.deltaY < 0 ? 1 : -1);
644 zoomEditor(event.deltaY < 0 ? 1 : -1);
498}, { passive: false });
645}, { passive: false });
499
646
647document.addEventListener("contextmenu", (event) =>
648{
649 if (!scene?.canvas || anyModalOpen() || !draft)
650 { return; }
651 const rect = scene.canvas.getBoundingClientRect();
652 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
653 { return; }
654 event.preventDefault();
655 const tile = view.screenToTile(event.clientX - rect.left, event.clientY - rect.top);
656 const localX = tile.tileX - chunkX * CHUNK_SIZE;
657 const localY = tile.tileY - chunkY * CHUNK_SIZE;
658 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
659 { return; }
660 const spawner = spawnerAt(localX, localY);
661 if (!spawner)
662 { return; }
663 tileConfigModal.openSpawner({
664 localX,
665 localY,
666 tileX: tile.tileX,
667 tileY: tile.tileY,
668 config: { ...spawner.config }
669 });
670});
671
500main().catch((error) =>
672main().catch((error) =>
501{
673{
502 $("error").textContent = error.message;
674 $("error").textContent = error.message;
client/src/editor/paletteModal.js added +146 −0
@@ -0,0 +1,146 @@
1 import { listPlaceableGrounds, listPlaceableBlocks } from "/shared/definitions/tiles.js";
2 import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
3 import { defaultStateForType, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4
5 /**
6 * Select-tool modal: Ground / Blocks / Spawners, auto-built from definitions.
7 */
8 export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
9 {
10 const backdrop = document.getElementById("palette-backdrop");
11 const modal = document.getElementById("palette-modal");
12 const tabs = document.getElementById("palette-tabs");
13 const panels = document.getElementById("palette-panels");
14 let open = false;
15 let activeTab = "grounds";
16
17 const tabsSpec = [
18 { id: "grounds", label: "Ground tiles" },
19 { id: "blocks", label: "Blocks" },
20 { id: "spawners", label: "Spawners" }
21 ];
22
23 function show (visible)
24 {
25 open = visible;
26 backdrop.hidden = !visible;
27 modal.hidden = !visible;
28 if (visible)
29 { render(); }
30 }
31
32 function render ()
33 {
34 tabs.innerHTML = "";
35 for (const tab of tabsSpec)
36 {
37 const button = document.createElement("button");
38 button.type = "button";
39 button.className = `settings-tab${tab.id === activeTab ? " active" : ""}`;
40 button.textContent = tab.label;
41 button.addEventListener("click", () =>
42 {
43 activeTab = tab.id;
44 render();
45 });
46 tabs.append(button);
47 }
48
49 panels.innerHTML = "";
50 const grid = document.createElement("div");
51 grid.className = "palette-grid";
52 if (activeTab === "grounds")
53 {
54 for (const def of listPlaceableGrounds())
55 {
56 const state = defaultStateForType(catalog, "ground", def.key);
57 const name = spriteImageName("ground", def.key, resolveState(
58 catalog.grounds?.[def.key]?.states ?? [],
59 state
60 ));
61 grid.append(tileCard({
62 label: def.displayName,
63 url: imageUrlFor?.(name),
64 onClick ()
65 {
66 onSelect({ kind: "ground", typeId: def.id });
67 show(false);
68 }
69 }));
70 }
71 }
72 else if (activeTab === "blocks")
73 {
74 for (const def of listPlaceableBlocks())
75 {
76 const state = defaultStateForType(catalog, "block", def.key);
77 const name = spriteImageName("block", def.key, resolveState(
78 catalog.blocks?.[def.key]?.states ?? [],
79 state
80 ));
81 grid.append(tileCard({
82 label: def.displayName,
83 url: imageUrlFor?.(name),
84 onClick ()
85 {
86 onSelect({ kind: "block", typeId: def.id });
87 show(false);
88 }
89 }));
90 }
91 }
92 else
93 {
94 for (const def of listSpawnableMobTypes())
95 {
96 grid.append(tileCard({
97 label: def.displayName,
98 url: imageUrlFor?.(mobSpriteName(def.mobTypeId)),
99 onClick ()
100 {
101 onSelect({ kind: "spawner", mobTypeId: def.mobTypeId });
102 show(false);
103 }
104 }));
105 }
106 }
107 panels.append(grid);
108 }
109
110 document.getElementById("open-palette").addEventListener("click", () => show(true));
111 document.getElementById("palette-close").addEventListener("click", () => show(false));
112 backdrop.addEventListener("click", () => show(false));
113
114 return {
115 isOpen: () => open,
116 close: () => show(false)
117 };
118 }
119
120 function tileCard ({ label, url, onClick })
121 {
122 const button = document.createElement("button");
123 button.type = "button";
124 button.className = "palette-card";
125 const thumb = document.createElement("div");
126 thumb.className = "palette-thumb";
127 if (url)
128 {
129 const img = document.createElement("img");
130 img.alt = "";
131 img.src = url;
132 img.onerror = () =>
133 {
134 img.remove();
135 thumb.textContent = label.slice(0, 1);
136 };
137 thumb.append(img);
138 }
139 else
140 { thumb.textContent = label.slice(0, 1); }
141 const caption = document.createElement("span");
142 caption.textContent = label;
143 button.append(thumb, caption);
144 button.addEventListener("click", onClick);
145 return button;
146 }
@@ -0,0 +1,146 @@
1import { listPlaceableGrounds, listPlaceableBlocks } from "/shared/definitions/tiles.js";
2import { listSpawnableMobTypes, mobSpriteName } from "/shared/definitions/mobs.js";
3import { defaultStateForType, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4
5/**
6 * Select-tool modal: Ground / Blocks / Spawners, auto-built from definitions.
7 */
8export function initPaletteModal ({ onSelect, catalog, imageUrlFor })
9{
10 const backdrop = document.getElementById("palette-backdrop");
11 const modal = document.getElementById("palette-modal");
12 const tabs = document.getElementById("palette-tabs");
13 const panels = document.getElementById("palette-panels");
14 let open = false;
15 let activeTab = "grounds";
16
17 const tabsSpec = [
18 { id: "grounds", label: "Ground tiles" },
19 { id: "blocks", label: "Blocks" },
20 { id: "spawners", label: "Spawners" }
21 ];
22
23 function show (visible)
24 {
25 open = visible;
26 backdrop.hidden = !visible;
27 modal.hidden = !visible;
28 if (visible)
29 { render(); }
30 }
31
32 function render ()
33 {
34 tabs.innerHTML = "";
35 for (const tab of tabsSpec)
36 {
37 const button = document.createElement("button");
38 button.type = "button";
39 button.className = `settings-tab${tab.id === activeTab ? " active" : ""}`;
40 button.textContent = tab.label;
41 button.addEventListener("click", () =>
42 {
43 activeTab = tab.id;
44 render();
45 });
46 tabs.append(button);
47 }
48
49 panels.innerHTML = "";
50 const grid = document.createElement("div");
51 grid.className = "palette-grid";
52 if (activeTab === "grounds")
53 {
54 for (const def of listPlaceableGrounds())
55 {
56 const state = defaultStateForType(catalog, "ground", def.key);
57 const name = spriteImageName("ground", def.key, resolveState(
58 catalog.grounds?.[def.key]?.states ?? [],
59 state
60 ));
61 grid.append(tileCard({
62 label: def.displayName,
63 url: imageUrlFor?.(name),
64 onClick ()
65 {
66 onSelect({ kind: "ground", typeId: def.id });
67 show(false);
68 }
69 }));
70 }
71 }
72 else if (activeTab === "blocks")
73 {
74 for (const def of listPlaceableBlocks())
75 {
76 const state = defaultStateForType(catalog, "block", def.key);
77 const name = spriteImageName("block", def.key, resolveState(
78 catalog.blocks?.[def.key]?.states ?? [],
79 state
80 ));
81 grid.append(tileCard({
82 label: def.displayName,
83 url: imageUrlFor?.(name),
84 onClick ()
85 {
86 onSelect({ kind: "block", typeId: def.id });
87 show(false);
88 }
89 }));
90 }
91 }
92 else
93 {
94 for (const def of listSpawnableMobTypes())
95 {
96 grid.append(tileCard({
97 label: def.displayName,
98 url: imageUrlFor?.(mobSpriteName(def.mobTypeId)),
99 onClick ()
100 {
101 onSelect({ kind: "spawner", mobTypeId: def.mobTypeId });
102 show(false);
103 }
104 }));
105 }
106 }
107 panels.append(grid);
108 }
109
110 document.getElementById("open-palette").addEventListener("click", () => show(true));
111 document.getElementById("palette-close").addEventListener("click", () => show(false));
112 backdrop.addEventListener("click", () => show(false));
113
114 return {
115 isOpen: () => open,
116 close: () => show(false)
117 };
118}
119
120function tileCard ({ label, url, onClick })
121{
122 const button = document.createElement("button");
123 button.type = "button";
124 button.className = "palette-card";
125 const thumb = document.createElement("div");
126 thumb.className = "palette-thumb";
127 if (url)
128 {
129 const img = document.createElement("img");
130 img.alt = "";
131 img.src = url;
132 img.onerror = () =>
133 {
134 img.remove();
135 thumb.textContent = label.slice(0, 1);
136 };
137 thumb.append(img);
138 }
139 else
140 { thumb.textContent = label.slice(0, 1); }
141 const caption = document.createElement("span");
142 caption.textContent = label;
143 button.append(thumb, caption);
144 button.addEventListener("click", onClick);
145 return button;
146}
client/src/editor/tileConfigModal.js added +125 −0
@@ -0,0 +1,125 @@
1 /**
2 * Right-click config modal for editor tiles that have configurable data (spawners).
3 */
4 import { listSpawnableMobTypes, normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
5
6 export function initTileConfigModal ({ onSave, onRemove })
7 {
8 const backdrop = document.getElementById("tile-config-backdrop");
9 const modal = document.getElementById("tile-config-modal");
10 const form = document.getElementById("tile-config-form");
11 const title = document.getElementById("tile-config-title");
12 let open = false;
13 let context = null;
14
15 function show (visible)
16 {
17 open = visible;
18 backdrop.hidden = !visible;
19 modal.hidden = !visible;
20 if (!visible)
21 { context = null; }
22 }
23
24 function openSpawner (ctx)
25 {
26 context = { kind: "spawner", ...ctx };
27 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
28 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
29 form.innerHTML = "";
30 form.append(
31 field("Mob type", mobSelect("mobTypeId", config.mobTypeId)),
32 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
33 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
34 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
35 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
36 );
37 const spawnInput = form.querySelector('[name="spawnRangeTiles"]');
38 const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]');
39 const syncWanderMin = () =>
40 {
41 const spawn = Number(spawnInput.value) || 1;
42 wanderInput.min = String(spawn);
43 if (Number(wanderInput.value) < spawn)
44 { wanderInput.value = String(spawn); }
45 };
46 spawnInput.addEventListener("input", syncWanderMin);
47 syncWanderMin();
48 show(true);
49 }
50
51 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
52 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
53 backdrop.addEventListener("click", () => show(false));
54 document.getElementById("tile-config-save").addEventListener("click", () =>
55 {
56 if (!context)
57 { return; }
58 const data = new FormData(form);
59 onSave?.(context, normalizeSpawnerConfig({
60 mobTypeId: String(data.get("mobTypeId") || "deer"),
61 maxAlive: Number(data.get("maxAlive") || 3),
62 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
63 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
64 spawnerId: String(data.get("spawnerId") || context.config.spawnerId)
65 }, context.config.spawnerId));
66 show(false);
67 });
68 document.getElementById("tile-config-remove").addEventListener("click", () =>
69 {
70 if (!context)
71 { return; }
72 onRemove?.(context);
73 show(false);
74 });
75
76 return {
77 isOpen: () => open,
78 openSpawner,
79 close: () => show(false)
80 };
81 }
82
83 function field (label, input)
84 {
85 const wrap = document.createElement("label");
86 wrap.append(document.createTextNode(label), input);
87 return wrap;
88 }
89
90 function numberInput (name, value, min, max)
91 {
92 const input = document.createElement("input");
93 input.type = "number";
94 input.name = name;
95 input.min = String(min);
96 input.max = String(max);
97 input.value = String(value);
98 return input;
99 }
100
101 function textInput (name, value, readOnly = false)
102 {
103 const input = document.createElement("input");
104 input.type = "text";
105 input.name = name;
106 input.value = String(value ?? "");
107 input.readOnly = readOnly;
108 return input;
109 }
110
111 function mobSelect (name, value)
112 {
113 const select = document.createElement("select");
114 select.name = name;
115 for (const def of listSpawnableMobTypes())
116 {
117 const option = document.createElement("option");
118 option.value = def.mobTypeId;
119 option.textContent = def.displayName;
120 if (def.mobTypeId === value)
121 { option.selected = true; }
122 select.append(option);
123 }
124 return select;
125 }
@@ -0,0 +1,125 @@
1/**
2 * Right-click config modal for editor tiles that have configurable data (spawners).
3 */
4import { listSpawnableMobTypes, normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
5
6export function initTileConfigModal ({ onSave, onRemove })
7{
8 const backdrop = document.getElementById("tile-config-backdrop");
9 const modal = document.getElementById("tile-config-modal");
10 const form = document.getElementById("tile-config-form");
11 const title = document.getElementById("tile-config-title");
12 let open = false;
13 let context = null;
14
15 function show (visible)
16 {
17 open = visible;
18 backdrop.hidden = !visible;
19 modal.hidden = !visible;
20 if (!visible)
21 { context = null; }
22 }
23
24 function openSpawner (ctx)
25 {
26 context = { kind: "spawner", ...ctx };
27 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
28 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
29 form.innerHTML = "";
30 form.append(
31 field("Mob type", mobSelect("mobTypeId", config.mobTypeId)),
32 field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)),
33 field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)),
34 field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)),
35 field("Spawner id", textInput("spawnerId", config.spawnerId, true))
36 );
37 const spawnInput = form.querySelector('[name="spawnRangeTiles"]');
38 const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]');
39 const syncWanderMin = () =>
40 {
41 const spawn = Number(spawnInput.value) || 1;
42 wanderInput.min = String(spawn);
43 if (Number(wanderInput.value) < spawn)
44 { wanderInput.value = String(spawn); }
45 };
46 spawnInput.addEventListener("input", syncWanderMin);
47 syncWanderMin();
48 show(true);
49 }
50
51 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
52 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
53 backdrop.addEventListener("click", () => show(false));
54 document.getElementById("tile-config-save").addEventListener("click", () =>
55 {
56 if (!context)
57 { return; }
58 const data = new FormData(form);
59 onSave?.(context, normalizeSpawnerConfig({
60 mobTypeId: String(data.get("mobTypeId") || "deer"),
61 maxAlive: Number(data.get("maxAlive") || 3),
62 spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4),
63 maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4),
64 spawnerId: String(data.get("spawnerId") || context.config.spawnerId)
65 }, context.config.spawnerId));
66 show(false);
67 });
68 document.getElementById("tile-config-remove").addEventListener("click", () =>
69 {
70 if (!context)
71 { return; }
72 onRemove?.(context);
73 show(false);
74 });
75
76 return {
77 isOpen: () => open,
78 openSpawner,
79 close: () => show(false)
80 };
81}
82
83function field (label, input)
84{
85 const wrap = document.createElement("label");
86 wrap.append(document.createTextNode(label), input);
87 return wrap;
88}
89
90function numberInput (name, value, min, max)
91{
92 const input = document.createElement("input");
93 input.type = "number";
94 input.name = name;
95 input.min = String(min);
96 input.max = String(max);
97 input.value = String(value);
98 return input;
99}
100
101function textInput (name, value, readOnly = false)
102{
103 const input = document.createElement("input");
104 input.type = "text";
105 input.name = name;
106 input.value = String(value ?? "");
107 input.readOnly = readOnly;
108 return input;
109}
110
111function mobSelect (name, value)
112{
113 const select = document.createElement("select");
114 select.name = name;
115 for (const def of listSpawnableMobTypes())
116 {
117 const option = document.createElement("option");
118 option.value = def.mobTypeId;
119 option.textContent = def.displayName;
120 if (def.mobTypeId === value)
121 { option.selected = true; }
122 select.append(option);
123 }
124 return select;
125}
client/src/render/chunkBake.js +1 −1
@@ -135,7 +135,7 @@ function blockSpriteName (catalog, block)
135 135 if (!entry)
136 136 { return null; }
137 137 const def = BLOCK_DEFINITIONS[entry.typeId];
138 if (!def)
138 if (!def || def.editorHidden)
139 139 { return null; }
140 140 const states = catalog.blocks?.[def.key]?.states ?? [];
141 141 const state = resolveState(states, entry.state);
@@ -135,7 +135,7 @@ function blockSpriteName (catalog, block)
135 if (!entry)
135 if (!entry)
136 { return null; }
136 { return null; }
137 const def = BLOCK_DEFINITIONS[entry.typeId];
137 const def = BLOCK_DEFINITIONS[entry.typeId];
138 if (!def)
138 if (!def || def.editorHidden)
139 { return null; }
139 { return null; }
140 const states = catalog.blocks?.[def.key]?.states ?? [];
140 const states = catalog.blocks?.[def.key]?.states ?? [];
141 const state = resolveState(states, entry.state);
141 const state = resolveState(states, entry.state);
client/src/render/sprites.js +3 −1
@@ -2,7 +2,9 @@ import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2 2
3 3 export const UTILITY_IMAGES = [
4 4 { name: "night-shade", url: shadeDataUrl("#000000") },
5 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") }
5 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") },
6 { name: "spawn-range", url: shadeDataUrl("rgba(72, 180, 210, 0.32)") },
7 { name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") }
6 8 ];
7 9
8 10 export function playImagesFromCatalog (catalog)
@@ -2,7 +2,9 @@ import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2
2
3export const UTILITY_IMAGES = [
3export const UTILITY_IMAGES = [
4 { name: "night-shade", url: shadeDataUrl("#000000") },
4 { name: "night-shade", url: shadeDataUrl("#000000") },
5 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") }
5 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") },
6 { name: "spawn-range", url: shadeDataUrl("rgba(72, 180, 210, 0.32)") },
7 { name: "wander-range", url: shadeDataUrl("rgba(210, 170, 72, 0.22)") }
6];
8];
7
9
8export function playImagesFromCatalog (catalog)
10export function playImagesFromCatalog (catalog)
client/src/render/worldView.js +133 −0
@@ -105,6 +105,10 @@ export class WorldView
105 105 this.swipes = [];
106 106 this.damageFloats = [];
107 107 this.damageNumbersEl = document.getElementById("damage-numbers");
108 /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */
109 this.editorSpawners = new Map();
110 this.spawnRangeHighlight = null;
111 this.wanderRangeHighlight = null;
108 112 this.#syncBloomLayer();
109 113 }
110 114
@@ -155,6 +159,14 @@ export class WorldView
155 159 this.chunks.delete(key);
156 160 this.#destroyBakedChunk(key);
157 161 this.#destroyEdges(key);
162 const prefix = `${chunkX},${chunkY}:`;
163 for (const [spawnerKey, entry] of [...this.editorSpawners.entries()])
164 {
165 if (!spawnerKey.startsWith(prefix))
166 { continue; }
167 entry.object?.destroy();
168 this.editorSpawners.delete(spawnerKey);
169 }
158 170 for (const [tileKey, objects] of [...this.tiles.entries()])
159 171 {
160 172 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
@@ -365,6 +377,8 @@ export class WorldView
365 377 }
366 378 this.#rebuildAllEdges();
367 379 this.#redrawPreview();
380 this.#relayoutEditorSpawners();
381 this.#relayoutSpawnRangeHighlight();
368 382 applyNearestToAllTextures(this.scene, this.game.images);
369 383 }
370 384
@@ -585,6 +599,125 @@ export class WorldView
585 599 this.#rebuildChunk(snapshot);
586 600 }
587 601
602 /**
603 * Editor-only mob markers for authored spawners (invisible during play).
604 * @param {number} chunkX
605 * @param {number} chunkY
606 * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners
607 * @param {(mobTypeId: string) => string} resolveSprite
608 */
609 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
610 {
611 const prefix = `${chunkX},${chunkY}:`;
612 for (const [key, entry] of [...this.editorSpawners.entries()])
613 {
614 if (!key.startsWith(prefix))
615 { continue; }
616 entry.object?.destroy();
617 this.editorSpawners.delete(key);
618 }
619 for (const spawner of spawners ?? [])
620 {
621 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
622 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
623 const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null;
624 if (!spriteName)
625 { continue; }
626 const key = `${prefix}${spawner.localX},${spawner.localY}`;
627 const object = this.#ensureSprite(null, spriteName, SORT_ENTITY);
628 if (!object)
629 { continue; }
630 object.renderer.alpha = 0.85;
631 const pivot = tilePivot(tileX, tileY, this.tileSize());
632 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
633 this.#markUnlit(object);
634 this.editorSpawners.set(key, { object, tileX, tileY, spriteName });
635 }
636 }
637
638 clearEditorSpawners ()
639 {
640 for (const entry of this.editorSpawners.values())
641 { entry.object?.destroy(); }
642 this.editorSpawners.clear();
643 }
644
645 #relayoutEditorSpawners ()
646 {
647 const size = this.tileSize();
648 for (const entry of this.editorSpawners.values())
649 {
650 if (!entry.object)
651 { continue; }
652 const pivot = tilePivot(entry.tileX, entry.tileY, size);
653 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
654 }
655 }
656
657 /**
658 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
659 */
660 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
661 {
662 const spawnRadius = Math.max(0, spawnRange | 0);
663 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
664 if (this.spawnRangeHighlight
665 && this.wanderRangeHighlight
666 && this.spawnRangeHighlight.tileX === tileX
667 && this.spawnRangeHighlight.tileY === tileY
668 && this.spawnRangeHighlight.range === spawnRadius
669 && this.wanderRangeHighlight.range === wanderRadius)
670 {
671 this.#relayoutSpawnRangeHighlight();
672 return;
673 }
674 this.clearSpawnRangeHighlight();
675 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
676 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
677 if (wanderObject)
678 {
679 this.#markUnlit(wanderObject);
680 wanderObject.renderer.alpha = 1;
681 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
682 }
683 if (spawnObject)
684 {
685 this.#markUnlit(spawnObject);
686 spawnObject.renderer.alpha = 1;
687 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
688 }
689 this.#relayoutSpawnRangeHighlight();
690 }
691
692 clearSpawnRangeHighlight ()
693 {
694 this.spawnRangeHighlight?.object?.destroy();
695 this.wanderRangeHighlight?.object?.destroy();
696 this.spawnRangeHighlight = null;
697 this.wanderRangeHighlight = null;
698 }
699
700 #relayoutSpawnRangeHighlight ()
701 {
702 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
703 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
704 }
705
706 #layoutRangeOverlay (highlight, layer)
707 {
708 if (!highlight?.object)
709 { return; }
710 const size = this.tileSize();
711 const side = (2 * highlight.range + 1) * size;
712 const left = (highlight.tileX - highlight.range) * size;
713 const top = (highlight.tileY - highlight.range) * size;
714 highlight.object.transform.position.x = left + side / 2;
715 highlight.object.transform.position.y = top + side / 2;
716 highlight.object.transform.size = new vector(side, side);
717 highlight.object.layer = layer;
718 this.#markSortDirty();
719 }
720
588 721 setTilePreview (tileX, tileY, override)
589 722 {
590 723 const previous = this.preview;
@@ -105,6 +105,10 @@ export class WorldView
105 this.swipes = [];
105 this.swipes = [];
106 this.damageFloats = [];
106 this.damageFloats = [];
107 this.damageNumbersEl = document.getElementById("damage-numbers");
107 this.damageNumbersEl = document.getElementById("damage-numbers");
108 /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */
109 this.editorSpawners = new Map();
110 this.spawnRangeHighlight = null;
111 this.wanderRangeHighlight = null;
108 this.#syncBloomLayer();
112 this.#syncBloomLayer();
109 }
113 }
110
114
@@ -155,6 +159,14 @@ export class WorldView
155 this.chunks.delete(key);
159 this.chunks.delete(key);
156 this.#destroyBakedChunk(key);
160 this.#destroyBakedChunk(key);
157 this.#destroyEdges(key);
161 this.#destroyEdges(key);
162 const prefix = `${chunkX},${chunkY}:`;
163 for (const [spawnerKey, entry] of [...this.editorSpawners.entries()])
164 {
165 if (!spawnerKey.startsWith(prefix))
166 { continue; }
167 entry.object?.destroy();
168 this.editorSpawners.delete(spawnerKey);
169 }
158 for (const [tileKey, objects] of [...this.tiles.entries()])
170 for (const [tileKey, objects] of [...this.tiles.entries()])
159 {
171 {
160 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
172 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
@@ -365,6 +377,8 @@ export class WorldView
365 }
377 }
366 this.#rebuildAllEdges();
378 this.#rebuildAllEdges();
367 this.#redrawPreview();
379 this.#redrawPreview();
380 this.#relayoutEditorSpawners();
381 this.#relayoutSpawnRangeHighlight();
368 applyNearestToAllTextures(this.scene, this.game.images);
382 applyNearestToAllTextures(this.scene, this.game.images);
369 }
383 }
370
384
@@ -585,6 +599,125 @@ export class WorldView
585 this.#rebuildChunk(snapshot);
599 this.#rebuildChunk(snapshot);
586 }
600 }
587
601
602 /**
603 * Editor-only mob markers for authored spawners (invisible during play).
604 * @param {number} chunkX
605 * @param {number} chunkY
606 * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners
607 * @param {(mobTypeId: string) => string} resolveSprite
608 */
609 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
610 {
611 const prefix = `${chunkX},${chunkY}:`;
612 for (const [key, entry] of [...this.editorSpawners.entries()])
613 {
614 if (!key.startsWith(prefix))
615 { continue; }
616 entry.object?.destroy();
617 this.editorSpawners.delete(key);
618 }
619 for (const spawner of spawners ?? [])
620 {
621 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
622 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
623 const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null;
624 if (!spriteName)
625 { continue; }
626 const key = `${prefix}${spawner.localX},${spawner.localY}`;
627 const object = this.#ensureSprite(null, spriteName, SORT_ENTITY);
628 if (!object)
629 { continue; }
630 object.renderer.alpha = 0.85;
631 const pivot = tilePivot(tileX, tileY, this.tileSize());
632 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
633 this.#markUnlit(object);
634 this.editorSpawners.set(key, { object, tileX, tileY, spriteName });
635 }
636 }
637
638 clearEditorSpawners ()
639 {
640 for (const entry of this.editorSpawners.values())
641 { entry.object?.destroy(); }
642 this.editorSpawners.clear();
643 }
644
645 #relayoutEditorSpawners ()
646 {
647 const size = this.tileSize();
648 for (const entry of this.editorSpawners.values())
649 {
650 if (!entry.object)
651 { continue; }
652 const pivot = tilePivot(entry.tileX, entry.tileY, size);
653 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
654 }
655 }
656
657 /**
658 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
659 */
660 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
661 {
662 const spawnRadius = Math.max(0, spawnRange | 0);
663 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
664 if (this.spawnRangeHighlight
665 && this.wanderRangeHighlight
666 && this.spawnRangeHighlight.tileX === tileX
667 && this.spawnRangeHighlight.tileY === tileY
668 && this.spawnRangeHighlight.range === spawnRadius
669 && this.wanderRangeHighlight.range === wanderRadius)
670 {
671 this.#relayoutSpawnRangeHighlight();
672 return;
673 }
674 this.clearSpawnRangeHighlight();
675 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
676 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
677 if (wanderObject)
678 {
679 this.#markUnlit(wanderObject);
680 wanderObject.renderer.alpha = 1;
681 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
682 }
683 if (spawnObject)
684 {
685 this.#markUnlit(spawnObject);
686 spawnObject.renderer.alpha = 1;
687 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
688 }
689 this.#relayoutSpawnRangeHighlight();
690 }
691
692 clearSpawnRangeHighlight ()
693 {
694 this.spawnRangeHighlight?.object?.destroy();
695 this.wanderRangeHighlight?.object?.destroy();
696 this.spawnRangeHighlight = null;
697 this.wanderRangeHighlight = null;
698 }
699
700 #relayoutSpawnRangeHighlight ()
701 {
702 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
703 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
704 }
705
706 #layoutRangeOverlay (highlight, layer)
707 {
708 if (!highlight?.object)
709 { return; }
710 const size = this.tileSize();
711 const side = (2 * highlight.range + 1) * size;
712 const left = (highlight.tileX - highlight.range) * size;
713 const top = (highlight.tileY - highlight.range) * size;
714 highlight.object.transform.position.x = left + side / 2;
715 highlight.object.transform.position.y = top + side / 2;
716 highlight.object.transform.size = new vector(side, side);
717 highlight.object.layer = layer;
718 this.#markSortDirty();
719 }
720
588 setTilePreview (tileX, tileY, override)
721 setTilePreview (tileX, tileY, override)
589 {
722 {
590 const previous = this.preview;
723 const previous = this.preview;
client/ui/editor.css +116 −0
@@ -226,3 +226,119 @@ label { display: block; margin: 0.4rem 0; }
226 226 overflow: auto;
227 227 padding: 0.75rem 1rem;
228 228 }
229
230 #palette-backdrop,
231 #tile-config-backdrop {
232 position: fixed;
233 inset: 0;
234 background: rgba(0, 0, 0, 0.62);
235 z-index: 19;
236 }
237
238 #palette-modal,
239 #tile-config-modal {
240 position: fixed;
241 z-index: 20;
242 display: flex;
243 flex-direction: column;
244 background: #161a22;
245 border: 1px solid #3a4250;
246 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
247 }
248
249 #palette-modal {
250 inset: 8vh 12vw;
251 }
252
253 #tile-config-modal {
254 top: 20vh;
255 left: 50%;
256 transform: translateX(-50%);
257 width: min(420px, 90vw);
258 }
259
260 #palette-modal[hidden],
261 #palette-backdrop[hidden],
262 #tile-config-modal[hidden],
263 #tile-config-backdrop[hidden],
264 #tile-tooltip[hidden] {
265 display: none !important;
266 }
267
268 #palette-modal > header,
269 #tile-config-modal > header,
270 #tile-config-modal > footer {
271 display: flex;
272 align-items: center;
273 justify-content: space-between;
274 gap: 0.75rem;
275 padding: 0.75rem 1rem;
276 border-bottom: 1px solid #2c3340;
277 }
278
279 #tile-config-modal > footer {
280 border-bottom: 0;
281 border-top: 1px solid #2c3340;
282 }
283
284 #palette-panels {
285 flex: 1;
286 overflow: auto;
287 padding: 0.75rem 1rem 1.25rem;
288 }
289
290 .palette-grid {
291 display: grid;
292 grid-template-columns: repeat(auto-fill, minmax(7.5rem, 1fr));
293 gap: 0.6rem;
294 }
295
296 .palette-card {
297 display: flex;
298 flex-direction: column;
299 align-items: center;
300 gap: 0.35rem;
301 padding: 0.55rem 0.4rem;
302 min-height: 6.5rem;
303 }
304
305 .palette-thumb {
306 width: 48px;
307 height: 48px;
308 display: grid;
309 place-items: center;
310 background: #0d1016;
311 border: 1px solid #2c3340;
312 image-rendering: pixelated;
313 font-weight: 600;
314 color: #9aa3b2;
315 }
316
317 .palette-thumb img {
318 width: 100%;
319 height: 100%;
320 object-fit: contain;
321 image-rendering: pixelated;
322 }
323
324 #tile-config-form {
325 padding: 0.75rem 1rem 1rem;
326 display: flex;
327 flex-direction: column;
328 gap: 0.35rem;
329 }
330
331 #tile-tooltip {
332 position: fixed;
333 z-index: 15;
334 pointer-events: none;
335 max-width: 16rem;
336 padding: 0.4rem 0.55rem;
337 background: rgba(12, 14, 18, 0.92);
338 border: 1px solid #3a4250;
339 color: #e8e4d9;
340 font-size: 0.8rem;
341 white-space: pre-wrap;
342 box-shadow: 0 6px 18px rgba(0, 0, 0, 0.4);
343 }
344
@@ -226,3 +226,119 @@ label { display: block; margin: 0.4rem 0; }
226 overflow: auto;
226 overflow: auto;
227 padding: 0.75rem 1rem;
227 padding: 0.75rem 1rem;
228}
228}
229
230#palette-backdrop,
231#tile-config-backdrop {
232 position: fixed;
233 inset: 0;
234 background: rgba(0, 0, 0, 0.62);
235 z-index: 19;
236}
237
238#palette-modal,
239#tile-config-modal {
240 position: fixed;
241 z-index: 20;
242 display: flex;
243 flex-direction: column;
244 background: #161a22;
245 border: 1px solid #3a4250;
246 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
247}
248
249#palette-modal {
250 inset: 8vh 12vw;
251}
252
253#tile-config-modal {
254 top: 20vh;
255 left: 50%;
256 transform: translateX(-50%);
257 width: min(420px, 90vw);
258}
259
260#palette-modal[hidden],
261#palette-backdrop[hidden],
262#tile-config-modal[hidden],
263#tile-config-backdrop[hidden],
264#tile-tooltip[hidden] {
265 display: none !important;
266}
267
268#palette-modal > header,
269#tile-config-modal > header,
270#tile-config-modal > footer {
271 display: flex;
272 align-items: center;
273 justify-content: space-between;
274 gap: 0.75rem;
275 padding: 0.75rem 1rem;
276 border-bottom: 1px solid #2c3340;
277}
278
279#tile-config-modal > footer {
280 border-bottom: 0;
281 border-top: 1px solid #2c3340;
282}
283
284#palette-panels {
285 flex: 1;
286 overflow: auto;
287 padding: 0.75rem 1rem 1.25rem;
288}
289
290.palette-grid {
291 display: grid;
292 grid-template-columns: repeat(auto-fill, minmax(7.5rem, 1fr));
293 gap: 0.6rem;
294}
295
296.palette-card {
297 display: flex;
298 flex-direction: column;
299 align-items: center;
300 gap: 0.35rem;
301 padding: 0.55rem 0.4rem;
302 min-height: 6.5rem;
303}
304
305.palette-thumb {
306 width: 48px;
307 height: 48px;
308 display: grid;
309 place-items: center;
310 background: #0d1016;
311 border: 1px solid #2c3340;
312 image-rendering: pixelated;
313 font-weight: 600;
314 color: #9aa3b2;
315}
316
317.palette-thumb img {
318 width: 100%;
319 height: 100%;
320 object-fit: contain;
321 image-rendering: pixelated;
322}
323
324#tile-config-form {
325 padding: 0.75rem 1rem 1rem;
326 display: flex;
327 flex-direction: column;
328 gap: 0.35rem;
329}
330
331#tile-tooltip {
332 position: fixed;
333 z-index: 15;
334 pointer-events: none;
335 max-width: 16rem;
336 padding: 0.4rem 0.55rem;
337 background: rgba(12, 14, 18, 0.92);
338 border: 1px solid #3a4250;
339 color: #e8e4d9;
340 font-size: 0.8rem;
341 white-space: pre-wrap;
342 box-shadow: 0 6px 18px rgba(0, 0, 0, 0.4);
343}
344
docs/FEATURES.md +8 −8
@@ -16,7 +16,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16 16 ## Ground and block tile layers
17 17
18 18 **Status:** full
19 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live block types include grass grounds, wood, stone wall, torch, bank, spawner, and **church altar** (respawn destination — see **Player death and respawn**). **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks stay individual sprites so mobiles can Y-sort behind them.
19 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live block types include grass grounds, wood, stone wall, torch, bank, and **church altar** (respawn destination — see **Player death and respawn**). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks stay individual sprites so mobiles can Y-sort behind them.
20 20 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
21 21
22 22 ## Open and closed chunks
@@ -64,19 +64,19 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
64 64 ## World editor (server)
65 65
66 66 **Status:** full
67 **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks (including spawners and banks), write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace stalls wait on later economy work.
67 **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace stalls wait on later economy work.
68 68 **Code:** `server/src/editor/service.js`
69 69
70 70 ## World editor (client)
71 71
72 72 **Status:** full
73 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states, open/closed, per-chunk changelog, night preview slider, world-settings modal, save chunk and Apply now. Spawner paint uses mob type, max alive and range; bank is a placeable block. Placeholder sprites stand in until real art exists.
74 **Code:** `client/editor.html`, `client/src/editor/main.js`, `client/ui/editor.css`
73 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states, open/closed, per-chunk changelog, night preview slider, world-settings modal, save chunk and Apply now. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
74 **Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
75 75
76 76 ## Per-chunk changelog
77 77
78 78 **Status:** full
79 **Spec:** Each save stores who, when, and structured bullets of ground/block/open-closed diffs.
79 **Spec:** Each save stores who, when, and structured bullets of ground/block/spawner/open-closed diffs.
80 80 **Code:** `server/src/editor/service.js` (`diffChunks`), `server/src/persistence/worldDb.js` (`world_chunk_edit_log`), tests in `server/tests/editor-diff.test.js`
81 81
82 82 ## WebSocket gateway
@@ -178,8 +178,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
178 178 ## Spawners
179 179
180 180 **Status:** full
181 **Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Wildlife options are deer and rats. Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked; courier pigeons cannot.
182 **Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
181 **Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include deer and rats; the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked; courier pigeons cannot.
182 **Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
183 183
184 184 ## Mob definitions (content schema)
185 185
@@ -208,7 +208,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
208 208 ## Combat, skills, groups, pigeons
209 209
210 210 **Status:** partial
211 **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs retaliate when attacked and keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
211 **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs retaliate when attacked and keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
212 212 **Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
213 213
214 214 ## Player death and respawn
@@ -16,7 +16,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16## Ground and block tile layers
16## Ground and block tile layers
17
17
18**Status:** full
18**Status:** full
19**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live block types include grass grounds, wood, stone wall, torch, bank, spawner, and **church altar** (respawn destination — see **Player death and respawn**). **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks stay individual sprites so mobiles can Y-sort behind them.
19**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live block types include grass grounds, wood, stone wall, torch, bank, and **church altar** (respawn destination — see **Player death and respawn**). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks stay individual sprites so mobiles can Y-sort behind them.
20**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
20**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
21
21
22## Open and closed chunks
22## Open and closed chunks
@@ -64,19 +64,19 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
64## World editor (server)
64## World editor (server)
65
65
66**Status:** full
66**Status:** full
67**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks (including spawners and banks), write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace stalls wait on later economy work.
67**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace stalls wait on later economy work.
68**Code:** `server/src/editor/service.js`
68**Code:** `server/src/editor/service.js`
69
69
70## World editor (client)
70## World editor (client)
71
71
72**Status:** full
72**Status:** full
73**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states, open/closed, per-chunk changelog, night preview slider, world-settings modal, save chunk and Apply now. Spawner paint uses mob type, max alive and range; bank is a placeable block. Placeholder sprites stand in until real art exists.
73**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states, open/closed, per-chunk changelog, night preview slider, world-settings modal, save chunk and Apply now. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
74**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/ui/editor.css`
74**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
75
75
76## Per-chunk changelog
76## Per-chunk changelog
77
77
78**Status:** full
78**Status:** full
79**Spec:** Each save stores who, when, and structured bullets of ground/block/open-closed diffs.
79**Spec:** Each save stores who, when, and structured bullets of ground/block/spawner/open-closed diffs.
80**Code:** `server/src/editor/service.js` (`diffChunks`), `server/src/persistence/worldDb.js` (`world_chunk_edit_log`), tests in `server/tests/editor-diff.test.js`
80**Code:** `server/src/editor/service.js` (`diffChunks`), `server/src/persistence/worldDb.js` (`world_chunk_edit_log`), tests in `server/tests/editor-diff.test.js`
81
81
82## WebSocket gateway
82## WebSocket gateway
@@ -178,8 +178,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
178## Spawners
178## Spawners
179
179
180**Status:** full
180**Status:** full
181**Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Wildlife options are deer and rats. Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked; courier pigeons cannot.
181**Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include deer and rats; the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked; courier pigeons cannot.
182**Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
182**Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
183
183
184## Mob definitions (content schema)
184## Mob definitions (content schema)
185
185
@@ -208,7 +208,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
208## Combat, skills, groups, pigeons
208## Combat, skills, groups, pigeons
209
209
210**Status:** partial
210**Status:** partial
211**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs retaliate when attacked and keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
211**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs retaliate when attacked and keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
212**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
212**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
213
213
214## Player death and respawn
214## Player death and respawn
server/src/editor/service.js +30 −1
@@ -1,7 +1,7 @@
1 1 import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock } from "../../../shared/definitions/tiles.js";
2 2 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3 3 import { localToTile } from "../world/coordinates.js";
4 import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob } from "../world/chunkData.js";
4 import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob, normalizeSpawner } from "../world/chunkData.js";
5 5 import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
6 6 import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
7 7 import { closedNeighborEdges } from "../world/chunkFlags.js";
@@ -53,6 +53,8 @@ export class EditorService
53 53 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, settings.defaultGroundTypeId)); }
54 54 if (Array.isArray(draft.blocks))
55 55 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
56 if (Array.isArray(draft.spawners))
57 { next.spawners = draft.spawners.map((entry) => normalizeSpawner(entry)).filter(Boolean); }
56 58
57 59 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
58 60 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
@@ -205,9 +207,36 @@ export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
205 207 }
206 208 }
207 209 }
210
211 const prevSpawners = indexSpawners(previous.spawners);
212 const nextSpawners = indexSpawners(next.spawners);
213 for (const key of new Set([...prevSpawners.keys(), ...nextSpawners.keys()]))
214 {
215 const prev = prevSpawners.get(key);
216 const cur = nextSpawners.get(key);
217 const [localX, localY] = key.split(",").map(Number);
218 const tileX = localToTile(chunkX, localX);
219 const tileY = localToTile(chunkY, localY);
220 const prevConfig = JSON.stringify(prev?.config ?? null);
221 const nextConfig = JSON.stringify(cur?.config ?? null);
222 if (!prev && cur)
223 { bullets.push(`Spawner (${cur.config.mobTypeId}) placed at ${tileX}, ${tileY}.`); }
224 else if (prev && !cur)
225 { bullets.push(`Spawner removed at ${tileX}, ${tileY}.`); }
226 else if (prevConfig !== nextConfig)
227 { bullets.push(`Spawner at ${tileX}, ${tileY} config changed.`); }
228 }
208 229 return bullets;
209 230 }
210 231
232 function indexSpawners (spawners)
233 {
234 const map = new Map();
235 for (const entry of spawners ?? [])
236 { map.set(`${entry.localX},${entry.localY}`, entry); }
237 return map;
238 }
239
211 240 function nameGround (typeId)
212 241 {
213 242 return groundDefinition(typeId)?.displayName ?? `ground ${typeId}`;
@@ -1,7 +1,7 @@
1import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock } from "../../../shared/definitions/tiles.js";
1import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock } from "../../../shared/definitions/tiles.js";
2import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3import { localToTile } from "../world/coordinates.js";
3import { localToTile } from "../world/coordinates.js";
4import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob } from "../world/chunkData.js";
4import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob, normalizeSpawner } from "../world/chunkData.js";
5import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
5import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
6import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
6import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
7import { closedNeighborEdges } from "../world/chunkFlags.js";
7import { closedNeighborEdges } from "../world/chunkFlags.js";
@@ -53,6 +53,8 @@ export class EditorService
53 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, settings.defaultGroundTypeId)); }
53 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, settings.defaultGroundTypeId)); }
54 if (Array.isArray(draft.blocks))
54 if (Array.isArray(draft.blocks))
55 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
55 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
56 if (Array.isArray(draft.spawners))
57 { next.spawners = draft.spawners.map((entry) => normalizeSpawner(entry)).filter(Boolean); }
56
58
57 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
59 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
58 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
60 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
@@ -205,9 +207,36 @@ export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
205 }
207 }
206 }
208 }
207 }
209 }
210
211 const prevSpawners = indexSpawners(previous.spawners);
212 const nextSpawners = indexSpawners(next.spawners);
213 for (const key of new Set([...prevSpawners.keys(), ...nextSpawners.keys()]))
214 {
215 const prev = prevSpawners.get(key);
216 const cur = nextSpawners.get(key);
217 const [localX, localY] = key.split(",").map(Number);
218 const tileX = localToTile(chunkX, localX);
219 const tileY = localToTile(chunkY, localY);
220 const prevConfig = JSON.stringify(prev?.config ?? null);
221 const nextConfig = JSON.stringify(cur?.config ?? null);
222 if (!prev && cur)
223 { bullets.push(`Spawner (${cur.config.mobTypeId}) placed at ${tileX}, ${tileY}.`); }
224 else if (prev && !cur)
225 { bullets.push(`Spawner removed at ${tileX}, ${tileY}.`); }
226 else if (prevConfig !== nextConfig)
227 { bullets.push(`Spawner at ${tileX}, ${tileY} config changed.`); }
228 }
208 return bullets;
229 return bullets;
209}
230}
210
231
232function indexSpawners (spawners)
233{
234 const map = new Map();
235 for (const entry of spawners ?? [])
236 { map.set(`${entry.localX},${entry.localY}`, entry); }
237 return map;
238}
239
211function nameGround (typeId)
240function nameGround (typeId)
212{
241{
213 return groundDefinition(typeId)?.displayName ?? `ground ${typeId}`;
242 return groundDefinition(typeId)?.displayName ?? `ground ${typeId}`;
server/src/persistence/stateDb.js +17 −5
@@ -500,11 +500,8 @@ export class StateDatabase
500 500 {
501 501 const parsed = JSON.parse(row.skills_blob || "{}");
502 502 const skills = normalizePlayerSkills(parsed);
503 const rawHealth = Number(
504 (parsed?.xp && typeof parsed.xp === "object" ? parsed.xp.health : parsed?.health) ?? 0
505 ) || 0;
506 // Persist the Health level-10 floor for legacy `{}` / under-leveled rows.
507 if (rawHealth < skills.xp.health)
503 // Persist floors (Health ≥ 10, others ≥ 1) for legacy under-leveled rows.
504 if (this.#skillsBlobNeedsRewrite(parsed, skills))
508 505 { this.saveSkills(characterId, skills); }
509 506 return skills;
510 507 }
@@ -516,6 +513,21 @@ export class StateDatabase
516 513 return null;
517 514 }
518 515
516 /** True when stored blob is below the default minimum levels and must be rewritten. */
517 #skillsBlobNeedsRewrite (parsed, normalized)
518 {
519 const raw = parsed?.xp && typeof parsed.xp === "object" ? parsed.xp : parsed;
520 if (!raw || typeof raw !== "object")
521 { return true; }
522 for (const skillId of Object.keys(normalized.xp))
523 {
524 const stored = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
525 if (stored < normalized.xp[skillId])
526 { return true; }
527 }
528 return false;
529 }
530
519 531 saveSkills (characterId, skills)
520 532 {
521 533 this.#ensureBag(characterId);
@@ -500,11 +500,8 @@ export class StateDatabase
500 {
500 {
501 const parsed = JSON.parse(row.skills_blob || "{}");
501 const parsed = JSON.parse(row.skills_blob || "{}");
502 const skills = normalizePlayerSkills(parsed);
502 const skills = normalizePlayerSkills(parsed);
503 const rawHealth = Number(
503 // Persist floors (Health ≥ 10, others ≥ 1) for legacy under-leveled rows.
504 (parsed?.xp && typeof parsed.xp === "object" ? parsed.xp.health : parsed?.health) ?? 0
504 if (this.#skillsBlobNeedsRewrite(parsed, skills))
505 ) || 0;
506 // Persist the Health level-10 floor for legacy `{}` / under-leveled rows.
507 if (rawHealth < skills.xp.health)
508 { this.saveSkills(characterId, skills); }
505 { this.saveSkills(characterId, skills); }
509 return skills;
506 return skills;
510 }
507 }
@@ -516,6 +513,21 @@ export class StateDatabase
516 return null;
513 return null;
517 }
514 }
518
515
516 /** True when stored blob is below the default minimum levels and must be rewritten. */
517 #skillsBlobNeedsRewrite (parsed, normalized)
518 {
519 const raw = parsed?.xp && typeof parsed.xp === "object" ? parsed.xp : parsed;
520 if (!raw || typeof raw !== "object")
521 { return true; }
522 for (const skillId of Object.keys(normalized.xp))
523 {
524 const stored = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
525 if (stored < normalized.xp[skillId])
526 { return true; }
527 }
528 return false;
529 }
530
519 saveSkills (characterId, skills)
531 saveSkills (characterId, skills)
520 {
532 {
521 this.#ensureBag(characterId);
533 this.#ensureBag(characterId);
server/src/simulation/simulation.js +24 −1
@@ -29,7 +29,7 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29 29 import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30 30 import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31 31 import { mobComponents } from "./spawners.js";
32 import { defaultPlayerSkills } from "../../../shared/skills/state.js";
32 import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
33 33 import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
34 34 import { BlockType } from "../../../shared/definitions/tiles.js";
35 35 import { ItemId } from "../../../shared/definitions/items.js";
@@ -57,6 +57,7 @@ export class Simulation
57 57 this.courier = null;
58 58 this.altarTiles = [];
59 59 this.authoredCache = new Map();
60 this.simulatingChunkKeys = new Set();
60 61 this.nextEntityId = 1;
61 62 this.nextGroundItemId = stateDb.nextGroundItemId();
62 63 this.tickIndex = 0;
@@ -278,6 +279,9 @@ export class Simulation
278 279 vaultReserved: []
279 280 };
280 281 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
282 // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
283 if (enforceMinimumSkillLevels(skills))
284 { this.stateDb.saveSkills(character.character_id, skills); }
281 285 const maxHealth = playerMaxHealth(skills);
282 286 const maxStamina = playerMaxStamina(skills);
283 287 const isDead = !!row.is_dead;
@@ -1066,6 +1070,25 @@ export class Simulation
1066 1070 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
1067 1071 }
1068 1072 this.#syncAllReplicas();
1073
1074 const nextSimulating = new Set();
1075 for (const [key, count] of chunkSim)
1076 {
1077 if (count > 0)
1078 { nextSimulating.add(key); }
1079 }
1080 let preheated = false;
1081 for (const key of nextSimulating)
1082 {
1083 if (!this.simulatingChunkKeys.has(key))
1084 {
1085 preheated = true;
1086 break;
1087 }
1088 }
1089 this.simulatingChunkKeys = nextSimulating;
1090 if (preheated)
1091 { this.#stepSpawners(); }
1069 1092 }
1070 1093
1071 1094 #ensureCoverage (tileX, tileY, loader)
@@ -29,7 +29,7 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
29import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
30import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31import { mobComponents } from "./spawners.js";
31import { mobComponents } from "./spawners.js";
32import { defaultPlayerSkills } from "../../../shared/skills/state.js";
32import { defaultPlayerSkills, enforceMinimumSkillLevels } from "../../../shared/skills/state.js";
33import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
33import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
34import { BlockType } from "../../../shared/definitions/tiles.js";
34import { BlockType } from "../../../shared/definitions/tiles.js";
35import { ItemId } from "../../../shared/definitions/items.js";
35import { ItemId } from "../../../shared/definitions/items.js";
@@ -57,6 +57,7 @@ export class Simulation
57 this.courier = null;
57 this.courier = null;
58 this.altarTiles = [];
58 this.altarTiles = [];
59 this.authoredCache = new Map();
59 this.authoredCache = new Map();
60 this.simulatingChunkKeys = new Set();
60 this.nextEntityId = 1;
61 this.nextEntityId = 1;
61 this.nextGroundItemId = stateDb.nextGroundItemId();
62 this.nextGroundItemId = stateDb.nextGroundItemId();
62 this.tickIndex = 0;
63 this.tickIndex = 0;
@@ -278,6 +279,9 @@ export class Simulation
278 vaultReserved: []
279 vaultReserved: []
279 };
280 };
280 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
281 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
282 // Login floor: Health ≥ 10, every other skill ≥ 1 (persist if raised).
283 if (enforceMinimumSkillLevels(skills))
284 { this.stateDb.saveSkills(character.character_id, skills); }
281 const maxHealth = playerMaxHealth(skills);
285 const maxHealth = playerMaxHealth(skills);
282 const maxStamina = playerMaxStamina(skills);
286 const maxStamina = playerMaxStamina(skills);
283 const isDead = !!row.is_dead;
287 const isDead = !!row.is_dead;
@@ -1066,6 +1070,25 @@ export class Simulation
1066 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
1070 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
1067 }
1071 }
1068 this.#syncAllReplicas();
1072 this.#syncAllReplicas();
1073
1074 const nextSimulating = new Set();
1075 for (const [key, count] of chunkSim)
1076 {
1077 if (count > 0)
1078 { nextSimulating.add(key); }
1079 }
1080 let preheated = false;
1081 for (const key of nextSimulating)
1082 {
1083 if (!this.simulatingChunkKeys.has(key))
1084 {
1085 preheated = true;
1086 break;
1087 }
1088 }
1089 this.simulatingChunkKeys = nextSimulating;
1090 if (preheated)
1091 { this.#stepSpawners(); }
1069 }
1092 }
1070
1093
1071 #ensureCoverage (tileX, tileY, loader)
1094 #ensureCoverage (tileX, tileY, loader)
server/src/simulation/spawners.js +40 −22
@@ -1,8 +1,7 @@
1 1 import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 2 import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";
4 3 import {
5 defaultSpawnerConfig,
4 normalizeSpawnerConfig,
6 5 listAmbientMobTypes,
7 6 mobDefinition,
8 7 mobSpriteName
@@ -14,38 +13,45 @@ export function collectSpawnRequests (world)
14 13 {
15 14 const requests = [];
16 15 const counts = countBySpawner(world);
16 const reserved = new Set();
17 17 for (const [key, chunk] of world.chunks)
18 18 {
19 19 if (chunk.replica || !chunk.simulating || !chunk.data.open)
20 20 { continue; }
21 21 const [chunkX, chunkY] = key.split(",").map(Number);
22 for (let localY = 0; localY < CHUNK_SIZE; localY++)
22 for (const entry of chunk.data.spawners ?? [])
23 23 {
24 for (let localX = 0; localX < CHUNK_SIZE; localX++)
24 const localX = entry.localX;
25 const localY = entry.localY;
26 const index = localY * CHUNK_SIZE + localX;
27 const config = normalizeSpawnerConfig(
28 entry.config,
29 `${chunkX}:${chunkY}:${index}`
30 );
31 const flying = !!mobDefinition(config.mobTypeId)?.flying;
32 const originX = chunkX * CHUNK_SIZE + localX;
33 const originY = chunkY * CHUNK_SIZE + localY;
34 const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
35 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
25 36 {
26 const block = chunk.data.blocks[localY * CHUNK_SIZE + localX];
27 if (block?.typeId !== BlockType.spawner)
28 { continue; }
29 const config = { ...defaultSpawnerConfig(`${chunkX}:${chunkY}:${localY * CHUNK_SIZE + localX}`), ...(block.config ?? {}) };
30 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
31 { continue; }
32 const originX = chunkX * CHUNK_SIZE + localX;
33 const originY = chunkY * CHUNK_SIZE + localY;
34 const flying = !!mobDefinition(config.mobTypeId)?.flying;
35 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying);
37 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
36 38 if (!tile)
37 { continue; }
39 { break; }
40 reserved.add(`${tile.tileX},${tile.tileY}`);
38 41 requests.push({
39 42 ...tile,
40 43 mobTypeId: config.mobTypeId,
41 44 spawnerId: config.spawnerId,
42 persistent: !!mobDefinition(config.mobTypeId)?.persistent
45 originTileX: originX,
46 originTileY: originY,
47 wanderRangeTiles: config.maxWanderRangeTiles,
48 persistent
43 49 });
44 50 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
45 51 }
46 52 }
47 53 }
48 requests.push(...collectAmbientRequests(world));
54 requests.push(...collectAmbientRequests(world, reserved));
49 55 return requests;
50 56 }
51 57
@@ -66,7 +72,14 @@ export function mobComponents (request)
66 72 health: { current: def.health ?? 8, max: def.health ?? 8 }
67 73 };
68 74 if (request.spawnerId)
69 { components.spawnOrigin = { spawnerId: request.spawnerId }; }
75 {
76 components.spawnOrigin = {
77 spawnerId: request.spawnerId,
78 originTileX: request.originTileX ?? request.tileX,
79 originTileY: request.originTileY ?? request.tileY,
80 wanderRangeTiles: request.wanderRangeTiles ?? 4
81 };
82 }
70 83 if (def.persistent)
71 84 { components.persistent = {}; }
72 85 if (def.freeFlight)
@@ -89,7 +102,7 @@ export function mobComponents (request)
89 102 return components;
90 103 }
91 104
92 function collectAmbientRequests (world)
105 function collectAmbientRequests (world, reserved = new Set())
93 106 {
94 107 const requests = [];
95 108 const ambientTypes = listAmbientMobTypes();
@@ -117,10 +130,12 @@ function collectAmbientRequests (world)
117 130 loader.position.tileX,
118 131 loader.position.tileY,
119 132 8,
120 !!def.flying
133 !!def.flying,
134 reserved
121 135 );
122 136 if (!tile)
123 137 { continue; }
138 reserved.add(`${tile.tileX},${tile.tileY}`);
124 139 requests.push({
125 140 ...tile,
126 141 mobTypeId: def.mobTypeId,
@@ -154,13 +169,16 @@ function countCreatures (world, mobTypeId)
154 169 return count;
155 170 }
156 171
157 function pickSpawnTile (world, originX, originY, range, flying = false)
172 function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null)
158 173 {
159 174 const radius = Math.max(1, range | 0);
160 for (let attempt = 0; attempt < 24; attempt++)
175 for (let attempt = 0; attempt < 48; attempt++)
161 176 {
162 177 const tileX = originX + randInt(-radius, radius);
163 178 const tileY = originY + randInt(-radius, radius);
179 const key = `${tileX},${tileY}`;
180 if (reserved?.has(key))
181 { continue; }
164 182 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
165 183 { continue; }
166 184 if (flying)
@@ -1,8 +1,7 @@
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";
2import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";
4import {
3import {
5 defaultSpawnerConfig,
4 normalizeSpawnerConfig,
6 listAmbientMobTypes,
5 listAmbientMobTypes,
7 mobDefinition,
6 mobDefinition,
8 mobSpriteName
7 mobSpriteName
@@ -14,38 +13,45 @@ export function collectSpawnRequests (world)
14{
13{
15 const requests = [];
14 const requests = [];
16 const counts = countBySpawner(world);
15 const counts = countBySpawner(world);
16 const reserved = new Set();
17 for (const [key, chunk] of world.chunks)
17 for (const [key, chunk] of world.chunks)
18 {
18 {
19 if (chunk.replica || !chunk.simulating || !chunk.data.open)
19 if (chunk.replica || !chunk.simulating || !chunk.data.open)
20 { continue; }
20 { continue; }
21 const [chunkX, chunkY] = key.split(",").map(Number);
21 const [chunkX, chunkY] = key.split(",").map(Number);
22 for (let localY = 0; localY < CHUNK_SIZE; localY++)
22 for (const entry of chunk.data.spawners ?? [])
23 {
23 {
24 for (let localX = 0; localX < CHUNK_SIZE; localX++)
24 const localX = entry.localX;
25 const localY = entry.localY;
26 const index = localY * CHUNK_SIZE + localX;
27 const config = normalizeSpawnerConfig(
28 entry.config,
29 `${chunkX}:${chunkY}:${index}`
30 );
31 const flying = !!mobDefinition(config.mobTypeId)?.flying;
32 const originX = chunkX * CHUNK_SIZE + localX;
33 const originY = chunkY * CHUNK_SIZE + localY;
34 const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
35 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
25 {
36 {
26 const block = chunk.data.blocks[localY * CHUNK_SIZE + localX];
37 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
27 if (block?.typeId !== BlockType.spawner)
28 { continue; }
29 const config = { ...defaultSpawnerConfig(`${chunkX}:${chunkY}:${localY * CHUNK_SIZE + localX}`), ...(block.config ?? {}) };
30 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
31 { continue; }
32 const originX = chunkX * CHUNK_SIZE + localX;
33 const originY = chunkY * CHUNK_SIZE + localY;
34 const flying = !!mobDefinition(config.mobTypeId)?.flying;
35 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying);
36 if (!tile)
38 if (!tile)
37 { continue; }
39 { break; }
40 reserved.add(`${tile.tileX},${tile.tileY}`);
38 requests.push({
41 requests.push({
39 ...tile,
42 ...tile,
40 mobTypeId: config.mobTypeId,
43 mobTypeId: config.mobTypeId,
41 spawnerId: config.spawnerId,
44 spawnerId: config.spawnerId,
42 persistent: !!mobDefinition(config.mobTypeId)?.persistent
45 originTileX: originX,
46 originTileY: originY,
47 wanderRangeTiles: config.maxWanderRangeTiles,
48 persistent
43 });
49 });
44 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
50 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
45 }
51 }
46 }
52 }
47 }
53 }
48 requests.push(...collectAmbientRequests(world));
54 requests.push(...collectAmbientRequests(world, reserved));
49 return requests;
55 return requests;
50}
56}
51
57
@@ -66,7 +72,14 @@ export function mobComponents (request)
66 health: { current: def.health ?? 8, max: def.health ?? 8 }
72 health: { current: def.health ?? 8, max: def.health ?? 8 }
67 };
73 };
68 if (request.spawnerId)
74 if (request.spawnerId)
69 { components.spawnOrigin = { spawnerId: request.spawnerId }; }
75 {
76 components.spawnOrigin = {
77 spawnerId: request.spawnerId,
78 originTileX: request.originTileX ?? request.tileX,
79 originTileY: request.originTileY ?? request.tileY,
80 wanderRangeTiles: request.wanderRangeTiles ?? 4
81 };
82 }
70 if (def.persistent)
83 if (def.persistent)
71 { components.persistent = {}; }
84 { components.persistent = {}; }
72 if (def.freeFlight)
85 if (def.freeFlight)
@@ -89,7 +102,7 @@ export function mobComponents (request)
89 return components;
102 return components;
90}
103}
91
104
92function collectAmbientRequests (world)
105function collectAmbientRequests (world, reserved = new Set())
93{
106{
94 const requests = [];
107 const requests = [];
95 const ambientTypes = listAmbientMobTypes();
108 const ambientTypes = listAmbientMobTypes();
@@ -117,10 +130,12 @@ function collectAmbientRequests (world)
117 loader.position.tileX,
130 loader.position.tileX,
118 loader.position.tileY,
131 loader.position.tileY,
119 8,
132 8,
120 !!def.flying
133 !!def.flying,
134 reserved
121 );
135 );
122 if (!tile)
136 if (!tile)
123 { continue; }
137 { continue; }
138 reserved.add(`${tile.tileX},${tile.tileY}`);
124 requests.push({
139 requests.push({
125 ...tile,
140 ...tile,
126 mobTypeId: def.mobTypeId,
141 mobTypeId: def.mobTypeId,
@@ -154,13 +169,16 @@ function countCreatures (world, mobTypeId)
154 return count;
169 return count;
155}
170}
156
171
157function pickSpawnTile (world, originX, originY, range, flying = false)
172function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null)
158{
173{
159 const radius = Math.max(1, range | 0);
174 const radius = Math.max(1, range | 0);
160 for (let attempt = 0; attempt < 24; attempt++)
175 for (let attempt = 0; attempt < 48; attempt++)
161 {
176 {
162 const tileX = originX + randInt(-radius, radius);
177 const tileX = originX + randInt(-radius, radius);
163 const tileY = originY + randInt(-radius, radius);
178 const tileY = originY + randInt(-radius, radius);
179 const key = `${tileX},${tileY}`;
180 if (reserved?.has(key))
181 { continue; }
164 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
182 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
165 { continue; }
183 { continue; }
166 if (flying)
184 if (flying)
server/src/simulation/workerWorld.js +71 −0
@@ -814,6 +814,7 @@ export class WorkerWorld
814 814 const events = expireGroundItems(this, now);
815 815 const transferRequests = [];
816 816 this.#queueAmbientWander();
817 this.#queueSpawnerWander();
817 818 for (const entity of this.ecs.query(Component.position, Component.movement))
818 819 {
819 820 const { handle, entityId, position, movement } = entity;
@@ -897,6 +898,8 @@ export class WorkerWorld
897 898 const def = mobDefinition(entity.creature.mobTypeId);
898 899 if (!def?.ambient || def.freeFlight)
899 900 { continue; }
901 if (this.ecs.get(entity.handle, Component.spawnOrigin))
902 { continue; }
900 903 const path = this.ecs.get(entity.handle, Component.path);
901 904 if (!path)
902 905 { continue; }
@@ -919,6 +922,55 @@ export class WorkerWorld
919 922 }
920 923 }
921 924
925 /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */
926 #queueSpawnerWander ()
927 {
928 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
929 {
930 const combat = this.ecs.get(entity.handle, Component.combat);
931 if (combat?.targetEntityId != null)
932 { continue; }
933 const follow = this.ecs.get(entity.handle, Component.follow);
934 if (follow?.targetEntityId != null)
935 { continue; }
936 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
937 if (def?.freeFlight)
938 { continue; }
939 const path = this.ecs.get(entity.handle, Component.path);
940 if (!path || path.tiles?.length)
941 { continue; }
942 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
943 { continue; }
944 if (Math.random() > 0.4)
945 { continue; }
946
947 const origin = entity.spawnOrigin;
948 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
949 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
950 const range = Math.max(0, origin.wanderRangeTiles | 0);
951 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
952 if (!goal)
953 { continue; }
954 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
955 { continue; }
956 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
957 const tiles = findPath(
958 entity.position.tileX,
959 entity.position.tileY,
960 goal.tileX,
961 goal.tileY,
962 (x, y) => this.walkableFor(entity.entityId, x, y),
963 bounds.minX,
964 bounds.minY,
965 bounds.maxX,
966 bounds.maxY
967 );
968 if (!tiles?.length)
969 { continue; }
970 path.tiles = tiles;
971 }
972 }
973
922 974 #applyTransfer (message)
923 975 {
924 976 const payload = message.payload;
@@ -1138,6 +1190,25 @@ export class WorkerWorld
1138 1190 }
1139 1191 }
1140 1192
1193 function pickWanderGoalInRange (world, entityId, originX, originY, range)
1194 {
1195 const radius = Math.max(0, range | 0);
1196 for (let attempt = 0; attempt < 24; attempt++)
1197 {
1198 const tileX = originX + randInt(-radius, radius);
1199 const tileY = originY + randInt(-radius, radius);
1200 if (!world.walkableFor(entityId, tileX, tileY))
1201 { continue; }
1202 return { tileX, tileY };
1203 }
1204 return null;
1205 }
1206
1207 function randInt (min, max)
1208 {
1209 return min + Math.floor(Math.random() * (max - min + 1));
1210 }
1211
1141 1212 export function replicaNeededForOwnedChunks (ownedChunkKeys)
1142 1213 {
1143 1214 const needed = new Set();
@@ -814,6 +814,7 @@ export class WorkerWorld
814 const events = expireGroundItems(this, now);
814 const events = expireGroundItems(this, now);
815 const transferRequests = [];
815 const transferRequests = [];
816 this.#queueAmbientWander();
816 this.#queueAmbientWander();
817 this.#queueSpawnerWander();
817 for (const entity of this.ecs.query(Component.position, Component.movement))
818 for (const entity of this.ecs.query(Component.position, Component.movement))
818 {
819 {
819 const { handle, entityId, position, movement } = entity;
820 const { handle, entityId, position, movement } = entity;
@@ -897,6 +898,8 @@ export class WorkerWorld
897 const def = mobDefinition(entity.creature.mobTypeId);
898 const def = mobDefinition(entity.creature.mobTypeId);
898 if (!def?.ambient || def.freeFlight)
899 if (!def?.ambient || def.freeFlight)
899 { continue; }
900 { continue; }
901 if (this.ecs.get(entity.handle, Component.spawnOrigin))
902 { continue; }
900 const path = this.ecs.get(entity.handle, Component.path);
903 const path = this.ecs.get(entity.handle, Component.path);
901 if (!path)
904 if (!path)
902 { continue; }
905 { continue; }
@@ -919,6 +922,55 @@ export class WorkerWorld
919 }
922 }
920 }
923 }
921
924
925 /** Idle wander for spawner mobs: goals must stay within maxWanderRange of the spawner. Combat chase is unrestricted. */
926 #queueSpawnerWander ()
927 {
928 for (const entity of this.ecs.query(Component.position, Component.movement, Component.spawnOrigin))
929 {
930 const combat = this.ecs.get(entity.handle, Component.combat);
931 if (combat?.targetEntityId != null)
932 { continue; }
933 const follow = this.ecs.get(entity.handle, Component.follow);
934 if (follow?.targetEntityId != null)
935 { continue; }
936 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
937 if (def?.freeFlight)
938 { continue; }
939 const path = this.ecs.get(entity.handle, Component.path);
940 if (!path || path.tiles?.length)
941 { continue; }
942 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
943 { continue; }
944 if (Math.random() > 0.4)
945 { continue; }
946
947 const origin = entity.spawnOrigin;
948 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
949 const originY = Number.isInteger(origin.originTileY) ? origin.originTileY : entity.position.tileY;
950 const range = Math.max(0, origin.wanderRangeTiles | 0);
951 const goal = pickWanderGoalInRange(this, entity.entityId, originX, originY, range);
952 if (!goal)
953 { continue; }
954 if (goal.tileX === entity.position.tileX && goal.tileY === entity.position.tileY)
955 { continue; }
956 const bounds = chunkBoundsAround(entity.position.tileX, entity.position.tileY, VISIBLE_CHUNK_RADIUS);
957 const tiles = findPath(
958 entity.position.tileX,
959 entity.position.tileY,
960 goal.tileX,
961 goal.tileY,
962 (x, y) => this.walkableFor(entity.entityId, x, y),
963 bounds.minX,
964 bounds.minY,
965 bounds.maxX,
966 bounds.maxY
967 );
968 if (!tiles?.length)
969 { continue; }
970 path.tiles = tiles;
971 }
972 }
973
922 #applyTransfer (message)
974 #applyTransfer (message)
923 {
975 {
924 const payload = message.payload;
976 const payload = message.payload;
@@ -1138,6 +1190,25 @@ export class WorkerWorld
1138 }
1190 }
1139}
1191}
1140
1192
1193function pickWanderGoalInRange (world, entityId, originX, originY, range)
1194{
1195 const radius = Math.max(0, range | 0);
1196 for (let attempt = 0; attempt < 24; attempt++)
1197 {
1198 const tileX = originX + randInt(-radius, radius);
1199 const tileY = originY + randInt(-radius, radius);
1200 if (!world.walkableFor(entityId, tileX, tileY))
1201 { continue; }
1202 return { tileX, tileY };
1203 }
1204 return null;
1205}
1206
1207function randInt (min, max)
1208{
1209 return min + Math.floor(Math.random() * (max - min + 1));
1210}
1211
1141export function replicaNeededForOwnedChunks (ownedChunkKeys)
1212export function replicaNeededForOwnedChunks (ownedChunkKeys)
1142{
1213{
1143 const needed = new Set();
1214 const needed = new Set();
server/src/world/chunkData.js +104 −8
@@ -1,5 +1,13 @@
1 1 import { CHUNK_SIZE, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2 import { GroundType, isBlockPassable, blockLightRange, normalizeGround, normalizeBlock } from "../../../shared/definitions/tiles.js";
2 import {
3 GroundType,
4 BlockType,
5 isBlockPassable,
6 blockLightRange,
7 normalizeGround,
8 normalizeBlock
9 } from "../../../shared/definitions/tiles.js";
10 import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";
3 11 import { tileIndex } from "./coordinates.js";
4 12
5 13 export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)
@@ -12,7 +20,8 @@ export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defa
12 20 open: false,
13 21 grounds,
14 22 blocks,
15 light
23 light,
24 spawners: []
16 25 };
17 26 }
18 27
@@ -22,7 +31,8 @@ export function cloneChunkData (data)
22 31 open: data.open,
23 32 grounds: data.grounds.map((ground) => normalizeGround(ground)),
24 33 blocks: data.blocks.map((block) => structuredClone(normalizeBlock(block))),
25 light: data.light.slice()
34 light: data.light.slice(),
35 spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)
26 36 };
27 37 }
28 38
@@ -32,7 +42,8 @@ export function encodeChunkBlob (data)
32 42 open: !!data.open,
33 43 grounds: data.grounds.map((ground) => normalizeGround(ground)),
34 44 blocks: data.blocks.map((block) => normalizeBlock(block)),
35 light: data.light
45 light: data.light,
46 spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)
36 47 });
37 48 }
38 49
@@ -45,7 +56,7 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
45 56 const fallback = createEmptyChunkData(groundTypeId);
46 57 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
47 58 const grounds = Array.isArray(parsed.grounds) ? parsed.grounds.slice(0, tileCount) : fallback.grounds;
48 const blocks = Array.isArray(parsed.blocks) ? parsed.blocks.slice(0, tileCount) : fallback.blocks;
59 const blocks = Array.isArray(parsed.blocks) ? parsed.blocks.slice(0, tileCount) : fallback.blocks.slice();
49 60 const light = Array.isArray(parsed.light) ? parsed.light.slice(0, tileCount) : fallback.light;
50 61
51 62 while (grounds.length < tileCount)
@@ -55,14 +66,62 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
55 66 while (light.length < tileCount)
56 67 { light.push(0); }
57 68
69 const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed);
70
58 71 return {
59 72 open: !!parsed.open,
60 73 grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)),
61 blocks: blocks.map((block) => normalizeBlock(block)),
62 light
74 blocks: blocks.map((block) => {
75 const normalized = normalizeBlock(block);
76 if (normalized?.typeId === BlockType.spawner)
77 { return null; }
78 return normalized;
79 }),
80 light,
81 spawners
63 82 };
64 83 }
65 84
85 export function normalizeSpawner (value)
86 {
87 if (!value || !Number.isInteger(value.localX) || !Number.isInteger(value.localY))
88 { return null; }
89 if (value.localX < 0 || value.localY < 0 || value.localX >= CHUNK_SIZE || value.localY >= CHUNK_SIZE)
90 { return null; }
91 const config = value.config && typeof value.config === "object" ? value.config : {};
92 const spawnerId = typeof config.spawnerId === "string" && config.spawnerId
93 ? config.spawnerId
94 : `${value.localX},${value.localY}`;
95 return {
96 localX: value.localX,
97 localY: value.localY,
98 config: normalizeSpawnerConfig(config, spawnerId)
99 };
100 }
101
102 export function spawnerAt (data, localX, localY)
103 {
104 return (data.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
105 }
106
107 export function setSpawner (data, localX, localY, config)
108 {
109 if (!Array.isArray(data.spawners))
110 { data.spawners = []; }
111 const next = normalizeSpawner({ localX, localY, config });
112 data.spawners = data.spawners.filter((entry) => entry.localX !== localX || entry.localY !== localY);
113 if (next)
114 { data.spawners.push(next); }
115 return next;
116 }
117
118 export function clearSpawner (data, localX, localY)
119 {
120 if (!Array.isArray(data.spawners))
121 { return; }
122 data.spawners = data.spawners.filter((entry) => entry.localX !== localX || entry.localY !== localY);
123 }
124
66 125 export function getTile (data, localX, localY)
67 126 {
68 127 const index = tileIndex(localX, localY);
@@ -71,7 +130,8 @@ export function getTile (data, localX, localY)
71 130 groundTypeId: ground.typeId,
72 131 groundState: ground.state,
73 132 block: data.blocks[index],
74 light: data.light[index]
133 light: data.light[index],
134 spawner: spawnerAt(data, localX, localY)
75 135 };
76 136 }
77 137
@@ -113,4 +173,40 @@ export function collectLightSources (chunkX, chunkY, data)
113 173 return sources;
114 174 }
115 175
176 function migrateLegacySpawners (blocks, authored, parsedHint)
177 {
178 const byKey = new Map();
179 for (const entry of authored)
180 {
181 const normalized = normalizeSpawner(entry);
182 if (normalized)
183 { byKey.set(`${normalized.localX},${normalized.localY}`, normalized); }
184 }
185
186 for (let index = 0; index < blocks.length; index++)
187 {
188 const block = normalizeBlock(blocks[index]);
189 if (block?.typeId !== BlockType.spawner)
190 { continue; }
191 const localX = index % CHUNK_SIZE;
192 const localY = Math.floor(index / CHUNK_SIZE);
193 const key = `${localX},${localY}`;
194 if (!byKey.has(key))
195 {
196 const spawnerId = block.config?.spawnerId
197 ?? (parsedHint?.chunkX != null
198 ? `${parsedHint.chunkX}:${parsedHint.chunkY}:${index}`
199 : key);
200 byKey.set(key, normalizeSpawner({
201 localX,
202 localY,
203 config: { spawnerId, ...(block.config ?? {}) }
204 }));
205 }
206 blocks[index] = null;
207 }
208
209 return [...byKey.values()].filter(Boolean);
210 }
211
116 212 export { GroundType, normalizeGround, normalizeBlock };
@@ -1,5 +1,13 @@
1import { CHUNK_SIZE, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
1import { CHUNK_SIZE, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2import { GroundType, isBlockPassable, blockLightRange, normalizeGround, normalizeBlock } from "../../../shared/definitions/tiles.js";
2import {
3 GroundType,
4 BlockType,
5 isBlockPassable,
6 blockLightRange,
7 normalizeGround,
8 normalizeBlock
9} from "../../../shared/definitions/tiles.js";
10import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";
3import { tileIndex } from "./coordinates.js";
11import { tileIndex } from "./coordinates.js";
4
12
5export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)
13export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)
@@ -12,7 +20,8 @@ export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defa
12 open: false,
20 open: false,
13 grounds,
21 grounds,
14 blocks,
22 blocks,
15 light
23 light,
24 spawners: []
16 };
25 };
17}
26}
18
27
@@ -22,7 +31,8 @@ export function cloneChunkData (data)
22 open: data.open,
31 open: data.open,
23 grounds: data.grounds.map((ground) => normalizeGround(ground)),
32 grounds: data.grounds.map((ground) => normalizeGround(ground)),
24 blocks: data.blocks.map((block) => structuredClone(normalizeBlock(block))),
33 blocks: data.blocks.map((block) => structuredClone(normalizeBlock(block))),
25 light: data.light.slice()
34 light: data.light.slice(),
35 spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)
26 };
36 };
27}
37}
28
38
@@ -32,7 +42,8 @@ export function encodeChunkBlob (data)
32 open: !!data.open,
42 open: !!data.open,
33 grounds: data.grounds.map((ground) => normalizeGround(ground)),
43 grounds: data.grounds.map((ground) => normalizeGround(ground)),
34 blocks: data.blocks.map((block) => normalizeBlock(block)),
44 blocks: data.blocks.map((block) => normalizeBlock(block)),
35 light: data.light
45 light: data.light,
46 spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)
36 });
47 });
37}
48}
38
49
@@ -45,7 +56,7 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
45 const fallback = createEmptyChunkData(groundTypeId);
56 const fallback = createEmptyChunkData(groundTypeId);
46 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
57 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
47 const grounds = Array.isArray(parsed.grounds) ? parsed.grounds.slice(0, tileCount) : fallback.grounds;
58 const grounds = Array.isArray(parsed.grounds) ? parsed.grounds.slice(0, tileCount) : fallback.grounds;
48 const blocks = Array.isArray(parsed.blocks) ? parsed.blocks.slice(0, tileCount) : fallback.blocks;
59 const blocks = Array.isArray(parsed.blocks) ? parsed.blocks.slice(0, tileCount) : fallback.blocks.slice();
49 const light = Array.isArray(parsed.light) ? parsed.light.slice(0, tileCount) : fallback.light;
60 const light = Array.isArray(parsed.light) ? parsed.light.slice(0, tileCount) : fallback.light;
50
61
51 while (grounds.length < tileCount)
62 while (grounds.length < tileCount)
@@ -55,14 +66,62 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
55 while (light.length < tileCount)
66 while (light.length < tileCount)
56 { light.push(0); }
67 { light.push(0); }
57
68
69 const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed);
70
58 return {
71 return {
59 open: !!parsed.open,
72 open: !!parsed.open,
60 grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)),
73 grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)),
61 blocks: blocks.map((block) => normalizeBlock(block)),
74 blocks: blocks.map((block) => {
62 light
75 const normalized = normalizeBlock(block);
76 if (normalized?.typeId === BlockType.spawner)
77 { return null; }
78 return normalized;
79 }),
80 light,
81 spawners
63 };
82 };
64}
83}
65
84
85export function normalizeSpawner (value)
86{
87 if (!value || !Number.isInteger(value.localX) || !Number.isInteger(value.localY))
88 { return null; }
89 if (value.localX < 0 || value.localY < 0 || value.localX >= CHUNK_SIZE || value.localY >= CHUNK_SIZE)
90 { return null; }
91 const config = value.config && typeof value.config === "object" ? value.config : {};
92 const spawnerId = typeof config.spawnerId === "string" && config.spawnerId
93 ? config.spawnerId
94 : `${value.localX},${value.localY}`;
95 return {
96 localX: value.localX,
97 localY: value.localY,
98 config: normalizeSpawnerConfig(config, spawnerId)
99 };
100}
101
102export function spawnerAt (data, localX, localY)
103{
104 return (data.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
105}
106
107export function setSpawner (data, localX, localY, config)
108{
109 if (!Array.isArray(data.spawners))
110 { data.spawners = []; }
111 const next = normalizeSpawner({ localX, localY, config });
112 data.spawners = data.spawners.filter((entry) => entry.localX !== localX || entry.localY !== localY);
113 if (next)
114 { data.spawners.push(next); }
115 return next;
116}
117
118export function clearSpawner (data, localX, localY)
119{
120 if (!Array.isArray(data.spawners))
121 { return; }
122 data.spawners = data.spawners.filter((entry) => entry.localX !== localX || entry.localY !== localY);
123}
124
66export function getTile (data, localX, localY)
125export function getTile (data, localX, localY)
67{
126{
68 const index = tileIndex(localX, localY);
127 const index = tileIndex(localX, localY);
@@ -71,7 +130,8 @@ export function getTile (data, localX, localY)
71 groundTypeId: ground.typeId,
130 groundTypeId: ground.typeId,
72 groundState: ground.state,
131 groundState: ground.state,
73 block: data.blocks[index],
132 block: data.blocks[index],
74 light: data.light[index]
133 light: data.light[index],
134 spawner: spawnerAt(data, localX, localY)
75 };
135 };
76}
136}
77
137
@@ -113,4 +173,40 @@ export function collectLightSources (chunkX, chunkY, data)
113 return sources;
173 return sources;
114}
174}
115
175
176function migrateLegacySpawners (blocks, authored, parsedHint)
177{
178 const byKey = new Map();
179 for (const entry of authored)
180 {
181 const normalized = normalizeSpawner(entry);
182 if (normalized)
183 { byKey.set(`${normalized.localX},${normalized.localY}`, normalized); }
184 }
185
186 for (let index = 0; index < blocks.length; index++)
187 {
188 const block = normalizeBlock(blocks[index]);
189 if (block?.typeId !== BlockType.spawner)
190 { continue; }
191 const localX = index % CHUNK_SIZE;
192 const localY = Math.floor(index / CHUNK_SIZE);
193 const key = `${localX},${localY}`;
194 if (!byKey.has(key))
195 {
196 const spawnerId = block.config?.spawnerId
197 ?? (parsedHint?.chunkX != null
198 ? `${parsedHint.chunkX}:${parsedHint.chunkY}:${index}`
199 : key);
200 byKey.set(key, normalizeSpawner({
201 localX,
202 localY,
203 config: { spawnerId, ...(block.config ?? {}) }
204 }));
205 }
206 blocks[index] = null;
207 }
208
209 return [...byKey.values()].filter(Boolean);
210}
211
116export { GroundType, normalizeGround, normalizeBlock };
212export { GroundType, normalizeGround, normalizeBlock };
server/tests/chunk-spawners.test.js added +41 −0
@@ -0,0 +1,41 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { BlockType } from "../../shared/definitions/tiles.js";
4 import { normalizeSpawnerConfig } from "../../shared/definitions/mobs.js";
5 import { createEmptyChunkData, decodeChunkBlob, encodeChunkBlob } from "../src/world/chunkData.js";
6
7 test("decode migrates legacy spawner blocks into spawners[]", () =>
8 {
9 const legacy = createEmptyChunkData();
10 legacy.open = true;
11 legacy.blocks[8 * 16 + 8] = {
12 typeId: BlockType.spawner,
13 state: null,
14 config: { spawnerId: "legacy-1", mobTypeId: "rat", maxAlive: 1, spawnRangeTiles: 2 }
15 };
16 const decoded = decodeChunkBlob(encodeChunkBlob({
17 open: legacy.open,
18 grounds: legacy.grounds,
19 blocks: legacy.blocks,
20 light: legacy.light
21 }));
22 assert.equal(decoded.blocks[8 * 16 + 8], null);
23 assert.equal(decoded.spawners.length, 1);
24 assert.equal(decoded.spawners[0].localX, 8);
25 assert.equal(decoded.spawners[0].localY, 8);
26 assert.equal(decoded.spawners[0].config.mobTypeId, "rat");
27 assert.equal(decoded.spawners[0].config.spawnerId, "legacy-1");
28 assert.ok(decoded.spawners[0].config.maxWanderRangeTiles >= decoded.spawners[0].config.spawnRangeTiles);
29 });
30
31 test("normalizeSpawnerConfig forces wander range ≥ spawn range", () =>
32 {
33 const config = normalizeSpawnerConfig({
34 spawnerId: "a",
35 mobTypeId: "deer",
36 spawnRangeTiles: 6,
37 maxWanderRangeTiles: 2
38 });
39 assert.equal(config.spawnRangeTiles, 6);
40 assert.equal(config.maxWanderRangeTiles, 6);
41 });
@@ -0,0 +1,41 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
4import { normalizeSpawnerConfig } from "../../shared/definitions/mobs.js";
5import { createEmptyChunkData, decodeChunkBlob, encodeChunkBlob } from "../src/world/chunkData.js";
6
7test("decode migrates legacy spawner blocks into spawners[]", () =>
8{
9 const legacy = createEmptyChunkData();
10 legacy.open = true;
11 legacy.blocks[8 * 16 + 8] = {
12 typeId: BlockType.spawner,
13 state: null,
14 config: { spawnerId: "legacy-1", mobTypeId: "rat", maxAlive: 1, spawnRangeTiles: 2 }
15 };
16 const decoded = decodeChunkBlob(encodeChunkBlob({
17 open: legacy.open,
18 grounds: legacy.grounds,
19 blocks: legacy.blocks,
20 light: legacy.light
21 }));
22 assert.equal(decoded.blocks[8 * 16 + 8], null);
23 assert.equal(decoded.spawners.length, 1);
24 assert.equal(decoded.spawners[0].localX, 8);
25 assert.equal(decoded.spawners[0].localY, 8);
26 assert.equal(decoded.spawners[0].config.mobTypeId, "rat");
27 assert.equal(decoded.spawners[0].config.spawnerId, "legacy-1");
28 assert.ok(decoded.spawners[0].config.maxWanderRangeTiles >= decoded.spawners[0].config.spawnRangeTiles);
29});
30
31test("normalizeSpawnerConfig forces wander range ≥ spawn range", () =>
32{
33 const config = normalizeSpawnerConfig({
34 spawnerId: "a",
35 mobTypeId: "deer",
36 spawnRangeTiles: 6,
37 maxWanderRangeTiles: 2
38 });
39 assert.equal(config.spawnRangeTiles, 6);
40 assert.equal(config.maxWanderRangeTiles, 6);
41});
server/tests/editor-diff.test.js +13 −0
@@ -16,3 +16,16 @@ test("chunk diffs describe ground, block, and open-closed changes", () =>
16 16 assert.ok(bullets.some((line) => line.includes("Ground at 0, 0 changed from Grass to Wood.")));
17 17 assert.ok(bullets.some((line) => line.includes("Block Torch placed at 1, 0.")));
18 18 });
19
20 test("chunk diffs describe spawner placement", () =>
21 {
22 const previous = createEmptyChunkData();
23 const next = createEmptyChunkData();
24 next.spawners = [{
25 localX: 2,
26 localY: 3,
27 config: { spawnerId: "0:0:50", mobTypeId: "deer", maxAlive: 2, spawnRangeTiles: 4 }
28 }];
29 const bullets = diffChunks(0, 0, previous, next, true);
30 assert.ok(bullets.some((line) => line.includes("Spawner (deer) placed at 2, 3.")));
31 });
@@ -16,3 +16,16 @@ test("chunk diffs describe ground, block, and open-closed changes", () =>
16 assert.ok(bullets.some((line) => line.includes("Ground at 0, 0 changed from Grass to Wood.")));
16 assert.ok(bullets.some((line) => line.includes("Ground at 0, 0 changed from Grass to Wood.")));
17 assert.ok(bullets.some((line) => line.includes("Block Torch placed at 1, 0.")));
17 assert.ok(bullets.some((line) => line.includes("Block Torch placed at 1, 0.")));
18});
18});
19
20test("chunk diffs describe spawner placement", () =>
21{
22 const previous = createEmptyChunkData();
23 const next = createEmptyChunkData();
24 next.spawners = [{
25 localX: 2,
26 localY: 3,
27 config: { spawnerId: "0:0:50", mobTypeId: "deer", maxAlive: 2, spawnRangeTiles: 4 }
28 }];
29 const bullets = diffChunks(0, 0, previous, next, true);
30 assert.ok(bullets.some((line) => line.includes("Spawner (deer) placed at 2, 3.")));
31});
server/tests/inventory.test.js +6 −9
@@ -3,7 +3,6 @@ import assert from "node:assert/strict";
3 3 import { emptyEquipment, emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
4 4 import { ItemOriginKind } from "../../shared/items/origin.js";
5 5 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
6 import { BlockType } from "../../shared/definitions/tiles.js";
7 6 import { Component } from "../src/ecs/components.js";
8 7 import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
9 8 import {
@@ -245,20 +244,18 @@ test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
245 244 {
246 245 const data = createEmptyChunkData();
247 246 data.open = true;
248 data.blocks[8 * 16 + 8] = {
249 typeId: BlockType.spawner,
250 state: null,
247 data.spawners = [{
248 localX: 8,
249 localY: 8,
251 250 config: { spawnerId: "0:0:136", mobTypeId: "deer", maxAlive: 2, spawnRangeTiles: 3 }
252 };
251 }];
253 252 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
254 253 harness.simulation.reloadWorld();
255 254 const character = makeCharacter(harness.stateDb, { tileX: 4, tileY: 4 });
256 255 harness.simulation.spawnCharacter(1, character);
257 for (let i = 0; i < 80; i++)
258 { harness.simulation.step(); }
256 harness.simulation.step();
259 257 const deer = [...harness.simulation.directory.values()].filter((entity) => entity.firstName === "Deer");
260 assert.ok(deer.length >= 1);
261 assert.ok(deer.length <= 2);
258 assert.equal(deer.length, 2);
262 259 const pigeons = [...harness.simulation.directory.values()].filter((entity) => entity.firstName === "Pigeon");
263 260 assert.equal(pigeons.length, 0);
264 261 }
@@ -3,7 +3,6 @@ import assert from "node:assert/strict";
3import { emptyEquipment, emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
3import { emptyEquipment, emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
4import { ItemOriginKind } from "../../shared/items/origin.js";
4import { ItemOriginKind } from "../../shared/items/origin.js";
5import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
6import { BlockType } from "../../shared/definitions/tiles.js";
7import { Component } from "../src/ecs/components.js";
6import { Component } from "../src/ecs/components.js";
8import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
7import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
9import {
8import {
@@ -245,20 +244,18 @@ test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
245 {
244 {
246 const data = createEmptyChunkData();
245 const data = createEmptyChunkData();
247 data.open = true;
246 data.open = true;
248 data.blocks[8 * 16 + 8] = {
247 data.spawners = [{
249 typeId: BlockType.spawner,
248 localX: 8,
250 state: null,
249 localY: 8,
251 config: { spawnerId: "0:0:136", mobTypeId: "deer", maxAlive: 2, spawnRangeTiles: 3 }
250 config: { spawnerId: "0:0:136", mobTypeId: "deer", maxAlive: 2, spawnRangeTiles: 3 }
252 };
251 }];
253 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
252 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
254 harness.simulation.reloadWorld();
253 harness.simulation.reloadWorld();
255 const character = makeCharacter(harness.stateDb, { tileX: 4, tileY: 4 });
254 const character = makeCharacter(harness.stateDb, { tileX: 4, tileY: 4 });
256 harness.simulation.spawnCharacter(1, character);
255 harness.simulation.spawnCharacter(1, character);
257 for (let i = 0; i < 80; i++)
256 harness.simulation.step();
258 { harness.simulation.step(); }
259 const deer = [...harness.simulation.directory.values()].filter((entity) => entity.firstName === "Deer");
257 const deer = [...harness.simulation.directory.values()].filter((entity) => entity.firstName === "Deer");
260 assert.ok(deer.length >= 1);
258 assert.equal(deer.length, 2);
261 assert.ok(deer.length <= 2);
262 const pigeons = [...harness.simulation.directory.values()].filter((entity) => entity.firstName === "Pigeon");
259 const pigeons = [...harness.simulation.directory.values()].filter((entity) => entity.firstName === "Pigeon");
263 assert.equal(pigeons.length, 0);
260 assert.equal(pigeons.length, 0);
264 }
261 }
server/tests/skills.test.js +34 −1
@@ -13,7 +13,8 @@ import {
13 13 normalizePlayerSkills,
14 14 defaultPlayerSkills,
15 15 addSkillXp,
16 publicSkillsView
16 publicSkillsView,
17 enforceMinimumSkillLevels
17 18 } from "../../shared/skills/state.js";
18 19 import { skillLevel, SkillId, playerMaxHealth } from "../../shared/definitions/skills.js";
19 20 import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
@@ -21,6 +22,38 @@ import { mobComponents } from "../src/simulation/spawners.js";
21 22 import { MobId } from "../../shared/definitions/mobs.js";
22 23 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
23 24
25 test("enforceMinimumSkillLevels raises Health to 10 and leaves higher XP alone", () =>
26 {
27 const low = { xp: { health: 0, strength: 0 } };
28 assert.equal(enforceMinimumSkillLevels(low), true);
29 assert.equal(skillLevel(low, SkillId.health), 10);
30 assert.equal(skillLevel(low, SkillId.strength), 1);
31
32 const high = { xp: { health: totalXpForLevel(12), strength: totalXpForLevel(5) } };
33 assert.equal(enforceMinimumSkillLevels(high), false);
34 assert.equal(skillLevel(high, SkillId.health), 12);
35 assert.equal(skillLevel(high, SkillId.strength), 5);
36 });
37
38 test("login floors under-minimum skills and persists them", () =>
39 {
40 const harness = makeSimulation({ workerCount: 1 });
41 try
42 {
43 const character = makeCharacter(harness.stateDb);
44 harness.stateDb.db.prepare("UPDATE character_bags SET skills_blob = ? WHERE character_id = ?")
45 .run(JSON.stringify({ xp: { health: 3, strength: 0 } }), character.character_id);
46
47 harness.simulation.spawnCharacter(1, character);
48 const stored = harness.stateDb.getSkills(character.character_id);
49 assert.equal(skillLevel(stored, SkillId.health), 10);
50 assert.equal(skillLevel(stored, SkillId.strength), 1);
51 assert.equal(skillLevel(stored, SkillId.defence), 1);
52 }
53 finally
54 { harness.close(); }
55 });
56
24 57 test("normalizeSkillXp floors Health to the level-10 starting XP", () =>
25 58 {
26 59 assert.equal(normalizeSkillXp({}).health, totalXpForLevel(10));
@@ -13,7 +13,8 @@ import {
13 normalizePlayerSkills,
13 normalizePlayerSkills,
14 defaultPlayerSkills,
14 defaultPlayerSkills,
15 addSkillXp,
15 addSkillXp,
16 publicSkillsView
16 publicSkillsView,
17 enforceMinimumSkillLevels
17} from "../../shared/skills/state.js";
18} from "../../shared/skills/state.js";
18import { skillLevel, SkillId, playerMaxHealth } from "../../shared/definitions/skills.js";
19import { skillLevel, SkillId, playerMaxHealth } from "../../shared/definitions/skills.js";
19import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
20import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
@@ -21,6 +22,38 @@ import { mobComponents } from "../src/simulation/spawners.js";
21import { MobId } from "../../shared/definitions/mobs.js";
22import { MobId } from "../../shared/definitions/mobs.js";
22import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
23import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
23
24
25test("enforceMinimumSkillLevels raises Health to 10 and leaves higher XP alone", () =>
26{
27 const low = { xp: { health: 0, strength: 0 } };
28 assert.equal(enforceMinimumSkillLevels(low), true);
29 assert.equal(skillLevel(low, SkillId.health), 10);
30 assert.equal(skillLevel(low, SkillId.strength), 1);
31
32 const high = { xp: { health: totalXpForLevel(12), strength: totalXpForLevel(5) } };
33 assert.equal(enforceMinimumSkillLevels(high), false);
34 assert.equal(skillLevel(high, SkillId.health), 12);
35 assert.equal(skillLevel(high, SkillId.strength), 5);
36});
37
38test("login floors under-minimum skills and persists them", () =>
39{
40 const harness = makeSimulation({ workerCount: 1 });
41 try
42 {
43 const character = makeCharacter(harness.stateDb);
44 harness.stateDb.db.prepare("UPDATE character_bags SET skills_blob = ? WHERE character_id = ?")
45 .run(JSON.stringify({ xp: { health: 3, strength: 0 } }), character.character_id);
46
47 harness.simulation.spawnCharacter(1, character);
48 const stored = harness.stateDb.getSkills(character.character_id);
49 assert.equal(skillLevel(stored, SkillId.health), 10);
50 assert.equal(skillLevel(stored, SkillId.strength), 1);
51 assert.equal(skillLevel(stored, SkillId.defence), 1);
52 }
53 finally
54 { harness.close(); }
55});
56
24test("normalizeSkillXp floors Health to the level-10 starting XP", () =>
57test("normalizeSkillXp floors Health to the level-10 starting XP", () =>
25{
58{
26 assert.equal(normalizeSkillXp({}).health, totalXpForLevel(10));
59 assert.equal(normalizeSkillXp({}).health, totalXpForLevel(10));
shared/definitions/mobs.js +27 −1
@@ -118,7 +118,27 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
118 118 spawnerId,
119 119 mobTypeId,
120 120 maxAlive: 3,
121 spawnRangeTiles: 4
121 spawnRangeTiles: 4,
122 maxWanderRangeTiles: 8
123 };
124 }
125
126 /** Clamp wander ≥ spawn; coerce numeric fields. */
127 export function normalizeSpawnerConfig (config, spawnerId = "spawner")
128 {
129 const base = defaultSpawnerConfig(spawnerId, config?.mobTypeId ?? MobId.deer);
130 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId };
131 const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
132 const maxWanderRangeTiles = Math.max(
133 spawnRangeTiles,
134 Math.min(64, Number(merged.maxWanderRangeTiles) || spawnRangeTiles)
135 );
136 return {
137 spawnerId: String(merged.spawnerId),
138 mobTypeId: merged.mobTypeId ?? MobId.deer,
139 maxAlive: Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
140 spawnRangeTiles,
141 maxWanderRangeTiles
122 142 };
123 143 }
124 144
@@ -126,3 +146,9 @@ export function listAmbientMobTypes ()
126 146 {
127 147 return Object.values(MOB_DEFINITIONS).filter((def) => def.ambient);
128 148 }
149
150 /** Every mob type that can be authored as a world-editor spawner. */
151 export function listSpawnableMobTypes ()
152 {
153 return Object.values(MOB_DEFINITIONS);
154 }
@@ -118,7 +118,27 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
118 spawnerId,
118 spawnerId,
119 mobTypeId,
119 mobTypeId,
120 maxAlive: 3,
120 maxAlive: 3,
121 spawnRangeTiles: 4
121 spawnRangeTiles: 4,
122 maxWanderRangeTiles: 8
123 };
124}
125
126/** Clamp wander ≥ spawn; coerce numeric fields. */
127export function normalizeSpawnerConfig (config, spawnerId = "spawner")
128{
129 const base = defaultSpawnerConfig(spawnerId, config?.mobTypeId ?? MobId.deer);
130 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId };
131 const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
132 const maxWanderRangeTiles = Math.max(
133 spawnRangeTiles,
134 Math.min(64, Number(merged.maxWanderRangeTiles) || spawnRangeTiles)
135 );
136 return {
137 spawnerId: String(merged.spawnerId),
138 mobTypeId: merged.mobTypeId ?? MobId.deer,
139 maxAlive: Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
140 spawnRangeTiles,
141 maxWanderRangeTiles
122 };
142 };
123}
143}
124
144
@@ -126,3 +146,9 @@ export function listAmbientMobTypes ()
126{
146{
127 return Object.values(MOB_DEFINITIONS).filter((def) => def.ambient);
147 return Object.values(MOB_DEFINITIONS).filter((def) => def.ambient);
128}
148}
149
150/** Every mob type that can be authored as a world-editor spawner. */
151export function listSpawnableMobTypes ()
152{
153 return Object.values(MOB_DEFINITIONS);
154}
shared/definitions/tiles.js +16 −2
@@ -6,6 +6,7 @@ export const GroundType = Object.freeze({
6 6 export const BlockType = Object.freeze({
7 7 stoneWall: 1,
8 8 torch: 2,
9 /** @deprecated Legacy authored block; migrated into chunk `spawners[]` on load. */
9 10 spawner: 3,
10 11 bank: 4,
11 12 churchAltar: 5
@@ -55,11 +56,13 @@ export const BLOCK_DEFINITIONS = Object.freeze({
55 56 id: BlockType.spawner,
56 57 key: "spawner",
57 58 displayName: "Spawner",
58 passable: false,
59 passable: true,
59 60 lightRangeTiles: 0,
60 61 frames: 1,
61 62 framesPerRow: 1,
62 animationSpeed: 0
63 animationSpeed: 0,
64 /** Not shown in the placeable block palette; use the Spawners tab. */
65 editorHidden: true
63 66 }),
64 67 [BlockType.bank]: Object.freeze({
65 68 id: BlockType.bank,
@@ -83,6 +86,17 @@ export const BLOCK_DEFINITIONS = Object.freeze({
83 86 })
84 87 });
85 88
89 /** Grounds and real blocks the editor may place (excludes legacy/hidden entries). */
90 export function listPlaceableGrounds ()
91 {
92 return Object.values(GROUND_DEFINITIONS);
93 }
94
95 export function listPlaceableBlocks ()
96 {
97 return Object.values(BLOCK_DEFINITIONS).filter((def) => !def.editorHidden);
98 }
99
86 100 export function groundDefinition (typeId)
87 101 {
88 102 return GROUND_DEFINITIONS[typeId] ?? null;
@@ -6,6 +6,7 @@ export const GroundType = Object.freeze({
6export const BlockType = Object.freeze({
6export const BlockType = Object.freeze({
7 stoneWall: 1,
7 stoneWall: 1,
8 torch: 2,
8 torch: 2,
9 /** @deprecated Legacy authored block; migrated into chunk `spawners[]` on load. */
9 spawner: 3,
10 spawner: 3,
10 bank: 4,
11 bank: 4,
11 churchAltar: 5
12 churchAltar: 5
@@ -55,11 +56,13 @@ export const BLOCK_DEFINITIONS = Object.freeze({
55 id: BlockType.spawner,
56 id: BlockType.spawner,
56 key: "spawner",
57 key: "spawner",
57 displayName: "Spawner",
58 displayName: "Spawner",
58 passable: false,
59 passable: true,
59 lightRangeTiles: 0,
60 lightRangeTiles: 0,
60 frames: 1,
61 frames: 1,
61 framesPerRow: 1,
62 framesPerRow: 1,
62 animationSpeed: 0
63 animationSpeed: 0,
64 /** Not shown in the placeable block palette; use the Spawners tab. */
65 editorHidden: true
63 }),
66 }),
64 [BlockType.bank]: Object.freeze({
67 [BlockType.bank]: Object.freeze({
65 id: BlockType.bank,
68 id: BlockType.bank,
@@ -83,6 +86,17 @@ export const BLOCK_DEFINITIONS = Object.freeze({
83 })
86 })
84});
87});
85
88
89/** Grounds and real blocks the editor may place (excludes legacy/hidden entries). */
90export function listPlaceableGrounds ()
91{
92 return Object.values(GROUND_DEFINITIONS);
93}
94
95export function listPlaceableBlocks ()
96{
97 return Object.values(BLOCK_DEFINITIONS).filter((def) => !def.editorHidden);
98}
99
86export function groundDefinition (typeId)
100export function groundDefinition (typeId)
87{
101{
88 return GROUND_DEFINITIONS[typeId] ?? null;
102 return GROUND_DEFINITIONS[typeId] ?? null;
shared/skills/state.js +30 −10
@@ -1,8 +1,8 @@
1 import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS } from "../definitions/skills.js";
1 import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS, DEFAULT_PLAYER_SKILL_LEVELS } from "../definitions/skills.js";
2 2 import { maxTotalSkillXp, totalXpForLevel, xpProgress, MAX_SKILL_LEVEL } from "./progression.js";
3 3
4 /** Health starts at level 10; older `{}` skills_blob rows must not load as 1 HP. */
5 export const STARTING_HEALTH_XP = totalXpForLevel(10);
4 /** Health starts at level 10; other skills at level 1 (0 XP). */
5 export const STARTING_HEALTH_XP = totalXpForLevel(DEFAULT_PLAYER_SKILL_LEVELS[SkillId.health] ?? 10);
6 6
7 7 export function emptySkillXp ()
8 8 {
@@ -12,18 +12,38 @@ export function emptySkillXp ()
12 12 return xp;
13 13 }
14 14
15 /** Raise any skill below its default starting level up to that floor. Returns whether XP changed. */
16 export function enforceMinimumSkillLevels (skillsComponent)
17 {
18 if (!skillsComponent?.xp)
19 { return false; }
20 let raised = false;
21 for (const skillId of ALL_SKILL_IDS)
22 {
23 const minLevel = DEFAULT_PLAYER_SKILL_LEVELS[skillId] ?? 1;
24 const minXp = totalXpForLevel(minLevel);
25 const current = Math.max(0, Math.floor(Number(skillsComponent.xp[skillId]) || 0));
26 if (current < minXp)
27 {
28 skillsComponent.xp[skillId] = minXp;
29 raised = true;
30 }
31 }
32 return raised;
33 }
34
15 35 export function normalizeSkillXp (raw)
16 36 {
17 37 const xp = emptySkillXp();
18 if (!raw || typeof raw !== "object")
19 { return xp; }
20 for (const skillId of ALL_SKILL_IDS)
38 if (raw && typeof raw === "object")
21 39 {
22 const value = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
23 xp[skillId] = Number.isSafeInteger(value) ? value : 0;
40 for (const skillId of ALL_SKILL_IDS)
41 {
42 const value = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
43 xp[skillId] = Number.isSafeInteger(value) ? value : 0;
44 }
24 45 }
25 if (xp[SkillId.health] < STARTING_HEALTH_XP)
26 { xp[SkillId.health] = STARTING_HEALTH_XP; }
46 enforceMinimumSkillLevels({ xp });
27 47 return xp;
28 48 }
29 49
@@ -1,8 +1,8 @@
1import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS } from "../definitions/skills.js";
1import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS, DEFAULT_PLAYER_SKILL_LEVELS } from "../definitions/skills.js";
2import { maxTotalSkillXp, totalXpForLevel, xpProgress, MAX_SKILL_LEVEL } from "./progression.js";
2import { maxTotalSkillXp, totalXpForLevel, xpProgress, MAX_SKILL_LEVEL } from "./progression.js";
3
3
4/** Health starts at level 10; older `{}` skills_blob rows must not load as 1 HP. */
4/** Health starts at level 10; other skills at level 1 (0 XP). */
5export const STARTING_HEALTH_XP = totalXpForLevel(10);
5export const STARTING_HEALTH_XP = totalXpForLevel(DEFAULT_PLAYER_SKILL_LEVELS[SkillId.health] ?? 10);
6
6
7export function emptySkillXp ()
7export function emptySkillXp ()
8{
8{
@@ -12,18 +12,38 @@ export function emptySkillXp ()
12 return xp;
12 return xp;
13}
13}
14
14
15/** Raise any skill below its default starting level up to that floor. Returns whether XP changed. */
16export function enforceMinimumSkillLevels (skillsComponent)
17{
18 if (!skillsComponent?.xp)
19 { return false; }
20 let raised = false;
21 for (const skillId of ALL_SKILL_IDS)
22 {
23 const minLevel = DEFAULT_PLAYER_SKILL_LEVELS[skillId] ?? 1;
24 const minXp = totalXpForLevel(minLevel);
25 const current = Math.max(0, Math.floor(Number(skillsComponent.xp[skillId]) || 0));
26 if (current < minXp)
27 {
28 skillsComponent.xp[skillId] = minXp;
29 raised = true;
30 }
31 }
32 return raised;
33}
34
15export function normalizeSkillXp (raw)
35export function normalizeSkillXp (raw)
16{
36{
17 const xp = emptySkillXp();
37 const xp = emptySkillXp();
18 if (!raw || typeof raw !== "object")
38 if (raw && typeof raw === "object")
19 { return xp; }
20 for (const skillId of ALL_SKILL_IDS)
21 {
39 {
22 const value = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
40 for (const skillId of ALL_SKILL_IDS)
23 xp[skillId] = Number.isSafeInteger(value) ? value : 0;
41 {
42 const value = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
43 xp[skillId] = Number.isSafeInteger(value) ? value : 0;
44 }
24 }
45 }
25 if (xp[SkillId.health] < STARTING_HEALTH_XP)
46 enforceMinimumSkillLevels({ xp });
26 { xp[SkillId.health] = STARTING_HEALTH_XP; }
27 return xp;
47 return xp;
28}
48}
29
49