BlueGit

timfa questward

tweaks to sprites, shading

timfa Tim Falken · pushed by timfa

Authored 2026-08-26 · 2 months ago

Hash
48b50124d0fd1a1863197be34e4d41a322fc4831
Parent
1d5e7747
14 files changed +636 −65
client/assets/characters/player-body-female/player-body-female.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/characters/player-body-male/player-body-male.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/characters/ref-unisex-silhouette/silhouette.png added Binary file +0 −0

The contents of this binary file are not shown.

client/src/play/main.js +4 −0
@@ -999,6 +999,10 @@ async function main ()
999 999 { showError(message.message); }
1000 1000 social?.showError(message.message);
1001 1001 break;
1002 case MessageType.toast:
1003 if (playing)
1004 { toasts?.show(message.message); }
1005 break;
1002 1006 case MessageType.forceLogout:
1003 1007 returnToMenu(message.reason);
1004 1008 break;
@@ -999,6 +999,10 @@ async function main ()
999 { showError(message.message); }
999 { showError(message.message); }
1000 social?.showError(message.message);
1000 social?.showError(message.message);
1001 break;
1001 break;
1002 case MessageType.toast:
1003 if (playing)
1004 { toasts?.show(message.message); }
1005 break;
1002 case MessageType.forceLogout:
1006 case MessageType.forceLogout:
1003 returnToMenu(message.reason);
1007 returnToMenu(message.reason);
1004 break;
1008 break;
client/src/render/worldView.js +25 −2
@@ -263,6 +263,12 @@ export class WorldView
263 263 this.#rebuildChunk(snapshot);
264 264 this.#redrawPreview();
265 265 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
266 if (snapshot.staticOnly)
267 {
268 this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY);
269 this.#rebuildAllEdges();
270 return;
271 }
266 272 for (const entity of snapshot.entities ?? [])
267 273 { this.#upsertEntity(entity); }
268 274 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
@@ -276,6 +282,23 @@ export class WorldView
276 282 this.#rebuildAllEdges();
277 283 }
278 284
285 #stripChunkDynamic (chunkX, chunkY)
286 {
287 for (const [id, item] of [...this.groundItems.entries()])
288 {
289 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
290 { this.despawnGroundItem(id); }
291 }
292 for (const [id, entity] of [...this.entities.entries()])
293 {
294 if (id === this.localEntityId)
295 { continue; }
296 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
297 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
298 { this.despawnEntity(id); }
299 }
300 }
301
279 302 removeChunk (chunkX, chunkY)
280 303 {
281 304 const key = `${chunkX},${chunkY}`;
@@ -306,8 +329,8 @@ export class WorldView
306 329 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
307 330 { this.despawnGroundItem(id); }
308 331 }
309 // Server only sends unsubscribeChunk (not per-entity despawns) when a chunk
310 // leaves the 3×3 interest set — drop mobs/players that still sit on that chunk.
332 // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring.
333 // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots.
311 334 for (const [id, entity] of [...this.entities.entries()])
312 335 {
313 336 if (id === this.localEntityId)
@@ -263,6 +263,12 @@ export class WorldView
263 this.#rebuildChunk(snapshot);
263 this.#rebuildChunk(snapshot);
264 this.#redrawPreview();
264 this.#redrawPreview();
265 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
265 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
266 if (snapshot.staticOnly)
267 {
268 this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY);
269 this.#rebuildAllEdges();
270 return;
271 }
266 for (const entity of snapshot.entities ?? [])
272 for (const entity of snapshot.entities ?? [])
267 { this.#upsertEntity(entity); }
273 { this.#upsertEntity(entity); }
268 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
274 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
@@ -276,6 +282,23 @@ export class WorldView
276 this.#rebuildAllEdges();
282 this.#rebuildAllEdges();
277 }
283 }
278
284
285 #stripChunkDynamic (chunkX, chunkY)
286 {
287 for (const [id, item] of [...this.groundItems.entries()])
288 {
289 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
290 { this.despawnGroundItem(id); }
291 }
292 for (const [id, entity] of [...this.entities.entries()])
293 {
294 if (id === this.localEntityId)
295 { continue; }
296 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
297 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
298 { this.despawnEntity(id); }
299 }
300 }
301
279 removeChunk (chunkX, chunkY)
302 removeChunk (chunkX, chunkY)
280 {
303 {
281 const key = `${chunkX},${chunkY}`;
304 const key = `${chunkX},${chunkY}`;
@@ -306,8 +329,8 @@ export class WorldView
306 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
329 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
307 { this.despawnGroundItem(id); }
330 { this.despawnGroundItem(id); }
308 }
331 }
309 // Server only sends unsubscribeChunk (not per-entity despawns) when a chunk
332 // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring.
310 // leaves the 3×3 interest set — drop mobs/players that still sit on that chunk.
333 // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots.
311 for (const [id, entity] of [...this.entities.entries()])
334 for (const [id, entity] of [...this.entities.entries()])
312 {
335 {
313 if (id === this.localEntityId)
336 if (id === this.localEntityId)
server/src/courier/service.js +235 −35
@@ -7,6 +7,16 @@ 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 9 import { findReservedChequeIndex } from "../items/bags.js";
10 import { randomUUID } from "node:crypto";
11 import {
12 BANK_LETTER_AUTHOR,
13 bankRestNoticeLetterBody,
14 isBankRestNoticeLetter,
15 isCentralExchangeLetter,
16 itemNameForNotice,
17 mergeBankRestNoticeLines,
18 sourceNameForVaultDeposit
19 } from "../../../shared/courier/bankNotice.js";
10 20
11 21 export class CourierService
12 22 {
@@ -126,6 +136,7 @@ export class CourierService
126 136 senderCharacterId: characterId,
127 137 destinationKind: dest.kind,
128 138 destinationCharacterId: dest.characterId ?? null,
139 vaultCharacterId: dest.vaultCharacterId ?? null,
129 140 cargo: takenCargo,
130 141 originX: originTileX + 0.5,
131 142 originY: originTileY + 0.5,
@@ -138,14 +149,34 @@ export class CourierService
138 149 return { transit, bag };
139 150 }
140 151
141 /** Market / system dispatch already holding cargo (no bag take). */
142 dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo })
152 /**
153 * Market / system dispatch already holding cargo (no bag take).
154 * When the recipient is offline, holds delivery until login (CE letters, etc.).
155 */
156 dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo, vaultCharacterId = null })
143 157 {
158 const recipientId = vaultCharacterId ?? senderCharacterId;
159 if (!this.simulation.isCharacterOnline(recipientId))
160 {
161 const dest = this.#resolveDestination(destination, originTileX, originTileY);
162 this.stateDb.insertHeldCourierDelivery({
163 characterId: recipientId,
164 senderCharacterId,
165 originTileX,
166 originTileY,
167 destinationKind: dest.kind,
168 destinationCharacterId: dest.characterId ?? recipientId,
169 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? recipientId,
170 cargo
171 });
172 return null;
173 }
144 174 const dest = this.#resolveDestination(destination, originTileX, originTileY);
145 175 return this.stateDb.insertCourierTransit({
146 176 senderCharacterId,
147 177 destinationKind: dest.kind,
148 178 destinationCharacterId: dest.characterId ?? null,
179 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? null,
149 180 cargo,
150 181 originX: originTileX + 0.5,
151 182 originY: originTileY + 0.5,
@@ -157,6 +188,32 @@ export class CourierService
157 188 });
158 189 }
159 190
191 /** Flush offline-held deliveries and send a bank resting notice when the player enters the world. */
192 onCharacterEnteredWorld (characterId, tileX, tileY)
193 {
194 for (const held of this.stateDb.listHeldCourierDeliveries(characterId))
195 {
196 this.stateDb.deleteHeldCourierDelivery(held.holdId);
197 const row = this.stateDb.getCharacter(held.destinationCharacterId ?? characterId);
198 this.dispatchHeldCargo({
199 senderCharacterId: held.senderCharacterId,
200 originTileX: held.originTileX,
201 originTileY: held.originTileY,
202 destination: held.destinationKind === "bank"
203 ? { kind: "bank" }
204 : {
205 kind: "player",
206 firstName: row?.first_name ?? "Unknown",
207 lastName: row?.last_name ?? ""
208 },
209 cargo: held.cargo,
210 vaultCharacterId: held.vaultCharacterId ?? characterId
211 });
212 }
213 const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY);
214 void noticeTransit;
215 }
216
160 217 step (now, dt)
161 218 {
162 219 const events = [];
@@ -203,12 +260,19 @@ export class CourierService
203 260 }
204 261 return;
205 262 }
206 const character = this.stateDb.getCharacter(transit.destinationCharacterId);
207 if (character)
208 {
209 transit.destX = character.tile_x + 0.5;
210 transit.destY = character.tile_y + 0.5;
211 }
263 this.#routeTransitToBank(transit, transit.destinationCharacterId);
264 }
265
266 #routeTransitToBank (transit, vaultCharacterId)
267 {
268 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
269 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
270 if (!bank)
271 { return; }
272 transit.destinationKind = "bank";
273 transit.vaultCharacterId = vaultCharacterId ?? transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId;
274 transit.destX = bank.tileX + 0.5;
275 transit.destY = bank.tileY + 0.5;
212 276 }
213 277
214 278 #resolveDestination (destination, originTileX, originTileY)
@@ -223,12 +287,30 @@ export class CourierService
223 287 throw error;
224 288 }
225 289 const onlineId = this.simulation.characterEntities.get(character.character_id);
226 const pos = onlineId ? this.simulation.positionOf(onlineId) : null;
290 if (!onlineId)
291 {
292 const bank = this.nearestBank(originTileX, originTileY)
293 ?? this.nearestBank(character.tile_x, character.tile_y);
294 if (!bank)
295 {
296 const error = new Error("No bank exists in the world yet.");
297 error.userFacing = true;
298 throw error;
299 }
300 return {
301 kind: "bank",
302 characterId: character.character_id,
303 vaultCharacterId: character.character_id,
304 tileX: bank.tileX,
305 tileY: bank.tileY
306 };
307 }
308 const pos = this.simulation.positionOf(onlineId);
227 309 return {
228 310 kind: "player",
229 311 characterId: character.character_id,
230 tileX: pos?.tileX ?? character.tile_x,
231 tileY: pos?.tileY ?? character.tile_y
312 tileX: pos.tileX,
313 tileY: pos.tileY
232 314 };
233 315 }
234 316 if (destination?.kind === "bank")
@@ -330,7 +412,16 @@ export class CourierService
330 412 }
331 413
332 414 if (transit.destinationKind === "bank")
333 { this.#creditVault(transit.senderCharacterId, transit.cargo); }
415 {
416 const vaultCharacterId = transit.vaultCharacterId
417 ?? transit.destinationCharacterId
418 ?? transit.senderCharacterId;
419 const toast = this.#creditVault(vaultCharacterId, transit.cargo, {
420 senderCharacterId: transit.senderCharacterId
421 });
422 if (toast)
423 { events.push(toast); }
424 }
334 425 else if (transit.destinationKind === "player")
335 426 {
336 427 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
@@ -346,6 +437,7 @@ export class CourierService
346 437 transit.destY = bank.tileY + 0.5;
347 438 transit.traveled = 0;
348 439 transit.destinationKind = "bank";
440 transit.vaultCharacterId = transit.destinationCharacterId;
349 441 transit.updatedAt = now;
350 442 this.stateDb.updateCourierTransit(transit);
351 443 events.push({
@@ -355,7 +447,11 @@ export class CourierService
355 447 });
356 448 return events;
357 449 }
358 this.#creditVault(transit.destinationCharacterId, transit.cargo);
450 const toast = this.#creditVault(transit.destinationCharacterId, transit.cargo, {
451 senderCharacterId: transit.senderCharacterId
452 });
453 if (toast)
454 { events.push(toast); }
359 455 }
360 456 }
361 457
@@ -390,32 +486,25 @@ export class CourierService
390 486 {
391 487 cargo = this.#normalizeCargo(cargo);
392 488 const onlineId = this.simulation.characterEntities.get(characterId);
393 if (onlineId)
394 {
395 if (cargo.kind === "item")
396 {
397 const bag = this.simulation.bagOf(onlineId);
398 if (!bag)
399 { return false; }
400 const def = itemDefinition(cargo.stack.itemId);
401 const result = insertStack(bag.inventory, cargo.stack, def);
402 if (!result.ok || result.remainder)
403 { return false; }
404 bag.inventory = result.slots;
405 this.#persistBag(characterId, bag);
406 return true;
407 }
408 }
409
489 if (!onlineId)
490 { return false; }
410 491 if (cargo.kind === "item")
411 492 {
412 this.#creditVault(characterId, cargo);
493 const bag = this.simulation.bagOf(onlineId);
494 if (!bag)
495 { return false; }
496 const def = itemDefinition(cargo.stack.itemId);
497 const result = insertStack(bag.inventory, cargo.stack, def);
498 if (!result.ok || result.remainder)
499 { return false; }
500 bag.inventory = result.slots;
501 this.#persistBag(characterId, bag);
413 502 return true;
414 503 }
415 504 return false;
416 505 }
417 506
418 #creditVault (characterId, cargo)
507 #creditVault (characterId, cargo, { senderCharacterId = null, recordRestNotice = true } = {})
419 508 {
420 509 cargo = this.#normalizeCargo(cargo);
421 510 const onlineId = this.simulation.characterEntities.get(characterId);
@@ -423,15 +512,24 @@ export class CourierService
423 512 ? this.simulation.bagOf(onlineId)
424 513 : this.stateDb.getBag(characterId);
425 514 if (!bag)
426 { return; }
515 { return null; }
427 516 if (cargo.kind !== "item")
428 { return; }
517 { return null; }
429 518
430 519 const stack = cargo.stack;
520 const isCeLetter = stack?.itemId === ItemId.letter && isCentralExchangeLetter(stack.instance);
521 const isRestNoticeLetter = stack?.itemId === ItemId.letter && isBankRestNoticeLetter(stack.instance);
522
431 523 if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
432 524 {
433 525 this.#redeemChequeIntoVault(characterId, bag, stack);
434 return;
526 this.#maybeRecordRestNotice({
527 characterId,
528 stack,
529 senderCharacterId,
530 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
531 });
532 return null;
435 533 }
436 534
437 535 const def = itemDefinition(stack.itemId);
@@ -444,6 +542,39 @@ export class CourierService
444 542 bag.vault = result.slots;
445 543 bag.vaultReserved = vault.reserved;
446 544 this.#persistBag(characterId, bag);
545
546 this.#maybeRecordRestNotice({
547 characterId,
548 stack,
549 senderCharacterId,
550 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
551 });
552
553 if (onlineId && isRestNoticeLetter)
554 {
555 return {
556 type: "toast",
557 characterId,
558 message: "A letter arrived for you at the bank."
559 };
560 }
561 return null;
562 }
563
564 #maybeRecordRestNotice ({ characterId, stack, senderCharacterId, recordRestNotice })
565 {
566 if (!recordRestNotice || !stack)
567 { return; }
568 const sender = senderCharacterId ? this.stateDb.getCharacter(senderCharacterId) : null;
569 const senderDisplayName = sender
570 ? `${sender.first_name} ${sender.last_name}`.trim()
571 : null;
572 this.stateDb.appendBankRestNotice(characterId, {
573 itemId: stack.itemId,
574 itemName: itemNameForNotice(stack),
575 quantity: stack.quantity | 0 || 1,
576 sourceName: sourceNameForVaultDeposit(stack, senderCharacterId, senderDisplayName)
577 });
447 578 }
448 579
449 580 /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */
@@ -502,6 +633,18 @@ export class CourierService
502 633 bag.vault = inserted.slots;
503 634 bag.vaultReserved = vault.reserved;
504 635 this.#persistBag(characterId, bag);
636 this.#maybeRecordRestNotice({
637 characterId,
638 stack: {
639 itemId: reservedStack.itemId,
640 quantity: reservedStack.quantity,
641 origin: reservedStack.origin ?? null,
642 origins: reservedStack.origins ?? null,
643 instance: reservedStack.instance ?? null
644 },
645 senderCharacterId: null,
646 recordRestNotice: !this.simulation.characterEntities.get(characterId)
647 });
505 648 }
506 649
507 650 #persistBag (characterId, bag)
@@ -514,4 +657,61 @@ export class CourierService
514 657 this.simulation.pushInventory(characterId, bag);
515 658 }
516 659 }
660
661 #characterDisplayName (characterId)
662 {
663 const row = this.stateDb.getCharacter(characterId);
664 return {
665 firstName: row?.first_name ?? "Unknown",
666 lastName: row?.last_name ?? "",
667 full: row ? `${row.first_name} ${row.last_name}`.trim() : "Adventurer"
668 };
669 }
670
671 #dispatchBankRestNotice (characterId, tileX, tileY)
672 {
673 const entries = this.stateDb.listBankRestNotices(characterId);
674 if (!entries.length)
675 { return null; }
676 const bank = this.nearestBank(tileX, tileY);
677 if (!bank)
678 { return null; }
679
680 const lines = mergeBankRestNoticeLines(entries.map((entry) => ({
681 quantity: entry.quantity,
682 itemName: entry.itemName,
683 sourceName: entry.sourceName
684 })));
685 const { full: playerName } = this.#characterDisplayName(characterId);
686 const body = bankRestNoticeLetterBody({ playerName, lines });
687 const stack = {
688 itemId: ItemId.letter,
689 quantity: 1,
690 instance: {
691 kind: "letter",
692 letterId: randomUUID(),
693 authorCharacterId: 0,
694 authorDisplayName: BANK_LETTER_AUTHOR,
695 body,
696 opened: false,
697 writtenAt: Date.now(),
698 bankRestNotice: true
699 }
700 };
701 this.stateDb.clearBankRestNotices(characterId);
702 return this.stateDb.insertCourierTransit({
703 senderCharacterId: characterId,
704 destinationKind: "player",
705 destinationCharacterId: characterId,
706 vaultCharacterId: characterId,
707 cargo: { kind: "item", stack },
708 originX: bank.tileX + 0.5,
709 originY: bank.tileY + 0.5,
710 destX: tileX + 0.5,
711 destY: tileY + 0.5,
712 traveled: 0,
713 status: "in_transit",
714 entityId: null
715 });
716 }
517 717 }
@@ -7,6 +7,16 @@ import { 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";
9import { findReservedChequeIndex } from "../items/bags.js";
10import { randomUUID } from "node:crypto";
11import {
12 BANK_LETTER_AUTHOR,
13 bankRestNoticeLetterBody,
14 isBankRestNoticeLetter,
15 isCentralExchangeLetter,
16 itemNameForNotice,
17 mergeBankRestNoticeLines,
18 sourceNameForVaultDeposit
19} from "../../../shared/courier/bankNotice.js";
10
20
11export class CourierService
21export class CourierService
12{
22{
@@ -126,6 +136,7 @@ export class CourierService
126 senderCharacterId: characterId,
136 senderCharacterId: characterId,
127 destinationKind: dest.kind,
137 destinationKind: dest.kind,
128 destinationCharacterId: dest.characterId ?? null,
138 destinationCharacterId: dest.characterId ?? null,
139 vaultCharacterId: dest.vaultCharacterId ?? null,
129 cargo: takenCargo,
140 cargo: takenCargo,
130 originX: originTileX + 0.5,
141 originX: originTileX + 0.5,
131 originY: originTileY + 0.5,
142 originY: originTileY + 0.5,
@@ -138,14 +149,34 @@ export class CourierService
138 return { transit, bag };
149 return { transit, bag };
139 }
150 }
140
151
141 /** Market / system dispatch already holding cargo (no bag take). */
152 /**
142 dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo })
153 * Market / system dispatch already holding cargo (no bag take).
154 * When the recipient is offline, holds delivery until login (CE letters, etc.).
155 */
156 dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo, vaultCharacterId = null })
143 {
157 {
158 const recipientId = vaultCharacterId ?? senderCharacterId;
159 if (!this.simulation.isCharacterOnline(recipientId))
160 {
161 const dest = this.#resolveDestination(destination, originTileX, originTileY);
162 this.stateDb.insertHeldCourierDelivery({
163 characterId: recipientId,
164 senderCharacterId,
165 originTileX,
166 originTileY,
167 destinationKind: dest.kind,
168 destinationCharacterId: dest.characterId ?? recipientId,
169 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? recipientId,
170 cargo
171 });
172 return null;
173 }
144 const dest = this.#resolveDestination(destination, originTileX, originTileY);
174 const dest = this.#resolveDestination(destination, originTileX, originTileY);
145 return this.stateDb.insertCourierTransit({
175 return this.stateDb.insertCourierTransit({
146 senderCharacterId,
176 senderCharacterId,
147 destinationKind: dest.kind,
177 destinationKind: dest.kind,
148 destinationCharacterId: dest.characterId ?? null,
178 destinationCharacterId: dest.characterId ?? null,
179 vaultCharacterId: vaultCharacterId ?? dest.vaultCharacterId ?? null,
149 cargo,
180 cargo,
150 originX: originTileX + 0.5,
181 originX: originTileX + 0.5,
151 originY: originTileY + 0.5,
182 originY: originTileY + 0.5,
@@ -157,6 +188,32 @@ export class CourierService
157 });
188 });
158 }
189 }
159
190
191 /** Flush offline-held deliveries and send a bank resting notice when the player enters the world. */
192 onCharacterEnteredWorld (characterId, tileX, tileY)
193 {
194 for (const held of this.stateDb.listHeldCourierDeliveries(characterId))
195 {
196 this.stateDb.deleteHeldCourierDelivery(held.holdId);
197 const row = this.stateDb.getCharacter(held.destinationCharacterId ?? characterId);
198 this.dispatchHeldCargo({
199 senderCharacterId: held.senderCharacterId,
200 originTileX: held.originTileX,
201 originTileY: held.originTileY,
202 destination: held.destinationKind === "bank"
203 ? { kind: "bank" }
204 : {
205 kind: "player",
206 firstName: row?.first_name ?? "Unknown",
207 lastName: row?.last_name ?? ""
208 },
209 cargo: held.cargo,
210 vaultCharacterId: held.vaultCharacterId ?? characterId
211 });
212 }
213 const noticeTransit = this.#dispatchBankRestNotice(characterId, tileX, tileY);
214 void noticeTransit;
215 }
216
160 step (now, dt)
217 step (now, dt)
161 {
218 {
162 const events = [];
219 const events = [];
@@ -203,12 +260,19 @@ export class CourierService
203 }
260 }
204 return;
261 return;
205 }
262 }
206 const character = this.stateDb.getCharacter(transit.destinationCharacterId);
263 this.#routeTransitToBank(transit, transit.destinationCharacterId);
207 if (character)
264 }
208 {
265
209 transit.destX = character.tile_x + 0.5;
266 #routeTransitToBank (transit, vaultCharacterId)
210 transit.destY = character.tile_y + 0.5;
267 {
211 }
268 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
269 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
270 if (!bank)
271 { return; }
272 transit.destinationKind = "bank";
273 transit.vaultCharacterId = vaultCharacterId ?? transit.vaultCharacterId ?? transit.destinationCharacterId ?? transit.senderCharacterId;
274 transit.destX = bank.tileX + 0.5;
275 transit.destY = bank.tileY + 0.5;
212 }
276 }
213
277
214 #resolveDestination (destination, originTileX, originTileY)
278 #resolveDestination (destination, originTileX, originTileY)
@@ -223,12 +287,30 @@ export class CourierService
223 throw error;
287 throw error;
224 }
288 }
225 const onlineId = this.simulation.characterEntities.get(character.character_id);
289 const onlineId = this.simulation.characterEntities.get(character.character_id);
226 const pos = onlineId ? this.simulation.positionOf(onlineId) : null;
290 if (!onlineId)
291 {
292 const bank = this.nearestBank(originTileX, originTileY)
293 ?? this.nearestBank(character.tile_x, character.tile_y);
294 if (!bank)
295 {
296 const error = new Error("No bank exists in the world yet.");
297 error.userFacing = true;
298 throw error;
299 }
300 return {
301 kind: "bank",
302 characterId: character.character_id,
303 vaultCharacterId: character.character_id,
304 tileX: bank.tileX,
305 tileY: bank.tileY
306 };
307 }
308 const pos = this.simulation.positionOf(onlineId);
227 return {
309 return {
228 kind: "player",
310 kind: "player",
229 characterId: character.character_id,
311 characterId: character.character_id,
230 tileX: pos?.tileX ?? character.tile_x,
312 tileX: pos.tileX,
231 tileY: pos?.tileY ?? character.tile_y
313 tileY: pos.tileY
232 };
314 };
233 }
315 }
234 if (destination?.kind === "bank")
316 if (destination?.kind === "bank")
@@ -330,7 +412,16 @@ export class CourierService
330 }
412 }
331
413
332 if (transit.destinationKind === "bank")
414 if (transit.destinationKind === "bank")
333 { this.#creditVault(transit.senderCharacterId, transit.cargo); }
415 {
416 const vaultCharacterId = transit.vaultCharacterId
417 ?? transit.destinationCharacterId
418 ?? transit.senderCharacterId;
419 const toast = this.#creditVault(vaultCharacterId, transit.cargo, {
420 senderCharacterId: transit.senderCharacterId
421 });
422 if (toast)
423 { events.push(toast); }
424 }
334 else if (transit.destinationKind === "player")
425 else if (transit.destinationKind === "player")
335 {
426 {
336 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
427 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
@@ -346,6 +437,7 @@ export class CourierService
346 transit.destY = bank.tileY + 0.5;
437 transit.destY = bank.tileY + 0.5;
347 transit.traveled = 0;
438 transit.traveled = 0;
348 transit.destinationKind = "bank";
439 transit.destinationKind = "bank";
440 transit.vaultCharacterId = transit.destinationCharacterId;
349 transit.updatedAt = now;
441 transit.updatedAt = now;
350 this.stateDb.updateCourierTransit(transit);
442 this.stateDb.updateCourierTransit(transit);
351 events.push({
443 events.push({
@@ -355,7 +447,11 @@ export class CourierService
355 });
447 });
356 return events;
448 return events;
357 }
449 }
358 this.#creditVault(transit.destinationCharacterId, transit.cargo);
450 const toast = this.#creditVault(transit.destinationCharacterId, transit.cargo, {
451 senderCharacterId: transit.senderCharacterId
452 });
453 if (toast)
454 { events.push(toast); }
359 }
455 }
360 }
456 }
361
457
@@ -390,32 +486,25 @@ export class CourierService
390 {
486 {
391 cargo = this.#normalizeCargo(cargo);
487 cargo = this.#normalizeCargo(cargo);
392 const onlineId = this.simulation.characterEntities.get(characterId);
488 const onlineId = this.simulation.characterEntities.get(characterId);
393 if (onlineId)
489 if (!onlineId)
394 {
490 { return false; }
395 if (cargo.kind === "item")
396 {
397 const bag = this.simulation.bagOf(onlineId);
398 if (!bag)
399 { return false; }
400 const def = itemDefinition(cargo.stack.itemId);
401 const result = insertStack(bag.inventory, cargo.stack, def);
402 if (!result.ok || result.remainder)
403 { return false; }
404 bag.inventory = result.slots;
405 this.#persistBag(characterId, bag);
406 return true;
407 }
408 }
409
410 if (cargo.kind === "item")
491 if (cargo.kind === "item")
411 {
492 {
412 this.#creditVault(characterId, cargo);
493 const bag = this.simulation.bagOf(onlineId);
494 if (!bag)
495 { return false; }
496 const def = itemDefinition(cargo.stack.itemId);
497 const result = insertStack(bag.inventory, cargo.stack, def);
498 if (!result.ok || result.remainder)
499 { return false; }
500 bag.inventory = result.slots;
501 this.#persistBag(characterId, bag);
413 return true;
502 return true;
414 }
503 }
415 return false;
504 return false;
416 }
505 }
417
506
418 #creditVault (characterId, cargo)
507 #creditVault (characterId, cargo, { senderCharacterId = null, recordRestNotice = true } = {})
419 {
508 {
420 cargo = this.#normalizeCargo(cargo);
509 cargo = this.#normalizeCargo(cargo);
421 const onlineId = this.simulation.characterEntities.get(characterId);
510 const onlineId = this.simulation.characterEntities.get(characterId);
@@ -423,15 +512,24 @@ export class CourierService
423 ? this.simulation.bagOf(onlineId)
512 ? this.simulation.bagOf(onlineId)
424 : this.stateDb.getBag(characterId);
513 : this.stateDb.getBag(characterId);
425 if (!bag)
514 if (!bag)
426 { return; }
515 { return null; }
427 if (cargo.kind !== "item")
516 if (cargo.kind !== "item")
428 { return; }
517 { return null; }
429
518
430 const stack = cargo.stack;
519 const stack = cargo.stack;
520 const isCeLetter = stack?.itemId === ItemId.letter && isCentralExchangeLetter(stack.instance);
521 const isRestNoticeLetter = stack?.itemId === ItemId.letter && isBankRestNoticeLetter(stack.instance);
522
431 if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
523 if (stack?.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
432 {
524 {
433 this.#redeemChequeIntoVault(characterId, bag, stack);
525 this.#redeemChequeIntoVault(characterId, bag, stack);
434 return;
526 this.#maybeRecordRestNotice({
527 characterId,
528 stack,
529 senderCharacterId,
530 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
531 });
532 return null;
435 }
533 }
436
534
437 const def = itemDefinition(stack.itemId);
535 const def = itemDefinition(stack.itemId);
@@ -444,6 +542,39 @@ export class CourierService
444 bag.vault = result.slots;
542 bag.vault = result.slots;
445 bag.vaultReserved = vault.reserved;
543 bag.vaultReserved = vault.reserved;
446 this.#persistBag(characterId, bag);
544 this.#persistBag(characterId, bag);
545
546 this.#maybeRecordRestNotice({
547 characterId,
548 stack,
549 senderCharacterId,
550 recordRestNotice: recordRestNotice && !onlineId && !isCeLetter && !isRestNoticeLetter
551 });
552
553 if (onlineId && isRestNoticeLetter)
554 {
555 return {
556 type: "toast",
557 characterId,
558 message: "A letter arrived for you at the bank."
559 };
560 }
561 return null;
562 }
563
564 #maybeRecordRestNotice ({ characterId, stack, senderCharacterId, recordRestNotice })
565 {
566 if (!recordRestNotice || !stack)
567 { return; }
568 const sender = senderCharacterId ? this.stateDb.getCharacter(senderCharacterId) : null;
569 const senderDisplayName = sender
570 ? `${sender.first_name} ${sender.last_name}`.trim()
571 : null;
572 this.stateDb.appendBankRestNotice(characterId, {
573 itemId: stack.itemId,
574 itemName: itemNameForNotice(stack),
575 quantity: stack.quantity | 0 || 1,
576 sourceName: sourceNameForVaultDeposit(stack, senderCharacterId, senderDisplayName)
577 });
447 }
578 }
448
579
449 /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */
580 /** Pigeon/bank delivery of a filled cheque deposits the reserved goods, not the paper. */
@@ -502,6 +633,18 @@ export class CourierService
502 bag.vault = inserted.slots;
633 bag.vault = inserted.slots;
503 bag.vaultReserved = vault.reserved;
634 bag.vaultReserved = vault.reserved;
504 this.#persistBag(characterId, bag);
635 this.#persistBag(characterId, bag);
636 this.#maybeRecordRestNotice({
637 characterId,
638 stack: {
639 itemId: reservedStack.itemId,
640 quantity: reservedStack.quantity,
641 origin: reservedStack.origin ?? null,
642 origins: reservedStack.origins ?? null,
643 instance: reservedStack.instance ?? null
644 },
645 senderCharacterId: null,
646 recordRestNotice: !this.simulation.characterEntities.get(characterId)
647 });
505 }
648 }
506
649
507 #persistBag (characterId, bag)
650 #persistBag (characterId, bag)
@@ -514,4 +657,61 @@ export class CourierService
514 this.simulation.pushInventory(characterId, bag);
657 this.simulation.pushInventory(characterId, bag);
515 }
658 }
516 }
659 }
660
661 #characterDisplayName (characterId)
662 {
663 const row = this.stateDb.getCharacter(characterId);
664 return {
665 firstName: row?.first_name ?? "Unknown",
666 lastName: row?.last_name ?? "",
667 full: row ? `${row.first_name} ${row.last_name}`.trim() : "Adventurer"
668 };
669 }
670
671 #dispatchBankRestNotice (characterId, tileX, tileY)
672 {
673 const entries = this.stateDb.listBankRestNotices(characterId);
674 if (!entries.length)
675 { return null; }
676 const bank = this.nearestBank(tileX, tileY);
677 if (!bank)
678 { return null; }
679
680 const lines = mergeBankRestNoticeLines(entries.map((entry) => ({
681 quantity: entry.quantity,
682 itemName: entry.itemName,
683 sourceName: entry.sourceName
684 })));
685 const { full: playerName } = this.#characterDisplayName(characterId);
686 const body = bankRestNoticeLetterBody({ playerName, lines });
687 const stack = {
688 itemId: ItemId.letter,
689 quantity: 1,
690 instance: {
691 kind: "letter",
692 letterId: randomUUID(),
693 authorCharacterId: 0,
694 authorDisplayName: BANK_LETTER_AUTHOR,
695 body,
696 opened: false,
697 writtenAt: Date.now(),
698 bankRestNotice: true
699 }
700 };
701 this.stateDb.clearBankRestNotices(characterId);
702 return this.stateDb.insertCourierTransit({
703 senderCharacterId: characterId,
704 destinationKind: "player",
705 destinationCharacterId: characterId,
706 vaultCharacterId: characterId,
707 cargo: { kind: "item", stack },
708 originX: bank.tileX + 0.5,
709 originY: bank.tileY + 0.5,
710 destX: tileX + 0.5,
711 destY: tileY + 0.5,
712 traveled: 0,
713 status: "in_transit",
714 entityId: null
715 });
716 }
517}
717}
server/src/gateway/websocket.js +36 −16
@@ -1,7 +1,7 @@
1 1 import { WebSocketServer } from "ws";
2 2 import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3 3 import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
4 import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5 5 import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6 6 import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7 7 import { publicSkillsView } from "../../../shared/skills/state.js";
@@ -24,7 +24,10 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
24 24 authSubject: identity.authSubject,
25 25 characterId: null,
26 26 entityId: null,
27 subscribed: new Set()
27 /** Chunks where entity / ground-item replication is active (3×3). */
28 entitySubscribed: new Set(),
29 /** Chunks with map + baked lighting only (5×5). */
30 staticSubscribed: new Set()
28 31 };
29 32 auth.register(session);
30 33 sessions.set(session.id, session);
@@ -672,7 +675,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
672 675 publishReplication(simulation.drainReplication());
673 676 session.characterId = null;
674 677 session.entityId = null;
675 session.subscribed.clear();
678 session.entitySubscribed.clear();
679 session.staticSubscribed.clear();
676 680 }
677 681
678 682 function syncSubscriptions (session, forceSnapshots)
@@ -683,26 +687,34 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
683 687 if (!position)
684 688 { return; }
685 689
686 const next = new Set(
687 visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS)
688 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
689 );
690 for (const key of session.subscribed)
690 const centerChunkX = tileToChunk(position.tileX);
691 const centerChunkY = tileToChunk(position.tileY);
692 const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS);
693 const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS);
694 const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
695 const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
696
697 for (const key of session.staticSubscribed)
691 698 {
692 if (!next.has(key))
699 if (!staticNext.has(key))
693 700 {
694 701 const [chunkX, chunkY] = key.split(",").map(Number);
695 702 send(session, { type: MessageType.unsubscribeChunk, chunkX, chunkY });
696 703 }
697 704 }
698 const snapshots = simulation.snapshotFor(session.entityId);
705
706 const snapshots = simulation.snapshotsForView(session.entityId);
699 707 for (const snapshot of snapshots)
700 708 {
701 709 const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
702 if (forceSnapshots || !session.subscribed.has(key))
703 { send(session, { type: MessageType.chunkSnapshot, ...snapshot }); }
710 const entityChanged = entityNext.has(key) !== session.entitySubscribed.has(key);
711 if (forceSnapshots || !session.staticSubscribed.has(key) || entityChanged)
712 {
713 send(session, { type: MessageType.chunkSnapshot, ...snapshot });
714 }
704 715 }
705 session.subscribed = next;
716 session.entitySubscribed = entityNext;
717 session.staticSubscribed = staticNext;
706 718 }
707 719
708 720 function requirePlaying (session)
@@ -836,6 +848,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
836 848 });
837 849 continue;
838 850 }
851 if (event.type === "toast")
852 {
853 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
854 if (session)
855 { send(session, { type: MessageType.toast, message: event.message }); }
856 continue;
857 }
839 858 if (event.type === "pigeon-delivered")
840 859 {
841 860 for (const session of sessions.values())
@@ -1042,8 +1061,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1042 1061 {
1043 1062 if (!session.entityId)
1044 1063 { continue; }
1045 const seesFrom = fromKey ? session.subscribed.has(fromKey) : false;
1046 const seesTo = session.subscribed.has(toKey);
1064 const seesFrom = fromKey ? session.entitySubscribed.has(fromKey) : false;
1065 const seesTo = session.entitySubscribed.has(toKey);
1066 const seesStaticTo = session.staticSubscribed.has(toKey);
1047 1067 if (event.type === "entity-spawn")
1048 1068 {
1049 1069 if (session.entityId === event.entityId || !seesTo)
@@ -1156,7 +1176,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1156 1176 }
1157 1177 if (event.type === "chunk-delta")
1158 1178 {
1159 if (!seesTo)
1179 if (!seesStaticTo)
1160 1180 { continue; }
1161 1181 send(session, {
1162 1182 type: MessageType.chunkDelta,
@@ -1,7 +1,7 @@
1import { WebSocketServer } from "ws";
1import { WebSocketServer } from "ws";
2import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
2import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
4import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
5import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
6import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import { publicSkillsView } from "../../../shared/skills/state.js";
7import { publicSkillsView } from "../../../shared/skills/state.js";
@@ -24,7 +24,10 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
24 authSubject: identity.authSubject,
24 authSubject: identity.authSubject,
25 characterId: null,
25 characterId: null,
26 entityId: null,
26 entityId: null,
27 subscribed: new Set()
27 /** Chunks where entity / ground-item replication is active (3×3). */
28 entitySubscribed: new Set(),
29 /** Chunks with map + baked lighting only (5×5). */
30 staticSubscribed: new Set()
28 };
31 };
29 auth.register(session);
32 auth.register(session);
30 sessions.set(session.id, session);
33 sessions.set(session.id, session);
@@ -672,7 +675,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
672 publishReplication(simulation.drainReplication());
675 publishReplication(simulation.drainReplication());
673 session.characterId = null;
676 session.characterId = null;
674 session.entityId = null;
677 session.entityId = null;
675 session.subscribed.clear();
678 session.entitySubscribed.clear();
679 session.staticSubscribed.clear();
676 }
680 }
677
681
678 function syncSubscriptions (session, forceSnapshots)
682 function syncSubscriptions (session, forceSnapshots)
@@ -683,26 +687,34 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
683 if (!position)
687 if (!position)
684 { return; }
688 { return; }
685
689
686 const next = new Set(
690 const centerChunkX = tileToChunk(position.tileX);
687 visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS)
691 const centerChunkY = tileToChunk(position.tileY);
688 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
692 const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS);
689 );
693 const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS);
690 for (const key of session.subscribed)
694 const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
695 const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
696
697 for (const key of session.staticSubscribed)
691 {
698 {
692 if (!next.has(key))
699 if (!staticNext.has(key))
693 {
700 {
694 const [chunkX, chunkY] = key.split(",").map(Number);
701 const [chunkX, chunkY] = key.split(",").map(Number);
695 send(session, { type: MessageType.unsubscribeChunk, chunkX, chunkY });
702 send(session, { type: MessageType.unsubscribeChunk, chunkX, chunkY });
696 }
703 }
697 }
704 }
698 const snapshots = simulation.snapshotFor(session.entityId);
705
706 const snapshots = simulation.snapshotsForView(session.entityId);
699 for (const snapshot of snapshots)
707 for (const snapshot of snapshots)
700 {
708 {
701 const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
709 const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
702 if (forceSnapshots || !session.subscribed.has(key))
710 const entityChanged = entityNext.has(key) !== session.entitySubscribed.has(key);
703 { send(session, { type: MessageType.chunkSnapshot, ...snapshot }); }
711 if (forceSnapshots || !session.staticSubscribed.has(key) || entityChanged)
712 {
713 send(session, { type: MessageType.chunkSnapshot, ...snapshot });
714 }
704 }
715 }
705 session.subscribed = next;
716 session.entitySubscribed = entityNext;
717 session.staticSubscribed = staticNext;
706 }
718 }
707
719
708 function requirePlaying (session)
720 function requirePlaying (session)
@@ -836,6 +848,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
836 });
848 });
837 continue;
849 continue;
838 }
850 }
851 if (event.type === "toast")
852 {
853 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
854 if (session)
855 { send(session, { type: MessageType.toast, message: event.message }); }
856 continue;
857 }
839 if (event.type === "pigeon-delivered")
858 if (event.type === "pigeon-delivered")
840 {
859 {
841 for (const session of sessions.values())
860 for (const session of sessions.values())
@@ -1042,8 +1061,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1042 {
1061 {
1043 if (!session.entityId)
1062 if (!session.entityId)
1044 { continue; }
1063 { continue; }
1045 const seesFrom = fromKey ? session.subscribed.has(fromKey) : false;
1064 const seesFrom = fromKey ? session.entitySubscribed.has(fromKey) : false;
1046 const seesTo = session.subscribed.has(toKey);
1065 const seesTo = session.entitySubscribed.has(toKey);
1066 const seesStaticTo = session.staticSubscribed.has(toKey);
1047 if (event.type === "entity-spawn")
1067 if (event.type === "entity-spawn")
1048 {
1068 {
1049 if (session.entityId === event.entityId || !seesTo)
1069 if (session.entityId === event.entityId || !seesTo)
@@ -1156,7 +1176,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1156 }
1176 }
1157 if (event.type === "chunk-delta")
1177 if (event.type === "chunk-delta")
1158 {
1178 {
1159 if (!seesTo)
1179 if (!seesStaticTo)
1160 { continue; }
1180 { continue; }
1161 send(session, {
1181 send(session, {
1162 type: MessageType.chunkDelta,
1182 type: MessageType.chunkDelta,
server/src/persistence/stateDb.js +120 −4
@@ -127,6 +127,29 @@ CREATE TABLE IF NOT EXISTS item_last_sales (
127 127 last_trade_at INTEGER NOT NULL,
128 128 price_from INTEGER NOT NULL
129 129 );
130
131 CREATE TABLE IF NOT EXISTS bank_rest_notices (
132 notice_id INTEGER PRIMARY KEY AUTOINCREMENT,
133 character_id INTEGER NOT NULL,
134 item_id INTEGER NOT NULL,
135 item_name TEXT NOT NULL,
136 quantity INTEGER NOT NULL,
137 source_name TEXT NOT NULL,
138 created_at INTEGER NOT NULL
139 );
140
141 CREATE TABLE IF NOT EXISTS held_courier_deliveries (
142 hold_id INTEGER PRIMARY KEY AUTOINCREMENT,
143 character_id INTEGER NOT NULL,
144 sender_character_id INTEGER NOT NULL,
145 origin_tile_x INTEGER NOT NULL,
146 origin_tile_y INTEGER NOT NULL,
147 destination_kind TEXT NOT NULL,
148 destination_character_id INTEGER,
149 vault_character_id INTEGER,
150 cargo_blob TEXT NOT NULL,
151 created_at INTEGER NOT NULL
152 );
130 153 `;
131 154
132 155 export class StateDatabase
@@ -148,6 +171,9 @@ export class StateDatabase
148 171 const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
149 172 if (!characterColumns.some((column) => column.name === "is_dead"))
150 173 { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
174 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
175 if (!courierColumns.some((column) => column.name === "vault_character_id"))
176 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
151 177 this.#grantLanternsToExistingCharacters();
152 178 }
153 179
@@ -703,8 +729,9 @@ export class StateDatabase
703 729 const result = this.db.prepare(`
704 730 INSERT INTO courier_transits (
705 731 sender_character_id, destination_kind, destination_character_id, cargo_blob,
706 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at
707 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
732 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at,
733 vault_character_id
734 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
708 735 `).run(
709 736 transit.senderCharacterId,
710 737 transit.destinationKind,
@@ -718,7 +745,8 @@ export class StateDatabase
718 745 transit.status ?? "in_transit",
719 746 transit.entityId ?? null,
720 747 now,
721 transit.createdAt ?? now
748 transit.createdAt ?? now,
749 transit.vaultCharacterId ?? null
722 750 );
723 751 return this.getCourierTransit(Number(result.lastInsertRowid));
724 752 }
@@ -742,7 +770,7 @@ export class StateDatabase
742 770 UPDATE courier_transits
743 771 SET traveled = ?, status = ?, entity_id = ?, updated_at = ?,
744 772 origin_x = ?, origin_y = ?, dest_x = ?, dest_y = ?,
745 destination_kind = ?, destination_character_id = ?
773 destination_kind = ?, destination_character_id = ?, vault_character_id = ?
746 774 WHERE courier_id = ?
747 775 `).run(
748 776 transit.traveled ?? 0,
@@ -755,10 +783,81 @@ export class StateDatabase
755 783 transit.destY,
756 784 transit.destinationKind,
757 785 transit.destinationCharacterId ?? null,
786 transit.vaultCharacterId ?? null,
758 787 transit.courierId
759 788 );
760 789 }
761 790
791 appendBankRestNotice (characterId, entry)
792 {
793 const qty = Math.max(1, entry.quantity | 0);
794 this.db.prepare(`
795 INSERT INTO bank_rest_notices (character_id, item_id, item_name, quantity, source_name, created_at)
796 VALUES (?, ?, ?, ?, ?, ?)
797 `).run(
798 characterId,
799 entry.itemId | 0,
800 String(entry.itemName ?? "Item"),
801 qty,
802 String(entry.sourceName ?? "unknown source"),
803 entry.createdAt ?? Date.now()
804 );
805 }
806
807 listBankRestNotices (characterId)
808 {
809 return this.db.prepare(`
810 SELECT * FROM bank_rest_notices WHERE character_id = ? ORDER BY notice_id ASC
811 `).all(characterId).map((row) => ({
812 noticeId: row.notice_id,
813 characterId: row.character_id,
814 itemId: row.item_id,
815 itemName: row.item_name,
816 quantity: row.quantity,
817 sourceName: row.source_name,
818 createdAt: row.created_at
819 }));
820 }
821
822 clearBankRestNotices (characterId)
823 {
824 this.db.prepare("DELETE FROM bank_rest_notices WHERE character_id = ?").run(characterId);
825 }
826
827 insertHeldCourierDelivery (delivery)
828 {
829 const now = delivery.createdAt ?? Date.now();
830 const result = this.db.prepare(`
831 INSERT INTO held_courier_deliveries (
832 character_id, sender_character_id, origin_tile_x, origin_tile_y,
833 destination_kind, destination_character_id, vault_character_id, cargo_blob, created_at
834 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
835 `).run(
836 delivery.characterId,
837 delivery.senderCharacterId,
838 delivery.originTileX | 0,
839 delivery.originTileY | 0,
840 delivery.destinationKind,
841 delivery.destinationCharacterId ?? null,
842 delivery.vaultCharacterId ?? null,
843 JSON.stringify(delivery.cargo),
844 now
845 );
846 return Number(result.lastInsertRowid);
847 }
848
849 listHeldCourierDeliveries (characterId)
850 {
851 return this.db.prepare(`
852 SELECT * FROM held_courier_deliveries WHERE character_id = ? ORDER BY hold_id ASC
853 `).all(characterId).map(parseHeldCourierDelivery);
854 }
855
856 deleteHeldCourierDelivery (holdId)
857 {
858 this.db.prepare("DELETE FROM held_courier_deliveries WHERE hold_id = ?").run(holdId);
859 }
860
762 861 insertMarketOrder (order)
763 862 {
764 863 const result = this.db.prepare(`
@@ -967,6 +1066,7 @@ function parseCourierTransit (row)
967 1066 senderCharacterId: row.sender_character_id,
968 1067 destinationKind: row.destination_kind,
969 1068 destinationCharacterId: row.destination_character_id,
1069 vaultCharacterId: row.vault_character_id ?? null,
970 1070 cargo: JSON.parse(row.cargo_blob),
971 1071 originX: row.origin_x,
972 1072 originY: row.origin_y,
@@ -979,3 +1079,19 @@ function parseCourierTransit (row)
979 1079 createdAt: row.created_at
980 1080 };
981 1081 }
1082
1083 function parseHeldCourierDelivery (row)
1084 {
1085 return {
1086 holdId: row.hold_id,
1087 characterId: row.character_id,
1088 senderCharacterId: row.sender_character_id,
1089 originTileX: row.origin_tile_x,
1090 originTileY: row.origin_tile_y,
1091 destinationKind: row.destination_kind,
1092 destinationCharacterId: row.destination_character_id,
1093 vaultCharacterId: row.vault_character_id,
1094 cargo: JSON.parse(row.cargo_blob),
1095 createdAt: row.created_at
1096 };
1097 }
@@ -127,6 +127,29 @@ CREATE TABLE IF NOT EXISTS item_last_sales (
127 last_trade_at INTEGER NOT NULL,
127 last_trade_at INTEGER NOT NULL,
128 price_from INTEGER NOT NULL
128 price_from INTEGER NOT NULL
129);
129);
130
131CREATE TABLE IF NOT EXISTS bank_rest_notices (
132 notice_id INTEGER PRIMARY KEY AUTOINCREMENT,
133 character_id INTEGER NOT NULL,
134 item_id INTEGER NOT NULL,
135 item_name TEXT NOT NULL,
136 quantity INTEGER NOT NULL,
137 source_name TEXT NOT NULL,
138 created_at INTEGER NOT NULL
139);
140
141CREATE TABLE IF NOT EXISTS held_courier_deliveries (
142 hold_id INTEGER PRIMARY KEY AUTOINCREMENT,
143 character_id INTEGER NOT NULL,
144 sender_character_id INTEGER NOT NULL,
145 origin_tile_x INTEGER NOT NULL,
146 origin_tile_y INTEGER NOT NULL,
147 destination_kind TEXT NOT NULL,
148 destination_character_id INTEGER,
149 vault_character_id INTEGER,
150 cargo_blob TEXT NOT NULL,
151 created_at INTEGER NOT NULL
152);
130`;
153`;
131
154
132export class StateDatabase
155export class StateDatabase
@@ -148,6 +171,9 @@ export class StateDatabase
148 const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
171 const characterColumns = this.db.prepare("PRAGMA table_info(characters)").all();
149 if (!characterColumns.some((column) => column.name === "is_dead"))
172 if (!characterColumns.some((column) => column.name === "is_dead"))
150 { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
173 { this.db.exec("ALTER TABLE characters ADD COLUMN is_dead INTEGER NOT NULL DEFAULT 0"); }
174 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
175 if (!courierColumns.some((column) => column.name === "vault_character_id"))
176 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
151 this.#grantLanternsToExistingCharacters();
177 this.#grantLanternsToExistingCharacters();
152 }
178 }
153
179
@@ -703,8 +729,9 @@ export class StateDatabase
703 const result = this.db.prepare(`
729 const result = this.db.prepare(`
704 INSERT INTO courier_transits (
730 INSERT INTO courier_transits (
705 sender_character_id, destination_kind, destination_character_id, cargo_blob,
731 sender_character_id, destination_kind, destination_character_id, cargo_blob,
706 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at
732 origin_x, origin_y, dest_x, dest_y, traveled, status, entity_id, updated_at, created_at,
707 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
733 vault_character_id
734 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
708 `).run(
735 `).run(
709 transit.senderCharacterId,
736 transit.senderCharacterId,
710 transit.destinationKind,
737 transit.destinationKind,
@@ -718,7 +745,8 @@ export class StateDatabase
718 transit.status ?? "in_transit",
745 transit.status ?? "in_transit",
719 transit.entityId ?? null,
746 transit.entityId ?? null,
720 now,
747 now,
721 transit.createdAt ?? now
748 transit.createdAt ?? now,
749 transit.vaultCharacterId ?? null
722 );
750 );
723 return this.getCourierTransit(Number(result.lastInsertRowid));
751 return this.getCourierTransit(Number(result.lastInsertRowid));
724 }
752 }
@@ -742,7 +770,7 @@ export class StateDatabase
742 UPDATE courier_transits
770 UPDATE courier_transits
743 SET traveled = ?, status = ?, entity_id = ?, updated_at = ?,
771 SET traveled = ?, status = ?, entity_id = ?, updated_at = ?,
744 origin_x = ?, origin_y = ?, dest_x = ?, dest_y = ?,
772 origin_x = ?, origin_y = ?, dest_x = ?, dest_y = ?,
745 destination_kind = ?, destination_character_id = ?
773 destination_kind = ?, destination_character_id = ?, vault_character_id = ?
746 WHERE courier_id = ?
774 WHERE courier_id = ?
747 `).run(
775 `).run(
748 transit.traveled ?? 0,
776 transit.traveled ?? 0,
@@ -755,10 +783,81 @@ export class StateDatabase
755 transit.destY,
783 transit.destY,
756 transit.destinationKind,
784 transit.destinationKind,
757 transit.destinationCharacterId ?? null,
785 transit.destinationCharacterId ?? null,
786 transit.vaultCharacterId ?? null,
758 transit.courierId
787 transit.courierId
759 );
788 );
760 }
789 }
761
790
791 appendBankRestNotice (characterId, entry)
792 {
793 const qty = Math.max(1, entry.quantity | 0);
794 this.db.prepare(`
795 INSERT INTO bank_rest_notices (character_id, item_id, item_name, quantity, source_name, created_at)
796 VALUES (?, ?, ?, ?, ?, ?)
797 `).run(
798 characterId,
799 entry.itemId | 0,
800 String(entry.itemName ?? "Item"),
801 qty,
802 String(entry.sourceName ?? "unknown source"),
803 entry.createdAt ?? Date.now()
804 );
805 }
806
807 listBankRestNotices (characterId)
808 {
809 return this.db.prepare(`
810 SELECT * FROM bank_rest_notices WHERE character_id = ? ORDER BY notice_id ASC
811 `).all(characterId).map((row) => ({
812 noticeId: row.notice_id,
813 characterId: row.character_id,
814 itemId: row.item_id,
815 itemName: row.item_name,
816 quantity: row.quantity,
817 sourceName: row.source_name,
818 createdAt: row.created_at
819 }));
820 }
821
822 clearBankRestNotices (characterId)
823 {
824 this.db.prepare("DELETE FROM bank_rest_notices WHERE character_id = ?").run(characterId);
825 }
826
827 insertHeldCourierDelivery (delivery)
828 {
829 const now = delivery.createdAt ?? Date.now();
830 const result = this.db.prepare(`
831 INSERT INTO held_courier_deliveries (
832 character_id, sender_character_id, origin_tile_x, origin_tile_y,
833 destination_kind, destination_character_id, vault_character_id, cargo_blob, created_at
834 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
835 `).run(
836 delivery.characterId,
837 delivery.senderCharacterId,
838 delivery.originTileX | 0,
839 delivery.originTileY | 0,
840 delivery.destinationKind,
841 delivery.destinationCharacterId ?? null,
842 delivery.vaultCharacterId ?? null,
843 JSON.stringify(delivery.cargo),
844 now
845 );
846 return Number(result.lastInsertRowid);
847 }
848
849 listHeldCourierDeliveries (characterId)
850 {
851 return this.db.prepare(`
852 SELECT * FROM held_courier_deliveries WHERE character_id = ? ORDER BY hold_id ASC
853 `).all(characterId).map(parseHeldCourierDelivery);
854 }
855
856 deleteHeldCourierDelivery (holdId)
857 {
858 this.db.prepare("DELETE FROM held_courier_deliveries WHERE hold_id = ?").run(holdId);
859 }
860
762 insertMarketOrder (order)
861 insertMarketOrder (order)
763 {
862 {
764 const result = this.db.prepare(`
863 const result = this.db.prepare(`
@@ -967,6 +1066,7 @@ function parseCourierTransit (row)
967 senderCharacterId: row.sender_character_id,
1066 senderCharacterId: row.sender_character_id,
968 destinationKind: row.destination_kind,
1067 destinationKind: row.destination_kind,
969 destinationCharacterId: row.destination_character_id,
1068 destinationCharacterId: row.destination_character_id,
1069 vaultCharacterId: row.vault_character_id ?? null,
970 cargo: JSON.parse(row.cargo_blob),
1070 cargo: JSON.parse(row.cargo_blob),
971 originX: row.origin_x,
1071 originX: row.origin_x,
972 originY: row.origin_y,
1072 originY: row.origin_y,
@@ -979,3 +1079,19 @@ function parseCourierTransit (row)
979 createdAt: row.created_at
1079 createdAt: row.created_at
980 };
1080 };
981}
1081}
1082
1083function parseHeldCourierDelivery (row)
1084{
1085 return {
1086 holdId: row.hold_id,
1087 characterId: row.character_id,
1088 senderCharacterId: row.sender_character_id,
1089 originTileX: row.origin_tile_x,
1090 originTileY: row.origin_tile_y,
1091 destinationKind: row.destination_kind,
1092 destinationCharacterId: row.destination_character_id,
1093 vaultCharacterId: row.vault_character_id,
1094 cargo: JSON.parse(row.cargo_blob),
1095 createdAt: row.created_at
1096 };
1097}
server/src/simulation/simulation.js +34 −4
@@ -4,6 +4,7 @@ import {
4 4 GAIT,
5 5 REGION_RUNTIME_STATE,
6 6 VISIBLE_CHUNK_RADIUS,
7 STATIC_CHUNK_RADIUS,
7 8 WORLD_YEAR_OFFSET
8 9 } from "../../../shared/protocol/constants.js";
9 10 import {
@@ -377,9 +378,15 @@ export class Simulation
377 378 this.#queueReplication(replicationSpawn(view));
378 379 this.#recalculateActivation(this.now);
379 380 this.#syncGhosts();
381 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
380 382 return entityId;
381 383 }
382 384
385 isCharacterOnline (characterId)
386 {
387 return this.characterEntities.has(characterId);
388 }
389
383 390 spawnEntity (components, options = {})
384 391 {
385 392 const entityId = options.entityId ?? this.nextEntityId++;
@@ -678,18 +685,41 @@ export class Simulation
678 685 if (!record)
679 686 { return []; }
680 687 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
681 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY));
688 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false));
682 689 }
683 690
684 snapshotChunk (chunkX, chunkY)
691 /** Client view: 5×5 map ring; inner 3×3 includes entities and ground items. */
692 snapshotsForView (entityId)
693 {
694 const record = this.directory.get(entityId);
695 if (!record)
696 { return []; }
697 const centerChunkX = tileToChunk(record.tileX);
698 const centerChunkY = tileToChunk(record.tileY);
699 const entityKeys = new Set(
700 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
701 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
702 );
703 return visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS)
704 .map((coord) =>
705 {
706 const key = chunkKey(coord.chunkX, coord.chunkY);
707 const staticOnly = !entityKeys.has(key);
708 const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly);
709 return { ...snapshot, staticOnly };
710 });
711 }
712
713 snapshotChunk (chunkX, chunkY, staticOnly = false)
685 714 {
686 715 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
687 716 if (owner == null)
688 { return this.#syntheticSnapshot(chunkX, chunkY); }
717 { return this.#syntheticSnapshot(chunkX, chunkY, staticOnly); }
689 718 return this.workers[owner].call({
690 719 type: WorkerMessage.snapshotChunk,
691 720 chunkX,
692 chunkY
721 chunkY,
722 staticOnly: !!staticOnly
693 723 });
694 724 }
695 725
@@ -4,6 +4,7 @@ import {
4 GAIT,
4 GAIT,
5 REGION_RUNTIME_STATE,
5 REGION_RUNTIME_STATE,
6 VISIBLE_CHUNK_RADIUS,
6 VISIBLE_CHUNK_RADIUS,
7 STATIC_CHUNK_RADIUS,
7 WORLD_YEAR_OFFSET
8 WORLD_YEAR_OFFSET
8} from "../../../shared/protocol/constants.js";
9} from "../../../shared/protocol/constants.js";
9import {
10import {
@@ -377,9 +378,15 @@ export class Simulation
377 this.#queueReplication(replicationSpawn(view));
378 this.#queueReplication(replicationSpawn(view));
378 this.#recalculateActivation(this.now);
379 this.#recalculateActivation(this.now);
379 this.#syncGhosts();
380 this.#syncGhosts();
381 this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
380 return entityId;
382 return entityId;
381 }
383 }
382
384
385 isCharacterOnline (characterId)
386 {
387 return this.characterEntities.has(characterId);
388 }
389
383 spawnEntity (components, options = {})
390 spawnEntity (components, options = {})
384 {
391 {
385 const entityId = options.entityId ?? this.nextEntityId++;
392 const entityId = options.entityId ?? this.nextEntityId++;
@@ -678,18 +685,41 @@ export class Simulation
678 if (!record)
685 if (!record)
679 { return []; }
686 { return []; }
680 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
687 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
681 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY));
688 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false));
682 }
689 }
683
690
684 snapshotChunk (chunkX, chunkY)
691 /** Client view: 5×5 map ring; inner 3×3 includes entities and ground items. */
692 snapshotsForView (entityId)
693 {
694 const record = this.directory.get(entityId);
695 if (!record)
696 { return []; }
697 const centerChunkX = tileToChunk(record.tileX);
698 const centerChunkY = tileToChunk(record.tileY);
699 const entityKeys = new Set(
700 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
701 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
702 );
703 return visibleChunkCoords(centerChunkX, centerChunkY, STATIC_CHUNK_RADIUS)
704 .map((coord) =>
705 {
706 const key = chunkKey(coord.chunkX, coord.chunkY);
707 const staticOnly = !entityKeys.has(key);
708 const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly);
709 return { ...snapshot, staticOnly };
710 });
711 }
712
713 snapshotChunk (chunkX, chunkY, staticOnly = false)
685 {
714 {
686 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
715 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
687 if (owner == null)
716 if (owner == null)
688 { return this.#syntheticSnapshot(chunkX, chunkY); }
717 { return this.#syntheticSnapshot(chunkX, chunkY, staticOnly); }
689 return this.workers[owner].call({
718 return this.workers[owner].call({
690 type: WorkerMessage.snapshotChunk,
719 type: WorkerMessage.snapshotChunk,
691 chunkX,
720 chunkX,
692 chunkY
721 chunkY,
722 staticOnly: !!staticOnly
693 });
723 });
694 }
724 }
695
725
server/src/simulation/workerWorld.js +16 −2
@@ -137,7 +137,7 @@ export class WorkerWorld
137 137 case WorkerMessage.abortTransfer:
138 138 return this.#abortTransfer(message.entityId);
139 139 case WorkerMessage.snapshotChunk:
140 return this.#chunkSnapshot(message.chunkX, message.chunkY);
140 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly);
141 141 case WorkerMessage.listLoaders:
142 142 return this.#listLoaders();
143 143 case WorkerMessage.listPublicEntities:
@@ -1441,9 +1441,23 @@ export class WorkerWorld
1441 1441 return records;
1442 1442 }
1443 1443
1444 #chunkSnapshot (chunkX, chunkY)
1444 #chunkSnapshot (chunkX, chunkY, staticOnly = false)
1445 1445 {
1446 1446 const data = this.#chunkData(chunkX, chunkY);
1447 if (staticOnly)
1448 {
1449 return {
1450 chunkX,
1451 chunkY,
1452 open: data.open,
1453 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1454 grounds: data.grounds,
1455 blocks: data.blocks,
1456 light: data.light,
1457 entities: [],
1458 groundItems: []
1459 };
1460 }
1447 1461 const entities = [];
1448 1462 for (const entity of this.ecs.query(Component.position, Component.appearance))
1449 1463 {
@@ -137,7 +137,7 @@ export class WorkerWorld
137 case WorkerMessage.abortTransfer:
137 case WorkerMessage.abortTransfer:
138 return this.#abortTransfer(message.entityId);
138 return this.#abortTransfer(message.entityId);
139 case WorkerMessage.snapshotChunk:
139 case WorkerMessage.snapshotChunk:
140 return this.#chunkSnapshot(message.chunkX, message.chunkY);
140 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly);
141 case WorkerMessage.listLoaders:
141 case WorkerMessage.listLoaders:
142 return this.#listLoaders();
142 return this.#listLoaders();
143 case WorkerMessage.listPublicEntities:
143 case WorkerMessage.listPublicEntities:
@@ -1441,9 +1441,23 @@ export class WorkerWorld
1441 return records;
1441 return records;
1442 }
1442 }
1443
1443
1444 #chunkSnapshot (chunkX, chunkY)
1444 #chunkSnapshot (chunkX, chunkY, staticOnly = false)
1445 {
1445 {
1446 const data = this.#chunkData(chunkX, chunkY);
1446 const data = this.#chunkData(chunkX, chunkY);
1447 if (staticOnly)
1448 {
1449 return {
1450 chunkX,
1451 chunkY,
1452 open: data.open,
1453 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1454 grounds: data.grounds,
1455 blocks: data.blocks,
1456 light: data.light,
1457 entities: [],
1458 groundItems: []
1459 };
1460 }
1447 const entities = [];
1461 const entities = [];
1448 for (const entity of this.ecs.query(Component.position, Component.appearance))
1462 for (const entity of this.ecs.query(Component.position, Component.appearance))
1449 {
1463 {
server/tests/courier.test.js +84 −0
@@ -99,6 +99,90 @@ function countItem (slots, itemId)
99 99 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
100 100 }
101 101
102 test("pigeon to offline player flies to the bank and credits the recipient vault", () =>
103 {
104 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
105 try
106 {
107 placeBank(harness.worldDb, 20, 8);
108 harness.simulation.reloadWorld();
109 harness.simulation.applySettings({
110 pigeonTakeoffTilesPerSec: 40,
111 pigeonCruiseTilesPerSec: 40,
112 pigeonLandingTilesPerSec: 40,
113 simulationTickHz: 20
114 });
115 const sender = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8, firstName: "Ada", lastName: "Sender" });
116 const receiver = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8, firstName: "Bob", lastName: "Receiver" });
117 const senderId = harness.simulation.spawnCharacter(1, sender);
118 harness.simulation.despawnCharacter(receiver.character_id);
119 const bag = harness.simulation.bagOf(senderId);
120 const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
121 assert.ok(appleSlot >= 0);
122
123 const result = harness.simulation.dispatchPigeon({
124 characterId: sender.character_id,
125 destination: { kind: "player", firstName: "Bob", lastName: "Receiver" },
126 cargo: { kind: "item", slotIndex: appleSlot, quantity: 1 }
127 });
128 assert.equal(result.transit.destinationKind, "bank");
129 assert.equal(result.transit.vaultCharacterId, receiver.character_id);
130 assert.ok(Math.hypot(result.transit.destX - 20.5, result.transit.destY - 8.5) < 1);
131
132 stepTimes(harness.simulation, 40);
133 const receiverVault = harness.stateDb.getBag(receiver.character_id);
134 assert.equal(countItem(receiverVault.vault, ItemId.apple), 1);
135 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
136 }
137 finally
138 { harness.close(); }
139 });
140
141 test("logging in after offline bank deposits sends a bank resting notice by pigeon", () =>
142 {
143 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
144 try
145 {
146 placeBank(harness.worldDb, 20, 8);
147 harness.simulation.reloadWorld();
148 harness.simulation.applySettings({
149 pigeonTakeoffTilesPerSec: 40,
150 pigeonCruiseTilesPerSec: 40,
151 pigeonLandingTilesPerSec: 40,
152 simulationTickHz: 20
153 });
154 const sender = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8, firstName: "Ada", lastName: "Sender" });
155 const receiver = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8, firstName: "Bob", lastName: "Receiver" });
156 const senderId = harness.simulation.spawnCharacter(1, sender);
157 harness.simulation.despawnCharacter(receiver.character_id);
158
159 const bag = harness.simulation.bagOf(senderId);
160 const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
161 harness.simulation.dispatchPigeon({
162 characterId: sender.character_id,
163 destination: { kind: "player", firstName: "Bob", lastName: "Receiver" },
164 cargo: { kind: "item", slotIndex: appleSlot, quantity: 1 }
165 });
166 stepTimes(harness.simulation, 40);
167 assert.equal(harness.stateDb.listBankRestNotices(receiver.character_id).length, 1);
168
169 const receiverId = harness.simulation.spawnCharacter(2, receiver);
170 const active = harness.stateDb.listActiveCourierTransits();
171 assert.equal(active.length, 1);
172 assert.equal(active[0].destinationKind, "player");
173 assert.equal(active[0].cargo.stack.itemId, ItemId.letter);
174 assert.match(active[0].cargo.stack.instance.body, /While you have been resting/);
175 assert.match(active[0].cargo.stack.instance.body, /Ada Sender/);
176
177 stepTimes(harness.simulation, 40);
178 const receiverBag = harness.simulation.bagOf(receiverId);
179 const letterSlot = receiverBag.inventory.find((slot) => slot?.itemId === ItemId.letter);
180 assert.ok(letterSlot);
181 assert.match(letterSlot.instance.body, /Signed,\nThe Bank/);
182 }
183 finally
184 { harness.close(); }
185 });
102 186 test("pigeon delivers an item to an online player inventory", () =>
103 187 {
104 188 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
@@ -99,6 +99,90 @@ function countItem (slots, itemId)
99 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
99 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
100}
100}
101
101
102test("pigeon to offline player flies to the bank and credits the recipient vault", () =>
103{
104 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
105 try
106 {
107 placeBank(harness.worldDb, 20, 8);
108 harness.simulation.reloadWorld();
109 harness.simulation.applySettings({
110 pigeonTakeoffTilesPerSec: 40,
111 pigeonCruiseTilesPerSec: 40,
112 pigeonLandingTilesPerSec: 40,
113 simulationTickHz: 20
114 });
115 const sender = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8, firstName: "Ada", lastName: "Sender" });
116 const receiver = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8, firstName: "Bob", lastName: "Receiver" });
117 const senderId = harness.simulation.spawnCharacter(1, sender);
118 harness.simulation.despawnCharacter(receiver.character_id);
119 const bag = harness.simulation.bagOf(senderId);
120 const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
121 assert.ok(appleSlot >= 0);
122
123 const result = harness.simulation.dispatchPigeon({
124 characterId: sender.character_id,
125 destination: { kind: "player", firstName: "Bob", lastName: "Receiver" },
126 cargo: { kind: "item", slotIndex: appleSlot, quantity: 1 }
127 });
128 assert.equal(result.transit.destinationKind, "bank");
129 assert.equal(result.transit.vaultCharacterId, receiver.character_id);
130 assert.ok(Math.hypot(result.transit.destX - 20.5, result.transit.destY - 8.5) < 1);
131
132 stepTimes(harness.simulation, 40);
133 const receiverVault = harness.stateDb.getBag(receiver.character_id);
134 assert.equal(countItem(receiverVault.vault, ItemId.apple), 1);
135 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
136 }
137 finally
138 { harness.close(); }
139});
140
141test("logging in after offline bank deposits sends a bank resting notice by pigeon", () =>
142{
143 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
144 try
145 {
146 placeBank(harness.worldDb, 20, 8);
147 harness.simulation.reloadWorld();
148 harness.simulation.applySettings({
149 pigeonTakeoffTilesPerSec: 40,
150 pigeonCruiseTilesPerSec: 40,
151 pigeonLandingTilesPerSec: 40,
152 simulationTickHz: 20
153 });
154 const sender = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8, firstName: "Ada", lastName: "Sender" });
155 const receiver = makeCharacter(harness.stateDb, { tileX: 10, tileY: 8, firstName: "Bob", lastName: "Receiver" });
156 const senderId = harness.simulation.spawnCharacter(1, sender);
157 harness.simulation.despawnCharacter(receiver.character_id);
158
159 const bag = harness.simulation.bagOf(senderId);
160 const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
161 harness.simulation.dispatchPigeon({
162 characterId: sender.character_id,
163 destination: { kind: "player", firstName: "Bob", lastName: "Receiver" },
164 cargo: { kind: "item", slotIndex: appleSlot, quantity: 1 }
165 });
166 stepTimes(harness.simulation, 40);
167 assert.equal(harness.stateDb.listBankRestNotices(receiver.character_id).length, 1);
168
169 const receiverId = harness.simulation.spawnCharacter(2, receiver);
170 const active = harness.stateDb.listActiveCourierTransits();
171 assert.equal(active.length, 1);
172 assert.equal(active[0].destinationKind, "player");
173 assert.equal(active[0].cargo.stack.itemId, ItemId.letter);
174 assert.match(active[0].cargo.stack.instance.body, /While you have been resting/);
175 assert.match(active[0].cargo.stack.instance.body, /Ada Sender/);
176
177 stepTimes(harness.simulation, 40);
178 const receiverBag = harness.simulation.bagOf(receiverId);
179 const letterSlot = receiverBag.inventory.find((slot) => slot?.itemId === ItemId.letter);
180 assert.ok(letterSlot);
181 assert.match(letterSlot.instance.body, /Signed,\nThe Bank/);
182 }
183 finally
184 { harness.close(); }
185});
102test("pigeon delivers an item to an online player inventory", () =>
186test("pigeon delivers an item to an online player inventory", () =>
103{
187{
104 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
188 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
server/tests/worker-threads.test.js +12 −1
@@ -1,5 +1,6 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 import { STATIC_CHUNK_RADIUS, VISIBLE_CHUNK_RADIUS } from "../../shared/protocol/constants.js";
3 4 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
4 5
5 6 test("thread workers speak the same protocol as in-process workers", { timeout: 20_000 }, async () =>
@@ -10,8 +11,18 @@ test("thread workers speak the same protocol as in-process workers", { timeout:
10 11 const character = makeCharacter(harness.stateDb);
11 12 const entityId = harness.simulation.spawnCharacter(1, character);
12 13 const snapshots = harness.simulation.snapshotFor(entityId);
13 assert.equal(snapshots.length, 9);
14 assert.equal(snapshots.length, (VISIBLE_CHUNK_RADIUS * 2 + 1) ** 2);
14 15 assert.ok(snapshots.some((snapshot) => snapshot.entities.some((entity) => entity.entityId === entityId)));
16
17 const viewSnapshots = harness.simulation.snapshotsForView(entityId);
18 assert.equal(viewSnapshots.length, (STATIC_CHUNK_RADIUS * 2 + 1) ** 2);
19 const staticOnly = viewSnapshots.filter((snapshot) => snapshot.staticOnly);
20 assert.equal(staticOnly.length, viewSnapshots.length - snapshots.length);
21 for (const snapshot of staticOnly)
22 {
23 assert.deepEqual(snapshot.entities, []);
24 assert.deepEqual(snapshot.groundItems, []);
25 }
15 26 }
16 27 finally
17 28 {
@@ -1,5 +1,6 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { STATIC_CHUNK_RADIUS, VISIBLE_CHUNK_RADIUS } from "../../shared/protocol/constants.js";
3import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
4import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
4
5
5test("thread workers speak the same protocol as in-process workers", { timeout: 20_000 }, async () =>
6test("thread workers speak the same protocol as in-process workers", { timeout: 20_000 }, async () =>
@@ -10,8 +11,18 @@ test("thread workers speak the same protocol as in-process workers", { timeout:
10 const character = makeCharacter(harness.stateDb);
11 const character = makeCharacter(harness.stateDb);
11 const entityId = harness.simulation.spawnCharacter(1, character);
12 const entityId = harness.simulation.spawnCharacter(1, character);
12 const snapshots = harness.simulation.snapshotFor(entityId);
13 const snapshots = harness.simulation.snapshotFor(entityId);
13 assert.equal(snapshots.length, 9);
14 assert.equal(snapshots.length, (VISIBLE_CHUNK_RADIUS * 2 + 1) ** 2);
14 assert.ok(snapshots.some((snapshot) => snapshot.entities.some((entity) => entity.entityId === entityId)));
15 assert.ok(snapshots.some((snapshot) => snapshot.entities.some((entity) => entity.entityId === entityId)));
16
17 const viewSnapshots = harness.simulation.snapshotsForView(entityId);
18 assert.equal(viewSnapshots.length, (STATIC_CHUNK_RADIUS * 2 + 1) ** 2);
19 const staticOnly = viewSnapshots.filter((snapshot) => snapshot.staticOnly);
20 assert.equal(staticOnly.length, viewSnapshots.length - snapshots.length);
21 for (const snapshot of staticOnly)
22 {
23 assert.deepEqual(snapshot.entities, []);
24 assert.deepEqual(snapshot.groundItems, []);
25 }
15 }
26 }
16 finally
27 finally
17 {
28 {
shared/courier/bankNotice.js added +66 −0
@@ -0,0 +1,66 @@
1 import { stackDisplayLabel } from "../definitions/items.js";
2 import { originLabel } from "../items/origin.js";
3
4 export const BANK_LETTER_AUTHOR = "The Bank";
5
6 export function isCentralExchangeLetter (instance)
7 {
8 return instance?.kind === "letter" && /Central Exchange/.test(String(instance.body ?? ""));
9 }
10
11 export function isBankRestNoticeLetter (instance)
12 {
13 return instance?.kind === "letter" && instance.bankRestNotice === true;
14 }
15
16 /** @param {{ quantity: number, itemName: string, sourceName: string }[]} lines */
17 export function bankRestNoticeLetterBody ({ playerName, lines })
18 {
19 const name = String(playerName ?? "Adventurer").trim() || "Adventurer";
20 const bodyLines = lines.map((line) =>
21 `- ${line.quantity} ${line.itemName}, received from ${line.sourceName}`
22 ).join("\n");
23 return [
24 `Dear ${name},`,
25 "While you have been resting, the following items were deposited into your bank account:",
26 "",
27 bodyLines,
28 "",
29 "Signed,",
30 BANK_LETTER_AUTHOR
31 ].join("\n");
32 }
33
34 export function itemNameForNotice (stack)
35 {
36 return stackDisplayLabel(stack);
37 }
38
39 /** Prefer pigeon sender name; otherwise origin label (`Mined by Ada`, …). */
40 export function sourceNameForVaultDeposit (stack, senderCharacterId, senderDisplayName)
41 {
42 if (senderDisplayName)
43 { return senderDisplayName; }
44 if (senderCharacterId)
45 { return `character #${senderCharacterId}`; }
46 const origins = stack?.origins ?? (stack?.origin ? [{ origin: stack.origin, quantity: stack.quantity ?? 1 }] : []);
47 if (origins.length === 1 && origins[0]?.origin)
48 { return originLabel(origins[0].origin); }
49 return "unknown source";
50 }
51
52 /** Merge notice rows that share item name and source. */
53 export function mergeBankRestNoticeLines (entries)
54 {
55 const merged = new Map();
56 for (const entry of entries ?? [])
57 {
58 const key = `${entry.itemName}|${entry.sourceName}`;
59 const prev = merged.get(key);
60 if (prev)
61 { prev.quantity += entry.quantity | 0; }
62 else
63 { merged.set(key, { ...entry, quantity: entry.quantity | 0 }); }
64 }
65 return [...merged.values()];
66 }
@@ -0,0 +1,66 @@
1import { stackDisplayLabel } from "../definitions/items.js";
2import { originLabel } from "../items/origin.js";
3
4export const BANK_LETTER_AUTHOR = "The Bank";
5
6export function isCentralExchangeLetter (instance)
7{
8 return instance?.kind === "letter" && /Central Exchange/.test(String(instance.body ?? ""));
9}
10
11export function isBankRestNoticeLetter (instance)
12{
13 return instance?.kind === "letter" && instance.bankRestNotice === true;
14}
15
16/** @param {{ quantity: number, itemName: string, sourceName: string }[]} lines */
17export function bankRestNoticeLetterBody ({ playerName, lines })
18{
19 const name = String(playerName ?? "Adventurer").trim() || "Adventurer";
20 const bodyLines = lines.map((line) =>
21 `- ${line.quantity} ${line.itemName}, received from ${line.sourceName}`
22 ).join("\n");
23 return [
24 `Dear ${name},`,
25 "While you have been resting, the following items were deposited into your bank account:",
26 "",
27 bodyLines,
28 "",
29 "Signed,",
30 BANK_LETTER_AUTHOR
31 ].join("\n");
32}
33
34export function itemNameForNotice (stack)
35{
36 return stackDisplayLabel(stack);
37}
38
39/** Prefer pigeon sender name; otherwise origin label (`Mined by Ada`, …). */
40export function sourceNameForVaultDeposit (stack, senderCharacterId, senderDisplayName)
41{
42 if (senderDisplayName)
43 { return senderDisplayName; }
44 if (senderCharacterId)
45 { return `character #${senderCharacterId}`; }
46 const origins = stack?.origins ?? (stack?.origin ? [{ origin: stack.origin, quantity: stack.quantity ?? 1 }] : []);
47 if (origins.length === 1 && origins[0]?.origin)
48 { return originLabel(origins[0].origin); }
49 return "unknown source";
50}
51
52/** Merge notice rows that share item name and source. */
53export function mergeBankRestNoticeLines (entries)
54{
55 const merged = new Map();
56 for (const entry of entries ?? [])
57 {
58 const key = `${entry.itemName}|${entry.sourceName}`;
59 const prev = merged.get(key);
60 if (prev)
61 { prev.quantity += entry.quantity | 0; }
62 else
63 { merged.set(key, { ...entry, quantity: entry.quantity | 0 }); }
64 }
65 return [...merged.values()];
66}
shared/protocol/constants.js +4 −1
@@ -3,6 +3,8 @@ export const REGION_CHUNKS = 4;
3 3 export const SPRITE_SIZE_PX = 16;
4 4 export const PIVOT_FROM_BOTTOM_PX = 8;
5 5 export const VISIBLE_CHUNK_RADIUS = 1;
6 /** Map-only chunks around the player (Chebyshev); entities sync only inside VISIBLE_CHUNK_RADIUS. */
7 export const STATIC_CHUNK_RADIUS = 2;
6 8
7 9 /** If an entity has a path but has not left its tile for this long, repath. */
8 10 export const NAV_STUCK_MS = 5000;
@@ -172,6 +174,7 @@ export const MessageType = Object.freeze({
172 174 placeMarketBuy: "PLACE_MARKET_BUY",
173 175 cancelMarketOrder: "CANCEL_MARKET_ORDER",
174 176 marketTrade: "MARKET_TRADE",
175 skillLevelUp: "SKILL_LEVEL_UP"
177 skillLevelUp: "SKILL_LEVEL_UP",
178 toast: "TOAST"
176 179 });
177 180
@@ -3,6 +3,8 @@ export const REGION_CHUNKS = 4;
3export const SPRITE_SIZE_PX = 16;
3export const SPRITE_SIZE_PX = 16;
4export const PIVOT_FROM_BOTTOM_PX = 8;
4export const PIVOT_FROM_BOTTOM_PX = 8;
5export const VISIBLE_CHUNK_RADIUS = 1;
5export const VISIBLE_CHUNK_RADIUS = 1;
6/** Map-only chunks around the player (Chebyshev); entities sync only inside VISIBLE_CHUNK_RADIUS. */
7export const STATIC_CHUNK_RADIUS = 2;
6
8
7/** If an entity has a path but has not left its tile for this long, repath. */
9/** If an entity has a path but has not left its tile for this long, repath. */
8export const NAV_STUCK_MS = 5000;
10export const NAV_STUCK_MS = 5000;
@@ -172,6 +174,7 @@ export const MessageType = Object.freeze({
172 placeMarketBuy: "PLACE_MARKET_BUY",
174 placeMarketBuy: "PLACE_MARKET_BUY",
173 cancelMarketOrder: "CANCEL_MARKET_ORDER",
175 cancelMarketOrder: "CANCEL_MARKET_ORDER",
174 marketTrade: "MARKET_TRADE",
176 marketTrade: "MARKET_TRADE",
175 skillLevelUp: "SKILL_LEVEL_UP"
177 skillLevelUp: "SKILL_LEVEL_UP",
178 toast: "TOAST"
176});
179});
177
180