BlueGit

timfa questward

Files

questward / shared / items / inventory.js

inventory.js

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