-
Notifications
You must be signed in to change notification settings - Fork 537
Expand file tree
/
Copy pathStory.cs
More file actions
2969 lines (2455 loc) · 127 KB
/
Copy pathStory.cs
File metadata and controls
2969 lines (2455 loc) · 127 KB
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace Ink.Runtime
{
/// <summary>
/// A Story is the core class that represents a complete Ink narrative, and
/// manages the evaluation and state of it.
/// </summary>
public class Story : Runtime.Object
{
/// <summary>
/// The current version of the ink story file format.
/// </summary>
public const int inkVersionCurrent = 21;
// Version numbers are for engine itself and story file, rather
// than the story state save format
// -- old engine, new format: always fail
// -- new engine, old format: possibly cope, based on this number
// When incrementing the version number above, the question you
// should ask yourself is:
// -- Will the engine be able to load an old story file from
// before I made these changes to the engine?
// If possible, you should support it, though it's not as
// critical as loading old save games, since it's an
// in-development problem only.
/// <summary>
/// The minimum legacy version of ink that can be loaded by the current version of the code.
/// </summary>
const int inkVersionMinimumCompatible = 18;
/// <summary>
/// The list of Choice objects available at the current point in
/// the Story. This list will be populated as the Story is stepped
/// through with the Continue() method. Once canContinue becomes
/// false, this list will be populated, and is usually
/// (but not always) on the final Continue() step.
/// </summary>
public List<Choice> currentChoices
{
get
{
// Don't include invisible choices for external usage.
var choices = new List<Choice>();
foreach (var c in _state.currentChoices) {
if (!c.isInvisibleDefault) {
c.index = choices.Count;
choices.Add (c);
}
}
return choices;
}
}
/// <summary>
/// The latest line of text to be generated from a Continue() call.
/// </summary>
public string currentText {
get {
IfAsyncWeCant ("call currentText since it's a work in progress");
return state.currentText;
}
}
/// <summary>
/// Gets a list of tags as defined with '#' in source that were seen
/// during the latest Continue() call.
/// </summary>
public List<string> currentTags {
get {
IfAsyncWeCant ("call currentTags since it's a work in progress");
return state.currentTags;
}
}
/// <summary>
/// Any errors generated during evaluation of the Story.
/// </summary>
public List<string> currentErrors { get { return state.currentErrors; } }
/// <summary>
/// Any warnings generated during evaluation of the Story.
/// </summary>
public List<string> currentWarnings { get { return state.currentWarnings; } }
/// <summary>
/// The current flow name if using multi-flow functionality - see SwitchFlow
/// </summary>
public string currentFlowName => state.currentFlowName;
/// <summary>
/// Is the default flow currently active? By definition, will also return true if not using multi-flow functionality - see SwitchFlow
/// </summary>
public bool currentFlowIsDefaultFlow { get { return state.currentFlowIsDefaultFlow; } }
/// <summary>
/// Names of currently alive flows (not including the default flow)
/// </summary>
public List<string> aliveFlowNames { get { return state.aliveFlowNames; } }
/// <summary>
/// Whether the currentErrors list contains any errors.
/// THIS MAY BE REMOVED - you should be setting an error handler directly
/// using Story.onError.
/// </summary>
public bool hasError { get { return state.hasError; } }
/// <summary>
/// Whether the currentWarnings list contains any warnings.
/// </summary>
public bool hasWarning { get { return state.hasWarning; } }
/// <summary>
/// The VariablesState object contains all the global variables in the story.
/// However, note that there's more to the state of a Story than just the
/// global variables. This is a convenience accessor to the full state object.
/// </summary>
public VariablesState variablesState{ get { return state.variablesState; } }
public ListDefinitionsOrigin listDefinitions {
get {
return _listDefinitions;
}
}
/// <summary>
/// The entire current state of the story including (but not limited to):
///
/// * Global variables
/// * Temporary variables
/// * Read/visit and turn counts
/// * The callstack and evaluation stacks
/// * The current threads
///
/// </summary>
public StoryState state { get { return _state; } }
/// <summary>
/// Error handler for all runtime errors in ink - i.e. problems
/// with the source ink itself that are only discovered when playing
/// the story.
/// It's strongly recommended that you assign an error handler to your
/// story instance to avoid getting exceptions for ink errors.
/// </summary>
public event Ink.ErrorHandler onError;
/// <summary>
/// Callback for when ContinueInternal is complete
/// </summary>
public event Action onDidContinue;
/// <summary>
/// Callback for when a choice is about to be executed
/// </summary>
public event Action<Choice> onMakeChoice;
/// <summary>
/// Callback for when a function is about to be evaluated
/// </summary>
public event Action<string, object[]> onEvaluateFunction;
/// <summary>
/// Callback for when a function has been evaluated
/// This is necessary because evaluating a function can cause continuing
/// </summary>
public event Action<string, object[], string, object> onCompleteEvaluateFunction;
/// <summary>
/// Callback for when a path string is chosen
/// </summary>
public event Action<string, object[]> onChoosePathString;
/// <summary>
/// Start recording ink profiling information during calls to Continue on Story.
/// Return a Profiler instance that you can request a report from when you're finished.
/// </summary>
public Profiler StartProfiling() {
IfAsyncWeCant ("start profiling");
_profiler = new Profiler();
return _profiler;
}
/// <summary>
/// Stop recording ink profiling information during calls to Continue on Story.
/// To generate a report from the profiler, call
/// </summary>
public void EndProfiling() {
_profiler = null;
}
// Warning: When creating a Story using this constructor, you need to
// call ResetState on it before use. Intended for compiler use only.
// For normal use, use the constructor that takes a json string.
public Story (Container contentContainer, List<Runtime.ListDefinition> lists = null)
{
_mainContentContainer = contentContainer;
if (lists != null)
_listDefinitions = new ListDefinitionsOrigin (lists);
_externals = new Dictionary<string, ExternalFunctionDef> ();
}
/// <summary>
/// Construct a Story object using a JSON string compiled through inklecate.
/// </summary>
public Story(string jsonString) : this((Container)null)
{
Dictionary<string, object> rootObject = SimpleJson.TextToDictionary (jsonString);
object versionObj = rootObject ["inkVersion"];
if (versionObj == null)
throw new System.Exception ("ink version number not found. Are you sure it's a valid .ink.json file?");
int formatFromFile = (int)versionObj;
if (formatFromFile > inkVersionCurrent) {
throw new System.Exception ("Version of ink used to build story was newer than the current version of the engine");
} else if (formatFromFile < inkVersionMinimumCompatible) {
throw new System.Exception ("Version of ink used to build story is too old to be loaded by this version of the engine");
} else if (formatFromFile != inkVersionCurrent) {
System.Diagnostics.Debug.WriteLine ("WARNING: Version of ink used to build story doesn't match current version of engine. Non-critical, but recommend synchronising.");
}
var rootToken = rootObject ["root"];
if (rootToken == null)
throw new System.Exception ("Root node for ink not found. Are you sure it's a valid .ink.json file?");
object listDefsObj;
if (rootObject.TryGetValue ("listDefs", out listDefsObj)) {
_listDefinitions = Json.JTokenToListDefinitions (listDefsObj);
}
_mainContentContainer = Json.JTokenToRuntimeObject (rootToken) as Container;
ResetState ();
}
/// <summary>
/// The Story itself in JSON representation.
/// </summary>
public string ToJson()
{
//return ToJsonOld();
var writer = new SimpleJson.Writer();
ToJson(writer);
return writer.ToString();
}
/// <summary>
/// The Story itself in JSON representation.
/// </summary>
public void ToJson(Stream stream)
{
var writer = new SimpleJson.Writer(stream);
ToJson(writer);
}
void ToJson(SimpleJson.Writer writer)
{
writer.WriteObjectStart();
writer.WriteProperty("inkVersion", inkVersionCurrent);
// Main container content
writer.WriteProperty("root", w => Json.WriteRuntimeContainer(w, _mainContentContainer));
// List definitions
if (_listDefinitions != null) {
writer.WritePropertyStart("listDefs");
writer.WriteObjectStart();
foreach (ListDefinition def in _listDefinitions.lists)
{
writer.WritePropertyStart(def.name);
writer.WriteObjectStart();
foreach (var itemToVal in def.items)
{
InkListItem item = itemToVal.Key;
int val = itemToVal.Value;
writer.WriteProperty(item.itemName, val);
}
writer.WriteObjectEnd();
writer.WritePropertyEnd();
}
writer.WriteObjectEnd();
writer.WritePropertyEnd();
}
writer.WriteObjectEnd();
}
/// <summary>
/// Reset the Story back to its initial state as it was when it was
/// first constructed.
/// </summary>
public void ResetState()
{
// TODO: Could make this possible
IfAsyncWeCant ("ResetState");
_state = new StoryState (this);
_state.variablesState.variableChangedEvent += VariableStateDidChangeEvent;
ResetGlobals ();
}
void ResetErrors()
{
_state.ResetErrors ();
}
/// <summary>
/// Unwinds the callstack. Useful to reset the Story's evaluation
/// without actually changing any meaningful state, for example if
/// you want to exit a section of story prematurely and tell it to
/// go elsewhere with a call to ChoosePathString(...).
/// Doing so without calling ResetCallstack() could cause unexpected
/// issues if, for example, the Story was in a tunnel already.
/// </summary>
public void ResetCallstack()
{
IfAsyncWeCant ("ResetCallstack");
_state.ForceEnd ();
}
void ResetGlobals()
{
if (_mainContentContainer.namedContent.ContainsKey ("global decl")) {
var originalPointer = state.currentPointer;
ChoosePath (new Path ("global decl"), incrementingTurnIndex: false);
// Continue, but without validating external bindings,
// since we may be doing this reset at initialisation time.
ContinueInternal ();
state.currentPointer = originalPointer;
}
state.variablesState.SnapshotDefaultGlobals ();
}
public void SwitchFlow(string flowName)
{
IfAsyncWeCant("switch flow");
if (_asyncSaving) throw new System.Exception("Story is already in background saving mode, can't switch flow to "+flowName);
state.SwitchFlow_Internal(flowName);
}
public void RemoveFlow(string flowName)
{
state.RemoveFlow_Internal(flowName);
}
public void SwitchToDefaultFlow()
{
state.SwitchToDefaultFlow_Internal();
}
/// <summary>
/// Continue the story for one line of content, if possible.
/// If you're not sure if there's more content available, for example if you
/// want to check whether you're at a choice point or at the end of the story,
/// you should call <c>canContinue</c> before calling this function.
/// </summary>
/// <returns>The line of text content.</returns>
public string Continue()
{
ContinueAsync(0);
return currentText;
}
/// <summary>
/// Check whether more content is available if you were to call <c>Continue()</c> - i.e.
/// are we mid story rather than at a choice point or at the end.
/// </summary>
/// <value><c>true</c> if it's possible to call <c>Continue()</c>.</value>
public bool canContinue {
get {
return state.canContinue;
}
}
/// <summary>
/// If ContinueAsync was called (with milliseconds limit > 0) then this property
/// will return false if the ink evaluation isn't yet finished, and you need to call
/// it again in order for the Continue to fully complete.
/// </summary>
public bool asyncContinueComplete {
get {
return !_asyncContinueActive;
}
}
/// <summary>
/// An "asnychronous" version of Continue that only partially evaluates the ink,
/// with a budget of a certain time limit. It will exit ink evaluation early if
/// the evaluation isn't complete within the time limit, with the
/// asyncContinueComplete property being false.
/// This is useful if ink evaluation takes a long time, and you want to distribute
/// it over multiple game frames for smoother animation.
/// If you pass a limit of zero, then it will fully evaluate the ink in the same
/// way as calling Continue (and in fact, this exactly what Continue does internally).
/// </summary>
public void ContinueAsync (float millisecsLimitAsync)
{
if( !_hasValidatedExternals )
ValidateExternalBindings ();
ContinueInternal (millisecsLimitAsync);
}
void ContinueInternal (float millisecsLimitAsync = 0)
{
if( _profiler != null )
_profiler.PreContinue();
var isAsyncTimeLimited = millisecsLimitAsync > 0;
_recursiveContinueCount++;
// Doing either:
// - full run through non-async (so not active and don't want to be)
// - Starting async run-through
if (!_asyncContinueActive) {
_asyncContinueActive = isAsyncTimeLimited;
if (!canContinue) {
throw new Exception ("Can't continue - should check canContinue before calling Continue");
}
_state.didSafeExit = false;
_state.ResetOutput ();
// 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 (_recursiveContinueCount == 1)
_state.variablesState.StartVariableObservation();
}
// Async was previously active, but now we want to finish synchronously
else if( _asyncContinueActive && !isAsyncTimeLimited ) {
_asyncContinueActive = false;
}
// Start timing
var durationStopwatch = new Stopwatch ();
durationStopwatch.Start ();
bool outputStreamEndsInNewline = false;
_sawLookaheadUnsafeFunctionAfterNewline = false;
do {
try {
outputStreamEndsInNewline = ContinueSingleStep ();
} catch(StoryException e) {
AddError (e.Message, useEndLineNumber:e.useEndLineNumber);
break;
}
if (outputStreamEndsInNewline)
break;
// Run out of async time?
if (_asyncContinueActive && durationStopwatch.ElapsedMilliseconds > millisecsLimitAsync) {
break;
}
} while(canContinue);
durationStopwatch.Stop ();
Dictionary<string, Object> changedVariablesToObserve = null;
// 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 (outputStreamEndsInNewline || !canContinue) {
// Need to rewind, due to evaluating further than we should?
if( _stateSnapshotAtLastNewline != null ) {
RestoreStateSnapshot ();
}
// Finished a section of content / reached a choice point?
if( !canContinue ) {
if (state.callStack.canPopThread)
AddError ("Thread available to pop, threads should always be flat by the end of evaluation?");
if (state.generatedChoices.Count == 0 && !state.didSafeExit && _temporaryEvaluationContainer == null) {
if (state.callStack.CanPop (PushPopType.Tunnel))
AddError ("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?");
else if (state.callStack.CanPop (PushPopType.Function))
AddError ("unexpectedly reached end of content. Do you need a '~ return'?");
else if (!state.callStack.canPop)
AddError ("ran out of content. Do you need a '-> DONE' or '-> END'?");
else
AddError ("unexpectedly reached end of content for unknown reason. Please debug compiler!");
}
}
state.didSafeExit = false;
_sawLookaheadUnsafeFunctionAfterNewline = false;
if (_recursiveContinueCount == 1)
changedVariablesToObserve = _state.variablesState.CompleteVariableObservation();
_asyncContinueActive = false;
if(onDidContinue != null) onDidContinue();
}
_recursiveContinueCount--;
if( _profiler != null )
_profiler.PostContinue();
// 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( state.hasError || state.hasWarning ) {
if( onError != null ) {
if( state.hasError ) {
foreach(var err in state.currentErrors) {
onError(err, ErrorType.Error);
}
}
if( state.hasWarning ) {
foreach(var err in state.currentWarnings) {
onError(err, ErrorType.Warning);
}
}
ResetErrors();
}
// Throw an exception since there's no error handler
else {
var sb = new StringBuilder();
sb.Append("Ink had ");
if( state.hasError ) {
sb.Append(state.currentErrors.Count);
sb.Append(state.currentErrors.Count == 1 ? " error" : " errors");
if( state.hasWarning ) sb.Append(" and ");
}
if( state.hasWarning ) {
sb.Append(state.currentWarnings.Count);
sb.Append(state.currentWarnings.Count == 1 ? " warning" : " warnings");
}
sb.Append(". It is strongly suggested that you assign an error handler to story.onError. The first issue was: ");
sb.Append(state.hasError ? state.currentErrors[0] : state.currentWarnings[0]);
// If you get this exception, please assign an error handler to your story.
// If you're using Unity, you can do something like this when you create
// your story:
//
// var story = new Ink.Runtime.Story(jsonTxt);
// story.onError = (errorMessage, errorType) => {
// if( errorType == ErrorType.Warning )
// Debug.LogWarning(errorMessage);
// else
// Debug.LogError(errorMessage);
// };
//
//
throw new StoryException(sb.ToString());
}
}
// Send out variable observation events at the last second, since it might trigger new ink to be run
if( changedVariablesToObserve != null && changedVariablesToObserve.Count > 0 ) {
_state.variablesState.NotifyObservers(changedVariablesToObserve);
}
}
bool ContinueSingleStep ()
{
if (_profiler != null)
_profiler.PreStep ();
// Run main step function (walks through content)
Step ();
if (_profiler != null)
_profiler.PostStep ();
// Run out of content and we have a default invisible choice that we can follow?
if (!canContinue && !state.callStack.elementIsEvaluateFromGame) {
TryFollowDefaultInvisibleChoice ();
}
if (_profiler != null)
_profiler.PreSnapshot ();
// Don't save/rewind during string evaluation, which is e.g. used for choices
if (!state.inStringEvaluation) {
// We previously found a newline, but were we just double checking that
// it wouldn't immediately be removed by glue?
if (_stateSnapshotAtLastNewline != null) {
// 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.
var change = CalculateNewlineOutputStateChange (
_stateSnapshotAtLastNewline.currentText, state.currentText,
_stateSnapshotAtLastNewline.currentTags.Count, state.currentTags.Count
);
// 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 || _sawLookaheadUnsafeFunctionAfterNewline) {
RestoreStateSnapshot ();
// Hit a newline for sure, we're done
return 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) {
DiscardSnapshot();
}
}
// Current content ends in a newline - approaching end of our evaluation
if (state.outputStreamEndsInNewline) {
// 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 (canContinue) {
// 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 (_stateSnapshotAtLastNewline == null)
StateSnapshot ();
}
// Can't continue, so we're about to exit - make sure we
// don't have an old state hanging around.
else {
DiscardSnapshot();
}
}
}
if (_profiler != null)
_profiler.PostSnapshot ();
// outputStreamEndsInNewline = false
return false;
}
// Assumption: prevText is the snapshot where we saw a newline, and we're checking whether we're really done
// with that line. Therefore prevText will definitely end in a newline.
//
// We take tags into account too, so that a tag following a content line:
// Content
// # tag
// ... doesn't cause the tag to be wrongly associated with the content above.
enum OutputStateChange
{
NoChange,
ExtendedBeyondNewline,
NewlineRemoved
}
OutputStateChange CalculateNewlineOutputStateChange (string prevText, string currText, int prevTagCount, int currTagCount)
{
// Simple case: nothing's changed, and we still have a newline
// at the end of the current content
var newlineStillExists = currText.Length >= prevText.Length && prevText.Length > 0 && currText [prevText.Length - 1] == '\n';
if (prevTagCount == currTagCount && prevText.Length == currText.Length
&& newlineStillExists)
return OutputStateChange.NoChange;
// Old newline has been removed, it wasn't the end of the line after all
if (!newlineStillExists) {
return OutputStateChange.NewlineRemoved;
}
// Tag added - definitely the start of a new line
if (currTagCount > prevTagCount)
return OutputStateChange.ExtendedBeyondNewline;
// There must be new content - check whether it's just whitespace
for (int i = prevText.Length; i < currText.Length; i++) {
var c = currText [i];
if (c != ' ' && c != '\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.
return OutputStateChange.NoChange;
}
/// <summary>
/// Continue the story until the next choice point or until it runs out of content.
/// This is as opposed to the Continue() method which only evaluates one line of
/// output at a time.
/// </summary>
/// <returns>The resulting text evaluated by the ink engine, concatenated together.</returns>
public string ContinueMaximally()
{
IfAsyncWeCant ("ContinueMaximally");
var sb = new StringBuilder ();
while (canContinue) {
sb.Append (Continue ());
}
return sb.ToString ();
}
public SearchResult ContentAtPath(Path path)
{
return mainContentContainer.ContentAtPath (path);
}
public Runtime.Container KnotContainerWithName (string name)
{
INamedContent namedContainer;
if (mainContentContainer.namedContent.TryGetValue (name, out namedContainer))
return namedContainer as Container;
else
return null;
}
public Pointer PointerAtPath (Path path)
{
if (path.length == 0)
return Pointer.Null;
var p = new Pointer ();
int pathLengthToUse = path.length;
SearchResult result;
if( path.lastComponent.isIndex ) {
pathLengthToUse = path.length - 1;
result = mainContentContainer.ContentAtPath (path, partialPathLength:pathLengthToUse);
p.container = result.container;
p.index = path.lastComponent.index;
} else {
result = mainContentContainer.ContentAtPath (path);
p.container = result.container;
p.index = -1;
}
if (result.obj == null || result.obj == mainContentContainer && pathLengthToUse > 0)
Error ("Failed to find content at path '" + path + "', and no approximation of it was possible.");
else if (result.approximate)
Warning ("Failed to find content at path '" + path + "', so it was approximated to: '"+result.obj.path+"'.");
return p;
}
// Maximum snapshot stack:
// - stateSnapshotDuringSave -- not retained, but returned to game code
// - _stateSnapshotAtLastNewline (has older patch)
// - _state (current, being patched)
void StateSnapshot()
{
_stateSnapshotAtLastNewline = _state;
_state = _state.CopyAndStartPatching(forBackgroundSave:false);
}
void RestoreStateSnapshot()
{
// Patched state had temporarily hijacked our
// VariablesState and set its own callstack on it,
// so we need to restore that.
// If we're in the middle of saving, we may also
// need to give the VariablesState the old patch.
_stateSnapshotAtLastNewline.RestoreAfterPatch();
_state = _stateSnapshotAtLastNewline;
_stateSnapshotAtLastNewline = null;
// If save completed while the above snapshot was
// active, we need to apply any changes made since
// the save was started but before the snapshot was made.
if( !_asyncSaving ) {
_state.ApplyAnyPatch();
}
}
void DiscardSnapshot()
{
// Normally we want to integrate the patch
// into the main global/counts dictionaries.
// However, if we're in the middle of async
// saving, we simply stay in a "patching" state,
// albeit with the newer cloned patch.
if( !_asyncSaving )
_state.ApplyAnyPatch();
// No longer need the snapshot.
_stateSnapshotAtLastNewline = null;
}
/// <summary>
/// Advanced usage!
/// If you have a large story, and saving state to JSON takes too long for your
/// framerate, you can temporarily freeze a copy of the state for saving on
/// a separate thread. Internally, the engine maintains a "diff patch".
/// When you've finished saving your state, call BackgroundSaveComplete()
/// and that diff patch will be applied, allowing the story to continue
/// in its usual mode.
/// </summary>
/// <returns>The state for background thread save.</returns>
public StoryState CopyStateForBackgroundThreadSave()
{
IfAsyncWeCant("start saving on a background thread");
if (_asyncSaving) throw new System.Exception("Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!");
var stateToSave = _state;
_state = _state.CopyAndStartPatching(forBackgroundSave:true);
_asyncSaving = true;
return stateToSave;
}
/// <summary>
/// See CopyStateForBackgroundThreadSave. This method releases the
/// "frozen" save state, applying its patch that it was using internally.
/// </summary>
public void BackgroundSaveComplete()
{
// CopyStateForBackgroundThreadSave must be called outside
// of any async ink evaluation, since otherwise you'd be saving
// during an intermediate state.
// However, it's possible to *complete* the save in the middle of
// a glue-lookahead when there's a state stored in _stateSnapshotAtLastNewline.
// This state will have its own patch that is newer than the save patch.
// We hold off on the final apply until the glue-lookahead is finished.
// In that case, the apply is always done, it's just that it may
// apply the looked-ahead changes OR it may simply apply the changes
// made during the save process to the old _stateSnapshotAtLastNewline state.
if ( _stateSnapshotAtLastNewline == null ) {
_state.ApplyAnyPatch();
}
_asyncSaving = false;
}
void Step ()
{
bool shouldAddToStream = true;
// Get current content
var pointer = state.currentPointer;
if (pointer.isNull) {
return;
}
// Step directly to the first element of content in a container (if necessary)
Container containerToEnter = pointer.Resolve () as Container;
while(containerToEnter) {
// Mark container as being entered
VisitContainer (containerToEnter, atStart:true);
// No content? the most we can do is step past it
if (containerToEnter.content.Count == 0)
break;
pointer = Pointer.StartOf (containerToEnter);
containerToEnter = pointer.Resolve() as Container;
}
state.currentPointer = pointer;
if( _profiler != null ) {
_profiler.Step(state.callStack);
}
// 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)
var currentContentObj = pointer.Resolve ();
bool isLogicOrFlowControl = PerformLogicAndFlowControl (currentContentObj);
// Has flow been forced to end by flow control above?
if (state.currentPointer.isNull) {
return;
}
if (isLogicOrFlowControl) {
shouldAddToStream = false;
}
// Choice with condition?
var choicePoint = currentContentObj as ChoicePoint;
if (choicePoint) {
var choice = ProcessChoice (choicePoint);
if (choice) {
state.generatedChoices.Add (choice);
}
currentContentObj = null;
shouldAddToStream = false;
}
// If the container has no content, then it will be
// the "content" itself, but we skip over it.
if (currentContentObj is Container) {
shouldAddToStream = false;
}
// Content to add to evaluation stack or the output stream
if (shouldAddToStream) {
// 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.
var varPointer = currentContentObj as VariablePointerValue;
if (varPointer && varPointer.contextIndex == -1) {
// Create new object so we're not overwriting the story's own data
var contextIdx = state.callStack.ContextForVariableNamed(varPointer.variableName);
currentContentObj = new VariablePointerValue (varPointer.variableName, contextIdx);
}
// Expression evaluation content
if (state.inExpressionEvaluation) {
state.PushEvaluationStack (currentContentObj);
}
// Output stream content (i.e. not expression evaluation)
else {
state.PushToOutputStream (currentContentObj);
}
}
// Increment the content pointer, following diverts if necessary
NextContent ();
// 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.
var controlCmd = currentContentObj as ControlCommand;
if (controlCmd && controlCmd.commandType == ControlCommand.CommandType.StartThread) {
state.callStack.PushThread ();
}
}
// Mark a container as having been visited
void VisitContainer(Container container, bool atStart)
{
if ( !container.countingAtStartOnly || atStart ) {
if( container.visitsShouldBeCounted )
state.IncrementVisitCountForContainer (container);
if (container.turnIndexShouldBeCounted)
state.RecordTurnIndexVisitToContainer (container);
}
}
List<Container> _prevContainers = new List<Container>();
void VisitChangedContainersDueToDivert()
{
var previousPointer = state.previousPointer;
var pointer = state.currentPointer;
// Unless we're pointing *directly* at a piece of content, we don't do
// counting here. Otherwise, the main stepping function will do the counting.
if (pointer.isNull || pointer.index == -1)
return;
// First, find the previously open set of containers
_prevContainers.Clear();
if (!previousPointer.isNull) {
Container prevAncestor = previousPointer.Resolve() as Container ?? previousPointer.container as Container;