import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js"; import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js"; import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js"; import { itemDefinition } from "../../../shared/definitions/items.js"; import { applySkillXp } from "../../../shared/skills/state.js"; import { skillLevel } from "../../../shared/definitions/skills.js"; import { formatDialogueRewardMessage } from "../../../shared/quests/dialogueRewards.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { floorDiv } from "../world/coordinates.js"; import { WorkerMessage } from "../simulation/protocol.js"; /** * Quest progress + dialogue sessions (main simulation thread). */ export class QuestRuntime { constructor ({ stateDb, content, simulation }) { this.stateDb = stateDb; this.content = content; this.simulation = simulation; /** @type {Map} */ this.sessions = new Map(); } reloadContent () { this.content.reload(); } closeAllSessions () { for (const characterId of [...this.sessions.keys()]) { this.closeDialogue(characterId, "revision"); } } questSnapshot (characterId) { const states = this.stateDb.listQuestStates(characterId) .filter((row) => row.state !== "not-started"); const quests = []; for (const row of states) { const def = this.content.quest(row.questId); if (!def) { quests.push({ questId: row.questId, title: "Quest unavailable", orphaned: true, state: row.state, description: "", step: null, journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic) }); continue; } const stepIndex = typeof row.state === "number" ? row.state : null; const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null; const completedObjectiveIds = row.progress?.completedObjectiveIds ?? []; quests.push({ questId: def.questId, title: def.title, orphaned: false, state: row.state, description: def.description, step: stepDef ? { stepId: stepDef.stepId, title: stepDef.title, description: stepDef.description, objectives: stepDef.objectives.map((obj) => ({ objectiveId: obj.objectiveId, text: obj.text, done: completedObjectiveIds.includes(obj.objectiveId) })) } : null, journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic) }); } quests.sort((a, b) => { const aDone = a.state === "completed" ? 1 : 0; const bDone = b.state === "completed" ? 1 : 0; if (aDone !== bDone) { return aDone - bDone; } return String(a.title).localeCompare(String(b.title)); }); return { quests }; } playerViewFor (characterId) { const entityId = this.simulation.characterEntities.get(characterId | 0); const record = entityId != null ? this.simulation.directory.get(entityId) : null; const skills = this.stateDb.getSkills(characterId) ?? {}; let hp = 1; let maxHp = 1; let stamina = 1; let maxStamina = 1; if (entityId != null && record) { const staminaComp = this.simulation.staminaOf(entityId); if (staminaComp) { stamina = Number(staminaComp.current) || 0; maxStamina = Math.max(1, Number(staminaComp.max) || 1); } const worker = this.simulation.workers[record.workerId]; const view = worker?.call?.({ type: WorkerMessage.inspect, entityId }); if (view && view.health != null) { hp = Number(view.health) || 0; maxHp = Math.max(1, Number(view.maxHealth) || 1); } } return { tileX: record?.tileX | 0, tileY: record?.tileY | 0, dimensionId: record?.dimensionId ?? "overworld", skills, hp, maxHp, stamina, maxStamina }; } buildConditionContext (characterId, playerView, activeQuestId = null) { const bag = this.#loadBag(characterId); const inventory = bag?.inventory ?? []; const tileX = playerView?.tileX | 0; const tileY = playerView?.tileY | 0; const dimensionId = playerView?.dimensionId ?? "overworld"; const chunkX = floorDiv(tileX, CHUNK_SIZE); const chunkY = floorDiv(tileY, CHUNK_SIZE); const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null; return { tileX, tileY, chunkX, chunkY, dimensionId, hp: playerView?.hp ?? 0, maxHp: playerView?.maxHp ?? 1, stamina: playerView?.stamina ?? 0, maxStamina: playerView?.maxStamina ?? 1, countItem: (itemId) => countItemInSlots(inventory, itemId | 0), questState: (questId) => this.stateDb.getQuestState(characterId, questId).state, dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId), dialogueTriggerLatched: (dialogueId, trigger) => this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger), skillLevel: (skillId) => skillLevel(playerView?.skills ?? {}, skillId), hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId), killCount: (condition) => { if (!questRow) { return 0; } return questRow.progress?.counters?.[killKey(condition)] | 0; }, interactBlockDone: (condition) => { if (!questRow) { return false; } return !!questRow.progress?.interacts?.[interactKey(condition)]; } }; } tryOpenDialogue (characterId, entityId, dialogueId) { const tree = this.content.dialogue(dialogueId); if (!tree) { return { ok: false, error: "Nothing to say." }; } this.closeDialogue(characterId, "replace"); const playerView = this.playerViewFor(characterId); return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView); } chooseDialogue (characterId, triggerId) { const session = this.sessions.get(characterId | 0); if (!session) { return { ok: false, error: "No dialogue open." }; } if (session.phase === "lines") { return { ok: false, error: "Finish reading first." }; } if (session.phase === "rewards") { return { ok: false, error: "Finish reading first." }; } const tree = this.content.dialogue(session.dialogueId); if (!tree) { this.closeDialogue(characterId, "missing"); return { ok: false, error: "Dialogue missing." }; } const step = tree.steps.find((s) => s.stepId === session.stepId); if (!step || step.exit?.kind !== "triggers") { return { ok: false, error: "Cannot choose now." }; } const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId)); if (!trigger) { return { ok: false, error: "Unknown choice." }; } const playerView = this.playerViewFor(characterId); const ctx = this.buildConditionContext(characterId, playerView); if (!evaluateConditionSet(trigger.when, ctx)) { return { ok: false, error: "That choice is unavailable." }; } this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger); const events = []; this.#applyEffects(characterId, trigger.effects, playerView, events); this.#reevaluateQuests(characterId, playerView, events); if (!trigger.nextStepId) { const npcEntityId = session.entityId; this.sessions.delete(characterId | 0); events.push({ type: "dialogueClose", reason: "end", npcEntityId }); return { ok: true, events }; } return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events); } closeDialogue (characterId, reason = "close") { const id = characterId | 0; const session = this.sessions.get(id); if (!session) { return { events: [] }; } this.sessions.delete(id); return { events: [{ type: "dialogueClose", reason, npcEntityId: session.entityId }] }; } interruptDialogueForEntity (entityId) { const events = []; for (const [characterId, session] of [...this.sessions]) { if (session.entityId === (entityId | 0)) { const closed = this.closeDialogue(characterId, "attacked"); events.push(...closed.events.map((e) => ({ ...e, characterId }))); } } return events; } #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = []) { const step = tree.steps.find((s) => s.stepId === stepId); if (!step) { this.sessions.delete(characterId | 0); priorEvents.push({ type: "dialogueClose", reason: "missing-step" }); return { ok: false, error: "Broken dialogue.", events: priorEvents }; } this.stateDb.markDialogueHeard(characterId, tree.dialogueId, step.stepId); const events = [...priorEvents]; const linePayloads = []; for (const line of step.lines) { this.#applyEffects(characterId, line.effects, playerView, events); linePayloads.push({ speaker: line.speaker, text: line.text }); } // Stay open while the client pages lines; resolve exit only on dialogueAdvance. this.sessions.set(characterId | 0, { entityId: entityId | 0, dialogueId: tree.dialogueId, stepId: step.stepId, phase: "lines", pendingExit: step.exit ?? { kind: "end" } }); events.push({ type: "dialogueStep", dialogueId: tree.dialogueId, stepId: step.stepId, label: step.label, npcEntityId: entityId | 0, lines: linePayloads }); this.#reevaluateQuests(characterId, playerView, events); return { ok: true, events }; } /** Client finished reading all lines (or reward notices) of the current step. */ advanceDialogue (characterId) { const session = this.sessions.get(characterId | 0); if (!session || (session.phase !== "lines" && session.phase !== "rewards")) { return { ok: false, error: "No dialogue lines to advance." }; } const tree = this.content.dialogue(session.dialogueId); if (!tree) { this.sessions.delete(characterId | 0); return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] }; } const playerView = this.playerViewFor(characterId); const events = []; if (session.phase === "lines") { const step = tree.steps.find((s) => s.stepId === session.stepId); const rewardMessages = this.#grantStepItemRewards( characterId, step, events ); this.#reevaluateQuests(characterId, playerView, events); if (rewardMessages.length > 0) { session.phase = "rewards"; events.push({ type: "dialogueItemRewards", dialogueId: session.dialogueId, stepId: session.stepId, npcEntityId: session.entityId, messages: rewardMessages }); return { ok: true, events }; } } return this.#resolveDialogueExit(characterId, session, tree, playerView, events); } #resolveDialogueExit (characterId, session, tree, playerView, events) { const exit = session.pendingExit ?? { kind: "end" }; if (exit.kind === "branches") { const ctx = this.buildConditionContext(characterId, playerView); let matched = null; for (const branch of exit.branches ?? []) { if (evaluateConditionSet(branch.when, ctx)) { matched = branch; break; } } if (!matched || !matched.nextStepId) { this.#applyEffects(characterId, matched?.effects, playerView, events); const npcEntityId = session.entityId; this.sessions.delete(characterId | 0); events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId }); return { ok: true, events }; } this.#applyEffects(characterId, matched.effects, playerView, events); return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events); } if (exit.kind === "triggers") { const ctx = this.buildConditionContext(characterId, playerView); const triggers = (exit.triggers ?? []) .filter((t) => evaluateConditionSet(t.when, ctx)) .map((t) => ({ trigger: t.trigger, text: t.text })); if (triggers.length === 0) { const npcEntityId = session.entityId; this.sessions.delete(characterId | 0); events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId }); return { ok: true, events }; } session.phase = "choices"; session.pendingExit = null; events.push({ type: "dialogueChoices", dialogueId: session.dialogueId, stepId: session.stepId, npcEntityId: session.entityId, triggers }); return { ok: true, events }; } const npcEntityId = session.entityId; this.sessions.delete(characterId | 0); events.push({ type: "dialogueClose", reason: "end", npcEntityId }); return { ok: true, events }; } /** * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices. */ #grantStepItemRewards (characterId, step, events) { const rewards = step?.itemRewards ?? []; if (!rewards.length) { return []; } const bagParts = []; const bankParts = []; for (const reward of rewards) { const bag = this.#loadBag(characterId); if (!bag) { continue; } const itemId = reward.itemId | 0; const def = itemDefinition(itemId); const quantity = Math.max(1, Number(reward.quantity) || 1); const displayName = def?.displayName ?? `Item ${itemId}`; const stack = attachOrigins({ itemId, quantity, origins: [{ origin: godsOrigin(), quantity }] }); const result = insertStack(bag.inventory, stack, def); bag.inventory = result.slots; const intoBag = quantity - Math.max(0, result.remainder | 0); let intoBank = 0; if (result.remainder > 0) { const vaultResult = insertStackGrowable( bag.vault, attachOrigins({ itemId, quantity: result.remainder, origins: [{ origin: godsOrigin(), quantity: result.remainder }] }), def ); bag.vault = vaultResult.slots; intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0); } this.#persistBag(characterId, bag); events.push({ type: "inventoryDirty" }); if (intoBag > 0) { bagParts.push({ displayName, quantity: intoBag }); } if (intoBank > 0) { bankParts.push({ displayName, quantity: intoBank }); } } const messages = []; const bagMsg = formatDialogueRewardMessage(bagParts, "bag"); const bankMsg = formatDialogueRewardMessage(bankParts, "bank"); if (bagMsg) { messages.push(bagMsg); } if (bankMsg) { messages.push(bankMsg); } return messages; } #loadBag (characterId) { const onlineId = this.simulation.characterEntities.get(characterId | 0); const bag = onlineId ? this.simulation.bagOf(onlineId) : this.stateDb.getBag(characterId); return bag; } #persistBag (characterId, bag) { this.stateDb.saveBag(characterId, bag); const onlineId = this.simulation.characterEntities.get(characterId | 0); if (onlineId) { this.simulation.applyBag?.(onlineId, bag); this.simulation.pushInventory?.(characterId, bag); } } #applyEffects (characterId, effects, playerView, events) { if (!Array.isArray(effects) || effects.length === 0) { return; } for (const effect of effects) { if (effect.kind === EffectKind.giveItem) { const bag = this.#loadBag(characterId); if (!bag) { continue; } const def = itemDefinition(effect.itemId | 0); const quantity = Math.max(1, Number(effect.quantity) || 1); const stack = attachOrigins({ itemId: effect.itemId | 0, quantity, origins: [{ origin: godsOrigin(), quantity }] }); const result = insertStack(bag.inventory, stack, def); bag.inventory = result.slots; if (result.remainder > 0) { const vaultResult = insertStackGrowable( bag.vault, attachOrigins({ itemId: effect.itemId | 0, quantity: result.remainder, origins: [{ origin: godsOrigin(), quantity: result.remainder }] }), def ); bag.vault = vaultResult.slots; } this.#persistBag(characterId, bag); events.push({ type: "inventoryDirty" }); } else if (effect.kind === EffectKind.takeItem) { const bag = this.#loadBag(characterId); if (!bag) { continue; } const taken = takeMatchingFromSlots(bag.inventory, { itemId: effect.itemId | 0, quantity: Math.max(1, Number(effect.quantity) || 1), compact: false }); if (taken.ok) { bag.inventory = taken.slots; this.#persistBag(characterId, bag); events.push({ type: "inventoryDirty" }); } } else if (effect.kind === EffectKind.giveXp) { const skills = this.stateDb.getSkills(characterId); if (skills) { applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0)); this.stateDb.saveSkills(characterId, skills); if (playerView) { playerView.skills = skills; } events.push({ type: "skillsDirty" }); } } else if (effect.kind === EffectKind.startQuest) { this.startQuest(characterId, effect.questId, playerView, events); } } } startQuest (characterId, questId, playerView, events = []) { const def = this.content.quest(questId); if (!def) { return; } const current = this.stateDb.getQuestState(characterId, questId); if (current.state !== "not-started") { return; } this.stateDb.saveQuestState(characterId, questId, 1, { completedObjectiveIds: [], counters: {}, interacts: {} }, Date.now(), null); this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events); events.push({ type: "questsDirty" }); this.#reevaluateQuests(characterId, playerView, events); } #reevaluateQuests (characterId, playerView, events) { const states = this.stateDb.listQuestStates(characterId) .filter((row) => typeof row.state === "number"); for (const row of states) { const def = this.content.quest(row.questId); if (!def) { continue; } const stepDef = def.steps[row.state - 1]; if (!stepDef) { continue; } const ctx = this.buildConditionContext(characterId, playerView, row.questId); const completed = new Set(row.progress?.completedObjectiveIds ?? []); let changed = false; for (const obj of stepDef.objectives) { if (completed.has(obj.objectiveId)) { continue; } if (evaluateConditionSet(obj.when, ctx)) { completed.add(obj.objectiveId); changed = true; } } if (!changed) { continue; } const progress = { ...row.progress, completedObjectiveIds: [...completed] }; const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId)); if (!allDone) { this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt); events.push({ type: "questsDirty" }); continue; } this.#applyEffects(characterId, stepDef.onComplete, playerView, events); const journal = this.stateDb.appendQuestJournal( characterId, row.questId, stepDef.stepId, stepDef.completionJournalText ); const nextIndex = row.state + 1; if (nextIndex > def.steps.length) { this.#applyEffects(characterId, def.rewards, playerView, events); this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now()); } else { const nextStep = def.steps[nextIndex - 1]; this.stateDb.saveQuestState(characterId, row.questId, nextIndex, { completedObjectiveIds: [], counters: {}, interacts: {} }, row.startedAt, null); this.#applyEffects(characterId, nextStep?.onEnter, playerView, events); } events.push({ type: "questStepComplete", questId: row.questId, title: def.title, journalText: journal?.text ?? null }); events.push({ type: "questsDirty" }); } } noteKill (characterId, { mobTypeId, spawnerId }) { const events = []; const playerView = this.playerViewFor(characterId); const states = this.stateDb.listQuestStates(characterId) .filter((row) => typeof row.state === "number"); for (const row of states) { const def = this.content.quest(row.questId); const stepDef = def?.steps[row.state - 1]; if (!stepDef) { continue; } let changed = false; const counters = { ...(row.progress?.counters ?? {}) }; for (const obj of stepDef.objectives) { for (const clause of obj.when?.all ?? []) { const c = clause.condition; if (c?.kind !== "killCount") { continue; } const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId); const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId); if (!matchMob && !matchSpawner) { continue; } const key = killKey(c); counters[key] = (counters[key] | 0) + 1; changed = true; } } if (!changed) { continue; } this.stateDb.saveQuestState(characterId, row.questId, row.state, { ...row.progress, counters }, row.startedAt, row.completedAt); } this.#reevaluateQuests(characterId, playerView, events); return events; } } function journalPublic (row) { return { entryId: row.entry_id ?? row.entryId, questId: row.quest_id ?? row.questId, stepId: row.step_id ?? row.stepId, text: row.text, writtenAt: row.written_at ?? row.writtenAt }; } function killKey (condition) { if (condition.spawnerId) { return `spawner:${condition.spawnerId}`; } return `mob:${condition.mobTypeId}`; } function interactKey (condition) { if (condition.tileX != null) { return `tile:${condition.tileX},${condition.tileY}`; } return `block:${condition.blockTypeId}`; }