BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

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