bladeink 1.2.4

This is a Rust port of inkle's ink, a scripting language for writing interactive narrative.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
use crate::{
    choice::Choice,
    choice_point::ChoicePoint,
    container::Container,
    control_command::{CommandType, ControlCommand},
    object::RTObject,
    pointer::{self, Pointer},
    push_pop::PushPopType,
    story::{OutputStateChange, Story, errors::ErrorType},
    story_error::StoryError,
    value::Value,
    value_type::VariablePointerValue,
    void::Void,
};
use std::{self, rc::Rc};

/// # Story Progress
/// Methods to move the story forwards.
impl Story {
    /// `true` if the story is not waiting for user input from
    /// [`choose_choice_index`](Story::choose_choice_index).
    pub fn can_continue(&self) -> bool {
        self.get_state().can_continue()
    }

    /// Tries to continue pulling text from the story.
    pub fn cont(&mut self) -> Result<String, StoryError> {
        self.continue_async(0.0)?;
        self.get_current_text()
    }

    /// Continues the story until a choice or error is reached.
    /// If a choice is reached, returns all text produced along the way.
    pub fn continue_maximally(&mut self) -> Result<String, StoryError> {
        self.if_async_we_cant("continue_maximally")?;

        let mut sb = String::new();

        while self.can_continue() {
            sb.push_str(&self.cont()?);
        }

        Ok(sb)
    }

    /// Continues running the story code for the specified number of
    /// milliseconds.
    pub fn continue_async(&mut self, millisecs_limit_async: f32) -> Result<(), StoryError> {
        if !self.has_validated_externals {
            self.validate_external_bindings()?;
        }

        self.continue_internal(millisecs_limit_async)
    }

    pub(crate) fn if_async_we_cant(&self, activity_str: &str) -> Result<(), StoryError> {
        if self.async_continue_active {
            return Err(StoryError::InvalidStoryState(format!(
                "Can't {}. Story is in the middle of a continue_async(). Make more continue_async() calls or a single cont() call beforehand.",
                activity_str
            )));
        }

        Ok(())
    }

    pub(crate) fn continue_internal(
        &mut self,
        millisecs_limit_async: f32,
    ) -> Result<(), StoryError> {
        let is_async_time_limited = millisecs_limit_async > 0.0;

        self.recursive_continue_count += 1;

        // Doing either:
        // - full run through non-async (so not active and don't want to be)
        // - Starting async run-through
        if !self.async_continue_active {
            self.async_continue_active = is_async_time_limited;
            if !self.can_continue() {
                return Err(StoryError::InvalidStoryState(
                    "Can't continue - should check can_continue before calling Continue".to_owned(),
                ));
            }

            self.get_state_mut().set_did_safe_exit(false);

            self.get_state_mut().reset_output(None);

            // It's possible for ink to call game to call ink to call game etc
            // In this case, we only want to batch observe variable changes
            // for the outermost call.
            if self.recursive_continue_count == 1 {
                self.state.variables_state.start_variable_observation();
            }
        } else if self.async_continue_active && !is_async_time_limited {
            self.async_continue_active = false;
        }

        // Start timing (only when necessary)
        let duration_stopwatch = match self.async_continue_active {
            true => Some(web_time::Instant::now()),
            false => None,
        };

        let mut output_stream_ends_in_newline = false;
        self.saw_lookahead_unsafe_function_after_new_line = false;

        loop {
            match self.continue_single_step() {
                Ok(r) => output_stream_ends_in_newline = r,
                Err(e) => {
                    self.add_error(e.get_message(), false);
                    break;
                }
            }

            if output_stream_ends_in_newline {
                break;
            }

            // Run out of async time?
            if self.async_continue_active
                && duration_stopwatch.as_ref().unwrap().elapsed().as_millis() as f32
                    > millisecs_limit_async
            {
                break;
            }

            if !self.can_continue() {
                break;
            }
        }

        let mut changed_variables_to_observe = None;

        // 4 outcomes:
        // - got newline (so finished this line of text)
        // - can't continue (e.g. choices or ending)
        // - ran out of time during evaluation
        // - error
        //
        // Successfully finished evaluation in time (or in error)
        if output_stream_ends_in_newline || !self.can_continue() {
            // Need to rewind, due to evaluating further than we should?
            if self.state_snapshot_at_last_new_line.is_some() {
                self.restore_state_snapshot();
            }

            // Finished a section of content / reached a choice point?
            if !self.can_continue() {
                if self.state.get_callstack().borrow().can_pop_thread() {
                    self.add_error("Thread available to pop, threads should always be flat by the end of evaluation?", false);
                }

                if self.state.get_generated_choices().is_empty()
                    && !self.get_state().is_did_safe_exit()
                    && self.temporary_evaluation_container.is_none()
                {
                    if self
                        .state
                        .get_callstack()
                        .borrow()
                        .can_pop_type(Some(PushPopType::Tunnel))
                    {
                        self.add_error("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?", false);
                    } else if self
                        .state
                        .get_callstack()
                        .borrow()
                        .can_pop_type(Some(PushPopType::Function))
                    {
                        self.add_error(
                            "unexpectedly reached end of content. Do you need a '~ return'?",
                            false,
                        );
                    } else if !self.get_state().get_callstack().borrow().can_pop() {
                        self.add_error(
                            "ran out of content. Do you need a '-> DONE' or '-> END'?",
                            false,
                        );
                    } else {
                        self.add_error("unexpectedly reached end of content for unknown reason. Please debug compiler!", false);
                    }
                }
            }
            self.get_state_mut().set_did_safe_exit(false);
            self.saw_lookahead_unsafe_function_after_new_line = false;

            if self.recursive_continue_count == 1 {
                changed_variables_to_observe =
                    Some(self.state.variables_state.complete_variable_observation());
            }

            self.async_continue_active = false;
        }

        self.recursive_continue_count -= 1;

        // Report any errors that occured during evaluation.
        // This may either have been StoryExceptions that were thrown
        // and caught during evaluation, or directly added with AddError.
        if self.get_state().has_error() || self.get_state().has_warning() {
            match &self.on_error {
                Some(on_err) => {
                    if self.get_state().has_error() {
                        for err in self.get_state().get_current_errors() {
                            on_err.borrow_mut().error(err, ErrorType::Error);
                        }
                    }

                    if self.get_state().has_warning() {
                        for err in self.get_state().get_current_warnings() {
                            on_err.borrow_mut().error(err, ErrorType::Warning);
                        }
                    }

                    self.reset_errors();
                }
                // No error handler: throw for errors, silently discard warnings
                None => {
                    if self.get_state().has_error() {
                        let mut sb = String::new();
                        sb.push_str("Ink had ");
                        sb.push_str(&self.get_state().get_current_errors().len().to_string());
                        if self.get_state().get_current_errors().len() == 1 {
                            sb.push_str(" error");
                        } else {
                            sb.push_str(" errors");
                        }
                        if self.get_state().has_warning() {
                            sb.push_str(" and ");
                            sb.push_str(
                                self.get_state()
                                    .get_current_warnings()
                                    .len()
                                    .to_string()
                                    .as_str(),
                            );
                            if self.get_state().get_current_warnings().len() == 1 {
                                sb.push_str(" warning");
                            } else {
                                sb.push_str(" warnings");
                            }
                        }
                        sb.push_str(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: ");
                        sb.push_str(self.get_state().get_current_errors()[0].as_str());
                        return Err(StoryError::InvalidStoryState(sb));
                    }
                    // Only warnings and no handler: discard silently (consistent
                    // with the C# reference implementation which does not throw
                    // for warnings without a handler).
                    self.reset_errors();
                }
            }
        }

        // Send out variable observation events at the last second, since it might trigger new ink to be run
        if let Some(changed) = changed_variables_to_observe {
            for (variable_name, value) in changed {
                self.notify_variable_changed(&variable_name, &value);
            }
        }

        Ok(())
    }

    pub(crate) fn continue_single_step(&mut self) -> Result<bool, StoryError> {
        // Run main step function (walks through content)
        self.step()?;

        // Run out of content and we have a default invisible choice that we can follow?
        if !self.can_continue()
            && !self
                .get_state()
                .get_callstack()
                .borrow()
                .element_is_evaluate_from_game()
        {
            self.try_follow_default_invisible_choice()?;
        }

        // Don't save/rewind during string evaluation, which is e.g. used for choices
        if !self.get_state().in_string_evaluation() {
            // We previously found a newline, but were we just double checking that
            // it wouldn't immediately be removed by glue?
            if let Some(state_snapshot_at_last_new_line) =
                self.state_snapshot_at_last_new_line.as_mut()
            {
                // Has proper text or a tag been added? Then we know that the newline
                // that was previously added is definitely the end of the line.
                let change = Story::calculate_newline_output_state_change(
                    &state_snapshot_at_last_new_line.get_current_text(),
                    &self.state.get_current_text(),
                    state_snapshot_at_last_new_line.get_current_tags().len() as i32,
                    self.state.get_current_tags().len() as i32,
                );

                // The last time we saw a newline, it was definitely the end of the line, so we
                // want to rewind to that point.
                if change == OutputStateChange::ExtendedBeyondNewline
                    || self.saw_lookahead_unsafe_function_after_new_line
                {
                    self.restore_state_snapshot();

                    // Hit a newline for sure, we're done
                    return Ok(true);
                }
                // Newline that previously existed is no longer valid - e.g.
                // glue was encounted that caused it to be removed.
                else if change == OutputStateChange::NewlineRemoved {
                    self.state_snapshot_at_last_new_line = None;
                    self.discard_snapshot();
                }
            }

            // Current content ends in a newline - approaching end of our evaluation
            if self.get_state().output_stream_ends_in_newline() {
                // If we can continue evaluation for a bit:
                // Create a snapshot in case we need to rewind.
                // We're going to continue stepping in case we see glue or some
                // non-text content such as choices.
                if self.can_continue() {
                    // Don't bother to record the state beyond the current newline.
                    // e.g.:
                    // Hello world\n // record state at the end of here
                    // ~ complexCalculation() // don't actually need this unless it generates
                    // text
                    if self.state_snapshot_at_last_new_line.is_none() {
                        self.state_snapshot();
                    }
                }
                // Can't continue, so we're about to exit - make sure we
                // don't have an old state hanging around.
                else {
                    self.discard_snapshot();
                }
            }
        }

        Ok(false)
    }

    pub(crate) fn step(&mut self) -> Result<(), StoryError> {
        let mut should_add_to_stream = true;

        // Get current content
        let mut pointer = self.get_state().get_current_pointer().clone();

        if pointer.is_null() {
            return Ok(());
        }

        // Step directly to the first element of content in a container (if
        // necessary)
        let r = pointer.resolve();

        let mut container_to_enter = match r {
            Some(o) => o.into_any().downcast::<Container>().ok(),
            None => None,
        };

        while let Some(cte) = container_to_enter.as_ref() {
            // Mark container as being entered
            self.visit_container(cte, true);

            // No content? the most we can do is step past it
            if cte.content.is_empty() {
                break;
            }

            pointer = Pointer::start_of(cte.clone());

            let r = pointer.resolve();

            container_to_enter = match r {
                Some(o) => o.into_any().downcast::<Container>().ok(),
                None => None,
            };
        }

        self.get_state_mut().set_current_pointer(pointer.clone());

        // Is the current content Object:
        // - Normal content
        // - Or a logic/flow statement - if so, do it
        // Stop flow if we hit a stack pop when we're unable to pop (e.g.
        // return/done statement in knot
        // that was diverted to rather than called as a function)
        let mut current_content_obj = pointer.resolve();

        let is_logic_or_flow_control = self.perform_logic_and_flow_control(&current_content_obj)?;

        // Has flow been forced to end by flow control above?
        if self.get_state().get_current_pointer().is_null() {
            return Ok(());
        }

        if is_logic_or_flow_control {
            should_add_to_stream = false;
        }

        // Choice with condition?
        if let Some(cco) = &current_content_obj {
            // If the container has no content, then it will be
            // the "content" itself, but we skip over it.
            if cco.as_any().is::<Container>() {
                should_add_to_stream = false;
            }

            if let Ok(choice_point) = cco.clone().into_any().downcast::<ChoicePoint>() {
                let choice = self.process_choice(&choice_point)?;
                if let Some(choice) = choice {
                    self.get_state_mut()
                        .get_generated_choices_mut()
                        .push(choice);
                }

                current_content_obj = None;
                should_add_to_stream = false;
            }
        }

        // Content to add to evaluation stack or the output stream
        if should_add_to_stream {
            // If we're pushing a variable pointer onto the evaluation stack,
            // ensure that it's specific
            // to our current (possibly temporary) context index. And make a
            // copy of the pointer
            // so that we're not editing the original runtime Object.
            let var_pointer = Value::get_value::<&VariablePointerValue>(
                current_content_obj.as_ref().unwrap().as_ref(),
            );

            if let Some(var_pointer) = var_pointer
                && var_pointer.context_index == -1
            {
                // Create new Object so we're not overwriting the story's own
                // data
                let context_idx = self
                    .get_state()
                    .get_callstack()
                    .borrow()
                    .context_for_variable_named(&var_pointer.variable_name);
                current_content_obj = Some(Rc::new(Value::new_variable_pointer(
                    &var_pointer.variable_name,
                    context_idx as i32,
                )));
            }

            // Expression evaluation content
            if self.get_state().get_in_expression_evaluation() {
                self.get_state_mut()
                    .push_evaluation_stack(current_content_obj.as_ref().unwrap().clone());
            }
            // Output stream content (i.e. not expression evaluation)
            else {
                self.get_state_mut()
                    .push_to_output_stream(current_content_obj.as_ref().unwrap().clone());
            }
        }

        // Increment the content pointer, following diverts if necessary
        self.next_content()?;

        // Starting a thread should be done after the increment to the content
        // pointer,
        // so that when returning from the thread, it returns to the content
        // after this instruction.
        if let Some(current_content_obj) = &current_content_obj
            && let Some(control_cmd) = current_content_obj
                .as_any()
                .downcast_ref::<ControlCommand>()
            && control_cmd.command_type == CommandType::StartThread
        {
            self.get_state().get_callstack().borrow_mut().push_thread();
        }

        Ok(())
    }

    pub(crate) fn next_content(&mut self) -> Result<(), StoryError> {
        // Setting previousContentObject is critical for
        // VisitChangedContainersDueToDivert
        let cp = self.get_state().get_current_pointer();
        self.get_state_mut().set_previous_pointer(cp);

        // Divert step?
        if !self.get_state().diverted_pointer.is_null() {
            let dp = self.get_state().diverted_pointer.clone();
            self.get_state_mut().set_current_pointer(dp);
            self.get_state_mut()
                .set_diverted_pointer(pointer::NULL.clone());

            // Internally uses state.previousContentObject and
            // state.currentContentObject
            self.visit_changed_containers_due_to_divert();

            // Diverted location has valid content?
            if !self.get_state().get_current_pointer().is_null() {
                return Ok(());
            }

            // Otherwise, if diverted location doesn't have valid content,
            // drop down and attempt to increment.
            // This can happen if the diverted path is intentionally jumping
            // to the end of a container - e.g. a Conditional that's
            // re-joining
        }

        let successful_pointer_increment = self.increment_content_pointer();

        // Ran out of content? Try to auto-exit from a function,
        // or finish evaluating the content of a thread
        if !successful_pointer_increment {
            let mut did_pop = false;

            let can_pop_type = self
                .get_state()
                .get_callstack()
                .as_ref()
                .borrow()
                .can_pop_type(Some(PushPopType::Function));
            if can_pop_type {
                // Pop from the call stack
                self.get_state_mut()
                    .pop_callstack(Some(PushPopType::Function))?;

                // This pop was due to dropping off the end of a function that
                // didn't return anything,
                // so in this case, we make sure that the evaluator has
                // something to chomp on if it needs it
                if self.get_state().get_in_expression_evaluation() {
                    self.get_state_mut()
                        .push_evaluation_stack(Rc::new(Void::new()));
                }

                did_pop = true;
            } else if self
                .get_state()
                .get_callstack()
                .as_ref()
                .borrow()
                .can_pop_thread()
            {
                self.get_state()
                    .get_callstack()
                    .as_ref()
                    .borrow_mut()
                    .pop_thread()?;

                did_pop = true;
            } else {
                self.get_state_mut()
                    .try_exit_function_evaluation_from_game();
            }

            // Step past the point where we last called out
            if did_pop && !self.get_state().get_current_pointer().is_null() {
                self.next_content()?;
            }
        }

        Ok(())
    }

    pub(crate) fn increment_content_pointer(&self) -> bool {
        let mut successful_increment = true;

        let mut pointer = self
            .get_state()
            .get_callstack()
            .as_ref()
            .borrow()
            .get_current_element()
            .current_pointer
            .clone();
        pointer.index += 1;

        let mut container = pointer.container.as_ref().unwrap().clone();

        // Each time we step off the end, we fall out to the next container, all
        // the
        // while we're in indexed rather than named content
        while pointer.index >= container.content.len() as i32 {
            successful_increment = false;

            let next_ancestor = container.get_object().get_parent();

            if next_ancestor.is_none() {
                break;
            }

            let rto: Rc<dyn RTObject> = container;
            let index_in_ancestor = next_ancestor
                .as_ref()
                .unwrap()
                .content
                .iter()
                .position(|s| Rc::ptr_eq(s, &rto));
            if index_in_ancestor.is_none() {
                break;
            }

            pointer = Pointer::new(next_ancestor, index_in_ancestor.unwrap() as i32);
            container = pointer.container.as_ref().unwrap().clone();

            // Increment to next content in outer container
            pointer.index += 1;

            successful_increment = true;
        }

        if !successful_increment {
            pointer = pointer::NULL.clone();
        }

        self.get_state()
            .get_callstack()
            .as_ref()
            .borrow_mut()
            .get_current_element_mut()
            .current_pointer = pointer;

        successful_increment
    }

    pub(crate) fn calculate_newline_output_state_change(
        prev_text: &str,
        curr_text: &str,
        prev_tag_count: i32,
        curr_tag_count: i32,
    ) -> OutputStateChange {
        // Simple case: nothing's changed, and we still have a newline
        // at the end of the current content
        let newline_still_exists = curr_text.len() >= prev_text.len()
            && !prev_text.is_empty()
            && curr_text.as_bytes()[prev_text.len() - 1] == b'\n';
        if prev_tag_count == curr_tag_count
            && prev_text.len() == curr_text.len()
            && newline_still_exists
        {
            return OutputStateChange::NoChange;
        }

        // Old newline has been removed, it wasn't the end of the line after all
        if !newline_still_exists {
            return OutputStateChange::NewlineRemoved;
        }

        // Tag added - definitely the start of a new line
        if curr_tag_count > prev_tag_count {
            return OutputStateChange::ExtendedBeyondNewline;
        }

        // There must be new content - check whether it's just whitespace
        for c in curr_text.as_bytes().iter().skip(prev_text.len()) {
            if *c != b' ' && *c != b'\t' {
                return OutputStateChange::ExtendedBeyondNewline;
            }
        }

        // There's new text but it's just spaces and tabs, so there's still the
        // potential
        // for glue to kill the newline.
        OutputStateChange::NoChange
    }

    pub(crate) fn visit_container(&mut self, container: &Rc<Container>, at_start: bool) {
        if !container.counting_at_start_only || at_start {
            if container.visits_should_be_counted {
                self.get_state_mut()
                    .increment_visit_count_for_container(container);
            }

            if container.turn_index_should_be_counted {
                self.get_state_mut()
                    .record_turn_index_visit_to_container(container);
            }
        }
    }

    /// The vector of [`Choice`](crate::choice::Choice) objects available at
    /// the current point in the `Story`. This vector will be
    /// populated as the `Story` is stepped through with the
    /// [`cont`](Story::cont) method.
    /// Once [`can_continue`](Story::can_continue) becomes `false`, this
    /// vector will be populated, and is usually (but not always) on the
    /// final [`cont`](Story::cont) step.
    pub fn get_current_choices(&self) -> Vec<Rc<Choice>> {
        // Don't include invisible choices for external usage.
        let mut choices = Vec::new();

        if let Some(current_choices) = self.get_state().get_current_choices() {
            for c in current_choices {
                if !c.is_invisible_default {
                    c.index.replace(choices.len());
                    choices.push(c.clone());
                }
            }
        }

        choices
    }

    /// The string of output text available at the current point in
    /// the `Story`. This string will be built as the `Story` is stepped
    /// through with the [`cont`](Story::cont) method.
    pub fn get_current_text(&mut self) -> Result<String, StoryError> {
        self.if_async_we_cant("call currentText since it's a work in progress")?;
        Ok(self.get_state_mut().get_current_text())
    }

    /// String representation of the location where the story currently is.
    pub fn get_current_path(&self) -> Option<String> {
        self.get_state().current_path_string()
    }
}