BlueGit

timfa questward

Files

questward / server / src / quests / runtime.js

runtime.js

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