BlueGit

timfa questward

Files

questward / server / src / quests / runtime.js

runtime.js

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