import { Component } from "../ecs/components.js"; import { BlockType } from "../../../shared/definitions/tiles.js"; import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js"; import { ItemId, itemDefinition } from "../../../shared/definitions/items.js"; import { SkillId, skillLevel } from "../../../shared/definitions/skills.js"; import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js"; import { recipeDefinition, canStartCraft, canCraftFitInventory, hasRecipeInputs } from "../../../shared/crafting/recipes.js"; import { resolveTailorCraft } from "../../../shared/crafting/tailor.js"; import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js"; import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js"; import { attachOrigins, craftOrigin, craftOriginVerbForStation } from "../../../shared/items/origin.js"; import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js"; import { bagView } from "../items/bags.js"; import { tileToChunk, tileToLocal } from "../world/coordinates.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { tileShoveTowardBlock } from "../simulation/tileInteract.js"; function userError (message) { const error = new Error(message); error.userFacing = true; return error; } function characterDisplayName (world, handle) { const appearance = world.ecs.get(handle, Component.appearance); const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim(); return name || "someone"; } function ensureCraftSessions (world) { if (!world.craftSessions) { world.craftSessions = new Map(); } return world.craftSessions; } function nearStationBlock (world, tileX, tileY, blockType) { for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy)); const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx); if (data.blocks[index]?.typeId === blockType) { return true; } } } return false; } function stationBlockType (stationId) { if (stationId === CraftingStationId.furnace) { return BlockType.furnace; } if (stationId === CraftingStationId.anvil) { return BlockType.anvil; } if (stationId === CraftingStationId.woodworkingBench) { return BlockType.woodworkingBench; } if (stationId === CraftingStationId.craftingBench) { return BlockType.craftingBench; } if (stationId === CraftingStationId.spinningWheel) { return BlockType.spinningWheel; } if (stationId === CraftingStationId.loom) { return BlockType.loom; } if (stationId === CraftingStationId.tailorBench) { return BlockType.tailorBench; } return null; } function takeInputs (slots, inputs) { let next = slots.map((slot) => (slot ? structuredClone(slot) : null)); for (const input of inputs ?? []) { let remaining = Math.max(0, stackQuantity(input.quantity)); if (!remaining) { continue; } for (let i = 0; i < next.length && remaining > 0; i++) { if (!next[i] || next[i].itemId !== input.itemId) { continue; } const taken = takeFromSlot(next, i, remaining); if (!taken.ok) { continue; } next = taken.slots; remaining -= stackQuantity(taken.taken?.quantity); } if (remaining > 0) { return { ok: false, slots }; } } return { ok: true, slots: next }; } /** Spend one fill level of a dye bottle (remove at 0). Never loses the leftover. */ function consumeDyeUse (slots, slotIndex) { return consumeFillCharge(slots, slotIndex, { kind: "dye", itemId: ItemId.dye }); } export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {}) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { throw userError("Character is not in the world."); } const handle = world.ecs.handleOf(entityId); const identity = world.ecs.get(handle, Component.networkIdentity); if (!identity || identity.sessionId !== sessionId) { throw userError("Character is not in the world."); } if (world.ecs.has(handle, Component.dead)) { throw userError("You are dead."); } const stationDef = craftingStationDefinition(stationId); if (!stationDef) { throw userError("Unknown crafting station."); } let recipe = recipeDefinition(recipeId); if (!recipe) { throw userError("Unknown recipe."); } const stationIds = Array.isArray(recipe.stationIds) ? recipe.stationIds : [recipe.stationId]; if (!stationIds.includes(stationId)) { throw userError("That recipe cannot be made here."); } const position = world.ecs.get(handle, Component.position); const blockType = stationBlockType(stationId); if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType)) { throw userError("You need to stand next to the station."); } const inventory = world.ecs.get(handle, Component.inventory); const skills = world.ecs.get(handle, Component.skills); const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing); let dyeSlotIndex = null; if (recipe.tailorTemplate) { const dyeIdx = options.dyeSlotIndex; let dyeStack = null; if (dyeIdx != null && dyeIdx >= 0) { dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null; dyeSlotIndex = dyeIdx | 0; } const resolved = resolveTailorCraft({ templateId: recipe.tailorTemplate, clothTier: options.clothTier, dyeStack }); if (!resolved.ok) { throw userError(resolved.reason); } recipe = resolved.recipe; } if (!canStartCraft(inventory?.slots ?? [], recipe, level, { dyeSlotIndex })) { if ((level | 0) < (recipe.minSkillLevel | 0 || 1)) { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); } if (!hasRecipeInputs(inventory?.slots ?? [], recipe)) { throw userError("Missing materials."); } if (recipe.consumeDye && dyeSlotIndex != null) { const dyeProbe = consumeDyeUse(inventory?.slots ?? [], dyeSlotIndex); if (!dyeProbe.ok) { throw userError("Need bag space to separate the partially used dye."); } } throw userError("Not enough bag space for the result."); } if (recipe.consumeDye && dyeSlotIndex != null) { const dye = inventory?.slots?.[dyeSlotIndex]; if (!dye || dye.itemId !== ItemId.dye) { throw userError("Selected dye is missing."); } } const sessions = ensureCraftSessions(world); const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS); sessions.set(characterId, { sessionId, stationId, recipeId, recipe, dyeSlotIndex, finishesAt: now + durationMs }); const events = []; if (blockType) { const shove = tileShoveTowardBlock(world, handle, entityId, blockType); if (shove) { events.push(shove); } } events.push({ type: "item-bubble", entityId, itemId: recipe.output.itemId, quantity: Math.max(1, recipe.output.quantity | 0 || 1) }); events.push({ type: "craft-started", sessionId, characterId, recipeId, durationMs }); return { events }; } export function openStation (world, sessionId, characterId, stationId) { const entityId = world.characterEntities.get(characterId); if (entityId == null) { throw userError("Character is not in the world."); } const handle = world.ecs.handleOf(entityId); const identity = world.ecs.get(handle, Component.networkIdentity); if (!identity || identity.sessionId !== sessionId) { throw userError("Character is not in the world."); } if (world.ecs.has(handle, Component.dead)) { throw userError("You are dead."); } const stationDef = craftingStationDefinition(stationId); if (!stationDef) { throw userError("Unknown crafting station."); } const blockType = stationBlockType(stationId); const position = world.ecs.get(handle, Component.position); if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType)) { throw userError("You need to stand next to the station."); } const events = []; if (blockType) { const shove = tileShoveTowardBlock(world, handle, entityId, blockType); if (shove) { events.push(shove); } } events.push({ type: "station-open", sessionId, characterId, stationId }); return { events }; } export function cancelCraft (world, characterId) { ensureCraftSessions(world).delete(characterId); return { events: [] }; } export function stepCrafting (world, now) { const sessions = ensureCraftSessions(world); const events = []; const privates = []; for (const [characterId, session] of [...sessions.entries()]) { if (now < session.finishesAt) { continue; } sessions.delete(characterId); const entityId = world.characterEntities.get(characterId); if (entityId == null) { events.push({ type: "craft-result", sessionId: session.sessionId, recipeId: session.recipeId, ok: false, error: "Character left the world." }); continue; } const handle = world.ecs.handleOf(entityId); if (world.ecs.has(handle, Component.dead)) { events.push({ type: "craft-result", sessionId: session.sessionId, recipeId: session.recipeId, ok: false, error: "You are dead." }); continue; } const recipe = session.recipe ?? recipeDefinition(session.recipeId); const stationDef = craftingStationDefinition(session.stationId); const inventory = world.ecs.get(handle, Component.inventory); const skills = world.ecs.get(handle, Component.skills); const position = world.ecs.get(handle, Component.position); const blockType = stationBlockType(session.stationId); const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing); if (!recipe || !stationDef || !inventory || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType)) || !canCraftFitInventory(inventory.slots, recipe, { dyeSlotIndex: session.dyeSlotIndex }) || (level | 0) < (recipe.minSkillLevel | 0 || 1)) { events.push({ type: "craft-result", sessionId: session.sessionId, recipeId: session.recipeId, ok: false, error: "Could not finish crafting." }); continue; } const taken = takeInputs(inventory.slots, recipe.inputs); if (!taken.ok) { events.push({ type: "craft-result", sessionId: session.sessionId, recipeId: session.recipeId, ok: false, error: "Missing materials." }); continue; } let slotsAfter = taken.slots; if (recipe.consumeDye && session.dyeSlotIndex != null) { const dyeTaken = consumeDyeUse(slotsAfter, session.dyeSlotIndex); if (!dyeTaken.ok) { events.push({ type: "craft-result", sessionId: session.sessionId, recipeId: session.recipeId, ok: false, error: dyeTaken.reason === "space" ? "Need bag space to separate the partially used dye." : "Selected dye is missing." }); continue; } slotsAfter = dyeTaken.slots; } const outDef = itemDefinition(recipe.output.itemId); const outQty = Math.max(1, recipe.output.quantity | 0 || 1); const origin = craftOrigin( craftOriginVerbForStation(session.stationId), characterDisplayName(world, handle) ); const outStack = { itemId: recipe.output.itemId, quantity: outQty, origins: [{ origin, quantity: outQty }], ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {}) }; const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef); if (!added.ok || added.remainder > 0) { events.push({ type: "craft-result", sessionId: session.sessionId, recipeId: session.recipeId, ok: false, error: "Not enough bag space for the result." }); continue; } inventory.slots = added.slots; let skillsChanged = false; const levelUps = []; if (skills?.xp && recipe.xpMaterial && stationDef?.skillId) { const result = applySkillXp( skills, stationDef.skillId, smeltingXpForMaterial(recipe.xpMaterial) ); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } privates.push({ characterId, bag: bagView(world.ecs, handle) }); if (skillsChanged) { events.push({ type: "skills-updated", entityId, characterId, skills: publicSkillsView(skills), stored: storedSkillXp(skills), levelUps }); } events.push({ type: "craft-result", sessionId: session.sessionId, recipeId: session.recipeId, ok: true }); } return { events, privates }; } export function handleCraftCommand (world, sessionId, command, now) { switch (command.type) { case "open-station": return openStation(world, sessionId, command.characterId, command.stationId); case "start-craft": return startCraft( world, sessionId, command.characterId, command.stationId, command.recipeId, now, { clothTier: command.clothTier ?? null, dyeSlotIndex: command.dyeSlotIndex ?? null } ); case "cancel-craft": return cancelCraft(world, command.characterId); default: return null; } }