BlueGit

timfa questward

Files

questward / server / src / firestarting / service.js

service.js

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