BlueGit

timfa questward

Files

questward / server / src / quests / runtime.js

runtime.js

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