BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

service.js 31.6 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, removeGroundItem } 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 const tileX = item.tileX;
846 const tileY = item.tileY;
847 let reuseGroundItemId = null;
848
849 if (qty === 1)
850 {
851 reuseGroundItemId = item.groundItemId;
852 removeGroundItem(world, item.groundItemId);
853 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
854 }
855 else
856 {
857 item.stack = {
858 itemId: item.stack.itemId,
859 quantity: qty - 1,
860 instance: item.stack.instance ?? null,
861 origins: split.remain
862 };
863 events.push(publishGroundItem(item));
864 }
865
866 const placedDebarked = placeOrMergeGroundStack(world, {
867 tileX,
868 tileY,
869 stack: debarkedStack,
870 now,
871 source: "debark",
872 droppedByCharacterId: character.characterId,
873 groundItemId: reuseGroundItemId
874 });
875 events.push(...placedDebarked.events);
876
877 const placedBark = placeOrMergeGroundStack(world, {
878 tileX,
879 tileY,
880 stack: attachOrigins({
881 itemId: gather.barkItemId,
882 quantity: 1,
883 origins: [{ origin, quantity: 1 }]
884 }),
885 now,
886 source: "debark",
887 droppedByCharacterId: character.characterId
888 });
889 events.push(...placedBark.events);
890
891 const skills = world.ecs.get(handle, Component.skills);
892 let skillsChanged = false;
893 const levelUps = [];
894 if (skills?.xp)
895 {
896 const result = applySkillXp(
897 skills,
898 SkillId.woodworking,
899 woodworkingXpForDebark(gather.woodTier),
900 world.ecs.get(handle, Component.equipment)
901 );
902 if (result.changed)
903 { skillsChanged = true; }
904 if (result.levelUp)
905 { levelUps.push(result.levelUp); }
906 }
907
908 clearGather(world.ecs, handle);
909 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
910 events.push({
911 type: "gather-complete",
912 characterId: character.characterId,
913 kind: "debark",
914 woodTier: gather.woodTier,
915 itemId: gather.barkItemId
916 });
917}
918
919function completePlant (world, handle, entityId, character, gather, events, privates, now)
920{
921 const inventory = world.ecs.get(handle, Component.inventory);
922 if (!inventory)
923 {
924 clearGather(world.ecs, handle);
925 return;
926 }
927
928 let itemId = null;
929 let instance = null;
930 if (gather.plantKind === "flower")
931 {
932 itemId = ItemId.flower;
933 const live = blockAt(world, gather.tileX, gather.tileY);
934 const colorId = gather.flowerColorId
935 ?? flowerColorIdFromBlockState(live?.state)
936 ?? randomFlowerColorId();
937 instance = flowerItemInstance(colorId);
938 }
939 else if (gather.plantKind === "cotton")
940 {
941 itemId = rawClothItemId(ClothTier.cotton);
942 }
943 else if (gather.plantKind === "flax")
944 {
945 itemId = rawClothItemId(ClothTier.linen);
946 }
947 else if (gather.plantKind === "silk")
948 {
949 itemId = rawClothItemId(ClothTier.silk);
950 }
951 else if (gather.plantKind === "herb")
952 {
953 const herb = herbDefinition(gather.herbId);
954 itemId = herb?.itemId ?? null;
955 }
956 else
957 {
958 clearGather(world.ecs, handle);
959 return;
960 }
961
962 const def = itemDefinition(itemId);
963 if (!def)
964 {
965 clearGather(world.ecs, handle);
966 return;
967 }
968
969 const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle));
970 const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment))));
971 const stack = attachOrigins({
972 itemId,
973 quantity,
974 instance,
975 origins: [{ origin, quantity }]
976 });
977 const inserted = insertStack(inventory.slots, stack, def);
978 if (!inserted.ok || inserted.remainder > 0)
979 {
980 clearGather(world.ecs, handle);
981 events.push({
982 type: "command-error",
983 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
984 message: "Your inventory is full."
985 });
986 return;
987 }
988 inventory.slots = inserted.slots;
989
990 const skills = world.ecs.get(handle, Component.skills);
991 let skillsChanged = false;
992 const levelUps = [];
993 if (skills?.xp)
994 {
995 const result = applySkillXp(
996 skills,
997 SkillId.herbalism,
998 herbalismXpForPick(gather.plantKind, gather.herbTier),
999 world.ecs.get(handle, Component.equipment)
1000 );
1001 if (result.changed)
1002 { skillsChanged = true; }
1003 if (result.levelUp)
1004 { levelUps.push(result.levelUp); }
1005 }
1006
1007 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId);
1008 if (delta)
1009 { events.push(delta); }
1010 ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
1011 tileX: gather.tileX,
1012 tileY: gather.tileY,
1013 typeId: gather.typeId,
1014 // Colour is chosen when the node refreshes (see stepPlantRespawns).
1015 state: gather.plantKind === "flower"
1016 ? null
1017 : (gather.plantKind === "herb" && isHerbId(gather.herbId)
1018 ? gather.herbId
1019 : defaultPlantState(gather.typeId)),
1020 respawnsAt: now + scaleRegrowDurationMs(PLANT_EXHAUST_MS, now)
1021 });
1022
1023 clearGather(world.ecs, handle);
1024 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
1025 events.push({
1026 type: "gather-complete",
1027 characterId: character.characterId,
1028 kind: "plant",
1029 plantKind: gather.plantKind,
1030 itemId
1031 });
1032}
1033
1034export function stepGather (world, now)
1035{
1036 const events = [];
1037 const privates = [];
1038 events.push(...stepOreRespawns(world, now).events);
1039 events.push(...stepTreeRespawns(world, now).events);
1040 events.push(...stepPlantRespawns(world, now).events);
1041
1042 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
1043 {
1044 const { handle, gather, position, character, entityId } = entity;
1045 if (world.ecs.has(handle, Component.dead))
1046 {
1047 clearGather(world.ecs, handle);
1048 continue;
1049 }
1050 const nearTarget = gather.kind === "debark"
1051 ? nearDebarkTarget(position, gather.tileX, gather.tileY)
1052 : isAdjacentTile(position.tileX, position.tileY, gather.tileX, gather.tileY);
1053 if (!nearTarget)
1054 {
1055 clearGather(world.ecs, handle);
1056 continue;
1057 }
1058 const block = blockAt(world, gather.tileX, gather.tileY);
1059
1060 if (gather.kind === "mining")
1061 {
1062 if (!block || block.typeId !== BlockType.boulder
1063 || materialFromOreBoulderState(block.state) !== gather.materialId)
1064 {
1065 clearGather(world.ecs, handle);
1066 continue;
1067 }
1068 }
1069 else if (gather.kind === "woodcutting")
1070 {
1071 if (!block || block.typeId !== gather.typeId || !isChopableTreeBlock(block))
1072 {
1073 clearGather(world.ecs, handle);
1074 continue;
1075 }
1076 }
1077 else if (gather.kind === "plant")
1078 {
1079 if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block))
1080 {
1081 clearGather(world.ecs, handle);
1082 continue;
1083 }
1084 }
1085 else if (gather.kind === "debark")
1086 {
1087 const item = world.groundItems.get(gather.groundItemId);
1088 if (!item?.stack
1089 || (item.stack.itemId | 0) !== (gather.logItemId | 0)
1090 || isLogDebarked(item.stack)
1091 || item.tileX !== gather.tileX
1092 || item.tileY !== gather.tileY)
1093 {
1094 clearGather(world.ecs, handle);
1095 continue;
1096 }
1097 }
1098 else
1099 {
1100 clearGather(world.ecs, handle);
1101 continue;
1102 }
1103
1104 if (now >= gather.nextSwingAt && now < gather.finishesAt)
1105 {
1106 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
1107 events.push({
1108 type: "gather-swing",
1109 attackerId: entityId,
1110 tileX: gather.tileX,
1111 tileY: gather.tileY,
1112 fromTileX: position.tileX,
1113 fromTileY: position.tileY,
1114 toolItemId: gather.toolItemId ?? null,
1115 swipe: false
1116 });
1117 }
1118
1119 if (now < gather.finishesAt)
1120 { continue; }
1121
1122 if (gather.kind === "mining")
1123 { completeMining(world, handle, entityId, character, gather, events, privates, now); }
1124 else if (gather.kind === "woodcutting")
1125 { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
1126 else if (gather.kind === "debark")
1127 { completeDebark(world, handle, entityId, character, gather, events, privates, now); }
1128 else
1129 { completePlant(world, handle, entityId, character, gather, events, privates, now); }
1130 }
1131 return { events, privates };
1132}
1133
1134export function handleGatherCommand (world, sessionId, command, now)
1135{
1136 switch (command.type)
1137 {
1138 case "mine":
1139 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1140 case "chop":
1141 return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1142 case "pick":
1143 return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
1144 case "debark-log":
1145 return startDebark(world, sessionId, command.characterId, command.groundItemId | 0, now);
1146 case "cancel-gather":
1147 {
1148 const entityId = world.characterEntities.get(command.characterId);
1149 if (entityId == null)
1150 { return { events: [] }; }
1151 const handle = world.ecs.handleOf(entityId);
1152 clearGather(world.ecs, handle);
1153 return { events: [] };
1154 }
1155 default:
1156 return null;
1157 }
1158}
1159
1160function defaultPlantState (typeId)
1161{
1162 if (typeId === BlockType.herbPlant)
1163 { return "mint"; }
1164 if (typeId === BlockType.flaxPlant)
1165 { return "flax-plant"; }
1166 if (typeId === BlockType.silkCocoon)
1167 { return "silk-cocoon"; }
1168 return "cotton-plant";
1169}