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