BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

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