import { Component } from "../ecs/components.js"; import { BlockType, woodTierForTreeBlock, isChopableTreeBlock, plantGatherForBlock } from "../../../shared/definitions/tiles.js"; import { itemDefinition, ItemId } from "../../../shared/definitions/items.js"; import { SkillId } from "../../../shared/definitions/skills.js"; import { materialFromOreBoulderState, oreItemIdForMaterial, miningDurationMs, miningXpForMaterial, oreExhaustDurationMs, oreBoulderState, EXHAUSTED_ORE_BOULDER_STATE, resolveMiningPickaxe, resolveWoodcuttingAxe, resolvePlantClippers, resolveHerbGather, woodcuttingDurationMs, woodcuttingXpForWood, treeExhaustDurationMs, logItemIdForWoodTier, herbalismDurationMs, herbalismXpForPick, PLANT_EXHAUST_MS } from "../../../shared/definitions/gathering.js"; import { rawClothItemId } from "../../../shared/definitions/clothItems.js"; import { ClothTier } from "../../../shared/definitions/materialTiers.js"; import { flowerItemInstance, flowerColorIdFromBlockState, flowerBlockState, flowerColorIdForTile, randomFlowerColorId } from "../../../shared/definitions/dyes.js"; import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js"; import { insertStack } from "../../../shared/items/inventory.js"; import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js"; import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js"; import { seasonIdAt, treeStumpStateForSeason, SeasonId } from "../../../shared/world/season.js"; import { bagView } from "../items/bags.js"; import { chebyshev, clearEngage } from "../combat/service.js"; import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; const GATHER_SWING_INTERVAL_MS = 900; 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 ensureOreRespawns (world) { if (!world.oreRespawns) { world.oreRespawns = new Map(); } return world.oreRespawns; } function ensureTreeRespawns (world) { if (!world.treeRespawns) { world.treeRespawns = new Map(); } return world.treeRespawns; } function ensurePlantRespawns (world) { if (!world.plantRespawns) { world.plantRespawns = new Map(); } return world.plantRespawns; } function blockAt (world, tileX, tileY) { const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY)); return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null; } function setBlockState (world, tileX, tileY, typeId, state) { const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); const localX = tileToLocal(tileX); const localY = tileToLocal(tileY); const data = world.chunkData(chunkX, chunkY); const index = localY * CHUNK_SIZE + localX; const prev = data?.blocks?.[index]; if (!prev || prev.typeId !== typeId) { return null; } const block = { typeId: prev.typeId, state, config: prev.config ?? null }; data.blocks[index] = block; return { type: "chunk-delta", chunkX, chunkY, tileX, tileY, localX, localY, block }; } function setBoulderState (world, tileX, tileY, state) { return setBlockState(world, tileX, tileY, BlockType.boulder, state); } function setTreeState (world, tileX, tileY, typeId, state) { return setBlockState(world, tileX, tileY, typeId, state); } function clearBlock (world, tileX, tileY, typeId) { const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); const localX = tileToLocal(tileX); const localY = tileToLocal(tileY); const data = world.chunkData(chunkX, chunkY); const index = localY * CHUNK_SIZE + localX; const prev = data?.blocks?.[index]; if (!prev || prev.typeId !== typeId) { return null; } data.blocks[index] = null; return { type: "chunk-delta", chunkX, chunkY, tileX, tileY, localX, localY, block: null }; } function placeBlock (world, tileX, tileY, typeId, state) { const chunkX = tileToChunk(tileX); const chunkY = tileToChunk(tileY); const localX = tileToLocal(tileX); const localY = tileToLocal(tileY); const data = world.chunkData(chunkX, chunkY); const index = localY * CHUNK_SIZE + localX; const block = { typeId, state, config: null }; data.blocks[index] = block; return { type: "chunk-delta", chunkX, chunkY, tileX, tileY, localX, localY, block }; } function pickaxeForOre (world, handle, materialId) { const inventory = world.ecs.get(handle, Component.inventory); const equipment = world.ecs.get(handle, Component.equipment); const skills = world.ecs.get(handle, Component.skills); return resolveMiningPickaxe({ inventorySlots: inventory?.slots, equipmentSlots: equipment?.slots, skills, materialId }); } function axeForWood (world, handle, woodTier) { const inventory = world.ecs.get(handle, Component.inventory); const equipment = world.ecs.get(handle, Component.equipment); const skills = world.ecs.get(handle, Component.skills); return resolveWoodcuttingAxe({ inventorySlots: inventory?.slots, equipmentSlots: equipment?.slots, skills, woodTier }); } function clearGather (ecs, handle) { if (ecs.has(handle, Component.gather)) { ecs.remove(handle, Component.gather); } } export function cancelGather (ecs, handle) { clearGather(ecs, handle); } /** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */ export function clearOreRespawnsForChunk (world, chunkX, chunkY) { const respawns = world.oreRespawns; if (!respawns?.size) { return; } for (const key of [...respawns.keys()]) { const [tileX, tileY] = key.split(",").map(Number); if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY) { respawns.delete(key); } } } /** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */ export function clearTreeRespawnsForChunk (world, chunkX, chunkY) { const respawns = world.treeRespawns; if (!respawns?.size) { return; } for (const key of [...respawns.keys()]) { const [tileX, tileY] = key.split(",").map(Number); if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY) { respawns.delete(key); } } } export function clearPlantRespawnsForChunk (world, chunkX, chunkY) { const respawns = world.plantRespawns; if (!respawns?.size) { return; } for (const key of [...respawns.keys()]) { const [tileX, tileY] = key.split(",").map(Number); if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY) { respawns.delete(key); } } } /** * Restore exhausted ore boulders whose timers have elapsed. */ export function stepOreRespawns (world, now) { const respawns = world.oreRespawns; if (!respawns?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...respawns.entries()]) { if (now < entry.respawnsAt) { continue; } respawns.delete(key); const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId)); if (delta) { events.push(delta); } } return { events }; } /** * Restore exhausted trees whose timers have elapsed (live seasonal look). */ export function stepTreeRespawns (world, now) { const respawns = world.treeRespawns; if (!respawns?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...respawns.entries()]) { if (now < entry.respawnsAt) { continue; } respawns.delete(key); const delta = setTreeState( world, entry.tileX, entry.tileY, entry.typeId, SeasonId.summer ); if (delta) { events.push(delta); } } return { events }; } export function stepPlantRespawns (world, now) { const respawns = world.plantRespawns; if (!respawns?.size) { return { events: [] }; } const events = []; for (const [key, entry] of [...respawns.entries()]) { if (now < entry.respawnsAt) { continue; } respawns.delete(key); const existing = blockAt(world, entry.tileX, entry.tileY); if (existing) { continue; } const state = entry.typeId === BlockType.flower ? flowerBlockState(randomFlowerColorId()) : (entry.state ?? defaultPlantState(entry.typeId)); const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state); if (delta) { events.push(delta); } } return { events }; } function beginGatherSwing (world, handle, entityId, position, gatherFields, now) { clearEngage(world.ecs, entityId); const path = world.ecs.get(handle, Component.path); if (path) { path.tiles = []; } world.ecs.add(handle, Component.gather, { ...gatherFields, startedAt: now, finishesAt: now + gatherFields.durationMs, nextSwingAt: now }); return { events: [{ type: "gather-swing", attackerId: entityId, tileX: gatherFields.tileX, tileY: gatherFields.tileY, fromTileX: position.tileX, fromTileY: position.tileY, toolItemId: gatherFields.toolItemId ?? null, swipe: false }] }; } /** * Start mining an ore boulder. Returns events / private bag updates when complete via stepGather. */ export function startMine (world, sessionId, characterId, tileX, tileY, now) { 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 position = world.ecs.get(handle, Component.position); if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1) { throw userError("You need to stand next to the rock."); } const block = blockAt(world, tileX, tileY); if (!block || block.typeId !== BlockType.boulder) { throw userError("There is nothing to mine there."); } const materialId = materialFromOreBoulderState(block.state); if (!materialId) { throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE ? "That rock is exhausted." : "That rock has no ore."); } const pickaxe = pickaxeForOre(world, handle, materialId); if (!pickaxe.ok) { throw userError(pickaxe.reason); } const durationMs = miningDurationMs(materialId, pickaxe.tool.tier); const toolItemId = pickaxe.tool.stack?.itemId ?? null; return beginGatherSwing(world, handle, entityId, position, { kind: "mining", tileX, tileY, materialId, toolTier: pickaxe.tool.tier, toolItemId, durationMs }, now); } /** * Start chopping a tree. Completes via stepGather (stump + log + woodcutting XP). */ export function startChop (world, sessionId, characterId, tileX, tileY, now) { 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 position = world.ecs.get(handle, Component.position); if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1) { throw userError("You need to stand next to the tree."); } const block = blockAt(world, tileX, tileY); if (!isChopableTreeBlock(block)) { throw userError(block && woodTierForTreeBlock(block.typeId) != null ? "That tree is already felled." : "There is nothing to chop there."); } const woodTier = woodTierForTreeBlock(block.typeId); const axe = axeForWood(world, handle, woodTier); if (!axe.ok) { throw userError(axe.reason); } const durationMs = woodcuttingDurationMs(woodTier, axe.tool.tier); const toolItemId = axe.tool.stack?.itemId ?? null; return beginGatherSwing(world, handle, entityId, position, { kind: "woodcutting", tileX, tileY, typeId: block.typeId, woodTier, toolTier: axe.tool.tier, toolItemId, durationMs }, now); } /** * Pick a plant node (flower / cotton; no tools required). */ export function startPick (world, sessionId, characterId, tileX, tileY, now) { 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 position = world.ecs.get(handle, Component.position); if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1) { throw userError("You need to stand next to the plant."); } const block = blockAt(world, tileX, tileY); const plant = plantGatherForBlock(block); if (!plant) { throw userError("There is nothing to pick there."); } const inventory = world.ecs.get(handle, Component.inventory); const equipment = world.ecs.get(handle, Component.equipment); const skills = world.ecs.get(handle, Component.skills); const clippers = resolvePlantClippers({ inventorySlots: inventory?.slots, equipmentSlots: equipment?.slots, skills, requireTool: !!plant.requiresClippers }); if (!clippers.ok) { throw userError(clippers.reason); } let herbId = null; let herbTier = null; if (plant.kind === "herb") { const gate = resolveHerbGather({ herbId: block.state, skills }); if (!gate.ok) { throw userError(gate.reason); } herbId = gate.herb.herbId; herbTier = gate.herb.tier; } const toolTier = clippers.tool?.tier ?? null; const durationMs = herbalismDurationMs(plant.kind, toolTier, herbTier); const toolItemId = clippers.tool?.stack?.itemId ?? null; const prefixEvents = []; let flowerColorId = null; if (plant.kind === "flower") { flowerColorId = flowerColorIdFromBlockState(block.state); if (!flowerColorId) { // Legacy / uncoloured placements: lock a colour before the pick starts. flowerColorId = flowerColorIdForTile(tileX, tileY); const delta = setBlockState( world, tileX, tileY, BlockType.flower, flowerBlockState(flowerColorId) ); if (delta) { prefixEvents.push(delta); } } } const started = beginGatherSwing(world, handle, entityId, position, { kind: "plant", plantKind: plant.kind, herbId, herbTier, tileX, tileY, typeId: block.typeId, flowerColorId, toolTier, toolItemId, durationMs }, now); return { ...started, events: [...prefixEvents, ...(started.events ?? [])] }; } function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = []) { privates.push({ characterId: character.characterId, bag: bagView(world.ecs, handle) }); if (skillsChanged) { events.push({ type: "skills-updated", entityId, characterId: character.characterId, skills: publicSkillsView(skills), stored: storedSkillXp(skills), levelUps }); } } function completeMining (world, handle, entityId, character, gather, events, privates, now) { const oreItemId = oreItemIdForMaterial(gather.materialId); const def = itemDefinition(oreItemId); const inventory = world.ecs.get(handle, Component.inventory); if (!oreItemId || !def || !inventory) { clearGather(world.ecs, handle); return; } const origin = gatherOrigin(GatherOriginVerb.mined, characterDisplayName(world, handle)); const stack = attachOrigins({ itemId: oreItemId, quantity: 1, origins: [{ origin, quantity: 1 }] }); const inserted = insertStack(inventory.slots, stack, def); if (!inserted.ok || inserted.remainder > 0) { clearGather(world.ecs, handle); events.push({ type: "command-error", sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId, message: "Your inventory is full." }); return; } inventory.slots = inserted.slots; const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp) { const result = applySkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } const exhausted = setBoulderState( world, gather.tileX, gather.tileY, EXHAUSTED_ORE_BOULDER_STATE ); if (exhausted) { events.push(exhausted); ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), { tileX: gather.tileX, tileY: gather.tileY, materialId: gather.materialId, respawnsAt: now + oreExhaustDurationMs(gather.materialId) }); } clearGather(world.ecs, handle); pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps); events.push({ type: "gather-complete", characterId: character.characterId, kind: "mining", materialId: gather.materialId, itemId: oreItemId }); } function completeWoodcutting (world, handle, entityId, character, gather, events, privates, now) { const logItemId = logItemIdForWoodTier(gather.woodTier); const def = itemDefinition(logItemId); const inventory = world.ecs.get(handle, Component.inventory); if (!logItemId || !def || !inventory) { clearGather(world.ecs, handle); return; } const origin = gatherOrigin(GatherOriginVerb.felled, characterDisplayName(world, handle)); const stack = attachOrigins({ itemId: logItemId, quantity: 1, origins: [{ origin, quantity: 1 }] }); const inserted = insertStack(inventory.slots, stack, def); if (!inserted.ok || inserted.remainder > 0) { clearGather(world.ecs, handle); events.push({ type: "command-error", sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId, message: "Your inventory is full." }); return; } inventory.slots = inserted.slots; const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp) { const result = applySkillXp(skills, SkillId.woodcutting, woodcuttingXpForWood(gather.woodTier)); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } const stumpState = treeStumpStateForSeason(seasonIdAt(now)); const exhausted = setTreeState( world, gather.tileX, gather.tileY, gather.typeId, stumpState ); if (exhausted) { events.push(exhausted); ensureTreeRespawns(world).set(tileKey(gather.tileX, gather.tileY), { tileX: gather.tileX, tileY: gather.tileY, typeId: gather.typeId, woodTier: gather.woodTier, respawnsAt: now + treeExhaustDurationMs(gather.woodTier) }); } clearGather(world.ecs, handle); pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps); events.push({ type: "gather-complete", characterId: character.characterId, kind: "woodcutting", woodTier: gather.woodTier, itemId: logItemId }); } function completePlant (world, handle, entityId, character, gather, events, privates, now) { const inventory = world.ecs.get(handle, Component.inventory); if (!inventory) { clearGather(world.ecs, handle); return; } let itemId = null; let instance = null; if (gather.plantKind === "flower") { itemId = ItemId.flower; const live = blockAt(world, gather.tileX, gather.tileY); const colorId = gather.flowerColorId ?? flowerColorIdFromBlockState(live?.state) ?? randomFlowerColorId(); instance = flowerItemInstance(colorId); } else if (gather.plantKind === "cotton") { itemId = rawClothItemId(ClothTier.cotton); } else if (gather.plantKind === "herb") { const herb = herbDefinition(gather.herbId); itemId = herb?.itemId ?? null; } else { clearGather(world.ecs, handle); return; } const def = itemDefinition(itemId); if (!def) { clearGather(world.ecs, handle); return; } const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle)); const stack = attachOrigins({ itemId, quantity: 1, instance, origins: [{ origin, quantity: 1 }] }); const inserted = insertStack(inventory.slots, stack, def); if (!inserted.ok || inserted.remainder > 0) { clearGather(world.ecs, handle); events.push({ type: "command-error", sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId, message: "Your inventory is full." }); return; } inventory.slots = inserted.slots; const skills = world.ecs.get(handle, Component.skills); let skillsChanged = false; const levelUps = []; if (skills?.xp) { const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind, gather.herbTier)); if (result.changed) { skillsChanged = true; } if (result.levelUp) { levelUps.push(result.levelUp); } } const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId); if (delta) { events.push(delta); } ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), { tileX: gather.tileX, tileY: gather.tileY, typeId: gather.typeId, // Colour is chosen when the node refreshes (see stepPlantRespawns). state: gather.plantKind === "flower" ? null : (gather.plantKind === "herb" && isHerbId(gather.herbId) ? gather.herbId : defaultPlantState(gather.typeId)), respawnsAt: now + PLANT_EXHAUST_MS }); clearGather(world.ecs, handle); pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps); events.push({ type: "gather-complete", characterId: character.characterId, kind: "plant", plantKind: gather.plantKind, itemId }); } export function stepGather (world, now) { const events = []; const privates = []; events.push(...stepOreRespawns(world, now).events); events.push(...stepTreeRespawns(world, now).events); events.push(...stepPlantRespawns(world, now).events); for (const entity of world.ecs.query(Component.gather, Component.position, Component.character)) { const { handle, gather, position, character, entityId } = entity; if (world.ecs.has(handle, Component.dead)) { clearGather(world.ecs, handle); continue; } if (chebyshev(position.tileX, position.tileY, gather.tileX, gather.tileY) > 1) { clearGather(world.ecs, handle); continue; } const block = blockAt(world, gather.tileX, gather.tileY); if (gather.kind === "mining") { if (!block || block.typeId !== BlockType.boulder || materialFromOreBoulderState(block.state) !== gather.materialId) { clearGather(world.ecs, handle); continue; } } else if (gather.kind === "woodcutting") { if (!block || block.typeId !== gather.typeId || !isChopableTreeBlock(block)) { clearGather(world.ecs, handle); continue; } } else if (gather.kind === "plant") { if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block)) { clearGather(world.ecs, handle); continue; } } else { clearGather(world.ecs, handle); continue; } if (now >= gather.nextSwingAt && now < gather.finishesAt) { gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS; events.push({ type: "gather-swing", attackerId: entityId, tileX: gather.tileX, tileY: gather.tileY, fromTileX: position.tileX, fromTileY: position.tileY, toolItemId: gather.toolItemId ?? null, swipe: false }); } if (now < gather.finishesAt) { continue; } if (gather.kind === "mining") { completeMining(world, handle, entityId, character, gather, events, privates, now); } else if (gather.kind === "woodcutting") { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); } else { completePlant(world, handle, entityId, character, gather, events, privates, now); } } return { events, privates }; } export function handleGatherCommand (world, sessionId, command, now) { switch (command.type) { case "mine": return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); case "chop": return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); case "pick": return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now); case "cancel-gather": { const entityId = world.characterEntities.get(command.characterId); if (entityId == null) { return { events: [] }; } const handle = world.ecs.handleOf(entityId); clearGather(world.ecs, handle); return { events: [] }; } default: return null; } } function defaultPlantState (typeId) { if (typeId === BlockType.herbPlant) { return "mint"; } return "cotton-plant"; }