BlueGit

timfa questward

Files

questward / server / src / quests / runtime.js

runtime.js

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