BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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