BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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