| 1 | import { Component } from "../ecs/components.js"; |
| 2 | import { BlockType } from "../../../shared/definitions/tiles.js"; |
| 3 | import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_CHANCE_CAMPFIRE } from "../../../shared/definitions/craftingStations.js"; |
| 4 | import { ItemId, itemDefinition } from "../../../shared/definitions/items.js"; |
| 5 | import { SkillId, skillLevel } from "../../../shared/definitions/skills.js"; |
| 6 | import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js"; |
| 7 | import |
| 8 | { |
| 9 | recipeDefinition, |
| 10 | canStartCraft, |
| 11 | canCraftFitInventory, |
| 12 | hasRecipeInputs |
| 13 | } from "../../../shared/crafting/recipes.js"; |
| 14 | import { resolveTailorCraft } from "../../../shared/crafting/tailor.js"; |
| 15 | import { pickEmptiestDyeSlot } from "../../../shared/crafting/dye.js"; |
| 16 | import { dyeColorKey as dyeInstanceColorKey } from "../../../shared/definitions/dyes.js"; |
| 17 | import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js"; |
| 18 | import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js"; |
| 19 | import |
| 20 | { |
| 21 | attachOrigins, |
| 22 | craftOrigin, |
| 23 | craftOriginVerbForStation, |
| 24 | CraftOriginVerb |
| 25 | } from "../../../shared/items/origin.js"; |
| 26 | import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js"; |
| 27 | import { craftDurationMultiplier } from "../../../shared/equipment/jewelryEffects.js"; |
| 28 | import { bagView } from "../items/bags.js"; |
| 29 | import { tileToChunk, tileToLocal } from "../world/coordinates.js"; |
| 30 | import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; |
| 31 | import { tileShoveTowardBlock } from "../simulation/tileInteract.js"; |
| 32 | |
| 33 | function userError (message) |
| 34 | { |
| 35 | const error = new Error(message); |
| 36 | error.userFacing = true; |
| 37 | return error; |
| 38 | } |
| 39 | |
| 40 | function characterDisplayName (world, handle) |
| 41 | { |
| 42 | const appearance = world.ecs.get(handle, Component.appearance); |
| 43 | const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); |
| 44 | return name || "someone"; |
| 45 | } |
| 46 | |
| 47 | function ensureCraftSessions (world) |
| 48 | { |
| 49 | if (!world.craftSessions) |
| 50 | { world.craftSessions = new Map(); } |
| 51 | return world.craftSessions; |
| 52 | } |
| 53 | |
| 54 | function nearStationBlock (world, tileX, tileY, blockType) |
| 55 | { |
| 56 | for (let dy = -1; dy <= 1; dy++) |
| 57 | { |
| 58 | for (let dx = -1; dx <= 1; dx++) |
| 59 | { |
| 60 | if (dx === 0 && dy === 0) |
| 61 | { continue; } |
| 62 | const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy)); |
| 63 | const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx); |
| 64 | if (data.blocks[index]?.typeId === blockType) |
| 65 | { return true; } |
| 66 | } |
| 67 | } |
| 68 | return false; |
| 69 | } |
| 70 | |
| 71 | function stationBlockType (stationId) |
| 72 | { |
| 73 | if (stationId === CraftingStationId.furnace) |
| 74 | { return BlockType.furnace; } |
| 75 | if (stationId === CraftingStationId.anvil) |
| 76 | { return BlockType.anvil; } |
| 77 | if (stationId === CraftingStationId.jeweleringStation) |
| 78 | { return BlockType.jeweleringStation; } |
| 79 | if (stationId === CraftingStationId.woodworkingBench) |
| 80 | { return BlockType.woodworkingBench; } |
| 81 | if (stationId === CraftingStationId.craftingBench) |
| 82 | { return BlockType.craftingBench; } |
| 83 | if (stationId === CraftingStationId.spinningWheel) |
| 84 | { return BlockType.spinningWheel; } |
| 85 | if (stationId === CraftingStationId.loom) |
| 86 | { return BlockType.loom; } |
| 87 | if (stationId === CraftingStationId.tailorBench) |
| 88 | { return BlockType.tailorBench; } |
| 89 | if (stationId === CraftingStationId.leatherworkingStation) |
| 90 | { return BlockType.leatherworkingTable; } |
| 91 | if (stationId === CraftingStationId.oven) |
| 92 | { return BlockType.oven; } |
| 93 | if (stationId === CraftingStationId.fireplace) |
| 94 | { return BlockType.campfire; } |
| 95 | return null; |
| 96 | } |
| 97 | |
| 98 | function cookBurnChance (stationId) |
| 99 | { |
| 100 | if (stationId === CraftingStationId.fireplace) |
| 101 | { return COOK_BURN_CHANCE_CAMPFIRE; } |
| 102 | if (stationId === CraftingStationId.oven) |
| 103 | { return COOK_BURN_CHANCE_OVEN; } |
| 104 | return 0; |
| 105 | } |
| 106 | |
| 107 | function takeInputs (slots, inputs) |
| 108 | { |
| 109 | let next = slots.map((slot) => (slot ? structuredClone(slot) : null)); |
| 110 | for (const input of inputs ?? []) |
| 111 | { |
| 112 | let remaining = Math.max(0, stackQuantity(input.quantity)); |
| 113 | if (!remaining) |
| 114 | { continue; } |
| 115 | for (let i = 0; i < next.length && remaining > 0; i++) |
| 116 | { |
| 117 | if (!next[i] || next[i].itemId !== input.itemId) |
| 118 | { continue; } |
| 119 | const taken = takeFromSlot(next, i, remaining); |
| 120 | if (!taken.ok) |
| 121 | { continue; } |
| 122 | next = taken.slots; |
| 123 | remaining -= stackQuantity(taken.taken?.quantity); |
| 124 | } |
| 125 | if (remaining > 0) |
| 126 | { return { ok: false, slots }; } |
| 127 | } |
| 128 | return { ok: true, slots: next }; |
| 129 | } |
| 130 | |
| 131 | /** Spend one fill level of a dye bottle (remove at 0). Never loses the leftover. */ |
| 132 | function consumeDyeUse (slots, slotIndex) |
| 133 | { |
| 134 | return consumeFillCharge(slots, slotIndex, { |
| 135 | kind: "dye", |
| 136 | itemId: ItemId.dye |
| 137 | }); |
| 138 | } |
| 139 | |
| 140 | export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {}) |
| 141 | { |
| 142 | const entityId = world.characterEntities.get(characterId); |
| 143 | if (entityId == null) |
| 144 | { throw userError("Character is not in the world."); } |
| 145 | const handle = world.ecs.handleOf(entityId); |
| 146 | const identity = world.ecs.get(handle, Component.networkIdentity); |
| 147 | if (!identity || identity.sessionId !== sessionId) |
| 148 | { throw userError("Character is not in the world."); } |
| 149 | if (world.ecs.has(handle, Component.dead)) |
| 150 | { throw userError("You are dead."); } |
| 151 | |
| 152 | const stationDef = craftingStationDefinition(stationId); |
| 153 | if (!stationDef) |
| 154 | { throw userError("Unknown crafting station."); } |
| 155 | let recipe = recipeDefinition(recipeId); |
| 156 | if (!recipe) |
| 157 | { throw userError("Unknown recipe."); } |
| 158 | const stationIds = Array.isArray(recipe.stationIds) |
| 159 | ? recipe.stationIds |
| 160 | : [recipe.stationId]; |
| 161 | if (!stationIds.includes(stationId)) |
| 162 | { throw userError("That recipe cannot be made here."); } |
| 163 | |
| 164 | const position = world.ecs.get(handle, Component.position); |
| 165 | const blockType = stationBlockType(stationId); |
| 166 | if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType)) |
| 167 | { throw userError("You need to stand next to the station."); } |
| 168 | |
| 169 | const inventory = world.ecs.get(handle, Component.inventory); |
| 170 | const skills = world.ecs.get(handle, Component.skills); |
| 171 | const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing); |
| 172 | |
| 173 | let dyeColorKey = null; |
| 174 | if (recipe.tailorTemplate) |
| 175 | { |
| 176 | if (stationId !== CraftingStationId.tailorBench) |
| 177 | { throw userError("That garment can only be made at a tailor's bench."); } |
| 178 | const dyeIdx = options.dyeSlotIndex; |
| 179 | let dyeStack = null; |
| 180 | if (dyeIdx != null && dyeIdx >= 0) |
| 181 | { |
| 182 | dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null; |
| 183 | dyeColorKey = dyeStack ? dyeInstanceColorKey(dyeStack.instance) : null; |
| 184 | } |
| 185 | const resolved = resolveTailorCraft({ |
| 186 | templateId: recipe.tailorTemplate, |
| 187 | clothTier: options.clothTier, |
| 188 | dyeStack |
| 189 | }); |
| 190 | if (!resolved.ok) |
| 191 | { throw userError(resolved.reason); } |
| 192 | recipe = resolved.recipe; |
| 193 | } |
| 194 | else if (options.dyeSlotIndex != null) |
| 195 | { |
| 196 | // Dye is tailor-only; ignore client-supplied dye on other stations. |
| 197 | dyeColorKey = null; |
| 198 | } |
| 199 | |
| 200 | if (!canStartCraft(inventory?.slots ?? [], recipe, level, { dyeColorKey, dyeSlotIndex: options.dyeSlotIndex ?? null })) |
| 201 | { |
| 202 | if ((level | 0) < (recipe.minSkillLevel | 0 || 1)) |
| 203 | { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); } |
| 204 | if (!hasRecipeInputs(inventory?.slots ?? [], recipe)) |
| 205 | { throw userError("Missing materials."); } |
| 206 | if (recipe.consumeDye && dyeColorKey != null) |
| 207 | { |
| 208 | const probeSlot = pickEmptiestDyeSlot(inventory?.slots ?? [], dyeColorKey); |
| 209 | const dyeProbe = consumeDyeUse(inventory?.slots ?? [], probeSlot); |
| 210 | if (!dyeProbe.ok) |
| 211 | { throw userError("Need bag space to separate the partially used dye."); } |
| 212 | } |
| 213 | throw userError("Not enough bag space for the result."); |
| 214 | } |
| 215 | if (recipe.consumeDye && dyeColorKey != null) |
| 216 | { |
| 217 | const probeSlot = pickEmptiestDyeSlot(inventory?.slots ?? [], dyeColorKey); |
| 218 | const dye = inventory?.slots?.[probeSlot]; |
| 219 | if (!dye || dye.itemId !== ItemId.dye) |
| 220 | { throw userError("Selected dye is missing."); } |
| 221 | } |
| 222 | |
| 223 | const sessions = ensureCraftSessions(world); |
| 224 | const equipment = world.ecs.get(handle, Component.equipment); |
| 225 | const durationMs = Math.max( |
| 226 | 1, |
| 227 | Math.floor(craftDurationMs(recipe, CRAFT_DURATION_MS) * craftDurationMultiplier(equipment)) |
| 228 | ); |
| 229 | let batchRemaining = 1; |
| 230 | if (options.batchAll) |
| 231 | { batchRemaining = Infinity; } |
| 232 | else if (options.batchCount != null) |
| 233 | { batchRemaining = Math.max(1, options.batchCount | 0); } |
| 234 | sessions.set(characterId, { |
| 235 | sessionId, |
| 236 | stationId, |
| 237 | recipeId, |
| 238 | recipe, |
| 239 | dyeColorKey, |
| 240 | batchRemaining, |
| 241 | durationMs, |
| 242 | finishesAt: now + durationMs |
| 243 | }); |
| 244 | const events = []; |
| 245 | if (blockType) |
| 246 | { |
| 247 | const shove = tileShoveTowardBlock(world, handle, entityId, blockType); |
| 248 | if (shove) |
| 249 | { events.push(shove); } |
| 250 | } |
| 251 | events.push({ |
| 252 | type: "item-bubble", |
| 253 | entityId, |
| 254 | itemId: recipe.output.itemId, |
| 255 | quantity: Math.max(1, recipe.output.quantity | 0 || 1) |
| 256 | }); |
| 257 | events.push({ |
| 258 | type: "craft-started", |
| 259 | sessionId, |
| 260 | characterId, |
| 261 | recipeId, |
| 262 | durationMs |
| 263 | }); |
| 264 | return { events }; |
| 265 | } |
| 266 | |
| 267 | export function openStation (world, sessionId, characterId, stationId) |
| 268 | { |
| 269 | const entityId = world.characterEntities.get(characterId); |
| 270 | if (entityId == null) |
| 271 | { throw userError("Character is not in the world."); } |
| 272 | const handle = world.ecs.handleOf(entityId); |
| 273 | const identity = world.ecs.get(handle, Component.networkIdentity); |
| 274 | if (!identity || identity.sessionId !== sessionId) |
| 275 | { throw userError("Character is not in the world."); } |
| 276 | if (world.ecs.has(handle, Component.dead)) |
| 277 | { throw userError("You are dead."); } |
| 278 | |
| 279 | const stationDef = craftingStationDefinition(stationId); |
| 280 | if (!stationDef) |
| 281 | { throw userError("Unknown crafting station."); } |
| 282 | const blockType = stationBlockType(stationId); |
| 283 | const position = world.ecs.get(handle, Component.position); |
| 284 | if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType)) |
| 285 | { throw userError("You need to stand next to the station."); } |
| 286 | |
| 287 | const events = []; |
| 288 | if (blockType) |
| 289 | { |
| 290 | const shove = tileShoveTowardBlock(world, handle, entityId, blockType); |
| 291 | if (shove) |
| 292 | { events.push(shove); } |
| 293 | } |
| 294 | events.push({ |
| 295 | type: "station-open", |
| 296 | sessionId, |
| 297 | characterId, |
| 298 | stationId |
| 299 | }); |
| 300 | return { events }; |
| 301 | } |
| 302 | |
| 303 | export function cancelCraft (world, characterId) |
| 304 | { |
| 305 | ensureCraftSessions(world).delete(characterId); |
| 306 | return { events: [] }; |
| 307 | } |
| 308 | |
| 309 | export function stepCrafting (world, now) |
| 310 | { |
| 311 | const sessions = ensureCraftSessions(world); |
| 312 | const events = []; |
| 313 | const privates = []; |
| 314 | for (const [characterId, session] of [...sessions.entries()]) |
| 315 | { |
| 316 | if (now < session.finishesAt) |
| 317 | { continue; } |
| 318 | sessions.delete(characterId); |
| 319 | const entityId = world.characterEntities.get(characterId); |
| 320 | if (entityId == null) |
| 321 | { |
| 322 | events.push({ |
| 323 | type: "craft-result", |
| 324 | sessionId: session.sessionId, |
| 325 | recipeId: session.recipeId, |
| 326 | ok: false, |
| 327 | error: "Character left the world." |
| 328 | }); |
| 329 | continue; |
| 330 | } |
| 331 | const handle = world.ecs.handleOf(entityId); |
| 332 | if (world.ecs.has(handle, Component.dead)) |
| 333 | { |
| 334 | events.push({ |
| 335 | type: "craft-result", |
| 336 | sessionId: session.sessionId, |
| 337 | recipeId: session.recipeId, |
| 338 | ok: false, |
| 339 | error: "You are dead." |
| 340 | }); |
| 341 | continue; |
| 342 | } |
| 343 | |
| 344 | const recipe = session.recipe ?? recipeDefinition(session.recipeId); |
| 345 | const stationDef = craftingStationDefinition(session.stationId); |
| 346 | const inventory = world.ecs.get(handle, Component.inventory); |
| 347 | const skills = world.ecs.get(handle, Component.skills); |
| 348 | const position = world.ecs.get(handle, Component.position); |
| 349 | const blockType = stationBlockType(session.stationId); |
| 350 | const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing); |
| 351 | |
| 352 | if (!recipe || !stationDef || !inventory |
| 353 | || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType)) |
| 354 | || !canCraftFitInventory(inventory.slots, recipe, { dyeColorKey: session.dyeColorKey }) |
| 355 | || (level | 0) < (recipe.minSkillLevel | 0 || 1)) |
| 356 | { |
| 357 | events.push({ |
| 358 | type: "craft-result", |
| 359 | sessionId: session.sessionId, |
| 360 | recipeId: session.recipeId, |
| 361 | ok: false, |
| 362 | error: "Could not finish crafting." |
| 363 | }); |
| 364 | continue; |
| 365 | } |
| 366 | |
| 367 | const taken = takeInputs(inventory.slots, recipe.inputs); |
| 368 | if (!taken.ok) |
| 369 | { |
| 370 | events.push({ |
| 371 | type: "craft-result", |
| 372 | sessionId: session.sessionId, |
| 373 | recipeId: session.recipeId, |
| 374 | ok: false, |
| 375 | error: "Missing materials." |
| 376 | }); |
| 377 | continue; |
| 378 | } |
| 379 | let slotsAfter = taken.slots; |
| 380 | if (recipe.consumeDye && session.dyeColorKey != null) |
| 381 | { |
| 382 | const consumeSlot = pickEmptiestDyeSlot(slotsAfter, session.dyeColorKey); |
| 383 | const dyeTaken = consumeDyeUse(slotsAfter, consumeSlot); |
| 384 | if (!dyeTaken.ok) |
| 385 | { |
| 386 | events.push({ |
| 387 | type: "craft-result", |
| 388 | sessionId: session.sessionId, |
| 389 | recipeId: session.recipeId, |
| 390 | ok: false, |
| 391 | error: dyeTaken.reason === "space" |
| 392 | ? "Need bag space to separate the partially used dye." |
| 393 | : "Selected dye is missing." |
| 394 | }); |
| 395 | continue; |
| 396 | } |
| 397 | slotsAfter = dyeTaken.slots; |
| 398 | } |
| 399 | |
| 400 | const burnChance = cookBurnChance(session.stationId); |
| 401 | const burned = burnChance > 0 |
| 402 | && recipe.burntOutput?.itemId |
| 403 | && ((world.rng?.() ?? Math.random()) < burnChance); |
| 404 | const outSpec = burned ? recipe.burntOutput : recipe.output; |
| 405 | const outDef = itemDefinition(outSpec.itemId); |
| 406 | const outQty = Math.max(1, outSpec.quantity | 0 || 1); |
| 407 | const origin = craftOrigin( |
| 408 | burned ? CraftOriginVerb.ruined : craftOriginVerbForStation(session.stationId), |
| 409 | characterDisplayName(world, handle) |
| 410 | ); |
| 411 | const outStack = { |
| 412 | itemId: outSpec.itemId, |
| 413 | quantity: outQty, |
| 414 | origins: [{ origin, quantity: outQty }], |
| 415 | ...(recipe.dyeColor && !burned ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {}) |
| 416 | }; |
| 417 | const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef); |
| 418 | if (!added.ok || added.remainder > 0) |
| 419 | { |
| 420 | events.push({ |
| 421 | type: "craft-result", |
| 422 | sessionId: session.sessionId, |
| 423 | recipeId: session.recipeId, |
| 424 | ok: false, |
| 425 | error: "Not enough bag space for the result." |
| 426 | }); |
| 427 | continue; |
| 428 | } |
| 429 | inventory.slots = added.slots; |
| 430 | |
| 431 | let skillsChanged = false; |
| 432 | const levelUps = []; |
| 433 | if (!burned && skills?.xp && stationDef?.skillId) |
| 434 | { |
| 435 | const result = applySkillXp( |
| 436 | skills, |
| 437 | stationDef.skillId, |
| 438 | craftXpForConsumedInputs(recipe.inputs, stationDef.skillId), |
| 439 | world.ecs.get(handle, Component.equipment) |
| 440 | ); |
| 441 | if (result.changed) |
| 442 | { skillsChanged = true; } |
| 443 | if (result.levelUp) |
| 444 | { levelUps.push(result.levelUp); } |
| 445 | } |
| 446 | |
| 447 | privates.push({ characterId, bag: bagView(world.ecs, handle) }); |
| 448 | if (skillsChanged) |
| 449 | { |
| 450 | events.push({ |
| 451 | type: "skills-updated", |
| 452 | entityId, |
| 453 | characterId, |
| 454 | ...publicSkillsPayload(skills), |
| 455 | stored: storedSkillXp(skills), |
| 456 | levelUps |
| 457 | }); |
| 458 | } |
| 459 | |
| 460 | if (burned) |
| 461 | { |
| 462 | events.push({ |
| 463 | type: "command-error", |
| 464 | sessionId: session.sessionId, |
| 465 | message: "You burn the food." |
| 466 | }); |
| 467 | } |
| 468 | |
| 469 | let continuing = false; |
| 470 | const batchRemaining = session.batchRemaining ?? 1; |
| 471 | const nextRemaining = batchRemaining === Infinity |
| 472 | ? Infinity |
| 473 | : Math.max(0, (batchRemaining | 0) - 1); |
| 474 | if (nextRemaining !== 0 && canStartCraft( |
| 475 | inventory.slots, |
| 476 | recipe, |
| 477 | level, |
| 478 | { dyeColorKey: session.dyeColorKey, dyeSlotIndex: null } |
| 479 | )) |
| 480 | { |
| 481 | const equipment = world.ecs.get(handle, Component.equipment); |
| 482 | const durationMs = session.durationMs ?? Math.max( |
| 483 | 1, |
| 484 | Math.floor(craftDurationMs(recipe, CRAFT_DURATION_MS) * craftDurationMultiplier(equipment)) |
| 485 | ); |
| 486 | sessions.set(characterId, { |
| 487 | ...session, |
| 488 | recipe, |
| 489 | batchRemaining: nextRemaining, |
| 490 | durationMs, |
| 491 | finishesAt: now + durationMs |
| 492 | }); |
| 493 | continuing = true; |
| 494 | events.push({ |
| 495 | type: "item-bubble", |
| 496 | entityId, |
| 497 | itemId: outSpec.itemId, |
| 498 | quantity: outQty |
| 499 | }); |
| 500 | } |
| 501 | events.push({ |
| 502 | type: "craft-result", |
| 503 | sessionId: session.sessionId, |
| 504 | recipeId: session.recipeId, |
| 505 | ok: true, |
| 506 | continuing |
| 507 | }); |
| 508 | } |
| 509 | return { events, privates }; |
| 510 | } |
| 511 | |
| 512 | export function handleCraftCommand (world, sessionId, command, now) |
| 513 | { |
| 514 | switch (command.type) |
| 515 | { |
| 516 | case "open-station": |
| 517 | return openStation(world, sessionId, command.characterId, command.stationId); |
| 518 | case "start-craft": |
| 519 | return startCraft( |
| 520 | world, |
| 521 | sessionId, |
| 522 | command.characterId, |
| 523 | command.stationId, |
| 524 | command.recipeId, |
| 525 | now, |
| 526 | { |
| 527 | clothTier: command.clothTier ?? null, |
| 528 | dyeSlotIndex: command.dyeSlotIndex ?? null, |
| 529 | batchCount: command.batchCount ?? null, |
| 530 | batchAll: !!command.batchAll |
| 531 | } |
| 532 | ); |
| 533 | case "cancel-craft": |
| 534 | return cancelCraft(world, command.characterId); |
| 535 | default: |
| 536 | return null; |
| 537 | } |
| 538 | } |