BlueGit

timfa questward

Files

questward / shared / items / inventory.js

inventory.js

inventory.js 19.8 KiB Download Raw
1export const INVENTORY_SLOTS = 32;
2export const EQUIPMENT_SLOTS = Object.freeze(["head", "chest", "legs", "boots", "weapon", "offhand"]);
3
4import { attachOrigins, mergeOriginLists, normalizeOrigins, splitOrigins } from "./origin.js";
5import { stackRulesFor } from "./stackRules.js";
6import { BLANK_CHEQUE_CARRY_CAP, ItemId, itemDefinition } from "../definitions/items.js";
7import { normalizeChargeStack } from "./charges.js";
8
9/** Stack counts can exceed 32-bit range (coin stacks up to 999B). */
10export function stackQuantity (value)
11{
12 const n = Number(value);
13 if (!Number.isFinite(n) || n <= 0)
14 { return 0; }
15 const q = Math.floor(n);
16 return Number.isSafeInteger(q) ? q : 0;
17}
18
19export function emptySlots (count = INVENTORY_SLOTS)
20{
21 return Array.from({ length: count }, () => null);
22}
23
24export function emptyEquipment ()
25{
26 const slots = {};
27 for (const slot of EQUIPMENT_SLOTS)
28 { slots[slot] = null; }
29 return { slots };
30}
31
32export function cloneStack (stack)
33{
34 return stack ? structuredClone(stack) : null;
35}
36
37/** One item from a stack, preserving a single origin slice (for equip). */
38export function singleItemFromStack (stack)
39{
40 if (!stack)
41 { return null; }
42 const split = splitOrigins(normalizeOrigins(stack), 1);
43 return {
44 itemId: stack.itemId,
45 quantity: 1,
46 instance: stack.instance ? cloneStack(stack.instance) : null,
47 origins: split.taken
48 };
49}
50
51export function potionStackIdentity (instance)
52{
53 if (!instance || instance.kind !== "potion")
54 { return null; }
55 const effectKey = instance.effectKey
56 ?? (instance.effect ? JSON.stringify(instance.effect) : "");
57 const fill = Math.max(1, Math.min(5, instance.fillLevel | 0 || 4));
58 return `${instance.potionKey ?? ""}|${effectKey}|${fill}`;
59}
60
61/** Dye stacks merge when RGB and remaining uses match exactly. */
62export function dyeStackIdentity (instance)
63{
64 if (!instance || instance.kind !== "dye" || !instance.color)
65 { return null; }
66 const fill = Math.max(1, Math.min(5, instance.fillLevel | 0 || 4));
67 return [
68 Math.round((instance.color.r ?? 0) * 1000),
69 Math.round((instance.color.g ?? 0) * 1000),
70 Math.round((instance.color.b ?? 0) * 1000),
71 fill
72 ].join(",");
73}
74
75export function stacksMatch (left, right, definition, { inVault = false } = {})
76{
77 if (!left || !right || left.itemId !== right.itemId)
78 { return false; }
79 const rules = stackRulesFor(definition, { inVault });
80 if (rules.uniqueInstance)
81 {
82 return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
83 }
84 if (definition?.potion)
85 {
86 const a = potionStackIdentity(left.instance);
87 const b = potionStackIdentity(right.instance);
88 return a != null && a === b;
89 }
90 if (definition?.dye)
91 {
92 const a = dyeStackIdentity(left.instance);
93 const b = dyeStackIdentity(right.instance);
94 return a != null && a === b;
95 }
96 if (left.instance != null || right.instance != null)
97 { return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null); }
98 return rules.stackable;
99}
100
101function stackPayload (stack, quantity, origins)
102{
103 return {
104 itemId: stack.itemId,
105 quantity,
106 instance: stack.instance ?? null,
107 origins: origins.map((entry) => ({
108 origin: entry.origin ?? null,
109 quantity: stackQuantity(entry.quantity)
110 })).filter((entry) => entry.quantity > 0)
111 };
112}
113
114export function insertStack (slots, stack, definition, options = {})
115{
116 if (!stack || stack.quantity <= 0)
117 { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; }
118 const rules = stackRulesFor(definition, options);
119 const next = slots.map(cloneStack);
120 let remaining = stackQuantity(stack.quantity);
121 let pendingOrigins = normalizeOrigins(stack);
122
123 if (rules.stackable && !rules.uniqueInstance)
124 {
125 for (const slot of next)
126 {
127 if (!slot || !stacksMatch(slot, stack, definition, options))
128 { continue; }
129 const space = rules.maxStackSize - stackQuantity(slot.quantity);
130 if (space <= 0)
131 { continue; }
132 const add = Math.min(space, remaining);
133 const split = splitOrigins(pendingOrigins, add);
134 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
135 slot.quantity = stackQuantity(slot.quantity) + add;
136 if (stack.instance != null && slot.instance == null)
137 { slot.instance = cloneStack(stack.instance); }
138 delete slot.origin;
139 pendingOrigins = split.remain;
140 remaining -= add;
141 if (remaining === 0)
142 { return { ok: true, slots: next, remainder: 0 }; }
143 }
144 }
145
146 for (let i = 0; i < next.length; i++)
147 {
148 if (next[i])
149 { continue; }
150 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
151 const amount = rules.stackable && !rules.uniqueInstance
152 ? Math.min(remaining, cap)
153 : 1;
154 const split = splitOrigins(pendingOrigins, amount);
155 next[i] = stackPayload(stack, amount, split.taken);
156 pendingOrigins = split.remain;
157 remaining -= amount;
158 if (remaining === 0)
159 { return { ok: true, slots: next, remainder: 0 }; }
160 if (!rules.stackable || rules.uniqueInstance)
161 { break; }
162 }
163 return { ok: false, slots, remainder: remaining };
164}
165
166export function takeFromSlot (slots, slotIndex, quantity = null)
167{
168 const next = slots.map(cloneStack);
169 const slot = next[slotIndex];
170 if (!slot)
171 { return { ok: false, slots, taken: null }; }
172 const maxQty = stackQuantity(slot.quantity);
173 const amount = quantity == null
174 ? maxQty
175 : Math.min(maxQty, Math.max(1, stackQuantity(quantity)));
176 if (amount <= 0)
177 { return { ok: false, slots, taken: null }; }
178 const split = splitOrigins(normalizeOrigins(slot), amount);
179 const taken = stackPayload(slot, amount, split.taken);
180 if (amount >= maxQty)
181 { next[slotIndex] = null; }
182 else
183 {
184 slot.quantity = maxQty - amount;
185 slot.origins = split.remain;
186 delete slot.origin;
187 }
188 return { ok: true, slots: next, taken };
189}
190
191/**
192 * Move or merge a bag stack from one slot into another (same bag).
193 * Empty target → move. Matching stackable → merge into target. Else → swap.
194 */
195export function moveInventorySlot (slots, fromIndex, toIndex)
196{
197 const next = (slots ?? emptySlots()).map(cloneStack);
198 const from = fromIndex | 0;
199 const to = toIndex | 0;
200 if (from === to)
201 { return { ok: true, slots: next, changed: false }; }
202 if (from < 0 || to < 0 || from >= next.length || to >= next.length)
203 { return { ok: false, slots, reason: "Invalid slot." }; }
204 const source = next[from];
205 if (!source || stackQuantity(source.quantity) <= 0)
206 { return { ok: false, slots, reason: "That inventory slot is empty." }; }
207
208 const dest = next[to];
209 if (!dest)
210 {
211 next[to] = source;
212 next[from] = null;
213 return { ok: true, slots: next, changed: true };
214 }
215
216 const def = itemDefinition(source.itemId);
217 if (stacksMatch(source, dest, def))
218 {
219 const rules = stackRulesFor(def);
220 if (rules.stackable && !rules.uniqueInstance)
221 {
222 const space = rules.maxStackSize === Number.POSITIVE_INFINITY
223 ? stackQuantity(source.quantity)
224 : Math.max(0, rules.maxStackSize - stackQuantity(dest.quantity));
225 if (space > 0)
226 {
227 const add = Math.min(space, stackQuantity(source.quantity));
228 const split = splitOrigins(normalizeOrigins(source), add);
229 dest.origins = mergeOriginLists(normalizeOrigins(dest), split.taken);
230 dest.quantity = stackQuantity(dest.quantity) + add;
231 if (source.instance != null && dest.instance == null)
232 { dest.instance = cloneStack(source.instance); }
233 delete dest.origin;
234 const remainQty = stackQuantity(source.quantity) - add;
235 if (remainQty <= 0)
236 { next[from] = null; }
237 else
238 {
239 source.quantity = remainQty;
240 source.origins = split.remain;
241 delete source.origin;
242 }
243 return { ok: true, slots: next, changed: true };
244 }
245 }
246 }
247
248 next[from] = dest;
249 next[to] = source;
250 return { ok: true, slots: next, changed: true };
251}
252
253/**
254 * Spend one fill charge from a potion/dye slot without losing the leftover bottle.
255 * Single bottles always mutate in place (or become an empty bottle). Multi-stacks
256 * peel one bottle and re-insert the reduced fill; tries both split orderings so a
257 * matching stack can absorb either side. Never mutates the input slots array.
258 *
259 * @returns {{ ok: true, slots, exhausted: boolean, instance: object } | { ok: false, reason: string }}
260 */
261export function consumeFillCharge (slots, slotIndex, {
262 kind = null,
263 itemId = null,
264 definition = null,
265 returnEmptyItemId = null
266} = {})
267{
268 const index = slotIndex | 0;
269 const source = slots?.[index];
270 if (!source || stackQuantity(source.quantity) <= 0)
271 { return { ok: false, reason: "empty" }; }
272 if (itemId != null && source.itemId !== itemId)
273 { return { ok: false, reason: "wrong-item" }; }
274 if (kind != null && source.instance?.kind !== kind)
275 { return { ok: false, reason: "wrong-item" }; }
276 const def = definition ?? itemDefinition(source.itemId);
277 if (!def)
278 { return { ok: false, reason: "unknown" }; }
279
280 const fill = Math.max(1, Math.min(5, source.instance?.fillLevel | 0 || 4));
281 const qty = stackQuantity(source.quantity);
282 const usedInstance = cloneStack(source.instance) ?? { kind, fillLevel: fill };
283
284 if (qty === 1)
285 {
286 const next = slots.map(cloneStack);
287 if (fill <= 1)
288 {
289 next[index] = null;
290 if (returnEmptyItemId)
291 {
292 const emptyDef = itemDefinition(returnEmptyItemId);
293 const emptyStack = attachOrigins({
294 itemId: returnEmptyItemId,
295 quantity: 1,
296 origins: normalizeOrigins(source)
297 });
298 const inserted = insertStack(next, emptyStack, emptyDef);
299 if (!inserted.ok || inserted.remainder > 0)
300 { return { ok: false, reason: "space" }; }
301 return { ok: true, slots: inserted.slots, exhausted: true, instance: usedInstance };
302 }
303 return { ok: true, slots: next, exhausted: true, instance: usedInstance };
304 }
305 next[index].instance = { ...next[index].instance, fillLevel: fill - 1 };
306 return { ok: true, slots: next, exhausted: false, instance: usedInstance };
307 }
308
309 // Multi-stack: try leaving the remainder in place, then the reduced bottle in place.
310 const reducedFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, false);
311 if (reducedFirst.ok)
312 { return { ...reducedFirst, instance: usedInstance }; }
313 const remainderFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, true);
314 if (remainderFirst.ok)
315 { return { ...remainderFirst, instance: usedInstance }; }
316 return { ok: false, reason: "space" };
317}
318
319function tryPeelFillCharge (slots, index, fill, def, returnEmptyItemId, remainderStaysInSlot)
320{
321 const peeled = takeFromSlot(slots, index, 1);
322 if (!peeled.ok || !peeled.taken)
323 { return { ok: false }; }
324
325 if (fill <= 1)
326 {
327 if (!returnEmptyItemId)
328 { return { ok: true, slots: peeled.slots, exhausted: true }; }
329 const emptyDef = itemDefinition(returnEmptyItemId);
330 const emptyStack = attachOrigins({
331 itemId: returnEmptyItemId,
332 quantity: 1,
333 origins: normalizeOrigins(peeled.taken)
334 });
335 const inserted = insertStack(peeled.slots, emptyStack, emptyDef);
336 if (!inserted.ok || inserted.remainder > 0)
337 { return { ok: false }; }
338 return { ok: true, slots: inserted.slots, exhausted: true };
339 }
340
341 const reduced = {
342 itemId: peeled.taken.itemId,
343 quantity: 1,
344 instance: { ...cloneStack(peeled.taken.instance), fillLevel: fill - 1 },
345 origins: peeled.taken.origins
346 };
347 const remainder = peeled.slots[index]
348 ? cloneStack(peeled.slots[index])
349 : null;
350
351 if (!remainderStaysInSlot)
352 {
353 const inserted = insertStack(peeled.slots, reduced, def);
354 if (!inserted.ok || inserted.remainder > 0)
355 { return { ok: false }; }
356 return { ok: true, slots: inserted.slots, exhausted: false };
357 }
358
359 // Put reduced bottle back in the original slot; re-home the untouched remainder.
360 const next = peeled.slots.map(cloneStack);
361 next[index] = stackPayload(reduced, 1, normalizeOrigins(reduced));
362 if (!remainder)
363 { return { ok: true, slots: next, exhausted: false }; }
364 const inserted = insertStack(next, remainder, def);
365 if (!inserted.ok || inserted.remainder > 0)
366 { return { ok: false }; }
367 return { ok: true, slots: inserted.slots, exhausted: false };
368}
369
370/** Like insertStack, but grows the slot array when capacity runs out (vault). */
371export function insertStackGrowable (slots, stack, definition)
372{
373 if (!stack || stack.quantity <= 0)
374 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
375 let next = (slots ?? []).map(cloneStack);
376 let remaining = stackQuantity(stack.quantity);
377 let pendingOrigins = normalizeOrigins(stack);
378 const rules = stackRulesFor(definition, { inVault: true });
379
380 if (rules.stackable && !rules.uniqueInstance)
381 {
382 for (const slot of next)
383 {
384 if (!slot || !stacksMatch(slot, stack, definition, { inVault: true }))
385 { continue; }
386 const space = rules.maxStackSize - stackQuantity(slot.quantity);
387 if (space <= 0)
388 { continue; }
389 const add = Math.min(space, remaining);
390 const split = splitOrigins(pendingOrigins, add);
391 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
392 slot.quantity = stackQuantity(slot.quantity) + add;
393 if (stack.instance != null && slot.instance == null)
394 { slot.instance = cloneStack(stack.instance); }
395 delete slot.origin;
396 pendingOrigins = split.remain;
397 remaining -= add;
398 if (remaining === 0)
399 { return { ok: true, slots: next, remainder: 0 }; }
400 }
401 }
402
403 while (remaining > 0)
404 {
405 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
406 const amount = rules.stackable && !rules.uniqueInstance
407 ? Math.min(remaining, cap)
408 : 1;
409 const split = splitOrigins(pendingOrigins, amount);
410 next.push(stackPayload(stack, amount, split.taken));
411 pendingOrigins = split.remain;
412 remaining -= amount;
413 if (!rules.stackable || rules.uniqueInstance)
414 { break; }
415 }
416 return { ok: remaining === 0, slots: next, remainder: remaining };
417}
418
419/** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
420export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
421{
422 let remaining = Math.max(0, stackQuantity(quantity));
423 if (!remaining)
424 { return { ok: false, slots, taken: null }; }
425 const next = (slots ?? []).map(cloneStack);
426 const takenOrigins = [];
427 for (let i = 0; i < next.length && remaining > 0; i++)
428 {
429 const slot = next[i];
430 if (!slot || slot.itemId !== itemId)
431 { continue; }
432 if (instance != null)
433 {
434 if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance))
435 { continue; }
436 }
437 const amount = Math.min(stackQuantity(slot.quantity), remaining);
438 const split = splitOrigins(normalizeOrigins(slot), amount);
439 takenOrigins.push(...split.taken);
440 if (amount >= stackQuantity(slot.quantity))
441 { next[i] = null; }
442 else
443 {
444 slot.quantity = stackQuantity(slot.quantity) - amount;
445 slot.origins = split.remain;
446 delete slot.origin;
447 }
448 remaining -= amount;
449 }
450 if (remaining > 0)
451 { return { ok: false, slots, taken: null }; }
452 return {
453 ok: true,
454 slots: compact ? next.filter((slot) => slot) : next,
455 taken: attachOrigins({
456 itemId,
457 quantity: stackQuantity(quantity),
458 instance: instance ?? null,
459 origins: mergeOriginLists([], takenOrigins)
460 })
461 };
462}
463
464export function countItemInSlots (slots, itemId)
465{
466 let total = 0;
467 for (const slot of slots ?? [])
468 {
469 if (slot?.itemId === itemId)
470 { total += stackQuantity(slot.quantity); }
471 }
472 return total;
473}
474
475export function countCoinsInSlots (slots)
476{
477 return countItemInSlots(slots, ItemId.coins);
478}
479
480/** Remove coin quantity from bag slots (FIFO across coin stacks). */
481export function takeCoinsFromSlots (slots, amount)
482{
483 let remaining = stackQuantity(amount);
484 if (!remaining)
485 { return { ok: true, slots: (slots ?? []).map(cloneStack) }; }
486 if (countCoinsInSlots(slots) < remaining)
487 { return { ok: false, slots: (slots ?? []).map(cloneStack) }; }
488 let next = (slots ?? []).map(cloneStack);
489 for (let i = 0; i < next.length && remaining > 0; i++)
490 {
491 if (!next[i] || next[i].itemId !== ItemId.coins)
492 { continue; }
493 const taken = takeFromSlot(next, i, remaining);
494 if (!taken.ok)
495 { continue; }
496 next = taken.slots;
497 remaining -= stackQuantity(taken.taken?.quantity);
498 }
499 return { ok: remaining === 0, slots: next };
500}
501
502/** Add coin stacks, splitting at max stack size (999B). */
503export function addCoinsToSlots (slots, amount, { growable = false } = {})
504{
505 const def = itemDefinition(ItemId.coins);
506 if (!def || amount <= 0)
507 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
508 let next = (slots ?? []).map(cloneStack);
509 if (!growable && next.length < INVENTORY_SLOTS)
510 {
511 const padded = emptySlots();
512 for (let i = 0; i < next.length; i++)
513 { padded[i] = next[i]; }
514 next = padded;
515 }
516 let remaining = stackQuantity(amount);
517 const insert = growable ? insertStackGrowable : insertStack;
518 while (remaining > 0)
519 {
520 const chunk = Math.min(remaining, def.maxStackSize ?? 99);
521 const result = insert(next, attachOrigins({ itemId: ItemId.coins, quantity: chunk }), def);
522 next = result.slots;
523 const placed = chunk - (result.remainder ?? 0);
524 remaining -= placed;
525 if (!result.ok || result.remainder > 0)
526 { return { ok: false, slots: next, remainder: remaining }; }
527 }
528 return { ok: true, slots: next, remainder: 0 };
529}
530
531/** Convert legacy currency counters into coin stacks. */
532export function migrateBagCoins (bag)
533{
534 let inventory = bag.inventory ?? emptySlots();
535 let vault = bag.vault ?? [];
536 if (bag.currency > 0)
537 {
538 const added = addCoinsToSlots(inventory, stackQuantity(bag.currency), { growable: false });
539 inventory = added.slots;
540 }
541 if (bag.vaultCurrency > 0)
542 {
543 const added = addCoinsToSlots(vault, stackQuantity(bag.vaultCurrency), { growable: true });
544 vault = added.slots;
545 }
546 return {
547 ...bag,
548 inventory,
549 vault,
550 currency: 0,
551 vaultCurrency: 0
552 };
553}
554
555export function migrateInheritanceCoins (inheritance)
556{
557 if (!inheritance?.currency)
558 { return inheritance; }
559 const added = addCoinsToSlots(inheritance.slots ?? emptySlots(), stackQuantity(inheritance.currency), { growable: true });
560 return {
561 ...inheritance,
562 slots: added.slots,
563 currency: 0
564 };
565}
566
567/** Trim excess blank cheques in inventory (e.g. after legacy saves or bugs). */
568export function normalizeInventorySlots (slots)
569{
570 const capped = capItemTotalInSlots(slots ?? emptySlots(), ItemId.blankCheque, BLANK_CHEQUE_CARRY_CAP);
571 return capped.map((slot) => normalizeChargeStack(slot));
572}
573
574export function capItemTotalInSlots (slots, itemId, cap)
575{
576 const next = (slots ?? []).map(cloneStack);
577 let total = countItemInSlots(next, itemId);
578 if (total <= cap)
579 { return next; }
580 let toRemove = total - cap;
581 for (let i = next.length - 1; i >= 0 && toRemove > 0; i--)
582 {
583 const slot = next[i];
584 if (!slot || slot.itemId !== itemId)
585 { continue; }
586 const beforeQty = stackQuantity(slot.quantity);
587 const drop = Math.min(beforeQty, toRemove);
588 const { remain } = splitOrigins(normalizeOrigins({ ...slot, quantity: beforeQty }), drop);
589 slot.quantity = beforeQty - drop;
590 slot.origins = remain;
591 delete slot.origin;
592 toRemove -= drop;
593 if (slot.quantity <= 0)
594 { next[i] = null; }
595 }
596 return next;
597}
598
599export function normalizeVault (raw)
600{
601 if (Array.isArray(raw))
602 {
603 return {
604 slots: raw.map((slot) => normalizeChargeStack(cloneStack(slot))),
605 reserved: []
606 };
607 }
608 return {
609 slots: (raw?.slots ?? []).map((slot) => normalizeChargeStack(cloneStack(slot))),
610 reserved: (raw?.reserved ?? []).map((slot) => normalizeChargeStack(cloneStack(slot)))
611 };
612}
613
614export function serializeVault (vault)
615{
616 const normalized = normalizeVault(vault);
617 return {
618 slots: publicSlots(normalized.slots),
619 reserved: publicSlots(normalized.reserved)
620 };
621}
622
623export function publicSlots (slots)
624{
625 return (slots ?? emptySlots()).map((slot) =>
626 {
627 if (!slot)
628 { return null; }
629 const payload = attachOrigins(cloneStack(slot));
630 const next = {
631 itemId: payload.itemId,
632 quantity: payload.quantity,
633 origins: payload.origins,
634 instance: payload.instance ?? null
635 };
636 // Cheque reservations keep chequeId so redeem can match the paper to vault goods.
637 if (payload.chequeId != null)
638 { next.chequeId = payload.chequeId; }
639 return next;
640 });
641}
642
643export function publicEquipment (equipment)
644{
645 const slots = {};
646 for (const slot of EQUIPMENT_SLOTS)
647 { slots[slot] = equipment?.slots?.[slot] ? cloneStack(equipment.slots[slot]) : null; }
648 return { slots };
649}