BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

service.js 31.2 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType, woodTierForTreeBlock, isChopableTreeBlock, plantGatherForBlock } from "../../../shared/definitions/tiles.js";
3import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4import { SkillId } from "../../../shared/definitions/skills.js";
5import {
6 materialFromOreBoulderState,
7 oreItemIdForMaterial,
8 miningDurationMs,
9 miningXpForMaterial,
10 oreExhaustDurationMs,
11 oreBoulderState,
12 EXHAUSTED_ORE_BOULDER_STATE,
13 resolveMiningPickaxe,
14 resolveWoodcuttingAxe,
15 resolvePlantClippers,
16 resolveHerbGather,
17 woodcuttingDurationMs,
18 woodcuttingXpForWood,
19 treeExhaustDurationMs,
20 logItemIdForWoodTier,
21 herbalismDurationMs,
22 herbalismXpForPick,
23 PLANT_EXHAUST_MS
24} from "../../../shared/definitions/gathering.js";
25import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
26import { ClothTier } from "../../../shared/definitions/materialTiers.js";
27import {
28 flowerItemInstance,
29 flowerColorIdFromBlockState,
30 flowerBlockState,
31 flowerColorIdForTile,
32 randomFlowerColorId
33} from "../../../shared/definitions/dyes.js";
34import { herbDefinition, isHerbId } from "../../../shared/definitions/herbs.js";
35import { insertStack, stackQuantity } from "../../../shared/items/inventory.js";
36import { attachOrigins, GatherOriginVerb, gatherOrigin, craftOrigin, CraftOriginVerb } from "../../../shared/items/origin.js";
37import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
38import
39{
40 gatherDurationMultiplier,
41 harvestYieldMultiplier
42} from "../../../shared/equipment/jewelryEffects.js";
43import {
44 seasonIdAt,
45 treeStumpStateForSeason,
46 SeasonId,
47 scaleRegrowDurationMs
48} from "../../../shared/world/season.js";
49import { bagView, addGroundItem, publicGroundItem } from "../items/bags.js";
50import { clearEngage } from "../combat/service.js";
51import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
52import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
53import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
54import {
55 barkItemIdForWood,
56 debarkedLogInstance,
57 isLogDebarked
58} from "../../../shared/definitions/woodItems.js";
59import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js";
60
61const GATHER_SWING_INTERVAL_MS = 900;
62/** Fixed strip duration — short axe work on a felled log. */
63export const DEBARK_DURATION_MS = 2000;
64
65function userError (message)
66{
67 const error = new Error(message);
68 error.userFacing = true;
69 return error;
70}
71
72function characterDisplayName (world, handle)
73{
74 const appearance = world.ecs.get(handle, Component.appearance);
75 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
76 return name || "someone";
77}
78
79function ensureOreRespawns (world)
80{
81 if (!world.oreRespawns)
82 { world.oreRespawns = new Map(); }
83 return world.oreRespawns;
84}
85
86function ensureTreeRespawns (world)
87{
88 if (!world.treeRespawns)
89 { world.treeRespawns = new Map(); }
90 return world.treeRespawns;
91}
92
93function ensurePlantRespawns (world)
94{
95 if (!world.plantRespawns)
96 { world.plantRespawns = new Map(); }
97 return world.plantRespawns;
98}
99
100function blockAt (world, tileX, tileY)
101{
102 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
103 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
104}
105
106function setBlockState (world, tileX, tileY, typeId, state)
107{
108 const chunkX = tileToChunk(tileX);
109 const chunkY = tileToChunk(tileY);
110 const localX = tileToLocal(tileX);
111 const localY = tileToLocal(tileY);
112 const data = world.chunkData(chunkX, chunkY);
113 const index = localY * CHUNK_SIZE + localX;
114 const prev = data?.blocks?.[index];
115 if (!prev || prev.typeId !== typeId)
116 { return null; }
117 const block = { typeId: prev.typeId, state, config: prev.config ?? null };
118 data.blocks[index] = block;
119 return {
120 type: "chunk-delta",
121 chunkX,
122 chunkY,
123 tileX,
124 tileY,
125 localX,
126 localY,
127 block
128 };
129}
130
131function setBoulderState (world, tileX, tileY, state)
132{
133 return setBlockState(world, tileX, tileY, BlockType.boulder, state);
134}
135
136function setTreeState (world, tileX, tileY, typeId, state)
137{
138 return setBlockState(world, tileX, tileY, typeId, state);
139}
140
141function clearBlock (world, tileX, tileY, typeId)
142{
143 const chunkX = tileToChunk(tileX);
144 const chunkY = tileToChunk(tileY);
145 const localX = tileToLocal(tileX);
146 const localY = tileToLocal(tileY);
147 const data = world.chunkData(chunkX, chunkY);
148 const index = localY * CHUNK_SIZE + localX;
149 const prev = data?.blocks?.[index];
150 if (!prev || prev.typeId !== typeId)
151 { return null; }
152 data.blocks[index] = null;
153 return {
154 type: "chunk-delta",
155 chunkX,
156 chunkY,
157 tileX,
158 tileY,
159 localX,
160 localY,
161 block: null
162 };
163}
164
165function placeBlock (world, tileX, tileY, typeId, state)
166{
167 const chunkX = tileToChunk(tileX);
168 const chunkY = tileToChunk(tileY);
169 const localX = tileToLocal(tileX);
170 const localY = tileToLocal(tileY);
171 const data = world.chunkData(chunkX, chunkY);
172 const index = localY * CHUNK_SIZE + localX;
173 const block = { typeId, state, config: null };
174 data.blocks[index] = block;
175 return {
176 type: "chunk-delta",
177 chunkX,
178 chunkY,
179 tileX,
180 tileY,
181 localX,
182 localY,
183 block
184 };
185}
186
187function pickaxeForOre (world, handle, materialId)
188{
189 const inventory = world.ecs.get(handle, Component.inventory);
190 const equipment = world.ecs.get(handle, Component.equipment);
191 const skills = world.ecs.get(handle, Component.skills);
192 return resolveMiningPickaxe({
193 inventorySlots: inventory?.slots,
194 equipmentSlots: equipment?.slots,
195 skills,
196 materialId
197 });
198}
199
200function axeForWood (world, handle, woodTier)
201{
202 const inventory = world.ecs.get(handle, Component.inventory);
203 const equipment = world.ecs.get(handle, Component.equipment);
204 const skills = world.ecs.get(handle, Component.skills);
205 return resolveWoodcuttingAxe({
206 inventorySlots: inventory?.slots,
207 equipmentSlots: equipment?.slots,
208 skills,
209 woodTier
210 });
211}
212
213function clearGather (ecs, handle)
214{
215 if (ecs.has(handle, Component.gather))
216 { ecs.remove(handle, Component.gather); }
217}
218
219export function cancelGather (ecs, handle)
220{
221 clearGather(ecs, handle);
222}
223
224/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
225export function clearOreRespawnsForChunk (world, chunkX, chunkY)
226{
227 const respawns = world.oreRespawns;
228 if (!respawns?.size)
229 { return; }
230 for (const key of [...respawns.keys()])
231 {
232 const [tileX, tileY] = key.split(",").map(Number);
233 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
234 { respawns.delete(key); }
235 }
236}
237
238/** Drop scheduled tree respawns when authored chunk data is replaced or unloaded. */
239export function clearTreeRespawnsForChunk (world, chunkX, chunkY)
240{
241 const respawns = world.treeRespawns;
242 if (!respawns?.size)
243 { return; }
244 for (const key of [...respawns.keys()])
245 {
246 const [tileX, tileY] = key.split(",").map(Number);
247 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
248 { respawns.delete(key); }
249 }
250}
251
252export function clearPlantRespawnsForChunk (world, chunkX, chunkY)
253{
254 const respawns = world.plantRespawns;
255 if (!respawns?.size)
256 { return; }
257 for (const key of [...respawns.keys()])
258 {
259 const [tileX, tileY] = key.split(",").map(Number);
260 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
261 { respawns.delete(key); }
262 }
263}
264
265/**
266 * Restore exhausted ore boulders whose timers have elapsed.
267 */
268export function stepOreRespawns (world, now)
269{
270 const respawns = world.oreRespawns;
271 if (!respawns?.size)
272 { return { events: [] }; }
273 const events = [];
274 for (const [key, entry] of [...respawns.entries()])
275 {
276 if (now < entry.respawnsAt)
277 { continue; }
278 respawns.delete(key);
279 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));
280 if (delta)
281 { events.push(delta); }
282 }
283 return { events };
284}
285
286/**
287 * Restore exhausted trees whose timers have elapsed (live seasonal look).
288 */
289export function stepTreeRespawns (world, now)
290{
291 const respawns = world.treeRespawns;
292 if (!respawns?.size)
293 { return { events: [] }; }
294 const events = [];
295 for (const [key, entry] of [...respawns.entries()])
296 {
297 if (now < entry.respawnsAt)
298 { continue; }
299 respawns.delete(key);
300 const delta = setTreeState(
301 world,
302 entry.tileX,
303 entry.tileY,
304 entry.typeId,
305 SeasonId.summer
306 );
307 if (delta)
308 { events.push(delta); }
309 }
310 return { events };
311}
312
313export function stepPlantRespawns (world, now)
314{
315 const respawns = world.plantRespawns;
316 if (!respawns?.size)
317 { return { events: [] }; }
318 const events = [];
319 for (const [key, entry] of [...respawns.entries()])
320 {
321 if (now < entry.respawnsAt)
322 { continue; }
323 respawns.delete(key);
324 const existing = blockAt(world, entry.tileX, entry.tileY);
325 if (existing)
326 { continue; }
327 const state = entry.typeId === BlockType.flower
328 ? flowerBlockState(randomFlowerColorId())
329 : (entry.state ?? defaultPlantState(entry.typeId));
330 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);
331 if (delta)
332 { events.push(delta); }
333 }
334 return { events };
335}
336
337function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
338{
339 clearEngage(world.ecs, entityId);
340 const path = world.ecs.get(handle, Component.path);
341 if (path)
342 { path.tiles = []; }
343 world.ecs.add(handle, Component.gather, {
344 ...gatherFields,
345 startedAt: now,
346 finishesAt: now + gatherFields.durationMs,
347 nextSwingAt: now
348 });
349 return {
350 events: [{
351 type: "gather-swing",
352 attackerId: entityId,
353 tileX: gatherFields.tileX,
354 tileY: gatherFields.tileY,
355 fromTileX: position.tileX,
356 fromTileY: position.tileY,
357 toolItemId: gatherFields.toolItemId ?? null,
358 swipe: false
359 }]
360 };
361}
362
363/**
364 * Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.
365 */
366export function startMine (world, sessionId, characterId, tileX, tileY, now)
367{
368 const entityId = world.characterEntities.get(characterId);
369 if (entityId == null)
370 { throw userError("Character is not in the world."); }
371 const handle = world.ecs.handleOf(entityId);
372 const identity = world.ecs.get(handle, Component.networkIdentity);
373 if (!identity || identity.sessionId !== sessionId)
374 { throw userError("Character is not in the world."); }
375 if (world.ecs.has(handle, Component.dead))
376 { throw userError("You are dead."); }
377
378 const position = world.ecs.get(handle, Component.position);
379 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
380 { throw userError("You need to stand next to the rock."); }
381
382 const block = blockAt(world, tileX, tileY);
383 if (!block || block.typeId !== BlockType.boulder)
384 { throw userError("There is nothing to mine there."); }
385 const materialId = materialFromOreBoulderState(block.state);
386 if (!materialId)
387 {
388 throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE
389 ? "That rock is exhausted."
390 : "That rock has no ore.");
391 }
392
393 const pickaxe = pickaxeForOre(world, handle, materialId);
394 if (!pickaxe.ok)
395 { throw userError(pickaxe.reason); }
396
397 const durationMs = Math.max(
398 1,
399 Math.floor(miningDurationMs(materialId, pickaxe.tool.tier)
400 * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment)))
401 );
402 const toolItemId = pickaxe.tool.stack?.itemId ?? null;
403 return beginGatherSwing(world, handle, entityId, position, {
404 kind: "mining",
405 tileX,
406 tileY,
407 materialId,
408 toolTier: pickaxe.tool.tier,
409 toolItemId,
410 durationMs
411 }, now);
412}
413
414/**
415 * Start chopping a tree. Completes via stepGather (stump + log + woodcutting XP).
416 */
417export function startChop (world, sessionId, characterId, tileX, tileY, now)
418{
419 const entityId = world.characterEntities.get(characterId);
420 if (entityId == null)
421 { throw userError("Character is not in the world."); }
422 const handle = world.ecs.handleOf(entityId);
423 const identity = world.ecs.get(handle, Component.networkIdentity);
424 if (!identity || identity.sessionId !== sessionId)
425 { throw userError("Character is not in the world."); }
426 if (world.ecs.has(handle, Component.dead))
427 { throw userError("You are dead."); }
428
429 const position = world.ecs.get(handle, Component.position);
430 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
431 { throw userError("You need to stand next to the tree."); }
432
433 const block = blockAt(world, tileX, tileY);
434 if (!isChopableTreeBlock(block))
435 {
436 throw userError(block && woodTierForTreeBlock(block.typeId) != null
437 ? "That tree is already felled."
438 : "There is nothing to chop there.");
439 }
440 const woodTier = woodTierForTreeBlock(block.typeId);
441 const axe = axeForWood(world, handle, woodTier);
442 if (!axe.ok)
443 { throw userError(axe.reason); }
444
445 const durationMs = Math.max(
446 1,
447 Math.floor(woodcuttingDurationMs(woodTier, axe.tool.tier)
448 * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment)))
449 );
450 const toolItemId = axe.tool.stack?.itemId ?? null;
451 return beginGatherSwing(world, handle, entityId, position, {
452 kind: "woodcutting",
453 tileX,
454 tileY,
455 typeId: block.typeId,
456 woodTier,
457 toolTier: axe.tool.tier,
458 toolItemId,
459 durationMs
460 }, now);
461}
462
463function woodTierFromLogItemId (itemId)
464{
465 const def = itemDefinition(itemId);
466 if (!def || def.familyId !== ItemFamilyId.log)
467 { return null; }
468 return def.tier ?? null;
469}
470
471function nearDebarkTarget (position, tileX, tileY)
472{
473 return isAdjacentTile(position.tileX, position.tileY, tileX, tileY)
474 || (position.tileX === tileX && position.tileY === tileY);
475}
476
477function publishGroundItem (item)
478{
479 return {
480 type: "ground-item-appear",
481 ...publicGroundItem(item),
482 stack: item.stack,
483 droppedAt: item.droppedAt,
484 source: item.source,
485 droppedByCharacterId: item.droppedByCharacterId,
486 expiresAt: item.expiresAt
487 };
488}
489
490/**
491 * Start stripping bark from a ground log (2s axe swings, then bark + debarked flag).
492 */
493export function startDebark (world, sessionId, characterId, groundItemId, now)
494{
495 const entityId = world.characterEntities.get(characterId);
496 if (entityId == null)
497 { throw userError("Character is not in the world."); }
498 const handle = world.ecs.handleOf(entityId);
499 const identity = world.ecs.get(handle, Component.networkIdentity);
500 if (!identity || identity.sessionId !== sessionId)
501 { throw userError("Character is not in the world."); }
502 if (world.ecs.has(handle, Component.dead))
503 { throw userError("You are dead."); }
504
505 const item = world.groundItems.get(groundItemId);
506 if (!item?.stack)
507 { throw userError("That item is no longer on the ground."); }
508
509 const woodTier = woodTierFromLogItemId(item.stack.itemId);
510 if (!woodTier)
511 { throw userError("That is not a log."); }
512 if (isLogDebarked(item.stack))
513 { throw userError("That log is already stripped of bark."); }
514
515 const position = world.ecs.get(handle, Component.position);
516 if (!nearDebarkTarget(position, item.tileX, item.tileY))
517 { throw userError("Stand next to the log."); }
518
519 const axe = axeForWood(world, handle, woodTier);
520 if (!axe.ok)
521 { throw userError(axe.reason || "You need an axe to strip this bark."); }
522
523 const barkId = barkItemIdForWood(woodTier);
524 if (barkId == null)
525 { throw userError("That bark cannot be stripped."); }
526
527 const toolItemId = axe.tool.stack?.itemId ?? null;
528 return beginGatherSwing(world, handle, entityId, position, {
529 kind: "debark",
530 tileX: item.tileX,
531 tileY: item.tileY,
532 groundItemId,
533 woodTier,
534 logItemId: item.stack.itemId,
535 barkItemId: barkId,
536 toolTier: axe.tool.tier,
537 toolItemId,
538 durationMs: DEBARK_DURATION_MS
539 }, now);
540}
541
542/**
543 * Pick a plant node (flower / cotton; no tools required).
544 */
545export function startPick (world, sessionId, characterId, tileX, tileY, now)
546{
547 const entityId = world.characterEntities.get(characterId);
548 if (entityId == null)
549 { throw userError("Character is not in the world."); }
550 const handle = world.ecs.handleOf(entityId);
551 const identity = world.ecs.get(handle, Component.networkIdentity);
552 if (!identity || identity.sessionId !== sessionId)
553 { throw userError("Character is not in the world."); }
554 if (world.ecs.has(handle, Component.dead))
555 { throw userError("You are dead."); }
556
557 const position = world.ecs.get(handle, Component.position);
558 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
559 { throw userError("You need to stand next to the plant."); }
560
561 const block = blockAt(world, tileX, tileY);
562 const plant = plantGatherForBlock(block);
563 if (!plant)
564 { throw userError("There is nothing to pick there."); }
565
566 const inventory = world.ecs.get(handle, Component.inventory);
567 const equipment = world.ecs.get(handle, Component.equipment);
568 const skills = world.ecs.get(handle, Component.skills);
569 const clippers = resolvePlantClippers({
570 inventorySlots: inventory?.slots,
571 equipmentSlots: equipment?.slots,
572 skills,
573 requireTool: !!plant.requiresClippers,
574 minClothTier: plant.minClothTier ?? null
575 });
576 if (!clippers.ok)
577 { throw userError(clippers.reason); }
578
579 let herbId = null;
580 let herbTier = null;
581 if (plant.kind === "herb")
582 {
583 const gate = resolveHerbGather({ herbId: block.state, skills });
584 if (!gate.ok)
585 { throw userError(gate.reason); }
586 herbId = gate.herb.herbId;
587 herbTier = gate.herb.tier;
588 }
589
590 const toolTier = clippers.tool?.tier ?? null;
591 const durationMs = Math.max(
592 1,
593 Math.floor(herbalismDurationMs(plant.kind, toolTier, herbTier)
594 * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment)))
595 );
596 const toolItemId = clippers.tool?.stack?.itemId ?? null;
597 const prefixEvents = [];
598 let flowerColorId = null;
599 if (plant.kind === "flower")
600 {
601 flowerColorId = flowerColorIdFromBlockState(block.state);
602 if (!flowerColorId)
603 {
604 // Legacy / uncoloured placements: lock a colour before the pick starts.
605 flowerColorId = flowerColorIdForTile(tileX, tileY);
606 const delta = setBlockState(
607 world,
608 tileX,
609 tileY,
610 BlockType.flower,
611 flowerBlockState(flowerColorId)
612 );
613 if (delta)
614 { prefixEvents.push(delta); }
615 }
616 }
617 const started = beginGatherSwing(world, handle, entityId, position, {
618 kind: "plant",
619 plantKind: plant.kind,
620 herbId,
621 herbTier,
622 tileX,
623 tileY,
624 typeId: block.typeId,
625 flowerColorId,
626 toolTier,
627 toolItemId,
628 durationMs
629 }, now);
630 return {
631 ...started,
632 events: [...prefixEvents, ...(started.events ?? [])]
633 };
634}
635
636function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])
637{
638 privates.push({
639 characterId: character.characterId,
640 bag: bagView(world.ecs, handle)
641 });
642 if (skillsChanged)
643 {
644 events.push({
645 type: "skills-updated",
646 entityId,
647 characterId: character.characterId,
648 ...publicSkillsPayload(skills),
649 stored: storedSkillXp(skills),
650 levelUps
651 });
652 }
653}
654
655function completeMining (world, handle, entityId, character, gather, events, privates, now)
656{
657 const oreItemId = oreItemIdForMaterial(gather.materialId);
658 const def = itemDefinition(oreItemId);
659 const inventory = world.ecs.get(handle, Component.inventory);
660 if (!oreItemId || !def || !inventory)
661 {
662 clearGather(world.ecs, handle);
663 return;
664 }
665 const origin = gatherOrigin(GatherOriginVerb.mined, characterDisplayName(world, handle));
666 const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment))));
667 const stack = attachOrigins({
668 itemId: oreItemId,
669 quantity,
670 origins: [{ origin, quantity }]
671 });
672 const inserted = insertStack(inventory.slots, stack, def);
673 if (!inserted.ok || inserted.remainder > 0)
674 {
675 clearGather(world.ecs, handle);
676 events.push({
677 type: "command-error",
678 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
679 message: "Your inventory is full."
680 });
681 return;
682 }
683 inventory.slots = inserted.slots;
684
685 const skills = world.ecs.get(handle, Component.skills);
686 let skillsChanged = false;
687 const levelUps = [];
688 if (skills?.xp)
689 {
690 const result = applySkillXp(
691 skills,
692 SkillId.mining,
693 miningXpForMaterial(gather.materialId),
694 world.ecs.get(handle, Component.equipment)
695 );
696 if (result.changed)
697 { skillsChanged = true; }
698 if (result.levelUp)
699 { levelUps.push(result.levelUp); }
700 }
701
702 const exhausted = setBoulderState(
703 world,
704 gather.tileX,
705 gather.tileY,
706 EXHAUSTED_ORE_BOULDER_STATE
707 );
708 if (exhausted)
709 {
710 events.push(exhausted);
711 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
712 tileX: gather.tileX,
713 tileY: gather.tileY,
714 materialId: gather.materialId,
715 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
716 });
717 }
718
719 clearGather(world.ecs, handle);
720 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
721 events.push({
722 type: "gather-complete",
723 characterId: character.characterId,
724 kind: "mining",
725 materialId: gather.materialId,
726 itemId: oreItemId
727 });
728}
729
730function completeWoodcutting (world, handle, entityId, character, gather, events, privates, now)
731{
732 const logItemId = logItemIdForWoodTier(gather.woodTier);
733 const def = itemDefinition(logItemId);
734 const inventory = world.ecs.get(handle, Component.inventory);
735 if (!logItemId || !def || !inventory)
736 {
737 clearGather(world.ecs, handle);
738 return;
739 }
740 const origin = gatherOrigin(GatherOriginVerb.felled, characterDisplayName(world, handle));
741 const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment))));
742 const stack = attachOrigins({
743 itemId: logItemId,
744 quantity,
745 origins: [{ origin, quantity }]
746 });
747 const inserted = insertStack(inventory.slots, stack, def);
748 if (!inserted.ok || inserted.remainder > 0)
749 {
750 clearGather(world.ecs, handle);
751 events.push({
752 type: "command-error",
753 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
754 message: "Your inventory is full."
755 });
756 return;
757 }
758 inventory.slots = inserted.slots;
759
760 const skills = world.ecs.get(handle, Component.skills);
761 let skillsChanged = false;
762 const levelUps = [];
763 if (skills?.xp)
764 {
765 const result = applySkillXp(
766 skills,
767 SkillId.woodcutting,
768 woodcuttingXpForWood(gather.woodTier),
769 world.ecs.get(handle, Component.equipment)
770 );
771 if (result.changed)
772 { skillsChanged = true; }
773 if (result.levelUp)
774 { levelUps.push(result.levelUp); }
775 }
776
777 const stumpState = treeStumpStateForSeason(seasonIdAt(now));
778 const exhausted = setTreeState(
779 world,
780 gather.tileX,
781 gather.tileY,
782 gather.typeId,
783 stumpState
784 );
785 if (exhausted)
786 {
787 events.push(exhausted);
788 ensureTreeRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
789 tileX: gather.tileX,
790 tileY: gather.tileY,
791 typeId: gather.typeId,
792 woodTier: gather.woodTier,
793 respawnsAt: now + scaleRegrowDurationMs(treeExhaustDurationMs(gather.woodTier), now)
794 });
795 }
796
797 clearGather(world.ecs, handle);
798 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
799 events.push({
800 type: "gather-complete",
801 characterId: character.characterId,
802 kind: "woodcutting",
803 woodTier: gather.woodTier,
804 itemId: logItemId
805 });
806}
807
808function completeDebark (world, handle, entityId, character, gather, events, privates, now)
809{
810 const item = world.groundItems.get(gather.groundItemId);
811 if (!item?.stack
812 || (item.stack.itemId | 0) !== (gather.logItemId | 0)
813 || isLogDebarked(item.stack)
814 || item.tileX !== gather.tileX
815 || item.tileY !== gather.tileY)
816 {
817 clearGather(world.ecs, handle);
818 return;
819 }
820
821 const qty = stackQuantity(item.stack.quantity);
822 if (qty <= 0)
823 {
824 clearGather(world.ecs, handle);
825 return;
826 }
827
828 const origin = craftOrigin(CraftOriginVerb.made, characterDisplayName(world, handle));
829 const debarkedStack = attachOrigins({
830 itemId: item.stack.itemId,
831 quantity: 1,
832 instance: debarkedLogInstance(),
833 origins: item.stack.origins ?? []
834 });
835 const despawnMs = world.settings.groundItemDespawnDurationMs ?? 600_000;
836
837 if (qty === 1)
838 {
839 item.stack = debarkedStack;
840 events.push(publishGroundItem(item));
841 }
842 else
843 {
844 item.stack = {
845 ...item.stack,
846 quantity: qty - 1
847 };
848 events.push(publishGroundItem(item));
849
850 const debarkedItem = {
851 groundItemId: (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1),
852 tileX: item.tileX,
853 tileY: item.tileY,
854 stack: debarkedStack,
855 droppedAt: now,
856 expiresAt: now + despawnMs,
857 source: "debark",
858 droppedByCharacterId: character.characterId
859 };
860 addGroundItem(world, debarkedItem);
861 events.push(publishGroundItem(debarkedItem));
862 }
863
864 const barkItem = {
865 groundItemId: (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1),
866 tileX: item.tileX,
867 tileY: item.tileY,
868 stack: attachOrigins({
869 itemId: gather.barkItemId,
870 quantity: 1,
871 origins: [{ origin, quantity: 1 }]
872 }),
873 droppedAt: now,
874 expiresAt: now + despawnMs,
875 source: "debark",
876 droppedByCharacterId: character.characterId
877 };
878 addGroundItem(world, barkItem);
879 events.push(publishGroundItem(barkItem));
880
881 clearGather(world.ecs, handle);
882 pushBagUpdate(events, privates, world, handle, entityId, character, false, null, []);
883 events.push({
884 type: "gather-complete",
885 characterId: character.characterId,
886 kind: "debark",
887 woodTier: gather.woodTier,
888 itemId: gather.barkItemId
889 });
890}
891
892function completePlant (world, handle, entityId, character, gather, events, privates, now)
893{
894 const inventory = world.ecs.get(handle, Component.inventory);
895 if (!inventory)
896 {
897 clearGather(world.ecs, handle);
898 return;
899 }
900
901 let itemId = null;
902 let instance = null;
903 if (gather.plantKind === "flower")
904 {
905 itemId = ItemId.flower;
906 const live = blockAt(world, gather.tileX, gather.tileY);
907 const colorId = gather.flowerColorId
908 ?? flowerColorIdFromBlockState(live?.state)
909 ?? randomFlowerColorId();
910 instance = flowerItemInstance(colorId);
911 }
912 else if (gather.plantKind === "cotton")
913 {
914 itemId = rawClothItemId(ClothTier.cotton);
915 }
916 else if (gather.plantKind === "flax")
917 {
918 itemId = rawClothItemId(ClothTier.linen);
919 }
920 else if (gather.plantKind === "silk")
921 {
922 itemId = rawClothItemId(ClothTier.silk);
923 }
924 else if (gather.plantKind === "herb")
925 {
926 const herb = herbDefinition(gather.herbId);
927 itemId = herb?.itemId ?? null;
928 }
929 else
930 {
931 clearGather(world.ecs, handle);
932 return;
933 }
934
935 const def = itemDefinition(itemId);
936 if (!def)
937 {
938 clearGather(world.ecs, handle);
939 return;
940 }
941
942 const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle));
943 const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment))));
944 const stack = attachOrigins({
945 itemId,
946 quantity,
947 instance,
948 origins: [{ origin, quantity }]
949 });
950 const inserted = insertStack(inventory.slots, stack, def);
951 if (!inserted.ok || inserted.remainder > 0)
952 {
953 clearGather(world.ecs, handle);
954 events.push({
955 type: "command-error",
956 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
957 message: "Your inventory is full."
958 });
959 return;
960 }
961 inventory.slots = inserted.slots;
962
963 const skills = world.ecs.get(handle, Component.skills);
964 let skillsChanged = false;
965 const levelUps = [];
966 if (skills?.xp)
967 {
968 const result = applySkillXp(
969 skills,
970 SkillId.herbalism,
971 herbalismXpForPick(gather.plantKind, gather.herbTier),
972 world.ecs.get(handle, Component.equipment)
973 );
974 if (result.changed)
975 { skillsChanged = true; }
976 if (result.levelUp)
977 { levelUps.push(result.levelUp); }
978 }
979
980 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId);
981 if (delta)
982 { events.push(delta); }
983 ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
984 tileX: gather.tileX,
985 tileY: gather.tileY,
986 typeId: gather.typeId,
987 // Colour is chosen when the node refreshes (see stepPlantRespawns).
988 state: gather.plantKind === "flower"
989 ? null
990 : (gather.plantKind === "herb" && isHerbId(gather.herbId)
991 ? gather.herbId
992 : defaultPlantState(gather.typeId)),
993 respawnsAt: now + scaleRegrowDurationMs(PLANT_EXHAUST_MS, now)
994 });
995
996 clearGather(world.ecs, handle);
997 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
998 events.push({
999 type: "gather-complete",
1000 characterId: character.characterId,
1001 kind: "plant",
1002 plantKind: gather.plantKind,
1003 itemId
1004 });
1005}
1006
1007export function stepGather (world, now)
1008{
1009 const events = [];
1010 const privates = [];
1011 events.push(...stepOreRespawns(world, now).events);
1012 events.push(...stepTreeRespawns(world, now).events);
1013 events.push(...stepPlantRespawns(world, now).events);
1014
1015 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
1016 {
1017 const { handle, gather, position, character, entityId } = entity;
1018 if (world.ecs.has(handle, Component.dead))
1019 {
1020 clearGather(world.ecs, handle);
1021 continue;
1022 }
1023 const nearTarget = gather.kind === "debark"
1024 ? nearDebarkTarget(position, gather.tileX, gather.tileY)
1025 : isAdjacentTile(position.tileX, position.tileY, gather.tileX, gather.tileY);
1026 if (!nearTarget)
1027 {
1028 clearGather(world.ecs, handle);
1029 continue;
1030 }
1031 const block = blockAt(world, gather.tileX, gather.tileY);
1032
1033 if (gather.kind === "mining")
1034 {
1035 if (!block || block.typeId !== BlockType.boulder
1036 || materialFromOreBoulderState(block.state) !== gather.materialId)
1037 {
1038 clearGather(world.ecs, handle);
1039 continue;
1040 }
1041 }
1042 else if (gather.kind === "woodcutting")
1043 {
1044 if (!block || block.typeId !== gather.typeId || !isChopableTreeBlock(block))
1045 {
1046 clearGather(world.ecs, handle);
1047 continue;
1048 }
1049 }
1050 else if (gather.kind === "plant")
1051 {
1052 if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block))
1053 {
1054 clearGather(world.ecs, handle);
1055 continue;
1056 }
1057 }
1058 else if (gather.kind === "debark")
1059 {
1060 const item = world.groundItems.get(gather.groundItemId);
1061 if (!item?.stack
1062 || (item.stack.itemId | 0) !== (gather.logItemId | 0)
1063 || isLogDebarked(item.stack)
1064 || item.tileX !== gather.tileX
1065 || item.tileY !== gather.tileY)
1066 {
1067 clearGather(world.ecs, handle);
1068 continue;
1069 }
1070 }
1071 else
1072 {
1073 clearGather(world.ecs, handle);
1074 continue;
1075 }
1076
1077 if (now >= gather.nextSwingAt && now < gather.finishesAt)
1078 {
1079 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
1080 events.push({
1081 type: "gather-swing",
1082 attackerId: entityId,
1083 tileX: gather.tileX,
1084 tileY: gather.tileY,
1085 fromTileX: position.tileX,
1086 fromTileY: position.tileY,
1087 toolItemId: gather.toolItemId ?? null,
1088 swipe: false
1089 });
1090 }
1091
1092 if (now < gather.finishesAt)
1093 { continue; }
1094
1095 if (gather.kind === "mining")
1096 { completeMining(world, handle, entityId, character, gather, events, privates, now); }
1097 else if (gather.kind === "woodcutting")
1098 { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
1099 else if (gather.kind === "debark")
1100 { completeDebark(world, handle, entityId, character, gather, events, privates, now); }
1101 else
1102 { completePlant(world, handle, entityId, character, gather, events, privates, now); }
1103 }
1104 return { events, privates };
1105}
1106
1107export function handleGatherCommand (world, sessionId, command, now)
1108{
1109 switch (command.type)
1110 {
1111 case "mine":
1112 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1113 case "chop":
1114 return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1115 case "pick":
1116 return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1117 case "debark-log":
1118 return startDebark(world, sessionId, command.characterId, command.groundItemId | 0, now);
1119 case "cancel-gather":
1120 {
1121 const entityId = world.characterEntities.get(command.characterId);
1122 if (entityId == null)
1123 { return { events: [] }; }
1124 const handle = world.ecs.handleOf(entityId);
1125 clearGather(world.ecs, handle);
1126 return { events: [] };
1127 }
1128 default:
1129 return null;
1130 }
1131}
1132
1133function defaultPlantState (typeId)
1134{
1135 if (typeId === BlockType.herbPlant)
1136 { return "mint"; }
1137 if (typeId === BlockType.flaxPlant)
1138 { return "flax-plant"; }
1139 if (typeId === BlockType.silkCocoon)
1140 { return "silk-cocoon"; }
1141 return "cotton-plant";
1142}