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