| 1 | import { Component } from "../ecs/components.js"; |
| 2 | import { BlockType } from "../../../shared/definitions/tiles.js"; |
| 3 | import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "../../../shared/definitions/alchemy.js"; |
| 4 | import { ItemId, itemDefinition } from "../../../shared/definitions/items.js"; |
| 5 | import { |
| 6 | evaluateAlchemyBottle, |
| 7 | potionItemInstance, |
| 8 | recipePaperBody, |
| 9 | resolvedAlchemyPotions |
| 10 | } from "../../../shared/alchemy/recipes.js"; |
| 11 | import { bagView } from "../items/bags.js"; |
| 12 | import { |
| 13 | countItemInSlots, |
| 14 | emptySlots, |
| 15 | insertStack, |
| 16 | normalizeInventorySlots, |
| 17 | takeMatchingFromSlots, |
| 18 | stackQuantity |
| 19 | } from "../../../shared/items/inventory.js"; |
| 20 | import { tileToChunk, tileToLocal } from "../world/coordinates.js"; |
| 21 | import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; |
| 22 | import { randomUUID } from "node:crypto"; |
| 23 | import { tileShoveTowardBlock } from "../simulation/tileInteract.js"; |
| 24 | |
| 25 | /** |
| 26 | * Cauldron sessions live on the worker world (per character while the UI is open). |
| 27 | * Clients send intents only; all brew outcomes are evaluated here. |
| 28 | */ |
| 29 | |
| 30 | function userError (message) |
| 31 | { |
| 32 | const error = new Error(message); |
| 33 | error.userFacing = true; |
| 34 | return error; |
| 35 | } |
| 36 | |
| 37 | function ensureSessions (world) |
| 38 | { |
| 39 | if (!world.cauldronSessions) |
| 40 | { world.cauldronSessions = new Map(); } |
| 41 | return world.cauldronSessions; |
| 42 | } |
| 43 | |
| 44 | function emptySession () |
| 45 | { |
| 46 | return { |
| 47 | slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null), |
| 48 | brew: [], |
| 49 | steps: [], |
| 50 | lastSuccessRecipe: null |
| 51 | }; |
| 52 | } |
| 53 | |
| 54 | function sessionView (session) |
| 55 | { |
| 56 | return { |
| 57 | slots: (session.slots ?? []).map((slot) => (slot |
| 58 | ? { itemId: slot.itemId, quantity: slot.quantity | 0 } |
| 59 | : null)), |
| 60 | brew: (session.brew ?? []).map((row) => ({ itemId: row.itemId, quantity: row.quantity | 0 })), |
| 61 | steps: (session.steps ?? []).map((step) => ({ ...step })), |
| 62 | canSaveRecipe: !!session.lastSuccessRecipe, |
| 63 | lastSuccess: session.lastSuccessRecipe |
| 64 | ? { |
| 65 | potionKey: session.lastSuccessRecipe.potionKey, |
| 66 | displayName: session.lastSuccessRecipe.displayName, |
| 67 | minAlchemyLevel: session.lastSuccessRecipe.minAlchemyLevel ?? 1 |
| 68 | } |
| 69 | : null |
| 70 | }; |
| 71 | } |
| 72 | |
| 73 | function nearCauldron (world, tileX, tileY) |
| 74 | { |
| 75 | for (let dy = -1; dy <= 1; dy++) |
| 76 | { |
| 77 | for (let dx = -1; dx <= 1; dx++) |
| 78 | { |
| 79 | const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy)); |
| 80 | const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx); |
| 81 | if (data.blocks[index]?.typeId === BlockType.cauldron) |
| 82 | { return true; } |
| 83 | } |
| 84 | } |
| 85 | return false; |
| 86 | } |
| 87 | |
| 88 | function requireNearCauldron (world, handle) |
| 89 | { |
| 90 | const position = world.ecs.get(handle, Component.position); |
| 91 | if (!nearCauldron(world, position.tileX, position.tileY)) |
| 92 | { throw userError("Stand next to a cauldron."); } |
| 93 | } |
| 94 | |
| 95 | function requireSession (world, characterId) |
| 96 | { |
| 97 | const session = ensureSessions(world).get(characterId); |
| 98 | if (!session) |
| 99 | { throw userError("Open a cauldron first."); } |
| 100 | return session; |
| 101 | } |
| 102 | |
| 103 | function clearBrew (session) |
| 104 | { |
| 105 | session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null); |
| 106 | session.brew = []; |
| 107 | session.steps = []; |
| 108 | } |
| 109 | |
| 110 | function ensureInventory (world, handle) |
| 111 | { |
| 112 | let inventory = world.ecs.get(handle, Component.inventory); |
| 113 | if (!inventory) |
| 114 | { inventory = world.ecs.add(handle, Component.inventory, { slots: emptySlots() }); } |
| 115 | inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots()); |
| 116 | return inventory; |
| 117 | } |
| 118 | |
| 119 | export function handleAlchemyCommand (world, sessionId, command) |
| 120 | { |
| 121 | switch (command.type) |
| 122 | { |
| 123 | case "open-cauldron": |
| 124 | return openCauldron(world, sessionId, command); |
| 125 | case "cauldron-set-slot": |
| 126 | return setSlot(world, sessionId, command); |
| 127 | case "cauldron-insert": |
| 128 | return insertFromSlot(world, sessionId, command); |
| 129 | case "cauldron-action": |
| 130 | return action(world, sessionId, command); |
| 131 | case "cauldron-bottle": |
| 132 | return bottle(world, sessionId, command); |
| 133 | case "cauldron-clear": |
| 134 | return clear(world, sessionId, command); |
| 135 | case "cauldron-save-recipe": |
| 136 | return saveRecipe(world, sessionId, command); |
| 137 | case "cauldron-close": |
| 138 | return closeCauldron(world, sessionId, command); |
| 139 | default: |
| 140 | return null; |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | function openCauldron (world, sessionId, command) |
| 145 | { |
| 146 | const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId); |
| 147 | requireNearCauldron(world, handle); |
| 148 | const sessions = ensureSessions(world); |
| 149 | const existing = sessions.get(command.characterId) ?? emptySession(); |
| 150 | sessions.set(command.characterId, existing); |
| 151 | const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron); |
| 152 | return { |
| 153 | events: shove ? [shove] : [], |
| 154 | private: bagView(world.ecs, handle), |
| 155 | cauldron: true, |
| 156 | cauldronState: sessionView(existing) |
| 157 | }; |
| 158 | } |
| 159 | |
| 160 | function closeCauldron (world, sessionId, command) |
| 161 | { |
| 162 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 163 | ensureSessions(world).delete(command.characterId); |
| 164 | return { events: [], private: bagView(world.ecs, handle), cauldron: false }; |
| 165 | } |
| 166 | |
| 167 | function setSlot (world, sessionId, command) |
| 168 | { |
| 169 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 170 | requireNearCauldron(world, handle); |
| 171 | const session = requireSession(world, command.characterId); |
| 172 | const slotIndex = command.slotIndex | 0; |
| 173 | if (slotIndex < 0 || slotIndex >= CAULDRON_SLOT_COUNT) |
| 174 | { throw userError("Invalid cauldron slot."); } |
| 175 | |
| 176 | const itemId = command.itemId | 0; |
| 177 | const quantity = Math.max(0, command.quantity | 0); |
| 178 | if (!itemId || quantity <= 0) |
| 179 | { |
| 180 | session.slots[slotIndex] = null; |
| 181 | return { |
| 182 | events: [], |
| 183 | private: bagView(world.ecs, handle), |
| 184 | cauldron: true, |
| 185 | cauldronState: sessionView(session) |
| 186 | }; |
| 187 | } |
| 188 | |
| 189 | const def = itemDefinition(itemId); |
| 190 | if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle) |
| 191 | { throw userError("That cannot go in a cauldron slot."); } |
| 192 | |
| 193 | const inventory = ensureInventory(world, handle); |
| 194 | const have = countItemInSlots(inventory.slots, itemId); |
| 195 | if (have < quantity) |
| 196 | { throw userError("Not enough of that item in your inventory."); } |
| 197 | |
| 198 | session.slots[slotIndex] = { itemId, quantity }; |
| 199 | return { |
| 200 | events: [], |
| 201 | private: bagView(world.ecs, handle), |
| 202 | cauldron: true, |
| 203 | cauldronState: sessionView(session) |
| 204 | }; |
| 205 | } |
| 206 | |
| 207 | function insertFromSlot (world, sessionId, command) |
| 208 | { |
| 209 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 210 | requireNearCauldron(world, handle); |
| 211 | const session = requireSession(world, command.characterId); |
| 212 | const slotIndex = command.slotIndex | 0; |
| 213 | const reserved = session.slots[slotIndex]; |
| 214 | if (!reserved) |
| 215 | { throw userError("That cauldron slot is empty."); } |
| 216 | |
| 217 | const inventory = ensureInventory(world, handle); |
| 218 | const pulled = takeMatchingFromSlots(inventory.slots, { |
| 219 | itemId: reserved.itemId, |
| 220 | quantity: reserved.quantity, |
| 221 | compact: false |
| 222 | }); |
| 223 | if (!pulled.ok) |
| 224 | { throw userError("Not enough of that item in your inventory."); } |
| 225 | inventory.slots = pulled.slots; |
| 226 | session.slots[slotIndex] = null; |
| 227 | |
| 228 | const existing = session.brew.find((row) => row.itemId === reserved.itemId); |
| 229 | if (existing) |
| 230 | { existing.quantity += reserved.quantity; } |
| 231 | else |
| 232 | { session.brew.push({ itemId: reserved.itemId, quantity: reserved.quantity }); } |
| 233 | |
| 234 | session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId }); |
| 235 | session.lastSuccessRecipe = null; |
| 236 | |
| 237 | return { |
| 238 | events: [], |
| 239 | private: bagView(world.ecs, handle), |
| 240 | cauldron: true, |
| 241 | cauldronState: sessionView(session) |
| 242 | }; |
| 243 | } |
| 244 | |
| 245 | function action (world, sessionId, command) |
| 246 | { |
| 247 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 248 | requireNearCauldron(world, handle); |
| 249 | const session = requireSession(world, command.characterId); |
| 250 | const kind = command.action; |
| 251 | if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool) |
| 252 | { throw userError("Unknown cauldron action."); } |
| 253 | session.steps.push({ kind }); |
| 254 | session.lastSuccessRecipe = null; |
| 255 | return { |
| 256 | events: [], |
| 257 | private: bagView(world.ecs, handle), |
| 258 | cauldron: true, |
| 259 | cauldronState: sessionView(session) |
| 260 | }; |
| 261 | } |
| 262 | |
| 263 | function bottle (world, sessionId, command) |
| 264 | { |
| 265 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 266 | requireNearCauldron(world, handle); |
| 267 | const session = requireSession(world, command.characterId); |
| 268 | if (!(session.brew?.length > 0) && !(session.steps?.length > 0)) |
| 269 | { throw userError("The cauldron is empty."); } |
| 270 | |
| 271 | const inventory = ensureInventory(world, handle); |
| 272 | const skills = world.ecs.get(handle, Component.skills) ?? {}; |
| 273 | |
| 274 | const evaluation = evaluateAlchemyBottle({ |
| 275 | skills, |
| 276 | brewStacks: session.brew, |
| 277 | takenSteps: session.steps, |
| 278 | potions: resolvedAlchemyPotions() |
| 279 | }); |
| 280 | |
| 281 | const wanted = Math.max(1, evaluation.batch | 0); |
| 282 | const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle); |
| 283 | const produced = Math.min(wanted, bottles); |
| 284 | if (produced <= 0) |
| 285 | { throw userError("You need glass bottles to bottle the brew."); } |
| 286 | |
| 287 | const takeBottles = takeMatchingFromSlots(inventory.slots, { |
| 288 | itemId: ItemId.glassBottle, |
| 289 | quantity: produced, |
| 290 | compact: false |
| 291 | }); |
| 292 | if (!takeBottles.ok) |
| 293 | { throw userError("You need glass bottles to bottle the brew."); } |
| 294 | inventory.slots = takeBottles.slots; |
| 295 | |
| 296 | const instance = potionItemInstance(evaluation.result); |
| 297 | const potionDef = itemDefinition(ItemId.potion); |
| 298 | const inserted = insertStack(inventory.slots, { |
| 299 | itemId: ItemId.potion, |
| 300 | quantity: produced, |
| 301 | instance |
| 302 | }, potionDef); |
| 303 | if (!inserted.ok) |
| 304 | { |
| 305 | const refund = insertStack(inventory.slots, { |
| 306 | itemId: ItemId.glassBottle, |
| 307 | quantity: produced |
| 308 | }, itemDefinition(ItemId.glassBottle)); |
| 309 | inventory.slots = refund.ok ? refund.slots : inventory.slots; |
| 310 | throw userError("Not enough inventory space for potions."); |
| 311 | } |
| 312 | inventory.slots = inserted.slots; |
| 313 | |
| 314 | session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null; |
| 315 | clearBrew(session); |
| 316 | |
| 317 | return { |
| 318 | events: [], |
| 319 | private: bagView(world.ecs, handle), |
| 320 | cauldron: true, |
| 321 | cauldronState: sessionView(session), |
| 322 | alchemyResult: { |
| 323 | success: !!evaluation.success, |
| 324 | reason: evaluation.reason ?? null, |
| 325 | produced, |
| 326 | wanted, |
| 327 | lost: Math.max(0, wanted - produced), |
| 328 | potion: { |
| 329 | potionKey: instance.potionKey, |
| 330 | displayName: instance.displayName, |
| 331 | unstable: instance.unstable, |
| 332 | color: instance.color, |
| 333 | fillLevel: instance.fillLevel |
| 334 | } |
| 335 | } |
| 336 | }; |
| 337 | } |
| 338 | |
| 339 | function clear (world, sessionId, command) |
| 340 | { |
| 341 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 342 | requireNearCauldron(world, handle); |
| 343 | const session = requireSession(world, command.characterId); |
| 344 | clearBrew(session); |
| 345 | session.lastSuccessRecipe = null; |
| 346 | return { |
| 347 | events: [], |
| 348 | private: bagView(world.ecs, handle), |
| 349 | cauldron: true, |
| 350 | cauldronState: sessionView(session) |
| 351 | }; |
| 352 | } |
| 353 | |
| 354 | function saveRecipe (world, sessionId, command) |
| 355 | { |
| 356 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 357 | requireNearCauldron(world, handle); |
| 358 | const session = requireSession(world, command.characterId); |
| 359 | const recipe = session.lastSuccessRecipe; |
| 360 | if (!recipe) |
| 361 | { throw userError("No successful recipe to save."); } |
| 362 | |
| 363 | const inventory = ensureInventory(world, handle); |
| 364 | const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper); |
| 365 | if (paperIndex < 0) |
| 366 | { throw userError("You need a sheet of paper."); } |
| 367 | |
| 368 | const paperSlot = inventory.slots[paperIndex]; |
| 369 | const recipeStack = { |
| 370 | itemId: ItemId.recipePaper, |
| 371 | quantity: 1, |
| 372 | instance: { |
| 373 | kind: "recipe-paper", |
| 374 | recipeId: randomUUID(), |
| 375 | potionKey: recipe.potionKey, |
| 376 | displayName: `${recipe.displayName} recipe`, |
| 377 | minAlchemyLevel: recipe.minAlchemyLevel ?? 1, |
| 378 | body: recipePaperBody(recipe), |
| 379 | writtenAt: Date.now() |
| 380 | } |
| 381 | }; |
| 382 | |
| 383 | if (stackQuantity(paperSlot.quantity) <= 1) |
| 384 | { inventory.slots[paperIndex] = recipeStack; } |
| 385 | else |
| 386 | { |
| 387 | const free = inventory.slots.findIndex((entry) => !entry); |
| 388 | if (free < 0) |
| 389 | { throw userError("Need a free inventory slot for the recipe paper."); } |
| 390 | paperSlot.quantity -= 1; |
| 391 | inventory.slots[free] = recipeStack; |
| 392 | } |
| 393 | |
| 394 | session.lastSuccessRecipe = null; |
| 395 | return { |
| 396 | events: [], |
| 397 | private: bagView(world.ecs, handle), |
| 398 | cauldron: true, |
| 399 | cauldronState: sessionView(session) |
| 400 | }; |
| 401 | } |