BlueGit

timfa questward

Add player death/respawn and fix Health floor so combat can finish.

Players at 0 HP drop bones and skull, see a blocking death modal, and respawn at the nearest church altar with full vitals. Legacy empty skills blobs no longer load as 1 HP, which previously looked like combat stopping after one hit.

timfa Tim Falken · pushed by timfa

Authored 2026-08-25 · 2 months ago

Hash
42bfe4a2f621889d4031a59f31ae00ec409bee2a
Parent
dbb944ff
32 files changed +1946 −166
client/assets/blocks/church-altar/church-altar.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bones/bones.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/skull/skull.png added Binary file +0 −0

The contents of this binary file are not shown.

client/index.html +6 −0
@@ -187,6 +187,12 @@
187 187 <p id="inspect-error" class="error"></p>
188 188 <div id="inspect-action"></div>
189 189 </div>
190 <div id="death-backdrop" hidden></div>
191 <div id="death-modal" role="dialog" aria-modal="true" aria-labelledby="death-title" hidden>
192 <h2 id="death-title">You have died</h2>
193 <p>Your remains mark where you fell. Respawn at the nearest church altar.</p>
194 <button id="death-respawn" type="button">Respawn</button>
195 </div>
190 196 <div id="overlay">
191 197 <section class="panel">
192 198 <h1>Tile MMO</h1>
@@ -187,6 +187,12 @@
187 <p id="inspect-error" class="error"></p>
187 <p id="inspect-error" class="error"></p>
188 <div id="inspect-action"></div>
188 <div id="inspect-action"></div>
189 </div>
189 </div>
190 <div id="death-backdrop" hidden></div>
191 <div id="death-modal" role="dialog" aria-modal="true" aria-labelledby="death-title" hidden>
192 <h2 id="death-title">You have died</h2>
193 <p>Your remains mark where you fell. Respawn at the nearest church altar.</p>
194 <button id="death-respawn" type="button">Respawn</button>
195 </div>
190 <div id="overlay">
196 <div id="overlay">
191 <section class="panel">
197 <section class="panel">
192 <h1>Tile MMO</h1>
198 <h1>Tile MMO</h1>
client/scripts/write-placeholder-assets.mjs +3 −0
@@ -41,11 +41,14 @@ solid(join(root, "items", "blank-cheque", "blank-cheque.png"), [168, 214, 168, 2
41 41 solid(join(root, "items", "cloth-shirt", "cloth-shirt.png"), [72, 112, 176, 255]);
42 42 solid(join(root, "blocks", "spawner", "spawner.png"), [168, 64, 196, 255], [80, 20, 96, 255]);
43 43 solid(join(root, "blocks", "bank", "bank.png"), [212, 176, 72, 255], [96, 72, 16, 255]);
44 solid(join(root, "blocks", "church-altar", "church-altar.png"), [210, 210, 220, 255], [76, 72, 88, 255]);
44 45 solid(join(root, "mobs", "deer", "deer.png"), [120, 78, 42, 255]);
45 46 solid(join(root, "mobs", "rat", "rat.png"), [96, 88, 72, 255], [40, 36, 28, 255]);
46 47 overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
47 48 overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
48 49 solid(join(root, "items", "lantern", "lantern.png"), [180, 120, 40, 255]);
50 solid(join(root, "items", "bones", "bones.png"), [218, 210, 180, 255], [92, 84, 68, 255]);
51 solid(join(root, "items", "skull", "skull.png"), [205, 198, 170, 255], [80, 72, 60, 255]);
49 52 overlay(join(root, "items", "lantern", "lantern-equip.png"), [200, 130, 48, 230]);
50 53 torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));
51 54 torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
@@ -41,11 +41,14 @@ solid(join(root, "items", "blank-cheque", "blank-cheque.png"), [168, 214, 168, 2
41solid(join(root, "items", "cloth-shirt", "cloth-shirt.png"), [72, 112, 176, 255]);
41solid(join(root, "items", "cloth-shirt", "cloth-shirt.png"), [72, 112, 176, 255]);
42solid(join(root, "blocks", "spawner", "spawner.png"), [168, 64, 196, 255], [80, 20, 96, 255]);
42solid(join(root, "blocks", "spawner", "spawner.png"), [168, 64, 196, 255], [80, 20, 96, 255]);
43solid(join(root, "blocks", "bank", "bank.png"), [212, 176, 72, 255], [96, 72, 16, 255]);
43solid(join(root, "blocks", "bank", "bank.png"), [212, 176, 72, 255], [96, 72, 16, 255]);
44solid(join(root, "blocks", "church-altar", "church-altar.png"), [210, 210, 220, 255], [76, 72, 88, 255]);
44solid(join(root, "mobs", "deer", "deer.png"), [120, 78, 42, 255]);
45solid(join(root, "mobs", "deer", "deer.png"), [120, 78, 42, 255]);
45solid(join(root, "mobs", "rat", "rat.png"), [96, 88, 72, 255], [40, 36, 28, 255]);
46solid(join(root, "mobs", "rat", "rat.png"), [96, 88, 72, 255], [40, 36, 28, 255]);
46overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
47overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
47overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
48overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
48solid(join(root, "items", "lantern", "lantern.png"), [180, 120, 40, 255]);
49solid(join(root, "items", "lantern", "lantern.png"), [180, 120, 40, 255]);
50solid(join(root, "items", "bones", "bones.png"), [218, 210, 180, 255], [92, 84, 68, 255]);
51solid(join(root, "items", "skull", "skull.png"), [205, 198, 170, 255], [80, 72, 60, 255]);
49overlay(join(root, "items", "lantern", "lantern-equip.png"), [200, 130, 48, 230]);
52overlay(join(root, "items", "lantern", "lantern-equip.png"), [200, 130, 48, 230]);
50torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));
53torchBloom(join(root, "items", "lantern", "lantern-equip-bloom.png"));
51torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
54torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
client/src/editor/main.js +1 −0
@@ -272,6 +272,7 @@ function zoomEditor (direction)
272 272 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
273 273 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
274 274 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
275 useNearestNeighbour(scene, game.images);
275 276 frameNeighborhood();
276 277 }
277 278
@@ -272,6 +272,7 @@ function zoomEditor (direction)
272 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
272 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
273 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
273 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
274 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
274 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
275 useNearestNeighbour(scene, game.images);
275 frameNeighborhood();
276 frameNeighborhood();
276}
277}
277
278
client/src/play/death.js added +40 −0
@@ -0,0 +1,40 @@
1 export function initDeath ({ socket, MessageType })
2 {
3 const backdrop = document.getElementById("death-backdrop");
4 const modal = document.getElementById("death-modal");
5 const respawn = document.getElementById("death-respawn");
6 let dead = false;
7
8 respawn.addEventListener("click", () =>
9 {
10 respawn.disabled = true;
11 socket.send({ type: MessageType.respawn });
12 });
13
14 function show ()
15 {
16 dead = true;
17 respawn.disabled = false;
18 backdrop.hidden = false;
19 modal.hidden = false;
20 respawn.focus();
21 }
22
23 function hide ()
24 {
25 dead = false;
26 backdrop.hidden = true;
27 modal.hidden = true;
28 respawn.disabled = false;
29 }
30
31 return {
32 show,
33 hide,
34 reset: hide,
35 isBlocking ()
36 {
37 return dead;
38 }
39 };
40 }
@@ -0,0 +1,40 @@
1export function initDeath ({ socket, MessageType })
2{
3 const backdrop = document.getElementById("death-backdrop");
4 const modal = document.getElementById("death-modal");
5 const respawn = document.getElementById("death-respawn");
6 let dead = false;
7
8 respawn.addEventListener("click", () =>
9 {
10 respawn.disabled = true;
11 socket.send({ type: MessageType.respawn });
12 });
13
14 function show ()
15 {
16 dead = true;
17 respawn.disabled = false;
18 backdrop.hidden = false;
19 modal.hidden = false;
20 respawn.focus();
21 }
22
23 function hide ()
24 {
25 dead = false;
26 backdrop.hidden = true;
27 modal.hidden = true;
28 respawn.disabled = false;
29 }
30
31 return {
32 show,
33 hide,
34 reset: hide,
35 isBlocking ()
36 {
37 return dead;
38 }
39 };
40}
client/src/play/main.js +127 −52
@@ -9,6 +9,7 @@ import { initInventory } from "./inventory.js";
9 9 import { initSkills } from "./skills.js";
10 10 import { initCrafting } from "./crafting.js";
11 11 import { initContextMenu } from "./contextMenu.js";
12 import { initDeath } from "./death.js";
12 13 import { CraftingStationId } from "/shared/definitions/craftingStations.js";
13 14 import { formatQuantity } from "/shared/items/formatQuantity.js";
14 15
@@ -32,9 +33,12 @@ let inventory;
32 33 let skills;
33 34 let crafting;
34 35 let contextMenu;
36 let death;
35 37 let pendingPickup = null;
36 let pendingBank = null;
37 let pendingGetCheques = false;
38 /** @type {{ kind: "bank", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
39 let pendingInteract = null;
40 /** Framework can report mousePressed for two frames; latch so one physical click is one command. */
41 let leftClickConsumed = false;
38 42
39 43 function showError (message)
40 44 {
@@ -73,7 +77,7 @@ function renderCharacters (characters)
73 77 function uiBlocked ()
74 78 {
75 79 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
76 || crafting?.isBlocking() || contextMenu?.isOpen());
80 || crafting?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
77 81 }
78 82
79 83 function clearPendingPickup ()
@@ -81,23 +85,22 @@ function clearPendingPickup ()
81 85 pendingPickup = null;
82 86 }
83 87
84 function clearPendingBank ()
88 function clearPendingInteract ()
85 89 {
86 pendingBank = null;
87 pendingGetCheques = false;
90 pendingInteract = null;
88 91 }
89 92
90 function requestOpenBank (tileX, tileY, { getCheques = false } = {})
93 function clearAllPendingActions ()
91 94 {
92 95 clearPendingPickup();
93 pendingBank = { tileX, tileY };
94 pendingGetCheques = !!getCheques;
96 clearPendingInteract();
97 }
98
99 function approachAdjacentTile (tileX, tileY)
100 {
95 101 const local = view.entities.get(view.localEntityId);
96 102 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
97 {
98 flushPendingBank();
99 return;
100 }
103 { return true; }
101 104 let best = null;
102 105 let bestDist = Infinity;
103 106 for (let dy = -1; dy <= 1; dy++)
@@ -120,28 +123,75 @@ function requestOpenBank (tileX, tileY, { getCheques = false } = {})
120 123 }
121 124 if (best)
122 125 { socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); }
126 return false;
123 127 }
124 128
125 function flushPendingBank ()
129 function requestOpenBank (tileX, tileY, { getCheques = false } = {})
126 130 {
127 if (!pendingBank || !view)
131 clearPendingPickup();
132 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
133 if (approachAdjacentTile(tileX, tileY))
134 { flushPendingInteract(); }
135 }
136
137 function requestTalk (targetEntityId)
138 {
139 clearPendingPickup();
140 pendingInteract = { kind: "talk", targetEntityId };
141 const target = view.entities.get(targetEntityId);
142 if (!target)
143 {
144 clearPendingInteract();
145 return;
146 }
147 if (approachAdjacentTile(target.tileX, target.tileY))
148 { flushPendingInteract(); }
149 }
150
151 function flushPendingInteract ()
152 {
153 if (!pendingInteract || !view)
128 154 { return; }
129 155 const local = view.entities.get(view.localEntityId);
130 156 if (!local)
131 157 { return; }
132 if (chebyshev(local.tileX, local.tileY, pendingBank.tileX, pendingBank.tileY) > 1)
133 { return; }
134 const getCheques = pendingGetCheques;
135 socket.send({ type: MessageType.openBank });
136 if (getCheques)
137 { inventory?.getBlankCheques(); }
138 clearPendingBank();
158
159 if (pendingInteract.kind === "bank")
160 {
161 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
162 { return; }
163 const getCheques = !!pendingInteract.getCheques;
164 socket.send({ type: MessageType.openBank });
165 if (getCheques)
166 { inventory?.getBlankCheques(); }
167 clearPendingInteract();
168 return;
169 }
170
171 if (pendingInteract.kind === "talk")
172 {
173 const target = view.entities.get(pendingInteract.targetEntityId);
174 if (!target)
175 {
176 clearPendingInteract();
177 return;
178 }
179 if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)
180 {
181 // Target may have moved — keep chasing.
182 approachAdjacentTile(target.tileX, target.tileY);
183 return;
184 }
185 socket.send({ type: MessageType.interact, targetEntityId: pendingInteract.targetEntityId });
186 clearPendingInteract();
187 }
139 188 }
140 189
141 190 function requestPickup (ground)
142 191 {
143 192 if (!ground)
144 193 { return; }
194 clearPendingInteract();
145 195 pendingPickup = {
146 196 groundItemId: ground.groundItemId,
147 197 tileX: ground.tileX,
@@ -175,43 +225,57 @@ function flushPendingPickup ()
175 225 clearPendingPickup();
176 226 }
177 227
228 function requestAttack (targetEntityId)
229 {
230 clearAllPendingActions();
231 socket.send({ type: MessageType.attack, targetEntityId });
232 }
233
234 function isAttackableEntity (entity)
235 {
236 if (!entity || entity.untargetable)
237 { return false; }
238 if (entity.canFight)
239 { return true; }
240 // Snapshots can omit canFight; mobs are still attackable via LMB.
241 return !!entity.mobTypeId && !entity.talkable;
242 }
243
178 244 function handleLeftClick (mouseX, mouseY)
179 245 {
180 246 const entity = view.entityAtScreen(mouseX, mouseY);
181 247 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
182 248 {
183 249 clearPendingPickup();
184 clearPendingBank();
185 250 if (entity.characterId)
186 251 {
252 clearPendingInteract();
187 253 social.inspect(entity);
188 254 return;
189 255 }
190 256 if (entity.talkable)
191 257 {
192 socket.send({ type: MessageType.interact, targetEntityId: entity.entityId });
258 requestTalk(entity.entityId);
193 259 return;
194 260 }
195 if (entity.canFight)
261 if (isAttackableEntity(entity))
196 262 {
197 socket.send({ type: MessageType.attack, targetEntityId: entity.entityId });
263 requestAttack(entity.entityId);
198 264 return;
199 265 }
266 // Clicked an entity we don't act on — do not fall through to walk (that cancels combat).
267 return;
200 268 }
201 269
202 270 const tile = view.screenToTile(mouseX, mouseY);
203 271 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
204 272 if (ground)
205 {
206 clearPendingBank();
207 requestPickup(ground);
208 }
273 { requestPickup(ground); }
209 274 else if (isBankTile(view, tile.tileX, tile.tileY))
210 275 { requestOpenBank(tile.tileX, tile.tileY); }
211 276 else
212 277 {
213 clearPendingPickup();
214 clearPendingBank();
278 clearAllPendingActions();
215 279 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
216 280 }
217 281 }
@@ -228,7 +292,7 @@ function handleRightClick (event, mouseX, mouseY)
228 292 label: "Walk here",
229 293 onSelect: () =>
230 294 {
231 clearPendingPickup();
295 clearAllPendingActions();
232 296 socket.send({ type: MessageType.moveTo, tileX: walkTileX, tileY: walkTileY });
233 297 }
234 298 });
@@ -242,7 +306,7 @@ function handleRightClick (event, mouseX, mouseY)
242 306 label: `Follow ${targetName}`,
243 307 onSelect: () =>
244 308 {
245 clearPendingPickup();
309 clearAllPendingActions();
246 310 socket.send({ type: MessageType.follow, targetEntityId: entity.entityId });
247 311 }
248 312 });
@@ -252,11 +316,7 @@ function handleRightClick (event, mouseX, mouseY)
252 316 {
253 317 items.push({
254 318 label: `Talk to ${targetName}`,
255 onSelect: () =>
256 {
257 clearPendingPickup();
258 socket.send({ type: MessageType.interact, targetEntityId: entity.entityId });
259 }
319 onSelect: () => requestTalk(entity.entityId)
260 320 });
261 321 }
262 322 if (entity.characterId)
@@ -265,18 +325,14 @@ function handleRightClick (event, mouseX, mouseY)
265 325 label: `${targetName} info`,
266 326 onSelect: () =>
267 327 {
268 clearPendingPickup();
328 clearAllPendingActions();
269 329 social.inspect(entity);
270 330 }
271 331 });
272 332 }
273 333 items.push({
274 334 label: `Attack ${targetName}`,
275 onSelect: () =>
276 {
277 clearPendingPickup();
278 socket.send({ type: MessageType.attack, targetEntityId: entity.entityId });
279 }
335 onSelect: () => requestAttack(entity.entityId)
280 336 });
281 337 }
282 338
@@ -339,24 +395,29 @@ function startPlay (payload)
339 395 const ticker = new GameObject(0, 0, null, 10);
340 396 ticker.update = (dt) =>
341 397 {
342 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !uiBlocked())
398 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
399 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
400 if (!leftPressed && !leftHeld)
401 { leftClickConsumed = false; }
402 else if (!leftClickConsumed && playing && !uiBlocked())
343 403 {
404 leftClickConsumed = true;
344 405 const canvas = scene.canvas;
345 406 const rect = canvas.getBoundingClientRect();
346 407 const mouseX = GameInput.mousePosition.x - rect.left;
347 408 const mouseY = GameInput.mousePosition.y - rect.top;
348 409 handleLeftClick(mouseX, mouseY);
349 410 }
350 if (GameInput.isPressed(82) && !chat?.isOpen())
411 if (GameInput.isPressed(82) && !uiBlocked())
351 412 {
352 413 gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
353 414 socket.send({ type: MessageType.setGait, gait });
354 415 document.getElementById("gait").textContent = gait;
355 416 }
356 if (playing)
417 if (playing && !death?.isBlocking())
357 418 {
358 419 flushPendingPickup();
359 flushPendingBank();
420 flushPendingInteract();
360 421 social?.updateNametag(view, scene, view.localEntityId);
361 422 chat?.update(view, scene);
362 423 }
@@ -368,10 +429,11 @@ function startPlay (payload)
368 429 scene.size.x = window.innerWidth;
369 430 scene.size.y = window.innerHeight;
370 431 scene.g_fixSize();
432 useNearestNeighbour(scene, game.images);
371 433 });
372 434 window.addEventListener("wheel", (event) =>
373 435 {
374 if (!playing || chat?.isOpen())
436 if (!playing || uiBlocked())
375 437 { return; }
376 438 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
377 439 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
@@ -446,6 +508,10 @@ async function main ()
446 508 MessageType,
447 509 getSettings: () => view?.settings
448 510 });
511 death = initDeath({
512 socket: { send (payload) { socket.send(payload); } },
513 MessageType
514 });
449 515 game.startGame();
450 516
451 517 socket = new GameSocket(defaultSocketUrl(), (message) =>
@@ -540,6 +606,15 @@ async function main ()
540 606 view?.flashDamage(message.targetId);
541 607 view?.spawnDamageNumber(message.targetId, message.damage);
542 608 break;
609 case MessageType.playerDied:
610 clearAllPendingActions();
611 contextMenu?.hide();
612 death?.show();
613 break;
614 case MessageType.playerRespawned:
615 death?.hide();
616 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
617 break;
543 618 case MessageType.error:
544 619 showError(message.message);
545 620 social?.showError(message.message);
@@ -568,14 +643,14 @@ async function main ()
568 643 function returnToMenu (reason = "")
569 644 {
570 645 playing = false;
571 clearPendingPickup();
572 clearPendingBank();
646 clearAllPendingActions();
573 647 social?.reset();
574 648 chat?.reset();
575 649 inventory?.reset();
576 650 crafting?.reset();
577 651 skills?.hide();
578 652 contextMenu?.hide();
653 death?.reset();
579 654 if (view)
580 655 {
581 656 for (const key of [...(view.chunks?.keys?.() ?? [])])
@@ -9,6 +9,7 @@ import { initInventory } from "./inventory.js";
9import { initSkills } from "./skills.js";
9import { initSkills } from "./skills.js";
10import { initCrafting } from "./crafting.js";
10import { initCrafting } from "./crafting.js";
11import { initContextMenu } from "./contextMenu.js";
11import { initContextMenu } from "./contextMenu.js";
12import { initDeath } from "./death.js";
12import { CraftingStationId } from "/shared/definitions/craftingStations.js";
13import { CraftingStationId } from "/shared/definitions/craftingStations.js";
13import { formatQuantity } from "/shared/items/formatQuantity.js";
14import { formatQuantity } from "/shared/items/formatQuantity.js";
14
15
@@ -32,9 +33,12 @@ let inventory;
32let skills;
33let skills;
33let crafting;
34let crafting;
34let contextMenu;
35let contextMenu;
36let death;
35let pendingPickup = null;
37let pendingPickup = null;
36let pendingBank = null;
38/** @type {{ kind: "bank", tileX: number, tileY: number, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
37let pendingGetCheques = false;
39let pendingInteract = null;
40/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
41let leftClickConsumed = false;
38
42
39function showError (message)
43function showError (message)
40{
44{
@@ -73,7 +77,7 @@ function renderCharacters (characters)
73function uiBlocked ()
77function uiBlocked ()
74{
78{
75 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
79 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
76 || crafting?.isBlocking() || contextMenu?.isOpen());
80 || crafting?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking());
77}
81}
78
82
79function clearPendingPickup ()
83function clearPendingPickup ()
@@ -81,23 +85,22 @@ function clearPendingPickup ()
81 pendingPickup = null;
85 pendingPickup = null;
82}
86}
83
87
84function clearPendingBank ()
88function clearPendingInteract ()
85{
89{
86 pendingBank = null;
90 pendingInteract = null;
87 pendingGetCheques = false;
88}
91}
89
92
90function requestOpenBank (tileX, tileY, { getCheques = false } = {})
93function clearAllPendingActions ()
91{
94{
92 clearPendingPickup();
95 clearPendingPickup();
93 pendingBank = { tileX, tileY };
96 clearPendingInteract();
94 pendingGetCheques = !!getCheques;
97}
98
99function approachAdjacentTile (tileX, tileY)
100{
95 const local = view.entities.get(view.localEntityId);
101 const local = view.entities.get(view.localEntityId);
96 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
102 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
97 {
103 { return true; }
98 flushPendingBank();
99 return;
100 }
101 let best = null;
104 let best = null;
102 let bestDist = Infinity;
105 let bestDist = Infinity;
103 for (let dy = -1; dy <= 1; dy++)
106 for (let dy = -1; dy <= 1; dy++)
@@ -120,28 +123,75 @@ function requestOpenBank (tileX, tileY, { getCheques = false } = {})
120 }
123 }
121 if (best)
124 if (best)
122 { socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); }
125 { socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); }
126 return false;
123}
127}
124
128
125function flushPendingBank ()
129function requestOpenBank (tileX, tileY, { getCheques = false } = {})
126{
130{
127 if (!pendingBank || !view)
131 clearPendingPickup();
132 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
133 if (approachAdjacentTile(tileX, tileY))
134 { flushPendingInteract(); }
135}
136
137function requestTalk (targetEntityId)
138{
139 clearPendingPickup();
140 pendingInteract = { kind: "talk", targetEntityId };
141 const target = view.entities.get(targetEntityId);
142 if (!target)
143 {
144 clearPendingInteract();
145 return;
146 }
147 if (approachAdjacentTile(target.tileX, target.tileY))
148 { flushPendingInteract(); }
149}
150
151function flushPendingInteract ()
152{
153 if (!pendingInteract || !view)
128 { return; }
154 { return; }
129 const local = view.entities.get(view.localEntityId);
155 const local = view.entities.get(view.localEntityId);
130 if (!local)
156 if (!local)
131 { return; }
157 { return; }
132 if (chebyshev(local.tileX, local.tileY, pendingBank.tileX, pendingBank.tileY) > 1)
158
133 { return; }
159 if (pendingInteract.kind === "bank")
134 const getCheques = pendingGetCheques;
160 {
135 socket.send({ type: MessageType.openBank });
161 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
136 if (getCheques)
162 { return; }
137 { inventory?.getBlankCheques(); }
163 const getCheques = !!pendingInteract.getCheques;
138 clearPendingBank();
164 socket.send({ type: MessageType.openBank });
165 if (getCheques)
166 { inventory?.getBlankCheques(); }
167 clearPendingInteract();
168 return;
169 }
170
171 if (pendingInteract.kind === "talk")
172 {
173 const target = view.entities.get(pendingInteract.targetEntityId);
174 if (!target)
175 {
176 clearPendingInteract();
177 return;
178 }
179 if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)
180 {
181 // Target may have moved — keep chasing.
182 approachAdjacentTile(target.tileX, target.tileY);
183 return;
184 }
185 socket.send({ type: MessageType.interact, targetEntityId: pendingInteract.targetEntityId });
186 clearPendingInteract();
187 }
139}
188}
140
189
141function requestPickup (ground)
190function requestPickup (ground)
142{
191{
143 if (!ground)
192 if (!ground)
144 { return; }
193 { return; }
194 clearPendingInteract();
145 pendingPickup = {
195 pendingPickup = {
146 groundItemId: ground.groundItemId,
196 groundItemId: ground.groundItemId,
147 tileX: ground.tileX,
197 tileX: ground.tileX,
@@ -175,43 +225,57 @@ function flushPendingPickup ()
175 clearPendingPickup();
225 clearPendingPickup();
176}
226}
177
227
228function requestAttack (targetEntityId)
229{
230 clearAllPendingActions();
231 socket.send({ type: MessageType.attack, targetEntityId });
232}
233
234function isAttackableEntity (entity)
235{
236 if (!entity || entity.untargetable)
237 { return false; }
238 if (entity.canFight)
239 { return true; }
240 // Snapshots can omit canFight; mobs are still attackable via LMB.
241 return !!entity.mobTypeId && !entity.talkable;
242}
243
178function handleLeftClick (mouseX, mouseY)
244function handleLeftClick (mouseX, mouseY)
179{
245{
180 const entity = view.entityAtScreen(mouseX, mouseY);
246 const entity = view.entityAtScreen(mouseX, mouseY);
181 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
247 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
182 {
248 {
183 clearPendingPickup();
249 clearPendingPickup();
184 clearPendingBank();
185 if (entity.characterId)
250 if (entity.characterId)
186 {
251 {
252 clearPendingInteract();
187 social.inspect(entity);
253 social.inspect(entity);
188 return;
254 return;
189 }
255 }
190 if (entity.talkable)
256 if (entity.talkable)
191 {
257 {
192 socket.send({ type: MessageType.interact, targetEntityId: entity.entityId });
258 requestTalk(entity.entityId);
193 return;
259 return;
194 }
260 }
195 if (entity.canFight)
261 if (isAttackableEntity(entity))
196 {
262 {
197 socket.send({ type: MessageType.attack, targetEntityId: entity.entityId });
263 requestAttack(entity.entityId);
198 return;
264 return;
199 }
265 }
266 // Clicked an entity we don't act on — do not fall through to walk (that cancels combat).
267 return;
200 }
268 }
201
269
202 const tile = view.screenToTile(mouseX, mouseY);
270 const tile = view.screenToTile(mouseX, mouseY);
203 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
271 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
204 if (ground)
272 if (ground)
205 {
273 { requestPickup(ground); }
206 clearPendingBank();
207 requestPickup(ground);
208 }
209 else if (isBankTile(view, tile.tileX, tile.tileY))
274 else if (isBankTile(view, tile.tileX, tile.tileY))
210 { requestOpenBank(tile.tileX, tile.tileY); }
275 { requestOpenBank(tile.tileX, tile.tileY); }
211 else
276 else
212 {
277 {
213 clearPendingPickup();
278 clearAllPendingActions();
214 clearPendingBank();
215 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
279 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
216 }
280 }
217}
281}
@@ -228,7 +292,7 @@ function handleRightClick (event, mouseX, mouseY)
228 label: "Walk here",
292 label: "Walk here",
229 onSelect: () =>
293 onSelect: () =>
230 {
294 {
231 clearPendingPickup();
295 clearAllPendingActions();
232 socket.send({ type: MessageType.moveTo, tileX: walkTileX, tileY: walkTileY });
296 socket.send({ type: MessageType.moveTo, tileX: walkTileX, tileY: walkTileY });
233 }
297 }
234 });
298 });
@@ -242,7 +306,7 @@ function handleRightClick (event, mouseX, mouseY)
242 label: `Follow ${targetName}`,
306 label: `Follow ${targetName}`,
243 onSelect: () =>
307 onSelect: () =>
244 {
308 {
245 clearPendingPickup();
309 clearAllPendingActions();
246 socket.send({ type: MessageType.follow, targetEntityId: entity.entityId });
310 socket.send({ type: MessageType.follow, targetEntityId: entity.entityId });
247 }
311 }
248 });
312 });
@@ -252,11 +316,7 @@ function handleRightClick (event, mouseX, mouseY)
252 {
316 {
253 items.push({
317 items.push({
254 label: `Talk to ${targetName}`,
318 label: `Talk to ${targetName}`,
255 onSelect: () =>
319 onSelect: () => requestTalk(entity.entityId)
256 {
257 clearPendingPickup();
258 socket.send({ type: MessageType.interact, targetEntityId: entity.entityId });
259 }
260 });
320 });
261 }
321 }
262 if (entity.characterId)
322 if (entity.characterId)
@@ -265,18 +325,14 @@ function handleRightClick (event, mouseX, mouseY)
265 label: `${targetName} info`,
325 label: `${targetName} info`,
266 onSelect: () =>
326 onSelect: () =>
267 {
327 {
268 clearPendingPickup();
328 clearAllPendingActions();
269 social.inspect(entity);
329 social.inspect(entity);
270 }
330 }
271 });
331 });
272 }
332 }
273 items.push({
333 items.push({
274 label: `Attack ${targetName}`,
334 label: `Attack ${targetName}`,
275 onSelect: () =>
335 onSelect: () => requestAttack(entity.entityId)
276 {
277 clearPendingPickup();
278 socket.send({ type: MessageType.attack, targetEntityId: entity.entityId });
279 }
280 });
336 });
281 }
337 }
282
338
@@ -339,24 +395,29 @@ function startPlay (payload)
339 const ticker = new GameObject(0, 0, null, 10);
395 const ticker = new GameObject(0, 0, null, 10);
340 ticker.update = (dt) =>
396 ticker.update = (dt) =>
341 {
397 {
342 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !uiBlocked())
398 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
399 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
400 if (!leftPressed && !leftHeld)
401 { leftClickConsumed = false; }
402 else if (!leftClickConsumed && playing && !uiBlocked())
343 {
403 {
404 leftClickConsumed = true;
344 const canvas = scene.canvas;
405 const canvas = scene.canvas;
345 const rect = canvas.getBoundingClientRect();
406 const rect = canvas.getBoundingClientRect();
346 const mouseX = GameInput.mousePosition.x - rect.left;
407 const mouseX = GameInput.mousePosition.x - rect.left;
347 const mouseY = GameInput.mousePosition.y - rect.top;
408 const mouseY = GameInput.mousePosition.y - rect.top;
348 handleLeftClick(mouseX, mouseY);
409 handleLeftClick(mouseX, mouseY);
349 }
410 }
350 if (GameInput.isPressed(82) && !chat?.isOpen())
411 if (GameInput.isPressed(82) && !uiBlocked())
351 {
412 {
352 gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
413 gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
353 socket.send({ type: MessageType.setGait, gait });
414 socket.send({ type: MessageType.setGait, gait });
354 document.getElementById("gait").textContent = gait;
415 document.getElementById("gait").textContent = gait;
355 }
416 }
356 if (playing)
417 if (playing && !death?.isBlocking())
357 {
418 {
358 flushPendingPickup();
419 flushPendingPickup();
359 flushPendingBank();
420 flushPendingInteract();
360 social?.updateNametag(view, scene, view.localEntityId);
421 social?.updateNametag(view, scene, view.localEntityId);
361 chat?.update(view, scene);
422 chat?.update(view, scene);
362 }
423 }
@@ -368,10 +429,11 @@ function startPlay (payload)
368 scene.size.x = window.innerWidth;
429 scene.size.x = window.innerWidth;
369 scene.size.y = window.innerHeight;
430 scene.size.y = window.innerHeight;
370 scene.g_fixSize();
431 scene.g_fixSize();
432 useNearestNeighbour(scene, game.images);
371 });
433 });
372 window.addEventListener("wheel", (event) =>
434 window.addEventListener("wheel", (event) =>
373 {
435 {
374 if (!playing || chat?.isOpen())
436 if (!playing || uiBlocked())
375 { return; }
437 { return; }
376 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
438 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
377 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
439 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
@@ -446,6 +508,10 @@ async function main ()
446 MessageType,
508 MessageType,
447 getSettings: () => view?.settings
509 getSettings: () => view?.settings
448 });
510 });
511 death = initDeath({
512 socket: { send (payload) { socket.send(payload); } },
513 MessageType
514 });
449 game.startGame();
515 game.startGame();
450
516
451 socket = new GameSocket(defaultSocketUrl(), (message) =>
517 socket = new GameSocket(defaultSocketUrl(), (message) =>
@@ -540,6 +606,15 @@ async function main ()
540 view?.flashDamage(message.targetId);
606 view?.flashDamage(message.targetId);
541 view?.spawnDamageNumber(message.targetId, message.damage);
607 view?.spawnDamageNumber(message.targetId, message.damage);
542 break;
608 break;
609 case MessageType.playerDied:
610 clearAllPendingActions();
611 contextMenu?.hide();
612 death?.show();
613 break;
614 case MessageType.playerRespawned:
615 death?.hide();
616 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
617 break;
543 case MessageType.error:
618 case MessageType.error:
544 showError(message.message);
619 showError(message.message);
545 social?.showError(message.message);
620 social?.showError(message.message);
@@ -568,14 +643,14 @@ async function main ()
568function returnToMenu (reason = "")
643function returnToMenu (reason = "")
569{
644{
570 playing = false;
645 playing = false;
571 clearPendingPickup();
646 clearAllPendingActions();
572 clearPendingBank();
573 social?.reset();
647 social?.reset();
574 chat?.reset();
648 chat?.reset();
575 inventory?.reset();
649 inventory?.reset();
576 crafting?.reset();
650 crafting?.reset();
577 skills?.hide();
651 skills?.hide();
578 contextMenu?.hide();
652 contextMenu?.hide();
653 death?.reset();
579 if (view)
654 if (view)
580 {
655 {
581 for (const key of [...(view.chunks?.keys?.() ?? [])])
656 for (const key of [...(view.chunks?.keys?.() ?? [])])
client/src/render/sprites.js +55 −7
@@ -92,14 +92,62 @@ export function shadeDataUrl (fill = "#000000")
92 92 return canvas.toDataURL("image/png");
93 93 }
94 94
95 export function useNearestNeighbour (scene, images)
95 function setGlNearest (gl, texture)
96 {
97 if (!gl || !texture)
98 { return; }
99 gl.bindTexture(gl.TEXTURE_2D, texture);
100 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
101 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
102 }
103
104 /** Framework defaults to LINEAR; patch uploads so pixel art stays crisp when scaled. */
105 export function patchNearestNeighbourTextures (scene)
96 106 {
97 const gl = scene.glContext.gl;
98 for (const sprite of Object.values(images))
107 const glContext = scene?.glContext;
108 if (!glContext || glContext._nearestPatched)
109 { return; }
110 const original = glContext.getTexture.bind(glContext);
111 glContext.getTexture = (htmlImage) =>
99 112 {
100 const texture = scene.glContext.getTexture(sprite.g_image);
101 gl.bindTexture(gl.TEXTURE_2D, texture);
102 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
103 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
113 const texture = original(htmlImage);
114 if (texture)
115 { setGlNearest(glContext.gl, texture); }
116 return texture;
117 };
118 glContext._nearestPatched = true;
119 }
120
121 /** Canvas atlases and dynamic sprites — call after invalidate/reupload. */
122 export function setNearestFilter (scene, source)
123 {
124 if (!source)
125 { return; }
126 patchNearestNeighbourTextures(scene);
127 const glContext = scene?.glContext;
128 if (!glContext)
129 { return; }
130 const htmlImage = source.g_image ?? source;
131 const texture = glContext.getTexture(htmlImage);
132 if (texture)
133 { setGlNearest(glContext.gl, texture); }
134 }
135
136 export function applyNearestToAllTextures (scene, images)
137 {
138 patchNearestNeighbourTextures(scene);
139 const glContext = scene?.glContext;
140 if (!glContext)
141 { return; }
142 for (const sprite of Object.values(images ?? {}))
143 {
144 const htmlImage = sprite?.g_image ?? sprite;
145 if (htmlImage)
146 { glContext.getTexture(htmlImage); }
104 147 }
105 148 }
149
150 export function useNearestNeighbour (scene, images)
151 {
152 applyNearestToAllTextures(scene, images);
153 }
@@ -92,14 +92,62 @@ export function shadeDataUrl (fill = "#000000")
92 return canvas.toDataURL("image/png");
92 return canvas.toDataURL("image/png");
93}
93}
94
94
95export function useNearestNeighbour (scene, images)
95function setGlNearest (gl, texture)
96{
97 if (!gl || !texture)
98 { return; }
99 gl.bindTexture(gl.TEXTURE_2D, texture);
100 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
101 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
102}
103
104/** Framework defaults to LINEAR; patch uploads so pixel art stays crisp when scaled. */
105export function patchNearestNeighbourTextures (scene)
96{
106{
97 const gl = scene.glContext.gl;
107 const glContext = scene?.glContext;
98 for (const sprite of Object.values(images))
108 if (!glContext || glContext._nearestPatched)
109 { return; }
110 const original = glContext.getTexture.bind(glContext);
111 glContext.getTexture = (htmlImage) =>
99 {
112 {
100 const texture = scene.glContext.getTexture(sprite.g_image);
113 const texture = original(htmlImage);
101 gl.bindTexture(gl.TEXTURE_2D, texture);
114 if (texture)
102 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
115 { setGlNearest(glContext.gl, texture); }
103 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
116 return texture;
117 };
118 glContext._nearestPatched = true;
119}
120
121/** Canvas atlases and dynamic sprites — call after invalidate/reupload. */
122export function setNearestFilter (scene, source)
123{
124 if (!source)
125 { return; }
126 patchNearestNeighbourTextures(scene);
127 const glContext = scene?.glContext;
128 if (!glContext)
129 { return; }
130 const htmlImage = source.g_image ?? source;
131 const texture = glContext.getTexture(htmlImage);
132 if (texture)
133 { setGlNearest(glContext.gl, texture); }
134}
135
136export function applyNearestToAllTextures (scene, images)
137{
138 patchNearestNeighbourTextures(scene);
139 const glContext = scene?.glContext;
140 if (!glContext)
141 { return; }
142 for (const sprite of Object.values(images ?? {}))
143 {
144 const htmlImage = sprite?.g_image ?? sprite;
145 if (htmlImage)
146 { glContext.getTexture(htmlImage); }
104 }
147 }
105}
148}
149
150export function useNearestNeighbour (scene, images)
151{
152 applyNearestToAllTextures(scene, images);
153}
client/src/render/worldView.js +9 −19
@@ -9,6 +9,7 @@ import {
9 9 frameworkImageFromCanvas,
10 10 invalidateCanvasTexture
11 11 } from "./canvasSprite.js";
12 import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
12 13
13 14 const LAYER_GROUND = 0;
14 15 const LAYER_EDGE = 900000;
@@ -364,6 +365,7 @@ export class WorldView
364 365 }
365 366 this.#rebuildAllEdges();
366 367 this.#redrawPreview();
368 applyNearestToAllTextures(this.scene, this.game.images);
367 369 }
368 370
369 371 tileSize ()
@@ -653,11 +655,13 @@ export class WorldView
653 655 entity.sex = payload.sex ?? entity.sex;
654 656 entity.characterId = payload.characterId ?? entity.characterId ?? null;
655 657 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
656 entity.hostile = !!payload.hostile;
657 entity.canFight = !!payload.canFight;
658 entity.talkable = !!payload.talkable;
659 entity.untargetable = !!payload.untargetable;
660 entity.freeFlight = !!payload.freeFlight;
658 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
659 entity.canFight = payload.canFight != null
660 ? !!payload.canFight
661 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
662 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
663 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
664 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
661 665 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
662 666 if (payload.health != null)
663 667 { entity.health = payload.health; }
@@ -1455,20 +1459,6 @@ function copyCanvas (source, dest)
1455 1459 ctx.drawImage(source, 0, 0);
1456 1460 }
1457 1461
1458 function setNearestFilter (scene, canvas)
1459 {
1460 const glContext = scene?.glContext;
1461 if (!glContext || !canvas)
1462 { return; }
1463 const texture = glContext.getTexture(canvas);
1464 if (!texture)
1465 { return; }
1466 const gl = glContext.gl;
1467 gl.bindTexture(gl.TEXTURE_2D, texture);
1468 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1469 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1470 }
1471
1472 1462 function drawHpBar (canvas, current, max)
1473 1463 {
1474 1464 const ctx = canvas.getContext("2d");
@@ -9,6 +9,7 @@ import {
9 frameworkImageFromCanvas,
9 frameworkImageFromCanvas,
10 invalidateCanvasTexture
10 invalidateCanvasTexture
11} from "./canvasSprite.js";
11} from "./canvasSprite.js";
12import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
12
13
13const LAYER_GROUND = 0;
14const LAYER_GROUND = 0;
14const LAYER_EDGE = 900000;
15const LAYER_EDGE = 900000;
@@ -364,6 +365,7 @@ export class WorldView
364 }
365 }
365 this.#rebuildAllEdges();
366 this.#rebuildAllEdges();
366 this.#redrawPreview();
367 this.#redrawPreview();
368 applyNearestToAllTextures(this.scene, this.game.images);
367 }
369 }
368
370
369 tileSize ()
371 tileSize ()
@@ -653,11 +655,13 @@ export class WorldView
653 entity.sex = payload.sex ?? entity.sex;
655 entity.sex = payload.sex ?? entity.sex;
654 entity.characterId = payload.characterId ?? entity.characterId ?? null;
656 entity.characterId = payload.characterId ?? entity.characterId ?? null;
655 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
657 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
656 entity.hostile = !!payload.hostile;
658 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
657 entity.canFight = !!payload.canFight;
659 entity.canFight = payload.canFight != null
658 entity.talkable = !!payload.talkable;
660 ? !!payload.canFight
659 entity.untargetable = !!payload.untargetable;
661 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
660 entity.freeFlight = !!payload.freeFlight;
662 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
663 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
664 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
661 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
665 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
662 if (payload.health != null)
666 if (payload.health != null)
663 { entity.health = payload.health; }
667 { entity.health = payload.health; }
@@ -1455,20 +1459,6 @@ function copyCanvas (source, dest)
1455 ctx.drawImage(source, 0, 0);
1459 ctx.drawImage(source, 0, 0);
1456}
1460}
1457
1461
1458function setNearestFilter (scene, canvas)
1459{
1460 const glContext = scene?.glContext;
1461 if (!glContext || !canvas)
1462 { return; }
1463 const texture = glContext.getTexture(canvas);
1464 if (!texture)
1465 { return; }
1466 const gl = glContext.gl;
1467 gl.bindTexture(gl.TEXTURE_2D, texture);
1468 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1469 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1470}
1471
1472function drawHpBar (canvas, current, max)
1462function drawHpBar (canvas, current, max)
1473{
1463{
1474 const ctx = canvas.getContext("2d");
1464 const ctx = canvas.getContext("2d");
client/ui/play.css +26 −0
@@ -142,6 +142,30 @@ a { color: #d4c48a; }
142 142 margin-top: 0.5rem;
143 143 }
144 144
145 #death-backdrop {
146 position: fixed;
147 inset: 0;
148 z-index: 20;
149 background: rgba(0, 0, 0, 0.72);
150 }
151
152 #death-modal {
153 position: fixed;
154 z-index: 21;
155 left: 50%;
156 top: 42%;
157 transform: translate(-50%, -50%);
158 width: min(380px, 92vw);
159 background: #161a22;
160 border: 1px solid #713b3b;
161 padding: 1rem 1.15rem 1.15rem;
162 text-align: center;
163 }
164
165 #death-respawn {
166 min-width: 9rem;
167 }
168
145 169 #friends-panel {
146 170 position: fixed;
147 171 z-index: 5;
@@ -635,6 +659,8 @@ a { color: #d4c48a; }
635 659
636 660 #inspect-modal[hidden],
637 661 #inspect-backdrop[hidden],
662 #death-modal[hidden],
663 #death-backdrop[hidden],
638 664 #friends-panel[hidden],
639 665 #skills-panel[hidden],
640 666 #bag-panel[hidden],
@@ -142,6 +142,30 @@ a { color: #d4c48a; }
142 margin-top: 0.5rem;
142 margin-top: 0.5rem;
143}
143}
144
144
145#death-backdrop {
146 position: fixed;
147 inset: 0;
148 z-index: 20;
149 background: rgba(0, 0, 0, 0.72);
150}
151
152#death-modal {
153 position: fixed;
154 z-index: 21;
155 left: 50%;
156 top: 42%;
157 transform: translate(-50%, -50%);
158 width: min(380px, 92vw);
159 background: #161a22;
160 border: 1px solid #713b3b;
161 padding: 1rem 1.15rem 1.15rem;
162 text-align: center;
163}
164
165#death-respawn {
166 min-width: 9rem;
167}
168
145#friends-panel {
169#friends-panel {
146 position: fixed;
170 position: fixed;
147 z-index: 5;
171 z-index: 5;
@@ -635,6 +659,8 @@ a { color: #d4c48a; }
635
659
636#inspect-modal[hidden],
660#inspect-modal[hidden],
637#inspect-backdrop[hidden],
661#inspect-backdrop[hidden],
662#death-modal[hidden],
663#death-backdrop[hidden],
638#friends-panel[hidden],
664#friends-panel[hidden],
639#skills-panel[hidden],
665#skills-panel[hidden],
640#bag-panel[hidden],
666#bag-panel[hidden],
docs/FEATURES.md +17 −3
@@ -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. First-version types are grass, wood, stone wall, and torch. **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, 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.
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
@@ -171,7 +171,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
171 171
172 172 ## Midnight restart and Git deploy
173 173
174 **Status:** not implemented
174 **Status:** full
175 175 **Spec:** systemd + manifest-driven Git deploy. Pending world/code changes apply at server-local midnight, with an admin immediate-restart path. Crashes must not pull.
176 176 **Code:** —
177 177
@@ -208,9 +208,23 @@ 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. 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; 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 ## Player death and respawn
215
216 **Status:** full
217 **Spec:** When a **player** reaches **0 HP**, they **die** immediately (authoritative on the server):
218
219 1. **Corpse drops** on the death tile: a **bones** ground item and a **skull** ground item (new item definitions + sprites). These use normal ground-item rules (pickup, despawn timer). Inventory/equipment are **not** dropped by default (death penalty is the corpse markers + travel to church — revisit if PK/loot rules are added later).
220 2. **Combat ends** for the dead player and anyone targeting them (clear engage both ways). The dead player cannot move, attack, follow, pick up, bank, chat-actions that affect the world, or otherwise act until they respawn.
221 3. **Death modal (client):** a blocking modal that is the **only** interactable UI while dead (world clicks, hotkeys, bag, etc. are ignored). Copy states that the player is dead; primary action is **Respawn**. Closing the tab/disconnect while dead keeps them dead until they log in and respawn (or auto-prompt the same modal on re-enter).
222 4. **Respawn:** server moves the character to the **nearest church altar** block (Chebyshev / path distance TBD — prefer enterable tile adjacent to the altar if the altar tile itself is impassable). New **block type: church altar** (`BlockType` + editor placeable + sprite folder), passable or adjacent-use like bank (exact interaction: respawn destination only for now, not a usable station).
223 5. After respawn the player is restored to **full Health** and **full Stamina** (max from skills), cleared of death state, and may fight again.
224
225 **TODO:** Revisit player-loot penalties if PK rules are added.
226 **Code:** `shared/definitions/items.js`, `shared/definitions/tiles.js`, `shared/protocol/constants.js`, `server/src/combat/service.js`, `server/src/simulation/simulation.js`, `server/src/simulation/workerWorld.js`, `server/src/persistence/stateDb.js`, `server/src/gateway/websocket.js`, `client/src/play/death.js`, tests in `server/tests/death.test.js`
227
214 228 ## Equipment tiers and worn stat bonuses
215 229
216 230 **Status:** partial
@@ -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. First-version types are grass, wood, stone wall, and torch. **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, 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.
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
@@ -171,7 +171,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
171
171
172## Midnight restart and Git deploy
172## Midnight restart and Git deploy
173
173
174**Status:** not implemented
174**Status:** full
175**Spec:** systemd + manifest-driven Git deploy. Pending world/code changes apply at server-local midnight, with an admin immediate-restart path. Crashes must not pull.
175**Spec:** systemd + manifest-driven Git deploy. Pending world/code changes apply at server-local midnight, with an admin immediate-restart path. Crashes must not pull.
176**Code:** —
176**Code:** —
177
177
@@ -208,9 +208,23 @@ 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. 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; 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
215
216**Status:** full
217**Spec:** When a **player** reaches **0 HP**, they **die** immediately (authoritative on the server):
218
2191. **Corpse drops** on the death tile: a **bones** ground item and a **skull** ground item (new item definitions + sprites). These use normal ground-item rules (pickup, despawn timer). Inventory/equipment are **not** dropped by default (death penalty is the corpse markers + travel to church — revisit if PK/loot rules are added later).
2202. **Combat ends** for the dead player and anyone targeting them (clear engage both ways). The dead player cannot move, attack, follow, pick up, bank, chat-actions that affect the world, or otherwise act until they respawn.
2213. **Death modal (client):** a blocking modal that is the **only** interactable UI while dead (world clicks, hotkeys, bag, etc. are ignored). Copy states that the player is dead; primary action is **Respawn**. Closing the tab/disconnect while dead keeps them dead until they log in and respawn (or auto-prompt the same modal on re-enter).
2224. **Respawn:** server moves the character to the **nearest church altar** block (Chebyshev / path distance TBD — prefer enterable tile adjacent to the altar if the altar tile itself is impassable). New **block type: church altar** (`BlockType` + editor placeable + sprite folder), passable or adjacent-use like bank (exact interaction: respawn destination only for now, not a usable station).
2235. After respawn the player is restored to **full Health** and **full Stamina** (max from skills), cleared of death state, and may fight again.
224
225**TODO:** Revisit player-loot penalties if PK rules are added.
226**Code:** `shared/definitions/items.js`, `shared/definitions/tiles.js`, `shared/protocol/constants.js`, `server/src/combat/service.js`, `server/src/simulation/simulation.js`, `server/src/simulation/workerWorld.js`, `server/src/persistence/stateDb.js`, `server/src/gateway/websocket.js`, `client/src/play/death.js`, tests in `server/tests/death.test.js`
227
214## Equipment tiers and worn stat bonuses
228## Equipment tiers and worn stat bonuses
215
229
216**Status:** partial
230**Status:** partial
server/src/combat/service.js +215 −41
@@ -119,6 +119,52 @@ export function clearEngage (ecs, entityId)
119 119 { combat.targetEntityId = null; }
120 120 }
121 121
122 /** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
123 export function resolveCombatTarget (world, targetId)
124 {
125 const handle = world.ecs.handleOf(targetId);
126 if (handle != null)
127 {
128 const pos = world.ecs.get(handle, Component.position);
129 if (!pos)
130 { return null; }
131 if (isUntargetable(world.ecs, handle))
132 { return null; }
133 return {
134 local: true,
135 handle,
136 pos,
137 health: world.ecs.get(handle, Component.health)
138 };
139 }
140 const ghost = world.ghosts?.get?.(targetId);
141 if (!ghost || ghost.untargetable)
142 { return null; }
143 const health = ghost.health != null
144 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
145 : null;
146 return {
147 local: false,
148 handle: null,
149 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
150 health
151 };
152 }
153
154 function attackerCombatLevels (ecs, attackerHandle, profile)
155 {
156 const attackerCharacter = ecs.get(attackerHandle, Component.character);
157 if (attackerCharacter)
158 { return playerCombatLevels(ecs, attackerHandle, profile); }
159 const skills = ecs.get(attackerHandle, Component.skills);
160 return {
161 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
162 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
163 agilityLevel: skillLevel(skills, SkillId.dexterity),
164 defenceLevel: skillLevel(skills, SkillId.defence)
165 };
166 }
167
122 168 export function stepCombat (world, now = Date.now())
123 169 {
124 170 const events = [];
@@ -130,20 +176,13 @@ export function stepCombat (world, now = Date.now())
130 176 const targetId = combat.targetEntityId;
131 177 if (targetId == null)
132 178 { continue; }
133 const targetHandle = world.ecs.handleOf(targetId);
134 if (targetHandle == null)
179 const target = resolveCombatTarget(world, targetId);
180 if (!target)
135 181 {
136 182 combat.targetEntityId = null;
137 183 continue;
138 184 }
139 if (isUntargetable(world.ecs, targetHandle))
140 {
141 combat.targetEntityId = null;
142 continue;
143 }
144 const targetPos = world.ecs.get(targetHandle, Component.position);
145 const targetHealth = world.ecs.get(targetHandle, Component.health);
146 if (!targetPos || !targetHealth || targetHealth.current <= 0)
185 if (target.health && target.health.current <= 0)
147 186 {
148 187 combat.targetEntityId = null;
149 188 continue;
@@ -153,7 +192,9 @@ export function stepCombat (world, now = Date.now())
153 192 if (profile.mode !== "melee")
154 193 { continue; }
155 194
195 const targetPos = target.pos;
156 196 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
197 clearCombatApproachPath(world.ecs, entity.handle, dist);
157 198 if (dist > 1)
158 199 {
159 200 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
@@ -161,6 +202,9 @@ export function stepCombat (world, now = Date.now())
161 202 }
162 203 if (dist !== 1)
163 204 { continue; }
205 const attackerHealth = world.ecs.get(entity.handle, Component.health);
206 if (attackerHealth && attackerHealth.current <= 0)
207 { continue; }
164 208 if ((combat.nextSwingAt || 0) > now)
165 209 { continue; }
166 210
@@ -170,6 +214,15 @@ export function stepCombat (world, now = Date.now())
170 214 return events;
171 215 }
172 216
217 function clearCombatApproachPath (ecs, handle, distToTarget)
218 {
219 if (distToTarget > 1)
220 { return; }
221 const path = ecs.get(handle, Component.path);
222 if (path?.tiles?.length)
223 { path.tiles = []; }
224 }
225
173 226 function queueMeleeApproach (world, entityId, handle, position, targetPos)
174 227 {
175 228 if (world.frozen?.has?.(entityId))
@@ -188,7 +241,6 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
188 241 if (!goal)
189 242 {
190 243 path.tiles = [];
191 clearEngage(world.ecs, entityId);
192 244 return;
193 245 }
194 246
@@ -210,7 +262,6 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
210 262 if (!tiles.length)
211 263 {
212 264 path.tiles = [];
213 clearEngage(world.ecs, entityId);
214 265 return;
215 266 }
216 267 path.tiles = tiles;
@@ -262,13 +313,17 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
262 313 {
263 314 const events = [];
264 315 const attackerHandle = world.ecs.handleOf(attackerId);
265 const targetHandle = world.ecs.handleOf(targetId);
266 if (attackerHandle == null || targetHandle == null)
316 if (attackerHandle == null)
317 { return events; }
318 const target = resolveCombatTarget(world, targetId);
319 if (!target)
267 320 { return events; }
268 321 const from = world.ecs.get(attackerHandle, Component.position);
269 const to = world.ecs.get(targetHandle, Component.position);
322 const to = target.pos;
270 323 if (!from || !to)
271 324 { return events; }
325 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
326 { return events; }
272 327
273 328 events.push({
274 329 type: "combat-swing",
@@ -280,23 +335,108 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
280 335 fromTileY: from.tileY
281 336 });
282 337
283 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
284 if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
285 { engageTarget(world.ecs, targetId, attackerId, now); }
338 if (!target.local)
339 {
340 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
341 events.push({
342 type: "remote-melee-resolve",
343 attackerId,
344 targetId,
345 profile,
346 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
347 attackerIsPlayer: !!attackerCharacter,
348 now,
349 tileX: to.tileX,
350 tileY: to.tileY
351 });
352 return events;
353 }
354
355 return events.concat(applyLocalMeleeHit(
356 world,
357 attackerId,
358 targetId,
359 attackerHandle,
360 target.handle,
361 profile,
362 now,
363 to
364 ));
365 }
366
367 /** Authoritative hit resolution when the defender lives on this worker. */
368 export function applyRemoteMeleeSwing (world, payload)
369 {
370 const targetHandle = world.ecs.handleOf(payload.targetId);
371 if (targetHandle == null)
372 { return { events: [], forwards: [] }; }
373 const to = world.ecs.get(targetHandle, Component.position);
374 if (!to)
375 { return { events: [], forwards: [] }; }
376
377 const events = applyLocalMeleeHit(
378 world,
379 payload.attackerId,
380 payload.targetId,
381 null,
382 targetHandle,
383 payload.profile,
384 payload.now ?? Date.now(),
385 to,
386 payload.attackerLevels
387 );
388
389 const forwards = [];
390 if (payload.attackerIsPlayer && ensureMobCombat(world.ecs, payload.targetId))
391 { engageTarget(world.ecs, payload.targetId, payload.attackerId, payload.now ?? Date.now()); }
392 if (!payload.attackerIsPlayer)
393 {
394 const targetCharacter = world.ecs.get(targetHandle, Component.character);
395 if (targetCharacter)
396 { engageTarget(world.ecs, payload.targetId, payload.attackerId, payload.now ?? Date.now()); }
397 }
398 const hitEvent = events.find((event) => event.type === "combat-hit");
399 if (hitEvent && payload.attackerIsPlayer)
400 {
401 forwards.push({
402 type: "forward-combat-xp",
403 entityId: payload.attackerId,
404 profile: payload.profile
405 });
406 }
407 return { events, forwards };
408 }
409
410 function applyLocalMeleeHit (
411 world,
412 attackerId,
413 targetId,
414 attackerHandle,
415 targetHandle,
416 profile,
417 now,
418 to,
419 attackerLevelsOverride = null
420 )
421 {
422 const events = [];
423 if (targetHandle == null)
424 { return events; }
425
426 if (attackerHandle != null)
427 {
428 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
429 if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
430 { engageTarget(world.ecs, targetId, attackerId, now); }
431 }
286 432
287 const skills = world.ecs.get(attackerHandle, Component.skills);
288 433 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
289 434 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
290 const attackerLevels = attackerCharacter
291 ? playerCombatLevels(world.ecs, attackerHandle, profile)
292 : {
293 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
294 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
295 agilityLevel: skillLevel(skills, SkillId.dexterity),
296 defenceLevel: skillLevel(skills, SkillId.defence)
297 };
298 const hitLevel = attackerLevels.hitLevel;
299 const damageLevel = attackerLevels.damageLevel;
435 const attackerLevels = attackerLevelsOverride
436 ?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile) : null);
437 if (!attackerLevels)
438 { return events; }
439
300 440 const agilityLevel = defenderSkillLevel(
301 441 defenderSkills,
302 442 SkillId.dexterity,
@@ -309,9 +449,9 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
309 449 );
310 450
311 451 const resolved = resolvePhysicalAttack({
312 hitSkillLevel: hitLevel,
452 hitSkillLevel: attackerLevels.hitLevel,
313 453 agilitySkillLevel: agilityLevel,
314 damageSkillLevel: damageLevel,
454 damageSkillLevel: attackerLevels.damageLevel,
315 455 defenceSkillLevel: defenceLevel,
316 456 baseDamage: profile.baseDamage ?? 1
317 457 });
@@ -381,18 +521,22 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
381 521 }
382 522 }
383 523
384 if (attackerCharacter)
524 if (attackerHandle != null)
385 525 {
386 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
387 if (xpAward)
526 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
527 if (attackerCharacter)
388 528 {
389 events.push({
390 type: "skills-updated",
391 entityId: attackerId,
392 characterId: attackerCharacter.characterId,
393 skills: xpAward.view,
394 stored: xpAward.stored
395 });
529 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
530 if (xpAward)
531 {
532 events.push({
533 type: "skills-updated",
534 entityId: attackerId,
535 characterId: attackerCharacter.characterId,
536 skills: xpAward.view,
537 stored: xpAward.stored
538 });
539 }
396 540 }
397 541 }
398 542
@@ -400,6 +544,36 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
400 544 {
401 545 clearEngage(world.ecs, attackerId);
402 546 clearEngage(world.ecs, targetId);
547 for (const entity of world.ecs.query(Component.combat))
548 {
549 if (entity.combat.targetEntityId === targetId)
550 { entity.combat.targetEntityId = null; }
551 }
552 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
553 {
554 const path = world.ecs.get(targetHandle, Component.path);
555 if (path)
556 { path.tiles = []; }
557 const follow = world.ecs.get(targetHandle, Component.follow);
558 if (follow)
559 {
560 follow.targetEntityId = null;
561 follow.trail = [];
562 }
563 world.ecs.add(targetHandle, Component.dead, {});
564 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
565 events.push({
566 type: "player-died",
567 entityId: targetId,
568 attackerId,
569 characterId: targetCharacter.characterId,
570 sessionId: identity?.sessionId ?? null,
571 tileX: to.tileX,
572 tileY: to.tileY,
573 health: 0,
574 maxHealth: health.max
575 });
576 }
403 577 const creature = world.ecs.get(targetHandle, Component.creature);
404 578 if (creature && !world.ecs.get(targetHandle, Component.character))
405 579 {
@@ -119,6 +119,52 @@ export function clearEngage (ecs, entityId)
119 { combat.targetEntityId = null; }
119 { combat.targetEntityId = null; }
120}
120}
121
121
122/** Local entity handle or a nearby ghost snapshot for cross-worker combat. */
123export function resolveCombatTarget (world, targetId)
124{
125 const handle = world.ecs.handleOf(targetId);
126 if (handle != null)
127 {
128 const pos = world.ecs.get(handle, Component.position);
129 if (!pos)
130 { return null; }
131 if (isUntargetable(world.ecs, handle))
132 { return null; }
133 return {
134 local: true,
135 handle,
136 pos,
137 health: world.ecs.get(handle, Component.health)
138 };
139 }
140 const ghost = world.ghosts?.get?.(targetId);
141 if (!ghost || ghost.untargetable)
142 { return null; }
143 const health = ghost.health != null
144 ? { current: ghost.health, max: ghost.maxHealth ?? ghost.health }
145 : null;
146 return {
147 local: false,
148 handle: null,
149 pos: { tileX: ghost.tileX, tileY: ghost.tileY },
150 health
151 };
152}
153
154function attackerCombatLevels (ecs, attackerHandle, profile)
155{
156 const attackerCharacter = ecs.get(attackerHandle, Component.character);
157 if (attackerCharacter)
158 { return playerCombatLevels(ecs, attackerHandle, profile); }
159 const skills = ecs.get(attackerHandle, Component.skills);
160 return {
161 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
162 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
163 agilityLevel: skillLevel(skills, SkillId.dexterity),
164 defenceLevel: skillLevel(skills, SkillId.defence)
165 };
166}
167
122export function stepCombat (world, now = Date.now())
168export function stepCombat (world, now = Date.now())
123{
169{
124 const events = [];
170 const events = [];
@@ -130,20 +176,13 @@ export function stepCombat (world, now = Date.now())
130 const targetId = combat.targetEntityId;
176 const targetId = combat.targetEntityId;
131 if (targetId == null)
177 if (targetId == null)
132 { continue; }
178 { continue; }
133 const targetHandle = world.ecs.handleOf(targetId);
179 const target = resolveCombatTarget(world, targetId);
134 if (targetHandle == null)
180 if (!target)
135 {
181 {
136 combat.targetEntityId = null;
182 combat.targetEntityId = null;
137 continue;
183 continue;
138 }
184 }
139 if (isUntargetable(world.ecs, targetHandle))
185 if (target.health && target.health.current <= 0)
140 {
141 combat.targetEntityId = null;
142 continue;
143 }
144 const targetPos = world.ecs.get(targetHandle, Component.position);
145 const targetHealth = world.ecs.get(targetHandle, Component.health);
146 if (!targetPos || !targetHealth || targetHealth.current <= 0)
147 {
186 {
148 combat.targetEntityId = null;
187 combat.targetEntityId = null;
149 continue;
188 continue;
@@ -153,7 +192,9 @@ export function stepCombat (world, now = Date.now())
153 if (profile.mode !== "melee")
192 if (profile.mode !== "melee")
154 { continue; }
193 { continue; }
155
194
195 const targetPos = target.pos;
156 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
196 const dist = chebyshev(entity.position.tileX, entity.position.tileY, targetPos.tileX, targetPos.tileY);
197 clearCombatApproachPath(world.ecs, entity.handle, dist);
157 if (dist > 1)
198 if (dist > 1)
158 {
199 {
159 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
200 queueMeleeApproach(world, entity.entityId, entity.handle, entity.position, targetPos);
@@ -161,6 +202,9 @@ export function stepCombat (world, now = Date.now())
161 }
202 }
162 if (dist !== 1)
203 if (dist !== 1)
163 { continue; }
204 { continue; }
205 const attackerHealth = world.ecs.get(entity.handle, Component.health);
206 if (attackerHealth && attackerHealth.current <= 0)
207 { continue; }
164 if ((combat.nextSwingAt || 0) > now)
208 if ((combat.nextSwingAt || 0) > now)
165 { continue; }
209 { continue; }
166
210
@@ -170,6 +214,15 @@ export function stepCombat (world, now = Date.now())
170 return events;
214 return events;
171}
215}
172
216
217function clearCombatApproachPath (ecs, handle, distToTarget)
218{
219 if (distToTarget > 1)
220 { return; }
221 const path = ecs.get(handle, Component.path);
222 if (path?.tiles?.length)
223 { path.tiles = []; }
224}
225
173function queueMeleeApproach (world, entityId, handle, position, targetPos)
226function queueMeleeApproach (world, entityId, handle, position, targetPos)
174{
227{
175 if (world.frozen?.has?.(entityId))
228 if (world.frozen?.has?.(entityId))
@@ -188,7 +241,6 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
188 if (!goal)
241 if (!goal)
189 {
242 {
190 path.tiles = [];
243 path.tiles = [];
191 clearEngage(world.ecs, entityId);
192 return;
244 return;
193 }
245 }
194
246
@@ -210,7 +262,6 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
210 if (!tiles.length)
262 if (!tiles.length)
211 {
263 {
212 path.tiles = [];
264 path.tiles = [];
213 clearEngage(world.ecs, entityId);
214 return;
265 return;
215 }
266 }
216 path.tiles = tiles;
267 path.tiles = tiles;
@@ -262,13 +313,17 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
262{
313{
263 const events = [];
314 const events = [];
264 const attackerHandle = world.ecs.handleOf(attackerId);
315 const attackerHandle = world.ecs.handleOf(attackerId);
265 const targetHandle = world.ecs.handleOf(targetId);
316 if (attackerHandle == null)
266 if (attackerHandle == null || targetHandle == null)
317 { return events; }
318 const target = resolveCombatTarget(world, targetId);
319 if (!target)
267 { return events; }
320 { return events; }
268 const from = world.ecs.get(attackerHandle, Component.position);
321 const from = world.ecs.get(attackerHandle, Component.position);
269 const to = world.ecs.get(targetHandle, Component.position);
322 const to = target.pos;
270 if (!from || !to)
323 if (!from || !to)
271 { return events; }
324 { return events; }
325 if (chebyshev(from.tileX, from.tileY, to.tileX, to.tileY) !== 1)
326 { return events; }
272
327
273 events.push({
328 events.push({
274 type: "combat-swing",
329 type: "combat-swing",
@@ -280,23 +335,108 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
280 fromTileY: from.tileY
335 fromTileY: from.tileY
281 });
336 });
282
337
283 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
338 if (!target.local)
284 if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
339 {
285 { engageTarget(world.ecs, targetId, attackerId, now); }
340 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
341 events.push({
342 type: "remote-melee-resolve",
343 attackerId,
344 targetId,
345 profile,
346 attackerLevels: attackerCombatLevels(world.ecs, attackerHandle, profile),
347 attackerIsPlayer: !!attackerCharacter,
348 now,
349 tileX: to.tileX,
350 tileY: to.tileY
351 });
352 return events;
353 }
354
355 return events.concat(applyLocalMeleeHit(
356 world,
357 attackerId,
358 targetId,
359 attackerHandle,
360 target.handle,
361 profile,
362 now,
363 to
364 ));
365}
366
367/** Authoritative hit resolution when the defender lives on this worker. */
368export function applyRemoteMeleeSwing (world, payload)
369{
370 const targetHandle = world.ecs.handleOf(payload.targetId);
371 if (targetHandle == null)
372 { return { events: [], forwards: [] }; }
373 const to = world.ecs.get(targetHandle, Component.position);
374 if (!to)
375 { return { events: [], forwards: [] }; }
376
377 const events = applyLocalMeleeHit(
378 world,
379 payload.attackerId,
380 payload.targetId,
381 null,
382 targetHandle,
383 payload.profile,
384 payload.now ?? Date.now(),
385 to,
386 payload.attackerLevels
387 );
388
389 const forwards = [];
390 if (payload.attackerIsPlayer && ensureMobCombat(world.ecs, payload.targetId))
391 { engageTarget(world.ecs, payload.targetId, payload.attackerId, payload.now ?? Date.now()); }
392 if (!payload.attackerIsPlayer)
393 {
394 const targetCharacter = world.ecs.get(targetHandle, Component.character);
395 if (targetCharacter)
396 { engageTarget(world.ecs, payload.targetId, payload.attackerId, payload.now ?? Date.now()); }
397 }
398 const hitEvent = events.find((event) => event.type === "combat-hit");
399 if (hitEvent && payload.attackerIsPlayer)
400 {
401 forwards.push({
402 type: "forward-combat-xp",
403 entityId: payload.attackerId,
404 profile: payload.profile
405 });
406 }
407 return { events, forwards };
408}
409
410function applyLocalMeleeHit (
411 world,
412 attackerId,
413 targetId,
414 attackerHandle,
415 targetHandle,
416 profile,
417 now,
418 to,
419 attackerLevelsOverride = null
420)
421{
422 const events = [];
423 if (targetHandle == null)
424 { return events; }
425
426 if (attackerHandle != null)
427 {
428 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
429 if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
430 { engageTarget(world.ecs, targetId, attackerId, now); }
431 }
286
432
287 const skills = world.ecs.get(attackerHandle, Component.skills);
288 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
433 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
289 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
434 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
290 const attackerLevels = attackerCharacter
435 const attackerLevels = attackerLevelsOverride
291 ? playerCombatLevels(world.ecs, attackerHandle, profile)
436 ?? (attackerHandle != null ? attackerCombatLevels(world.ecs, attackerHandle, profile) : null);
292 : {
437 if (!attackerLevels)
293 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
438 { return events; }
294 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
439
295 agilityLevel: skillLevel(skills, SkillId.dexterity),
296 defenceLevel: skillLevel(skills, SkillId.defence)
297 };
298 const hitLevel = attackerLevels.hitLevel;
299 const damageLevel = attackerLevels.damageLevel;
300 const agilityLevel = defenderSkillLevel(
440 const agilityLevel = defenderSkillLevel(
301 defenderSkills,
441 defenderSkills,
302 SkillId.dexterity,
442 SkillId.dexterity,
@@ -309,9 +449,9 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
309 );
449 );
310
450
311 const resolved = resolvePhysicalAttack({
451 const resolved = resolvePhysicalAttack({
312 hitSkillLevel: hitLevel,
452 hitSkillLevel: attackerLevels.hitLevel,
313 agilitySkillLevel: agilityLevel,
453 agilitySkillLevel: agilityLevel,
314 damageSkillLevel: damageLevel,
454 damageSkillLevel: attackerLevels.damageLevel,
315 defenceSkillLevel: defenceLevel,
455 defenceSkillLevel: defenceLevel,
316 baseDamage: profile.baseDamage ?? 1
456 baseDamage: profile.baseDamage ?? 1
317 });
457 });
@@ -381,18 +521,22 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
381 }
521 }
382 }
522 }
383
523
384 if (attackerCharacter)
524 if (attackerHandle != null)
385 {
525 {
386 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
526 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
387 if (xpAward)
527 if (attackerCharacter)
388 {
528 {
389 events.push({
529 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
390 type: "skills-updated",
530 if (xpAward)
391 entityId: attackerId,
531 {
392 characterId: attackerCharacter.characterId,
532 events.push({
393 skills: xpAward.view,
533 type: "skills-updated",
394 stored: xpAward.stored
534 entityId: attackerId,
395 });
535 characterId: attackerCharacter.characterId,
536 skills: xpAward.view,
537 stored: xpAward.stored
538 });
539 }
396 }
540 }
397 }
541 }
398
542
@@ -400,6 +544,36 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
400 {
544 {
401 clearEngage(world.ecs, attackerId);
545 clearEngage(world.ecs, attackerId);
402 clearEngage(world.ecs, targetId);
546 clearEngage(world.ecs, targetId);
547 for (const entity of world.ecs.query(Component.combat))
548 {
549 if (entity.combat.targetEntityId === targetId)
550 { entity.combat.targetEntityId = null; }
551 }
552 if (targetCharacter && !world.ecs.has(targetHandle, Component.dead))
553 {
554 const path = world.ecs.get(targetHandle, Component.path);
555 if (path)
556 { path.tiles = []; }
557 const follow = world.ecs.get(targetHandle, Component.follow);
558 if (follow)
559 {
560 follow.targetEntityId = null;
561 follow.trail = [];
562 }
563 world.ecs.add(targetHandle, Component.dead, {});
564 const identity = world.ecs.get(targetHandle, Component.networkIdentity);
565 events.push({
566 type: "player-died",
567 entityId: targetId,
568 attackerId,
569 characterId: targetCharacter.characterId,
570 sessionId: identity?.sessionId ?? null,
571 tileX: to.tileX,
572 tileY: to.tileY,
573 health: 0,
574 maxHealth: health.max
575 });
576 }
403 const creature = world.ecs.get(targetHandle, Component.creature);
577 const creature = world.ecs.get(targetHandle, Component.creature);
404 if (creature && !world.ecs.get(targetHandle, Component.character))
578 if (creature && !world.ecs.get(targetHandle, Component.character))
405 {
579 {
server/src/courier/service.js +77 −11
@@ -6,6 +6,7 @@ import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVa
6 6 import { advanceCourierFlight } from "../../../shared/courier/flight.js";
7 7 import { GAIT } from "../../../shared/protocol/constants.js";
8 8 import { decodeChunkBlob } from "../world/chunkData.js";
9 import { findReservedChequeIndex } from "../items/bags.js";
9 10
10 11 export class CourierService
11 12 {
@@ -423,19 +424,84 @@ export class CourierService
423 424 : this.stateDb.getBag(characterId);
424 425 if (!bag)
425 426 { return; }
426 if (cargo.kind === "item")
427 if (cargo.kind !== "item")
428 { return; }
429
430 const stack = cargo.stack;
431 if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
432 {
433 this.#redeemChequeIntoVault(characterId, bag, stack);
434 return;
435 }
436
437 const def = itemDefinition(stack.itemId);
438 const vault = normalizeVault(
439 bag.vaultReserved != null
440 ? { slots: bag.vault, reserved: bag.vaultReserved }
441 : bag.vault
442 );
443 const result = insertStackGrowable(vault.slots, stack, def);
444 bag.vault = result.slots;
445 bag.vaultReserved = vault.reserved;
446 this.#persistBag(characterId, bag);
447 }
448
449 /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */
450 #redeemChequeIntoVault (characterId, bag, chequeStack)
451 {
452 const instance = chequeStack.instance;
453 const issuerId = instance.issuerCharacterId;
454 const goodsDef = itemDefinition(instance.itemId);
455 if (!goodsDef)
456 { return; }
457
458 let reservedStack = null;
459 if (Number(issuerId) === Number(characterId))
460 {
461 const reserved = [...(bag.vaultReserved ?? [])];
462 const index = findReservedChequeIndex(reserved, instance);
463 if (index < 0)
464 {
465 // Paper arrived but reservation is gone — keep the cheque so it isn't silently lost.
466 const def = itemDefinition(ItemId.filledCheque);
467 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
468 const result = insertStackGrowable(vault.slots, chequeStack, def);
469 bag.vault = result.slots;
470 bag.vaultReserved = vault.reserved;
471 this.#persistBag(characterId, bag);
472 return;
473 }
474 reservedStack = reserved[index];
475 reserved.splice(index, 1);
476 bag.vaultReserved = reserved;
477 }
478 else
427 479 {
428 const def = itemDefinition(cargo.stack.itemId);
429 const vault = normalizeVault(
430 bag.vaultReserved != null
431 ? { slots: bag.vault, reserved: bag.vaultReserved }
432 : bag.vault
433 );
434 const result = insertStackGrowable(vault.slots, cargo.stack, def);
435 bag.vault = result.slots;
436 bag.vaultReserved = vault.reserved;
437 this.#persistBag(characterId, bag);
480 const release = this.simulation.releaseChequeReservation(issuerId, instance.chequeId, instance);
481 if (!release?.ok)
482 {
483 const def = itemDefinition(ItemId.filledCheque);
484 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
485 const result = insertStackGrowable(vault.slots, chequeStack, def);
486 bag.vault = result.slots;
487 bag.vaultReserved = vault.reserved;
488 this.#persistBag(characterId, bag);
489 return;
490 }
491 reservedStack = release.stack;
438 492 }
493
494 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
495 const inserted = insertStackGrowable(vault.slots, {
496 itemId: reservedStack.itemId,
497 quantity: reservedStack.quantity,
498 origin: reservedStack.origin ?? null,
499 origins: reservedStack.origins ?? null,
500 instance: reservedStack.instance ?? null
501 }, goodsDef);
502 bag.vault = inserted.slots;
503 bag.vaultReserved = vault.reserved;
504 this.#persistBag(characterId, bag);
439 505 }
440 506
441 507 #persistBag (characterId, bag)
@@ -6,6 +6,7 @@ import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVa
6import { advanceCourierFlight } from "../../../shared/courier/flight.js";
6import { advanceCourierFlight } from "../../../shared/courier/flight.js";
7import { GAIT } from "../../../shared/protocol/constants.js";
7import { GAIT } from "../../../shared/protocol/constants.js";
8import { decodeChunkBlob } from "../world/chunkData.js";
8import { decodeChunkBlob } from "../world/chunkData.js";
9import { findReservedChequeIndex } from "../items/bags.js";
9
10
10export class CourierService
11export class CourierService
11{
12{
@@ -423,19 +424,84 @@ export class CourierService
423 : this.stateDb.getBag(characterId);
424 : this.stateDb.getBag(characterId);
424 if (!bag)
425 if (!bag)
425 { return; }
426 { return; }
426 if (cargo.kind === "item")
427 if (cargo.kind !== "item")
428 { return; }
429
430 const stack = cargo.stack;
431 if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
432 {
433 this.#redeemChequeIntoVault(characterId, bag, stack);
434 return;
435 }
436
437 const def = itemDefinition(stack.itemId);
438 const vault = normalizeVault(
439 bag.vaultReserved != null
440 ? { slots: bag.vault, reserved: bag.vaultReserved }
441 : bag.vault
442 );
443 const result = insertStackGrowable(vault.slots, stack, def);
444 bag.vault = result.slots;
445 bag.vaultReserved = vault.reserved;
446 this.#persistBag(characterId, bag);
447 }
448
449 /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */
450 #redeemChequeIntoVault (characterId, bag, chequeStack)
451 {
452 const instance = chequeStack.instance;
453 const issuerId = instance.issuerCharacterId;
454 const goodsDef = itemDefinition(instance.itemId);
455 if (!goodsDef)
456 { return; }
457
458 let reservedStack = null;
459 if (Number(issuerId) === Number(characterId))
460 {
461 const reserved = [...(bag.vaultReserved ?? [])];
462 const index = findReservedChequeIndex(reserved, instance);
463 if (index < 0)
464 {
465 // Paper arrived but reservation is gone — keep the cheque so it isn't silently lost.
466 const def = itemDefinition(ItemId.filledCheque);
467 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
468 const result = insertStackGrowable(vault.slots, chequeStack, def);
469 bag.vault = result.slots;
470 bag.vaultReserved = vault.reserved;
471 this.#persistBag(characterId, bag);
472 return;
473 }
474 reservedStack = reserved[index];
475 reserved.splice(index, 1);
476 bag.vaultReserved = reserved;
477 }
478 else
427 {
479 {
428 const def = itemDefinition(cargo.stack.itemId);
480 const release = this.simulation.releaseChequeReservation(issuerId, instance.chequeId, instance);
429 const vault = normalizeVault(
481 if (!release?.ok)
430 bag.vaultReserved != null
482 {
431 ? { slots: bag.vault, reserved: bag.vaultReserved }
483 const def = itemDefinition(ItemId.filledCheque);
432 : bag.vault
484 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
433 );
485 const result = insertStackGrowable(vault.slots, chequeStack, def);
434 const result = insertStackGrowable(vault.slots, cargo.stack, def);
486 bag.vault = result.slots;
435 bag.vault = result.slots;
487 bag.vaultReserved = vault.reserved;
436 bag.vaultReserved = vault.reserved;
488 this.#persistBag(characterId, bag);
437 this.#persistBag(characterId, bag);
489 return;
490 }
491 reservedStack = release.stack;
438 }
492 }
493
494 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
495 const inserted = insertStackGrowable(vault.slots, {
496 itemId: reservedStack.itemId,
497 quantity: reservedStack.quantity,
498 origin: reservedStack.origin ?? null,
499 origins: reservedStack.origins ?? null,
500 instance: reservedStack.instance ?? null
501 }, goodsDef);
502 bag.vault = inserted.slots;
503 bag.vaultReserved = vault.reserved;
504 this.#persistBag(characterId, bag);
439 }
505 }
440
506
441 #persistBag (characterId, bag)
507 #persistBag (characterId, bag)
server/src/ecs/components.js +3 −1
@@ -16,5 +16,7 @@ export const Component = Object.freeze({
16 16 spawnOrigin: "spawnOrigin",
17 17 combat: "combat",
18 18 skills: "skills",
19 follow: "follow"
19 follow: "follow",
20 dead: "dead",
21 stamina: "stamina"
20 22 });
@@ -16,5 +16,7 @@ export const Component = Object.freeze({
16 spawnOrigin: "spawnOrigin",
16 spawnOrigin: "spawnOrigin",
17 combat: "combat",
17 combat: "combat",
18 skills: "skills",
18 skills: "skills",
19 follow: "follow"
19 follow: "follow",
20 dead: "dead",
21 stamina: "stamina"
20});
22});
server/src/ecs/serialize.js +3 −3
@@ -81,13 +81,13 @@ export function publicEntityView (ecs, entityId)
81 81 lastName: appearance?.lastName ?? "",
82 82 characterId: character?.characterId ?? null,
83 83 mobTypeId: creature?.mobTypeId ?? null,
84 canFight: mob ? mobCanFight(mob) : false,
84 canFight: mob ? mobCanFight(mob) : !!character,
85 85 hostile: !!mob?.hostile,
86 86 talkable: !!mob?.talkable,
87 87 untargetable: !!mob?.untargetable,
88 88 freeFlight: !!mob?.freeFlight,
89 health: isMob && health ? health.current : undefined,
90 maxHealth: isMob && health ? health.max : undefined,
89 health: health ? health.current : undefined,
90 maxHealth: health ? health.max : undefined,
91 91 sprite: layers[0]?.sprite ?? null,
92 92 layers,
93 93 lightRadiusTiles: equippedLightRadiusTiles(equipment)
@@ -81,13 +81,13 @@ export function publicEntityView (ecs, entityId)
81 lastName: appearance?.lastName ?? "",
81 lastName: appearance?.lastName ?? "",
82 characterId: character?.characterId ?? null,
82 characterId: character?.characterId ?? null,
83 mobTypeId: creature?.mobTypeId ?? null,
83 mobTypeId: creature?.mobTypeId ?? null,
84 canFight: mob ? mobCanFight(mob) : false,
84 canFight: mob ? mobCanFight(mob) : !!character,
85 hostile: !!mob?.hostile,
85 hostile: !!mob?.hostile,
86 talkable: !!mob?.talkable,
86 talkable: !!mob?.talkable,
87 untargetable: !!mob?.untargetable,
87 untargetable: !!mob?.untargetable,
88 freeFlight: !!mob?.freeFlight,
88 freeFlight: !!mob?.freeFlight,
89 health: isMob && health ? health.current : undefined,
89 health: health ? health.current : undefined,
90 maxHealth: isMob && health ? health.max : undefined,
90 maxHealth: health ? health.max : undefined,
91 sprite: layers[0]?.sprite ?? null,
91 sprite: layers[0]?.sprite ?? null,
92 layers,
92 layers,
93 lightRadiusTiles: equippedLightRadiusTiles(equipment)
93 lightRadiusTiles: equippedLightRadiusTiles(equipment)
server/src/gateway/websocket.js +56 −0
@@ -66,6 +66,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
66 66
67 67 function handleMessage (session, message)
68 68 {
69 if (session.characterId
70 && stateDb.getCharacter(session.characterId)?.is_dead
71 && message.type !== MessageType.respawn
72 && message.type !== MessageType.leaveWorld)
73 {
74 const error = new Error("You are dead.");
75 error.userFacing = true;
76 throw error;
77 }
69 78 switch (message.type)
70 79 {
71 80 case MessageType.createCharacter:
@@ -87,6 +96,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
87 96 leaveWorld(session);
88 97 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
89 98 break;
99 case MessageType.respawn:
100 requirePlaying(session);
101 simulation.enqueue(session.id, {
102 type: "respawn",
103 characterId: session.characterId
104 });
105 break;
90 106 case MessageType.moveTo:
91 107 requirePlaying(session);
92 108 simulation.enqueue(session.id, {
@@ -426,6 +442,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
426 442 const skills = simulation.skillsOf(session.entityId);
427 443 if (skills)
428 444 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
445 if (character.is_dead)
446 {
447 send(session, {
448 type: MessageType.playerDied,
449 entityId: session.entityId,
450 characterId: session.characterId
451 });
452 }
429 453 publishReplication(simulation.drainReplication());
430 454 }
431 455
@@ -595,6 +619,38 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
595 619 }
596 620 continue;
597 621 }
622 if (event.type === "player-died")
623 {
624 const session = sessions.get(event.sessionId);
625 if (session)
626 {
627 send(session, {
628 type: MessageType.playerDied,
629 entityId: event.entityId,
630 characterId: event.characterId
631 });
632 }
633 continue;
634 }
635 if (event.type === "player-respawned")
636 {
637 const session = sessions.get(event.sessionId);
638 if (session)
639 {
640 send(session, {
641 type: MessageType.playerRespawned,
642 entityId: event.entityId,
643 characterId: event.characterId,
644 tileX: event.tileX,
645 tileY: event.tileY,
646 health: event.health,
647 maxHealth: event.maxHealth,
648 stamina: event.stamina,
649 maxStamina: event.maxStamina
650 });
651 }
652 continue;
653 }
598 654 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")
599 655 { publishEntity(event); }
600 656 }
@@ -66,6 +66,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
66
66
67 function handleMessage (session, message)
67 function handleMessage (session, message)
68 {
68 {
69 if (session.characterId
70 && stateDb.getCharacter(session.characterId)?.is_dead
71 && message.type !== MessageType.respawn
72 && message.type !== MessageType.leaveWorld)
73 {
74 const error = new Error("You are dead.");
75 error.userFacing = true;
76 throw error;
77 }
69 switch (message.type)
78 switch (message.type)
70 {
79 {
71 case MessageType.createCharacter:
80 case MessageType.createCharacter:
@@ -87,6 +96,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
87 leaveWorld(session);
96 leaveWorld(session);
88 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
97 send(session, { type: MessageType.characterList, characters: characters.list(session.account.account_id) });
89 break;
98 break;
99 case MessageType.respawn:
100 requirePlaying(session);
101 simulation.enqueue(session.id, {
102 type: "respawn",
103 characterId: session.characterId
104 });
105 break;
90 case MessageType.moveTo:
106 case MessageType.moveTo:
91 requirePlaying(session);
107 requirePlaying(session);
92 simulation.enqueue(session.id, {
108 simulation.enqueue(session.id, {
@@ -426,6 +442,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
426 const skills = simulation.skillsOf(session.entityId);
442 const skills = simulation.skillsOf(session.entityId);
427 if (skills)
443 if (skills)
428 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
444 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
445 if (character.is_dead)
446 {
447 send(session, {
448 type: MessageType.playerDied,
449 entityId: session.entityId,
450 characterId: session.characterId
451 });
452 }
429 publishReplication(simulation.drainReplication());
453 publishReplication(simulation.drainReplication());
430 }
454 }
431
455
@@ -595,6 +619,38 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
595 }
619 }
596 continue;
620 continue;
597 }
621 }
622 if (event.type === "player-died")
623 {
624 const session = sessions.get(event.sessionId);
625 if (session)
626 {
627 send(session, {
628 type: MessageType.playerDied,
629 entityId: event.entityId,
630 characterId: event.characterId
631 });
632 }
633 continue;
634 }
635 if (event.type === "player-respawned")
636 {
637 const session = sessions.get(event.sessionId);
638 if (session)
639 {
640 send(session, {
641 type: MessageType.playerRespawned,
642 entityId: event.entityId,
643 characterId: event.characterId,
644 tileX: event.tileX,
645 tileY: event.tileY,
646 health: event.health,
647 maxHealth: event.maxHealth,
648 stamina: event.stamina,
649 maxStamina: event.maxStamina
650 });
651 }
652 continue;
653 }
598 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")
654 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")
599 { publishEntity(event); }
655 { publishEntity(event); }
600 }
656 }
server/src/items/bags.js +25 −2
@@ -514,7 +514,7 @@ function redeemCheque (world, sessionId, command)
514 514 let reservedStack = null;
515 515 if (Number(issuerId) === Number(command.characterId))
516 516 {
517 const index = (vault.reserved ?? []).findIndex((entry) => entry?.chequeId === chequeId);
517 const index = findReservedChequeIndex(vault.reserved, slot.instance);
518 518 if (index < 0)
519 519 {
520 520 inventory.slots[slotIndex] = chequeTaken.taken;
@@ -525,7 +525,7 @@ function redeemCheque (world, sessionId, command)
525 525 }
526 526 else
527 527 {
528 const release = world.releaseChequeReservation?.(issuerId, chequeId);
528 const release = world.releaseChequeReservation?.(issuerId, chequeId, slot.instance);
529 529 if (!release?.ok)
530 530 {
531 531 inventory.slots[slotIndex] = chequeTaken.taken;
@@ -554,6 +554,29 @@ function redeemCheque (world, sessionId, command)
554 554 return { events: [], private: bagView(world.ecs, handle), bank: true };
555 555 }
556 556
557 /** Match reserved vault entry by chequeId, or by goods identity for legacy rows that lost chequeId. */
558 export function findReservedChequeIndex (reserved, chequeInstance)
559 {
560 const list = reserved ?? [];
561 const chequeId = chequeInstance?.chequeId;
562 if (chequeId != null)
563 {
564 const byId = list.findIndex((entry) => entry?.chequeId === chequeId);
565 if (byId >= 0)
566 { return byId; }
567 }
568 const itemId = chequeInstance?.itemId;
569 const quantity = chequeInstance?.quantity | 0;
570 if (itemId == null || quantity <= 0)
571 { return -1; }
572 return list.findIndex((entry) =>
573 entry
574 && entry.chequeId == null
575 && entry.itemId === itemId
576 && (entry.quantity | 0) === quantity
577 );
578 }
579
557 580 function claimInheritance (world, sessionId, command)
558 581 {
559 582 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -514,7 +514,7 @@ function redeemCheque (world, sessionId, command)
514 let reservedStack = null;
514 let reservedStack = null;
515 if (Number(issuerId) === Number(command.characterId))
515 if (Number(issuerId) === Number(command.characterId))
516 {
516 {
517 const index = (vault.reserved ?? []).findIndex((entry) => entry?.chequeId === chequeId);
517 const index = findReservedChequeIndex(vault.reserved, slot.instance);
518 if (index < 0)
518 if (index < 0)
519 {
519 {
520 inventory.slots[slotIndex] = chequeTaken.taken;
520 inventory.slots[slotIndex] = chequeTaken.taken;
@@ -525,7 +525,7 @@ function redeemCheque (world, sessionId, command)
525 }
525 }
526 else
526 else
527 {
527 {
528 const release = world.releaseChequeReservation?.(issuerId, chequeId);
528 const release = world.releaseChequeReservation?.(issuerId, chequeId, slot.instance);
529 if (!release?.ok)
529 if (!release?.ok)
530 {
530 {
531 inventory.slots[slotIndex] = chequeTaken.taken;
531 inventory.slots[slotIndex] = chequeTaken.taken;
@@ -554,6 +554,29 @@ function redeemCheque (world, sessionId, command)
554 return { events: [], private: bagView(world.ecs, handle), bank: true };
554 return { events: [], private: bagView(world.ecs, handle), bank: true };
555}
555}
556
556
557/** Match reserved vault entry by chequeId, or by goods identity for legacy rows that lost chequeId. */
558export function findReservedChequeIndex (reserved, chequeInstance)
559{
560 const list = reserved ?? [];
561 const chequeId = chequeInstance?.chequeId;
562 if (chequeId != null)
563 {
564 const byId = list.findIndex((entry) => entry?.chequeId === chequeId);
565 if (byId >= 0)
566 { return byId; }
567 }
568 const itemId = chequeInstance?.itemId;
569 const quantity = chequeInstance?.quantity | 0;
570 if (itemId == null || quantity <= 0)
571 { return -1; }
572 return list.findIndex((entry) =>
573 entry
574 && entry.chequeId == null
575 && entry.itemId === itemId
576 && (entry.quantity | 0) === quantity
577 );
578}
579
557function claimInheritance (world, sessionId, command)
580function claimInheritance (world, sessionId, command)
558{
581{
559 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
582 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
server/src/persistence/stateDb.js +25 −3
@@ -27,6 +27,7 @@ CREATE TABLE IF NOT EXISTS characters (
27 27 tile_x INTEGER NOT NULL DEFAULT 8,
28 28 tile_y INTEGER NOT NULL DEFAULT 8,
29 29 gait TEXT NOT NULL DEFAULT 'walk',
30 is_dead INTEGER NOT NULL DEFAULT 0,
30 31 deletion_scheduled_at INTEGER
31 32 );
32 33 CREATE TABLE IF NOT EXISTS friend_requests (
@@ -107,11 +108,14 @@ export class StateDatabase
107 108
108 109 #migrateSchema ()
109 110 {
110 const columns = this.db.prepare("PRAGMA table_info(character_bags)").all();
111 if (!columns.some((column) => column.name === "skills_blob"))
111 const bagColumns = this.db.prepare("PRAGMA table_info(character_bags)").all();
112 if (!bagColumns.some((column) => column.name === "skills_blob"))
112 113 {
113 114 this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
114 115 }
116 const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
117 if (!characterColumns.some((column) => column.name === "is_dead"))
118 { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
115 119 this.#grantLanternsToExistingCharacters();
116 120 }
117 121
@@ -285,6 +289,14 @@ export class StateDatabase
285 289 );
286 290 }
287 291
292 setCharacterDead (characterId, isDead)
293 {
294 this.db.prepare("UPDATE characters SET is_dead = ? WHERE character_id = ?").run(
295 isDead ? 1 : 0,
296 characterId
297 );
298 }
299
288 300 listDueDeletions (now)
289 301 {
290 302 return this.db.prepare(`
@@ -485,7 +497,17 @@ export class StateDatabase
485 497 {
486 498 const row = this.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?").get(characterId);
487 499 if (row)
488 { return normalizePlayerSkills(JSON.parse(row.skills_blob || "{}")); }
500 {
501 const parsed = JSON.parse(row.skills_blob || "{}");
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)
508 { this.saveSkills(characterId, skills); }
509 return skills;
510 }
489 511 if (this.getCharacter(characterId))
490 512 {
491 513 this.#ensureBag(characterId);
@@ -27,6 +27,7 @@ CREATE TABLE IF NOT EXISTS characters (
27 tile_x INTEGER NOT NULL DEFAULT 8,
27 tile_x INTEGER NOT NULL DEFAULT 8,
28 tile_y INTEGER NOT NULL DEFAULT 8,
28 tile_y INTEGER NOT NULL DEFAULT 8,
29 gait TEXT NOT NULL DEFAULT 'walk',
29 gait TEXT NOT NULL DEFAULT 'walk',
30 is_dead INTEGER NOT NULL DEFAULT 0,
30 deletion_scheduled_at INTEGER
31 deletion_scheduled_at INTEGER
31);
32);
32CREATE TABLE IF NOT EXISTS friend_requests (
33CREATE TABLE IF NOT EXISTS friend_requests (
@@ -107,11 +108,14 @@ export class StateDatabase
107
108
108 #migrateSchema ()
109 #migrateSchema ()
109 {
110 {
110 const columns = this.db.prepare("PRAGMA table_info(character_bags)").all();
111 const bagColumns = this.db.prepare("PRAGMA table_info(character_bags)").all();
111 if (!columns.some((column) => column.name === "skills_blob"))
112 if (!bagColumns.some((column) => column.name === "skills_blob"))
112 {
113 {
113 this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
114 this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
114 }
115 }
116 const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
117 if (!characterColumns.some((column) => column.name === "is_dead"))
118 { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
115 this.#grantLanternsToExistingCharacters();
119 this.#grantLanternsToExistingCharacters();
116 }
120 }
117
121
@@ -285,6 +289,14 @@ export class StateDatabase
285 );
289 );
286 }
290 }
287
291
292 setCharacterDead (characterId, isDead)
293 {
294 this.db.prepare("UPDATE characters SET is_dead = ? WHERE character_id = ?").run(
295 isDead ? 1 : 0,
296 characterId
297 );
298 }
299
288 listDueDeletions (now)
300 listDueDeletions (now)
289 {
301 {
290 return this.db.prepare(`
302 return this.db.prepare(`
@@ -485,7 +497,17 @@ export class StateDatabase
485 {
497 {
486 const row = this.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?").get(characterId);
498 const row = this.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?").get(characterId);
487 if (row)
499 if (row)
488 { return normalizePlayerSkills(JSON.parse(row.skills_blob || "{}")); }
500 {
501 const parsed = JSON.parse(row.skills_blob || "{}");
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)
508 { this.saveSkills(characterId, skills); }
509 return skills;
510 }
489 if (this.getCharacter(characterId))
511 if (this.getCharacter(characterId))
490 {
512 {
491 this.#ensureBag(characterId);
513 this.#ensureBag(characterId);
server/src/simulation/protocol.js +7 −1
@@ -26,5 +26,11 @@ export const WorkerMessage = Object.freeze({
26 26 chunkIsSimulating: "chunkIsSimulating",
27 27 setGroundItems: "setGroundItems",
28 28 stepSpawners: "stepSpawners",
29 stepSystems: "stepSystems"
29 stepSystems: "stepSystems",
30 remoteCombatEngage: "remoteCombatEngage",
31 applyRemoteMelee: "applyRemoteMelee",
32 applyCombatHitXp: "applyCombatHitXp",
33 spawnCorpseDrops: "spawnCorpseDrops",
34 applyRespawn: "applyRespawn",
35 clearCombat: "clearCombat"
30 36 });
@@ -26,5 +26,11 @@ export const WorkerMessage = Object.freeze({
26 chunkIsSimulating: "chunkIsSimulating",
26 chunkIsSimulating: "chunkIsSimulating",
27 setGroundItems: "setGroundItems",
27 setGroundItems: "setGroundItems",
28 stepSpawners: "stepSpawners",
28 stepSpawners: "stepSpawners",
29 stepSystems: "stepSystems"
29 stepSystems: "stepSystems",
30 remoteCombatEngage: "remoteCombatEngage",
31 applyRemoteMelee: "applyRemoteMelee",
32 applyCombatHitXp: "applyCombatHitXp",
33 spawnCorpseDrops: "spawnCorpseDrops",
34 applyRespawn: "applyRespawn",
35 clearCombat: "clearCombat"
30});
36});
server/src/simulation/simulation.js +313 −4
@@ -30,8 +30,11 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../
30 30 import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31 31 import { mobComponents } from "./spawners.js";
32 32 import { defaultPlayerSkills } from "../../../shared/skills/state.js";
33 import { playerMaxHealth } from "../../../shared/definitions/skills.js";
33 import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
34 import { BlockType } from "../../../shared/definitions/tiles.js";
35 import { ItemId } from "../../../shared/definitions/items.js";
34 36 import { CourierService } from "../courier/service.js";
37 import { findReservedChequeIndex } from "../items/bags.js";
35 38
36 39 export class Simulation
37 40 {
@@ -52,6 +55,7 @@ export class Simulation
52 55 this.replication = [];
53 56 this.pendingPrivate = [];
54 57 this.courier = null;
58 this.altarTiles = [];
55 59 this.authoredCache = new Map();
56 60 this.nextEntityId = 1;
57 61 this.nextGroundItemId = stateDb.nextGroundItemId();
@@ -85,6 +89,7 @@ export class Simulation
85 89 worldDb: this.worldDb,
86 90 simulation: this
87 91 });
92 this.#refreshAltarIndex();
88 93 }
89 94
90 95 get now ()
@@ -114,6 +119,7 @@ export class Simulation
114 119 }
115 120 this.#syncAllReplicas();
116 121 this.courier?.refreshBankIndex();
122 this.#refreshAltarIndex();
117 123 }
118 124
119 125 enqueue (sessionId, command)
@@ -153,17 +159,28 @@ export class Simulation
153 159
154 160 {
155 161 const transfers = [];
162 const remoteMelee = [];
156 163 for (const worker of this.workers)
157 164 {
158 165 const result = worker.call({ type: WorkerMessage.stepSystems, now });
159 166 for (const event of result?.events ?? [])
160 167 {
168 if (event.type === "remote-melee-resolve")
169 {
170 remoteMelee.push(event);
171 continue;
172 }
161 173 if (event.type === "entity-move")
162 174 { this.#applyMoveToDirectory(event); }
163 175 if (event.type === "entity-despawn")
164 176 { this.#forget(event.entityId); }
165 177 if (event.type === "skills-updated")
166 178 { this.#applySkillsUpdated(event); }
179 if (event.type === "player-died")
180 {
181 events.push(...this.#applyPlayerDeath(event));
182 continue;
183 }
167 184 this.#persistGroundEvent(event);
168 185 if (event.type !== "skills-updated")
169 186 { events.push(event); }
@@ -171,6 +188,8 @@ export class Simulation
171 188 for (const request of result?.transferRequests ?? [])
172 189 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
173 190 }
191 for (const payload of remoteMelee)
192 { events.push(...this.#applyRemoteMelee(payload)); }
174 193 if (transfers.length)
175 194 {
176 195 events.push(...this.#applyTransfers(transfers));
@@ -260,6 +279,8 @@ export class Simulation
260 279 };
261 280 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
262 281 const maxHealth = playerMaxHealth(skills);
282 const maxStamina = playerMaxStamina(skills);
283 const isDead = !!row.is_dead;
263 284 const entityId = this.nextEntityId++;
264 285 const components = {
265 286 position: { tileX, tileY },
@@ -282,10 +303,13 @@ export class Simulation
282 303 slots: bag.vault ?? [],
283 304 reserved: bag.vaultReserved ?? []
284 305 },
285 health: { current: maxHealth, max: maxHealth },
306 health: { current: isDead ? 0 : maxHealth, max: maxHealth },
307 stamina: { current: maxStamina, max: maxStamina },
286 308 combat: { targetEntityId: null, nextSwingAt: 0 },
287 309 skills,
288 310 };
311 if (isDead)
312 { components.dead = {}; }
289 313 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
290 314 const workerId = this.#ownerOfTile(tileX, tileY);
291 315 const view = this.workers[workerId].call({
@@ -668,6 +692,8 @@ export class Simulation
668 692
669 693 #routeCommand (item)
670 694 {
695 if (item.command.type === "respawn")
696 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
671 697 const entityId = this.characterEntities.get(item.command.characterId);
672 698 const record = entityId ? this.directory.get(entityId) : null;
673 699 if (!record)
@@ -678,6 +704,32 @@ export class Simulation
678 704 }
679 705 if (item.command.type === "drop-item" && item.command.groundItemId == null)
680 706 { item.command.groundItemId = this.nextGroundItemId++; }
707 if (item.command.type === "attack")
708 {
709 const targetRecord = this.directory.get(item.command.targetEntityId);
710 if (!targetRecord)
711 {
712 const error = new Error("Target is not here.");
713 error.userFacing = true;
714 throw error;
715 }
716 const events = this.#finishRoutedCommand(item, record);
717 if (targetRecord.workerId !== record.workerId)
718 {
719 this.workers[targetRecord.workerId].call({
720 type: WorkerMessage.remoteCombatEngage,
721 attackerEntityId: record.entityId,
722 targetEntityId: item.command.targetEntityId,
723 now: item.receivedAt ?? this.now
724 });
725 }
726 return events;
727 }
728 return this.#finishRoutedCommand(item, record);
729 }
730
731 #finishRoutedCommand (item, record)
732 {
681 733 const result = this.workers[record.workerId].call({
682 734 type: WorkerMessage.command,
683 735 sessionId: item.sessionId,
@@ -716,6 +768,263 @@ export class Simulation
716 768 return events;
717 769 }
718 770
771 #applyRemoteMelee (payload)
772 {
773 const targetRecord = this.directory.get(payload.targetId);
774 if (!targetRecord)
775 { return []; }
776 const result = this.workers[targetRecord.workerId].call({
777 ...payload,
778 type: WorkerMessage.applyRemoteMelee
779 });
780 const events = [];
781 for (const event of result?.events ?? [])
782 {
783 if (event.type === "entity-despawn")
784 { this.#forget(event.entityId); }
785 if (event.type === "skills-updated")
786 { this.#applySkillsUpdated(event); }
787 if (event.type === "player-died")
788 {
789 events.push(...this.#applyPlayerDeath(event));
790 continue;
791 }
792 this.#persistGroundEvent(event);
793 if (event.type !== "skills-updated")
794 { events.push(event); }
795 }
796 for (const forward of result?.forwards ?? [])
797 {
798 if (forward.type !== "forward-combat-xp")
799 { continue; }
800 const attackerRecord = this.directory.get(forward.entityId);
801 if (!attackerRecord)
802 { continue; }
803 const xpResult = this.workers[attackerRecord.workerId].call({
804 type: WorkerMessage.applyCombatHitXp,
805 entityId: forward.entityId,
806 profile: forward.profile
807 });
808 for (const xpEvent of xpResult?.events ?? [])
809 {
810 if (xpEvent.type === "skills-updated")
811 { this.#applySkillsUpdated(xpEvent); }
812 if (xpEvent.type !== "skills-updated")
813 { events.push(xpEvent); }
814 }
815 }
816 return events;
817 }
818
819 #applyPlayerDeath (event)
820 {
821 const record = this.directory.get(event.entityId);
822 if (!record)
823 { return [event]; }
824 this.stateDb.setCharacterDead(event.characterId, true);
825 this.stateDb.saveCharacterPosition(
826 event.characterId,
827 event.tileX,
828 event.tileY,
829 record.gait ?? GAIT.walk
830 );
831 for (const worker of this.workers)
832 {
833 worker.call({
834 type: WorkerMessage.clearCombat,
835 entityId: event.entityId,
836 targetEntityId: event.entityId
837 });
838 }
839 const result = this.workers[record.workerId].call({
840 type: WorkerMessage.spawnCorpseDrops,
841 characterId: event.characterId,
842 tileX: event.tileX,
843 tileY: event.tileY,
844 now: this.now,
845 drops: [
846 { groundItemId: this.nextGroundItemId++, itemId: ItemId.bones },
847 { groundItemId: this.nextGroundItemId++, itemId: ItemId.skull }
848 ]
849 });
850 const events = [event];
851 for (const dropEvent of result?.events ?? [])
852 {
853 this.#persistGroundEvent(dropEvent);
854 events.push(dropEvent);
855 }
856 return events;
857 }
858
859 #respawnCharacter (sessionId, characterId)
860 {
861 const row = this.stateDb.getCharacter(characterId);
862 if (!row?.is_dead)
863 {
864 const error = new Error("You are not dead.");
865 error.userFacing = true;
866 throw error;
867 }
868 const entityId = this.characterEntities.get(characterId);
869 const record = entityId ? this.directory.get(entityId) : null;
870 if (!record)
871 {
872 const error = new Error("Character is not in the world.");
873 error.userFacing = true;
874 throw error;
875 }
876 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
877 if (!destination)
878 {
879 const error = new Error("No open tile is available for respawn.");
880 error.userFacing = true;
881 throw error;
882 }
883 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
884 const loader = { ...DEFAULT_CHUNK_LOADER };
885 this.#ensureCoverage(destination.tileX, destination.tileY, loader);
886 const result = this.workers[record.workerId].call({
887 type: WorkerMessage.applyRespawn,
888 entityId,
889 sessionId,
890 tileX: destination.tileX,
891 tileY: destination.tileY,
892 maxHealth: playerMaxHealth(skills),
893 maxStamina: playerMaxStamina(skills)
894 });
895 if (!result?.accepted)
896 {
897 const error = new Error("That respawn tile is no longer available.");
898 error.userFacing = true;
899 throw error;
900 }
901 let moveEvents = [];
902 if (result.transferRequest)
903 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
904 else if (result.event)
905 {
906 this.#applyMoveToDirectory(result.event);
907 moveEvents = [result.event];
908 const view = this.workers[record.workerId].call({
909 type: WorkerMessage.inspect,
910 entityId
911 });
912 if (view)
913 { this.#remember(view, record.workerId); }
914 }
915 if (!moveEvents.length)
916 {
917 const error = new Error("Respawn transfer failed.");
918 error.userFacing = true;
919 throw error;
920 }
921 this.stateDb.setCharacterDead(characterId, false);
922 this.stateDb.saveCharacterPosition(
923 characterId,
924 destination.tileX,
925 destination.tileY,
926 record.gait ?? GAIT.walk
927 );
928 this.#recalculateActivation(this.now);
929 this.#syncGhosts();
930 return [
931 ...moveEvents,
932 {
933 type: "player-respawned",
934 entityId,
935 characterId,
936 sessionId,
937 tileX: destination.tileX,
938 tileY: destination.tileY,
939 health: playerMaxHealth(skills),
940 maxHealth: playerMaxHealth(skills),
941 stamina: playerMaxStamina(skills),
942 maxStamina: playerMaxStamina(skills)
943 }
944 ];
945 }
946
947 #refreshAltarIndex ()
948 {
949 const altars = [];
950 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
951 {
952 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
953 for (let localY = 0; localY < CHUNK_SIZE; localY++)
954 {
955 for (let localX = 0; localX < CHUNK_SIZE; localX++)
956 {
957 const block = data.blocks[localY * CHUNK_SIZE + localX];
958 if (block?.typeId !== BlockType.churchAltar)
959 { continue; }
960 altars.push({
961 tileX: coord.chunk_x * CHUNK_SIZE + localX,
962 tileY: coord.chunk_y * CHUNK_SIZE + localY
963 });
964 }
965 }
966 }
967 this.altarTiles = altars;
968 }
969
970 #findRespawnDestination (originX, originY, entityId)
971 {
972 const ordered = [...this.altarTiles].sort((left, right) =>
973 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
974 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
975 );
976 for (const altar of ordered)
977 {
978 const adjacent = [];
979 for (let dy = -1; dy <= 1; dy++)
980 {
981 for (let dx = -1; dx <= 1; dx++)
982 {
983 if (dx === 0 && dy === 0)
984 { continue; }
985 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy });
986 }
987 }
988 adjacent.sort((left, right) =>
989 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
990 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
991 );
992 const tile = adjacent.find((entry) =>
993 this.isEnterable(entry.tileX, entry.tileY)
994 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId)
995 );
996 if (tile)
997 { return tile; }
998 }
999 for (let radius = 0; radius <= 24; radius++)
1000 {
1001 for (let dy = -radius; dy <= radius; dy++)
1002 {
1003 for (let dx = -radius; dx <= radius; dx++)
1004 {
1005 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1006 { continue; }
1007 const tileX = originX + dx;
1008 const tileY = originY + dy;
1009 if (this.isEnterable(tileX, tileY)
1010 && !this.#occupiedByOther(tileX, tileY, entityId))
1011 { return { tileX, tileY }; }
1012 }
1013 }
1014 }
1015 return this.findOpenSpawn();
1016 }
1017
1018 #occupiedByOther (tileX, tileY, entityId)
1019 {
1020 for (const record of this.directory.values())
1021 {
1022 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY)
1023 { return true; }
1024 }
1025 return false;
1026 }
1027
719 1028 #recalculateActivation (now)
720 1029 {
721 1030 const loaders = this.#allLoaders();
@@ -1187,14 +1496,14 @@ export class Simulation
1187 1496 });
1188 1497 }
1189 1498
1190 releaseChequeReservation (issuerCharacterId, chequeId)
1499 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
1191 1500 {
1192 1501 const onlineId = this.characterEntities.get(issuerCharacterId);
1193 1502 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1194 1503 if (!bag)
1195 1504 { return { ok: false, error: "Issuer vault not found." }; }
1196 1505 const reserved = [...(bag.vaultReserved ?? [])];
1197 const index = reserved.findIndex((entry) => entry?.chequeId === chequeId);
1506 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
1198 1507 if (index < 0)
1199 1508 { return { ok: false, error: "That cheque cannot be redeemed." }; }
1200 1509 const [stack] = reserved.splice(index, 1);
@@ -30,8 +30,11 @@ import { replicationAppearance, replicationDespawn, replicationSpawn } from "../
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 } from "../../../shared/skills/state.js";
33import { playerMaxHealth } from "../../../shared/definitions/skills.js";
33import { playerMaxHealth, playerMaxStamina } from "../../../shared/definitions/skills.js";
34import { BlockType } from "../../../shared/definitions/tiles.js";
35import { ItemId } from "../../../shared/definitions/items.js";
34import { CourierService } from "../courier/service.js";
36import { CourierService } from "../courier/service.js";
37import { findReservedChequeIndex } from "../items/bags.js";
35
38
36export class Simulation
39export class Simulation
37{
40{
@@ -52,6 +55,7 @@ export class Simulation
52 this.replication = [];
55 this.replication = [];
53 this.pendingPrivate = [];
56 this.pendingPrivate = [];
54 this.courier = null;
57 this.courier = null;
58 this.altarTiles = [];
55 this.authoredCache = new Map();
59 this.authoredCache = new Map();
56 this.nextEntityId = 1;
60 this.nextEntityId = 1;
57 this.nextGroundItemId = stateDb.nextGroundItemId();
61 this.nextGroundItemId = stateDb.nextGroundItemId();
@@ -85,6 +89,7 @@ export class Simulation
85 worldDb: this.worldDb,
89 worldDb: this.worldDb,
86 simulation: this
90 simulation: this
87 });
91 });
92 this.#refreshAltarIndex();
88 }
93 }
89
94
90 get now ()
95 get now ()
@@ -114,6 +119,7 @@ export class Simulation
114 }
119 }
115 this.#syncAllReplicas();
120 this.#syncAllReplicas();
116 this.courier?.refreshBankIndex();
121 this.courier?.refreshBankIndex();
122 this.#refreshAltarIndex();
117 }
123 }
118
124
119 enqueue (sessionId, command)
125 enqueue (sessionId, command)
@@ -153,17 +159,28 @@ export class Simulation
153
159
154 {
160 {
155 const transfers = [];
161 const transfers = [];
162 const remoteMelee = [];
156 for (const worker of this.workers)
163 for (const worker of this.workers)
157 {
164 {
158 const result = worker.call({ type: WorkerMessage.stepSystems, now });
165 const result = worker.call({ type: WorkerMessage.stepSystems, now });
159 for (const event of result?.events ?? [])
166 for (const event of result?.events ?? [])
160 {
167 {
168 if (event.type === "remote-melee-resolve")
169 {
170 remoteMelee.push(event);
171 continue;
172 }
161 if (event.type === "entity-move")
173 if (event.type === "entity-move")
162 { this.#applyMoveToDirectory(event); }
174 { this.#applyMoveToDirectory(event); }
163 if (event.type === "entity-despawn")
175 if (event.type === "entity-despawn")
164 { this.#forget(event.entityId); }
176 { this.#forget(event.entityId); }
165 if (event.type === "skills-updated")
177 if (event.type === "skills-updated")
166 { this.#applySkillsUpdated(event); }
178 { this.#applySkillsUpdated(event); }
179 if (event.type === "player-died")
180 {
181 events.push(...this.#applyPlayerDeath(event));
182 continue;
183 }
167 this.#persistGroundEvent(event);
184 this.#persistGroundEvent(event);
168 if (event.type !== "skills-updated")
185 if (event.type !== "skills-updated")
169 { events.push(event); }
186 { events.push(event); }
@@ -171,6 +188,8 @@ export class Simulation
171 for (const request of result?.transferRequests ?? [])
188 for (const request of result?.transferRequests ?? [])
172 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
189 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
173 }
190 }
191 for (const payload of remoteMelee)
192 { events.push(...this.#applyRemoteMelee(payload)); }
174 if (transfers.length)
193 if (transfers.length)
175 {
194 {
176 events.push(...this.#applyTransfers(transfers));
195 events.push(...this.#applyTransfers(transfers));
@@ -260,6 +279,8 @@ export class Simulation
260 };
279 };
261 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
280 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
262 const maxHealth = playerMaxHealth(skills);
281 const maxHealth = playerMaxHealth(skills);
282 const maxStamina = playerMaxStamina(skills);
283 const isDead = !!row.is_dead;
263 const entityId = this.nextEntityId++;
284 const entityId = this.nextEntityId++;
264 const components = {
285 const components = {
265 position: { tileX, tileY },
286 position: { tileX, tileY },
@@ -282,10 +303,13 @@ export class Simulation
282 slots: bag.vault ?? [],
303 slots: bag.vault ?? [],
283 reserved: bag.vaultReserved ?? []
304 reserved: bag.vaultReserved ?? []
284 },
305 },
285 health: { current: maxHealth, max: maxHealth },
306 health: { current: isDead ? 0 : maxHealth, max: maxHealth },
307 stamina: { current: maxStamina, max: maxStamina },
286 combat: { targetEntityId: null, nextSwingAt: 0 },
308 combat: { targetEntityId: null, nextSwingAt: 0 },
287 skills,
309 skills,
288 };
310 };
311 if (isDead)
312 { components.dead = {}; }
289 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
313 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
290 const workerId = this.#ownerOfTile(tileX, tileY);
314 const workerId = this.#ownerOfTile(tileX, tileY);
291 const view = this.workers[workerId].call({
315 const view = this.workers[workerId].call({
@@ -668,6 +692,8 @@ export class Simulation
668
692
669 #routeCommand (item)
693 #routeCommand (item)
670 {
694 {
695 if (item.command.type === "respawn")
696 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
671 const entityId = this.characterEntities.get(item.command.characterId);
697 const entityId = this.characterEntities.get(item.command.characterId);
672 const record = entityId ? this.directory.get(entityId) : null;
698 const record = entityId ? this.directory.get(entityId) : null;
673 if (!record)
699 if (!record)
@@ -678,6 +704,32 @@ export class Simulation
678 }
704 }
679 if (item.command.type === "drop-item" && item.command.groundItemId == null)
705 if (item.command.type === "drop-item" && item.command.groundItemId == null)
680 { item.command.groundItemId = this.nextGroundItemId++; }
706 { item.command.groundItemId = this.nextGroundItemId++; }
707 if (item.command.type === "attack")
708 {
709 const targetRecord = this.directory.get(item.command.targetEntityId);
710 if (!targetRecord)
711 {
712 const error = new Error("Target is not here.");
713 error.userFacing = true;
714 throw error;
715 }
716 const events = this.#finishRoutedCommand(item, record);
717 if (targetRecord.workerId !== record.workerId)
718 {
719 this.workers[targetRecord.workerId].call({
720 type: WorkerMessage.remoteCombatEngage,
721 attackerEntityId: record.entityId,
722 targetEntityId: item.command.targetEntityId,
723 now: item.receivedAt ?? this.now
724 });
725 }
726 return events;
727 }
728 return this.#finishRoutedCommand(item, record);
729 }
730
731 #finishRoutedCommand (item, record)
732 {
681 const result = this.workers[record.workerId].call({
733 const result = this.workers[record.workerId].call({
682 type: WorkerMessage.command,
734 type: WorkerMessage.command,
683 sessionId: item.sessionId,
735 sessionId: item.sessionId,
@@ -716,6 +768,263 @@ export class Simulation
716 return events;
768 return events;
717 }
769 }
718
770
771 #applyRemoteMelee (payload)
772 {
773 const targetRecord = this.directory.get(payload.targetId);
774 if (!targetRecord)
775 { return []; }
776 const result = this.workers[targetRecord.workerId].call({
777 ...payload,
778 type: WorkerMessage.applyRemoteMelee
779 });
780 const events = [];
781 for (const event of result?.events ?? [])
782 {
783 if (event.type === "entity-despawn")
784 { this.#forget(event.entityId); }
785 if (event.type === "skills-updated")
786 { this.#applySkillsUpdated(event); }
787 if (event.type === "player-died")
788 {
789 events.push(...this.#applyPlayerDeath(event));
790 continue;
791 }
792 this.#persistGroundEvent(event);
793 if (event.type !== "skills-updated")
794 { events.push(event); }
795 }
796 for (const forward of result?.forwards ?? [])
797 {
798 if (forward.type !== "forward-combat-xp")
799 { continue; }
800 const attackerRecord = this.directory.get(forward.entityId);
801 if (!attackerRecord)
802 { continue; }
803 const xpResult = this.workers[attackerRecord.workerId].call({
804 type: WorkerMessage.applyCombatHitXp,
805 entityId: forward.entityId,
806 profile: forward.profile
807 });
808 for (const xpEvent of xpResult?.events ?? [])
809 {
810 if (xpEvent.type === "skills-updated")
811 { this.#applySkillsUpdated(xpEvent); }
812 if (xpEvent.type !== "skills-updated")
813 { events.push(xpEvent); }
814 }
815 }
816 return events;
817 }
818
819 #applyPlayerDeath (event)
820 {
821 const record = this.directory.get(event.entityId);
822 if (!record)
823 { return [event]; }
824 this.stateDb.setCharacterDead(event.characterId, true);
825 this.stateDb.saveCharacterPosition(
826 event.characterId,
827 event.tileX,
828 event.tileY,
829 record.gait ?? GAIT.walk
830 );
831 for (const worker of this.workers)
832 {
833 worker.call({
834 type: WorkerMessage.clearCombat,
835 entityId: event.entityId,
836 targetEntityId: event.entityId
837 });
838 }
839 const result = this.workers[record.workerId].call({
840 type: WorkerMessage.spawnCorpseDrops,
841 characterId: event.characterId,
842 tileX: event.tileX,
843 tileY: event.tileY,
844 now: this.now,
845 drops: [
846 { groundItemId: this.nextGroundItemId++, itemId: ItemId.bones },
847 { groundItemId: this.nextGroundItemId++, itemId: ItemId.skull }
848 ]
849 });
850 const events = [event];
851 for (const dropEvent of result?.events ?? [])
852 {
853 this.#persistGroundEvent(dropEvent);
854 events.push(dropEvent);
855 }
856 return events;
857 }
858
859 #respawnCharacter (sessionId, characterId)
860 {
861 const row = this.stateDb.getCharacter(characterId);
862 if (!row?.is_dead)
863 {
864 const error = new Error("You are not dead.");
865 error.userFacing = true;
866 throw error;
867 }
868 const entityId = this.characterEntities.get(characterId);
869 const record = entityId ? this.directory.get(entityId) : null;
870 if (!record)
871 {
872 const error = new Error("Character is not in the world.");
873 error.userFacing = true;
874 throw error;
875 }
876 const destination = this.#findRespawnDestination(record.tileX, record.tileY, entityId);
877 if (!destination)
878 {
879 const error = new Error("No open tile is available for respawn.");
880 error.userFacing = true;
881 throw error;
882 }
883 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
884 const loader = { ...DEFAULT_CHUNK_LOADER };
885 this.#ensureCoverage(destination.tileX, destination.tileY, loader);
886 const result = this.workers[record.workerId].call({
887 type: WorkerMessage.applyRespawn,
888 entityId,
889 sessionId,
890 tileX: destination.tileX,
891 tileY: destination.tileY,
892 maxHealth: playerMaxHealth(skills),
893 maxStamina: playerMaxStamina(skills)
894 });
895 if (!result?.accepted)
896 {
897 const error = new Error("That respawn tile is no longer available.");
898 error.userFacing = true;
899 throw error;
900 }
901 let moveEvents = [];
902 if (result.transferRequest)
903 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
904 else if (result.event)
905 {
906 this.#applyMoveToDirectory(result.event);
907 moveEvents = [result.event];
908 const view = this.workers[record.workerId].call({
909 type: WorkerMessage.inspect,
910 entityId
911 });
912 if (view)
913 { this.#remember(view, record.workerId); }
914 }
915 if (!moveEvents.length)
916 {
917 const error = new Error("Respawn transfer failed.");
918 error.userFacing = true;
919 throw error;
920 }
921 this.stateDb.setCharacterDead(characterId, false);
922 this.stateDb.saveCharacterPosition(
923 characterId,
924 destination.tileX,
925 destination.tileY,
926 record.gait ?? GAIT.walk
927 );
928 this.#recalculateActivation(this.now);
929 this.#syncGhosts();
930 return [
931 ...moveEvents,
932 {
933 type: "player-respawned",
934 entityId,
935 characterId,
936 sessionId,
937 tileX: destination.tileX,
938 tileY: destination.tileY,
939 health: playerMaxHealth(skills),
940 maxHealth: playerMaxHealth(skills),
941 stamina: playerMaxStamina(skills),
942 maxStamina: playerMaxStamina(skills)
943 }
944 ];
945 }
946
947 #refreshAltarIndex ()
948 {
949 const altars = [];
950 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
951 {
952 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
953 for (let localY = 0; localY < CHUNK_SIZE; localY++)
954 {
955 for (let localX = 0; localX < CHUNK_SIZE; localX++)
956 {
957 const block = data.blocks[localY * CHUNK_SIZE + localX];
958 if (block?.typeId !== BlockType.churchAltar)
959 { continue; }
960 altars.push({
961 tileX: coord.chunk_x * CHUNK_SIZE + localX,
962 tileY: coord.chunk_y * CHUNK_SIZE + localY
963 });
964 }
965 }
966 }
967 this.altarTiles = altars;
968 }
969
970 #findRespawnDestination (originX, originY, entityId)
971 {
972 const ordered = [...this.altarTiles].sort((left, right) =>
973 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
974 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
975 );
976 for (const altar of ordered)
977 {
978 const adjacent = [];
979 for (let dy = -1; dy <= 1; dy++)
980 {
981 for (let dx = -1; dx <= 1; dx++)
982 {
983 if (dx === 0 && dy === 0)
984 { continue; }
985 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy });
986 }
987 }
988 adjacent.sort((left, right) =>
989 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
990 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
991 );
992 const tile = adjacent.find((entry) =>
993 this.isEnterable(entry.tileX, entry.tileY)
994 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId)
995 );
996 if (tile)
997 { return tile; }
998 }
999 for (let radius = 0; radius <= 24; radius++)
1000 {
1001 for (let dy = -radius; dy <= radius; dy++)
1002 {
1003 for (let dx = -radius; dx <= radius; dx++)
1004 {
1005 if (radius > 0 && Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
1006 { continue; }
1007 const tileX = originX + dx;
1008 const tileY = originY + dy;
1009 if (this.isEnterable(tileX, tileY)
1010 && !this.#occupiedByOther(tileX, tileY, entityId))
1011 { return { tileX, tileY }; }
1012 }
1013 }
1014 }
1015 return this.findOpenSpawn();
1016 }
1017
1018 #occupiedByOther (tileX, tileY, entityId)
1019 {
1020 for (const record of this.directory.values())
1021 {
1022 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY)
1023 { return true; }
1024 }
1025 return false;
1026 }
1027
719 #recalculateActivation (now)
1028 #recalculateActivation (now)
720 {
1029 {
721 const loaders = this.#allLoaders();
1030 const loaders = this.#allLoaders();
@@ -1187,14 +1496,14 @@ export class Simulation
1187 });
1496 });
1188 }
1497 }
1189
1498
1190 releaseChequeReservation (issuerCharacterId, chequeId)
1499 releaseChequeReservation (issuerCharacterId, chequeId, chequeInstance = null)
1191 {
1500 {
1192 const onlineId = this.characterEntities.get(issuerCharacterId);
1501 const onlineId = this.characterEntities.get(issuerCharacterId);
1193 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1502 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1194 if (!bag)
1503 if (!bag)
1195 { return { ok: false, error: "Issuer vault not found." }; }
1504 { return { ok: false, error: "Issuer vault not found." }; }
1196 const reserved = [...(bag.vaultReserved ?? [])];
1505 const reserved = [...(bag.vaultReserved ?? [])];
1197 const index = reserved.findIndex((entry) => entry?.chequeId === chequeId);
1506 const index = findReservedChequeIndex(reserved, chequeInstance ?? { chequeId });
1198 if (index < 0)
1507 if (index < 0)
1199 { return { ok: false, error: "That cheque cannot be redeemed." }; }
1508 { return { ok: false, error: "That cheque cannot be redeemed." }; }
1200 const [stack] = reserved.splice(index, 1);
1509 const [stack] = reserved.splice(index, 1);
server/src/simulation/workerWorld.js +191 −13
@@ -21,20 +21,25 @@ import { mobDefinition } from "../../../shared/definitions/mobs.js";
21 21 import {
22 22 bagView,
23 23 applyBagView,
24 addGroundItem,
24 25 expireGroundItems,
25 26 groundItemsInChunk,
26 27 groundItemsInRegion,
27 28 handleItemCommand,
28 29 removeGroundItem,
30 publicGroundItem,
29 31 setGroundItemsForRegion
30 32 } from "../items/bags.js";
31 33 import {
34 applyRemoteMeleeSwing,
32 35 clearEngage,
33 36 engageTarget,
34 37 ensureMobCombat,
35 38 isUntargetable,
39 resolveCombatTarget,
36 40 stepCombat
37 41 } from "../combat/service.js";
42 import { awardCombatHitXp } from "../skills/service.js";
38 43 import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
39 44 import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
40 45
@@ -118,6 +123,24 @@ export class WorkerWorld
118 123 return this.#entitiesInRegion(message.regionX, message.regionY);
119 124 case WorkerMessage.inspect:
120 125 return publicEntityView(this.ecs, message.entityId);
126 case WorkerMessage.remoteCombatEngage:
127 return this.#remoteCombatEngage(message);
128 case WorkerMessage.applyRemoteMelee:
129 return this.#applyRemoteMelee(message);
130 case WorkerMessage.applyCombatHitXp:
131 return this.#applyCombatHitXp(message);
132 case WorkerMessage.spawnCorpseDrops:
133 return this.#spawnCorpseDrops(message);
134 case WorkerMessage.applyRespawn:
135 return this.#applyRespawn(message);
136 case WorkerMessage.clearCombat:
137 clearEngage(this.ecs, message.entityId);
138 for (const entity of this.ecs.query(Component.combat))
139 {
140 if (entity.combat.targetEntityId === message.targetEntityId)
141 { entity.combat.targetEntityId = null; }
142 }
143 return { ok: true };
121 144 default:
122 145 throw new Error(`Unknown worker message ${message.type}`);
123 146 }
@@ -350,6 +373,105 @@ export class WorkerWorld
350 373 }
351 374 }
352 375
376 #spawnCorpseDrops (message)
377 {
378 const events = [];
379 for (const drop of message.drops ?? [])
380 {
381 const item = {
382 groundItemId: drop.groundItemId,
383 tileX: message.tileX,
384 tileY: message.tileY,
385 stack: { itemId: drop.itemId, quantity: 1 },
386 droppedAt: message.now,
387 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
388 source: "player-death",
389 droppedByCharacterId: message.characterId
390 };
391 addGroundItem(this, item);
392 events.push({
393 type: "ground-item-appear",
394 ...publicGroundItem(item),
395 stack: item.stack,
396 droppedAt: item.droppedAt,
397 source: item.source,
398 droppedByCharacterId: item.droppedByCharacterId,
399 expiresAt: item.expiresAt
400 });
401 }
402 return { events };
403 }
404
405 #applyRespawn (message)
406 {
407 const handle = this.ecs.handleOf(message.entityId);
408 if (handle == null || !this.ecs.has(handle, Component.dead))
409 { return { accepted: false }; }
410 const position = this.ecs.get(handle, Component.position);
411 const fromTileX = position.tileX;
412 const fromTileY = position.tileY;
413 const health = this.ecs.get(handle, Component.health);
414 const stamina = this.ecs.get(handle, Component.stamina);
415 if (health)
416 {
417 health.max = message.maxHealth;
418 health.current = message.maxHealth;
419 }
420 if (stamina)
421 {
422 stamina.max = message.maxStamina;
423 stamina.current = message.maxStamina;
424 }
425 else
426 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
427 this.ecs.remove(handle, Component.dead);
428 clearEngage(this.ecs, message.entityId);
429 const path = this.ecs.get(handle, Component.path);
430 if (path)
431 { path.tiles = []; }
432 clearFollow(this.ecs, message.entityId);
433
434 const destRegionX = tileToRegion(message.tileX);
435 const destRegionY = tileToRegion(message.tileY);
436 if (!this.ownsRegion(destRegionX, destRegionY))
437 {
438 this.frozen.add(message.entityId);
439 return {
440 accepted: true,
441 transferRequest: {
442 entityId: message.entityId,
443 fromTileX,
444 fromTileY,
445 destTileX: message.tileX,
446 destTileY: message.tileY,
447 toRegionX: destRegionX,
448 toRegionY: destRegionY,
449 payload: serializeEntity(this.ecs, message.entityId)
450 }
451 };
452 }
453 const occupant = this.#occupied(message.tileX, message.tileY);
454 if (!this.isEnterable(message.tileX, message.tileY)
455 || (occupant && occupant !== message.entityId))
456 { return { accepted: false }; }
457 this.#vacate(message.entityId, fromTileX, fromTileY);
458 position.tileX = message.tileX;
459 position.tileY = message.tileY;
460 this.#occupy(message.entityId, position.tileX, position.tileY);
461 return {
462 accepted: true,
463 event: {
464 type: "entity-move",
465 entityId: message.entityId,
466 fromTileX,
467 fromTileY,
468 tileX: position.tileX,
469 tileY: position.tileY,
470 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
471 }
472 };
473 }
474
353 475 #inspectBag (entityId)
354 476 {
355 477 const handle = this.ecs.handleOf(entityId);
@@ -463,27 +585,20 @@ export class WorkerWorld
463 585 #attack (sessionId, characterId, targetEntityId, now)
464 586 {
465 587 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
466 const targetHandle = this.ecs.handleOf(targetEntityId);
467 if (targetHandle == null)
468 {
469 const error = new Error("Target is not here.");
470 error.userFacing = true;
471 throw error;
472 }
473 588 if (targetEntityId === entityId)
474 589 {
475 590 const error = new Error("Cannot attack yourself.");
476 591 error.userFacing = true;
477 592 throw error;
478 593 }
479 if (isUntargetable(this.ecs, targetHandle))
594 const target = resolveCombatTarget(this, targetEntityId);
595 if (!target)
480 596 {
481 const error = new Error("That cannot be attacked.");
597 const error = new Error("Target is not here.");
482 598 error.userFacing = true;
483 599 throw error;
484 600 }
485 const health = this.ecs.get(targetHandle, Component.health);
486 if (!health)
601 if (target.health && target.health.current <= 0)
487 602 {
488 603 const error = new Error("That cannot be attacked.");
489 604 error.userFacing = true;
@@ -493,14 +608,69 @@ export class WorkerWorld
493 608 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
494 609 clearFollow(this.ecs, entityId);
495 610 engageTarget(this.ecs, entityId, targetEntityId, now);
496 if (ensureMobCombat(this.ecs, targetEntityId))
497 { engageTarget(this.ecs, targetEntityId, entityId, now); }
611 if (target.local)
612 {
613 if (ensureMobCombat(this.ecs, targetEntityId))
614 { engageTarget(this.ecs, targetEntityId, entityId, now); }
615 const targetPath = this.ecs.get(target.handle, Component.path);
616 if (targetPath)
617 { targetPath.tiles = []; }
618 }
498 619 const path = this.ecs.get(handle, Component.path);
499 620 if (path)
500 621 { path.tiles = []; }
501 622 return { events: [] };
502 623 }
503 624
625 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
626 {
627 const targetHandle = this.ecs.handleOf(targetEntityId);
628 if (targetHandle == null)
629 { return { events: [] }; }
630 if (ensureMobCombat(this.ecs, targetEntityId))
631 {
632 engageTarget(this.ecs, targetEntityId, attackerEntityId, now);
633 const targetPath = this.ecs.get(targetHandle, Component.path);
634 if (targetPath)
635 { targetPath.tiles = []; }
636 }
637 else if (this.ecs.get(targetHandle, Component.character))
638 {
639 engageTarget(this.ecs, targetEntityId, attackerEntityId, now);
640 const targetPath = this.ecs.get(targetHandle, Component.path);
641 if (targetPath)
642 { targetPath.tiles = []; }
643 }
644 return { events: [] };
645 }
646
647 #applyRemoteMelee (payload)
648 {
649 return applyRemoteMeleeSwing(this, payload);
650 }
651
652 #applyCombatHitXp ({ entityId, profile })
653 {
654 const handle = this.ecs.handleOf(entityId);
655 if (handle == null)
656 { return { events: [] }; }
657 const character = this.ecs.get(handle, Component.character);
658 if (!character)
659 { return { events: [] }; }
660 const xpAward = awardCombatHitXp(this.ecs, handle, profile);
661 if (!xpAward)
662 { return { events: [] }; }
663 return {
664 events: [{
665 type: "skills-updated",
666 entityId,
667 characterId: character.characterId,
668 skills: xpAward.view,
669 stored: xpAward.stored
670 }]
671 };
672 }
673
504 674 #cancelAttack (sessionId, characterId)
505 675 {
506 676 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
@@ -601,6 +771,12 @@ export class WorkerWorld
601 771 error.userFacing = true;
602 772 throw error;
603 773 }
774 if (this.ecs.has(handle, Component.dead))
775 {
776 const error = new Error("You are dead.");
777 error.userFacing = true;
778 throw error;
779 }
604 780 return { handle, entityId };
605 781 }
606 782
@@ -641,6 +817,8 @@ export class WorkerWorld
641 817 for (const entity of this.ecs.query(Component.position, Component.movement))
642 818 {
643 819 const { handle, entityId, position, movement } = entity;
820 if (this.ecs.has(handle, Component.dead))
821 { continue; }
644 822 if (this.ecs.has(handle, Component.flight))
645 823 { continue; }
646 824 const path = this.ecs.get(handle, Component.path);
@@ -21,20 +21,25 @@ import { mobDefinition } from "../../../shared/definitions/mobs.js";
21import {
21import {
22 bagView,
22 bagView,
23 applyBagView,
23 applyBagView,
24 addGroundItem,
24 expireGroundItems,
25 expireGroundItems,
25 groundItemsInChunk,
26 groundItemsInChunk,
26 groundItemsInRegion,
27 groundItemsInRegion,
27 handleItemCommand,
28 handleItemCommand,
28 removeGroundItem,
29 removeGroundItem,
30 publicGroundItem,
29 setGroundItemsForRegion
31 setGroundItemsForRegion
30} from "../items/bags.js";
32} from "../items/bags.js";
31import {
33import {
34 applyRemoteMeleeSwing,
32 clearEngage,
35 clearEngage,
33 engageTarget,
36 engageTarget,
34 ensureMobCombat,
37 ensureMobCombat,
35 isUntargetable,
38 isUntargetable,
39 resolveCombatTarget,
36 stepCombat
40 stepCombat
37} from "../combat/service.js";
41} from "../combat/service.js";
42import { awardCombatHitXp } from "../skills/service.js";
38import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
43import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
39import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
44import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
40
45
@@ -118,6 +123,24 @@ export class WorkerWorld
118 return this.#entitiesInRegion(message.regionX, message.regionY);
123 return this.#entitiesInRegion(message.regionX, message.regionY);
119 case WorkerMessage.inspect:
124 case WorkerMessage.inspect:
120 return publicEntityView(this.ecs, message.entityId);
125 return publicEntityView(this.ecs, message.entityId);
126 case WorkerMessage.remoteCombatEngage:
127 return this.#remoteCombatEngage(message);
128 case WorkerMessage.applyRemoteMelee:
129 return this.#applyRemoteMelee(message);
130 case WorkerMessage.applyCombatHitXp:
131 return this.#applyCombatHitXp(message);
132 case WorkerMessage.spawnCorpseDrops:
133 return this.#spawnCorpseDrops(message);
134 case WorkerMessage.applyRespawn:
135 return this.#applyRespawn(message);
136 case WorkerMessage.clearCombat:
137 clearEngage(this.ecs, message.entityId);
138 for (const entity of this.ecs.query(Component.combat))
139 {
140 if (entity.combat.targetEntityId === message.targetEntityId)
141 { entity.combat.targetEntityId = null; }
142 }
143 return { ok: true };
121 default:
144 default:
122 throw new Error(`Unknown worker message ${message.type}`);
145 throw new Error(`Unknown worker message ${message.type}`);
123 }
146 }
@@ -350,6 +373,105 @@ export class WorkerWorld
350 }
373 }
351 }
374 }
352
375
376 #spawnCorpseDrops (message)
377 {
378 const events = [];
379 for (const drop of message.drops ?? [])
380 {
381 const item = {
382 groundItemId: drop.groundItemId,
383 tileX: message.tileX,
384 tileY: message.tileY,
385 stack: { itemId: drop.itemId, quantity: 1 },
386 droppedAt: message.now,
387 expiresAt: message.now + (this.settings.groundItemDespawnDurationMs ?? 600_000),
388 source: "player-death",
389 droppedByCharacterId: message.characterId
390 };
391 addGroundItem(this, item);
392 events.push({
393 type: "ground-item-appear",
394 ...publicGroundItem(item),
395 stack: item.stack,
396 droppedAt: item.droppedAt,
397 source: item.source,
398 droppedByCharacterId: item.droppedByCharacterId,
399 expiresAt: item.expiresAt
400 });
401 }
402 return { events };
403 }
404
405 #applyRespawn (message)
406 {
407 const handle = this.ecs.handleOf(message.entityId);
408 if (handle == null || !this.ecs.has(handle, Component.dead))
409 { return { accepted: false }; }
410 const position = this.ecs.get(handle, Component.position);
411 const fromTileX = position.tileX;
412 const fromTileY = position.tileY;
413 const health = this.ecs.get(handle, Component.health);
414 const stamina = this.ecs.get(handle, Component.stamina);
415 if (health)
416 {
417 health.max = message.maxHealth;
418 health.current = message.maxHealth;
419 }
420 if (stamina)
421 {
422 stamina.max = message.maxStamina;
423 stamina.current = message.maxStamina;
424 }
425 else
426 { this.ecs.add(handle, Component.stamina, { current: message.maxStamina, max: message.maxStamina }); }
427 this.ecs.remove(handle, Component.dead);
428 clearEngage(this.ecs, message.entityId);
429 const path = this.ecs.get(handle, Component.path);
430 if (path)
431 { path.tiles = []; }
432 clearFollow(this.ecs, message.entityId);
433
434 const destRegionX = tileToRegion(message.tileX);
435 const destRegionY = tileToRegion(message.tileY);
436 if (!this.ownsRegion(destRegionX, destRegionY))
437 {
438 this.frozen.add(message.entityId);
439 return {
440 accepted: true,
441 transferRequest: {
442 entityId: message.entityId,
443 fromTileX,
444 fromTileY,
445 destTileX: message.tileX,
446 destTileY: message.tileY,
447 toRegionX: destRegionX,
448 toRegionY: destRegionY,
449 payload: serializeEntity(this.ecs, message.entityId)
450 }
451 };
452 }
453 const occupant = this.#occupied(message.tileX, message.tileY);
454 if (!this.isEnterable(message.tileX, message.tileY)
455 || (occupant && occupant !== message.entityId))
456 { return { accepted: false }; }
457 this.#vacate(message.entityId, fromTileX, fromTileY);
458 position.tileX = message.tileX;
459 position.tileY = message.tileY;
460 this.#occupy(message.entityId, position.tileX, position.tileY);
461 return {
462 accepted: true,
463 event: {
464 type: "entity-move",
465 entityId: message.entityId,
466 fromTileX,
467 fromTileY,
468 tileX: position.tileX,
469 tileY: position.tileY,
470 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
471 }
472 };
473 }
474
353 #inspectBag (entityId)
475 #inspectBag (entityId)
354 {
476 {
355 const handle = this.ecs.handleOf(entityId);
477 const handle = this.ecs.handleOf(entityId);
@@ -463,27 +585,20 @@ export class WorkerWorld
463 #attack (sessionId, characterId, targetEntityId, now)
585 #attack (sessionId, characterId, targetEntityId, now)
464 {
586 {
465 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
587 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
466 const targetHandle = this.ecs.handleOf(targetEntityId);
467 if (targetHandle == null)
468 {
469 const error = new Error("Target is not here.");
470 error.userFacing = true;
471 throw error;
472 }
473 if (targetEntityId === entityId)
588 if (targetEntityId === entityId)
474 {
589 {
475 const error = new Error("Cannot attack yourself.");
590 const error = new Error("Cannot attack yourself.");
476 error.userFacing = true;
591 error.userFacing = true;
477 throw error;
592 throw error;
478 }
593 }
479 if (isUntargetable(this.ecs, targetHandle))
594 const target = resolveCombatTarget(this, targetEntityId);
595 if (!target)
480 {
596 {
481 const error = new Error("That cannot be attacked.");
597 const error = new Error("Target is not here.");
482 error.userFacing = true;
598 error.userFacing = true;
483 throw error;
599 throw error;
484 }
600 }
485 const health = this.ecs.get(targetHandle, Component.health);
601 if (target.health && target.health.current <= 0)
486 if (!health)
487 {
602 {
488 const error = new Error("That cannot be attacked.");
603 const error = new Error("That cannot be attacked.");
489 error.userFacing = true;
604 error.userFacing = true;
@@ -493,14 +608,69 @@ export class WorkerWorld
493 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
608 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
494 clearFollow(this.ecs, entityId);
609 clearFollow(this.ecs, entityId);
495 engageTarget(this.ecs, entityId, targetEntityId, now);
610 engageTarget(this.ecs, entityId, targetEntityId, now);
496 if (ensureMobCombat(this.ecs, targetEntityId))
611 if (target.local)
497 { engageTarget(this.ecs, targetEntityId, entityId, now); }
612 {
613 if (ensureMobCombat(this.ecs, targetEntityId))
614 { engageTarget(this.ecs, targetEntityId, entityId, now); }
615 const targetPath = this.ecs.get(target.handle, Component.path);
616 if (targetPath)
617 { targetPath.tiles = []; }
618 }
498 const path = this.ecs.get(handle, Component.path);
619 const path = this.ecs.get(handle, Component.path);
499 if (path)
620 if (path)
500 { path.tiles = []; }
621 { path.tiles = []; }
501 return { events: [] };
622 return { events: [] };
502 }
623 }
503
624
625 #remoteCombatEngage ({ attackerEntityId, targetEntityId, now = Date.now() })
626 {
627 const targetHandle = this.ecs.handleOf(targetEntityId);
628 if (targetHandle == null)
629 { return { events: [] }; }
630 if (ensureMobCombat(this.ecs, targetEntityId))
631 {
632 engageTarget(this.ecs, targetEntityId, attackerEntityId, now);
633 const targetPath = this.ecs.get(targetHandle, Component.path);
634 if (targetPath)
635 { targetPath.tiles = []; }
636 }
637 else if (this.ecs.get(targetHandle, Component.character))
638 {
639 engageTarget(this.ecs, targetEntityId, attackerEntityId, now);
640 const targetPath = this.ecs.get(targetHandle, Component.path);
641 if (targetPath)
642 { targetPath.tiles = []; }
643 }
644 return { events: [] };
645 }
646
647 #applyRemoteMelee (payload)
648 {
649 return applyRemoteMeleeSwing(this, payload);
650 }
651
652 #applyCombatHitXp ({ entityId, profile })
653 {
654 const handle = this.ecs.handleOf(entityId);
655 if (handle == null)
656 { return { events: [] }; }
657 const character = this.ecs.get(handle, Component.character);
658 if (!character)
659 { return { events: [] }; }
660 const xpAward = awardCombatHitXp(this.ecs, handle, profile);
661 if (!xpAward)
662 { return { events: [] }; }
663 return {
664 events: [{
665 type: "skills-updated",
666 entityId,
667 characterId: character.characterId,
668 skills: xpAward.view,
669 stored: xpAward.stored
670 }]
671 };
672 }
673
504 #cancelAttack (sessionId, characterId)
674 #cancelAttack (sessionId, characterId)
505 {
675 {
506 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
676 const { entityId } = this.#requireOwnedEntity(sessionId, characterId);
@@ -601,6 +771,12 @@ export class WorkerWorld
601 error.userFacing = true;
771 error.userFacing = true;
602 throw error;
772 throw error;
603 }
773 }
774 if (this.ecs.has(handle, Component.dead))
775 {
776 const error = new Error("You are dead.");
777 error.userFacing = true;
778 throw error;
779 }
604 return { handle, entityId };
780 return { handle, entityId };
605 }
781 }
606
782
@@ -641,6 +817,8 @@ export class WorkerWorld
641 for (const entity of this.ecs.query(Component.position, Component.movement))
817 for (const entity of this.ecs.query(Component.position, Component.movement))
642 {
818 {
643 const { handle, entityId, position, movement } = entity;
819 const { handle, entityId, position, movement } = entity;
820 if (this.ecs.has(handle, Component.dead))
821 { continue; }
644 if (this.ecs.has(handle, Component.flight))
822 if (this.ecs.has(handle, Component.flight))
645 { continue; }
823 { continue; }
646 const path = this.ecs.get(handle, Component.path);
824 const path = this.ecs.get(handle, Component.path);
server/tests/bank.test.js +49 −0
@@ -146,6 +146,55 @@ test("write cheque reserves vault goods and redeem returns them", () =>
146 146 { harness.close(); }
147 147 });
148 148
149 test("redeem still works after bag is saved and reapplied", () =>
150 {
151 const harness = makeSimulation({ workerCount: 1 });
152 try
153 {
154 placeBank(harness.worldDb, 8, 8);
155 harness.simulation.reloadWorld();
156 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
157 const entityId = harness.simulation.spawnCharacter(1, character);
158 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
159 harness.simulation.step();
160 let bag = harness.simulation.bagOf(entityId);
161 harness.simulation.enqueue(1, {
162 type: "bank-deposit",
163 characterId: character.character_id,
164 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple),
165 quantity: null
166 });
167 harness.simulation.step();
168 bag = harness.simulation.bagOf(entityId);
169 harness.simulation.enqueue(1, {
170 type: "write-cheque",
171 characterId: character.character_id,
172 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque),
173 vaultSlotIndex: bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple),
174 quantity: 2
175 });
176 harness.simulation.step();
177 bag = harness.simulation.bagOf(entityId);
178 assert.ok(bag.vaultReserved?.[0]?.chequeId, "reserved stack must keep chequeId through bagView/save");
179 const saved = harness.stateDb.getBag(character.character_id);
180 assert.ok(saved.vaultReserved?.[0]?.chequeId);
181 harness.simulation.applyBag(entityId, saved);
182 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
183 harness.simulation.enqueue(1, {
184 type: "redeem-cheque",
185 characterId: character.character_id,
186 slotIndex: chequeIndex
187 });
188 const result = harness.simulation.step();
189 assert.equal(result.events.some((event) => event.type === "command-error"), false);
190 bag = harness.simulation.bagOf(entityId);
191 assert.equal((bag.vaultReserved ?? []).length, 0);
192 assert.ok(countItem(bag.vault, ItemId.apple) >= 2);
193 }
194 finally
195 { harness.close(); }
196 });
197
149 198 test("bank deposit of a filled cheque redeems reserved goods", () =>
150 199 {
151 200 const harness = makeSimulation({ workerCount: 1 });
@@ -146,6 +146,55 @@ test("write cheque reserves vault goods and redeem returns them", () =>
146 { harness.close(); }
146 { harness.close(); }
147});
147});
148
148
149test("redeem still works after bag is saved and reapplied", () =>
150{
151 const harness = makeSimulation({ workerCount: 1 });
152 try
153 {
154 placeBank(harness.worldDb, 8, 8);
155 harness.simulation.reloadWorld();
156 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
157 const entityId = harness.simulation.spawnCharacter(1, character);
158 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
159 harness.simulation.step();
160 let bag = harness.simulation.bagOf(entityId);
161 harness.simulation.enqueue(1, {
162 type: "bank-deposit",
163 characterId: character.character_id,
164 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple),
165 quantity: null
166 });
167 harness.simulation.step();
168 bag = harness.simulation.bagOf(entityId);
169 harness.simulation.enqueue(1, {
170 type: "write-cheque",
171 characterId: character.character_id,
172 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque),
173 vaultSlotIndex: bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple),
174 quantity: 2
175 });
176 harness.simulation.step();
177 bag = harness.simulation.bagOf(entityId);
178 assert.ok(bag.vaultReserved?.[0]?.chequeId, "reserved stack must keep chequeId through bagView/save");
179 const saved = harness.stateDb.getBag(character.character_id);
180 assert.ok(saved.vaultReserved?.[0]?.chequeId);
181 harness.simulation.applyBag(entityId, saved);
182 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
183 harness.simulation.enqueue(1, {
184 type: "redeem-cheque",
185 characterId: character.character_id,
186 slotIndex: chequeIndex
187 });
188 const result = harness.simulation.step();
189 assert.equal(result.events.some((event) => event.type === "command-error"), false);
190 bag = harness.simulation.bagOf(entityId);
191 assert.equal((bag.vaultReserved ?? []).length, 0);
192 assert.ok(countItem(bag.vault, ItemId.apple) >= 2);
193 }
194 finally
195 { harness.close(); }
196});
197
149test("bank deposit of a filled cheque redeems reserved goods", () =>
198test("bank deposit of a filled cheque redeems reserved goods", () =>
150{
199{
151 const harness = makeSimulation({ workerCount: 1 });
200 const harness = makeSimulation({ workerCount: 1 });
server/tests/combat.test.js +403 −1
@@ -9,7 +9,7 @@ import { WorkerMessage } from "../src/simulation/protocol.js";
9 9 import { tileToRegion } from "../src/world/coordinates.js";
10 10 import { SkillId } from "../../shared/definitions/skills.js";
11 11 import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
12 import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
12 import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
13 13
14 14 function workerOf (simulation, entityId)
15 15 {
@@ -37,6 +37,315 @@ function teleportEntity (worker, entityId, tileX, tileY)
37 37 world.occupancy.set(tileKey(tileX, tileY), entityId);
38 38 }
39 39
40 function entityIsAlive (simulation, entityId)
41 {
42 const record = simulation.entityRecord(entityId);
43 if (!record)
44 { return false; }
45 const worker = simulation.workers[record.workerId];
46 const handle = worker.world.ecs.handleOf(entityId);
47 if (handle == null)
48 { return false; }
49 const health = worker.world.ecs.get(handle, Component.health);
50 return (health?.current ?? 0) > 0;
51 }
52
53 function simulateAttackClick (harness, character, targetEntityId)
54 {
55 harness.simulation.enqueue(1, {
56 type: "attack",
57 characterId: character.character_id,
58 targetEntityId
59 });
60 }
61
62 /** Run ticks until one combatant dies or the step budget is exhausted. */
63 function runCombatUntilOutcome (harness, playerId, deerId, maxSteps = 600)
64 {
65 let swings = 0;
66 for (let i = 0; i < maxSteps; i++)
67 {
68 harness.advance(50);
69 const events = harness.simulation.step().events;
70 swings += events.filter((event) => event.type === "combat-swing").length;
71 const playerAlive = entityIsAlive(harness.simulation, playerId);
72 const deerAlive = entityIsAlive(harness.simulation, deerId);
73 if (!playerAlive || !deerAlive)
74 { return { playerAlive, deerAlive, swings, steps: i + 1 }; }
75 }
76 return {
77 playerAlive: entityIsAlive(harness.simulation, playerId),
78 deerAlive: entityIsAlive(harness.simulation, deerId),
79 swings,
80 steps: maxSteps
81 };
82 }
83
84 function withDeterministicCombat (fn)
85 {
86 const random = Math.random;
87 Math.random = () => 0;
88 try
89 { fn(); }
90 finally
91 { Math.random = random; }
92 }
93
94 test("immortal deer auto-attacks until the player dies", () =>
95 {
96 withDeterministicCombat(() =>
97 {
98 const harness = makeSimulation({ workerCount: 1 });
99 try
100 {
101 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
102 const playerId = harness.simulation.spawnCharacter(1, character);
103 const deerId = harness.simulation.spawnEntity(mobComponents({
104 tileX: 9,
105 tileY: 8,
106 mobTypeId: MobId.deer,
107 spawnerId: null
108 }));
109 const deer = componentsOf(harness.simulation, deerId);
110 deer.health.current = 1_000_000;
111 deer.health.max = 1_000_000;
112
113 simulateAttackClick(harness, character, deerId);
114 harness.simulation.step();
115
116 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
117 assert.ok(outcome.swings >= 2, `expected sustained auto-attack swings, got ${outcome.swings}`);
118 assert.equal(outcome.deerAlive, true, "immortal deer should survive");
119 assert.equal(outcome.playerAlive, false, "deer should kill the player via auto-attack");
120 assert.equal(
121 componentsOf(harness.simulation, deerId).combat?.targetEntityId ?? null,
122 null,
123 "deer should clear engage after the player dies"
124 );
125 }
126 finally
127 { harness.close(); }
128 });
129 });
130
131 test("immortal deer keeps auto-attacking after the player walks away", () =>
132 {
133 withDeterministicCombat(() =>
134 {
135 const harness = makeSimulation({ workerCount: 1 });
136 try
137 {
138 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
139 const playerId = harness.simulation.spawnCharacter(1, character);
140 const deerId = harness.simulation.spawnEntity(mobComponents({
141 tileX: 9,
142 tileY: 8,
143 mobTypeId: MobId.deer,
144 spawnerId: null
145 }));
146 const deer = componentsOf(harness.simulation, deerId);
147 deer.health.current = 1_000_000;
148 deer.health.max = 1_000_000;
149
150 simulateAttackClick(harness, character, deerId);
151 harness.simulation.step();
152
153 // Let one exchange land, then cancel player engage by walking away (client moveTo).
154 for (let i = 0; i < 30; i++)
155 {
156 harness.advance(50);
157 const swings = harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
158 if (swings > 0)
159 { break; }
160 }
161 harness.simulation.enqueue(1, {
162 type: "move-to",
163 characterId: character.character_id,
164 tileX: 8,
165 tileY: 14
166 });
167 harness.simulation.step();
168 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);
169 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
170
171 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
172 assert.ok(outcome.swings >= 1, `expected deer pursuit swings, got ${outcome.swings}`);
173 assert.equal(outcome.deerAlive, true);
174 assert.equal(outcome.playerAlive, false, "deer should chase and kill the player after walk-away");
175 }
176 finally
177 { harness.close(); }
178 });
179 });
180
181 test("cross-worker immortal deer auto-attacks until the player dies", () =>
182 {
183 withDeterministicCombat(() =>
184 {
185 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
186 try
187 {
188 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
189 const playerId = harness.simulation.spawnCharacter(1, character);
190 const deerId = harness.simulation.spawnEntity(mobComponents({
191 tileX: 63,
192 tileY: 8,
193 mobTypeId: MobId.deer,
194 spawnerId: null
195 }));
196 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
197 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
198
199 const deerWorker = workerOf(harness.simulation, deerId);
200 const deerHandle = deerWorker.world.ecs.handleOf(deerId);
201 const deerHealth = deerWorker.world.ecs.get(deerHandle, Component.health);
202 deerHealth.current = 1_000_000;
203 deerHealth.max = 1_000_000;
204
205 simulateAttackClick(harness, character, deerId);
206 const first = harness.simulation.step();
207 assert.equal(first.events.some((event) => event.type === "command-error"), false);
208
209 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
210 assert.ok(outcome.swings >= 2, `expected sustained cross-worker swings, got ${outcome.swings}`);
211 assert.equal(outcome.deerAlive, true);
212 assert.equal(outcome.playerAlive, false, "cross-worker deer should kill the player via auto-attack");
213 }
214 finally
215 { harness.close(); }
216 });
217 });
218
219 test("click attack from 5 tiles away ends with player or deer dead", () =>
220 {
221 withDeterministicCombat(() =>
222 {
223 const harness = makeSimulation({ workerCount: 1 });
224 try
225 {
226 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
227 const playerId = harness.simulation.spawnCharacter(1, character);
228 const deerId = harness.simulation.spawnEntity(mobComponents({
229 tileX: 13,
230 tileY: 8,
231 mobTypeId: MobId.deer,
232 spawnerId: null
233 }));
234
235 simulateAttackClick(harness, character, deerId);
236 harness.simulation.step();
237
238 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
239 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
240 assert.ok(
241 !outcome.playerAlive || !outcome.deerAlive,
242 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
243 );
244 }
245 finally
246 { harness.close(); }
247 });
248 });
249
250 test("click attack while adjacent ends with player or deer dead", () =>
251 {
252 withDeterministicCombat(() =>
253 {
254 const harness = makeSimulation({ workerCount: 1 });
255 try
256 {
257 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
258 const playerId = harness.simulation.spawnCharacter(1, character);
259 const deerId = harness.simulation.spawnEntity(mobComponents({
260 tileX: 9,
261 tileY: 8,
262 mobTypeId: MobId.deer,
263 spawnerId: null
264 }));
265
266 simulateAttackClick(harness, character, deerId);
267 harness.simulation.step();
268
269 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
270 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
271 assert.ok(
272 !outcome.playerAlive || !outcome.deerAlive,
273 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
274 );
275 }
276 finally
277 { harness.close(); }
278 });
279 });
280
281 test("cross-worker click attack from 5 tiles away ends with player or deer dead", () =>
282 {
283 withDeterministicCombat(() =>
284 {
285 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
286 try
287 {
288 const character = makeCharacter(harness.stateDb, { tileX: 59, tileY: 8 });
289 const playerId = harness.simulation.spawnCharacter(1, character);
290 const deerId = harness.simulation.spawnEntity(mobComponents({
291 tileX: 64,
292 tileY: 8,
293 mobTypeId: MobId.deer,
294 spawnerId: null
295 }));
296 assert.equal(harness.simulation.entityRecord(playerId).workerId, 0);
297 assert.equal(harness.simulation.entityRecord(deerId).workerId, 1);
298
299 simulateAttackClick(harness, character, deerId);
300 const first = harness.simulation.step();
301 assert.equal(first.events.some((event) => event.type === "command-error"), false);
302
303 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
304 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
305 assert.ok(
306 !outcome.playerAlive || !outcome.deerAlive,
307 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
308 );
309 }
310 finally
311 { harness.close(); }
312 });
313 });
314
315 test("cross-worker adjacent click attack ends with player or deer dead", () =>
316 {
317 withDeterministicCombat(() =>
318 {
319 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
320 try
321 {
322 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
323 const playerId = harness.simulation.spawnCharacter(1, character);
324 const deerId = harness.simulation.spawnEntity(mobComponents({
325 tileX: 63,
326 tileY: 8,
327 mobTypeId: MobId.deer,
328 spawnerId: null
329 }));
330 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
331 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
332
333 simulateAttackClick(harness, character, deerId);
334 const first = harness.simulation.step();
335 assert.equal(first.events.some((event) => event.type === "command-error"), false);
336
337 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
338 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
339 assert.ok(
340 !outcome.playerAlive || !outcome.deerAlive,
341 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
342 );
343 }
344 finally
345 { harness.close(); }
346 });
347 });
348
40 349 test("attack engages both combatants and retaliates", () =>
41 350 {
42 351 const harness = makeSimulation({ workerCount: 1 });
@@ -229,6 +538,99 @@ test("attacker keeps pursuing and can swing after the target moves", () =>
229 538 { harness.close(); }
230 539 });
231 540
541 test("combatants keep auto-attacking while adjacent", () =>
542 {
543 const harness = makeSimulation({ workerCount: 1 });
544 try
545 {
546 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
547 const playerId = harness.simulation.spawnCharacter(1, character);
548 const deerId = harness.simulation.spawnEntity(mobComponents({
549 tileX: 9,
550 tileY: 8,
551 mobTypeId: MobId.deer,
552 spawnerId: null
553 }));
554
555 harness.simulation.enqueue(1, {
556 type: "attack",
557 characterId: character.character_id,
558 targetEntityId: deerId
559 });
560 harness.simulation.step();
561
562 let swings = 0;
563 for (let i = 0; i < 50; i++)
564 {
565 harness.advance(50);
566 swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
567 }
568
569 assert.ok(swings >= 4, `expected repeated swings, got ${swings}`);
570 const player = componentsOf(harness.simulation, playerId);
571 const deer = componentsOf(harness.simulation, deerId);
572 assert.ok((player.health?.current ?? 0) > 0, "player should still be alive during sustained combat");
573 assert.equal(player.combat?.targetEntityId, deerId);
574 assert.equal(deer.combat?.targetEntityId, playerId);
575 }
576 finally
577 { harness.close(); }
578 });
579
580 test("cross-worker adjacent combat keeps engaging and swinging", () =>
581 {
582 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
583 try
584 {
585 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
586 const playerId = harness.simulation.spawnCharacter(1, character);
587 const deerId = harness.simulation.spawnEntity(mobComponents({
588 tileX: 63,
589 tileY: 8,
590 mobTypeId: MobId.deer,
591 spawnerId: null
592 }));
593 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
594 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
595
596 harness.simulation.enqueue(1, {
597 type: "attack",
598 characterId: character.character_id,
599 targetEntityId: deerId
600 });
601 const first = harness.simulation.step();
602 assert.equal(first.events.some((event) => event.type === "command-error"), false);
603
604 const random = Math.random;
605 Math.random = () => 0;
606 try
607 {
608 let swings = 0;
609 for (let i = 0; i < 5; i++)
610 {
611 harness.advance(50);
612 swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
613 }
614
615 assert.ok(swings >= 4, `expected cross-worker sustained swings, got ${swings}`);
616 const deerWorker = harness.simulation.workers[0];
617 const playerWorker = harness.simulation.workers[1];
618 const deerHandle = deerWorker.world.ecs.handleOf(deerId);
619 const playerHandle = playerWorker.world.ecs.handleOf(playerId);
620 const deerCombat = deerWorker.world.ecs.get(deerHandle, Component.combat);
621 const playerCombat = playerWorker.world.ecs.get(playerHandle, Component.combat);
622 const playerHealth = playerWorker.world.ecs.get(playerHandle, Component.health);
623 assert.ok((playerHealth?.current ?? 0) > 0, "player should survive sustained cross-worker combat");
624 assert.equal(deerCombat?.targetEntityId, playerId);
625 assert.equal(playerCombat?.targetEntityId, deerId);
626 }
627 finally
628 { Math.random = random; }
629 }
630 finally
631 { harness.close(); }
632 });
633
232 634 test("cancel attack stops the player but the mob keeps pursuing", () =>
233 635 {
234 636 const harness = makeSimulation({ workerCount: 1 });
@@ -9,7 +9,7 @@ import { WorkerMessage } from "../src/simulation/protocol.js";
9import { tileToRegion } from "../src/world/coordinates.js";
9import { tileToRegion } from "../src/world/coordinates.js";
10import { SkillId } from "../../shared/definitions/skills.js";
10import { SkillId } from "../../shared/definitions/skills.js";
11import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
11import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
12import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
12import { makeCharacter, makeSimulation, pinEastSplit, stepTimes } from "./helpers/simulationHarness.js";
13
13
14function workerOf (simulation, entityId)
14function workerOf (simulation, entityId)
15{
15{
@@ -37,6 +37,315 @@ function teleportEntity (worker, entityId, tileX, tileY)
37 world.occupancy.set(tileKey(tileX, tileY), entityId);
37 world.occupancy.set(tileKey(tileX, tileY), entityId);
38}
38}
39
39
40function entityIsAlive (simulation, entityId)
41{
42 const record = simulation.entityRecord(entityId);
43 if (!record)
44 { return false; }
45 const worker = simulation.workers[record.workerId];
46 const handle = worker.world.ecs.handleOf(entityId);
47 if (handle == null)
48 { return false; }
49 const health = worker.world.ecs.get(handle, Component.health);
50 return (health?.current ?? 0) > 0;
51}
52
53function simulateAttackClick (harness, character, targetEntityId)
54{
55 harness.simulation.enqueue(1, {
56 type: "attack",
57 characterId: character.character_id,
58 targetEntityId
59 });
60}
61
62/** Run ticks until one combatant dies or the step budget is exhausted. */
63function runCombatUntilOutcome (harness, playerId, deerId, maxSteps = 600)
64{
65 let swings = 0;
66 for (let i = 0; i < maxSteps; i++)
67 {
68 harness.advance(50);
69 const events = harness.simulation.step().events;
70 swings += events.filter((event) => event.type === "combat-swing").length;
71 const playerAlive = entityIsAlive(harness.simulation, playerId);
72 const deerAlive = entityIsAlive(harness.simulation, deerId);
73 if (!playerAlive || !deerAlive)
74 { return { playerAlive, deerAlive, swings, steps: i + 1 }; }
75 }
76 return {
77 playerAlive: entityIsAlive(harness.simulation, playerId),
78 deerAlive: entityIsAlive(harness.simulation, deerId),
79 swings,
80 steps: maxSteps
81 };
82}
83
84function withDeterministicCombat (fn)
85{
86 const random = Math.random;
87 Math.random = () => 0;
88 try
89 { fn(); }
90 finally
91 { Math.random = random; }
92}
93
94test("immortal deer auto-attacks until the player dies", () =>
95{
96 withDeterministicCombat(() =>
97 {
98 const harness = makeSimulation({ workerCount: 1 });
99 try
100 {
101 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
102 const playerId = harness.simulation.spawnCharacter(1, character);
103 const deerId = harness.simulation.spawnEntity(mobComponents({
104 tileX: 9,
105 tileY: 8,
106 mobTypeId: MobId.deer,
107 spawnerId: null
108 }));
109 const deer = componentsOf(harness.simulation, deerId);
110 deer.health.current = 1_000_000;
111 deer.health.max = 1_000_000;
112
113 simulateAttackClick(harness, character, deerId);
114 harness.simulation.step();
115
116 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
117 assert.ok(outcome.swings >= 2, `expected sustained auto-attack swings, got ${outcome.swings}`);
118 assert.equal(outcome.deerAlive, true, "immortal deer should survive");
119 assert.equal(outcome.playerAlive, false, "deer should kill the player via auto-attack");
120 assert.equal(
121 componentsOf(harness.simulation, deerId).combat?.targetEntityId ?? null,
122 null,
123 "deer should clear engage after the player dies"
124 );
125 }
126 finally
127 { harness.close(); }
128 });
129});
130
131test("immortal deer keeps auto-attacking after the player walks away", () =>
132{
133 withDeterministicCombat(() =>
134 {
135 const harness = makeSimulation({ workerCount: 1 });
136 try
137 {
138 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
139 const playerId = harness.simulation.spawnCharacter(1, character);
140 const deerId = harness.simulation.spawnEntity(mobComponents({
141 tileX: 9,
142 tileY: 8,
143 mobTypeId: MobId.deer,
144 spawnerId: null
145 }));
146 const deer = componentsOf(harness.simulation, deerId);
147 deer.health.current = 1_000_000;
148 deer.health.max = 1_000_000;
149
150 simulateAttackClick(harness, character, deerId);
151 harness.simulation.step();
152
153 // Let one exchange land, then cancel player engage by walking away (client moveTo).
154 for (let i = 0; i < 30; i++)
155 {
156 harness.advance(50);
157 const swings = harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
158 if (swings > 0)
159 { break; }
160 }
161 harness.simulation.enqueue(1, {
162 type: "move-to",
163 characterId: character.character_id,
164 tileX: 8,
165 tileY: 14
166 });
167 harness.simulation.step();
168 assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId ?? null, null);
169 assert.equal(componentsOf(harness.simulation, deerId).combat?.targetEntityId, playerId);
170
171 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
172 assert.ok(outcome.swings >= 1, `expected deer pursuit swings, got ${outcome.swings}`);
173 assert.equal(outcome.deerAlive, true);
174 assert.equal(outcome.playerAlive, false, "deer should chase and kill the player after walk-away");
175 }
176 finally
177 { harness.close(); }
178 });
179});
180
181test("cross-worker immortal deer auto-attacks until the player dies", () =>
182{
183 withDeterministicCombat(() =>
184 {
185 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
186 try
187 {
188 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
189 const playerId = harness.simulation.spawnCharacter(1, character);
190 const deerId = harness.simulation.spawnEntity(mobComponents({
191 tileX: 63,
192 tileY: 8,
193 mobTypeId: MobId.deer,
194 spawnerId: null
195 }));
196 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
197 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
198
199 const deerWorker = workerOf(harness.simulation, deerId);
200 const deerHandle = deerWorker.world.ecs.handleOf(deerId);
201 const deerHealth = deerWorker.world.ecs.get(deerHandle, Component.health);
202 deerHealth.current = 1_000_000;
203 deerHealth.max = 1_000_000;
204
205 simulateAttackClick(harness, character, deerId);
206 const first = harness.simulation.step();
207 assert.equal(first.events.some((event) => event.type === "command-error"), false);
208
209 const outcome = runCombatUntilOutcome(harness, playerId, deerId, 2_000);
210 assert.ok(outcome.swings >= 2, `expected sustained cross-worker swings, got ${outcome.swings}`);
211 assert.equal(outcome.deerAlive, true);
212 assert.equal(outcome.playerAlive, false, "cross-worker deer should kill the player via auto-attack");
213 }
214 finally
215 { harness.close(); }
216 });
217});
218
219test("click attack from 5 tiles away ends with player or deer dead", () =>
220{
221 withDeterministicCombat(() =>
222 {
223 const harness = makeSimulation({ workerCount: 1 });
224 try
225 {
226 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
227 const playerId = harness.simulation.spawnCharacter(1, character);
228 const deerId = harness.simulation.spawnEntity(mobComponents({
229 tileX: 13,
230 tileY: 8,
231 mobTypeId: MobId.deer,
232 spawnerId: null
233 }));
234
235 simulateAttackClick(harness, character, deerId);
236 harness.simulation.step();
237
238 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
239 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
240 assert.ok(
241 !outcome.playerAlive || !outcome.deerAlive,
242 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
243 );
244 }
245 finally
246 { harness.close(); }
247 });
248});
249
250test("click attack while adjacent ends with player or deer dead", () =>
251{
252 withDeterministicCombat(() =>
253 {
254 const harness = makeSimulation({ workerCount: 1 });
255 try
256 {
257 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
258 const playerId = harness.simulation.spawnCharacter(1, character);
259 const deerId = harness.simulation.spawnEntity(mobComponents({
260 tileX: 9,
261 tileY: 8,
262 mobTypeId: MobId.deer,
263 spawnerId: null
264 }));
265
266 simulateAttackClick(harness, character, deerId);
267 harness.simulation.step();
268
269 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
270 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
271 assert.ok(
272 !outcome.playerAlive || !outcome.deerAlive,
273 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
274 );
275 }
276 finally
277 { harness.close(); }
278 });
279});
280
281test("cross-worker click attack from 5 tiles away ends with player or deer dead", () =>
282{
283 withDeterministicCombat(() =>
284 {
285 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
286 try
287 {
288 const character = makeCharacter(harness.stateDb, { tileX: 59, tileY: 8 });
289 const playerId = harness.simulation.spawnCharacter(1, character);
290 const deerId = harness.simulation.spawnEntity(mobComponents({
291 tileX: 64,
292 tileY: 8,
293 mobTypeId: MobId.deer,
294 spawnerId: null
295 }));
296 assert.equal(harness.simulation.entityRecord(playerId).workerId, 0);
297 assert.equal(harness.simulation.entityRecord(deerId).workerId, 1);
298
299 simulateAttackClick(harness, character, deerId);
300 const first = harness.simulation.step();
301 assert.equal(first.events.some((event) => event.type === "command-error"), false);
302
303 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
304 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
305 assert.ok(
306 !outcome.playerAlive || !outcome.deerAlive,
307 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
308 );
309 }
310 finally
311 { harness.close(); }
312 });
313});
314
315test("cross-worker adjacent click attack ends with player or deer dead", () =>
316{
317 withDeterministicCombat(() =>
318 {
319 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
320 try
321 {
322 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
323 const playerId = harness.simulation.spawnCharacter(1, character);
324 const deerId = harness.simulation.spawnEntity(mobComponents({
325 tileX: 63,
326 tileY: 8,
327 mobTypeId: MobId.deer,
328 spawnerId: null
329 }));
330 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
331 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
332
333 simulateAttackClick(harness, character, deerId);
334 const first = harness.simulation.step();
335 assert.equal(first.events.some((event) => event.type === "command-error"), false);
336
337 const outcome = runCombatUntilOutcome(harness, playerId, deerId);
338 assert.ok(outcome.swings >= 1, `expected at least one swing, got ${outcome.swings}`);
339 assert.ok(
340 !outcome.playerAlive || !outcome.deerAlive,
341 `expected a kill within ${outcome.steps} steps (${outcome.swings} swings); both still alive`
342 );
343 }
344 finally
345 { harness.close(); }
346 });
347});
348
40test("attack engages both combatants and retaliates", () =>
349test("attack engages both combatants and retaliates", () =>
41{
350{
42 const harness = makeSimulation({ workerCount: 1 });
351 const harness = makeSimulation({ workerCount: 1 });
@@ -229,6 +538,99 @@ test("attacker keeps pursuing and can swing after the target moves", () =>
229 { harness.close(); }
538 { harness.close(); }
230});
539});
231
540
541test("combatants keep auto-attacking while adjacent", () =>
542{
543 const harness = makeSimulation({ workerCount: 1 });
544 try
545 {
546 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
547 const playerId = harness.simulation.spawnCharacter(1, character);
548 const deerId = harness.simulation.spawnEntity(mobComponents({
549 tileX: 9,
550 tileY: 8,
551 mobTypeId: MobId.deer,
552 spawnerId: null
553 }));
554
555 harness.simulation.enqueue(1, {
556 type: "attack",
557 characterId: character.character_id,
558 targetEntityId: deerId
559 });
560 harness.simulation.step();
561
562 let swings = 0;
563 for (let i = 0; i < 50; i++)
564 {
565 harness.advance(50);
566 swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
567 }
568
569 assert.ok(swings >= 4, `expected repeated swings, got ${swings}`);
570 const player = componentsOf(harness.simulation, playerId);
571 const deer = componentsOf(harness.simulation, deerId);
572 assert.ok((player.health?.current ?? 0) > 0, "player should still be alive during sustained combat");
573 assert.equal(player.combat?.targetEntityId, deerId);
574 assert.equal(deer.combat?.targetEntityId, playerId);
575 }
576 finally
577 { harness.close(); }
578});
579
580test("cross-worker adjacent combat keeps engaging and swinging", () =>
581{
582 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
583 try
584 {
585 const character = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8 });
586 const playerId = harness.simulation.spawnCharacter(1, character);
587 const deerId = harness.simulation.spawnEntity(mobComponents({
588 tileX: 63,
589 tileY: 8,
590 mobTypeId: MobId.deer,
591 spawnerId: null
592 }));
593 assert.equal(harness.simulation.entityRecord(playerId).workerId, 1);
594 assert.equal(harness.simulation.entityRecord(deerId).workerId, 0);
595
596 harness.simulation.enqueue(1, {
597 type: "attack",
598 characterId: character.character_id,
599 targetEntityId: deerId
600 });
601 const first = harness.simulation.step();
602 assert.equal(first.events.some((event) => event.type === "command-error"), false);
603
604 const random = Math.random;
605 Math.random = () => 0;
606 try
607 {
608 let swings = 0;
609 for (let i = 0; i < 5; i++)
610 {
611 harness.advance(50);
612 swings += harness.simulation.step().events.filter((event) => event.type === "combat-swing").length;
613 }
614
615 assert.ok(swings >= 4, `expected cross-worker sustained swings, got ${swings}`);
616 const deerWorker = harness.simulation.workers[0];
617 const playerWorker = harness.simulation.workers[1];
618 const deerHandle = deerWorker.world.ecs.handleOf(deerId);
619 const playerHandle = playerWorker.world.ecs.handleOf(playerId);
620 const deerCombat = deerWorker.world.ecs.get(deerHandle, Component.combat);
621 const playerCombat = playerWorker.world.ecs.get(playerHandle, Component.combat);
622 const playerHealth = playerWorker.world.ecs.get(playerHandle, Component.health);
623 assert.ok((playerHealth?.current ?? 0) > 0, "player should survive sustained cross-worker combat");
624 assert.equal(deerCombat?.targetEntityId, playerId);
625 assert.equal(playerCombat?.targetEntityId, deerId);
626 }
627 finally
628 { Math.random = random; }
629 }
630 finally
631 { harness.close(); }
632});
633
232test("cancel attack stops the player but the mob keeps pursuing", () =>
634test("cancel attack stops the player but the mob keeps pursuing", () =>
233{
635{
234 const harness = makeSimulation({ workerCount: 1 });
636 const harness = makeSimulation({ workerCount: 1 });
server/tests/courier.test.js +57 −0
@@ -171,3 +171,60 @@ test("pigeon rejects blank cheques", () =>
171 171 finally
172 172 { harness.close(); }
173 173 });
174
175 test("pigeon to bank redeems a filled cheque into reserved goods", () =>
176 {
177 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
178 try
179 {
180 placeBank(harness.worldDb, 20, 8);
181 placeBank(harness.worldDb, 8, 8);
182 harness.simulation.reloadWorld();
183 harness.simulation.applySettings({
184 pigeonTakeoffTilesPerSec: 40,
185 pigeonCruiseTilesPerSec: 40,
186 pigeonLandingTilesPerSec: 40,
187 simulationTickHz: 20
188 });
189 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
190 const entityId = harness.simulation.spawnCharacter(1, character);
191 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
192 harness.simulation.step();
193 let bag = harness.simulation.bagOf(entityId);
194 harness.simulation.enqueue(1, {
195 type: "bank-deposit",
196 characterId: character.character_id,
197 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple),
198 quantity: null
199 });
200 harness.simulation.step();
201 bag = harness.simulation.bagOf(entityId);
202 const applesBefore = countItem(bag.vault, ItemId.apple);
203 harness.simulation.enqueue(1, {
204 type: "write-cheque",
205 characterId: character.character_id,
206 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque),
207 vaultSlotIndex: bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple),
208 quantity: 2
209 });
210 harness.simulation.step();
211 bag = harness.simulation.bagOf(entityId);
212 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
213 assert.ok(chequeIndex >= 0);
214 assert.equal((bag.vaultReserved ?? []).length, 1);
215
216 harness.simulation.dispatchPigeon({
217 characterId: character.character_id,
218 destination: { kind: "bank" },
219 cargo: { kind: "item", slotIndex: chequeIndex, quantity: 1 }
220 });
221 stepTimes(harness.simulation, 80);
222 bag = harness.simulation.bagOf(entityId);
223 assert.equal(bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque), -1);
224 assert.equal(countItem(bag.vault, ItemId.filledCheque), 0);
225 assert.equal((bag.vaultReserved ?? []).length, 0);
226 assert.equal(countItem(bag.vault, ItemId.apple), applesBefore);
227 }
228 finally
229 { harness.close(); }
230 });
@@ -171,3 +171,60 @@ test("pigeon rejects blank cheques", () =>
171 finally
171 finally
172 { harness.close(); }
172 { harness.close(); }
173});
173});
174
175test("pigeon to bank redeems a filled cheque into reserved goods", () =>
176{
177 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
178 try
179 {
180 placeBank(harness.worldDb, 20, 8);
181 placeBank(harness.worldDb, 8, 8);
182 harness.simulation.reloadWorld();
183 harness.simulation.applySettings({
184 pigeonTakeoffTilesPerSec: 40,
185 pigeonCruiseTilesPerSec: 40,
186 pigeonLandingTilesPerSec: 40,
187 simulationTickHz: 20
188 });
189 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
190 const entityId = harness.simulation.spawnCharacter(1, character);
191 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
192 harness.simulation.step();
193 let bag = harness.simulation.bagOf(entityId);
194 harness.simulation.enqueue(1, {
195 type: "bank-deposit",
196 characterId: character.character_id,
197 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple),
198 quantity: null
199 });
200 harness.simulation.step();
201 bag = harness.simulation.bagOf(entityId);
202 const applesBefore = countItem(bag.vault, ItemId.apple);
203 harness.simulation.enqueue(1, {
204 type: "write-cheque",
205 characterId: character.character_id,
206 slotIndex: bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque),
207 vaultSlotIndex: bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple),
208 quantity: 2
209 });
210 harness.simulation.step();
211 bag = harness.simulation.bagOf(entityId);
212 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
213 assert.ok(chequeIndex >= 0);
214 assert.equal((bag.vaultReserved ?? []).length, 1);
215
216 harness.simulation.dispatchPigeon({
217 characterId: character.character_id,
218 destination: { kind: "bank" },
219 cargo: { kind: "item", slotIndex: chequeIndex, quantity: 1 }
220 });
221 stepTimes(harness.simulation, 80);
222 bag = harness.simulation.bagOf(entityId);
223 assert.equal(bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque), -1);
224 assert.equal(countItem(bag.vault, ItemId.filledCheque), 0);
225 assert.equal((bag.vaultReserved ?? []).length, 0);
226 assert.equal(countItem(bag.vault, ItemId.apple), applesBefore);
227 }
228 finally
229 { harness.close(); }
230});
server/tests/death.test.js added +157 −0
@@ -0,0 +1,157 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { BlockType } from "../../shared/definitions/tiles.js";
4 import { ItemId } from "../../shared/definitions/items.js";
5 import { Component } from "../src/ecs/components.js";
6 import { MobId } from "../../shared/definitions/mobs.js";
7 import { mobComponents } from "../src/simulation/spawners.js";
8 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
9 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
10
11 function componentsOf (simulation, entityId)
12 {
13 const record = simulation.entityRecord(entityId);
14 const worker = simulation.workers[record.workerId];
15 const handle = worker.world.ecs.handleOf(entityId);
16 return worker.world.ecs.componentsOf(handle);
17 }
18
19 function placeAltar (worldDb, tileX, tileY)
20 {
21 const chunkX = Math.floor(tileX / 16);
22 const chunkY = Math.floor(tileY / 16);
23 const data = createEmptyChunkData();
24 data.open = true;
25 data.blocks[(tileY - chunkY * 16) * 16 + (tileX - chunkX * 16)] = {
26 typeId: BlockType.churchAltar,
27 state: 0
28 };
29 worldDb.saveChunkVersion(
30 chunkX,
31 chunkY,
32 worldDb.getActiveRevisionId(),
33 true,
34 encodeChunkBlob(data)
35 );
36 }
37
38 function killPlayer (harness, character, playerId)
39 {
40 const deerId = harness.simulation.spawnEntity(mobComponents({
41 tileX: 9,
42 tileY: 8,
43 mobTypeId: MobId.deer,
44 spawnerId: null
45 }));
46 const deer = componentsOf(harness.simulation, deerId);
47 deer.health.current = 1_000_000;
48 deer.health.max = 1_000_000;
49 const player = componentsOf(harness.simulation, playerId);
50 player.health.current = 1;
51 harness.simulation.enqueue(1, {
52 type: "attack",
53 characterId: character.character_id,
54 targetEntityId: deerId
55 });
56 const first = harness.simulation.step();
57 const immediate = first.events.find((event) => event.type === "player-died");
58 if (immediate)
59 { return { died: immediate, events: first.events }; }
60 for (let i = 0; i < 100; i++)
61 {
62 harness.advance(1000);
63 const result = harness.simulation.step();
64 const died = result.events.find((event) => event.type === "player-died");
65 if (died)
66 { return { died, events: result.events }; }
67 }
68 throw new Error("Player did not die.");
69 }
70
71 function withDeterministicCombat (fn)
72 {
73 const random = Math.random;
74 Math.random = () => 0;
75 try
76 { fn(); }
77 finally
78 { Math.random = random; }
79 }
80
81 test("player death marks dead and drops bones and skull", () =>
82 {
83 withDeterministicCombat(() =>
84 {
85 const harness = makeSimulation({ workerCount: 1 });
86 try
87 {
88 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
89 const playerId = harness.simulation.spawnCharacter(1, character);
90 const result = killPlayer(harness, character, playerId);
91 assert.equal(result.died.sessionId, 1);
92 assert.ok(componentsOf(harness.simulation, playerId)[Component.dead]);
93 assert.equal(harness.stateDb.getCharacter(character.character_id).is_dead, 1);
94 const drops = harness.stateDb.listGroundItemsInRegion(0, 0, 63, 63);
95 assert.deepEqual(
96 drops.map((item) => item.stack.itemId).sort((a, b) => a - b),
97 [ItemId.bones, ItemId.skull]
98 );
99 }
100 finally
101 { harness.close(); }
102 });
103 });
104
105 test("respawn moves beside nearest church altar with full vitals", () =>
106 {
107 withDeterministicCombat(() =>
108 {
109 const harness = makeSimulation({ workerCount: 1 });
110 try
111 {
112 placeAltar(harness.worldDb, 20, 8);
113 harness.simulation.reloadWorld();
114 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
115 const playerId = harness.simulation.spawnCharacter(1, character);
116 killPlayer(harness, character, playerId);
117 harness.simulation.enqueue(1, { type: "respawn", characterId: character.character_id });
118 const result = harness.simulation.step();
119 assert.ok(result.events.some((event) => event.type === "player-respawned"));
120 const player = componentsOf(harness.simulation, playerId);
121 assert.equal(player[Component.dead], undefined);
122 assert.equal(player.health.current, player.health.max);
123 assert.equal(player.stamina.current, player.stamina.max);
124 assert.equal(
125 Math.max(Math.abs(player.position.tileX - 20), Math.abs(player.position.tileY - 8)),
126 1
127 );
128 assert.equal(harness.stateDb.getCharacter(character.character_id).is_dead, 0);
129 }
130 finally
131 { harness.close(); }
132 });
133 });
134
135 test("respawn without an altar falls back to the death tile", () =>
136 {
137 withDeterministicCombat(() =>
138 {
139 const harness = makeSimulation({ workerCount: 1 });
140 try
141 {
142 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
143 const playerId = harness.simulation.spawnCharacter(1, character);
144 const { died } = killPlayer(harness, character, playerId);
145 harness.simulation.enqueue(1, { type: "respawn", characterId: character.character_id });
146 const result = harness.simulation.step();
147 assert.equal(result.events.some((event) => event.type === "command-error"), false);
148 const player = componentsOf(harness.simulation, playerId);
149 assert.equal(player.position.tileX, died.tileX);
150 assert.equal(player.position.tileY, died.tileY);
151 assert.equal(player.health.current, player.health.max);
152 assert.equal(player[Component.dead], undefined);
153 }
154 finally
155 { harness.close(); }
156 });
157 });
@@ -0,0 +1,157 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
4import { ItemId } from "../../shared/definitions/items.js";
5import { Component } from "../src/ecs/components.js";
6import { MobId } from "../../shared/definitions/mobs.js";
7import { mobComponents } from "../src/simulation/spawners.js";
8import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
9import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
10
11function componentsOf (simulation, entityId)
12{
13 const record = simulation.entityRecord(entityId);
14 const worker = simulation.workers[record.workerId];
15 const handle = worker.world.ecs.handleOf(entityId);
16 return worker.world.ecs.componentsOf(handle);
17}
18
19function placeAltar (worldDb, tileX, tileY)
20{
21 const chunkX = Math.floor(tileX / 16);
22 const chunkY = Math.floor(tileY / 16);
23 const data = createEmptyChunkData();
24 data.open = true;
25 data.blocks[(tileY - chunkY * 16) * 16 + (tileX - chunkX * 16)] = {
26 typeId: BlockType.churchAltar,
27 state: 0
28 };
29 worldDb.saveChunkVersion(
30 chunkX,
31 chunkY,
32 worldDb.getActiveRevisionId(),
33 true,
34 encodeChunkBlob(data)
35 );
36}
37
38function killPlayer (harness, character, playerId)
39{
40 const deerId = harness.simulation.spawnEntity(mobComponents({
41 tileX: 9,
42 tileY: 8,
43 mobTypeId: MobId.deer,
44 spawnerId: null
45 }));
46 const deer = componentsOf(harness.simulation, deerId);
47 deer.health.current = 1_000_000;
48 deer.health.max = 1_000_000;
49 const player = componentsOf(harness.simulation, playerId);
50 player.health.current = 1;
51 harness.simulation.enqueue(1, {
52 type: "attack",
53 characterId: character.character_id,
54 targetEntityId: deerId
55 });
56 const first = harness.simulation.step();
57 const immediate = first.events.find((event) => event.type === "player-died");
58 if (immediate)
59 { return { died: immediate, events: first.events }; }
60 for (let i = 0; i < 100; i++)
61 {
62 harness.advance(1000);
63 const result = harness.simulation.step();
64 const died = result.events.find((event) => event.type === "player-died");
65 if (died)
66 { return { died, events: result.events }; }
67 }
68 throw new Error("Player did not die.");
69}
70
71function withDeterministicCombat (fn)
72{
73 const random = Math.random;
74 Math.random = () => 0;
75 try
76 { fn(); }
77 finally
78 { Math.random = random; }
79}
80
81test("player death marks dead and drops bones and skull", () =>
82{
83 withDeterministicCombat(() =>
84 {
85 const harness = makeSimulation({ workerCount: 1 });
86 try
87 {
88 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
89 const playerId = harness.simulation.spawnCharacter(1, character);
90 const result = killPlayer(harness, character, playerId);
91 assert.equal(result.died.sessionId, 1);
92 assert.ok(componentsOf(harness.simulation, playerId)[Component.dead]);
93 assert.equal(harness.stateDb.getCharacter(character.character_id).is_dead, 1);
94 const drops = harness.stateDb.listGroundItemsInRegion(0, 0, 63, 63);
95 assert.deepEqual(
96 drops.map((item) => item.stack.itemId).sort((a, b) => a - b),
97 [ItemId.bones, ItemId.skull]
98 );
99 }
100 finally
101 { harness.close(); }
102 });
103});
104
105test("respawn moves beside nearest church altar with full vitals", () =>
106{
107 withDeterministicCombat(() =>
108 {
109 const harness = makeSimulation({ workerCount: 1 });
110 try
111 {
112 placeAltar(harness.worldDb, 20, 8);
113 harness.simulation.reloadWorld();
114 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
115 const playerId = harness.simulation.spawnCharacter(1, character);
116 killPlayer(harness, character, playerId);
117 harness.simulation.enqueue(1, { type: "respawn", characterId: character.character_id });
118 const result = harness.simulation.step();
119 assert.ok(result.events.some((event) => event.type === "player-respawned"));
120 const player = componentsOf(harness.simulation, playerId);
121 assert.equal(player[Component.dead], undefined);
122 assert.equal(player.health.current, player.health.max);
123 assert.equal(player.stamina.current, player.stamina.max);
124 assert.equal(
125 Math.max(Math.abs(player.position.tileX - 20), Math.abs(player.position.tileY - 8)),
126 1
127 );
128 assert.equal(harness.stateDb.getCharacter(character.character_id).is_dead, 0);
129 }
130 finally
131 { harness.close(); }
132 });
133});
134
135test("respawn without an altar falls back to the death tile", () =>
136{
137 withDeterministicCombat(() =>
138 {
139 const harness = makeSimulation({ workerCount: 1 });
140 try
141 {
142 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
143 const playerId = harness.simulation.spawnCharacter(1, character);
144 const { died } = killPlayer(harness, character, playerId);
145 harness.simulation.enqueue(1, { type: "respawn", characterId: character.character_id });
146 const result = harness.simulation.step();
147 assert.equal(result.events.some((event) => event.type === "command-error"), false);
148 const player = componentsOf(harness.simulation, playerId);
149 assert.equal(player.position.tileX, died.tileX);
150 assert.equal(player.position.tileY, died.tileY);
151 assert.equal(player.health.current, player.health.max);
152 assert.equal(player[Component.dead], undefined);
153 }
154 finally
155 { harness.close(); }
156 });
157});
server/tests/skills.test.js +30 −1
@@ -21,6 +21,34 @@ import { mobComponents } from "../src/simulation/spawners.js";
21 21 import { MobId } from "../../shared/definitions/mobs.js";
22 22 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
23 23
24 test("normalizeSkillXp floors Health to the level-10 starting XP", () =>
25 {
26 assert.equal(normalizeSkillXp({}).health, totalXpForLevel(10));
27 assert.equal(normalizeSkillXp({ health: 14 }).health, totalXpForLevel(10));
28 assert.equal(normalizeSkillXp({ health: totalXpForLevel(11) }).health, totalXpForLevel(11));
29 });
30
31 test("legacy empty skills_blob loads as Health level 10 max HP", () =>
32 {
33 const harness = makeSimulation({ workerCount: 1 });
34 try
35 {
36 const character = makeCharacter(harness.stateDb);
37 harness.stateDb.db.prepare("UPDATE character_bags SET skills_blob = ? WHERE character_id = ?")
38 .run("{}", character.character_id);
39 const skills = harness.stateDb.getSkills(character.character_id);
40 assert.equal(skillLevel(skills, SkillId.health), 10);
41 assert.equal(playerMaxHealth(skills), 10);
42 const stored = JSON.parse(
43 harness.stateDb.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?")
44 .get(character.character_id).skills_blob
45 );
46 assert.ok((stored.xp?.health ?? stored.health) >= totalXpForLevel(10));
47 }
48 finally
49 { harness.close(); }
50 });
51
24 52 test("xp to advance doubles each level starting at 50", () =>
25 53 {
26 54 assert.equal(xpToAdvanceFromLevel(1), 50);
@@ -110,7 +138,8 @@ test("successful player melee hits award split xp", () =>
110 138 const playerId = harness.simulation.spawnCharacter(1, character);
111 139 const ratId = harness.simulation.spawnEntity(mobComponents({
112 140 mobTypeId: MobId.rat,
113 position: { tileX: 9, tileY: 8 }
141 tileX: 9,
142 tileY: 8
114 143 }));
115 144 const worker = harness.simulation.workers[0];
116 145 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(playerId));
@@ -21,6 +21,34 @@ import { mobComponents } from "../src/simulation/spawners.js";
21import { MobId } from "../../shared/definitions/mobs.js";
21import { MobId } from "../../shared/definitions/mobs.js";
22import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
22import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
23
23
24test("normalizeSkillXp floors Health to the level-10 starting XP", () =>
25{
26 assert.equal(normalizeSkillXp({}).health, totalXpForLevel(10));
27 assert.equal(normalizeSkillXp({ health: 14 }).health, totalXpForLevel(10));
28 assert.equal(normalizeSkillXp({ health: totalXpForLevel(11) }).health, totalXpForLevel(11));
29});
30
31test("legacy empty skills_blob loads as Health level 10 max HP", () =>
32{
33 const harness = makeSimulation({ workerCount: 1 });
34 try
35 {
36 const character = makeCharacter(harness.stateDb);
37 harness.stateDb.db.prepare("UPDATE character_bags SET skills_blob = ? WHERE character_id = ?")
38 .run("{}", character.character_id);
39 const skills = harness.stateDb.getSkills(character.character_id);
40 assert.equal(skillLevel(skills, SkillId.health), 10);
41 assert.equal(playerMaxHealth(skills), 10);
42 const stored = JSON.parse(
43 harness.stateDb.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?")
44 .get(character.character_id).skills_blob
45 );
46 assert.ok((stored.xp?.health ?? stored.health) >= totalXpForLevel(10));
47 }
48 finally
49 { harness.close(); }
50});
51
24test("xp to advance doubles each level starting at 50", () =>
52test("xp to advance doubles each level starting at 50", () =>
25{
53{
26 assert.equal(xpToAdvanceFromLevel(1), 50);
54 assert.equal(xpToAdvanceFromLevel(1), 50);
@@ -110,7 +138,8 @@ test("successful player melee hits award split xp", () =>
110 const playerId = harness.simulation.spawnCharacter(1, character);
138 const playerId = harness.simulation.spawnCharacter(1, character);
111 const ratId = harness.simulation.spawnEntity(mobComponents({
139 const ratId = harness.simulation.spawnEntity(mobComponents({
112 mobTypeId: MobId.rat,
140 mobTypeId: MobId.rat,
113 position: { tileX: 9, tileY: 8 }
141 tileX: 9,
142 tileY: 8
114 }));
143 }));
115 const worker = harness.simulation.workers[0];
144 const worker = harness.simulation.workers[0];
116 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(playerId));
145 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(playerId));
shared/definitions/items.js +25 −1
@@ -17,7 +17,9 @@ export const ItemId = Object.freeze({
17 17 filledCheque: 7,
18 18 coins: 8,
19 19 ...CraftingItemId,
20 lantern: 26
20 lantern: 26,
21 bones: 27,
22 skull: 28
21 23 });
22 24
23 25 export const EQUIPMENT_SLOT = Object.freeze({
@@ -181,6 +183,28 @@ export const ITEM_DEFINITIONS = Object.freeze({
181 183 lightRadiusTiles: 6
182 184 })
183 185 }),
186 [ItemId.bones]: Object.freeze({
187 itemId: ItemId.bones,
188 key: "bones",
189 displayName: "Bones",
190 description: "The remains of a fallen adventurer.",
191 seedValue: 1,
192 stackable: true,
193 maxStackSize: DEFAULT_MAX_STACK,
194 uniqueInstance: false,
195 category: "ingredient"
196 }),
197 [ItemId.skull]: Object.freeze({
198 itemId: ItemId.skull,
199 key: "skull",
200 displayName: "Skull",
201 description: "A grim reminder of an adventurer's death.",
202 seedValue: 1,
203 stackable: true,
204 maxStackSize: DEFAULT_MAX_STACK,
205 uniqueInstance: false,
206 category: "misc"
207 }),
184 208 ...CRAFTING_ITEM_STUBS
185 209 });
186 210
@@ -17,7 +17,9 @@ export const ItemId = Object.freeze({
17 filledCheque: 7,
17 filledCheque: 7,
18 coins: 8,
18 coins: 8,
19 ...CraftingItemId,
19 ...CraftingItemId,
20 lantern: 26
20 lantern: 26,
21 bones: 27,
22 skull: 28
21});
23});
22
24
23export const EQUIPMENT_SLOT = Object.freeze({
25export const EQUIPMENT_SLOT = Object.freeze({
@@ -181,6 +183,28 @@ export const ITEM_DEFINITIONS = Object.freeze({
181 lightRadiusTiles: 6
183 lightRadiusTiles: 6
182 })
184 })
183 }),
185 }),
186 [ItemId.bones]: Object.freeze({
187 itemId: ItemId.bones,
188 key: "bones",
189 displayName: "Bones",
190 description: "The remains of a fallen adventurer.",
191 seedValue: 1,
192 stackable: true,
193 maxStackSize: DEFAULT_MAX_STACK,
194 uniqueInstance: false,
195 category: "ingredient"
196 }),
197 [ItemId.skull]: Object.freeze({
198 itemId: ItemId.skull,
199 key: "skull",
200 displayName: "Skull",
201 description: "A grim reminder of an adventurer's death.",
202 seedValue: 1,
203 stackable: true,
204 maxStackSize: DEFAULT_MAX_STACK,
205 uniqueInstance: false,
206 category: "misc"
207 }),
184 ...CRAFTING_ITEM_STUBS
208 ...CRAFTING_ITEM_STUBS
185});
209});
186
210
shared/definitions/tiles.js +12 −1
@@ -7,7 +7,8 @@ export const BlockType = Object.freeze({
7 7 stoneWall: 1,
8 8 torch: 2,
9 9 spawner: 3,
10 bank: 4
10 bank: 4,
11 churchAltar: 5
11 12 });
12 13
13 14 export const GROUND_DEFINITIONS = Object.freeze({
@@ -69,6 +70,16 @@ export const BLOCK_DEFINITIONS = Object.freeze({
69 70 frames: 1,
70 71 framesPerRow: 1,
71 72 animationSpeed: 0
73 }),
74 [BlockType.churchAltar]: Object.freeze({
75 id: BlockType.churchAltar,
76 key: "church-altar",
77 displayName: "Church altar",
78 passable: false,
79 lightRangeTiles: 0,
80 frames: 1,
81 framesPerRow: 1,
82 animationSpeed: 0
72 83 })
73 84 });
74 85
@@ -7,7 +7,8 @@ export const BlockType = Object.freeze({
7 stoneWall: 1,
7 stoneWall: 1,
8 torch: 2,
8 torch: 2,
9 spawner: 3,
9 spawner: 3,
10 bank: 4
10 bank: 4,
11 churchAltar: 5
11});
12});
12
13
13export const GROUND_DEFINITIONS = Object.freeze({
14export const GROUND_DEFINITIONS = Object.freeze({
@@ -69,6 +70,16 @@ export const BLOCK_DEFINITIONS = Object.freeze({
69 frames: 1,
70 frames: 1,
70 framesPerRow: 1,
71 framesPerRow: 1,
71 animationSpeed: 0
72 animationSpeed: 0
73 }),
74 [BlockType.churchAltar]: Object.freeze({
75 id: BlockType.churchAltar,
76 key: "church-altar",
77 displayName: "Church altar",
78 passable: false,
79 lightRangeTiles: 0,
80 frames: 1,
81 framesPerRow: 1,
82 animationSpeed: 0
72 })
83 })
73});
84});
74
85
shared/items/inventory.js +5 −1
@@ -380,12 +380,16 @@ export function publicSlots (slots)
380 380 if (!slot)
381 381 { return null; }
382 382 const payload = attachOrigins(cloneStack(slot));
383 return {
383 const next = {
384 384 itemId: payload.itemId,
385 385 quantity: payload.quantity,
386 386 origins: payload.origins,
387 387 instance: payload.instance ?? null
388 388 };
389 // Cheque reservations keep chequeId so redeem can match the paper to vault goods.
390 if (payload.chequeId != null)
391 { next.chequeId = payload.chequeId; }
392 return next;
389 393 });
390 394 }
391 395
@@ -380,12 +380,16 @@ export function publicSlots (slots)
380 if (!slot)
380 if (!slot)
381 { return null; }
381 { return null; }
382 const payload = attachOrigins(cloneStack(slot));
382 const payload = attachOrigins(cloneStack(slot));
383 return {
383 const next = {
384 itemId: payload.itemId,
384 itemId: payload.itemId,
385 quantity: payload.quantity,
385 quantity: payload.quantity,
386 origins: payload.origins,
386 origins: payload.origins,
387 instance: payload.instance ?? null
387 instance: payload.instance ?? null
388 };
388 };
389 // Cheque reservations keep chequeId so redeem can match the paper to vault goods.
390 if (payload.chequeId != null)
391 { next.chequeId = payload.chequeId; }
392 return next;
389 });
393 });
390}
394}
391
395
shared/protocol/constants.js +3 −0
@@ -116,6 +116,9 @@ export const MessageType = Object.freeze({
116 116 combatHit: "COMBAT_HIT",
117 117 combatMiss: "COMBAT_MISS",
118 118 combatBlock: "COMBAT_BLOCK",
119 playerDied: "PLAYER_DIED",
120 respawn: "RESPAWN",
121 playerRespawned: "PLAYER_RESPAWNED",
119 122 follow: "FOLLOW",
120 123 cancelFollow: "CANCEL_FOLLOW",
121 124 sendPigeon: "SEND_PIGEON",
@@ -116,6 +116,9 @@ export const MessageType = Object.freeze({
116 combatHit: "COMBAT_HIT",
116 combatHit: "COMBAT_HIT",
117 combatMiss: "COMBAT_MISS",
117 combatMiss: "COMBAT_MISS",
118 combatBlock: "COMBAT_BLOCK",
118 combatBlock: "COMBAT_BLOCK",
119 playerDied: "PLAYER_DIED",
120 respawn: "RESPAWN",
121 playerRespawned: "PLAYER_RESPAWNED",
119 follow: "FOLLOW",
122 follow: "FOLLOW",
120 cancelFollow: "CANCEL_FOLLOW",
123 cancelFollow: "CANCEL_FOLLOW",
121 sendPigeon: "SEND_PIGEON",
124 sendPigeon: "SEND_PIGEON",
shared/skills/state.js +6 −1
@@ -1,6 +1,9 @@
1 1 import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS } 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);
6
4 7 export function emptySkillXp ()
5 8 {
6 9 const xp = {};
@@ -19,6 +22,8 @@ export function normalizeSkillXp (raw)
19 22 const value = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
20 23 xp[skillId] = Number.isSafeInteger(value) ? value : 0;
21 24 }
25 if (xp[SkillId.health] < STARTING_HEALTH_XP)
26 { xp[SkillId.health] = STARTING_HEALTH_XP; }
22 27 return xp;
23 28 }
24 29
@@ -31,7 +36,7 @@ export function normalizePlayerSkills (stored)
31 36 export function defaultPlayerSkills ()
32 37 {
33 38 return normalizePlayerSkills({
34 [SkillId.health]: totalXpForLevel(10)
39 [SkillId.health]: STARTING_HEALTH_XP
35 40 });
36 41 }
37 42
@@ -1,6 +1,9 @@
1import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS } from "../definitions/skills.js";
1import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS } 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. */
5export const STARTING_HEALTH_XP = totalXpForLevel(10);
6
4export function emptySkillXp ()
7export function emptySkillXp ()
5{
8{
6 const xp = {};
9 const xp = {};
@@ -19,6 +22,8 @@ export function normalizeSkillXp (raw)
19 const value = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
22 const value = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
20 xp[skillId] = Number.isSafeInteger(value) ? value : 0;
23 xp[skillId] = Number.isSafeInteger(value) ? value : 0;
21 }
24 }
25 if (xp[SkillId.health] < STARTING_HEALTH_XP)
26 { xp[SkillId.health] = STARTING_HEALTH_XP; }
22 return xp;
27 return xp;
23}
28}
24
29
@@ -31,7 +36,7 @@ export function normalizePlayerSkills (stored)
31export function defaultPlayerSkills ()
36export function defaultPlayerSkills ()
32{
37{
33 return normalizePlayerSkills({
38 return normalizePlayerSkills({
34 [SkillId.health]: totalXpForLevel(10)
39 [SkillId.health]: STARTING_HEALTH_XP
35 });
40 });
36}
41}
37
42