# misc/dialogue (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/misc/dialogue/

Dialogue runner and script parser.
- A port of the original misc/dialogue.js. (DialogueRunner, DialogueScriptParser)
- DialogueRunner: steps through a script made of lines, choices, labels, and jumps in order. The state machine that visual novels / RPG dialogues / tutorials each built on their own.
  ```text
    runner.set_script(entries); runner.start(None);
    runner.get_current()   → DialogueCurrent::Line / choice / finished
    runner.advance() on a line, runner.choose(index) on a choice.
  ```
- DialogueScriptParser: turns one-line command text into a script.
  ```text
    /label label_name
    /jump label_name
    /speaker speaker_name              (default speaker for the following /say)
    /say line text
    /option option text -> label_name       (consecutive /option lines are grouped into one choice)
    /end
  ```
  Lines not starting with "/" are treated as /say of the preceding speaker. "//" is a comment.
- Differences from the original:
  Script entries are the DialogueEntry enum instead of objects with several fields. One entry cannot be both a label and a line.
  get_current returns the DialogueCurrent enum instead of a { kind, ... } object, and a choice's options are a list of option texts (`Vec<String>`).

## DialogueOption (struct) (Clone, Debug, PartialEq, Eq)

One option of a choice. (original { text, jump? })

Example: Build a script directly from entries and pick an option without a jump

```rust
use vanilla::{DialogueCurrent, DialogueEntry, DialogueOption, DialogueRunner};

let entry_list = vec![
	DialogueEntry::Choice(vec![
		DialogueOption { text: String::from("Yes"), jump: Some(String::from("yes")) },
		DialogueOption { text: String::from("No"), jump: None },
	]),
	DialogueEntry::Line { speaker: String::from("Guide"), text: String::from("Maybe later.") },
	DialogueEntry::End,
	DialogueEntry::Label(String::from("yes")),
	DialogueEntry::Line { speaker: String::from("Guide"), text: String::from("Great!") },
];
let mut dialogue_runner = DialogueRunner::new();
dialogue_runner.set_script(entry_list);
dialogue_runner.start(None);
dialogue_runner.choose(1);
assert_eq!(dialogue_runner.get_current(), DialogueCurrent::Line { speaker: String::from("Guide"), text: String::from("Maybe later.") });
```

- `pub text: String` (field, since 0.3.2): Option text.
  - returns String
- `pub jump: Option<String>` (field, since 0.3.2): Name of the label to move to when picked. If None or an unknown label, goes to the entry after the choice.
  - returns Option<String>

## DialogueRunner (struct) (Clone, Debug, Default)

Dialogue runner.

Example: Step through a script, advancing lines and picking options

```rust
use vanilla::{DialogueCurrent, DialogueRunner, DialogueScriptParser};

let script_text = "
/speaker Clerk
/say Welcome.
/option Go on an adventure -> adventure
/option Go home
/label home
/say Goodbye.
/end
/label adventure
/say Let's go!
";
let mut dialogue_runner = DialogueRunner::new();
dialogue_runner.set_script(DialogueScriptParser::parse(script_text));
dialogue_runner.start(None);
assert_eq!(dialogue_runner.get_current(), DialogueCurrent::Line { speaker: String::from("Clerk"), text: String::from("Welcome.") });

dialogue_runner.advance();
assert_eq!(dialogue_runner.get_current(), DialogueCurrent::Choice { options: vec![String::from("Go on an adventure"), String::from("Go home")] });

dialogue_runner.choose(0);
assert_eq!(dialogue_runner.get_current(), DialogueCurrent::Line { speaker: String::from("Clerk"), text: String::from("Let's go!") });

dialogue_runner.advance();
assert!(dialogue_runner.is_finished());
assert_eq!(dialogue_runner.get_current(), DialogueCurrent::Finished);
```

- `pub fn new() -> DialogueRunner` (constructor, since 0.3.2): Constructor. (empty script, finished state)
  - returns DialogueRunner: A runner with no script. (start with set_script and start)
- `pub fn set_script(&mut self, entry_list: Vec<DialogueEntry>)` (method, since 0.3.2): Sets the script. (builds a table of label positions and leaves it in the finished state. If a label appears more than once, the later one wins)
  - `entry_list` Vec<DialogueEntry>: List of script entries. (the result of DialogueScriptParser::parse or a hand-built list)
- `pub fn start(&mut self, label_name: Option<&str>)` (method, since 0.3.2): Starts. (from the given label, or from the beginning if the label does not exist)
  - Skips labels and jumps and stops at the first line or choice to show. Finished if the script is empty or has no such entry.
  - `label_name` Option<&str>: Name of the label to start from. None starts from the beginning.

  Example: Start from a label

  ```rust
  use vanilla::{DialogueCurrent, DialogueRunner, DialogueScriptParser};
  
  let mut dialogue_runner = DialogueRunner::new();
  dialogue_runner.set_script(DialogueScriptParser::parse("/say First.\n/label second\n/say Second."));
  dialogue_runner.start(Some("second"));
  assert_eq!(dialogue_runner.get_current(), DialogueCurrent::Line { speaker: String::new(), text: String::from("Second.") });
  
  dialogue_runner.start(Some("missing"));
  assert_eq!(dialogue_runner.get_current(), DialogueCurrent::Line { speaker: String::new(), text: String::from("First.") });
  ```

- `pub fn get_current(&self) -> DialogueCurrent` (method, since 0.3.2): Returns the current entry.
  - returns DialogueCurrent: The line or choice (list of option texts, a copy) to show now. DialogueCurrent::Finished if finished.
- `pub fn advance(&mut self)` (method, since 0.3.2): Advances to the next. (called on a line entry, ignored on a choice)
- `pub fn choose(&mut self, option_index: usize)` (method, since 0.3.2): Chooses. (called on a choice entry. Goes to the option's jump label if any, otherwise or for an unknown label to the next entry)
  - Ignored if finished or if the current entry is not a choice.
  - `option_index` usize: Index of the option to pick. (from 0, ignored if not less than the option count)
- `pub fn is_finished(&self) -> bool` (method, since 0.3.2): Whether it has finished.
  - returns bool: true if /end or the end of the script was reached, or if not started yet.

## DialogueScriptParser (struct)

Script parser. (a set of static functions)

Example: One-line command text into script entries

```rust
use vanilla::{DialogueEntry, DialogueOption, DialogueScriptParser};

let entry_list = DialogueScriptParser::parse("/speaker Guide\nHello.\n// comment\n/option Next -> next\n/option Stay\n/label next\n/end");
assert_eq!(entry_list, vec![
	DialogueEntry::Line { speaker: String::from("Guide"), text: String::from("Hello.") },
	DialogueEntry::Choice(vec![
		DialogueOption { text: String::from("Next"), jump: Some(String::from("next")) },
		DialogueOption { text: String::from("Stay"), jump: None },
	]),
	DialogueEntry::Label(String::from("next")),
	DialogueEntry::End,
]);
```

- `pub fn parse(script_text: &str) -> Vec<DialogueEntry>` (static, since 0.3.2): Parses. (trims each line and reads the command. Unknown commands are skipped)
  - Skips empty lines and lines starting with "//". Consecutive /option lines are grouped into one choice when another line comes or the text ends.
  - `script_text` &str: Script text. (lines are split by `'\n'`)
  - returns Vec<DialogueEntry>: List of script entries. (/speaker makes no entry and only changes the speaker of the following lines)

## DialogueEntry (enum) (Clone, Debug, PartialEq, Eq)

Script entry. (original { speaker, text } / { label } / { jump } / { choice: `[...]` } / { end: true })

- `Line` = `Line{ speaker: String, text: String, }`: Line. (speaker name and line text, an empty string if there is no speaker)
- `Label` = `Label(String)`: Label. (name of a jump target, skipped while running)
- `Jump` = `Jump(String)`: Jump. (moves to just after the label with that name, or to the next entry for an unknown label)
- `Choice` = `Choice(Vec<DialogueOption>)`: Choice. (list of options, stays until picked with choose)
- `End`: End of script. (finishes when reached)

## DialogueCurrent (enum) (Clone, Debug, PartialEq, Eq)

What to show now. (original { kind: "line" | "choice" | "finished", ... })

- `Line` = `Line{ speaker: String, text: String, }`: Time to show a line. (advance with advance)
- `Choice` = `Choice{ options: Vec<String>, }`: Time to show a choice. (list of option texts, pick with choose)
- `Finished`: Finished or not started.
