BlueGit

timfa questward

Files

questward / shared / items / inventory.js

inventory.js

inventory.js 12.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";
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 return `${instance.potionKey ?? ""}|${effectKey}`;
57}
58
59export function stacksMatch (left, right, definition, { inVault = false } = {})
60{
61 if (!left || !right || left.itemId !== right.itemId)
62 { return false; }
63 const rules = stackRulesFor(definition, { inVault });
64 if (rules.uniqueInstance)
65 {
66 return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
67 }
68 if (definition?.potion)
69 {
70 const a = potionStackIdentity(left.instance);
71 const b = potionStackIdentity(right.instance);
72 return a != null && a === b;
73 }
74 if (left.instance != null || right.instance != null)
75 { return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null); }
76 return rules.stackable;
77}
78
79function stackPayload (stack, quantity, origins)
80{
81 return {
82 itemId: stack.itemId,
83 quantity,
84 instance: stack.instance ?? null,
85 origins: origins.map((entry) => ({
86 origin: entry.origin ?? null,
87 quantity: stackQuantity(entry.quantity)
88 })).filter((entry) => entry.quantity > 0)
89 };
90}
91
92export function insertStack (slots, stack, definition, options = {})
93{
94 if (!stack || stack.quantity <= 0)
95 { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; }
96 const rules = stackRulesFor(definition, options);
97 const next = slots.map(cloneStack);
98 let remaining = stackQuantity(stack.quantity);
99 let pendingOrigins = normalizeOrigins(stack);
100
101 if (rules.stackable && !rules.uniqueInstance)
102 {
103 for (const slot of next)
104 {
105 if (!slot || !stacksMatch(slot, stack, definition, options))
106 { continue; }
107 const space = rules.maxStackSize - stackQuantity(slot.quantity);
108 if (space <= 0)
109 { continue; }
110 const add = Math.min(space, remaining);
111 const split = splitOrigins(pendingOrigins, add);
112 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
113 slot.quantity = stackQuantity(slot.quantity) + add;
114 if (stack.instance != null && slot.instance == null)
115 { slot.instance = cloneStack(stack.instance); }
116 delete slot.origin;
117 pendingOrigins = split.remain;
118 remaining -= add;
119 if (remaining === 0)
120 { return { ok: true, slots: next, remainder: 0 }; }
121 }
122 }
123
124 for (let i = 0; i < next.length; i++)
125 {
126 if (next[i])
127 { continue; }
128 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
129 const amount = rules.stackable && !rules.uniqueInstance
130 ? Math.min(remaining, cap)
131 : 1;
132 const split = splitOrigins(pendingOrigins, amount);
133 next[i] = stackPayload(stack, amount, split.taken);
134 pendingOrigins = split.remain;
135 remaining -= amount;
136 if (remaining === 0)
137 { return { ok: true, slots: next, remainder: 0 }; }
138 if (!rules.stackable || rules.uniqueInstance)
139 { break; }
140 }
141 return { ok: false, slots, remainder: remaining };
142}
143
144export function takeFromSlot (slots, slotIndex, quantity = null)
145{
146 const next = slots.map(cloneStack);
147 const slot = next[slotIndex];
148 if (!slot)
149 { return { ok: false, slots, taken: null }; }
150 const maxQty = stackQuantity(slot.quantity);
151 const amount = quantity == null
152 ? maxQty
153 : Math.min(maxQty, Math.max(1, stackQuantity(quantity)));
154 if (amount <= 0)
155 { return { ok: false, slots, taken: null }; }
156 const split = splitOrigins(normalizeOrigins(slot), amount);
157 const taken = stackPayload(slot, amount, split.taken);
158 if (amount >= maxQty)
159 { next[slotIndex] = null; }
160 else
161 {
162 slot.quantity = maxQty - amount;
163 slot.origins = split.remain;
164 delete slot.origin;
165 }
166 return { ok: true, slots: next, taken };
167}
168
169/** Like insertStack, but grows the slot array when capacity runs out (vault). */
170export function insertStackGrowable (slots, stack, definition)
171{
172 if (!stack || stack.quantity <= 0)
173 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
174 let next = (slots ?? []).map(cloneStack);
175 let remaining = stackQuantity(stack.quantity);
176 let pendingOrigins = normalizeOrigins(stack);
177 const rules = stackRulesFor(definition, { inVault: true });
178
179 if (rules.stackable && !rules.uniqueInstance)
180 {
181 for (const slot of next)
182 {
183 if (!slot || !stacksMatch(slot, stack, definition, { inVault: true }))
184 { continue; }
185 const space = rules.maxStackSize - stackQuantity(slot.quantity);
186 if (space <= 0)
187 { continue; }
188 const add = Math.min(space, remaining);
189 const split = splitOrigins(pendingOrigins, add);
190 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
191 slot.quantity = stackQuantity(slot.quantity) + add;
192 if (stack.instance != null && slot.instance == null)
193 { slot.instance = cloneStack(stack.instance); }
194 delete slot.origin;
195 pendingOrigins = split.remain;
196 remaining -= add;
197 if (remaining === 0)
198 { return { ok: true, slots: next, remainder: 0 }; }
199 }
200 }
201
202 while (remaining > 0)
203 {
204 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
205 const amount = rules.stackable && !rules.uniqueInstance
206 ? Math.min(remaining, cap)
207 : 1;
208 const split = splitOrigins(pendingOrigins, amount);
209 next.push(stackPayload(stack, amount, split.taken));
210 pendingOrigins = split.remain;
211 remaining -= amount;
212 if (!rules.stackable || rules.uniqueInstance)
213 { break; }
214 }
215 return { ok: remaining === 0, slots: next, remainder: remaining };
216}
217
218/** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */
219export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true })
220{
221 let remaining = Math.max(0, stackQuantity(quantity));
222 if (!remaining)
223 { return { ok: false, slots, taken: null }; }
224 const next = (slots ?? []).map(cloneStack);
225 const takenOrigins = [];
226 for (let i = 0; i < next.length && remaining > 0; i++)
227 {
228 const slot = next[i];
229 if (!slot || slot.itemId !== itemId)
230 { continue; }
231 if (instance != null)
232 {
233 if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance))
234 { continue; }
235 }
236 const amount = Math.min(stackQuantity(slot.quantity), remaining);
237 const split = splitOrigins(normalizeOrigins(slot), amount);
238 takenOrigins.push(...split.taken);
239 if (amount >= stackQuantity(slot.quantity))
240 { next[i] = null; }
241 else
242 {
243 slot.quantity = stackQuantity(slot.quantity) - amount;
244 slot.origins = split.remain;
245 delete slot.origin;
246 }
247 remaining -= amount;
248 }
249 if (remaining > 0)
250 { return { ok: false, slots, taken: null }; }
251 return {
252 ok: true,
253 slots: compact ? next.filter((slot) => slot) : next,
254 taken: attachOrigins({
255 itemId,
256 quantity: stackQuantity(quantity),
257 instance: instance ?? null,
258 origins: mergeOriginLists([], takenOrigins)
259 })
260 };
261}
262
263export function countItemInSlots (slots, itemId)
264{
265 let total = 0;
266 for (const slot of slots ?? [])
267 {
268 if (slot?.itemId === itemId)
269 { total += stackQuantity(slot.quantity); }
270 }
271 return total;
272}
273
274export function countCoinsInSlots (slots)
275{
276 return countItemInSlots(slots, ItemId.coins);
277}
278
279/** Remove coin quantity from bag slots (FIFO across coin stacks). */
280export function takeCoinsFromSlots (slots, amount)
281{
282 let remaining = stackQuantity(amount);
283 if (!remaining)
284 { return { ok: true, slots: (slots ?? []).map(cloneStack) }; }
285 if (countCoinsInSlots(slots) < remaining)
286 { return { ok: false, slots: (slots ?? []).map(cloneStack) }; }
287 let next = (slots ?? []).map(cloneStack);
288 for (let i = 0; i < next.length && remaining > 0; i++)
289 {
290 if (!next[i] || next[i].itemId !== ItemId.coins)
291 { continue; }
292 const taken = takeFromSlot(next, i, remaining);
293 if (!taken.ok)
294 { continue; }
295 next = taken.slots;
296 remaining -= stackQuantity(taken.taken?.quantity);
297 }
298 return { ok: remaining === 0, slots: next };
299}
300
301/** Add coin stacks, splitting at max stack size (999B). */
302export function addCoinsToSlots (slots, amount, { growable = false } = {})
303{
304 const def = itemDefinition(ItemId.coins);
305 if (!def || amount <= 0)
306 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
307 let next = (slots ?? []).map(cloneStack);
308 if (!growable && next.length < INVENTORY_SLOTS)
309 {
310 const padded = emptySlots();
311 for (let i = 0; i < next.length; i++)
312 { padded[i] = next[i]; }
313 next = padded;
314 }
315 let remaining = stackQuantity(amount);
316 const insert = growable ? insertStackGrowable : insertStack;
317 while (remaining > 0)
318 {
319 const chunk = Math.min(remaining, def.maxStackSize ?? 99);
320 const result = insert(next, { itemId: ItemId.coins, quantity: chunk }, def);
321 next = result.slots;
322 const placed = chunk - (result.remainder ?? 0);
323 remaining -= placed;
324 if (!result.ok || result.remainder > 0)
325 { return { ok: false, slots: next, remainder: remaining }; }
326 }
327 return { ok: true, slots: next, remainder: 0 };
328}
329
330/** Convert legacy currency counters into coin stacks. */
331export function migrateBagCoins (bag)
332{
333 let inventory = bag.inventory ?? emptySlots();
334 let vault = bag.vault ?? [];
335 if (bag.currency > 0)
336 {
337 const added = addCoinsToSlots(inventory, stackQuantity(bag.currency), { growable: false });
338 inventory = added.slots;
339 }
340 if (bag.vaultCurrency > 0)
341 {
342 const added = addCoinsToSlots(vault, stackQuantity(bag.vaultCurrency), { growable: true });
343 vault = added.slots;
344 }
345 return {
346 ...bag,
347 inventory,
348 vault,
349 currency: 0,
350 vaultCurrency: 0
351 };
352}
353
354export function migrateInheritanceCoins (inheritance)
355{
356 if (!inheritance?.currency)
357 { return inheritance; }
358 const added = addCoinsToSlots(inheritance.slots ?? emptySlots(), stackQuantity(inheritance.currency), { growable: true });
359 return {
360 ...inheritance,
361 slots: added.slots,
362 currency: 0
363 };
364}
365
366/** Trim excess blank cheques in inventory (e.g. after legacy saves or bugs). */
367export function normalizeInventorySlots (slots)
368{
369 return capItemTotalInSlots(slots ?? emptySlots(), ItemId.blankCheque, BLANK_CHEQUE_CARRY_CAP);
370}
371
372export function capItemTotalInSlots (slots, itemId, cap)
373{
374 const next = (slots ?? []).map(cloneStack);
375 let total = countItemInSlots(next, itemId);
376 if (total <= cap)
377 { return next; }
378 let toRemove = total - cap;
379 for (let i = next.length - 1; i >= 0 && toRemove > 0; i--)
380 {
381 const slot = next[i];
382 if (!slot || slot.itemId !== itemId)
383 { continue; }
384 const beforeQty = stackQuantity(slot.quantity);
385 const drop = Math.min(beforeQty, toRemove);
386 const { remain } = splitOrigins(normalizeOrigins({ ...slot, quantity: beforeQty }), drop);
387 slot.quantity = beforeQty - drop;
388 slot.origins = remain;
389 delete slot.origin;
390 toRemove -= drop;
391 if (slot.quantity <= 0)
392 { next[i] = null; }
393 }
394 return next;
395}
396
397export function normalizeVault (raw)
398{
399 if (Array.isArray(raw))
400 { return { slots: raw.map(cloneStack), reserved: [] }; }
401 return {
402 slots: (raw?.slots ?? []).map(cloneStack),
403 reserved: (raw?.reserved ?? []).map(cloneStack)
404 };
405}
406
407export function serializeVault (vault)
408{
409 const normalized = normalizeVault(vault);
410 return {
411 slots: publicSlots(normalized.slots),
412 reserved: publicSlots(normalized.reserved)
413 };
414}
415
416export function publicSlots (slots)
417{
418 return (slots ?? emptySlots()).map((slot) =>
419 {
420 if (!slot)
421 { return null; }
422 const payload = attachOrigins(cloneStack(slot));
423 const next = {
424 itemId: payload.itemId,
425 quantity: payload.quantity,
426 origins: payload.origins,
427 instance: payload.instance ?? null
428 };
429 // Cheque reservations keep chequeId so redeem can match the paper to vault goods.
430 if (payload.chequeId != null)
431 { next.chequeId = payload.chequeId; }
432 return next;
433 });
434}
435
436export function publicEquipment (equipment)
437{
438 const slots = {};
439 for (const slot of EQUIPMENT_SLOTS)
440 { slots[slot] = equipment?.slots?.[slot] ? cloneStack(equipment.slots[slot]) : null; }
441 return { slots };
442}