BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

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