BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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