BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

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