BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

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