BlueGit

timfa questward

Files

questward / server / src / firestarting / service.js

service.js

service.js 13.5 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 { addGroundItem, 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 groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
197 const stack = attachOrigins({
198 itemId: ashItemId,
199 quantity: 1,
200 origins: [{
201 origin: ashOrigin(woodName, litByName),
202 quantity: 1
203 }]
204 });
205 const item = {
206 groundItemId,
207 tileX,
208 tileY,
209 stack,
210 droppedAt: now,
211 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
212 source: "campfire-ash"
213 };
214 addGroundItem(world, item);
215 events.push({
216 type: "ground-item-appear",
217 ...publicGroundItem(item),
218 stack: item.stack,
219 droppedAt: item.droppedAt,
220 source: item.source,
221 expiresAt: item.expiresAt
222 });
223}
224
225/**
226 * Start lighting a ground log with a tinderbox (up to 3 skill rolls).
227 */
228export function startFire (world, sessionId, characterId, groundItemId, now)
229{
230 const entityId = world.characterEntities.get(characterId);
231 if (entityId == null)
232 { throw userError("Character is not in the world."); }
233 const handle = world.ecs.handleOf(entityId);
234 const identity = world.ecs.get(handle, Component.networkIdentity);
235 if (!identity || identity.sessionId !== sessionId)
236 { throw userError("Character is not in the world."); }
237 if (world.ecs.has(handle, Component.dead))
238 { throw userError("You are dead."); }
239
240 const item = world.groundItems.get(groundItemId | 0);
241 if (!item)
242 { throw userError("That item is no longer on the ground."); }
243 const woodTier = woodTierFromLogItemId(item.stack?.itemId);
244 if (!woodTier)
245 { throw userError("You can only light wood logs."); }
246
247 const position = world.ecs.get(handle, Component.position);
248 if (!isAdjacentTile(position.tileX, position.tileY, item.tileX, item.tileY))
249 { throw userError("You need to stand next to the logs."); }
250
251 if (blockAt(world, item.tileX, item.tileY))
252 { throw userError("There is no room for a fire there."); }
253
254 const difficulty = firestartingDifficulty(woodTier);
255 const skills = world.ecs.get(handle, Component.skills);
256 const level = skillLevel(skills, SkillId.firestarting);
257 if (level < difficulty)
258 {
259 const label = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier;
260 throw userError(`Your Firestarting skill is too low to light ${label} logs.`);
261 }
262
263 const inventory = world.ecs.get(handle, Component.inventory);
264 const tinderSlot = findTinderboxSlot(inventory?.slots);
265 if (tinderSlot < 0)
266 { throw userError("You need a tinderbox with charges remaining."); }
267
268 const consumed = consumeTinderboxCharge(inventory.slots, tinderSlot);
269 if (!consumed.ok)
270 { throw userError("You need a tinderbox with charges remaining."); }
271 inventory.slots = consumed.slots;
272
273 clearFireSession(world, characterId);
274 if (world.ecs.has(handle, Component.gather))
275 { world.ecs.remove(handle, Component.gather); }
276 const path = world.ecs.get(handle, Component.path);
277 if (path)
278 { path.tiles = []; }
279
280 ensureFireSessions(world).set(characterId, {
281 sessionId,
282 groundItemId: item.groundItemId,
283 tileX: item.tileX,
284 tileY: item.tileY,
285 woodTier,
286 difficulty,
287 attemptsLeft: MAX_LIGHT_ATTEMPTS,
288 nextAttemptAt: now,
289 toolItemId: CraftingItemId.tinderbox
290 });
291
292 return {
293 events: [],
294 private: bagView(world.ecs, handle)
295 };
296}
297
298export function cancelFirestarting (world, characterId)
299{
300 clearFireSession(world, characterId);
301}
302
303export function handleFirestartingCommand (world, sessionId, command, now = Date.now())
304{
305 if (command.type === "start-fire")
306 {
307 return startFire(world, sessionId, command.characterId, command.groundItemId, now);
308 }
309 if (command.type === "cancel-fire")
310 {
311 cancelFirestarting(world, command.characterId);
312 return { events: [] };
313 }
314 return null;
315}
316
317function succeedLight (world, handle, entityId, characterId, session, events, privates, now)
318{
319 const item = world.groundItems.get(session.groundItemId);
320 if (!item || woodTierFromLogItemId(item.stack?.itemId) !== session.woodTier)
321 {
322 events.push({
323 type: "command-error",
324 sessionId: session.sessionId,
325 message: "Those logs are gone."
326 });
327 clearFireSession(world, characterId);
328 return;
329 }
330 if (blockAt(world, session.tileX, session.tileY))
331 {
332 events.push({
333 type: "command-error",
334 sessionId: session.sessionId,
335 message: "There is no room for a fire there."
336 });
337 clearFireSession(world, characterId);
338 return;
339 }
340
341 consumeOneGroundLog(world, item, events);
342 const expiresAt = now + campfireDurationMs(session.woodTier);
343 const litByName = characterDisplayName(world, handle);
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 );
352 events.push(delta);
353 ensureCampfires(world).set(tileKey(session.tileX, session.tileY), {
354 tileX: session.tileX,
355 tileY: session.tileY,
356 woodTier: session.woodTier,
357 expiresAt,
358 litByName
359 });
360
361 const skills = world.ecs.get(handle, Component.skills);
362 let skillsChanged = false;
363 const levelUps = [];
364 if (skills?.xp)
365 {
366 const result = applySkillXp(
367 skills,
368 SkillId.firestarting,
369 session.difficulty,
370 world.ecs.get(handle, Component.equipment)
371 );
372 if (result.changed)
373 { skillsChanged = true; }
374 if (result.levelUp)
375 { levelUps.push(result.levelUp); }
376 }
377 if (skillsChanged)
378 {
379 events.push({
380 type: "skills-updated",
381 entityId,
382 characterId,
383 ...publicSkillsPayload(skills),
384 stored: storedSkillXp(skills),
385 levelUps
386 });
387 }
388 privates.push({ characterId, bag: bagView(world.ecs, handle) });
389 clearFireSession(world, characterId);
390}
391
392/**
393 * Advance lighting attempts and expire campfires.
394 */
395export function stepFirestarting (world, now)
396{
397 const events = [];
398 const privates = [];
399 events.push(...stepCampfireExpires(world, now).events);
400
401 const sessions = ensureFireSessions(world);
402 for (const [characterId, session] of [...sessions.entries()])
403 {
404 if (now < session.nextAttemptAt)
405 { continue; }
406 const entityId = world.characterEntities.get(characterId);
407 if (entityId == null)
408 {
409 clearFireSession(world, characterId);
410 continue;
411 }
412 const handle = world.ecs.handleOf(entityId);
413 if (world.ecs.has(handle, Component.dead))
414 {
415 clearFireSession(world, characterId);
416 continue;
417 }
418 const position = world.ecs.get(handle, Component.position);
419 if (!isAdjacentTile(position.tileX, position.tileY, session.tileX, session.tileY))
420 {
421 clearFireSession(world, characterId);
422 continue;
423 }
424
425 const item = world.groundItems.get(session.groundItemId);
426 if (!item)
427 {
428 events.push({
429 type: "command-error",
430 sessionId: session.sessionId,
431 message: "Those logs are gone."
432 });
433 clearFireSession(world, characterId);
434 continue;
435 }
436
437 events.push({
438 type: "gather-swing",
439 attackerId: entityId,
440 tileX: session.tileX,
441 tileY: session.tileY,
442 fromTileX: position.tileX,
443 fromTileY: position.tileY,
444 toolItemId: session.toolItemId,
445 swipe: false
446 });
447
448 const skills = world.ecs.get(handle, Component.skills);
449 const level = skillLevel(skills, SkillId.firestarting);
450 const roll = rollSkill(level, world.rng ?? Math.random);
451 session.attemptsLeft -= 1;
452 if (roll >= session.difficulty)
453 {
454 succeedLight(world, handle, entityId, characterId, session, events, privates, now);
455 continue;
456 }
457 if (session.attemptsLeft <= 0)
458 {
459 events.push({
460 type: "command-error",
461 sessionId: session.sessionId,
462 message: "The sparks fail to catch."
463 });
464 clearFireSession(world, characterId);
465 continue;
466 }
467 session.nextAttemptAt = now + FIRE_ATTEMPT_MS;
468 }
469
470 return { events, privates };
471}
472
473export function stepCampfireExpires (world, now)
474{
475 const expires = world.campfireExpires;
476 if (!expires?.size)
477 { return { events: [] }; }
478 const events = [];
479 for (const [key, entry] of [...expires.entries()])
480 {
481 if (now < entry.expiresAt)
482 { continue; }
483 expires.delete(key);
484 const block = blockAt(world, entry.tileX, entry.tileY);
485 if (!block || block.typeId !== BlockType.campfire)
486 { continue; }
487 const delta = clearBlockAt(world, entry.tileX, entry.tileY);
488 if (delta)
489 { events.push(delta); }
490 spawnAsh(
491 world,
492 entry.tileX,
493 entry.tileY,
494 entry.woodTier,
495 entry.litByName,
496 now,
497 events
498 );
499 }
500 return { events };
501}
502
503/** True if itemId is any wood log. */
504export function isWoodLogItemId (itemId)
505{
506 return woodTierFromLogItemId(itemId) != null
507 || WOOD_TIER_ORDER.some((tier) => logItemIdForWood(tier) === itemId);
508}
509
510export { woodTierFromLogItemId, woodTierRank, findTinderboxSlot };