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