BlueGit

timfa questward

Files

questward / docs / QUESTS.md

QUESTS.md

QUESTS.md 16.2 KiB Download Raw

Quests & NPC dialogue (world editor)

Status: not implemented (design only) Related: docs/FEATURES.md (Quests, Mob definitions), docs/SCRIPTS.md (parity reminder for future script verbs), server authority rules

Quests and NPC dialogue are admin-authored content. Authors create and edit them entirely in the world editor. Runtime evaluation is server-authoritative; clients only display dialogue UI and quest log snapshots.

This document is the product + data + editor spec for implementation.

---

1. Goals

  • Author quests and dialogue trees as world-scoped assets (editors under World settings).
  • Assign a dialogue to a humanoid spawner by reference (dialogueId); show assignment counts; support unique dialogues.
  • Progress quests via objectives with shared multi-condition sets (including negations) and per-step journal text.
  • Dialogue: line gifts, player-choice triggers, or auto-branches; track dialogueHeard per step; interrupt on attack.
  • Player Quests UI: list + split detail (journal | step/objectives).
  • Fail safe: broken references fail closed; editor validation catches unique/assignment rules.

---

2. Persistence & identity

AssetStorageApply model
Quest definitionsworld.sqlite (revisioned with map)Editor save → pending; Apply now → live
Dialogue treesworld.sqlite (revisioned with map) — not embedded in chunk JSONSame as quests
Spawner → dialogue linkChunk spawner config.dialogueId (string \null)Saved with the chunk
Quest progressstate.sqlite (questState)Live
Dialogue heardstate.sqlite (dialogueHeard)Live

2.1 IDs

  • Quest id: stable slug (deliver-tin-ore). Prefer immutable after publish.
  • Quest step id: stable within quest; conditions also use 1-based index in steps[] (§4).
  • Dialogue id: stable world-scoped id (smith-intro). Keys dialogueHeard, conditions, spawner assignment.
  • Dialogue step id / trigger id: stable within that dialogue.
  • NPC reference in quests: prefer spawner id + optional display-name hint — not transient entity ids.

2.2 World settings: Quests & Dialogues editors

In the world editor chrome, place Quests and Dialogues as separate buttons directly under the Settings button (same control stack, not tabs inside the Settings modal).

ButtonPurpose
SettingsExisting world settings
QuestsCRUD all quest defs (id, title, steps, objectives, rewards, validation)
DialoguesCRUD all dialogue trees (id, unique flag, steps, exits, validation)

Both editors are world-global (not per-chunk). Saves go through the same admin auth + revision story as other authored world data.

Dialogues list columns: id, label/title, step count, unique, assigned spawner count, validation warnings.

Delete dialogue: warn if any spawner still references it; optionally block delete until unassigned.

2.3 Spawner assignment

On a humanoid / talkable spawner:

  • Dropdown: Dialogue → none, or pick from world dialogue list (show id + unique badge).
  • Stores config.dialogueId only (no inline tree on the spawner).

Assignment count: Dialogues editor shows how many spawners currently reference each dialogueId (scan loaded/pending world chunks, or maintain an index on save). Click-through list of assignees (chunk + spawner label) is nice-to-have in v1.

2.4 Unique dialogues

DialogueTree.unique: boolean   // default false

When unique === true:

1. At most one spawner in the world may have config.dialogueId equal to that id. 2. That spawner’s maxAlive must be 1 (editor clamps / blocks save otherwise; server normalize rejects Apply if violated).

Editor UX:

  • Toggling Unique on while 2+ spawners assigned → block or offer “unassign others / cancel”.
  • Assigning a unique dialogue to a second spawner → block with clear error.
  • Setting maxAlive > 1 on a spawner that holds a unique dialogue → block or force maxAlive = 1.

Non-unique dialogues may be shared by many spawners (and many alive NPCs); dialogueHeard is still keyed by dialogueId+stepId (shared script progress).

---

3. Quest definition shape

Quest {
  questId: string
  title: string
  description: string          // player-facing log blurb (in-universe)
  steps: Step[]                // ordered progression
  rewards?: Reward[]           // granted on final step complete
  cancelable?: boolean         // default false in v1
}

3.1 Steps & objectives

A quest advances one step at a time. Each step has one or more objectives. Each objective has a player-facing text and a ConditionSet (multiple conditions with optional negation). The step completes only when all objectives on that step are done (AND).

Step {
  stepId: string
  title: string
  description: string
  completionJournalText: string
  objectives: Objective[]            // ≥ 1; all must complete
  onEnter?: Effect[]
  onComplete?: Effect[]
}

Objective {
  objectiveId: string
  text: string                       // HUD / detail line
  when: ConditionSet                 // objective complete when set passes (or event latch inside set)
}

Advancement:

1. While a step is active, the server tracks which objectiveIds are satisfied. 2. When every objective on the step is complete → append journal line → state n → n+1 or completed + rewards → show toast “Quest objectives achieved”. Clicking the toast opens the Quests detail modal on that quest. 3. Client: completed objectives struck through.

3.2 Condition sets (quests + dialogue)

Shared in shared/. Evaluated only on the server.

ConditionSet {
  all: ConditionClause[]     // every clause must pass (AND); empty = always true
}

ConditionClause {
  not?: boolean              // default false; if true, invert the condition result
  condition: Condition
}

Semantics: all clauses AND-ed. “Has item X, but not quest completed Y” → two clauses, second with not: true (or use a dedicated negative kind — prefer not on the clause so every kind is invertible).

Used by:

  • quest objectives (when)
  • dialogue triggers (when — hide if fail)
  • dialogue auto-branches (when — first branch whose set passes)

Editor: condition picker rows with a NOT toggle per row; add/remove rows.

Condition kinds

KindFieldsMeaning
hasItemitemId, quantity (≥ 1)Bag (not vault) has ≥ N
atTiletileX, tileYExact tile
nearTiletileX, tileY, range (≥ 1)Chebyshev ≤ range
inRectminTileX, minTileY, maxTileX, maxTileYInclusive AABB
atChunkchunkX, chunkYPlayer chunk
questStatequestId, stateEquals not-started \completed \number n
questStepAtLeastquestId, step (≥ 1)Active index ≥ step or completed
dialogueHearddialogueId, stepIdHeard row exists
dialogueTriggerdialogueId, triggerLatch: player chose that trigger (quest objectives)
hpAtLeastamount (≥ 0)Current HP ≥ amount
staminaAtLeastamount (≥ 0)Current stamina ≥ amount
hpPercentAtLeastpercent (0–100)currentHP / maxHP × 100 ≥ percent
staminaPercentAtLeastpercent (0–100)currentStamina / maxStamina × 100 ≥ percent
skillLevelAtLeastskillId, level (1–99)skillLevel(skills, skillId) ≥ level
killCountmobTypeId or spawnerId, count NKills while this quest step active
interactBlocktile and/or blockTypeIdSuccessful interact (once per quest step)

Notes:

  • Prefer not + hasItem over a separate lacksItem kind (legacy alias ok). Same for dialogueNotHeard → not + dialogueHeard.
  • Thresholds use ≥ (“above or equal”); document in editor labels as “at least”.
  • Max HP / max stamina = same formulas the play sim already uses for the character.
  • Unknown ids → clause fails closed (raw condition false; with not, that becomes true — authors should avoid dangling ids; validation warns).
  • Kill attribution = existing combat kill credit.

3.3 Rewards & effects (v1)

KindFields
giveItemitemId, quantity
giveXpskillId, amount
takeItemitemId, quantity
startQuestquestId

Sources: quest onEnter / onComplete, dialogue line, trigger, branch. Full bag → vault via carrier pigeon.

---

4. Character quest state & journal

4.0 Quest state

QuestStateValue = "not-started" | number | "completed"
// number = 1-based index of current incomplete step
CharacterQuest {
  questId: string
  state: QuestStateValue
  completedObjectiveIds: string[]
  counters: { [key: string]: number }
  startedAt?, completedAt?
}

Missing row ⇒ not-started. Conditions read state only; counters/objectives are runtime detail for UI + event objectives.

4.0b Dialogue heard

dialogueHeard (characterId, dialogueId, stepId, heardAt)
UNIQUE (characterId, dialogueId, stepId)

Insert on step enter (first time). Permanent in v1. Gate repeat gifts with when sets (not + dialogueHeard, not + hasItem, etc.).

4.0c Journal

QuestJournalEntry { questId, stepId, text, writtenAt }

Append-only; text frozen at write time.

---

4.1 Player UI — Quests

  • Quests HUD control → list modal: active (state number) first, completed at bottom; hide not-started.
  • Detail modal: left journal (this quest), right step description + objectives (strikethrough when done).
  • Step-complete toast: text “Quest objectives achieved”. Click → open quest detail for the quest that just advanced (same modal stack as the Quests button).

---

5. Dialogue (world asset + spawner link)

5.1 Shape

DialogueTree {
  dialogueId: string
  label: string                   // editor list title
  unique: boolean                 // default false; see §2.4
  steps: DialogueStep[]
  entryStepId?: string
}

DialogueStep {
  stepId: string
  label: string
  lines: DialogueLine[]
  exit:
    | { kind: "triggers", triggers: DialogueTrigger[] }
    | { kind: "branches", branches: DialogueBranch[] }
    | { kind: "end" }
}

DialogueLine {
  speaker: "npc" | "player"
  text: string
  effects?: Effect[]
}

DialogueTrigger {
  trigger: string
  label: string                   // editor
  text: string                    // player button
  nextStepId: string | null       // null → end
  when?: ConditionSet             // hide if fail; omit = always show
  effects?: Effect[]
}

DialogueBranch {
  label?: string
  when: ConditionSet              // empty all[] = always
  nextStepId: string | null
  effects?: Effect[]
}

End rules: null nextStepId, exit.kind: "end", no matching branch, or no visible triggers → close dialogue.

5.2 Runtime

1. Talk to NPC whose spawner has dialogueId → load world DialogueTree → open entryStepId. 2. Enter step → insert dialogueHeard if new → play lines (apply line effects). 3. Triggers / branches / end as authored. 4. Interrupt: if the NPC is attacked (takes a hostile hit / combat engagement against it) while a player has this dialogue open → immediately close that dialogue session (no further lines, choices, or pending line effects). Re-talk required. Does not roll back already-applied effects or heard rows.

5.3 Editor (Dialogues panel)

  • List + inspector (graph canvas = v1.1).
  • Per dialogue: id, label, unique, assignment count, steps, exit modes, shared condition-set picker (with NOT).
  • Validation: unique rules (§2.4), missing refs, empty texts, unreachable steps.

5.4 Spawner modal

Humanoid: Dialogue dropdown bound to world dialogues (not an inline tree editor). Link to “Open in Dialogues editor” optional.

---

6. How quests start

startQuest effect → not-started → 1. Block if already numeric or completed (v1 no repeats).

---

7. Implementation plan (phased)

1. Shared Condition / ConditionSet / Effect in shared/. 2. World DB: quest defs + dialogue trees; state: questState, dialogueHeard, journal. 3. World settings Quests + Dialogues editors; spawner dialogueId + unique/maxAlive validation; assignment counts. 4. Editor unsaved-chunk guard (§9) — may already ship. 5. Runtime dialogue + combat interrupt; line/trigger/branch effects. 6. Quest engine + Quests HUD. 7. Apply revision + tests (conditions+NOT, unique, interrupt, heard, journal).

---

8. Edge cases (resolved)

TopicDecision
Unique + 2 assigneesEditor/server reject until ≤ 1
Unique + maxAlive ≠ 1Reject / clamp to 1
Mark unique while assigned elsewhereMust unassign others first
Shared (non-unique) dialogueMany spawners OK; heard shared by dialogueId
Spawner dialogueId missing treeTalk no-ops / error log; fail closed
NPC attacked mid-dialogueSession closes immediately
Player walks away / disconnectClose session (no progress loss beyond already applied)
not + unknown idRaw false → NOT true — validation must warn on unknown ids
ThresholdsAll “at least” (≥)
Parallel questsYes; soft cap ~20 active
One step per questYes (single numeric state)
Apply mid-dialogueClose sessions

8.1 Open product choices (see §12)

Small list of remaining decisions before / during implementation — none are architectural blockers if defaults in §12 are accepted.

---

9. World editor: unsaved chunk navigation & Save affordance

Independent of quests; ship with this plan’s commit.

9.1 Dirty state

  • Baseline when chunk loads / after save; paint/spawner edits → dirty; structural compare.

9.2 Navigate away

Modal: Cancel / Discard / Save then navigate.

9.3 Save button

Disabled when clean; enabled + blinking when dirty.

---

10. Authority & safety

  • Client never decides conditions, heard, quest state, or effects.
  • Choose payload: dialogueId, stepId, trigger; server re-evaluates when.
  • Branches and interrupts are server-side.
  • Unique / maxAlive enforced on save and Apply.

---

11. Feasibility

High–medium. World-scoped dialogue assets + assignment is cleaner than per-spawner trees. ConditionSet + not covers “A but not B” without exploding kind count. Combat interrupt is a small session hook.

Hardest: event wiring for quest objectives + revision/orphan UX. Graph canvas still v1.1.

---

12. Defaults if unspecified (implementation may proceed)

Accept these unless overridden:

1. Condition polarity: per-clause not?: boolean inside ConditionSet.all (no separate OR groups in v1; use multiple ordered dialogue branches for OR). 2. Thresholds: all ≥ (“at least”). 3. Interrupt: any hostile damage/engagement on the NPC closes dialogue for whoever was talking to it (not only if the talker is the attacker). 4. Unique conflict: editor blocks the illegal save (does not auto-unassign silently). 5. Assignment count: computed from pending/applied chunk spawners when opening Dialogues editor (accurate enough for v1). 6. lacksItem / dialogueNotHeard: not separate kinds; use not + positive kind (editor may offer presets). 7. Objectives: one objective completes when its entire ConditionSet is true (event kinds latch once true). 8. Editors placement: Quests and Dialogues buttons stacked under the Settings button (separate modals, not Settings tabs). 9. Step-complete toast: “Quest objectives achieved”; click opens that quest’s detail modal.

Not blocking for v1: graph canvas, script verbs, repeatable quests, localization, visual tile picker.

Source
1# Quests & NPC dialogue (world editor)
2
3**Status:** not implemented (design only)
4**Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
5
6Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.
7
8This document is the product + data + editor spec for implementation.
9
10---
11
12## 1. Goals
13
14- Author **quests** and **dialogue trees** as world-scoped assets (editors under **World settings**).
15- Assign a dialogue to a **humanoid spawner** by reference (`dialogueId`); show assignment counts; support **unique** dialogues.
16- Progress quests via **objectives** with shared multi-condition sets (including negations) and per-step **journal** text.
17- Dialogue: line gifts, player-choice triggers, or **auto-branches**; track **dialogueHeard** per step; **interrupt on attack**.
18- Player **Quests** UI: list + split detail (journal | step/objectives).
19- Fail safe: broken references fail closed; editor validation catches unique/assignment rules.
20
21---
22
23## 2. Persistence & identity
24
25| Asset | Storage | Apply model |
26|-------|---------|-------------|
27| **Quest definitions** | `world.sqlite` (revisioned with map) | Editor save → pending; **Apply now** → live |
28| **Dialogue trees** | `world.sqlite` (revisioned with map) — **not** embedded in chunk JSON | Same as quests |
29| **Spawner → dialogue link** | Chunk spawner `config.dialogueId` (string \| null) | Saved with the chunk |
30| **Quest progress** | `state.sqlite` (`questState`) | Live |
31| **Dialogue heard** | `state.sqlite` (`dialogueHeard`) | Live |
32
33### 2.1 IDs
34
35- **Quest id:** stable slug (`deliver-tin-ore`). Prefer immutable after publish.
36- **Quest step id:** stable within quest; conditions also use **1-based index** in `steps[]` (§4).
37- **Dialogue id:** stable world-scoped id (`smith-intro`). Keys `dialogueHeard`, conditions, spawner assignment.
38- **Dialogue step id / trigger id:** stable within that dialogue.
39- **NPC reference in quests:** prefer **spawner id** + optional display-name hint — not transient entity ids.
40
41### 2.2 World settings: Quests & Dialogues editors
42
43In the world editor chrome, place **Quests** and **Dialogues** as **separate buttons directly under the Settings button** (same control stack, not tabs inside the Settings modal).
44
45| Button | Purpose |
46|--------|---------|
47| **Settings** | Existing world settings |
48| **Quests** | CRUD all quest defs (id, title, steps, objectives, rewards, validation) |
49| **Dialogues** | CRUD all dialogue trees (id, unique flag, steps, exits, validation) |
50
51Both editors are **world-global** (not per-chunk). Saves go through the same admin auth + revision story as other authored world data.
52
53**Dialogues list columns:** id, label/title, step count, **`unique`**, **assigned spawner count**, validation warnings.
54
55**Delete dialogue:** warn if any spawner still references it; optionally block delete until unassigned.
56
57### 2.3 Spawner assignment
58
59On a **humanoid / talkable** spawner:
60
61- Dropdown: **Dialogue** → none, or pick from world dialogue list (show id + unique badge).
62- Stores `config.dialogueId` only (no inline tree on the spawner).
63
64**Assignment count:** Dialogues editor shows how many spawners currently reference each `dialogueId` (scan loaded/pending world chunks, or maintain an index on save). Click-through list of assignees (chunk + spawner label) is nice-to-have in v1.
65
66### 2.4 Unique dialogues
67
68```text
69DialogueTree.unique: boolean // default false
70```
71
72When `unique === true`:
73
741. **At most one spawner** in the world may have `config.dialogueId` equal to that id.
752. That spawner’s **`maxAlive` must be `1`** (editor clamps / blocks save otherwise; server normalize rejects Apply if violated).
76
77Editor UX:
78
79- Toggling **Unique** on while 2+ spawners assigned → block or offer “unassign others / cancel”.
80- Assigning a unique dialogue to a second spawner → block with clear error.
81- Setting `maxAlive > 1` on a spawner that holds a unique dialogue → block or force `maxAlive = 1`.
82
83Non-unique dialogues may be shared by many spawners (and many alive NPCs); `dialogueHeard` is still keyed by `dialogueId`+`stepId` (shared script progress).
84
85---
86
87## 3. Quest definition shape
88
89```text
90Quest {
91 questId: string
92 title: string
93 description: string // player-facing log blurb (in-universe)
94 steps: Step[] // ordered progression
95 rewards?: Reward[] // granted on final step complete
96 cancelable?: boolean // default false in v1
97}
98```
99
100### 3.1 Steps & objectives
101
102A quest advances one **step** at a time. Each step has one or more **objectives**. Each objective has a player-facing **text** and a **ConditionSet** (multiple conditions with optional negation). The step completes only when **all** objectives on that step are done (AND).
103
104```text
105Step {
106 stepId: string
107 title: string
108 description: string
109 completionJournalText: string
110 objectives: Objective[] // ≥ 1; all must complete
111 onEnter?: Effect[]
112 onComplete?: Effect[]
113}
114
115Objective {
116 objectiveId: string
117 text: string // HUD / detail line
118 when: ConditionSet // objective complete when set passes (or event latch inside set)
119}
120```
121
122**Advancement:**
123
1241. While a step is active, the server tracks which `objectiveId`s are satisfied.
1252. When every objective on the step is complete → append journal line → `state` `n` → `n+1` or `completed` + rewards → show toast **“Quest objectives achieved”**. Clicking the toast opens the **Quests** detail modal on **that quest**.
1263. Client: completed objectives struck through.
127
128### 3.2 Condition sets (quests + dialogue)
129
130Shared in `shared/`. Evaluated **only on the server**.
131
132```text
133ConditionSet {
134 all: ConditionClause[] // every clause must pass (AND); empty = always true
135}
136
137ConditionClause {
138 not?: boolean // default false; if true, invert the condition result
139 condition: Condition
140}
141```
142
143**Semantics:** `all` clauses AND-ed. “Has item X, but **not** quest completed Y” → two clauses, second with `not: true` (or use a dedicated negative kind — prefer **`not` on the clause** so every kind is invertible).
144
145Used by:
146
147- quest **objectives** (`when`)
148- dialogue **triggers** (`when` — hide if fail)
149- dialogue **auto-branches** (`when` — first branch whose set passes)
150
151Editor: condition picker rows with a **NOT** toggle per row; add/remove rows.
152
153#### Condition kinds
154
155| Kind | Fields | Meaning |
156|------|--------|---------|
157| `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) has ≥ N |
158| `atTile` | `tileX`, `tileY` | Exact tile |
159| `nearTile` | `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range |
160| `inRect` | `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB |
161| `atChunk` | `chunkX`, `chunkY` | Player chunk |
162| `questState` | `questId`, `state` | Equals `not-started` \| `completed` \| number `n` |
163| `questStepAtLeast` | `questId`, `step` (≥ 1) | Active index ≥ step **or** `completed` |
164| `dialogueHeard` | `dialogueId`, `stepId` | Heard row exists |
165| `dialogueTrigger` | `dialogueId`, `trigger` | **Latch:** player chose that trigger (quest objectives) |
166| `hpAtLeast` | `amount` (≥ 0) | Current HP ≥ amount |
167| `staminaAtLeast` | `amount` (≥ 0) | Current stamina ≥ amount |
168| `hpPercentAtLeast` | `percent` (0–100) | currentHP / maxHP × 100 ≥ percent |
169| `staminaPercentAtLeast` | `percent` (0–100) | currentStamina / maxStamina × 100 ≥ percent |
170| `skillLevelAtLeast` | `skillId`, `level` (1–99) | `skillLevel(skills, skillId) ≥ level` |
171| `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Kills while this quest step active |
172| `interactBlock` | tile and/or `blockTypeId` | Successful interact (once per quest step) |
173
174**Notes:**
175
176- Prefer **`not` + `hasItem`** over a separate `lacksItem` kind (legacy alias ok). Same for `dialogueNotHeard` → `not` + `dialogueHeard`.
177- Thresholds use **≥** (“above or equal”); document in editor labels as “at least”.
178- Max HP / max stamina = same formulas the play sim already uses for the character.
179- Unknown ids → clause **fails closed** (raw condition false; with `not`, that becomes true — authors should avoid dangling ids; validation warns).
180- Kill attribution = existing combat kill credit.
181
182### 3.3 Rewards & effects (v1)
183
184| Kind | Fields |
185|------|--------|
186| `giveItem` | `itemId`, `quantity` |
187| `giveXp` | `skillId`, `amount` |
188| `takeItem` | `itemId`, `quantity` |
189| `startQuest` | `questId` |
190
191Sources: quest `onEnter` / `onComplete`, dialogue **line**, **trigger**, **branch**.
192Full bag → vault via carrier pigeon.
193
194---
195
196## 4. Character quest state & journal
197
198### 4.0 Quest state
199
200```text
201QuestStateValue = "not-started" | number | "completed"
202// number = 1-based index of current incomplete step
203```
204
205```text
206CharacterQuest {
207 questId: string
208 state: QuestStateValue
209 completedObjectiveIds: string[]
210 counters: { [key: string]: number }
211 startedAt?, completedAt?
212}
213```
214
215Missing row ⇒ `not-started`. Conditions read `state` only; counters/objectives are runtime detail for UI + event objectives.
216
217### 4.0b Dialogue heard
218
219```text
220dialogueHeard (characterId, dialogueId, stepId, heardAt)
221UNIQUE (characterId, dialogueId, stepId)
222```
223
224Insert on step **enter** (first time). Permanent in v1. Gate repeat gifts with `when` sets (`not` + `dialogueHeard`, `not` + `hasItem`, etc.).
225
226### 4.0c Journal
227
228```text
229QuestJournalEntry { questId, stepId, text, writtenAt }
230```
231
232Append-only; text frozen at write time.
233
234---
235
236## 4.1 Player UI — Quests
237
238- **Quests** HUD control → list modal: active (`state` number) first, **completed** at bottom; hide `not-started`.
239- Detail modal: left journal (this quest), right step description + objectives (strikethrough when done).
240- **Step-complete toast:** text **“Quest objectives achieved”**. Click → open quest detail for the quest that just advanced (same modal stack as the Quests button).
241
242---
243
244## 5. Dialogue (world asset + spawner link)
245
246### 5.1 Shape
247
248```text
249DialogueTree {
250 dialogueId: string
251 label: string // editor list title
252 unique: boolean // default false; see §2.4
253 steps: DialogueStep[]
254 entryStepId?: string
255}
256
257DialogueStep {
258 stepId: string
259 label: string
260 lines: DialogueLine[]
261 exit:
262 | { kind: "triggers", triggers: DialogueTrigger[] }
263 | { kind: "branches", branches: DialogueBranch[] }
264 | { kind: "end" }
265}
266
267DialogueLine {
268 speaker: "npc" | "player"
269 text: string
270 effects?: Effect[]
271}
272
273DialogueTrigger {
274 trigger: string
275 label: string // editor
276 text: string // player button
277 nextStepId: string | null // null → end
278 when?: ConditionSet // hide if fail; omit = always show
279 effects?: Effect[]
280}
281
282DialogueBranch {
283 label?: string
284 when: ConditionSet // empty all[] = always
285 nextStepId: string | null
286 effects?: Effect[]
287}
288```
289
290**End rules:** null `nextStepId`, `exit.kind: "end"`, no matching branch, or no visible triggers → **close dialogue**.
291
292### 5.2 Runtime
293
2941. Talk to NPC whose spawner has `dialogueId` → load world DialogueTree → open `entryStepId`.
2952. Enter step → insert `dialogueHeard` if new → play lines (apply line effects).
2963. Triggers / branches / end as authored.
2974. **Interrupt:** if the NPC is **attacked** (takes a hostile hit / combat engagement against it) while a player has this dialogue open → **immediately close** that dialogue session (no further lines, choices, or pending line effects). Re-talk required. Does not roll back already-applied effects or heard rows.
298
299### 5.3 Editor (Dialogues panel)
300
301- List + inspector (graph canvas = v1.1).
302- Per dialogue: id, label, **unique**, assignment count, steps, exit modes, shared condition-set picker (with NOT).
303- Validation: unique rules (§2.4), missing refs, empty texts, unreachable steps.
304
305### 5.4 Spawner modal
306
307Humanoid: **Dialogue** dropdown bound to world dialogues (not an inline tree editor). Link to “Open in Dialogues editor” optional.
308
309---
310
311## 6. How quests start
312
313`startQuest` effect → `not-started` → `1`. Block if already numeric or `completed` (v1 no repeats).
314
315---
316
317## 7. Implementation plan (phased)
318
3191. Shared `Condition` / `ConditionSet` / `Effect` in `shared/`.
3202. World DB: quest defs + dialogue trees; state: `questState`, `dialogueHeard`, journal.
3213. World settings **Quests** + **Dialogues** editors; spawner `dialogueId` + unique/maxAlive validation; assignment counts.
3224. Editor unsaved-chunk guard (§9) — may already ship.
3235. Runtime dialogue + combat interrupt; line/trigger/branch effects.
3246. Quest engine + Quests HUD.
3257. Apply revision + tests (conditions+NOT, unique, interrupt, heard, journal).
326
327---
328
329## 8. Edge cases (resolved)
330
331| Topic | Decision |
332|-------|----------|
333| Unique + 2 assignees | Editor/server reject until ≤ 1 |
334| Unique + maxAlive ≠ 1 | Reject / clamp to 1 |
335| Mark unique while assigned elsewhere | Must unassign others first |
336| Shared (non-unique) dialogue | Many spawners OK; heard shared by dialogueId |
337| Spawner dialogueId missing tree | Talk no-ops / error log; fail closed |
338| NPC attacked mid-dialogue | Session closes immediately |
339| Player walks away / disconnect | Close session (no progress loss beyond already applied) |
340| `not` + unknown id | Raw false → NOT true — validation must warn on unknown ids |
341| Thresholds | All “at least” (≥) |
342| Parallel quests | Yes; soft cap ~20 active |
343| One step per quest | Yes (single numeric state) |
344| Apply mid-dialogue | Close sessions |
345
346### 8.1 Open product choices (see §12)
347
348Small list of remaining decisions before / during implementation — none are architectural blockers if defaults in §12 are accepted.
349
350---
351
352## 9. World editor: unsaved chunk navigation & Save affordance
353
354Independent of quests; ship with this plan’s commit.
355
356### 9.1 Dirty state
357
358- Baseline when chunk loads / after save; paint/spawner edits → dirty; structural compare.
359
360### 9.2 Navigate away
361
362Modal: Cancel / Discard / Save then navigate.
363
364### 9.3 Save button
365
366Disabled when clean; enabled + blinking when dirty.
367
368---
369
370## 10. Authority & safety
371
372- Client never decides conditions, heard, quest state, or effects.
373- Choose payload: `dialogueId`, `stepId`, `trigger`; server re-evaluates `when`.
374- Branches and interrupts are server-side.
375- Unique / maxAlive enforced on save and Apply.
376
377---
378
379## 11. Feasibility
380
381**High–medium.** World-scoped dialogue assets + assignment is cleaner than per-spawner trees. ConditionSet + `not` covers “A but not B” without exploding kind count. Combat interrupt is a small session hook.
382
383Hardest: event wiring for quest objectives + revision/orphan UX. Graph canvas still v1.1.
384
385---
386
387## 12. Defaults if unspecified (implementation may proceed)
388
389Accept these unless overridden:
390
3911. **Condition polarity:** per-clause `not?: boolean` inside `ConditionSet.all` (no separate OR groups in v1; use multiple ordered dialogue branches for OR).
3922. **Thresholds:** all ≥ (“at least”).
3933. **Interrupt:** any hostile damage/engagement **on the NPC** closes dialogue for whoever was talking to it (not only if the talker is the attacker).
3944. **Unique conflict:** editor **blocks** the illegal save (does not auto-unassign silently).
3955. **Assignment count:** computed from pending/applied chunk spawners when opening Dialogues editor (accurate enough for v1).
3966. **`lacksItem` / `dialogueNotHeard`:** not separate kinds; use `not` + positive kind (editor may offer presets).
3977. **Objectives:** one objective completes when its entire `ConditionSet` is true (event kinds latch once true).
3988. **Editors placement:** **Quests** and **Dialogues** buttons stacked **under** the Settings button (separate modals, not Settings tabs).
3999. **Step-complete toast:** “Quest objectives achieved”; click opens that quest’s detail modal.
400
401**Not blocking for v1:** graph canvas, script verbs, repeatable quests, localization, visual tile picker.