BlueGit

timfa questward

Files

questward / server / src / fishing / service.js

service.js

service.js 17.4 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import {
3 BlockType,
4 GroundType,
5 isLiquidWaterGround,
6 normalizeGround
7} from "../../../shared/definitions/tiles.js";
8import {
9 FISH_SPECIES,
10 fishTierRankFromItemId,
11 fishingDifficulty,
12 fishingExhaustDurationMs,
13 baitItemIdForCloth,
14 BaitItemId,
15 normalizeFishingSpotConfig,
16 fishingPoleItemIdForWood,
17 woodTierFromFishingRodItemId
18} from "../../../shared/definitions/fishItems.js";
19import { resolveFishingTool } from "../../../shared/definitions/gathering.js";
20import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
21import {
22 ClothTier,
23 tierRank,
24 clothTierForWood
25} from "../../../shared/definitions/materialTiers.js";
26import { yarnItemId } from "../../../shared/definitions/clothItems.js";
27import { itemDefinition } from "../../../shared/definitions/items.js";
28import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
29import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
30import
31{
32 gatherDurationMultiplier,
33 harvestYieldMultiplier
34} from "../../../shared/equipment/jewelryEffects.js";
35import { rollSkill } from "../../../shared/combat/rolls.js";
36import {
37 insertStack,
38 stackQuantity,
39 takeMatchingFromSlots,
40 takeFromSlot
41} from "../../../shared/items/inventory.js";
42import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";
43import { placeOrMergeGroundStack, bagView } from "../items/bags.js";
44import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
45import { tileToChunk, tileToLocal } from "../world/coordinates.js";
46import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
47import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
48import { tileShoveEvent } from "../simulation/tileInteract.js";
49import { seasonIdAt } from "../../../shared/world/season.js";
50
51const FISH_ATTEMPT_MS = 3000;
52const FISH_SHOVE_MS = 1000;
53const MAX_FISH_ATTEMPTS = 3;
54/** Chance the fishing line snaps after a fully failed rod session. */
55const LINE_BREAK_CHANCE = 0.05;
56
57function userError (message)
58{
59 const error = new Error(message);
60 error.userFacing = true;
61 return error;
62}
63
64function tileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
65{
66 const dim = normalizeDimensionId(dimensionId);
67 return `${dim}:${tileX},${tileY}`;
68}
69
70function characterDisplayName (world, handle)
71{
72 const appearance = world.ecs.get(handle, Component.appearance);
73 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
74 return name || "someone";
75}
76
77function ensureFishSessions (world)
78{
79 if (!world.fishSessions)
80 { world.fishSessions = new Map(); }
81 return world.fishSessions;
82}
83
84function ensureFishSpotRespawns (world)
85{
86 if (!world.fishingSpotRespawns)
87 { world.fishingSpotRespawns = new Map(); }
88 return world.fishingSpotRespawns;
89}
90
91function clearFishSession (world, characterId)
92{
93 ensureFishSessions(world).delete(characterId);
94}
95
96function blockAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
97{
98 const dim = normalizeDimensionId(dimensionId);
99 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
100 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
101 return data.blocks[index] ?? null;
102}
103
104function groundAt (world, tileX, tileY, dimensionId = OVERWORLD_ID)
105{
106 const dim = normalizeDimensionId(dimensionId);
107 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
108 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
109 return normalizeGround(data.grounds[index]).typeId;
110}
111
112function setBlockState (world, tileX, tileY, state, dimensionId = OVERWORLD_ID)
113{
114 const dim = normalizeDimensionId(dimensionId);
115 const chunkX = tileToChunk(tileX);
116 const chunkY = tileToChunk(tileY);
117 const localX = tileToLocal(tileX);
118 const localY = tileToLocal(tileY);
119 const data = world.chunkData(chunkX, chunkY, dim);
120 const index = localY * CHUNK_SIZE + localX;
121 const existing = data.blocks[index];
122 if (!existing)
123 { return null; }
124 const block = { ...existing, state };
125 data.blocks[index] = block;
126 return {
127 type: "chunk-delta",
128 chunkX,
129 chunkY,
130 dimensionId: dim,
131 tileX,
132 tileY,
133 localX,
134 localY,
135 block
136 };
137}
138
139function spotFishItemIds (block)
140{
141 return normalizeFishingSpotConfig(block?.config).fishes;
142}
143
144function maxFishTierInList (fishItemIds)
145{
146 let max = 0;
147 for (const itemId of fishItemIds)
148 { max = Math.max(max, fishTierRankFromItemId(itemId)); }
149 return max;
150}
151
152function eligibleFishItemIds (fishItemIds, baitTierRank)
153{
154 return fishItemIds.filter((itemId) => fishTierRankFromItemId(itemId) <= baitTierRank);
155}
156
157function findBestBaitSlot (slots, maxRank)
158{
159 let best = null;
160 for (let i = 0; i < (slots?.length ?? 0); i++)
161 {
162 const slot = slots[i];
163 if (!slot || stackQuantity(slot.quantity) <= 0)
164 { continue; }
165 const def = itemDefinition(slot.itemId);
166 if (!def?.bait || !def.tier)
167 { continue; }
168 const rank = tierRank(def.tier);
169 if (rank < 1 || rank > maxRank)
170 { continue; }
171 if (!best || rank > best.rank)
172 { best = { slotIndex: i, itemId: slot.itemId, rank, tier: def.tier }; }
173 }
174 return best;
175}
176
177function toolTierRank (tool)
178{
179 const tier = tool?.def?.equipment?.tier ?? tool?.tier;
180 return tierRank(tier);
181}
182
183/**
184 * Start fishing at a fishing-spot block tile.
185 */
186export function startFish (world, sessionId, characterId, tileX, tileY, now = Date.now())
187{
188 const entityId = world.characterEntities.get(characterId);
189 if (entityId == null)
190 { throw userError("Character is not in the world."); }
191 const handle = world.ecs.handleOf(entityId);
192 const identity = world.ecs.get(handle, Component.networkIdentity);
193 if (!identity || identity.sessionId !== sessionId)
194 { throw userError("Character is not in the world."); }
195 if (world.ecs.has(handle, Component.dead))
196 { throw userError("You are dead."); }
197
198 const position = world.ecs.get(handle, Component.position);
199 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
200 { throw userError("You need to stand next to the fishing spot."); }
201
202 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
203 const block = blockAt(world, tileX, tileY, dim);
204 if (!block || block.typeId !== BlockType.fishingSpot)
205 { throw userError("There is no fishing spot there."); }
206 if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY, dim)))
207 { throw userError("The fish have scattered. Wait for them to return."); }
208
209 const ground = groundAt(world, tileX, tileY, dim);
210 const season = seasonIdAt(now);
211 if (ground !== GroundType.water && ground !== GroundType.deepWater)
212 { throw userError("Fishing spots must be on water."); }
213 if (!isLiquidWaterGround(ground, season))
214 { throw userError("The water is frozen solid."); }
215
216 const fishList = spotFishItemIds(block);
217 if (!fishList.length)
218 { throw userError("No fish swim here."); }
219
220 const inventory = world.ecs.get(handle, Component.inventory);
221 const equipment = world.ecs.get(handle, Component.equipment);
222 const skills = world.ecs.get(handle, Component.skills);
223 const resolved = resolveFishingTool({
224 inventorySlots: inventory?.slots,
225 equipmentSlots: equipment?.slots,
226 skills
227 });
228 if (!resolved.ok)
229 { throw userError(resolved.reason); }
230
231 const isNet = resolved.kind === EquipmentKind.fishingNet;
232 const rodRank = isNet ? 1 : toolTierRank(resolved.tool);
233 const maxInSpot = maxFishTierInList(fishList);
234 const usefulMax = Math.min(rodRank, maxInSpot);
235
236 let baitRank = 1;
237 let baitItemId = null;
238 let baitConsumedRank = 0;
239
240 if (isNet)
241 {
242 baitRank = 1;
243 baitConsumedRank = 0;
244 }
245 else
246 {
247 const bait = findBestBaitSlot(inventory?.slots, usefulMax);
248 if (!bait)
249 { throw userError("You need suitable bait for this spot."); }
250 baitRank = bait.rank;
251 baitItemId = bait.itemId;
252 baitConsumedRank = bait.rank;
253 }
254
255 const eligible = eligibleFishItemIds(fishList, baitRank);
256 if (!eligible.length)
257 { throw userError("No fish here match your bait."); }
258
259 if (!isNet)
260 {
261 const taken = takeMatchingFromSlots(inventory.slots, {
262 itemId: baitItemId,
263 quantity: 1,
264 compact: false
265 });
266 if (!taken.ok)
267 { throw userError("You need suitable bait for this spot."); }
268 inventory.slots = taken.slots;
269 }
270
271 clearFishSession(world, characterId);
272 if (world.ecs.has(handle, Component.gather))
273 { world.ecs.remove(handle, Component.gather); }
274 const path = world.ecs.get(handle, Component.path);
275 if (path)
276 { path.tiles = []; }
277
278 ensureFishSessions(world).set(characterId, {
279 sessionId,
280 tileX,
281 tileY,
282 dimensionId: dim,
283 toolItemId: resolved.tool.def.itemId,
284 isNet,
285 baitRank,
286 baitConsumedRank,
287 baitItemId,
288 eligible,
289 difficulty: fishingDifficulty(baitRank),
290 attemptsLeft: MAX_FISH_ATTEMPTS,
291 attemptStartedAt: now,
292 nextShoveAt: now,
293 attemptEndsAt: now + Math.max(
294 1,
295 Math.floor(FISH_ATTEMPT_MS * gatherDurationMultiplier(equipment))
296 )
297 });
298
299 return {
300 events: [],
301 private: isNet ? null : bagView(world.ecs, handle)
302 };
303}
304
305export function handleFishingCommand (world, sessionId, command, now = Date.now())
306{
307 if (command.type === "start-fish")
308 {
309 return startFish(
310 world,
311 sessionId,
312 command.characterId,
313 command.tileX | 0,
314 command.tileY | 0,
315 now
316 );
317 }
318 if (command.type === "cancel-fish")
319 {
320 clearFishSession(world, command.characterId);
321 return { events: [] };
322 }
323 return null;
324}
325
326function completeCatch (world, handle, entityId, characterId, session, events, privates, now)
327{
328 const eligible = session.eligible ?? [];
329 if (!eligible.length)
330 {
331 events.push({
332 type: "command-error",
333 sessionId: session.sessionId,
334 message: "The fish got away."
335 });
336 clearFishSession(world, characterId);
337 return;
338 }
339 const rng = world.rng ?? Math.random;
340 const pick = eligible[Math.floor(rng() * eligible.length) % eligible.length];
341 const fishRank = fishTierRankFromItemId(pick);
342 const inventory = world.ecs.get(handle, Component.inventory);
343 const def = itemDefinition(pick);
344 const origin = gatherOrigin(GatherOriginVerb.caught, characterDisplayName(world, handle));
345 const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment))));
346 const stack = attachOrigins({
347 itemId: pick,
348 quantity,
349 origins: [{ origin, quantity }]
350 });
351 const inserted = insertStack(inventory.slots, stack, def);
352 if (!inserted.ok || inserted.remainder > 0)
353 {
354 events.push({
355 type: "command-error",
356 sessionId: session.sessionId,
357 message: "Your inventory is full."
358 });
359 clearFishSession(world, characterId);
360 return;
361 }
362 inventory.slots = inserted.slots;
363
364 const xpAmount = (session.baitConsumedRank | 0) + fishRank;
365 const skills = world.ecs.get(handle, Component.skills);
366 let skillsChanged = false;
367 const levelUps = [];
368 if (skills?.xp && xpAmount > 0)
369 {
370 const result = applySkillXp(
371 skills,
372 SkillId.fishing,
373 xpAmount,
374 world.ecs.get(handle, Component.equipment)
375 );
376 if (result.changed)
377 { skillsChanged = true; }
378 if (result.levelUp)
379 { levelUps.push(result.levelUp); }
380 }
381 if (skillsChanged)
382 {
383 events.push({
384 type: "skills-updated",
385 entityId,
386 characterId,
387 ...publicSkillsPayload(skills),
388 stored: storedSkillXp(skills),
389 levelUps
390 });
391 }
392
393 const dim = normalizeDimensionId(session.dimensionId ?? OVERWORLD_ID);
394 const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted", dim);
395 if (exhausted)
396 { events.push(exhausted); }
397 ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY, dim), {
398 tileX: session.tileX,
399 tileY: session.tileY,
400 dimensionId: dim,
401 respawnsAt: now + fishingExhaustDurationMs(fishRank)
402 });
403
404 privates.push({ characterId, bag: bagView(world.ecs, handle) });
405 events.push({
406 type: "item-bubble",
407 entityId,
408 itemId: pick,
409 quantity: 1
410 });
411 clearFishSession(world, characterId);
412}
413
414export function stepFishing (world, now)
415{
416 const events = [];
417 const privates = [];
418 events.push(...stepFishingSpotRespawns(world, now).events);
419
420 const sessions = ensureFishSessions(world);
421 for (const [characterId, session] of [...sessions.entries()])
422 {
423 const entityId = world.characterEntities.get(characterId);
424 if (entityId == null)
425 {
426 clearFishSession(world, characterId);
427 continue;
428 }
429 const handle = world.ecs.handleOf(entityId);
430 if (world.ecs.has(handle, Component.dead))
431 {
432 clearFishSession(world, characterId);
433 continue;
434 }
435 const position = world.ecs.get(handle, Component.position);
436 if (!isAdjacentTile(position.tileX, position.tileY, session.tileX, session.tileY))
437 {
438 clearFishSession(world, characterId);
439 continue;
440 }
441
442 if (now >= session.nextShoveAt && now < session.attemptEndsAt)
443 {
444 session.nextShoveAt = now + FISH_SHOVE_MS;
445 events.push(tileShoveEvent(
446 entityId,
447 position.tileX,
448 position.tileY,
449 session.tileX,
450 session.tileY,
451 normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID)
452 ));
453 // Also emit gather-swing so tool overlay shows.
454 events.push({
455 type: "gather-swing",
456 attackerId: entityId,
457 tileX: session.tileX,
458 tileY: session.tileY,
459 fromTileX: position.tileX,
460 fromTileY: position.tileY,
461 dimensionId: normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID),
462 toolItemId: session.toolItemId,
463 swipe: false
464 });
465 }
466
467 if (now < session.attemptEndsAt)
468 { continue; }
469
470 const skills = world.ecs.get(handle, Component.skills);
471 const level = skillLevel(skills, SkillId.fishing);
472 const roll = rollSkill(level, world.rng ?? Math.random);
473 session.attemptsLeft -= 1;
474
475 if (roll >= session.difficulty)
476 {
477 completeCatch(world, handle, entityId, characterId, session, events, privates, now);
478 continue;
479 }
480
481 if (session.attemptsLeft <= 0)
482 {
483 events.push({
484 type: "command-error",
485 sessionId: session.sessionId,
486 message: "The fish got away."
487 });
488 maybeBreakFishingLine(world, handle, entityId, characterId, session, events, privates, now);
489 clearFishSession(world, characterId);
490 continue;
491 }
492
493 session.attemptStartedAt = now;
494 session.nextShoveAt = now;
495 session.attemptEndsAt = now + Math.max(
496 1,
497 Math.floor(FISH_ATTEMPT_MS * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment)))
498 );
499 }
500
501 return { events, privates };
502}
503
504function spawnGroundStack (world, tileX, tileY, itemId, now, events, source = "fishing-line-break", dimensionId = OVERWORLD_ID)
505{
506 const stack = attachOrigins({
507 itemId,
508 quantity: 1,
509 origins: []
510 });
511 const placed = placeOrMergeGroundStack(world, {
512 tileX,
513 tileY,
514 dimensionId: normalizeDimensionId(dimensionId),
515 stack,
516 now,
517 source
518 });
519 events.push(...placed.events);
520}
521
522/**
523 * After a fully failed rod session: 5% chance the line snaps → rod becomes pole + 1 yarn.
524 */
525function maybeBreakFishingLine (world, handle, entityId, characterId, session, events, privates, now)
526{
527 if (session.isNet)
528 { return; }
529 const rng = world.rng ?? Math.random;
530 if (rng() >= LINE_BREAK_CHANCE)
531 { return; }
532
533 const rodItemId = session.toolItemId | 0;
534 const rodDef = itemDefinition(rodItemId);
535 const woodTier = woodTierFromFishingRodItemId(rodItemId) ?? rodDef?.tier;
536 const poleItemId = rodDef?.poleItemId ?? fishingPoleItemIdForWood(woodTier);
537 const clothTier = rodDef?.clothTier ?? clothTierForWood(woodTier);
538 const yarnId = yarnItemId(clothTier);
539 if (!poleItemId || !yarnId)
540 { return; }
541
542 const inventory = world.ecs.get(handle, Component.inventory);
543 const equipment = world.ecs.get(handle, Component.equipment);
544 let removed = false;
545 let appearanceChanged = false;
546
547 if (inventory?.slots)
548 {
549 const idx = inventory.slots.findIndex((s) => s?.itemId === rodItemId);
550 if (idx >= 0)
551 {
552 const taken = takeFromSlot(inventory.slots, idx, 1);
553 if (taken.ok)
554 {
555 inventory.slots = taken.slots;
556 removed = true;
557 }
558 }
559 }
560 if (!removed && equipment?.slots?.weapon?.itemId === rodItemId)
561 {
562 equipment.slots.weapon = null;
563 removed = true;
564 appearanceChanged = true;
565 }
566 if (!removed)
567 { return; }
568
569 const position = world.ecs.get(handle, Component.position);
570 const poleDef = itemDefinition(poleItemId);
571 const yarnDef = itemDefinition(yarnId);
572 let slots = inventory.slots;
573
574 const poleIns = insertStack(slots, attachOrigins({ itemId: poleItemId, quantity: 1, origins: [] }), poleDef);
575 if (poleIns.ok && poleIns.remainder === 0)
576 { slots = poleIns.slots; }
577 else
578 { spawnGroundStack(world, position.tileX, position.tileY, poleItemId, now, events, "fishing-line-break", normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID)); }
579
580 const yarnIns = insertStack(slots, attachOrigins({ itemId: yarnId, quantity: 1, origins: [] }), yarnDef);
581 if (yarnIns.ok && yarnIns.remainder === 0)
582 { slots = yarnIns.slots; }
583 else
584 { spawnGroundStack(world, position.tileX, position.tileY, yarnId, now, events, "fishing-line-break", normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID)); }
585
586 inventory.slots = slots;
587
588 events.push({
589 type: "command-error",
590 sessionId: session.sessionId,
591 message: "Your fishing line broke!"
592 });
593 privates.push({
594 characterId,
595 bag: bagView(world.ecs, handle),
596 ...(appearanceChanged ? { appearanceChanged: true } : {})
597 });
598}
599
600export function stepFishingSpotRespawns (world, now)
601{
602 const respawns = world.fishingSpotRespawns;
603 if (!respawns?.size)
604 { return { events: [] }; }
605 const events = [];
606 for (const [key, entry] of [...respawns.entries()])
607 {
608 if (now < entry.respawnsAt)
609 { continue; }
610 respawns.delete(key);
611 const dim = normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID);
612 const block = blockAt(world, entry.tileX, entry.tileY, dim);
613 if (!block || block.typeId !== BlockType.fishingSpot)
614 { continue; }
615 const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot", dim);
616 if (delta)
617 { events.push(delta); }
618 }
619 return { events };
620}
621
622export { ClothTier, BaitItemId, baitItemIdForCloth, FISH_SPECIES };