| 1 | import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
|
| 2 | import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
|
| 3 | import {
|
| 4 | countableObjectiveProgress,
|
| 5 | objectiveProgressFingerprint
|
| 6 | } from "../../../shared/quests/objectiveProgress.js";
|
| 7 | import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
|
| 8 | import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
|
| 9 | import { itemDefinition, itemDisplayName } from "../../../shared/definitions/items.js";
|
| 10 | import { applySkillXp, publicSkillsPayload } from "../../../shared/skills/state.js";
|
| 11 | import { skillLevel, SKILL_DEFINITIONS } from "../../../shared/definitions/skills.js";
|
| 12 | import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../../shared/quests/dialogueRewards.js";
|
| 13 | import {
|
| 14 | formatQuestBankRewardLetterBody,
|
| 15 | QUESTWARD_GIFT_AUTHOR,
|
| 16 | QUESTWARD_GIFT_ORG
|
| 17 | } from "../../../shared/courier/questRewardLetters.js";
|
| 18 | import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
|
| 19 | import { floorDiv } from "../world/coordinates.js";
|
| 20 | import { WorkerMessage } from "../simulation/protocol.js";
|
| 21 |
|
| 22 | /**
|
| 23 | * Quest progress + dialogue sessions (main simulation thread).
|
| 24 | */
|
| 25 | export class QuestRuntime
|
| 26 | {
|
| 27 | constructor ({ stateDb, content, simulation })
|
| 28 | {
|
| 29 | this.stateDb = stateDb;
|
| 30 | this.content = content;
|
| 31 | this.simulation = simulation;
|
| 32 | /** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
|
| 33 | this.sessions = new Map();
|
| 34 | }
|
| 35 |
|
| 36 | reloadContent ()
|
| 37 | {
|
| 38 | this.content.reload();
|
| 39 | }
|
| 40 |
|
| 41 | closeAllSessions ()
|
| 42 | {
|
| 43 | for (const characterId of [...this.sessions.keys()])
|
| 44 | { this.closeDialogue(characterId, "revision"); }
|
| 45 | }
|
| 46 |
|
| 47 | questSnapshot (characterId)
|
| 48 | {
|
| 49 | const states = this.stateDb.listQuestStates(characterId)
|
| 50 | .filter((row) => row.state !== "not-started");
|
| 51 | const quests = [];
|
| 52 | const playerView = this.playerViewFor(characterId);
|
| 53 | for (const row of states)
|
| 54 | {
|
| 55 | const def = this.content.quest(row.questId);
|
| 56 | if (!def)
|
| 57 | {
|
| 58 | quests.push({
|
| 59 | questId: row.questId,
|
| 60 | title: "Quest unavailable",
|
| 61 | orphaned: true,
|
| 62 | state: row.state,
|
| 63 | description: "",
|
| 64 | step: null,
|
| 65 | journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
|
| 66 | });
|
| 67 | continue;
|
| 68 | }
|
| 69 | const stepIndex = typeof row.state === "number" ? row.state : null;
|
| 70 | const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
|
| 71 | const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
|
| 72 | const ctx = stepDef
|
| 73 | ? this.buildConditionContext(characterId, playerView, row.questId)
|
| 74 | : null;
|
| 75 | quests.push({
|
| 76 | questId: def.questId,
|
| 77 | title: def.title,
|
| 78 | orphaned: false,
|
| 79 | state: row.state,
|
| 80 | description: def.description,
|
| 81 | step: stepDef
|
| 82 | ? {
|
| 83 | stepId: stepDef.stepId,
|
| 84 | title: stepDef.title,
|
| 85 | description: stepDef.description,
|
| 86 | objectives: stepDef.objectives.map((obj) =>
|
| 87 | {
|
| 88 | const done = completedObjectiveIds.includes(obj.objectiveId);
|
| 89 | const progress = countableObjectiveProgress(obj.when, ctx);
|
| 90 | return {
|
| 91 | objectiveId: obj.objectiveId,
|
| 92 | text: obj.text,
|
| 93 | done,
|
| 94 | current: progress?.current ?? null,
|
| 95 | required: progress?.required ?? null
|
| 96 | };
|
| 97 | })
|
| 98 | }
|
| 99 | : null,
|
| 100 | journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
|
| 101 | });
|
| 102 | }
|
| 103 | quests.sort((a, b) =>
|
| 104 | {
|
| 105 | const aDone = a.state === "completed" ? 1 : 0;
|
| 106 | const bDone = b.state === "completed" ? 1 : 0;
|
| 107 | if (aDone !== bDone)
|
| 108 | { return aDone - bDone; }
|
| 109 | return String(a.title).localeCompare(String(b.title));
|
| 110 | });
|
| 111 | return { quests };
|
| 112 | }
|
| 113 |
|
| 114 | playerViewFor (characterId)
|
| 115 | {
|
| 116 | const entityId = this.simulation.characterEntities.get(characterId | 0);
|
| 117 | const record = entityId != null ? this.simulation.directory.get(entityId) : null;
|
| 118 | const skills = this.stateDb.getSkills(characterId) ?? {};
|
| 119 | let hp = 1;
|
| 120 | let maxHp = 1;
|
| 121 | let stamina = 1;
|
| 122 | let maxStamina = 1;
|
| 123 | if (entityId != null && record)
|
| 124 | {
|
| 125 | const staminaComp = this.simulation.staminaOf(entityId);
|
| 126 | if (staminaComp)
|
| 127 | {
|
| 128 | stamina = Number(staminaComp.current) || 0;
|
| 129 | maxStamina = Math.max(1, Number(staminaComp.max) || 1);
|
| 130 | }
|
| 131 | const worker = this.simulation.workers[record.workerId];
|
| 132 | const view = worker?.call?.({
|
| 133 | type: WorkerMessage.inspect,
|
| 134 | entityId
|
| 135 | });
|
| 136 | if (view && view.health != null)
|
| 137 | {
|
| 138 | hp = Number(view.health) || 0;
|
| 139 | maxHp = Math.max(1, Number(view.maxHealth) || 1);
|
| 140 | }
|
| 141 | }
|
| 142 | return {
|
| 143 | tileX: record?.tileX | 0,
|
| 144 | tileY: record?.tileY | 0,
|
| 145 | dimensionId: record?.dimensionId ?? "overworld",
|
| 146 | skills,
|
| 147 | hp,
|
| 148 | maxHp,
|
| 149 | stamina,
|
| 150 | maxStamina
|
| 151 | };
|
| 152 | }
|
| 153 |
|
| 154 | buildConditionContext (characterId, playerView, activeQuestId = null)
|
| 155 | {
|
| 156 | const bag = this.#loadBag(characterId);
|
| 157 | const inventory = bag?.inventory ?? [];
|
| 158 | const tileX = playerView?.tileX | 0;
|
| 159 | const tileY = playerView?.tileY | 0;
|
| 160 | const dimensionId = playerView?.dimensionId ?? "overworld";
|
| 161 | const chunkX = floorDiv(tileX, CHUNK_SIZE);
|
| 162 | const chunkY = floorDiv(tileY, CHUNK_SIZE);
|
| 163 | const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
|
| 164 | return {
|
| 165 | tileX,
|
| 166 | tileY,
|
| 167 | chunkX,
|
| 168 | chunkY,
|
| 169 | dimensionId,
|
| 170 | hp: playerView?.hp ?? 0,
|
| 171 | maxHp: playerView?.maxHp ?? 1,
|
| 172 | stamina: playerView?.stamina ?? 0,
|
| 173 | maxStamina: playerView?.maxStamina ?? 1,
|
| 174 | countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
|
| 175 | questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
|
| 176 | dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
|
| 177 | dialogueTriggerLatched: (dialogueId, trigger) =>
|
| 178 | this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
|
| 179 | skillLevel: (skillId) => skillLevel(playerView?.skills ?? {}, skillId),
|
| 180 | hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
|
| 181 | killCount: (condition) =>
|
| 182 | {
|
| 183 | if (!questRow)
|
| 184 | { return 0; }
|
| 185 | return questRow.progress?.counters?.[killKey(condition)] | 0;
|
| 186 | },
|
| 187 | interactBlockDone: (condition) =>
|
| 188 | {
|
| 189 | if (!questRow)
|
| 190 | { return false; }
|
| 191 | return !!questRow.progress?.interacts?.[interactKey(condition)];
|
| 192 | }
|
| 193 | };
|
| 194 | }
|
| 195 |
|
| 196 | tryOpenDialogue (characterId, entityId, dialogueId)
|
| 197 | {
|
| 198 | const tree = this.content.dialogue(dialogueId);
|
| 199 | if (!tree)
|
| 200 | { return { ok: false, error: "Nothing to say." }; }
|
| 201 | this.closeDialogue(characterId, "replace");
|
| 202 | const playerView = this.playerViewFor(characterId);
|
| 203 | return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
|
| 204 | }
|
| 205 |
|
| 206 | chooseDialogue (characterId, triggerId)
|
| 207 | {
|
| 208 | const session = this.sessions.get(characterId | 0);
|
| 209 | if (!session)
|
| 210 | { return { ok: false, error: "No dialogue open." }; }
|
| 211 | if (session.phase === "lines")
|
| 212 | { return { ok: false, error: "Finish reading first." }; }
|
| 213 | if (session.phase === "rewards")
|
| 214 | { return { ok: false, error: "Finish reading first." }; }
|
| 215 | const tree = this.content.dialogue(session.dialogueId);
|
| 216 | if (!tree)
|
| 217 | {
|
| 218 | this.closeDialogue(characterId, "missing");
|
| 219 | return { ok: false, error: "Dialogue missing." };
|
| 220 | }
|
| 221 | const step = tree.steps.find((s) => s.stepId === session.stepId);
|
| 222 | if (!step || step.exit?.kind !== "triggers")
|
| 223 | { return { ok: false, error: "Cannot choose now." }; }
|
| 224 | const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
|
| 225 | if (!trigger)
|
| 226 | { return { ok: false, error: "Unknown choice." }; }
|
| 227 | const playerView = this.playerViewFor(characterId);
|
| 228 | const ctx = this.buildConditionContext(characterId, playerView);
|
| 229 | if (!evaluateConditionSet(trigger.when, ctx))
|
| 230 | { return { ok: false, error: "That choice is unavailable." }; }
|
| 231 | this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
|
| 232 | const events = [];
|
| 233 | this.#applyEffects(characterId, trigger.effects, playerView, events);
|
| 234 | this.#reevaluateQuests(characterId, playerView, events);
|
| 235 | if (!trigger.nextStepId)
|
| 236 | {
|
| 237 | const npcEntityId = session.entityId;
|
| 238 | this.sessions.delete(characterId | 0);
|
| 239 | events.push({ type: "dialogueClose", reason: "end", npcEntityId });
|
| 240 | return { ok: true, events };
|
| 241 | }
|
| 242 | return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
|
| 243 | }
|
| 244 |
|
| 245 | closeDialogue (characterId, reason = "close")
|
| 246 | {
|
| 247 | const id = characterId | 0;
|
| 248 | const session = this.sessions.get(id);
|
| 249 | if (!session)
|
| 250 | { return { events: [] }; }
|
| 251 | this.sessions.delete(id);
|
| 252 | return {
|
| 253 | events: [{
|
| 254 | type: "dialogueClose",
|
| 255 | reason,
|
| 256 | npcEntityId: session.entityId
|
| 257 | }]
|
| 258 | };
|
| 259 | }
|
| 260 |
|
| 261 | interruptDialogueForEntity (entityId)
|
| 262 | {
|
| 263 | const events = [];
|
| 264 | for (const [characterId, session] of [...this.sessions])
|
| 265 | {
|
| 266 | if (session.entityId === (entityId | 0))
|
| 267 | {
|
| 268 | const closed = this.closeDialogue(characterId, "attacked");
|
| 269 | events.push(...closed.events.map((e) => ({ ...e, characterId })));
|
| 270 | }
|
| 271 | }
|
| 272 | return events;
|
| 273 | }
|
| 274 |
|
| 275 | #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
|
| 276 | {
|
| 277 | const step = tree.steps.find((s) => s.stepId === stepId);
|
| 278 | if (!step)
|
| 279 | {
|
| 280 | this.sessions.delete(characterId | 0);
|
| 281 | priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
|
| 282 | return { ok: false, error: "Broken dialogue.", events: priorEvents };
|
| 283 | }
|
| 284 | this.stateDb.markDialogueHeard(characterId, tree.dialogueId, step.stepId);
|
| 285 | const events = [...priorEvents];
|
| 286 | const linePayloads = [];
|
| 287 | for (const line of step.lines)
|
| 288 | {
|
| 289 | this.#applyEffects(characterId, line.effects, playerView, events);
|
| 290 | linePayloads.push({ speaker: line.speaker, text: line.text });
|
| 291 | }
|
| 292 | // Stay open while the client pages lines; resolve exit only on dialogueAdvance.
|
| 293 | this.sessions.set(characterId | 0, {
|
| 294 | entityId: entityId | 0,
|
| 295 | dialogueId: tree.dialogueId,
|
| 296 | stepId: step.stepId,
|
| 297 | phase: "lines",
|
| 298 | pendingExit: step.exit ?? { kind: "end" }
|
| 299 | });
|
| 300 | events.push({
|
| 301 | type: "dialogueStep",
|
| 302 | dialogueId: tree.dialogueId,
|
| 303 | stepId: step.stepId,
|
| 304 | label: step.label,
|
| 305 | npcEntityId: entityId | 0,
|
| 306 | lines: linePayloads
|
| 307 | });
|
| 308 | this.#reevaluateQuests(characterId, playerView, events);
|
| 309 | return { ok: true, events };
|
| 310 | }
|
| 311 |
|
| 312 | /** Client finished reading all lines (or reward notices) of the current step. */
|
| 313 | advanceDialogue (characterId)
|
| 314 | {
|
| 315 | const session = this.sessions.get(characterId | 0);
|
| 316 | if (!session || (session.phase !== "lines" && session.phase !== "rewards"))
|
| 317 | { return { ok: false, error: "No dialogue lines to advance." }; }
|
| 318 | const tree = this.content.dialogue(session.dialogueId);
|
| 319 | if (!tree)
|
| 320 | {
|
| 321 | this.sessions.delete(characterId | 0);
|
| 322 | return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
|
| 323 | }
|
| 324 | const playerView = this.playerViewFor(characterId);
|
| 325 | const events = [];
|
| 326 |
|
| 327 | if (session.phase === "lines")
|
| 328 | {
|
| 329 | const step = tree.steps.find((s) => s.stepId === session.stepId);
|
| 330 | const rewardMessages = [
|
| 331 | ...this.#grantStepItemRewards(characterId, step, events),
|
| 332 | ...this.#grantStepQuestRewards(characterId, step, playerView, events)
|
| 333 | ];
|
| 334 | this.#reevaluateQuests(characterId, playerView, events);
|
| 335 | if (rewardMessages.length > 0)
|
| 336 | {
|
| 337 | session.phase = "rewards";
|
| 338 | events.push({
|
| 339 | type: "dialogueItemRewards",
|
| 340 | dialogueId: session.dialogueId,
|
| 341 | stepId: session.stepId,
|
| 342 | npcEntityId: session.entityId,
|
| 343 | messages: rewardMessages
|
| 344 | });
|
| 345 | return { ok: true, events };
|
| 346 | }
|
| 347 | }
|
| 348 |
|
| 349 | return this.#resolveDialogueExit(characterId, session, tree, playerView, events);
|
| 350 | }
|
| 351 |
|
| 352 | #resolveDialogueExit (characterId, session, tree, playerView, events)
|
| 353 | {
|
| 354 | const exit = session.pendingExit ?? { kind: "end" };
|
| 355 |
|
| 356 | if (exit.kind === "branches")
|
| 357 | {
|
| 358 | const ctx = this.buildConditionContext(characterId, playerView);
|
| 359 | let matched = null;
|
| 360 | for (const branch of exit.branches ?? [])
|
| 361 | {
|
| 362 | if (evaluateConditionSet(branch.when, ctx))
|
| 363 | {
|
| 364 | matched = branch;
|
| 365 | break;
|
| 366 | }
|
| 367 | }
|
| 368 | if (!matched || !matched.nextStepId)
|
| 369 | {
|
| 370 | this.#applyEffects(characterId, matched?.effects, playerView, events);
|
| 371 | const npcEntityId = session.entityId;
|
| 372 | this.sessions.delete(characterId | 0);
|
| 373 | events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
|
| 374 | return { ok: true, events };
|
| 375 | }
|
| 376 | this.#applyEffects(characterId, matched.effects, playerView, events);
|
| 377 | return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
|
| 378 | }
|
| 379 |
|
| 380 | if (exit.kind === "triggers")
|
| 381 | {
|
| 382 | const ctx = this.buildConditionContext(characterId, playerView);
|
| 383 | const triggers = (exit.triggers ?? [])
|
| 384 | .filter((t) => evaluateConditionSet(t.when, ctx))
|
| 385 | .map((t) => ({ trigger: t.trigger, text: t.text }));
|
| 386 | if (triggers.length === 0)
|
| 387 | {
|
| 388 | const npcEntityId = session.entityId;
|
| 389 | this.sessions.delete(characterId | 0);
|
| 390 | events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
|
| 391 | return { ok: true, events };
|
| 392 | }
|
| 393 | session.phase = "choices";
|
| 394 | session.pendingExit = null;
|
| 395 | events.push({
|
| 396 | type: "dialogueChoices",
|
| 397 | dialogueId: session.dialogueId,
|
| 398 | stepId: session.stepId,
|
| 399 | npcEntityId: session.entityId,
|
| 400 | triggers
|
| 401 | });
|
| 402 | return { ok: true, events };
|
| 403 | }
|
| 404 |
|
| 405 | const npcEntityId = session.entityId;
|
| 406 | this.sessions.delete(characterId | 0);
|
| 407 | events.push({ type: "dialogueClose", reason: "end", npcEntityId });
|
| 408 | return { ok: true, events };
|
| 409 | }
|
| 410 |
|
| 411 | /**
|
| 412 | * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
|
| 413 | */
|
| 414 | #grantStepItemRewards (characterId, step, events)
|
| 415 | {
|
| 416 | const rewards = step?.itemRewards ?? [];
|
| 417 | if (!rewards.length)
|
| 418 | { return []; }
|
| 419 | const bagParts = [];
|
| 420 | const bankParts = [];
|
| 421 | for (const reward of rewards)
|
| 422 | {
|
| 423 | const bag = this.#loadBag(characterId);
|
| 424 | if (!bag)
|
| 425 | { continue; }
|
| 426 | const itemId = reward.itemId | 0;
|
| 427 | const def = itemDefinition(itemId);
|
| 428 | const quantity = Math.max(1, Number(reward.quantity) || 1);
|
| 429 | const displayName = def?.displayName ?? `Item ${itemId}`;
|
| 430 | const stack = attachOrigins({
|
| 431 | itemId,
|
| 432 | quantity,
|
| 433 | origins: [{ origin: godsOrigin(), quantity }]
|
| 434 | });
|
| 435 | const result = insertStack(bag.inventory, stack, def);
|
| 436 | bag.inventory = result.slots;
|
| 437 | const intoBag = quantity - Math.max(0, result.remainder | 0);
|
| 438 | let intoBank = 0;
|
| 439 | if (result.remainder > 0)
|
| 440 | {
|
| 441 | const vaultResult = insertStackGrowable(
|
| 442 | bag.vault,
|
| 443 | attachOrigins({
|
| 444 | itemId,
|
| 445 | quantity: result.remainder,
|
| 446 | origins: [{ origin: godsOrigin(), quantity: result.remainder }]
|
| 447 | }),
|
| 448 | def
|
| 449 | );
|
| 450 | bag.vault = vaultResult.slots;
|
| 451 | intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
|
| 452 | }
|
| 453 | this.#persistBag(characterId, bag);
|
| 454 | events.push({ type: "inventoryDirty" });
|
| 455 | if (intoBag > 0)
|
| 456 | { bagParts.push({ displayName, quantity: intoBag }); }
|
| 457 | if (intoBank > 0)
|
| 458 | { bankParts.push({ displayName, quantity: intoBank }); }
|
| 459 | }
|
| 460 | const messages = [];
|
| 461 | const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
|
| 462 | const bankMsg = formatDialogueRewardMessage(bankParts, "bank");
|
| 463 | if (bagMsg)
|
| 464 | { messages.push(bagMsg); }
|
| 465 | if (bankMsg)
|
| 466 | { messages.push(bankMsg); }
|
| 467 | return messages;
|
| 468 | }
|
| 469 |
|
| 470 | /** Start step.questRewards; returns player-facing notices for newly started quests. */
|
| 471 | #grantStepQuestRewards (characterId, step, playerView, events)
|
| 472 | {
|
| 473 | const rewards = step?.questRewards ?? [];
|
| 474 | if (!rewards.length)
|
| 475 | { return []; }
|
| 476 | const titles = [];
|
| 477 | for (const questId of rewards)
|
| 478 | {
|
| 479 | const current = this.stateDb.getQuestState(characterId, questId);
|
| 480 | if (current.state !== "not-started")
|
| 481 | { continue; }
|
| 482 | const def = this.content.quest(questId);
|
| 483 | if (!def)
|
| 484 | { continue; }
|
| 485 | this.startQuest(characterId, questId, playerView, events);
|
| 486 | titles.push(def.title || def.questId);
|
| 487 | }
|
| 488 | const message = formatDialogueQuestRewardMessage(titles);
|
| 489 | return message ? [message] : [];
|
| 490 | }
|
| 491 |
|
| 492 | #loadBag (characterId)
|
| 493 | {
|
| 494 | const onlineId = this.simulation.characterEntities.get(characterId | 0);
|
| 495 | const bag = onlineId
|
| 496 | ? this.simulation.bagOf(onlineId)
|
| 497 | : this.stateDb.getBag(characterId);
|
| 498 | return bag;
|
| 499 | }
|
| 500 |
|
| 501 | #persistBag (characterId, bag)
|
| 502 | {
|
| 503 | this.stateDb.saveBag(characterId, bag);
|
| 504 | const onlineId = this.simulation.characterEntities.get(characterId | 0);
|
| 505 | if (onlineId)
|
| 506 | {
|
| 507 | this.simulation.applyBag?.(onlineId, bag);
|
| 508 | this.simulation.pushInventory?.(characterId, bag);
|
| 509 | }
|
| 510 | }
|
| 511 |
|
| 512 | #applyEffects (characterId, effects, playerView, events)
|
| 513 | {
|
| 514 | if (!Array.isArray(effects) || effects.length === 0)
|
| 515 | { return; }
|
| 516 | for (const effect of effects)
|
| 517 | {
|
| 518 | if (effect.kind === EffectKind.giveItem)
|
| 519 | {
|
| 520 | const bag = this.#loadBag(characterId);
|
| 521 | if (!bag)
|
| 522 | { continue; }
|
| 523 | const def = itemDefinition(effect.itemId | 0);
|
| 524 | const quantity = Math.max(1, Number(effect.quantity) || 1);
|
| 525 | const stack = attachOrigins({
|
| 526 | itemId: effect.itemId | 0,
|
| 527 | quantity,
|
| 528 | origins: [{ origin: godsOrigin(), quantity }]
|
| 529 | });
|
| 530 | if (effect.toBank)
|
| 531 | {
|
| 532 | const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
|
| 533 | bag.vault = vaultResult.slots;
|
| 534 | }
|
| 535 | else
|
| 536 | {
|
| 537 | const result = insertStack(bag.inventory, stack, def);
|
| 538 | bag.inventory = result.slots;
|
| 539 | if (result.remainder > 0)
|
| 540 | {
|
| 541 | const vaultResult = insertStackGrowable(
|
| 542 | bag.vault ?? [],
|
| 543 | attachOrigins({
|
| 544 | itemId: effect.itemId | 0,
|
| 545 | quantity: result.remainder,
|
| 546 | origins: [{ origin: godsOrigin(), quantity: result.remainder }]
|
| 547 | }),
|
| 548 | def
|
| 549 | );
|
| 550 | bag.vault = vaultResult.slots;
|
| 551 | }
|
| 552 | }
|
| 553 | this.#persistBag(characterId, bag);
|
| 554 | events.push({ type: "inventoryDirty" });
|
| 555 | }
|
| 556 | else if (effect.kind === EffectKind.takeItem)
|
| 557 | {
|
| 558 | const bag = this.#loadBag(characterId);
|
| 559 | if (!bag)
|
| 560 | { continue; }
|
| 561 | const taken = takeMatchingFromSlots(bag.inventory, {
|
| 562 | itemId: effect.itemId | 0,
|
| 563 | quantity: Math.max(1, Number(effect.quantity) || 1),
|
| 564 | compact: false
|
| 565 | });
|
| 566 | if (taken.ok)
|
| 567 | {
|
| 568 | bag.inventory = taken.slots;
|
| 569 | this.#persistBag(characterId, bag);
|
| 570 | events.push({ type: "inventoryDirty" });
|
| 571 | }
|
| 572 | }
|
| 573 | else if (effect.kind === EffectKind.giveXp)
|
| 574 | {
|
| 575 | const skills = this.stateDb.getSkills(characterId);
|
| 576 | if (skills)
|
| 577 | {
|
| 578 | applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
|
| 579 | this.stateDb.saveSkills(characterId, skills);
|
| 580 | if (playerView)
|
| 581 | { playerView.skills = skills; }
|
| 582 | events.push({ type: "skillsDirty" });
|
| 583 | }
|
| 584 | }
|
| 585 | else if (effect.kind === EffectKind.startQuest)
|
| 586 | { this.startQuest(characterId, effect.questId, playerView, events); }
|
| 587 | }
|
| 588 | }
|
| 589 |
|
| 590 | startQuest (characterId, questId, playerView, events = [])
|
| 591 | {
|
| 592 | const def = this.content.quest(questId);
|
| 593 | if (!def)
|
| 594 | { return; }
|
| 595 | const current = this.stateDb.getQuestState(characterId, questId);
|
| 596 | if (current.state !== "not-started")
|
| 597 | { return; }
|
| 598 | this.stateDb.saveQuestState(characterId, questId, 1, {
|
| 599 | completedObjectiveIds: [],
|
| 600 | counters: {},
|
| 601 | interacts: {}
|
| 602 | }, Date.now(), null);
|
| 603 | this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
|
| 604 | events.push({ type: "questsDirty" });
|
| 605 | this.#reevaluateQuests(characterId, playerView, events);
|
| 606 | }
|
| 607 |
|
| 608 | /**
|
| 609 | * Grant world-settings initial quests when the character has not started or completed them.
|
| 610 | */
|
| 611 | ensureInitialQuests (characterId, playerView = null, events = [])
|
| 612 | {
|
| 613 | const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
|
| 614 | for (const questId of list)
|
| 615 | { this.startQuest(characterId, questId, playerView, events); }
|
| 616 | return events;
|
| 617 | }
|
| 618 |
|
| 619 | /**
|
| 620 | * Re-check active quest objectives against live bag/position/etc.
|
| 621 | * Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills).
|
| 622 | */
|
| 623 | reevaluateQuests (characterId, playerView = null, events = [])
|
| 624 | {
|
| 625 | const view = playerView ?? this.playerViewFor(characterId);
|
| 626 | this.#reevaluateQuests(characterId, view, events);
|
| 627 | return events;
|
| 628 | }
|
| 629 |
|
| 630 | /** Apply initial quests to every character in state (settings save / apply). */
|
| 631 | grantInitialQuestsToAllCharacters ()
|
| 632 | {
|
| 633 | const events = [];
|
| 634 | for (const characterId of this.stateDb.listAllCharacterIds())
|
| 635 | { this.ensureInitialQuests(characterId, null, events); }
|
| 636 | return events;
|
| 637 | }
|
| 638 |
|
| 639 | /**
|
| 640 | * Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
|
| 641 | * @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
|
| 642 | */
|
| 643 | #grantQuestCompletionRewards (characterId, def, playerView, events)
|
| 644 | {
|
| 645 | const xp = [];
|
| 646 | const bagItems = [];
|
| 647 | const bankItems = [];
|
| 648 | const rewards = def?.rewards ?? [];
|
| 649 | for (const effect of rewards)
|
| 650 | {
|
| 651 | if (effect.kind === EffectKind.giveXp)
|
| 652 | {
|
| 653 | const amount = Math.max(0, Number(effect.amount) || 0) | 0;
|
| 654 | if (amount <= 0)
|
| 655 | { continue; }
|
| 656 | const skillId = String(effect.skillId ?? "").trim();
|
| 657 | if (!skillId)
|
| 658 | { continue; }
|
| 659 | const onlineId = this.simulation.characterEntities.get(characterId | 0);
|
| 660 | let skills = onlineId
|
| 661 | ? this.simulation.skillsOf(onlineId)
|
| 662 | : this.stateDb.getSkills(characterId);
|
| 663 | if (!skills)
|
| 664 | { skills = this.stateDb.getSkills(characterId); }
|
| 665 | if (!skills)
|
| 666 | { continue; }
|
| 667 | applySkillXp(skills, skillId, amount);
|
| 668 | this.stateDb.saveSkills(characterId, skills);
|
| 669 | if (playerView)
|
| 670 | { playerView.skills = skills; }
|
| 671 | if (onlineId)
|
| 672 | { this.simulation.applySkills?.(onlineId, skills); }
|
| 673 | const payload = publicSkillsPayload(skills);
|
| 674 | this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
|
| 675 | xp.push({
|
| 676 | skillId,
|
| 677 | displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
|
| 678 | amount
|
| 679 | });
|
| 680 | continue;
|
| 681 | }
|
| 682 | if (effect.kind !== EffectKind.giveItem)
|
| 683 | { continue; }
|
| 684 | const bag = this.#loadBag(characterId);
|
| 685 | if (!bag)
|
| 686 | { continue; }
|
| 687 | const itemId = effect.itemId | 0;
|
| 688 | const defItem = itemDefinition(itemId);
|
| 689 | const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
|
| 690 | const displayName = defItem
|
| 691 | ? itemDisplayName({ itemId, quantity }, defItem)
|
| 692 | : `Item ${itemId}`;
|
| 693 | const stack = attachOrigins({
|
| 694 | itemId,
|
| 695 | quantity,
|
| 696 | origins: [{ origin: godsOrigin(), quantity }]
|
| 697 | });
|
| 698 | let intoBag = 0;
|
| 699 | let intoBank = 0;
|
| 700 | if (effect.toBank)
|
| 701 | {
|
| 702 | const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
|
| 703 | bag.vault = vaultResult.slots;
|
| 704 | intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
|
| 705 | }
|
| 706 | else
|
| 707 | {
|
| 708 | const result = insertStack(bag.inventory, stack, defItem);
|
| 709 | bag.inventory = result.slots;
|
| 710 | intoBag = quantity - Math.max(0, result.remainder | 0);
|
| 711 | if (result.remainder > 0)
|
| 712 | {
|
| 713 | const vaultResult = insertStackGrowable(
|
| 714 | bag.vault ?? [],
|
| 715 | attachOrigins({
|
| 716 | itemId,
|
| 717 | quantity: result.remainder,
|
| 718 | origins: [{ origin: godsOrigin(), quantity: result.remainder }]
|
| 719 | }),
|
| 720 | defItem
|
| 721 | );
|
| 722 | bag.vault = vaultResult.slots;
|
| 723 | intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
|
| 724 | }
|
| 725 | }
|
| 726 | this.#persistBag(characterId, bag);
|
| 727 | events.push({ type: "inventoryDirty" });
|
| 728 | if (intoBag > 0)
|
| 729 | { bagItems.push({ displayName, quantity: intoBag, itemId }); }
|
| 730 | if (intoBank > 0)
|
| 731 | { bankItems.push({ displayName, quantity: intoBank, itemId }); }
|
| 732 | }
|
| 733 |
|
| 734 | if (bankItems.length)
|
| 735 | { this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
|
| 736 |
|
| 737 | return { xp, bagItems };
|
| 738 | }
|
| 739 |
|
| 740 | #dispatchQuestBankRewardLetter (characterId, def, bankItems)
|
| 741 | {
|
| 742 | const courier = this.simulation.courier;
|
| 743 | if (!courier?.enqueueSystemLetter)
|
| 744 | { return; }
|
| 745 | const row = this.stateDb.getCharacter?.(characterId);
|
| 746 | const characterDisplayName = row
|
| 747 | ? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
|
| 748 | : "Adventurer";
|
| 749 | const originTileX = row?.tile_x | 0;
|
| 750 | const originTileY = row?.tile_y | 0;
|
| 751 | const bank = courier.nearestBank?.(originTileX, originTileY);
|
| 752 | courier.enqueueSystemLetter({
|
| 753 | characterId: characterId | 0,
|
| 754 | originTileX: bank?.tileX ?? originTileX,
|
| 755 | originTileY: bank?.tileY ?? originTileY,
|
| 756 | authorDisplayName: QUESTWARD_GIFT_AUTHOR,
|
| 757 | authorOrganization: QUESTWARD_GIFT_ORG,
|
| 758 | body: formatQuestBankRewardLetterBody({
|
| 759 | characterDisplayName,
|
| 760 | questTitle: def?.title ?? def?.questId,
|
| 761 | items: bankItems
|
| 762 | })
|
| 763 | });
|
| 764 | }
|
| 765 |
|
| 766 | #reevaluateQuests (characterId, playerView, events)
|
| 767 | {
|
| 768 | const states = this.stateDb.listQuestStates(characterId)
|
| 769 | .filter((row) => typeof row.state === "number");
|
| 770 | for (const row of states)
|
| 771 | {
|
| 772 | const def = this.content.quest(row.questId);
|
| 773 | if (!def)
|
| 774 | { continue; }
|
| 775 | const stepDef = def.steps[row.state - 1];
|
| 776 | if (!stepDef)
|
| 777 | { continue; }
|
| 778 | const ctx = this.buildConditionContext(characterId, playerView, row.questId);
|
| 779 | const completed = new Set(row.progress?.completedObjectiveIds ?? []);
|
| 780 | const newlyDone = [];
|
| 781 | let changed = false;
|
| 782 | for (const obj of stepDef.objectives)
|
| 783 | {
|
| 784 | if (completed.has(obj.objectiveId))
|
| 785 | { continue; }
|
| 786 | if (evaluateConditionSet(obj.when, ctx))
|
| 787 | {
|
| 788 | completed.add(obj.objectiveId);
|
| 789 | newlyDone.push(obj);
|
| 790 | changed = true;
|
| 791 | }
|
| 792 | }
|
| 793 | const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
|
| 794 | const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
|
| 795 | if (!changed && !progressChanged)
|
| 796 | { continue; }
|
| 797 | for (const obj of newlyDone)
|
| 798 | {
|
| 799 | events.push({
|
| 800 | type: "questObjectiveComplete",
|
| 801 | questId: row.questId,
|
| 802 | objectiveId: obj.objectiveId,
|
| 803 | text: obj.text || "Objective"
|
| 804 | });
|
| 805 | }
|
| 806 | const progress = {
|
| 807 | ...row.progress,
|
| 808 | completedObjectiveIds: [...completed],
|
| 809 | progressFingerprint: fingerprint
|
| 810 | };
|
| 811 | const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
|
| 812 | if (!allDone)
|
| 813 | {
|
| 814 | this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
|
| 815 | events.push({ type: "questsDirty" });
|
| 816 | continue;
|
| 817 | }
|
| 818 | if (!changed)
|
| 819 | {
|
| 820 | // Progress-only update while already fully complete (should not happen).
|
| 821 | this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
|
| 822 | events.push({ type: "questsDirty" });
|
| 823 | continue;
|
| 824 | }
|
| 825 | this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
|
| 826 | const journal = this.stateDb.appendQuestJournal(
|
| 827 | characterId,
|
| 828 | row.questId,
|
| 829 | stepDef.stepId,
|
| 830 | stepDef.completionJournalText
|
| 831 | );
|
| 832 | const nextIndex = row.state + 1;
|
| 833 | if (nextIndex > def.steps.length)
|
| 834 | {
|
| 835 | const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
|
| 836 | this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
|
| 837 | events.push({
|
| 838 | type: "questComplete",
|
| 839 | questId: row.questId,
|
| 840 | title: def.title,
|
| 841 | xp: summary.xp,
|
| 842 | items: summary.bagItems
|
| 843 | });
|
| 844 | }
|
| 845 | else
|
| 846 | {
|
| 847 | const nextStep = def.steps[nextIndex - 1];
|
| 848 | this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
|
| 849 | completedObjectiveIds: [],
|
| 850 | counters: {},
|
| 851 | interacts: {},
|
| 852 | progressFingerprint: ""
|
| 853 | }, row.startedAt, null);
|
| 854 | this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
|
| 855 | events.push({
|
| 856 | type: "questStepComplete",
|
| 857 | questId: row.questId,
|
| 858 | title: def.title,
|
| 859 | journalText: journal?.text ?? null
|
| 860 | });
|
| 861 | }
|
| 862 | events.push({ type: "questsDirty" });
|
| 863 | }
|
| 864 | }
|
| 865 |
|
| 866 | noteKill (characterId, { mobTypeId, spawnerId })
|
| 867 | {
|
| 868 | const events = [];
|
| 869 | const playerView = this.playerViewFor(characterId);
|
| 870 | const states = this.stateDb.listQuestStates(characterId)
|
| 871 | .filter((row) => typeof row.state === "number");
|
| 872 | for (const row of states)
|
| 873 | {
|
| 874 | const def = this.content.quest(row.questId);
|
| 875 | const stepDef = def?.steps[row.state - 1];
|
| 876 | if (!stepDef)
|
| 877 | { continue; }
|
| 878 | let changed = false;
|
| 879 | const counters = { ...(row.progress?.counters ?? {}) };
|
| 880 | for (const obj of stepDef.objectives)
|
| 881 | {
|
| 882 | for (const clause of obj.when?.all ?? [])
|
| 883 | {
|
| 884 | const c = clause.condition;
|
| 885 | if (c?.kind !== "killCount")
|
| 886 | { continue; }
|
| 887 | const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId);
|
| 888 | const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId);
|
| 889 | if (!matchMob && !matchSpawner)
|
| 890 | { continue; }
|
| 891 | const key = killKey(c);
|
| 892 | counters[key] = (counters[key] | 0) + 1;
|
| 893 | changed = true;
|
| 894 | }
|
| 895 | }
|
| 896 | if (!changed)
|
| 897 | { continue; }
|
| 898 | this.stateDb.saveQuestState(characterId, row.questId, row.state, {
|
| 899 | ...row.progress,
|
| 900 | counters
|
| 901 | }, row.startedAt, row.completedAt);
|
| 902 | }
|
| 903 | this.#reevaluateQuests(characterId, playerView, events);
|
| 904 | return events;
|
| 905 | }
|
| 906 | }
|
| 907 |
|
| 908 | function journalPublic (row)
|
| 909 | {
|
| 910 | return {
|
| 911 | entryId: row.entry_id ?? row.entryId,
|
| 912 | questId: row.quest_id ?? row.questId,
|
| 913 | stepId: row.step_id ?? row.stepId,
|
| 914 | text: row.text,
|
| 915 | writtenAt: row.written_at ?? row.writtenAt
|
| 916 | };
|
| 917 | }
|
| 918 |
|
| 919 | function killKey (condition)
|
| 920 | {
|
| 921 | if (condition.spawnerId)
|
| 922 | { return `spawner:${condition.spawnerId}`; }
|
| 923 | return `mob:${condition.mobTypeId}`;
|
| 924 | }
|
| 925 |
|
| 926 | function interactKey (condition)
|
| 927 | {
|
| 928 | if (condition.tileX != null)
|
| 929 | { return `tile:${condition.tileX},${condition.tileY}`; }
|
| 930 | return `block:${condition.blockTypeId}`;
|
| 931 | }
|