BlueGit

timfa questward

Files

questward / server / src / firestarting / service.js

service.js

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