BlueGit

timfa questward

Files

questward / server / src / firestarting / service.js

service.js

service.js 13.2 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "../../../shared/definitions/craftingItems.js";
4import {
5 ashItemIdForWood,
6 logItemIdForWood
7} from "../../../shared/definitions/woodItems.js";
8import {
9 campfireDurationMs,
10 firestartingDifficulty,
11 woodTierRank
12} from "../../../shared/definitions/craftingStations.js";
13import { MATERIAL_DISPLAY_NAME, WOOD_TIER_ORDER } from "../../../shared/definitions/materialTiers.js";
14import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js";
15import { itemDefinition } from "../../../shared/definitions/items.js";
16import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
17import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
18import { rollSkill } from "../../../shared/combat/rolls.js";
19import { stackQuantity } from "../../../shared/items/inventory.js";
20import { attachOrigins, ashOrigin, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js";
21import { placeOrMergeGroundStack, publicGroundItem, removeGroundItem, bagView } from "../items/bags.js";
22import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
23import { tileToChunk, tileToLocal } from "../world/coordinates.js";
24import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
25
26const FIRE_ATTEMPT_MS = 1100;
27const MAX_LIGHT_ATTEMPTS = 3;
28
29function userError (message)
30{
31 const error = new Error(message);
32 error.userFacing = true;
33 return error;
34}
35
36function characterDisplayName (world, handle)
37{
38 const appearance = world.ecs.get(handle, Component.appearance);
39 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
40 return name || "someone";
41}
42
43function tileKey (tileX, tileY)
44{
45 return `${tileX},${tileY}`;
46}
47
48function ensureCampfires (world)
49{
50 if (!world.campfireExpires)
51 { world.campfireExpires = new Map(); }
52 return world.campfireExpires;
53}
54
55function ensureFireSessions (world)
56{
57 if (!world.fireSessions)
58 { world.fireSessions = new Map(); }
59 return world.fireSessions;
60}
61
62function clearFireSession (world, characterId)
63{
64 ensureFireSessions(world).delete(characterId);
65}
66
67function woodTierFromLogItemId (itemId)
68{
69 const def = itemDefinition(itemId);
70 if (!def || def.familyId !== ItemFamilyId.log)
71 { return null; }
72 return def.tier ?? null;
73}
74
75function findTinderboxSlot (slots)
76{
77 for (let i = 0; i < (slots?.length ?? 0); i++)
78 {
79 const slot = slots[i];
80 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
81 { continue; }
82 const charges = slot.instance?.kind === "tinderbox"
83 ? (slot.instance.charges | 0)
84 : TINDERBOX_MAX_CHARGES;
85 if (charges > 0)
86 { return i; }
87 }
88 return -1;
89}
90
91/** Consume one tinderbox charge in place; remove item at 0. */
92function consumeTinderboxCharge (slots, slotIndex)
93{
94 const next = slots.map((s) => (s ? structuredClone(s) : null));
95 const slot = next[slotIndex];
96 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
97 { return { ok: false, slots }; }
98 const charges = slot.instance?.kind === "tinderbox"
99 ? (slot.instance.charges | 0)
100 : TINDERBOX_MAX_CHARGES;
101 if (charges <= 0)
102 { return { ok: false, slots }; }
103 if (charges <= 1)
104 {
105 next[slotIndex] = null;
106 return { ok: true, slots: next, exhausted: true };
107 }
108 next[slotIndex].instance = {
109 kind: "tinderbox",
110 charges: charges - 1
111 };
112 return { ok: true, slots: next, exhausted: false };
113}
114
115function placeBlock (world, tileX, tileY, typeId, state, config = null)
116{
117 const chunkX = tileToChunk(tileX);
118 const chunkY = tileToChunk(tileY);
119 const localX = tileToLocal(tileX);
120 const localY = tileToLocal(tileY);
121 const data = world.chunkData(chunkX, chunkY);
122 const index = localY * CHUNK_SIZE + localX;
123 const block = { typeId, state, config };
124 data.blocks[index] = block;
125 return {
126 type: "chunk-delta",
127 chunkX,
128 chunkY,
129 tileX,
130 tileY,
131 localX,
132 localY,
133 block
134 };
135}
136
137function clearBlockAt (world, tileX, tileY)
138{
139 const chunkX = tileToChunk(tileX);
140 const chunkY = tileToChunk(tileY);
141 const localX = tileToLocal(tileX);
142 const localY = tileToLocal(tileY);
143 const data = world.chunkData(chunkX, chunkY);
144 const index = localY * CHUNK_SIZE + localX;
145 if (!data.blocks[index])
146 { return null; }
147 data.blocks[index] = null;
148 return {
149 type: "chunk-delta",
150 chunkX,
151 chunkY,
152 tileX,
153 tileY,
154 localX,
155 localY,
156 block: null
157 };
158}
159
160function blockAt (world, tileX, tileY)
161{
162 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
163 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
164 return data.blocks[index] ?? null;
165}
166
167function consumeOneGroundLog (world, item, events)
168{
169 const qty = stackQuantity(item.stack?.quantity);
170 if (qty <= 1)
171 {
172 removeGroundItem(world, item.groundItemId);
173 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
174 return;
175 }
176 const split = splitOrigins(normalizeOrigins(item.stack), 1);
177 item.stack.quantity = qty - 1;
178 item.stack.origins = split.remain;
179 delete item.stack.origin;
180 events.push({
181 type: "ground-item-appear",
182 ...publicGroundItem(item),
183 stack: item.stack,
184 droppedAt: item.droppedAt,
185 source: item.source,
186 expiresAt: item.expiresAt
187 });
188}
189
190function spawnAsh (world, tileX, tileY, woodTier, litByName, now, events)
191{
192 const ashItemId = ashItemIdForWood(woodTier);
193 if (!ashItemId)
194 { return; }
195 const woodName = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
196 const stack = attachOrigins({
197 itemId: ashItemId,
198 quantity: 1,
199 origins: [{
200 origin: ashOrigin(woodName, litByName),
201 quantity: 1
202 }]
203 });
204 const placed = placeOrMergeGroundStack(world, {
205 tileX,
206 tileY,
207 stack,
208 now,
209 source: "campfire-ash"
210 });
211 events.push(...placed.events);
212}
213
214/**
215 * Start lighting a ground log with a tinderbox (up to 3 skill rolls).
216 */
217export function startFire (world, sessionId, characterId, groundItemId, now)
218{
219 const entityId = world.characterEntities.get(characterId);
220 if (entityId == null)
221 { throw userError("Character is not in the world."); }
222 const handle = world.ecs.handleOf(entityId);
223 const identity = world.ecs.get(handle, Component.networkIdentity);
224 if (!identity || identity.sessionId !== sessionId)
225 { throw userError("Character is not in the world."); }
226 if (world.ecs.has(handle, Component.dead))
227 { throw userError("You are dead."); }
228
229 const item = world.groundItems.get(groundItemId | 0);
230 if (!item)
231 { throw userError("That item is no longer on the ground."); }
232 const woodTier = woodTierFromLogItemId(item.stack?.itemId);
233 if (!woodTier)
234 { throw userError("You can only light wood logs."); }
235
236 const position = world.ecs.get(handle, Component.position);
237 if (!isAdjacentTile(position.tileX, position.tileY, item.tileX, item.tileY))
238 { throw userError("You need to stand next to the logs."); }
239
240 if (blockAt(world, item.tileX, item.tileY))
241 { throw userError("There is no room for a fire there."); }
242
243 const difficulty = firestartingDifficulty(woodTier);
244 const skills = world.ecs.get(handle, Component.skills);
245 const level = skillLevel(skills, SkillId.firestarting);
246 if (level < difficulty)
247 {
248 const label = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
249 throw userError(`Your Firestarting skill is too low to light ${label} logs.`);
250 }
251
252 const inventory = world.ecs.get(handle, Component.inventory);
253 const tinderSlot = findTinderboxSlot(inventory?.slots);
254 if (tinderSlot < 0)
255 { throw userError("You need a tinderbox with charges remaining."); }
256
257 const consumed = consumeTinderboxCharge(inventory.slots, tinderSlot);
258 if (!consumed.ok)
259 { throw userError("You need a tinderbox with charges remaining."); }
260 inventory.slots = consumed.slots;
261
262 clearFireSession(world, characterId);
263 if (world.ecs.has(handle, Component.gather))
264 { world.ecs.remove(handle, Component.gather); }
265 const path = world.ecs.get(handle, Component.path);
266 if (path)
267 { path.tiles = []; }
268
269 ensureFireSessions(world).set(characterId, {
270 sessionId,
271 groundItemId: item.groundItemId,
272 tileX: item.tileX,
273 tileY: item.tileY,
274 woodTier,
275 difficulty,
276 attemptsLeft: MAX_LIGHT_ATTEMPTS,
277 nextAttemptAt: now,
278 toolItemId: CraftingItemId.tinderbox
279 });
280
281 return {
282 events: [],
283 private: bagView(world.ecs, handle)
284 };
285}
286
287export function cancelFirestarting (world, characterId)
288{
289 clearFireSession(world, characterId);
290}
291
292export function handleFirestartingCommand (world, sessionId, command, now = Date.now())
293{
294 if (command.type === "start-fire")
295 {
296 return startFire(world, sessionId, command.characterId, command.groundItemId, now);
297 }
298 if (command.type === "cancel-fire")
299 {
300 cancelFirestarting(world, command.characterId);
301 return { events: [] };
302 }
303 return null;
304}
305
306function succeedLight (world, handle, entityId, characterId, session, events, privates, now)
307{
308 const item = world.groundItems.get(session.groundItemId);
309 if (!item || woodTierFromLogItemId(item.stack?.itemId) !== session.woodTier)
310 {
311 events.push({
312 type: "command-error",
313 sessionId: session.sessionId,
314 message: "Those logs are gone."
315 });
316 clearFireSession(world, characterId);
317 return;
318 }
319 if (blockAt(world, session.tileX, session.tileY))
320 {
321 events.push({
322 type: "command-error",
323 sessionId: session.sessionId,
324 message: "There is no room for a fire there."
325 });
326 clearFireSession(world, characterId);
327 return;
328 }
329
330 consumeOneGroundLog(world, item, events);
331 const expiresAt = now + campfireDurationMs(session.woodTier);
332 const litByName = characterDisplayName(world, handle);
333 const delta = placeBlock(
334 world,
335 session.tileX,
336 session.tileY,
337 BlockType.campfire,
338 session.woodTier,
339 { woodTier: session.woodTier, litAt: now, expiresAt, litByName }
340 );
341 events.push(delta);
342 ensureCampfires(world).set(tileKey(session.tileX, session.tileY), {
343 tileX: session.tileX,
344 tileY: session.tileY,
345 woodTier: session.woodTier,
346 expiresAt,
347 litByName
348 });
349
350 const skills = world.ecs.get(handle, Component.skills);
351 let skillsChanged = false;
352 const levelUps = [];
353 if (skills?.xp)
354 {
355 const result = applySkillXp(
356 skills,
357 SkillId.firestarting,
358 session.difficulty,
359 world.ecs.get(handle, Component.equipment)
360 );
361 if (result.changed)
362 { skillsChanged = true; }
363 if (result.levelUp)
364 { levelUps.push(result.levelUp); }
365 }
366 if (skillsChanged)
367 {
368 events.push({
369 type: "skills-updated",
370 entityId,
371 characterId,
372 ...publicSkillsPayload(skills),
373 stored: storedSkillXp(skills),
374 levelUps
375 });
376 }
377 privates.push({ characterId, bag: bagView(world.ecs, handle) });
378 clearFireSession(world, characterId);
379}
380
381/**
382 * Advance lighting attempts and expire campfires.
383 */
384export function stepFirestarting (world, now)
385{
386 const events = [];
387 const privates = [];
388 events.push(...stepCampfireExpires(world, now).events);
389
390 const sessions = ensureFireSessions(world);
391 for (const [characterId, session] of [...sessions.entries()])
392 {
393 if (now < session.nextAttemptAt)
394 { continue; }
395 const entityId = world.characterEntities.get(characterId);
396 if (entityId == null)
397 {
398 clearFireSession(world, characterId);
399 continue;
400 }
401 const handle = world.ecs.handleOf(entityId);
402 if (world.ecs.has(handle, Component.dead))
403 {
404 clearFireSession(world, characterId);
405 continue;
406 }
407 const position = world.ecs.get(handle, Component.position);
408 if (!isAdjacentTile(position.tileX, position.tileY, session.tileX, session.tileY))
409 {
410 clearFireSession(world, characterId);
411 continue;
412 }
413
414 const item = world.groundItems.get(session.groundItemId);
415 if (!item)
416 {
417 events.push({
418 type: "command-error",
419 sessionId: session.sessionId,
420 message: "Those logs are gone."
421 });
422 clearFireSession(world, characterId);
423 continue;
424 }
425
426 events.push({
427 type: "gather-swing",
428 attackerId: entityId,
429 tileX: session.tileX,
430 tileY: session.tileY,
431 fromTileX: position.tileX,
432 fromTileY: position.tileY,
433 toolItemId: session.toolItemId,
434 swipe: false
435 });
436
437 const skills = world.ecs.get(handle, Component.skills);
438 const level = skillLevel(skills, SkillId.firestarting);
439 const roll = rollSkill(level, world.rng ?? Math.random);
440 session.attemptsLeft -= 1;
441 if (roll >= session.difficulty)
442 {
443 succeedLight(world, handle, entityId, characterId, session, events, privates, now);
444 continue;
445 }
446 if (session.attemptsLeft <= 0)
447 {
448 events.push({
449 type: "command-error",
450 sessionId: session.sessionId,
451 message: "The sparks fail to catch."
452 });
453 clearFireSession(world, characterId);
454 continue;
455 }
456 session.nextAttemptAt = now + FIRE_ATTEMPT_MS;
457 }
458
459 return { events, privates };
460}
461
462export function stepCampfireExpires (world, now)
463{
464 const expires = world.campfireExpires;
465 if (!expires?.size)
466 { return { events: [] }; }
467 const events = [];
468 for (const [key, entry] of [...expires.entries()])
469 {
470 if (now < entry.expiresAt)
471 { continue; }
472 expires.delete(key);
473 const block = blockAt(world, entry.tileX, entry.tileY);
474 if (!block || block.typeId !== BlockType.campfire)
475 { continue; }
476 const delta = clearBlockAt(world, entry.tileX, entry.tileY);
477 if (delta)
478 { events.push(delta); }
479 spawnAsh(
480 world,
481 entry.tileX,
482 entry.tileY,
483 entry.woodTier,
484 entry.litByName,
485 now,
486 events
487 );
488 }
489 return { events };
490}
491
492/** True if itemId is any wood log. */
493export function isWoodLogItemId (itemId)
494{
495 return woodTierFromLogItemId(itemId) != null
496 || WOOD_TIER_ORDER.some((tier) => logItemIdForWood(tier) === itemId);
497}
498
499export { woodTierFromLogItemId, woodTierRank, findTinderboxSlot };