| 1 | import { Component } from "../ecs/components.js"; |
| 2 | import { BlockType } from "../../../shared/definitions/tiles.js"; |
| 3 | import { |
| 4 | AlchemyStepKind, |
| 5 | CAULDRON_SLOT_COUNT, |
| 6 | DYE_CAULDRON_SLOT_COUNT |
| 7 | } from "../../../shared/definitions/alchemy.js"; |
| 8 | import { ItemId, itemDefinition } from "../../../shared/definitions/items.js"; |
| 9 | import { SkillId } from "../../../shared/definitions/skills.js"; |
| 10 | import { |
| 11 | evaluateAlchemyBottle, |
| 12 | potionItemInstance, |
| 13 | recipePaperBody, |
| 14 | resolvedAlchemyPotions, |
| 15 | cauldronFlavorText |
| 16 | } from "../../../shared/alchemy/recipes.js"; |
| 17 | import { |
| 18 | DEFAULT_DYE_FILL, |
| 19 | FLOWER_MAX_STACK, |
| 20 | mixFlowersForDye |
| 21 | } from "../../../shared/definitions/dyes.js"; |
| 22 | import { bagView, placeOrMergeGroundStack } from "../items/bags.js"; |
| 23 | import { |
| 24 | countItemInSlots, |
| 25 | emptySlots, |
| 26 | insertStack, |
| 27 | normalizeInventorySlots, |
| 28 | takeMatchingFromSlots, |
| 29 | stackQuantity |
| 30 | } from "../../../shared/items/inventory.js"; |
| 31 | import { isFullPotionBottle } from "../../../shared/items/charges.js"; |
| 32 | import { attachOrigins, craftOrigin, CraftOriginVerb, writtenOrigin, normalizeOrigins } from "../../../shared/items/origin.js"; |
| 33 | import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js"; |
| 34 | import { |
| 35 | craftXpForConsumedInputs, |
| 36 | craftXpMultiplierForSkill |
| 37 | } from "../../../shared/definitions/gathering.js"; |
| 38 | import { tileToChunk, tileToLocal } from "../world/coordinates.js"; |
| 39 | import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; |
| 40 | import { randomUUID } from "node:crypto"; |
| 41 | import { tileShoveTowardBlock } from "../simulation/tileInteract.js"; |
| 42 | |
| 43 | /** |
| 44 | * Cauldron UI slot contents live on the client only. |
| 45 | * Server sessions track brew *steps* and soft ingredient claims (itemId/qty/instance) |
| 46 | * without removing items from the bag until bottle / create-dye succeeds. |
| 47 | */ |
| 48 | |
| 49 | function userError (message) |
| 50 | { |
| 51 | const error = new Error(message); |
| 52 | error.userFacing = true; |
| 53 | return error; |
| 54 | } |
| 55 | |
| 56 | function characterDisplayName (world, handle) |
| 57 | { |
| 58 | const appearance = world.ecs.get(handle, Component.appearance); |
| 59 | const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); |
| 60 | return name || "someone"; |
| 61 | } |
| 62 | |
| 63 | function ensureSessions (world) |
| 64 | { |
| 65 | if (!world.cauldronSessions) |
| 66 | { world.cauldronSessions = new Map(); } |
| 67 | return world.cauldronSessions; |
| 68 | } |
| 69 | |
| 70 | function emptySession () |
| 71 | { |
| 72 | return { |
| 73 | /** Soft claims for alchemy inserts — still in the bag until bottle. */ |
| 74 | pendingBrew: [], |
| 75 | steps: [], |
| 76 | lastSuccessRecipe: null |
| 77 | }; |
| 78 | } |
| 79 | |
| 80 | function sessionView (session) |
| 81 | { |
| 82 | const steps = session.steps ?? []; |
| 83 | return { |
| 84 | // Slots / dye slots are client-only; never authoritative on the server. |
| 85 | slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null), |
| 86 | dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null), |
| 87 | brew: (session.pendingBrew ?? []).map((row) => ({ |
| 88 | itemId: row.itemId, |
| 89 | quantity: row.quantity | 0, |
| 90 | instance: row.instance ? structuredClone(row.instance) : null |
| 91 | })), |
| 92 | steps: steps.map((step) => ({ ...step })), |
| 93 | flavorText: cauldronFlavorText(steps), |
| 94 | canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert), |
| 95 | /** Top ingredient slots lock after the first brew step until Bottle/Clear. */ |
| 96 | canAddIngredients: steps.length === 0, |
| 97 | canSaveRecipe: !!session.lastSuccessRecipe, |
| 98 | lastSuccess: session.lastSuccessRecipe |
| 99 | ? { |
| 100 | potionKey: session.lastSuccessRecipe.potionKey, |
| 101 | displayName: session.lastSuccessRecipe.displayName, |
| 102 | minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1 |
| 103 | } |
| 104 | : null |
| 105 | }; |
| 106 | } |
| 107 | |
| 108 | function nearCauldron (world, tileX, tileY) |
| 109 | { |
| 110 | for (let dy = -1; dy <= 1; dy++) |
| 111 | { |
| 112 | for (let dx = -1; dx <= 1; dx++) |
| 113 | { |
| 114 | if (dx === 0 && dy === 0) |
| 115 | { continue; } |
| 116 | const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy)); |
| 117 | const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx); |
| 118 | if (data.blocks[index]?.typeId === BlockType.cauldron) |
| 119 | { return true; } |
| 120 | } |
| 121 | } |
| 122 | return false; |
| 123 | } |
| 124 | |
| 125 | function requireNearCauldron (world, handle) |
| 126 | { |
| 127 | const position = world.ecs.get(handle, Component.position); |
| 128 | if (!nearCauldron(world, position.tileX, position.tileY)) |
| 129 | { throw userError("Stand next to a cauldron."); } |
| 130 | } |
| 131 | |
| 132 | function requireSession (world, characterId) |
| 133 | { |
| 134 | const session = ensureSessions(world).get(characterId); |
| 135 | if (!session) |
| 136 | { throw userError("Open a cauldron first."); } |
| 137 | return session; |
| 138 | } |
| 139 | |
| 140 | function clearAlchemy (session) |
| 141 | { |
| 142 | session.pendingBrew = []; |
| 143 | session.steps = []; |
| 144 | } |
| 145 | |
| 146 | function ensureInventory (world, handle) |
| 147 | { |
| 148 | let inventory = world.ecs.get(handle, Component.inventory); |
| 149 | if (!inventory) |
| 150 | { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); } |
| 151 | inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots()); |
| 152 | return inventory; |
| 153 | } |
| 154 | |
| 155 | function countMatchingInstance (slots, itemId, instance) |
| 156 | { |
| 157 | let total = 0; |
| 158 | const key = JSON.stringify(instance ?? null); |
| 159 | for (const slot of slots ?? []) |
| 160 | { |
| 161 | if (!slot || slot.itemId !== itemId) |
| 162 | { continue; } |
| 163 | if (JSON.stringify(slot.instance ?? null) !== key) |
| 164 | { continue; } |
| 165 | total += stackQuantity(slot.quantity); |
| 166 | } |
| 167 | return total; |
| 168 | } |
| 169 | |
| 170 | function pendingClaimedQuantity (pendingBrew, itemId, instance) |
| 171 | { |
| 172 | const key = JSON.stringify(instance ?? null); |
| 173 | let total = 0; |
| 174 | for (const row of pendingBrew ?? []) |
| 175 | { |
| 176 | if (row.itemId !== itemId) |
| 177 | { continue; } |
| 178 | if (JSON.stringify(row.instance ?? null) !== key) |
| 179 | { continue; } |
| 180 | total += row.quantity | 0; |
| 181 | } |
| 182 | return total; |
| 183 | } |
| 184 | |
| 185 | function addPendingBrew (session, brewRow) |
| 186 | { |
| 187 | const existing = session.pendingBrew.find((row) => |
| 188 | row.itemId === brewRow.itemId |
| 189 | && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null)); |
| 190 | if (existing) |
| 191 | { existing.quantity += brewRow.quantity; } |
| 192 | else |
| 193 | { session.pendingBrew.push(brewRow); } |
| 194 | } |
| 195 | |
| 196 | function refundStacks (inventory, rows) |
| 197 | { |
| 198 | for (const row of rows ?? []) |
| 199 | { |
| 200 | const def = itemDefinition(row.itemId); |
| 201 | const refund = insertStack(inventory.slots, attachOrigins({ |
| 202 | itemId: row.itemId, |
| 203 | quantity: row.quantity, |
| 204 | instance: row.instance ? structuredClone(row.instance) : null, |
| 205 | origins: row.origins ?? normalizeOrigins(row) |
| 206 | }), def); |
| 207 | if (refund.ok) |
| 208 | { inventory.slots = refund.slots; } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | export function handleAlchemyCommand (world, sessionId, command) |
| 213 | { |
| 214 | switch (command.type) |
| 215 | { |
| 216 | case "open-cauldron": |
| 217 | return openCauldron(world, sessionId, command); |
| 218 | case "cauldron-set-slot": |
| 219 | case "cauldron-set-dye-slot": |
| 220 | // Slot UI is client-only; ignore mutations, echo session for sync. |
| 221 | return echoSession(world, sessionId, command); |
| 222 | case "cauldron-insert": |
| 223 | return insertIngredient(world, sessionId, command); |
| 224 | case "cauldron-action": |
| 225 | return action(world, sessionId, command); |
| 226 | case "cauldron-bottle": |
| 227 | return bottle(world, sessionId, command); |
| 228 | case "cauldron-create-dye": |
| 229 | return createDye(world, sessionId, command); |
| 230 | case "cauldron-clear": |
| 231 | return clear(world, sessionId, command); |
| 232 | case "cauldron-clear-dye": |
| 233 | return clearDye(world, sessionId, command); |
| 234 | case "cauldron-save-recipe": |
| 235 | return saveRecipe(world, sessionId, command); |
| 236 | case "cauldron-close": |
| 237 | return closeCauldron(world, sessionId, command); |
| 238 | default: |
| 239 | return null; |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | function echoSession (world, sessionId, command) |
| 244 | { |
| 245 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 246 | requireNearCauldron(world, handle); |
| 247 | const session = requireSession(world, command.characterId); |
| 248 | return { |
| 249 | events: [], |
| 250 | private: bagView(world.ecs, handle), |
| 251 | cauldron: true, |
| 252 | cauldronState: sessionView(session) |
| 253 | }; |
| 254 | } |
| 255 | |
| 256 | function openCauldron (world, sessionId, command) |
| 257 | { |
| 258 | const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId); |
| 259 | requireNearCauldron(world, handle); |
| 260 | const inventory = ensureInventory(world, handle); |
| 261 | if (countItemInSlots(inventory.slots, ItemId.glassBottle) < 1) |
| 262 | { throw userError("I don't have any empty bottles."); } |
| 263 | |
| 264 | const sessions = ensureSessions(world); |
| 265 | const existing = sessions.get(command.characterId) ?? emptySession(); |
| 266 | if (!Array.isArray(existing.pendingBrew)) |
| 267 | { existing.pendingBrew = []; } |
| 268 | if (!Array.isArray(existing.steps)) |
| 269 | { existing.steps = []; } |
| 270 | sessions.set(command.characterId, existing); |
| 271 | const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron); |
| 272 | return { |
| 273 | events: shove ? [shove] : [], |
| 274 | private: bagView(world.ecs, handle), |
| 275 | cauldron: true, |
| 276 | cauldronState: sessionView(existing) |
| 277 | }; |
| 278 | } |
| 279 | |
| 280 | function closeCauldron (world, sessionId, command) |
| 281 | { |
| 282 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 283 | // Soft claims only — bag never held station items. |
| 284 | ensureSessions(world).delete(command.characterId); |
| 285 | return { events: [], private: bagView(world.ecs, handle), cauldron: false }; |
| 286 | } |
| 287 | |
| 288 | function insertIngredient (world, sessionId, command) |
| 289 | { |
| 290 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 291 | requireNearCauldron(world, handle); |
| 292 | const session = requireSession(world, command.characterId); |
| 293 | |
| 294 | const itemId = command.itemId | 0; |
| 295 | const quantity = Math.max(0, command.quantity | 0); |
| 296 | if (!itemId || quantity <= 0) |
| 297 | { throw userError("Nothing to insert."); } |
| 298 | |
| 299 | const def = itemDefinition(itemId); |
| 300 | const instance = command.instance ? structuredClone(command.instance) : null; |
| 301 | const isPotion = itemId === ItemId.potion && instance?.kind === "potion"; |
| 302 | |
| 303 | if (!def || def.uniqueInstance || def.equipment |
| 304 | || itemId === ItemId.glassBottle |
| 305 | || itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye) |
| 306 | { throw userError("Use the Dyes tab for flowers."); } |
| 307 | |
| 308 | if (itemId === ItemId.potion && !isPotion) |
| 309 | { throw userError("That is not a bottled brew."); } |
| 310 | if (isPotion) |
| 311 | { |
| 312 | if (!isFullPotionBottle({ itemId, instance })) |
| 313 | { throw userError("Only full bottles can be used as ingredients."); } |
| 314 | } |
| 315 | |
| 316 | const inventory = ensureInventory(world, handle); |
| 317 | const have = instance |
| 318 | ? countMatchingInstance(inventory.slots, itemId, instance) |
| 319 | : countItemInSlots(inventory.slots, itemId); |
| 320 | const alreadyClaimed = pendingClaimedQuantity(session.pendingBrew, itemId, instance); |
| 321 | if (have < alreadyClaimed + quantity) |
| 322 | { throw userError("Not enough of that item in your inventory."); } |
| 323 | |
| 324 | const uniqueKeys = new Set((session.pendingBrew ?? []).map((row) => |
| 325 | { |
| 326 | if ((row.itemId | 0) === ItemId.potion && row.instance?.potionKey) |
| 327 | { return `potion:${row.instance.potionKey}`; } |
| 328 | return `item:${row.itemId | 0}`; |
| 329 | })); |
| 330 | const claimKey = isPotion |
| 331 | ? `potion:${instance.potionKey}` |
| 332 | : `item:${itemId}`; |
| 333 | if (!uniqueKeys.has(claimKey) && uniqueKeys.size >= CAULDRON_SLOT_COUNT) |
| 334 | { |
| 335 | throw userError( |
| 336 | `A brew can use at most ${CAULDRON_SLOT_COUNT} different ingredients.` |
| 337 | ); |
| 338 | } |
| 339 | |
| 340 | addPendingBrew(session, { itemId, quantity, instance }); |
| 341 | session.steps.push({ |
| 342 | kind: AlchemyStepKind.insert, |
| 343 | itemId, |
| 344 | ...(isPotion ? { potionKey: instance.potionKey } : {}) |
| 345 | }); |
| 346 | session.lastSuccessRecipe = null; |
| 347 | |
| 348 | return { |
| 349 | events: [], |
| 350 | private: bagView(world.ecs, handle), |
| 351 | cauldron: true, |
| 352 | cauldronState: sessionView(session) |
| 353 | }; |
| 354 | } |
| 355 | |
| 356 | function action (world, sessionId, command) |
| 357 | { |
| 358 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 359 | requireNearCauldron(world, handle); |
| 360 | const session = requireSession(world, command.characterId); |
| 361 | const kind = command.action; |
| 362 | if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool) |
| 363 | { throw userError("Unknown cauldron action."); } |
| 364 | if (!session.steps.some((step) => step.kind === AlchemyStepKind.insert)) |
| 365 | { throw userError("Insert an ingredient first."); } |
| 366 | session.steps.push({ kind }); |
| 367 | session.lastSuccessRecipe = null; |
| 368 | return { |
| 369 | events: [], |
| 370 | private: bagView(world.ecs, handle), |
| 371 | cauldron: true, |
| 372 | cauldronState: sessionView(session) |
| 373 | }; |
| 374 | } |
| 375 | |
| 376 | function grantEmptyGlassBottles (world, handle, characterId, quantity, events, now = Date.now()) |
| 377 | { |
| 378 | const want = Math.max(0, quantity | 0); |
| 379 | if (want <= 0) |
| 380 | { return; } |
| 381 | const inventory = ensureInventory(world, handle); |
| 382 | const bottleDef = itemDefinition(ItemId.glassBottle); |
| 383 | const inserted = insertStack(inventory.slots, { |
| 384 | itemId: ItemId.glassBottle, |
| 385 | quantity: want |
| 386 | }, bottleDef); |
| 387 | inventory.slots = inserted.slots; |
| 388 | const remainder = inserted.remainder | 0; |
| 389 | if (remainder <= 0) |
| 390 | { return; } |
| 391 | const position = world.ecs.get(handle, Component.position); |
| 392 | const placed = placeOrMergeGroundStack(world, { |
| 393 | tileX: position.tileX, |
| 394 | tileY: position.tileY, |
| 395 | stack: { itemId: ItemId.glassBottle, quantity: remainder }, |
| 396 | now, |
| 397 | source: "alchemy-overflow", |
| 398 | droppedByCharacterId: characterId |
| 399 | }); |
| 400 | events.push(...placed.events); |
| 401 | events.push({ |
| 402 | type: "toast", |
| 403 | sessionId: null, |
| 404 | characterId, |
| 405 | message: "Glass bottle dropped on the ground" |
| 406 | }); |
| 407 | } |
| 408 | |
| 409 | function bottle (world, sessionId, command) |
| 410 | { |
| 411 | const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId); |
| 412 | requireNearCauldron(world, handle); |
| 413 | const session = requireSession(world, command.characterId); |
| 414 | if (!(session.pendingBrew?.length > 0) && !(session.steps?.length > 0)) |
| 415 | { throw userError("The cauldron is empty."); } |
| 416 | |
| 417 | const inventory = ensureInventory(world, handle); |
| 418 | const skills = world.ecs.get(handle, Component.skills) ?? {}; |
| 419 | |
| 420 | const evaluation = evaluateAlchemyBottle({ |
| 421 | skills, |
| 422 | brewStacks: session.pendingBrew, |
| 423 | takenSteps: session.steps, |
| 424 | potions: resolvedAlchemyPotions() |
| 425 | }); |
| 426 | |
| 427 | const wanted = Math.max(1, evaluation.batch | 0); |
| 428 | const requiresEmptyBottles = evaluation.result?.requiresEmptyBottles !== false; |
| 429 | const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle); |
| 430 | const produced = requiresEmptyBottles ? Math.min(wanted, bottles) : wanted; |
| 431 | if (requiresEmptyBottles && produced <= 0) |
| 432 | { throw userError("You need glass bottles to bottle the brew."); } |
| 433 | |
| 434 | for (const row of session.pendingBrew ?? []) |
| 435 | { |
| 436 | if (row.itemId === ItemId.potion && row.instance?.kind === "potion" |
| 437 | && !isFullPotionBottle({ itemId: row.itemId, instance: row.instance })) |
| 438 | { throw userError("Only full bottles can be used as ingredients."); } |
| 439 | const have = row.instance |
| 440 | ? countMatchingInstance(inventory.slots, row.itemId, row.instance) |
| 441 | : countItemInSlots(inventory.slots, row.itemId); |
| 442 | if (have < (row.quantity | 0)) |
| 443 | { throw userError("Not enough of that item in your inventory."); } |
| 444 | } |
| 445 | |
| 446 | // Consume soft-claimed ingredients only now (success path). |
| 447 | const consumed = []; |
| 448 | for (const row of session.pendingBrew ?? []) |
| 449 | { |
| 450 | const pulled = takeMatchingFromSlots(inventory.slots, { |
| 451 | itemId: row.itemId, |
| 452 | quantity: row.quantity, |
| 453 | instance: row.instance ?? null, |
| 454 | compact: false |
| 455 | }); |
| 456 | if (!pulled.ok) |
| 457 | { |
| 458 | refundStacks(inventory, consumed); |
| 459 | throw userError("Not enough of that item in your inventory."); |
| 460 | } |
| 461 | inventory.slots = pulled.slots; |
| 462 | consumed.push(pulled.taken); |
| 463 | } |
| 464 | |
| 465 | let takeBottles = null; |
| 466 | if (requiresEmptyBottles) |
| 467 | { |
| 468 | takeBottles = takeMatchingFromSlots(inventory.slots, { |
| 469 | itemId: ItemId.glassBottle, |
| 470 | quantity: produced, |
| 471 | compact: false |
| 472 | }); |
| 473 | if (!takeBottles.ok) |
| 474 | { |
| 475 | refundStacks(inventory, consumed); |
| 476 | throw userError("You need glass bottles to bottle the brew."); |
| 477 | } |
| 478 | inventory.slots = takeBottles.slots; |
| 479 | } |
| 480 | |
| 481 | const origin = craftOrigin(CraftOriginVerb.brewed, characterDisplayName(world, handle)); |
| 482 | const outputItemId = evaluation.result?.outputItemId | 0; |
| 483 | let alchemyPotionView = null; |
| 484 | |
| 485 | if (outputItemId && evaluation.success) |
| 486 | { |
| 487 | const outQty = Math.max(1, (evaluation.result.outputQuantity | 0) || 1) * produced; |
| 488 | const outDef = itemDefinition(outputItemId); |
| 489 | const inserted = insertStack(inventory.slots, attachOrigins({ |
| 490 | itemId: outputItemId, |
| 491 | quantity: outQty, |
| 492 | origins: [{ origin, quantity: outQty }] |
| 493 | }), outDef); |
| 494 | if (!inserted.ok) |
| 495 | { |
| 496 | refundStacks(inventory, consumed); |
| 497 | if (takeBottles) |
| 498 | { refundStacks(inventory, [takeBottles.taken]); } |
| 499 | throw userError("Not enough inventory space for the brew."); |
| 500 | } |
| 501 | inventory.slots = inserted.slots; |
| 502 | alchemyPotionView = { |
| 503 | potionKey: evaluation.result.potionKey, |
| 504 | displayName: evaluation.result.displayName, |
| 505 | unstable: false, |
| 506 | color: evaluation.result.color, |
| 507 | fillLevel: null |
| 508 | }; |
| 509 | } |
| 510 | else |
| 511 | { |
| 512 | const instance = potionItemInstance(evaluation.result); |
| 513 | const potionDef = itemDefinition(ItemId.potion); |
| 514 | const inserted = insertStack(inventory.slots, attachOrigins({ |
| 515 | itemId: ItemId.potion, |
| 516 | quantity: produced, |
| 517 | instance, |
| 518 | origins: [{ origin, quantity: produced }] |
| 519 | }), potionDef); |
| 520 | if (!inserted.ok) |
| 521 | { |
| 522 | refundStacks(inventory, consumed); |
| 523 | if (takeBottles) |
| 524 | { refundStacks(inventory, [takeBottles.taken]); } |
| 525 | throw userError("Not enough inventory space for potions."); |
| 526 | } |
| 527 | inventory.slots = inserted.slots; |
| 528 | alchemyPotionView = { |
| 529 | potionKey: instance.potionKey, |
| 530 | displayName: instance.displayName, |
| 531 | unstable: instance.unstable, |
| 532 | color: instance.color, |
| 533 | fillLevel: instance.fillLevel |
| 534 | }; |
| 535 | } |
| 536 | |
| 537 | session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null; |
| 538 | clearAlchemy(session); |
| 539 | |
| 540 | const events = []; |
| 541 | let returnedBottles = 0; |
| 542 | for (const row of consumed) |
| 543 | { |
| 544 | if ((row.itemId | 0) === ItemId.potion) |
| 545 | { returnedBottles += stackQuantity(row.quantity); } |
| 546 | } |
| 547 | grantEmptyGlassBottles(world, handle, command.characterId, returnedBottles, events); |
| 548 | |
| 549 | if (evaluation.success && skills?.xp) |
| 550 | { |
| 551 | const xpInputs = (consumed ?? []).map((row) => ({ |
| 552 | itemId: row.itemId, |
| 553 | quantity: row.quantity |
| 554 | })); |
| 555 | const amount = craftXpForConsumedInputs(xpInputs, SkillId.alchemy); |
| 556 | if (amount > 0) |
| 557 | { |
| 558 | const result = applySkillXp( |
| 559 | skills, |
| 560 | SkillId.alchemy, |
| 561 | amount, |
| 562 | world.ecs.get(handle, Component.equipment) |
| 563 | ); |
| 564 | if (result.changed) |
| 565 | { |
| 566 | events.push({ |
| 567 | type: "skills-updated", |
| 568 | entityId, |
| 569 | characterId: command.characterId, |
| 570 | ...publicSkillsPayload(skills), |
| 571 | stored: storedSkillXp(skills), |
| 572 | levelUps: result.levelUp ? [result.levelUp] : [] |
| 573 | }); |
| 574 | } |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | return { |
| 579 | events, |
| 580 | private: bagView(world.ecs, handle), |
| 581 | cauldron: true, |
| 582 | cauldronState: sessionView(session), |
| 583 | alchemyResult: { |
| 584 | success: !!evaluation.success, |
| 585 | reason: evaluation.reason ?? null, |
| 586 | produced, |
| 587 | wanted, |
| 588 | lost: Math.max(0, wanted - produced), |
| 589 | potion: alchemyPotionView |
| 590 | } |
| 591 | }; |
| 592 | } |
| 593 | |
| 594 | function createDye (world, sessionId, command) |
| 595 | { |
| 596 | const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId); |
| 597 | requireNearCauldron(world, handle); |
| 598 | requireSession(world, command.characterId); |
| 599 | |
| 600 | const rows = normalizeFlowerRows(command.flowers); |
| 601 | if (!rows.length) |
| 602 | { throw userError("Add flowers to make dye."); } |
| 603 | |
| 604 | const mixed = mixFlowersForDye(rows); |
| 605 | if (!mixed.ok) |
| 606 | { throw userError(mixed.reason); } |
| 607 | |
| 608 | const wanted = mixed.quantity; |
| 609 | const inventory = ensureInventory(world, handle); |
| 610 | const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle); |
| 611 | if (bottles < wanted && !command.confirmOverflow) |
| 612 | { |
| 613 | return { |
| 614 | events: [], |
| 615 | private: bagView(world.ecs, handle), |
| 616 | cauldron: true, |
| 617 | cauldronState: sessionView(requireSession(world, command.characterId)), |
| 618 | dyeConfirm: { |
| 619 | wanted, |
| 620 | bottles, |
| 621 | lost: Math.max(0, wanted - bottles) |
| 622 | } |
| 623 | }; |
| 624 | } |
| 625 | |
| 626 | const produced = Math.min(wanted, bottles); |
| 627 | if (produced <= 0) |
| 628 | { throw userError("You need glass bottles to bottle the dye."); } |
| 629 | |
| 630 | for (const row of rows) |
| 631 | { |
| 632 | const have = countMatchingInstance(inventory.slots, ItemId.flower, row.instance); |
| 633 | if (have < row.quantity) |
| 634 | { throw userError("Not enough of those flowers in your inventory."); } |
| 635 | } |
| 636 | |
| 637 | for (const row of rows) |
| 638 | { |
| 639 | const pulled = takeMatchingFromSlots(inventory.slots, { |
| 640 | itemId: ItemId.flower, |
| 641 | quantity: row.quantity, |
| 642 | instance: row.instance, |
| 643 | compact: false |
| 644 | }); |
| 645 | if (!pulled.ok) |
| 646 | { throw userError("Not enough of those flowers in your inventory."); } |
| 647 | inventory.slots = pulled.slots; |
| 648 | } |
| 649 | |
| 650 | const takeBottles = takeMatchingFromSlots(inventory.slots, { |
| 651 | itemId: ItemId.glassBottle, |
| 652 | quantity: produced, |
| 653 | compact: false |
| 654 | }); |
| 655 | if (!takeBottles.ok) |
| 656 | { throw userError("You need glass bottles to bottle the dye."); } |
| 657 | inventory.slots = takeBottles.slots; |
| 658 | |
| 659 | const dyeDef = itemDefinition(ItemId.dye); |
| 660 | const origin = craftOrigin(CraftOriginVerb.mixed, characterDisplayName(world, handle)); |
| 661 | const inserted = insertStack(inventory.slots, attachOrigins({ |
| 662 | itemId: ItemId.dye, |
| 663 | quantity: produced, |
| 664 | instance: mixed.instance, |
| 665 | origins: [{ origin, quantity: produced }] |
| 666 | }), dyeDef); |
| 667 | if (!inserted.ok) |
| 668 | { throw userError("Not enough inventory space for dye."); } |
| 669 | inventory.slots = inserted.slots; |
| 670 | |
| 671 | const events = []; |
| 672 | const skills = world.ecs.get(handle, Component.skills); |
| 673 | const flowerCount = rows.reduce((sum, row) => sum + (row.quantity | 0), 0); |
| 674 | if (skills?.xp && flowerCount > 0) |
| 675 | { |
| 676 | const result = applySkillXp( |
| 677 | skills, |
| 678 | SkillId.alchemy, |
| 679 | flowerCount * craftXpMultiplierForSkill(SkillId.alchemy), |
| 680 | world.ecs.get(handle, Component.equipment) |
| 681 | ); |
| 682 | if (result.changed) |
| 683 | { |
| 684 | events.push({ |
| 685 | type: "skills-updated", |
| 686 | entityId, |
| 687 | characterId: command.characterId, |
| 688 | ...publicSkillsPayload(skills), |
| 689 | stored: storedSkillXp(skills), |
| 690 | levelUps: result.levelUp ? [result.levelUp] : [] |
| 691 | }); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | return { |
| 696 | events, |
| 697 | private: bagView(world.ecs, handle), |
| 698 | cauldron: true, |
| 699 | cauldronState: sessionView(requireSession(world, command.characterId)), |
| 700 | alchemyResult: { |
| 701 | success: true, |
| 702 | reason: null, |
| 703 | produced, |
| 704 | wanted, |
| 705 | lost: Math.max(0, wanted - produced), |
| 706 | potion: { |
| 707 | potionKey: "dye", |
| 708 | displayName: "Dye", |
| 709 | unstable: false, |
| 710 | color: mixed.instance?.color ?? null, |
| 711 | fillLevel: mixed.instance?.fillLevel ?? DEFAULT_DYE_FILL |
| 712 | } |
| 713 | } |
| 714 | }; |
| 715 | } |
| 716 | |
| 717 | function normalizeFlowerRows (flowers) |
| 718 | { |
| 719 | if (!Array.isArray(flowers)) |
| 720 | { return []; } |
| 721 | const rows = []; |
| 722 | for (const entry of flowers) |
| 723 | { |
| 724 | const itemId = entry?.itemId | 0; |
| 725 | const quantity = Math.min(FLOWER_MAX_STACK, Math.max(0, entry?.quantity | 0)); |
| 726 | if (itemId !== ItemId.flower || quantity <= 0) |
| 727 | { continue; } |
| 728 | const instance = entry.instance ? structuredClone(entry.instance) : null; |
| 729 | if (!instance?.color) |
| 730 | { continue; } |
| 731 | rows.push({ itemId: ItemId.flower, quantity, instance }); |
| 732 | } |
| 733 | return rows; |
| 734 | } |
| 735 | |
| 736 | function clear (world, sessionId, command) |
| 737 | { |
| 738 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 739 | requireNearCauldron(world, handle); |
| 740 | const session = requireSession(world, command.characterId); |
| 741 | clearAlchemy(session); |
| 742 | session.lastSuccessRecipe = null; |
| 743 | return { |
| 744 | events: [], |
| 745 | private: bagView(world.ecs, handle), |
| 746 | cauldron: true, |
| 747 | cauldronState: sessionView(session) |
| 748 | }; |
| 749 | } |
| 750 | |
| 751 | function clearDye (world, sessionId, command) |
| 752 | { |
| 753 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 754 | requireNearCauldron(world, handle); |
| 755 | const session = requireSession(world, command.characterId); |
| 756 | // Dye slots are client-only; nothing to clear server-side. |
| 757 | return { |
| 758 | events: [], |
| 759 | private: bagView(world.ecs, handle), |
| 760 | cauldron: true, |
| 761 | cauldronState: sessionView(session) |
| 762 | }; |
| 763 | } |
| 764 | |
| 765 | function saveRecipe (world, sessionId, command) |
| 766 | { |
| 767 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 768 | requireNearCauldron(world, handle); |
| 769 | const session = requireSession(world, command.characterId); |
| 770 | const recipe = session.lastSuccessRecipe; |
| 771 | if (!recipe) |
| 772 | { throw userError("No successful recipe to save."); } |
| 773 | |
| 774 | const inventory = ensureInventory(world, handle); |
| 775 | const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper); |
| 776 | if (paperIndex < 0) |
| 777 | { throw userError("You need paper to write a recipe."); } |
| 778 | const paperSlot = inventory.slots[paperIndex]; |
| 779 | const recipeStack = attachOrigins({ |
| 780 | itemId: ItemId.recipePaper, |
| 781 | quantity: 1, |
| 782 | origins: [{ |
| 783 | origin: writtenOrigin(characterDisplayName(world, handle)), |
| 784 | quantity: 1 |
| 785 | }], |
| 786 | instance: { |
| 787 | kind: "recipe-paper", |
| 788 | recipeId: randomUUID(), |
| 789 | potionKey: recipe.potionKey, |
| 790 | displayName: `${recipe.displayName} recipe`, |
| 791 | authorCharacterId: command.characterId, |
| 792 | authorDisplayName: characterDisplayName(world, handle), |
| 793 | minAlchemyLevel: recipe.minAlchemyLevel ?? 1, |
| 794 | body: recipePaperBody(recipe), |
| 795 | writtenAt: Date.now() |
| 796 | } |
| 797 | }); |
| 798 | |
| 799 | if (stackQuantity(paperSlot.quantity) <= 1) |
| 800 | { inventory.slots[paperIndex] = recipeStack; } |
| 801 | else |
| 802 | { |
| 803 | const free = inventory.slots.findIndex((entry) => !entry); |
| 804 | if (free < 0) |
| 805 | { throw userError("Need a free inventory slot for the recipe paper."); } |
| 806 | paperSlot.quantity -= 1; |
| 807 | inventory.slots[free] = recipeStack; |
| 808 | } |
| 809 | |
| 810 | session.lastSuccessRecipe = null; |
| 811 | return { |
| 812 | events: [], |
| 813 | private: bagView(world.ecs, handle), |
| 814 | cauldron: true, |
| 815 | cauldronState: sessionView(session) |
| 816 | }; |
| 817 | } |