BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

bags.js 26.9 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { syncPlayerHealth } from "../skills/service.js";
3import { canEquipItem } from "../../../shared/equipment/stats.js";
4import { BlockType } from "../../../shared/definitions/tiles.js";
5import { ItemId, itemDefinition, itemSpriteName, stackDisplayLabel, LETTER_MAX_BODY_CHARS, BLANK_CHEQUE_CARRY_CAP } from "../../../shared/definitions/items.js";
6import {
7 emptyEquipment,
8 emptySlots,
9 insertStack,
10 insertStackGrowable,
11 normalizeVault,
12 normalizeInventorySlots,
13 publicEquipment,
14 publicSlots,
15 takeFromSlot,
16 takeMatchingFromSlots,
17 countItemInSlots,
18 cloneStack,
19 singleItemFromStack,
20 stackQuantity,
21 consumeFillCharge
22} from "../../../shared/items/inventory.js";
23import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25import { randomUUID } from "node:crypto";
26import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
27
28export function publicGroundItem (item)
29{
30 const instance = item.stack?.instance ?? null;
31 return {
32 groundItemId: item.groundItemId,
33 tileX: item.tileX,
34 tileY: item.tileY,
35 itemId: item.stack.itemId,
36 quantity: item.stack.quantity,
37 displayName: stackDisplayLabel(item.stack),
38 sprite: itemSpriteName(item.stack.itemId, instance),
39 instance: instance && (instance.kind === "potion" || instance.kind === "letter" || instance.kind === "recipe-paper")
40 ? instance
41 : null,
42 expiresAt: item.expiresAt
43 };
44}
45
46export function bagView (ecs, handle)
47{
48 const vault = normalizeVault(ecs.get(handle, Component.vault));
49 return {
50 inventory: publicSlots(normalizeInventorySlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots())),
51 equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()),
52 vault: publicSlots(vault.slots),
53 vaultReserved: publicSlots(vault.reserved)
54 };
55}
56
57export function applyBagView (ecs, handle, bag)
58{
59 const inventory = ensureInventory(ecs, handle);
60 inventory.slots = normalizeInventorySlots(publicSlots(bag.inventory ?? emptySlots()));
61 const equipment = ensureEquipment(ecs, handle);
62 const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment());
63 equipment.slots = nextEquip.slots;
64 const vault = ensureVault(ecs, handle);
65 const normalized = normalizeVault(
66 bag.vaultReserved != null || (bag.vault && !Array.isArray(bag.vault))
67 ? { slots: bag.vault, reserved: bag.vaultReserved }
68 : bag.vault
69 );
70 vault.slots = publicSlots(normalized.slots);
71 vault.reserved = publicSlots(normalized.reserved);
72 return bagView(ecs, handle);
73}
74
75export function handleItemCommand (world, sessionId, command, now)
76{
77 switch (command.type)
78 {
79 case "drop-item":
80 return dropItem(world, sessionId, command, now);
81 case "pickup-item":
82 return pickupItem(world, sessionId, command);
83 case "equip-item":
84 return equipItem(world, sessionId, command);
85 case "unequip-item":
86 return unequipItem(world, sessionId, command);
87 case "open-bank":
88 return openBank(world, sessionId, command);
89 case "bank-deposit":
90 return bankMove(world, sessionId, command, "inventory", "vault");
91 case "bank-withdraw":
92 return bankMove(world, sessionId, command, "vault", "inventory");
93 case "get-blank-cheques":
94 return getBlankCheques(world, sessionId, command);
95 case "return-blank-cheques":
96 return returnBlankCheques(world, sessionId, command);
97 case "write-cheque":
98 return writeCheque(world, sessionId, command);
99 case "redeem-cheque":
100 return redeemCheque(world, sessionId, command);
101 case "claim-inheritance":
102 return claimInheritance(world, sessionId, command);
103 case "write-letter":
104 return writeLetter(world, sessionId, command);
105 case "edit-letter":
106 return editLetter(world, sessionId, command);
107 case "open-letter":
108 return openLetter(world, sessionId, command);
109 case "eat-item":
110 return eatItem(world, sessionId, command);
111 case "drink-item":
112 return drinkItem(world, sessionId, command);
113 default:
114 return null;
115 }
116}
117
118export function expireGroundItems (world, now)
119{
120 const events = [];
121 for (const item of [...world.groundItems.values()])
122 {
123 if (item.expiresAt > now)
124 { continue; }
125 removeGroundItem(world, item.groundItemId);
126 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
127 }
128 return events;
129}
130
131export function groundItemsInChunk (world, chunkX, chunkY)
132{
133 return [...world.groundItems.values()]
134 .filter((item) => tileToChunk(item.tileX) === chunkX && tileToChunk(item.tileY) === chunkY)
135 .map(publicGroundItem);
136}
137
138export function groundItemsInRegion (world, regionX, regionY, tileToRegion)
139{
140 return [...world.groundItems.values()].filter((item) =>
141 tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY
142 );
143}
144
145export function addGroundItem (world, item)
146{
147 world.groundItems.set(item.groundItemId, item);
148 const key = tileKey(item.tileX, item.tileY);
149 if (!world.groundByTile.has(key))
150 { world.groundByTile.set(key, new Set()); }
151 world.groundByTile.get(key).add(item.groundItemId);
152}
153
154export function removeGroundItem (world, groundItemId)
155{
156 const item = world.groundItems.get(groundItemId);
157 if (!item)
158 { return null; }
159 world.groundItems.delete(groundItemId);
160 const key = tileKey(item.tileX, item.tileY);
161 world.groundByTile.get(key)?.delete(groundItemId);
162 return item;
163}
164
165export function replaceGroundItems (world, items)
166{
167 world.groundItems.clear();
168 world.groundByTile.clear();
169 for (const item of items ?? [])
170 { addGroundItem(world, item); }
171}
172
173export function setGroundItemsForRegion (world, regionX, regionY, items, tileToRegion)
174{
175 for (const item of [...world.groundItems.values()])
176 {
177 if (tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY)
178 { removeGroundItem(world, item.groundItemId); }
179 }
180 for (const item of items ?? [])
181 { addGroundItem(world, item); }
182}
183
184function dropItem (world, sessionId, command, now)
185{
186 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
187 const inventory = ensureInventory(world.ecs, handle);
188 const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null);
189 if (!taken.ok)
190 { throw userError("That inventory slot is empty."); }
191 inventory.slots = taken.slots;
192 const position = world.ecs.get(handle, Component.position);
193 const item = {
194 groundItemId: command.groundItemId,
195 tileX: position.tileX,
196 tileY: position.tileY,
197 stack: taken.taken,
198 droppedAt: now,
199 expiresAt: now + (world.settings.groundItemDespawnDurationMs ?? 600_000),
200 source: "player-drop",
201 droppedByCharacterId: command.characterId
202 };
203 addGroundItem(world, item);
204 return {
205 events: [{ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }],
206 private: bagView(world.ecs, handle)
207 };
208}
209
210function pickupItem (world, sessionId, command)
211{
212 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
213 const item = world.groundItems.get(command.groundItemId);
214 if (!item)
215 { throw userError("That item is no longer on the ground."); }
216 const position = world.ecs.get(handle, Component.position);
217 if (position.tileX !== item.tileX || position.tileY !== item.tileY)
218 { throw userError("Stand on the item to pick it up."); }
219 const def = itemDefinition(item.stack.itemId);
220 if (!def)
221 { throw userError("Unknown item."); }
222 const inventory = ensureInventory(world.ecs, handle);
223 let stackToAdd = item.stack;
224 if (item.stack.itemId === ItemId.blankCheque)
225 {
226 const have = countItemInSlots(inventory.slots, ItemId.blankCheque);
227 const room = BLANK_CHEQUE_CARRY_CAP - have;
228 if (room <= 0)
229 { throw userError(`You already carry ${BLANK_CHEQUE_CARRY_CAP} blank cheques.`); }
230 const takeQty = Math.min(item.stack.quantity, room);
231 stackToAdd = { ...item.stack, quantity: takeQty };
232 }
233 const inserted = insertStack(inventory.slots, stackToAdd, def);
234 if (!inserted.ok)
235 { throw userError("Your inventory cannot hold that."); }
236 inventory.slots = inserted.slots;
237 const events = [];
238 if (item.stack.itemId === ItemId.blankCheque && stackToAdd.quantity < item.stack.quantity)
239 {
240 item.stack.quantity -= stackToAdd.quantity;
241 events.push({
242 type: "ground-item-appear",
243 ...publicGroundItem(item),
244 stack: item.stack,
245 droppedAt: item.droppedAt,
246 source: item.source,
247 droppedByCharacterId: item.droppedByCharacterId,
248 expiresAt: item.expiresAt
249 });
250 }
251 else
252 {
253 removeGroundItem(world, item.groundItemId);
254 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
255 }
256 return {
257 events,
258 private: bagView(world.ecs, handle)
259 };
260}
261
262function equipItem (world, sessionId, command)
263{
264 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
265 const inventory = ensureInventory(world.ecs, handle);
266 const equipment = ensureEquipment(world.ecs, handle);
267 const slotIndex = command.slotIndex | 0;
268 const source = inventory.slots[slotIndex];
269 if (!source || stackQuantity(source.quantity) <= 0)
270 { throw userError("That inventory slot is empty."); }
271 const taken = takeFromSlot(inventory.slots, slotIndex, 1);
272 if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1)
273 { throw userError("That inventory slot is empty."); }
274 if (taken.taken.itemId === ItemId.coins)
275 {
276 inventory.slots = insertStack(taken.slots, taken.taken, itemDefinition(ItemId.coins)).slots;
277 throw userError("Coins cannot be equipped.");
278 }
279 const def = itemDefinition(taken.taken.itemId);
280 const slot = def?.equipment?.slot;
281 if (!slot)
282 {
283 inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
284 throw userError("That item cannot be equipped.");
285 }
286 const skills = world.ecs.get(handle, Component.skills);
287 const equipCheck = canEquipItem(skills, def);
288 if (!equipCheck.ok)
289 {
290 inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
291 throw userError(equipCheck.reason);
292 }
293 const toEquip = singleItemFromStack(taken.taken);
294 const previous = equipment.slots[slot];
295 if (previous)
296 {
297 const previousSingle = singleItemFromStack(previous);
298 const back = insertStack(taken.slots, previousSingle, itemDefinition(previous.itemId));
299 if (!back.ok)
300 {
301 inventory.slots = insertStack(inventory.slots, toEquip, def).slots;
302 throw userError("No inventory space to unequip the current item.");
303 }
304 inventory.slots = back.slots;
305 }
306 else
307 { inventory.slots = taken.slots; }
308 equipment.slots[slot] = toEquip;
309 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
310}
311
312function unequipItem (world, sessionId, command)
313{
314 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
315 const inventory = ensureInventory(world.ecs, handle);
316 const equipment = ensureEquipment(world.ecs, handle);
317 const worn = equipment.slots[command.equipSlot];
318 if (!worn)
319 { throw userError("Nothing is equipped there."); }
320 const def = itemDefinition(worn.itemId);
321 const single = singleItemFromStack(worn);
322 const inserted = insertStack(inventory.slots, single, def);
323 if (!inserted.ok)
324 { throw userError("Your inventory cannot hold that."); }
325 inventory.slots = inserted.slots;
326 equipment.slots[command.equipSlot] = null;
327 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
328}
329
330function eatItem (world, sessionId, command)
331{
332 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
333 syncPlayerHealth(world.ecs, handle);
334 const inventory = ensureInventory(world.ecs, handle);
335 const health = world.ecs.get(handle, Component.health);
336 if (!health)
337 { throw userError("You cannot eat right now."); }
338 if ((health.current | 0) >= (health.max | 0))
339 { throw userError("You are already at full health."); }
340 const slotIndex = command.slotIndex | 0;
341 const slot = inventory.slots[slotIndex];
342 if (!slot || stackQuantity(slot.quantity) <= 0)
343 { throw userError("That inventory slot is empty."); }
344 const def = itemDefinition(slot.itemId);
345 const healing = def?.healing ?? 0;
346 if (healing <= 0)
347 { throw userError("That cannot be eaten."); }
348 const taken = takeFromSlot(inventory.slots, slotIndex, 1);
349 if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1)
350 { throw userError("That inventory slot is empty."); }
351 inventory.slots = taken.slots;
352 health.current = Math.min(health.max | 0, (health.current | 0) + healing);
353 return { events: [], private: bagView(world.ecs, handle) };
354}
355
356function drinkItem (world, sessionId, command)
357{
358 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
359 syncPlayerHealth(world.ecs, handle);
360 const inventory = ensureInventory(world.ecs, handle);
361 const slotIndex = command.slotIndex | 0;
362 const slot = inventory.slots[slotIndex];
363 if (!slot || slot.itemId !== ItemId.potion || slot.instance?.kind !== "potion")
364 { throw userError("That is not a potion."); }
365 const consumed = consumeFillCharge(inventory.slots, slotIndex, {
366 kind: "potion",
367 itemId: ItemId.potion,
368 returnEmptyItemId: ItemId.glassBottle
369 });
370 if (!consumed.ok)
371 {
372 if (consumed.reason === "space")
373 {
374 throw userError(
375 "Need bag space to keep the partially used potion (or empty bottle)."
376 );
377 }
378 throw userError("That inventory slot is empty.");
379 }
380 inventory.slots = consumed.slots;
381 applyPotionEffect(world.ecs, handle, consumed.instance?.effect);
382 return { events: [], private: bagView(world.ecs, handle) };
383}
384
385function applyPotionEffect (ecs, handle, effect)
386{
387 if (!effect || typeof effect !== "object")
388 { return; }
389 const health = ecs.get(handle, Component.health);
390 if (effect.type === "heal" && health)
391 {
392 const amount = Math.max(0, effect.amount | 0 || 0);
393 health.current = Math.min(health.max | 0, (health.current | 0) + amount);
394 return;
395 }
396 if (effect.type === "damage" && health)
397 {
398 const amount = Math.max(0, effect.amount | 0 || 0);
399 health.current = Math.max(0, (health.current | 0) - amount);
400 }
401 // slow / blind / queasy: stub until status-effect systems exist
402}
403
404function openBank (world, sessionId, command)
405{
406 const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
407 const position = world.ecs.get(handle, Component.position);
408 if (!nearBank(world, position.tileX, position.tileY))
409 { throw userError("Stand next to a bank."); }
410 const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank);
411 return {
412 events: shove ? [shove] : [],
413 private: bagView(world.ecs, handle),
414 bank: true
415 };
416}
417
418function bankMove (world, sessionId, command, fromKey, toKey)
419{
420 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
421 requireBank(world, handle);
422 const inventory = ensureInventory(world.ecs, handle);
423 const vault = ensureVault(world.ecs, handle);
424 if (fromKey === "inventory" && toKey === "vault")
425 {
426 const slot = inventory.slots[command.slotIndex | 0];
427 if (slot?.itemId === ItemId.filledCheque)
428 { return redeemCheque(world, sessionId, command); }
429 }
430 const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots;
431 const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null);
432 if (!taken.ok)
433 { throw userError("That slot is empty."); }
434 const def = itemDefinition(taken.taken.itemId);
435 if (toKey === "vault")
436 {
437 const inserted = insertStackGrowable(vault.slots, taken.taken, def);
438 inventory.slots = taken.slots;
439 vault.slots = inserted.slots;
440 }
441 else
442 {
443 const inserted = insertStack(inventory.slots, taken.taken, def);
444 if (!inserted.ok)
445 { throw userError("Not enough space."); }
446 vault.slots = taken.slots;
447 inventory.slots = inserted.slots;
448 }
449 return { events: [], private: bagView(world.ecs, handle), bank: true };
450}
451
452function getBlankCheques (world, sessionId, command)
453{
454 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
455 requireBank(world, handle);
456 const inventory = ensureInventory(world.ecs, handle);
457 const have = countItemInSlots(inventory.slots, ItemId.blankCheque);
458 const need = Math.max(0, BLANK_CHEQUE_CARRY_CAP - have);
459 if (!need)
460 { return { events: [], private: bagView(world.ecs, handle), bank: true }; }
461 const def = itemDefinition(ItemId.blankCheque);
462 const inserted = insertStack(inventory.slots, { itemId: ItemId.blankCheque, quantity: need }, def);
463 if (!inserted.ok)
464 { throw userError("Need inventory space for blank cheques."); }
465 inventory.slots = inserted.slots;
466 return { events: [], private: bagView(world.ecs, handle), bank: true };
467}
468
469function returnBlankCheques (world, sessionId, command)
470{
471 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
472 requireBank(world, handle);
473 const inventory = ensureInventory(world.ecs, handle);
474 const slot = inventory.slots[command.slotIndex | 0];
475 if (!slot || slot.itemId !== ItemId.blankCheque)
476 { throw userError("Select blank cheques."); }
477 const quantity = command.quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, command.quantity | 0));
478 const taken = takeFromSlot(inventory.slots, command.slotIndex | 0, quantity);
479 if (!taken.ok)
480 { throw userError("Select blank cheques."); }
481 inventory.slots = taken.slots;
482 return { events: [], private: bagView(world.ecs, handle), bank: true };
483}
484
485function writeCheque (world, sessionId, command)
486{
487 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
488 const inventory = ensureInventory(world.ecs, handle);
489 const vault = ensureVault(world.ecs, handle);
490 const slotIndex = command.slotIndex | 0;
491 const blankSlot = inventory.slots[slotIndex];
492 if (!blankSlot || blankSlot.itemId !== ItemId.blankCheque)
493 { throw userError("Select a blank cheque."); }
494 const vaultSlot = vault.slots[command.vaultSlotIndex | 0];
495 if (!vaultSlot)
496 { throw userError("Select vault goods to reserve."); }
497 const def = itemDefinition(vaultSlot.itemId);
498 if (!def)
499 { throw userError("Unknown item."); }
500 const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);
501 const available = countItemInSlots(vault.slots, vaultSlot.itemId);
502 if (available < quantity)
503 { throw userError("Not enough unreserved goods in the vault."); }
504 if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))
505 { throw userError("Need a free inventory slot for the filled cheque."); }
506
507 const pulled = takeMatchingFromSlots(vault.slots, {
508 itemId: vaultSlot.itemId,
509 quantity,
510 instance: def.uniqueInstance ? vaultSlot.instance : null
511 });
512 if (!pulled.ok)
513 { throw userError("Not enough unreserved goods in the vault."); }
514
515 const chequeId = randomUUID();
516 const reservedStack = {
517 itemId: pulled.taken.itemId,
518 quantity: pulled.taken.quantity,
519 origin: pulled.taken.origin ?? null,
520 instance: pulled.taken.instance ?? null,
521 chequeId
522 };
523 vault.slots = pulled.slots;
524 vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack];
525
526 const filled = {
527 itemId: ItemId.filledCheque,
528 quantity: 1,
529 origin: null,
530 instance: {
531 kind: "filled-cheque",
532 chequeId,
533 issuerCharacterId: command.characterId,
534 itemId: pulled.taken.itemId,
535 quantity: pulled.taken.quantity,
536 reservedInstance: pulled.taken.instance ?? null,
537 createdAt: Date.now()
538 }
539 };
540 const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1);
541 inventory.slots = blankTaken.slots;
542 if (!inventory.slots[slotIndex])
543 { inventory.slots[slotIndex] = filled; }
544 else
545 {
546 const free = inventory.slots.findIndex((entry) => !entry);
547 inventory.slots[free] = filled;
548 }
549 return { events: [], private: bagView(world.ecs, handle) };
550}
551
552function redeemCheque (world, sessionId, command)
553{
554 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
555 requireBank(world, handle);
556 const inventory = ensureInventory(world.ecs, handle);
557 const vault = ensureVault(world.ecs, handle);
558 const slotIndex = command.slotIndex | 0;
559 const slot = inventory.slots[slotIndex];
560 if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")
561 { throw userError("Select a filled cheque."); }
562
563 const chequeId = slot.instance.chequeId;
564 const issuerId = slot.instance.issuerCharacterId;
565 const goodsDef = itemDefinition(slot.instance.itemId);
566 if (!goodsDef)
567 { throw userError("Unknown reserved goods."); }
568
569 const chequeTaken = takeFromSlot(inventory.slots, slotIndex, 1);
570 if (!chequeTaken.ok)
571 { throw userError("Select a filled cheque."); }
572 inventory.slots = chequeTaken.slots;
573
574 let reservedStack = null;
575 if (Number(issuerId) === Number(command.characterId))
576 {
577 const index = findReservedChequeIndex(vault.reserved, slot.instance);
578 if (index < 0)
579 {
580 inventory.slots[slotIndex] = chequeTaken.taken;
581 throw userError("That cheque cannot be redeemed.");
582 }
583 reservedStack = cloneStack(vault.reserved[index]);
584 vault.reserved = vault.reserved.filter((_, i) => i !== index);
585 }
586 else
587 {
588 const release = world.releaseChequeReservation?.(issuerId, chequeId, slot.instance);
589 if (!release?.ok)
590 {
591 inventory.slots[slotIndex] = chequeTaken.taken;
592 throw userError(release?.error ?? "That cheque cannot be redeemed.");
593 }
594 reservedStack = release.stack;
595 }
596
597 const inserted = insertStackGrowable(vault.slots, {
598 itemId: reservedStack.itemId,
599 quantity: reservedStack.quantity,
600 origin: reservedStack.origin ?? null,
601 origins: reservedStack.origins ?? null,
602 instance: reservedStack.instance ?? null
603 }, goodsDef);
604 if (!inserted.ok)
605 {
606 inventory.slots[slotIndex] = chequeTaken.taken;
607 if (Number(issuerId) === Number(command.characterId))
608 { vault.reserved = [...(vault.reserved ?? []), reservedStack]; }
609 else
610 { world.restoreChequeReservation?.(issuerId, reservedStack); }
611 throw userError("Your vault cannot hold those goods.");
612 }
613 vault.slots = inserted.slots;
614 return { events: [], private: bagView(world.ecs, handle), bank: true };
615}
616
617/** Match reserved vault entry by chequeId, or by goods identity for legacy rows that lost chequeId. */
618export function findReservedChequeIndex (reserved, chequeInstance)
619{
620 const list = reserved ?? [];
621 const chequeId = chequeInstance?.chequeId;
622 if (chequeId != null)
623 {
624 const byId = list.findIndex((entry) => entry?.chequeId === chequeId);
625 if (byId >= 0)
626 { return byId; }
627 }
628 const itemId = chequeInstance?.itemId;
629 const quantity = chequeInstance?.quantity | 0;
630 if (itemId == null || quantity <= 0)
631 { return -1; }
632 return list.findIndex((entry) =>
633 entry
634 && entry.chequeId == null
635 && entry.itemId === itemId
636 && (entry.quantity | 0) === quantity
637 );
638}
639
640function claimInheritance (world, sessionId, command)
641{
642 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
643 requireBank(world, handle);
644 const vault = ensureVault(world.ecs, handle);
645 const remainder = [];
646 for (const stack of command.stacks ?? [])
647 {
648 const def = itemDefinition(stack.itemId);
649 if (!def)
650 {
651 remainder.push(stack);
652 continue;
653 }
654 const inserted = insertStackGrowable(vault.slots, stack, def);
655 if (inserted.ok)
656 { vault.slots = inserted.slots; }
657 else
658 { remainder.push(stack); }
659 }
660 return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
661}
662
663function writeLetter (world, sessionId, command)
664{
665 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
666 const inventory = ensureInventory(world.ecs, handle);
667 const slotIndex = command.slotIndex | 0;
668 const slot = inventory.slots[slotIndex];
669 if (!slot || slot.itemId !== ItemId.paper)
670 { throw userError("Select blank paper."); }
671 const body = normalizeLetterBody(command.body);
672 const appearance = world.ecs.get(handle, Component.appearance);
673 const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim();
674 const letterStack = {
675 itemId: ItemId.letter,
676 quantity: 1,
677 origin: null,
678 instance: {
679 kind: "letter",
680 letterId: randomUUID(),
681 authorCharacterId: command.characterId,
682 authorDisplayName,
683 body,
684 opened: true,
685 writtenAt: Date.now()
686 }
687 };
688 if (slot.quantity <= 1)
689 {
690 inventory.slots[slotIndex] = letterStack;
691 return { events: [], private: bagView(world.ecs, handle) };
692 }
693 const free = inventory.slots.findIndex((entry) => !entry);
694 if (free < 0)
695 { throw userError("Need a free inventory slot for the letter."); }
696 slot.quantity -= 1;
697 inventory.slots[free] = letterStack;
698 return { events: [], private: bagView(world.ecs, handle) };
699}
700
701function editLetter (world, sessionId, command)
702{
703 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
704 const inventory = ensureInventory(world.ecs, handle);
705 const slotIndex = command.slotIndex | 0;
706 const slot = inventory.slots[slotIndex];
707 if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter")
708 { throw userError("That is not a letter."); }
709 if (slot.instance.authorCharacterId !== command.characterId)
710 { throw userError("Only the signer can edit this letter."); }
711 const appearance = world.ecs.get(handle, Component.appearance);
712 const authorDisplayName = `${appearance?.firstName ?? slot.instance.authorDisplayName} ${appearance?.lastName ?? ""}`.trim()
713 || slot.instance.authorDisplayName;
714 slot.instance = {
715 ...slot.instance,
716 authorDisplayName,
717 body: normalizeLetterBody(command.body),
718 writtenAt: Date.now()
719 };
720 return { events: [], private: bagView(world.ecs, handle) };
721}
722
723function openLetter (world, sessionId, command)
724{
725 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
726 const inventory = ensureInventory(world.ecs, handle);
727 const slotIndex = command.slotIndex | 0;
728 const slot = inventory.slots[slotIndex];
729 if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter")
730 { throw userError("That is not a letter."); }
731 if (slot.instance.opened !== false)
732 { return { events: [], private: bagView(world.ecs, handle) }; }
733 slot.instance = { ...slot.instance, opened: true };
734 return { events: [], private: bagView(world.ecs, handle) };
735}
736
737function normalizeLetterBody (raw)
738{
739 const body = String(raw ?? "").replace(/\r\n/g, "\n").trimEnd();
740 if (body.length > LETTER_MAX_BODY_CHARS)
741 { throw userError(`Letters can be at most ${LETTER_MAX_BODY_CHARS} characters.`); }
742 return body;
743}
744
745function requireBank (world, handle)
746{
747 const position = world.ecs.get(handle, Component.position);
748 if (!nearBank(world, position.tileX, position.tileY))
749 { throw userError("Stand next to a bank."); }
750}
751
752function nearBank (world, tileX, tileY)
753{
754 for (let dy = -1; dy <= 1; dy++)
755 {
756 for (let dx = -1; dx <= 1; dx++)
757 {
758 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
759 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
760 if (data.blocks[index]?.typeId === BlockType.bank)
761 { return true; }
762 }
763 }
764 return false;
765}
766
767function ensureInventory (ecs, handle)
768{
769 let inventory = ecs.get(handle, Component.inventory);
770 if (!inventory)
771 { inventory = ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
772 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
773 return inventory;
774}
775
776function ensureEquipment (ecs, handle)
777{
778 return ecs.get(handle, Component.equipment) ?? ecs.add(handle, Component.equipment, emptyEquipment());
779}
780
781function ensureVault (ecs, handle)
782{
783 let vault = ecs.get(handle, Component.vault);
784 if (!vault)
785 { vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); }
786 if (!Array.isArray(vault.slots))
787 { vault.slots = []; }
788 if (!Array.isArray(vault.reserved))
789 { vault.reserved = []; }
790 return vault;
791}
792
793function userError (message)
794{
795 const error = new Error(message);
796 error.userFacing = true;
797 return error;
798}