BlueGit

timfa questward

Files

questward / server / src / quests / runtime.js

runtime.js

runtime.js 31.6 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 if (exit.kind === "continue")
425 {
426 if (!exit.nextStepId)
427 {
428 const npcEntityId = session.entityId;
429 this.sessions.delete(characterId | 0);
430 events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });
431 return { ok: true, events };
432 }
433 return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);
434 }
435
436 const npcEntityId = session.entityId;
437 this.sessions.delete(characterId | 0);
438 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
439 return { ok: true, events };
440 }
441
442 /**
443 * Soft-take step.itemTakes from the bag (min(have, required)). Returns player-facing notices.
444 */
445 #takeStepItems (characterId, step, events)
446 {
447 const takes = step?.itemTakes ?? [];
448 if (!takes.length)
449 { return []; }
450 const parts = [];
451 for (const take of takes)
452 {
453 const bag = this.#loadBag(characterId);
454 if (!bag)
455 { continue; }
456 const itemId = take.itemId | 0;
457 const want = Math.max(1, Number(take.quantity) || 1);
458 const def = itemDefinition(itemId);
459 const displayName = def?.displayName ?? `Item ${itemId}`;
460 const result = takeMatchingUpToFromSlots(bag.inventory, {
461 itemId,
462 quantity: want,
463 compact: false
464 });
465 if (!result.ok || result.takenQuantity <= 0)
466 { continue; }
467 bag.inventory = result.slots;
468 this.#persistBag(characterId, bag);
469 events.push({ type: "inventoryDirty" });
470 parts.push({ displayName, quantity: result.takenQuantity });
471 }
472 const message = formatDialogueTakeMessage(parts);
473 return message ? [message] : [];
474 }
475
476 /**
477 * Grant step.itemRewards into bag (overflow → bank/vault). Returns player-facing notices.
478 */
479 #grantStepItemRewards (characterId, step, events)
480 {
481 const rewards = step?.itemRewards ?? [];
482 if (!rewards.length)
483 { return []; }
484 const bagParts = [];
485 const bankParts = [];
486 for (const reward of rewards)
487 {
488 const bag = this.#loadBag(characterId);
489 if (!bag)
490 { continue; }
491 const itemId = reward.itemId | 0;
492 const def = itemDefinition(itemId);
493 const quantity = Math.max(1, Number(reward.quantity) || 1);
494 const displayName = def?.displayName ?? `Item ${itemId}`;
495 const stack = attachOrigins({
496 itemId,
497 quantity,
498 origins: [{ origin: godsOrigin(), quantity }]
499 });
500 const result = insertStack(bag.inventory, stack, def);
501 bag.inventory = result.slots;
502 const intoBag = quantity - Math.max(0, result.remainder | 0);
503 let intoBank = 0;
504 if (result.remainder > 0)
505 {
506 const vaultResult = insertStackGrowable(
507 bag.vault,
508 attachOrigins({
509 itemId,
510 quantity: result.remainder,
511 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
512 }),
513 def
514 );
515 bag.vault = vaultResult.slots;
516 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
517 }
518 this.#persistBag(characterId, bag);
519 events.push({ type: "inventoryDirty" });
520 if (intoBag > 0)
521 { bagParts.push({ displayName, quantity: intoBag }); }
522 if (intoBank > 0)
523 { bankParts.push({ displayName, quantity: intoBank }); }
524 }
525 const messages = [];
526 const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
527 const bankMsg = formatDialogueRewardMessage(bankParts, "bank");
528 if (bagMsg)
529 { messages.push(bagMsg); }
530 if (bankMsg)
531 { messages.push(bankMsg); }
532 return messages;
533 }
534
535 /** Start step.questRewards; returns player-facing notices for newly started quests. */
536 #grantStepQuestRewards (characterId, step, playerView, events)
537 {
538 const rewards = step?.questRewards ?? [];
539 if (!rewards.length)
540 { return []; }
541 const titles = [];
542 for (const questId of rewards)
543 {
544 const current = this.stateDb.getQuestState(characterId, questId);
545 if (current.state !== "not-started")
546 { continue; }
547 const def = this.content.quest(questId);
548 if (!def)
549 { continue; }
550 this.startQuest(characterId, questId, playerView, events);
551 titles.push(def.title || def.questId);
552 }
553 const message = formatDialogueQuestRewardMessage(titles);
554 return message ? [message] : [];
555 }
556
557 #loadBag (characterId)
558 {
559 const onlineId = this.simulation.characterEntities.get(characterId | 0);
560 const bag = onlineId
561 ? this.simulation.bagOf(onlineId)
562 : this.stateDb.getBag(characterId);
563 return bag;
564 }
565
566 #playerDialogueIdentity (characterId)
567 {
568 const row = this.stateDb.getCharacter(characterId | 0);
569 return {
570 firstName: String(row?.first_name ?? "").trim(),
571 lastName: String(row?.last_name ?? "").trim(),
572 sex: row?.sex === "female" ? "female" : "male"
573 };
574 }
575
576 #persistBag (characterId, bag)
577 {
578 this.stateDb.saveBag(characterId, bag);
579 const onlineId = this.simulation.characterEntities.get(characterId | 0);
580 if (onlineId)
581 {
582 this.simulation.applyBag?.(onlineId, bag);
583 this.simulation.pushInventory?.(characterId, bag);
584 }
585 }
586
587 #applyEffects (characterId, effects, playerView, events)
588 {
589 if (!Array.isArray(effects) || effects.length === 0)
590 { return; }
591 for (const effect of effects)
592 {
593 if (effect.kind === EffectKind.giveItem)
594 {
595 const bag = this.#loadBag(characterId);
596 if (!bag)
597 { continue; }
598 const def = itemDefinition(effect.itemId | 0);
599 const quantity = Math.max(1, Number(effect.quantity) || 1);
600 const stack = attachOrigins({
601 itemId: effect.itemId | 0,
602 quantity,
603 origins: [{ origin: godsOrigin(), quantity }]
604 });
605 if (effect.toBank)
606 {
607 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, def);
608 bag.vault = vaultResult.slots;
609 }
610 else
611 {
612 const result = insertStack(bag.inventory, stack, def);
613 bag.inventory = result.slots;
614 if (result.remainder > 0)
615 {
616 const vaultResult = insertStackGrowable(
617 bag.vault ?? [],
618 attachOrigins({
619 itemId: effect.itemId | 0,
620 quantity: result.remainder,
621 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
622 }),
623 def
624 );
625 bag.vault = vaultResult.slots;
626 }
627 }
628 this.#persistBag(characterId, bag);
629 events.push({ type: "inventoryDirty" });
630 }
631 else if (effect.kind === EffectKind.takeItem)
632 {
633 const bag = this.#loadBag(characterId);
634 if (!bag)
635 { continue; }
636 const taken = takeMatchingFromSlots(bag.inventory, {
637 itemId: effect.itemId | 0,
638 quantity: Math.max(1, Number(effect.quantity) || 1),
639 compact: false
640 });
641 if (taken.ok)
642 {
643 bag.inventory = taken.slots;
644 this.#persistBag(characterId, bag);
645 events.push({ type: "inventoryDirty" });
646 }
647 }
648 else if (effect.kind === EffectKind.giveXp)
649 {
650 const skills = this.stateDb.getSkills(characterId);
651 if (skills)
652 {
653 applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
654 this.stateDb.saveSkills(characterId, skills);
655 if (playerView)
656 { playerView.skills = skills; }
657 events.push({ type: "skillsDirty" });
658 }
659 }
660 else if (effect.kind === EffectKind.startQuest)
661 { this.startQuest(characterId, effect.questId, playerView, events); }
662 }
663 }
664
665 startQuest (characterId, questId, playerView, events = [])
666 {
667 const def = this.content.quest(questId);
668 if (!def)
669 { return; }
670 const current = this.stateDb.getQuestState(characterId, questId);
671 if (current.state !== "not-started")
672 { return; }
673 this.stateDb.saveQuestState(characterId, questId, 1, {
674 completedObjectiveIds: [],
675 counters: {},
676 interacts: {}
677 }, Date.now(), null);
678 this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
679 events.push({ type: "questsDirty", characterId });
680 this.#reevaluateQuests(characterId, playerView, events);
681 }
682
683 /**
684 * Grant world-settings initial quests when the character has not started or completed them.
685 */
686 ensureInitialQuests (characterId, playerView = null, events = [])
687 {
688 const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
689 for (const questId of list)
690 { this.startQuest(characterId, questId, playerView, events); }
691 return events;
692 }
693
694 /**
695 * Re-check active quest objectives against live bag/position/etc.
696 * Used when opening the quest log (and wherever progress may have changed offline of dialogue/kills).
697 */
698 reevaluateQuests (characterId, playerView = null, events = [])
699 {
700 const view = playerView ?? this.playerViewFor(characterId);
701 this.#reevaluateQuests(characterId, view, events);
702 return events;
703 }
704
705 /** Apply initial quests to every character in state (settings save / apply). */
706 grantInitialQuestsToAllCharacters ()
707 {
708 const events = [];
709 for (const characterId of this.stateDb.listAllCharacterIds())
710 { this.ensureInitialQuests(characterId, null, events); }
711 return events;
712 }
713
714 /**
715 * Final quest rewards: XP + items (bag or bank). Banked items get a Questward letter.
716 * @returns {{ xp: { skillId: string, displayName: string, amount: number }[], bagItems: { displayName: string, quantity: number }[] }}
717 */
718 #grantQuestCompletionRewards (characterId, def, playerView, events)
719 {
720 const xp = [];
721 const bagItems = [];
722 const bankItems = [];
723 const rewards = def?.rewards ?? [];
724 for (const effect of rewards)
725 {
726 if (effect.kind === EffectKind.giveXp)
727 {
728 const amount = Math.max(0, Number(effect.amount) || 0) | 0;
729 if (amount <= 0)
730 { continue; }
731 const skillId = String(effect.skillId ?? "").trim();
732 if (!skillId)
733 { continue; }
734 const onlineId = this.simulation.characterEntities.get(characterId | 0);
735 let skills = onlineId
736 ? this.simulation.skillsOf(onlineId)
737 : this.stateDb.getSkills(characterId);
738 if (!skills)
739 { skills = this.stateDb.getSkills(characterId); }
740 if (!skills)
741 { continue; }
742 applySkillXp(skills, skillId, amount);
743 this.stateDb.saveSkills(characterId, skills);
744 if (playerView)
745 { playerView.skills = skills; }
746 if (onlineId)
747 { this.simulation.applySkills?.(onlineId, skills); }
748 const payload = publicSkillsPayload(skills);
749 this.simulation.pushSkills?.(characterId, payload.skills, payload.combatLevel);
750 xp.push({
751 skillId,
752 displayName: SKILL_DEFINITIONS[skillId]?.displayName ?? skillId,
753 amount
754 });
755 continue;
756 }
757 if (effect.kind !== EffectKind.giveItem)
758 { continue; }
759 const bag = this.#loadBag(characterId);
760 if (!bag)
761 { continue; }
762 const itemId = effect.itemId | 0;
763 const defItem = itemDefinition(itemId);
764 const quantity = Math.max(1, Number(effect.quantity) || 1) | 0;
765 const displayName = defItem
766 ? itemDisplayName({ itemId, quantity }, defItem)
767 : `Item ${itemId}`;
768 const stack = attachOrigins({
769 itemId,
770 quantity,
771 origins: [{ origin: godsOrigin(), quantity }]
772 });
773 let intoBag = 0;
774 let intoBank = 0;
775 if (effect.toBank)
776 {
777 const vaultResult = insertStackGrowable(bag.vault ?? [], stack, defItem);
778 bag.vault = vaultResult.slots;
779 intoBank = quantity - Math.max(0, vaultResult.remainder | 0);
780 }
781 else
782 {
783 const result = insertStack(bag.inventory, stack, defItem);
784 bag.inventory = result.slots;
785 intoBag = quantity - Math.max(0, result.remainder | 0);
786 if (result.remainder > 0)
787 {
788 const vaultResult = insertStackGrowable(
789 bag.vault ?? [],
790 attachOrigins({
791 itemId,
792 quantity: result.remainder,
793 origins: [{ origin: godsOrigin(), quantity: result.remainder }]
794 }),
795 defItem
796 );
797 bag.vault = vaultResult.slots;
798 intoBank = (result.remainder | 0) - Math.max(0, vaultResult.remainder | 0);
799 }
800 }
801 this.#persistBag(characterId, bag);
802 events.push({ type: "inventoryDirty" });
803 if (intoBag > 0)
804 { bagItems.push({ displayName, quantity: intoBag, itemId }); }
805 if (intoBank > 0)
806 { bankItems.push({ displayName, quantity: intoBank, itemId }); }
807 }
808
809 if (bankItems.length)
810 { this.#dispatchQuestBankRewardLetter(characterId, def, bankItems); }
811
812 return { xp, bagItems };
813 }
814
815 #dispatchQuestBankRewardLetter (characterId, def, bankItems)
816 {
817 const courier = this.simulation.courier;
818 if (!courier?.enqueueSystemLetter)
819 { return; }
820 const row = this.stateDb.getCharacter?.(characterId);
821 const characterDisplayName = row
822 ? `${row.first_name ?? ""} ${row.last_name ?? ""}`.trim()
823 : "Adventurer";
824 const originTileX = row?.tile_x | 0;
825 const originTileY = row?.tile_y | 0;
826 const originDim = row?.dimension_id ?? undefined;
827 const bank = courier.nearestBank?.(originTileX, originTileY, originDim);
828 courier.enqueueSystemLetter({
829 characterId: characterId | 0,
830 originTileX: bank?.tileX ?? originTileX,
831 originTileY: bank?.tileY ?? originTileY,
832 originDimensionId: bank?.dimensionId ?? originDim,
833 authorDisplayName: QUESTWARD_GIFT_AUTHOR,
834 authorOrganization: QUESTWARD_GIFT_ORG,
835 body: formatQuestBankRewardLetterBody({
836 characterDisplayName,
837 questTitle: def?.title ?? def?.questId,
838 items: bankItems
839 })
840 });
841 }
842
843 #reevaluateQuests (characterId, playerView, events)
844 {
845 const states = this.stateDb.listQuestStates(characterId)
846 .filter((row) => typeof row.state === "number");
847 for (const row of states)
848 {
849 const def = this.content.quest(row.questId);
850 if (!def)
851 { continue; }
852 const stepDef = def.steps[row.state - 1];
853 if (!stepDef)
854 { continue; }
855 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
856 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
857 const newlyDone = [];
858 let changed = false;
859 for (const obj of stepDef.objectives)
860 {
861 if (completed.has(obj.objectiveId))
862 { continue; }
863 if (evaluateConditionSet(obj.when, ctx))
864 {
865 completed.add(obj.objectiveId);
866 newlyDone.push(obj);
867 changed = true;
868 }
869 }
870 const fingerprint = objectiveProgressFingerprint(stepDef.objectives, ctx);
871 const progressChanged = fingerprint !== (row.progress?.progressFingerprint ?? "");
872 if (!changed && !progressChanged)
873 { continue; }
874 for (const obj of newlyDone)
875 {
876 events.push({
877 type: "questObjectiveComplete",
878 questId: row.questId,
879 objectiveId: obj.objectiveId,
880 text: obj.text || "Objective"
881 });
882 }
883 const progress = {
884 ...row.progress,
885 completedObjectiveIds: [...completed],
886 progressFingerprint: fingerprint
887 };
888 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
889 if (!allDone)
890 {
891 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
892 events.push({ type: "questsDirty", characterId });
893 continue;
894 }
895 if (!changed)
896 {
897 // Progress-only update while already fully complete (should not happen).
898 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
899 events.push({ type: "questsDirty", characterId });
900 continue;
901 }
902 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
903 const journal = this.stateDb.appendQuestJournal(
904 characterId,
905 row.questId,
906 stepDef.stepId,
907 stepDef.completionJournalText
908 );
909 const nextIndex = row.state + 1;
910 if (nextIndex > def.steps.length)
911 {
912 const summary = this.#grantQuestCompletionRewards(characterId, def, playerView, events);
913 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
914 events.push({
915 type: "questComplete",
916 questId: row.questId,
917 title: def.title,
918 xp: summary.xp,
919 items: summary.bagItems
920 });
921 }
922 else
923 {
924 const nextStep = def.steps[nextIndex - 1];
925 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
926 completedObjectiveIds: [],
927 counters: {},
928 interacts: {},
929 progressFingerprint: ""
930 }, row.startedAt, null);
931 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
932 events.push({
933 type: "questStepComplete",
934 questId: row.questId,
935 title: def.title,
936 journalText: journal?.text ?? null
937 });
938 }
939 events.push({ type: "questsDirty", characterId });
940 }
941 }
942
943 noteKill (characterId, { mobTypeId, spawnerId })
944 {
945 const events = [];
946 const playerView = this.playerViewFor(characterId);
947 const states = this.stateDb.listQuestStates(characterId)
948 .filter((row) => typeof row.state === "number");
949 for (const row of states)
950 {
951 const def = this.content.quest(row.questId);
952 const stepDef = def?.steps[row.state - 1];
953 if (!stepDef)
954 { continue; }
955 let changed = false;
956 const counters = { ...(row.progress?.counters ?? {}) };
957 for (const obj of stepDef.objectives)
958 {
959 for (const clause of obj.when?.all ?? [])
960 {
961 const c = clause.condition;
962 if (!matchesKillCondition(c, mobTypeId, spawnerId))
963 { continue; }
964 const key = killKey(c);
965 counters[key] = (counters[key] | 0) + 1;
966 changed = true;
967 }
968 }
969 if (!changed)
970 { continue; }
971 this.stateDb.saveQuestState(characterId, row.questId, row.state, {
972 ...row.progress,
973 counters
974 }, row.startedAt, row.completedAt);
975 }
976 this.#reevaluateQuests(characterId, playerView, events);
977 return events;
978 }
979}
980
981function journalPublic (row)
982{
983 return {
984 entryId: row.entry_id ?? row.entryId,
985 questId: row.quest_id ?? row.questId,
986 stepId: row.step_id ?? row.stepId,
987 text: row.text,
988 writtenAt: row.written_at ?? row.writtenAt
989 };
990}
991
992
993function matchesKillCondition (condition, mobTypeId, spawnerId)
994{
995 if (!condition || typeof condition !== "object")
996 { return false; }
997 if (condition.kind === "killMobFromSpawner")
998 {
999 if (condition.mobTypeId == null || condition.spawnerId == null || spawnerId == null)
1000 { return false; }
1001 return String(condition.mobTypeId) === String(mobTypeId)
1002 && String(condition.spawnerId) === String(spawnerId);
1003 }
1004 if (condition.kind === "killCount")
1005 {
1006 // Mob-type kills: match type. Legacy JSON may also use spawnerId alone.
1007 const matchMob = condition.mobTypeId != null && String(condition.mobTypeId) === String(mobTypeId);
1008 const matchSpawner = condition.spawnerId != null && String(condition.spawnerId) === String(spawnerId);
1009 return matchMob || matchSpawner;
1010 }
1011 return false;
1012}
1013
1014function killKey (condition)
1015{
1016 if (condition.spawnerId)
1017 { return `spawner:${condition.spawnerId}`; }
1018 return `mob:${condition.mobTypeId}`;
1019}
1020
1021function interactKey (condition)
1022{
1023 if (condition.tileX != null)
1024 { return `tile:${condition.tileX},${condition.tileY}`; }
1025 return `block:${condition.blockTypeId}`;
1026}