BlueGit

timfa questward

Files

questward / server / src / gathering / service.js

service.js

service.js 8.7 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { itemDefinition } 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} from "../../../shared/definitions/gathering.js";
15import { insertStack } from "../../../shared/items/inventory.js";
16import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
17import { bagView } from "../items/bags.js";
18import { chebyshev, clearEngage } from "../combat/service.js";
19import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
20import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
21
22const GATHER_SWING_INTERVAL_MS = 900;
23
24function userError (message)
25{
26 const error = new Error(message);
27 error.userFacing = true;
28 return error;
29}
30
31function ensureOreRespawns (world)
32{
33 if (!world.oreRespawns)
34 { world.oreRespawns = new Map(); }
35 return world.oreRespawns;
36}
37
38function blockAt (world, tileX, tileY)
39{
40 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
41 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
42}
43
44function setBoulderState (world, tileX, tileY, state)
45{
46 const chunkX = tileToChunk(tileX);
47 const chunkY = tileToChunk(tileY);
48 const localX = tileToLocal(tileX);
49 const localY = tileToLocal(tileY);
50 const data = world.chunkData(chunkX, chunkY);
51 const index = localY * CHUNK_SIZE + localX;
52 const prev = data?.blocks?.[index];
53 if (!prev || prev.typeId !== BlockType.boulder)
54 { return null; }
55 const block = { typeId: prev.typeId, state, config: prev.config ?? null };
56 data.blocks[index] = block;
57 return {
58 type: "chunk-delta",
59 chunkX,
60 chunkY,
61 tileX,
62 tileY,
63 localX,
64 localY,
65 block
66 };
67}
68
69function pickaxeForOre (world, handle, materialId)
70{
71 const inventory = world.ecs.get(handle, Component.inventory);
72 const equipment = world.ecs.get(handle, Component.equipment);
73 const skills = world.ecs.get(handle, Component.skills);
74 return resolveMiningPickaxe({
75 inventorySlots: inventory?.slots,
76 equipmentSlots: equipment?.slots,
77 skills,
78 materialId
79 });
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 = pickaxeForOre(world, handle, materialId);
157 if (!pickaxe.ok)
158 { throw userError(pickaxe.reason); }
159
160 const durationMs = miningDurationMs(materialId, pickaxe.tool.tier);
161 clearEngage(world.ecs, entityId);
162 const path = world.ecs.get(handle, Component.path);
163 if (path)
164 { path.tiles = []; }
165 world.ecs.add(handle, Component.gather, {
166 kind: "mining",
167 tileX,
168 tileY,
169 materialId,
170 toolTier: pickaxe.tool.tier,
171 startedAt: now,
172 finishesAt: now + durationMs,
173 nextSwingAt: now
174 });
175
176 return {
177 events: [{
178 type: "gather-swing",
179 attackerId: entityId,
180 tileX,
181 tileY,
182 fromTileX: position.tileX,
183 fromTileY: position.tileY,
184 swipe: false
185 }]
186 };
187}
188
189export function stepGather (world, now)
190{
191 const events = [];
192 const privates = [];
193 const respawnEvents = stepOreRespawns(world, now);
194 events.push(...respawnEvents.events);
195
196 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
197 {
198 const { handle, gather, position, character, entityId } = entity;
199 if (world.ecs.has(handle, Component.dead))
200 {
201 clearGather(world.ecs, handle);
202 continue;
203 }
204 if (chebyshev(position.tileX, position.tileY, gather.tileX, gather.tileY) > 1)
205 {
206 clearGather(world.ecs, handle);
207 continue;
208 }
209 const block = blockAt(world, gather.tileX, gather.tileY);
210 if (!block || block.typeId !== BlockType.boulder
211 || materialFromOreBoulderState(block.state) !== gather.materialId)
212 {
213 clearGather(world.ecs, handle);
214 continue;
215 }
216
217 if (now >= gather.nextSwingAt && now < gather.finishesAt)
218 {
219 gather.nextSwingAt = now + GATHER_SWING_INTERVAL_MS;
220 events.push({
221 type: "gather-swing",
222 attackerId: entityId,
223 tileX: gather.tileX,
224 tileY: gather.tileY,
225 fromTileX: position.tileX,
226 fromTileY: position.tileY,
227 swipe: false
228 });
229 }
230
231 if (now < gather.finishesAt)
232 { continue; }
233
234 const oreItemId = oreItemIdForMaterial(gather.materialId);
235 const def = itemDefinition(oreItemId);
236 const inventory = world.ecs.get(handle, Component.inventory);
237 if (!oreItemId || !def || !inventory)
238 {
239 clearGather(world.ecs, handle);
240 continue;
241 }
242 const inserted = insertStack(inventory.slots, { itemId: oreItemId, quantity: 1 }, def);
243 if (!inserted.ok || inserted.remainder > 0)
244 {
245 clearGather(world.ecs, handle);
246 events.push({
247 type: "command-error",
248 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
249 message: "Your inventory is full."
250 });
251 continue;
252 }
253 inventory.slots = inserted.slots;
254
255 const skills = world.ecs.get(handle, Component.skills);
256 let skillsChanged = false;
257 if (skills?.xp && addSkillXp(skills, SkillId.mining, miningXpForMaterial(gather.materialId)))
258 { skillsChanged = true; }
259
260 const exhausted = setBoulderState(
261 world,
262 gather.tileX,
263 gather.tileY,
264 EXHAUSTED_ORE_BOULDER_STATE
265 );
266 if (exhausted)
267 {
268 events.push(exhausted);
269 ensureOreRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
270 tileX: gather.tileX,
271 tileY: gather.tileY,
272 materialId: gather.materialId,
273 respawnsAt: now + oreExhaustDurationMs(gather.materialId)
274 });
275 }
276
277 clearGather(world.ecs, handle);
278 privates.push({
279 characterId: character.characterId,
280 bag: bagView(world.ecs, handle)
281 });
282 if (skillsChanged)
283 {
284 events.push({
285 type: "skills-updated",
286 characterId: character.characterId,
287 skills: publicSkillsView(skills),
288 stored: storedSkillXp(skills)
289 });
290 }
291 events.push({
292 type: "gather-complete",
293 characterId: character.characterId,
294 kind: "mining",
295 materialId: gather.materialId,
296 itemId: oreItemId
297 });
298 }
299 return { events, privates };
300}
301
302export function handleGatherCommand (world, sessionId, command, now)
303{
304 switch (command.type)
305 {
306 case "mine":
307 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
308 case "cancel-gather":
309 {
310 const entityId = world.characterEntities.get(command.characterId);
311 if (entityId == null)
312 { return { events: [] }; }
313 const handle = world.ecs.handleOf(entityId);
314 clearGather(world.ecs, handle);
315 return { events: [] };
316 }
317 default:
318 return null;
319 }
320}