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