| 1 | import { Component } from "../ecs/components.js"; |
| 2 | import { BlockType } from "../../../shared/definitions/tiles.js"; |
| 3 | import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "../../../shared/definitions/craftingItems.js"; |
| 4 | import { |
| 5 | ashItemIdForWood, |
| 6 | logItemIdForWood |
| 7 | } from "../../../shared/definitions/woodItems.js"; |
| 8 | import { |
| 9 | campfireDurationMs, |
| 10 | firestartingDifficulty, |
| 11 | woodTierRank |
| 12 | } from "../../../shared/definitions/craftingStations.js"; |
| 13 | import { MATERIAL_DISPLAY_NAME, WOOD_TIER_ORDER } from "../../../shared/definitions/materialTiers.js"; |
| 14 | import { ItemFamilyId } from "../../../shared/definitions/tierFamilies.js"; |
| 15 | import { itemDefinition } from "../../../shared/definitions/items.js"; |
| 16 | import { SkillId, skillLevel } from "../../../shared/definitions/skills.js"; |
| 17 | import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js"; |
| 18 | import { rollSkill } from "../../../shared/combat/rolls.js"; |
| 19 | import { stackQuantity } from "../../../shared/items/inventory.js"; |
| 20 | import { attachOrigins, ashOrigin } from "../../../shared/items/origin.js"; |
| 21 | import { addGroundItem, publicGroundItem, removeGroundItem, bagView } from "../items/bags.js"; |
| 22 | import { chebyshev } from "../combat/service.js"; |
| 23 | import { tileToChunk, tileToLocal } from "../world/coordinates.js"; |
| 24 | import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; |
| 25 | |
| 26 | const FIRE_ATTEMPT_MS = 1100; |
| 27 | const MAX_LIGHT_ATTEMPTS = 3; |
| 28 | |
| 29 | function userError (message) |
| 30 | { |
| 31 | const error = new Error(message); |
| 32 | error.userFacing = true; |
| 33 | return error; |
| 34 | } |
| 35 | |
| 36 | function 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 | |
| 43 | function tileKey (tileX, tileY) |
| 44 | { |
| 45 | return `${tileX},${tileY}`; |
| 46 | } |
| 47 | |
| 48 | function ensureCampfires (world) |
| 49 | { |
| 50 | if (!world.campfireExpires) |
| 51 | { world.campfireExpires = new Map(); } |
| 52 | return world.campfireExpires; |
| 53 | } |
| 54 | |
| 55 | function ensureFireSessions (world) |
| 56 | { |
| 57 | if (!world.fireSessions) |
| 58 | { world.fireSessions = new Map(); } |
| 59 | return world.fireSessions; |
| 60 | } |
| 61 | |
| 62 | function clearFireSession (world, characterId) |
| 63 | { |
| 64 | ensureFireSessions(world).delete(characterId); |
| 65 | } |
| 66 | |
| 67 | function 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 | |
| 75 | function 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. */ |
| 92 | function 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 | |
| 115 | function 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 | |
| 137 | function 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 | |
| 160 | function 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 | |
| 167 | function 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 | item.stack.quantity = qty - 1; |
| 177 | events.push({ |
| 178 | type: "ground-item-appear", |
| 179 | ...publicGroundItem(item), |
| 180 | stack: item.stack, |
| 181 | droppedAt: item.droppedAt, |
| 182 | source: item.source, |
| 183 | expiresAt: item.expiresAt |
| 184 | }); |
| 185 | } |
| 186 | |
| 187 | function spawnAsh (world, tileX, tileY, woodTier, litByName, now, events) |
| 188 | { |
| 189 | const ashItemId = ashItemIdForWood(woodTier); |
| 190 | if (!ashItemId) |
| 191 | { return; } |
| 192 | const woodName = MATERIAL_DISPLAY_NAME[woodTier] ?? woodTier; |
| 193 | const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1); |
| 194 | const stack = attachOrigins({ |
| 195 | itemId: ashItemId, |
| 196 | quantity: 1, |
| 197 | origins: [{ |
| 198 | origin: ashOrigin(woodName, litByName), |
| 199 | quantity: 1 |
| 200 | }] |
| 201 | }); |
| 202 | const item = { |
| 203 | groundItemId, |
| 204 | tileX, |
| 205 | tileY, |
| 206 | stack, |
| 207 | droppedAt: now, |
| 208 | expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000), |
| 209 | source: "campfire-ash" |
| 210 | }; |
| 211 | addGroundItem(world, item); |
| 212 | events.push({ |
| 213 | type: "ground-item-appear", |
| 214 | ...publicGroundItem(item), |
| 215 | stack: item.stack, |
| 216 | droppedAt: item.droppedAt, |
| 217 | source: item.source, |
| 218 | expiresAt: item.expiresAt |
| 219 | }); |
| 220 | } |
| 221 | |
| 222 | /** |
| 223 | * Start lighting a ground log with a tinderbox (up to 3 skill rolls). |
| 224 | */ |
| 225 | export 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 (chebyshev(position.tileX, position.tileY, item.tileX, item.tileY) > 1) |
| 246 | { throw userError("You need to stand next to the logs."); } |
| 247 | |
| 248 | if (blockAt(world, item.tileX, item.tileY)) |
| 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 | woodTier, |
| 283 | difficulty, |
| 284 | attemptsLeft: MAX_LIGHT_ATTEMPTS, |
| 285 | nextAttemptAt: now, |
| 286 | toolItemId: CraftingItemId.tinderbox |
| 287 | }); |
| 288 | |
| 289 | return { |
| 290 | events: [], |
| 291 | private: bagView(world.ecs, handle) |
| 292 | }; |
| 293 | } |
| 294 | |
| 295 | export function cancelFirestarting (world, characterId) |
| 296 | { |
| 297 | clearFireSession(world, characterId); |
| 298 | } |
| 299 | |
| 300 | export function handleFirestartingCommand (world, sessionId, command, now = Date.now()) |
| 301 | { |
| 302 | if (command.type === "start-fire") |
| 303 | { |
| 304 | return startFire(world, sessionId, command.characterId, command.groundItemId, now); |
| 305 | } |
| 306 | if (command.type === "cancel-fire") |
| 307 | { |
| 308 | cancelFirestarting(world, command.characterId); |
| 309 | return { events: [] }; |
| 310 | } |
| 311 | return null; |
| 312 | } |
| 313 | |
| 314 | function succeedLight (world, handle, entityId, characterId, session, events, privates, now) |
| 315 | { |
| 316 | const item = world.groundItems.get(session.groundItemId); |
| 317 | if (!item || woodTierFromLogItemId(item.stack?.itemId) !== session.woodTier) |
| 318 | { |
| 319 | events.push({ |
| 320 | type: "command-error", |
| 321 | sessionId: session.sessionId, |
| 322 | message: "Those logs are gone." |
| 323 | }); |
| 324 | clearFireSession(world, characterId); |
| 325 | return; |
| 326 | } |
| 327 | if (blockAt(world, session.tileX, session.tileY)) |
| 328 | { |
| 329 | events.push({ |
| 330 | type: "command-error", |
| 331 | sessionId: session.sessionId, |
| 332 | message: "There is no room for a fire there." |
| 333 | }); |
| 334 | clearFireSession(world, characterId); |
| 335 | return; |
| 336 | } |
| 337 | |
| 338 | consumeOneGroundLog(world, item, events); |
| 339 | const expiresAt = now + campfireDurationMs(session.woodTier); |
| 340 | const litByName = characterDisplayName(world, handle); |
| 341 | const delta = placeBlock( |
| 342 | world, |
| 343 | session.tileX, |
| 344 | session.tileY, |
| 345 | BlockType.campfire, |
| 346 | session.woodTier, |
| 347 | { woodTier: session.woodTier, litAt: now, expiresAt, litByName } |
| 348 | ); |
| 349 | events.push(delta); |
| 350 | ensureCampfires(world).set(tileKey(session.tileX, session.tileY), { |
| 351 | tileX: session.tileX, |
| 352 | tileY: session.tileY, |
| 353 | woodTier: session.woodTier, |
| 354 | expiresAt, |
| 355 | litByName |
| 356 | }); |
| 357 | |
| 358 | const skills = world.ecs.get(handle, Component.skills); |
| 359 | let skillsChanged = false; |
| 360 | const levelUps = []; |
| 361 | if (skills?.xp) |
| 362 | { |
| 363 | const result = applySkillXp(skills, SkillId.firestarting, session.difficulty); |
| 364 | if (result.changed) |
| 365 | { skillsChanged = true; } |
| 366 | if (result.levelUp) |
| 367 | { levelUps.push(result.levelUp); } |
| 368 | } |
| 369 | if (skillsChanged) |
| 370 | { |
| 371 | events.push({ |
| 372 | type: "skills-updated", |
| 373 | entityId, |
| 374 | characterId, |
| 375 | skills: publicSkillsView(skills), |
| 376 | stored: storedSkillXp(skills), |
| 377 | levelUps |
| 378 | }); |
| 379 | } |
| 380 | privates.push({ characterId, bag: bagView(world.ecs, handle) }); |
| 381 | clearFireSession(world, characterId); |
| 382 | } |
| 383 | |
| 384 | /** |
| 385 | * Advance lighting attempts and expire campfires. |
| 386 | */ |
| 387 | export function stepFirestarting (world, now) |
| 388 | { |
| 389 | const events = []; |
| 390 | const privates = []; |
| 391 | events.push(...stepCampfireExpires(world, now).events); |
| 392 | |
| 393 | const sessions = ensureFireSessions(world); |
| 394 | for (const [characterId, session] of [...sessions.entries()]) |
| 395 | { |
| 396 | if (now < session.nextAttemptAt) |
| 397 | { continue; } |
| 398 | const entityId = world.characterEntities.get(characterId); |
| 399 | if (entityId == null) |
| 400 | { |
| 401 | clearFireSession(world, characterId); |
| 402 | continue; |
| 403 | } |
| 404 | const handle = world.ecs.handleOf(entityId); |
| 405 | if (world.ecs.has(handle, Component.dead)) |
| 406 | { |
| 407 | clearFireSession(world, characterId); |
| 408 | continue; |
| 409 | } |
| 410 | const position = world.ecs.get(handle, Component.position); |
| 411 | if (chebyshev(position.tileX, position.tileY, session.tileX, session.tileY) > 1) |
| 412 | { |
| 413 | clearFireSession(world, characterId); |
| 414 | continue; |
| 415 | } |
| 416 | |
| 417 | const item = world.groundItems.get(session.groundItemId); |
| 418 | if (!item) |
| 419 | { |
| 420 | events.push({ |
| 421 | type: "command-error", |
| 422 | sessionId: session.sessionId, |
| 423 | message: "Those logs are gone." |
| 424 | }); |
| 425 | clearFireSession(world, characterId); |
| 426 | continue; |
| 427 | } |
| 428 | |
| 429 | events.push({ |
| 430 | type: "gather-swing", |
| 431 | attackerId: entityId, |
| 432 | tileX: session.tileX, |
| 433 | tileY: session.tileY, |
| 434 | fromTileX: position.tileX, |
| 435 | fromTileY: position.tileY, |
| 436 | toolItemId: session.toolItemId, |
| 437 | swipe: false |
| 438 | }); |
| 439 | |
| 440 | const skills = world.ecs.get(handle, Component.skills); |
| 441 | const level = skillLevel(skills, SkillId.firestarting); |
| 442 | const roll = rollSkill(level, world.rng ?? Math.random); |
| 443 | session.attemptsLeft -= 1; |
| 444 | if (roll >= session.difficulty) |
| 445 | { |
| 446 | succeedLight(world, handle, entityId, characterId, session, events, privates, now); |
| 447 | continue; |
| 448 | } |
| 449 | if (session.attemptsLeft <= 0) |
| 450 | { |
| 451 | events.push({ |
| 452 | type: "command-error", |
| 453 | sessionId: session.sessionId, |
| 454 | message: "The sparks fail to catch." |
| 455 | }); |
| 456 | clearFireSession(world, characterId); |
| 457 | continue; |
| 458 | } |
| 459 | session.nextAttemptAt = now + FIRE_ATTEMPT_MS; |
| 460 | } |
| 461 | |
| 462 | return { events, privates }; |
| 463 | } |
| 464 | |
| 465 | export function stepCampfireExpires (world, now) |
| 466 | { |
| 467 | const expires = world.campfireExpires; |
| 468 | if (!expires?.size) |
| 469 | { return { events: [] }; } |
| 470 | const events = []; |
| 471 | for (const [key, entry] of [...expires.entries()]) |
| 472 | { |
| 473 | if (now < entry.expiresAt) |
| 474 | { continue; } |
| 475 | expires.delete(key); |
| 476 | const block = blockAt(world, entry.tileX, entry.tileY); |
| 477 | if (!block || block.typeId !== BlockType.campfire) |
| 478 | { continue; } |
| 479 | const delta = clearBlockAt(world, entry.tileX, entry.tileY); |
| 480 | if (delta) |
| 481 | { events.push(delta); } |
| 482 | spawnAsh( |
| 483 | world, |
| 484 | entry.tileX, |
| 485 | entry.tileY, |
| 486 | entry.woodTier, |
| 487 | entry.litByName, |
| 488 | now, |
| 489 | events |
| 490 | ); |
| 491 | } |
| 492 | return { events }; |
| 493 | } |
| 494 | |
| 495 | /** True if itemId is any wood log. */ |
| 496 | export function isWoodLogItemId (itemId) |
| 497 | { |
| 498 | return woodTierFromLogItemId(itemId) != null |
| 499 | || WOOD_TIER_ORDER.some((tier) => logItemIdForWood(tier) === itemId); |
| 500 | } |
| 501 | |
| 502 | export { woodTierFromLogItemId, woodTierRank, findTinderboxSlot }; |