This repository was archived by the owner on Mar 1, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathDialogueRunner.cpp
More file actions
372 lines (275 loc) · 11.4 KB
/
DialogueRunner.cpp
File metadata and controls
372 lines (275 loc) · 11.4 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
// Fill out your copyright notice in the Description page of Project Settings.
#include "DialogueRunner.h"
#include "Line.h"
#include "Option.h"
#include "YarnSubsystem.h"
#include "Misc/YSLogging.h"
THIRD_PARTY_INCLUDES_START
#include "YarnSpinnerCore/VirtualMachine.h"
THIRD_PARTY_INCLUDES_END
//#include "StaticParty.h"
// Sets default values
ADialogueRunner::ADialogueRunner()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ADialogueRunner::PreInitializeComponents()
{
Super::PreInitializeComponents();
if (!YarnProject)
{
UE_LOG(LogYarnSpinner, Error, TEXT("DialogueRunner can't initialize, because it doesn't have a Yarn Asset."));
return;
}
YarnProject->Init();
Yarn::Program Program{};
bool bParseSuccess = Program.ParsePartialFromArray(YarnProject->Data.GetData(), YarnProject->Data.Num());
if (!bParseSuccess)
{
UE_LOG(LogYarnSpinner, Error, TEXT("DialogueRunner can't initialize, because its Yarn Asset failed to load."));
return;
}
// Create the Library
Library = MakeUnique<Yarn::Library>();
// Create the VirtualMachine, supplying it with the loaded Program and
// configuring it to use our library, plus use this ADialogueRunner as the
// logger and the variable storage
VirtualMachine = MakeUnique<Yarn::VirtualMachine>(Program, *(Library), *this);
VirtualMachine->OnLine.AddLambda([this](const Yarn::Line& Line)
{
YS_LOG("Received line %s", *Line.LineID);
// Get the Yarn line struct, and make a ULine out of it to use
ULine* LineObject = NewObject<ULine>(this);
LineObject->LineID = FName(*Line.LineID);
GetDisplayTextForLine(LineObject, Line);
const TArray<TSoftObjectPtr<UObject>> LineAssets = YarnProject->GetLineAssets(LineObject->LineID);
YS_LOG_FUNC("Got %d line assets for line '%s'", LineAssets.Num(), *LineObject->LineID.ToString())
OnRunLine(LineObject, LineAssets);
});
VirtualMachine->OnOptions.AddLambda([this](const Yarn::OptionSet& OptionSet)
{
YS_LOG("Received %llu options", OptionSet.Options.Num());
// Build a TArray for every option in this OptionSet
TArray<UOption*> Options;
for (const Yarn::Option& Option : OptionSet.Options)
{
YS_LOG("- %i: %s", Option.ID, *Option.Line.LineID);
UOption* Opt = NewObject<UOption>(this);
Opt->OptionID = Option.ID;
Opt->Line = NewObject<ULine>(Opt);
Opt->Line->LineID = FName(*Option.Line.LineID);
GetDisplayTextForLine(Opt->Line, Option.Line);
Opt->bIsAvailable = Option.IsAvailable;
Opt->SourceDialogueRunner = this;
Options.Add(Opt);
}
OnRunOptions(Options);
});
VirtualMachine->OnCheckFunctionExist.BindLambda([this](const FString& FunctionName) -> bool
{
return YarnSubsystem()->GetYarnLibraryRegistry()->HasFunction(FName(*FunctionName));
});
VirtualMachine->OnGetFunctionParamNum.BindLambda([this](const FString& FunctionName) -> int
{
return YarnSubsystem()->GetYarnLibraryRegistry()->GetExpectedFunctionParamCount(FName(*FunctionName));
});
VirtualMachine->OnCallFunction.BindLambda([this](const FString& FunctionName, const TArray<Yarn::FValue>& Parameters) -> Yarn::FValue
{
return YarnSubsystem()->GetYarnLibraryRegistry()->CallFunction(
FName(*FunctionName),
Parameters
);
});
VirtualMachine->OnCommand.AddLambda([this](const Yarn::Command& Command)
{
YS_LOG("Received command \"%s\"", *Command.Text);
const FString& CommandText = Command.Text;
TArray<FString> CommandElements;
CommandText.ParseIntoArray(CommandElements, TEXT(" "));
if (CommandElements.Num() == 0)
{
UE_LOG(LogYarnSpinner, Error, TEXT("Command received, but was unable to parse it."));
OnRunCommand(FString("(unknown)"), TArray<FString>());
return;
}
const FName CommandName = FName(CommandElements[0]);
CommandElements.RemoveAt(0);
const UYarnLibraryRegistry* const Lib = YarnSubsystem()->GetYarnLibraryRegistry();
if (Lib->HasCommand(CommandName))
{
return Lib->CallCommand(
CommandName,
this,
CommandElements
);
}
// Haven't handled the function yet, so call the DialogueRunner's handler
OnRunCommand(CommandName.ToString(), CommandElements);
});
VirtualMachine->OnNodeStart.AddLambda( [this](const FString& NodeName)
{
UE_LOG(LogYarnSpinner, Log, TEXT("Received node start \"%s\""), *NodeName);
});
VirtualMachine->OnNodeComplete.AddLambda([this](const FString& NodeName)
{
UE_LOG(LogYarnSpinner, Log, TEXT("Received node complete \"%s\""), *NodeName);
});
VirtualMachine->OnDialogueComplete.AddLambda([this]()
{
UE_LOG(LogYarnSpinner, Log, TEXT("Received dialogue complete"));
OnDialogueEnded();
});
}
// Called every frame
void ADialogueRunner::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void ADialogueRunner::OnDialogueStarted_Implementation()
{
// default = no-op
}
void ADialogueRunner::OnDialogueEnded_Implementation()
{
// default = no-op
}
void ADialogueRunner::OnRunLine_Implementation(ULine* Line, const TArray<TSoftObjectPtr<UObject>>& LineAssets)
{
// default = log and immediately continue
UE_LOG(LogYarnSpinner, Warning, TEXT("DialogueRunner received line with ID \"%s\". Implement OnRunLine to customise its behaviour."), *Line->LineID.ToString());
ContinueDialogue();
}
void ADialogueRunner::OnRunOptions_Implementation(const TArray<class UOption*>& Options)
{
// default = log and choose the first option
UE_LOG(LogYarnSpinner, Warning, TEXT("DialogueRunner received %i options. Choosing the first one by default. Implement OnRunOptions to customise its behaviour."), Options.Num());
SelectOption(Options[0]);
}
void ADialogueRunner::OnRunCommand_Implementation(const FString& Command, const TArray<FString>& Parameters)
{
// default = no-op
UE_LOG(LogYarnSpinner, Warning, TEXT("DialogueRunner received command \"%s\". Implement OnRunCommand to customise its behaviour."), *Command);
ContinueDialogue();
}
/** Starts running dialogue from the given node name. */
void ADialogueRunner::StartDialogue(FName NodeName)
{
if (VirtualMachine.IsValid() == false)
{
UE_LOG(LogYarnSpinner, Error, TEXT("DialogueRunner can't start node %s, because it failed to load a Yarn asset."), *NodeName.ToString());
return;
}
bool bNodeSelected = VirtualMachine->SetNode(NodeName.ToString());
if (bNodeSelected)
{
OnDialogueStarted();
ContinueDialogue();
}
else
{
UE_LOG(LogYarnSpinner, Error, TEXT("DialogueRunner can't start node %s, because a node with that name was not found."), *NodeName.ToString());
return;
}
}
/** Continues running the current dialogue, producing either lines, options, commands, or a dialogue-end signal. */
void ADialogueRunner::ContinueDialogue()
{
YS_LOG_FUNCSIG
if (VirtualMachine->GetCurrentExecutionState() == Yarn::VirtualMachine::ExecutionState::ERROR)
{
UE_LOG(LogYarnSpinner, Error, TEXT("VirtualMachine is in an error state and cannot continue running."));
return;
}
VirtualMachine->Continue();
Yarn::VirtualMachine::ExecutionState State = VirtualMachine->GetCurrentExecutionState();
if (State == Yarn::VirtualMachine::ExecutionState::ERROR)
{
UE_LOG(LogYarnSpinner, Error, TEXT("VirtualMachine encountered an error."));
return;
}
}
/** Indicates to the dialogue runner that an option was selected. */
void ADialogueRunner::SelectOption(UOption* Option)
{
Yarn::VirtualMachine::ExecutionState State = this->VirtualMachine->GetCurrentExecutionState();
if (State != Yarn::VirtualMachine::ExecutionState::WAITING_ON_OPTION_SELECTION)
{
UE_LOG(LogYarnSpinner, Error, TEXT("Dialogue Runner received a call to SelectOption but it wasn't expecting a selection!"));
return;
}
UE_LOG(LogYarnSpinner, Log, TEXT("Selected option %i (%s)"), Option->OptionID, *Option->Line->LineID.ToString());
VirtualMachine->SetSelectedOption(Option->OptionID);
if (bRunLinesForSelectedOptions)
{
const TArray<TSoftObjectPtr<UObject>> LineAssets = YarnProject->GetLineAssets(Option->Line->LineID);
YS_LOG_FUNC("Got %d line assets for line '%s'", LineAssets.Num(), *Option->Line->LineID.ToString())
OnRunLine(Option->Line, LineAssets);
}
else
{
ContinueDialogue();
}
}
void ADialogueRunner::SetValue(const FString& Name, bool bValue)
{
YS_LOG("Setting variable %s to bool %i", *Name, bValue);
YarnSubsystem()->SetValue(Name, bValue);
}
void ADialogueRunner::SetValue(const FString& Name, float Value)
{
YS_LOG("Setting variable %s to float %f", *Name, Value);
YarnSubsystem()->SetValue(Name, Value);
}
void ADialogueRunner::SetValue(const FString& Name, const FString& Value)
{
YS_LOG("Setting variable %s to string %s", *Name, *Value);
YarnSubsystem()->SetValue(Name, Value);
}
bool ADialogueRunner::HasValue(const FString& Name)
{
return YarnSubsystem()->HasValue(Name);
}
Yarn::FValue ADialogueRunner::GetValue(const FString& Name)
{
Yarn::FValue Value = YarnSubsystem()->GetValue(Name);
YS_LOG("Retrieving variable %s with value %s", *Name, *Value.ConvertToString());
return Value;
}
void ADialogueRunner::ClearValue(const FString& Name)
{
YS_LOG("Clearing variable %s", *Name);
YarnSubsystem()->ClearValue(Name);
}
UYarnSubsystem* ADialogueRunner::YarnSubsystem() const
{
if (!GetGameInstance())
{
YS_WARN("Could not retrieve YarnSubsystem because GetGameInstance() returned null")
return nullptr;
}
return GetGameInstance()->GetSubsystem<UYarnSubsystem>();
}
void ADialogueRunner::GetDisplayTextForLine(ULine* Line, const Yarn::Line& YarnLine)
{
const FName LineID = FName(*YarnLine.LineID);
// This assumes that we only ever care about lines that actually exist in .yarn files (rather than allowing extra lines in .csv files)
if (!YarnProject || !YarnProject->Lines.Contains(LineID))
{
Line->DisplayText = FText::FromString(TEXT("(missing line!)"));
return;
}
const FText LocalisedDisplayText = FText::FromString(FTextLocalizationManager::Get().GetDisplayString({YarnProject->GetName()}, {LineID.ToString()}, nullptr).Get());
const FText NonLocalisedDisplayText = FText::FromString(YarnProject->Lines[LineID]);
// Apply substitutions
FFormatOrderedArguments FormatArgs;
for (const FString& Substitution : YarnLine.Substitutions)
{
FormatArgs.Emplace(FText::FromString(Substitution));
}
const FText TextWithSubstitutions = (LocalisedDisplayText.IsEmptyOrWhitespace()) ? FText::Format(NonLocalisedDisplayText, FormatArgs) : FText::Format(LocalisedDisplayText, FormatArgs);
// TODO: add support for markup & context (speaker, target)
YS_LOG_FUNC("Setting line %s to display text '%s'", *LineID.ToString(), *TextWithSubstitutions.ToString())
Line->DisplayText = TextWithSubstitutions;
}