BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

service.js 8.9 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
4import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6import {
7 materialFromOreBoulderState,
8 canMineMaterial,
9 oreItemIdForMaterial,
10 miningDurationMs,
11 miningXpForMaterial,
12 oreExhaustDurationMs,
13 oreBoulderState,
14 EXHAUSTED_ORE_BOULDER_STATE
15} from "../../../shared/definitions/gathering.js";
16import { insertStack } from "../../../shared/items/inventory.js";
17import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
18import { bagView } from "../items/bags.js";
19import { chebyshev, clearEngage } from "../combat/service.js";
20import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
21import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
22
23const GATHER_SWING_INTERVAL_MS = 900;
24
25function userError (message)
26{
27 const error = new Error(message);
28 error.userFacing = true;
29 return error;
30}
31
32function ensureOreRespawns (world)
33{
34 if (!world.oreRespawns)
35 { world.oreRespawns = new Map(); }
36 return world.oreRespawns;
37}
38
39function blockAt (world, tileX, tileY)
40{
41 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
42 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
43}
44
45function setBoulderState (world, tileX, tileY, state)
46{
47 const chunkX = tileToChunk(tileX);
48 const chunkY = tileToChunk(tileY);
49 const localX = tileToLocal(tileX);
50 const localY = tileToLocal(tileY);
51 const data = world.chunkData(chunkX, chunkY);
52 const index = localY * CHUNK_SIZE + localX;
53 const prev = data?.blocks?.[index];
54 if (!prev || prev.typeId !== BlockType.boulder)
55 { return null; }
56 const block = { typeId: prev.typeId, state, config: prev.config ?? null };
57 data.blocks[index] = block;
58 return {
59 type: "chunk-delta",
60 chunkX,
61 chunkY,
62 tileX,
63 tileY,
64 localX,
65 localY,
66 block
67 };
68}
69
70function equippedPickaxe (ecs, handle)
71{
72 const equipment = ecs.get(handle, Component.equipment);
73 const stack = equipment?.slots?.weapon;
74 if (!stack?.itemId)
75 { return null; }
76 const def = itemDefinition(stack.itemId);
77 if (def?.equipment?.kind !== EquipmentKind.pickaxeTool)
78 { return null; }
79 return { stack, def, tier: def.equipment.tier };
80}
81
82function clearGather (ecs, handle)
83{
84 if (ecs.has(handle, Component.gather))
85 { ecs.remove(handle, Component.gather); }
86}
87
88export function cancelGather (ecs, handle)
89{
90 clearGather(ecs, handle);
91}
92
93/** Drop scheduled ore respawns when authored chunk data is replaced or unloaded. */
94export function clearOreRespawnsForChunk (world, chunkX, chunkY)
95{
96 const respawns = world.oreRespawns;
97 if (!respawns?.size)
98 { return; }
99 for (const key of [...respawns.keys()])
100 {
101 const [tileX, tileY] = key.split(",").map(Number);
102 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
103 { respawns.delete(key); }
104 }
105}
106
107/**
108 * Restore exhausted ore boulders whose timers have elapsed.
109 */
110export function stepOreRespawns (world, now)
111{
112 const respawns = world.oreRespawns;
113 if (!respawns?.size)
114 { return { events: [] }; }
115 const events = [];
116 for (const [key, entry] of [...respawns.entries()])
117 {
118 if (now < entry.respawnsAt)
119 { continue; }
120 respawns.delete(key);
121 const delta = setBoulderState(world, entry.tileX, entry.tileY, oreBoulderState(entry.materialId));
122 if (delta)
123 { events.push(delta); }
124 }
125 return { events };
126}
127
128/**
129 * Start mining an ore boulder. Returns events / private bag updates when complete via stepGather.
130 */
131export function startMine (world, sessionId, characterId, tileX, tileY, now)
132{
133 const entityId = world.characterEntities.get(characterId);
134 if (entityId == null)
135 { throw userError("Character is not in the world."); }
136 const handle = world.ecs.handleOf(entityId);
137 const identity = world.ecs.get(handle, Component.networkIdentity);
138 if (!identity || identity.sessionId !== sessionId)
139 { throw userError("Character is not in the world."); }
140 if (world.ecs.has(handle, Component.dead))
141 { throw userError("You are dead."); }
142
143 const position = world.ecs.get(handle, Component.position);
144 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
145 { throw userError("You need to stand next to the rock."); }
146
147 const block = blockAt(world, tileX, tileY);
148 if (!block || block.typeId !== BlockType.boulder)
149 { throw userError("There is nothing to mine there."); }
150 const materialId = materialFromOreBoulderState(block.state);
151 if (!materialId)
152 { throw userError(block.state === EXHAUSTED_ORE_BOULDER_STATE
153 ? "That rock is exhausted."
154 : "That rock has no ore."); }
155
156 const pickaxe = equippedPickaxe(world.ecs, handle);
157 if (!pickaxe)
158 { throw userError("Equip a pickaxe to mine."); }
159
160 const skills = world.ecs.get(handle, Component.skills);
161 const miningLevel = skillLevel(skills, SkillId.mining);
162 const gate = canMineMaterial(miningLevel, pickaxe.tier, materialId);
163 if (!gate.ok)
164 { throw userError(gate.reason); }
165
166 const durationMs = miningDurationMs(materialId, pickaxe.tier);
167 clearEngage(world.ecs, entityId);
168 const path = world.ecs.get(handle, Component.path);
169 if (path)
170 { path.tiles = []; }
171 world.ecs.add(handle, Component.gather, {
172 kind: "mining",
173 tileX,
174 tileY,
175 materialId,
176 startedAt: now,
177 finishesAt: now + durationMs,
178 nextSwingAt: now
179 });
180
181 return {
182 events: [{
183 type: "gather-swing",
184 attackerId: entityId,
185 tileX,
186 tileY,
187 fromTileX: position.tileX,
188 fromTileY: position.tileY,
189 swipe: false
190 }]
191 };
192}
193
194export function stepGather (world, now)
195{
196 const events = [];
197 const privates = [];
198 const respawnEvents = stepOreRespawns(world, now);
199 events.push(...respawnEvents.events);
200
201 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
202 {
203 const { handle, gather, position, character, entityId } = entity;
204 if (world.ecs.has(handle, Component.dead))
205 {
206 clearGather(world.ecs, handle);
207 continue;
208 }
209 if (chebyshev(position.tileX, position.tileY, gather.tileX, gather.tileY) > 1)
210 {
211 clearGather(world.ecs, handle);
212 continue;
213 }
214 const block = blockAt(world, gather.tileX, gather.tileY);
215 if (!block || block.typeId !== BlockType.boulder
216 || materialFromOreBoulderState(block.state) !== gather.materialId)
217 {
218 clearGather(world.ecs, handle);
219 continue;
220 }
221
222 if (now >= gather.nextSwingAt && now < gather.finishesAt)
223 {
224 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
225 events.push({
226 type: "gather-swing",
227 attackerId: entityId,
228 tileX: gather.tileX,
229 tileY: gather.tileY,
230 fromTileX: position.tileX,
231 fromTileY: position.tileY,
232 swipe: false
233 });
234 }
235
236 if (now < gather.finishesAt)
237 { continue; }
238
239 const oreItemId = oreItemIdForMaterial(gather.materialId);
240 const def = itemDefinition(oreItemId);
241 const inventory = world.ecs.get(handle, Component.inventory);
242 if (!oreItemId || !def || !inventory)
243 {
244 clearGather(world.ecs, handle);
245 continue;
246 }
247 const inserted = insertStack(inventory.slots, { itemId: oreItemId, quantity: 1 }, def);
248 if (!inserted.ok || inserted.remainder > 0)
249 {
250 clearGather(world.ecs, handle);
251 events.push({
252 type: "command-error",
253 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
254 message: "Your inventory is full."
255 });
256 continue;
257 }
258 inventory.slots = inserted.slots;
259
260 const skills = world.ecs.get(handle, Component.skills);
261 let skillsChanged = false;
262 if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))
263 { skillsChanged = true; }
264
265 const exhausted = setBoulderState(
266 world,
267 gather.tileX,
268 gather.tileY,
269 EXHAUSTED_ORE_BOULDER_STATE
270 );
271 if (exhausted)
272 {
273 events.push(exhausted);
274 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
275 tileX: gather.tileX,
276 tileY: gather.tileY,
277 materialId: gather.materialId,
278 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
279 });
280 }
281
282 clearGather(world.ecs, handle);
283 privates.push({
284 characterId: character.characterId,
285 bag: bagView(world.ecs, handle)
286 });
287 if (skillsChanged)
288 {
289 events.push({
290 type: "skills-updated",
291 characterId: character.characterId,
292 skills: publicSkillsView(skills),
293 stored: storedSkillXp(skills)
294 });
295 }
296 events.push({
297 type: "gather-complete",
298 characterId: character.characterId,
299 kind: "mining",
300 materialId: gather.materialId,
301 itemId: oreItemId
302 });
303 }
304 return { events, privates };
305}
306
307export function handleGatherCommand (world, sessionId, command, now)
308{
309 switch (command.type)
310 {
311 case "mine":
312 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
313 case "cancel-gather":
314 {
315 const entityId = world.characterEntities.get(command.characterId);
316 if (entityId == null)
317 { return { events: [] }; }
318 const handle = world.ecs.handleOf(entityId);
319 clearGather(world.ecs, handle);
320 return { events: [] };
321 }
322 default:
323 return null;
324 }
325}