Compare commits
9
Commits
8982ad7092
..
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58015f5ff8 | ||
|
|
084ea7f0eb | ||
|
|
b5ad858c5e | ||
|
|
bd55716349 | ||
|
|
9f86bdbb0c | ||
|
|
5200db1562 | ||
|
|
2d3f4761e7 | ||
|
|
88964cab6b | ||
|
|
aca89c631f |
No files matched your search
@@ -0,0 +1,30 @@
|
||||
# Line endings: LF everywhere, on every OS, whatever core.autocrlf says.
|
||||
* text=auto eol=lf
|
||||
|
||||
# cmd.exe misreads labels and goto in LF batch files, so they stay CRLF.
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
|
||||
# Binaries: never converted, never diffed as text.
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.webp binary
|
||||
*.svg text
|
||||
*.ogg binary
|
||||
*.wav binary
|
||||
*.mp3 binary
|
||||
*.ttf binary
|
||||
*.otf binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
*.dll binary
|
||||
*.so binary
|
||||
*.dylib binary
|
||||
*.pdb binary
|
||||
*.exe binary
|
||||
*.zip binary
|
||||
*.pck binary
|
||||
*.moc3 binary
|
||||
*.res binary
|
||||
*.scn binary
|
||||
+4
-1
@@ -8,7 +8,10 @@
|
||||
"sources": [
|
||||
"src/**/*.cs"
|
||||
],
|
||||
"depends": ["base2d>=1", "interactive_base>=1", "effects_base>=1", "time_base>=1", "map_base>=1", "interface>=1"],
|
||||
"test_sources": [
|
||||
"tests/*.cs"
|
||||
],
|
||||
"depends": ["shell2d_base>=1", "interactive_base>=1", "effects_base>=1", "time_base>=1", "map_base>=1", "ui_base>=1"],
|
||||
"ui": [],
|
||||
"test_suites": [
|
||||
{"id": "autoplay", "activate": ["--choices=", "--timeout="]},
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
[gd_scene load_steps=3 format=3]
|
||||
[gd_scene load_steps=4 format=3]
|
||||
|
||||
[ext_resource type="PackedScene" path="res://mods/base2d/scenes/ui/base_scene.tscn" id="1_target"]
|
||||
[ext_resource type="PackedScene" path="res://mods/shell2d_base/scenes/ui/base_scene.tscn" id="1_target"]
|
||||
[ext_resource type="Script" path="res://mods/dialog_base/src/UI/Executable/ExecutableMainEventChain.cs" id="2_chain"]
|
||||
[ext_resource type="PackedScene" path="res://scenes/ui/dialog_canvas.tscn" id="3_dialog"]
|
||||
|
||||
[node name="BaseScene" instance=ExtResource("1_target")]
|
||||
script = ExtResource("2_chain")
|
||||
|
||||
[node name="DialogCanvas" parent="Scene" index="2" instance=ExtResource("3_dialog")]
|
||||
@@ -0,0 +1,26 @@
|
||||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://mods/dialog_base/src/UI/Dialog/AnswerBox.cs" id="1_answerbox"]
|
||||
[ext_resource type="PackedScene" path="res://mods/dialog_base/scenes/ui/answer_item.tscn" id="2_answeritem"]
|
||||
|
||||
[node name="AnswerBox" type="Control"]
|
||||
layout_mode = 3
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
script = ExtResource("1_answerbox")
|
||||
itemScene = ExtResource("2_answeritem")
|
||||
content = NodePath("Content")
|
||||
|
||||
[node name="Content" type="VBoxContainer" parent="."]
|
||||
layout_mode = 1
|
||||
anchor_left = 0.6
|
||||
anchor_top = 0.35
|
||||
anchor_right = 0.95
|
||||
anchor_bottom = 0.65
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
mouse_filter = 2
|
||||
alignment = 1
|
||||
@@ -0,0 +1,30 @@
|
||||
[gd_scene format=3 uid="uid://bv80qy227xxee"]
|
||||
|
||||
[ext_resource type="Script" uid="uid://dbrnsck0vtfb3" path="res://mods/dialog_base/src/UI/Dialog/AnswerItem.cs" id="1_answeritem"]
|
||||
|
||||
[node name="AnswerItem" type="Control" unique_id=1180917887]
|
||||
custom_minimum_size = Vector2(0, 50)
|
||||
layout_mode = 3
|
||||
anchors_preset = 0
|
||||
size_flags_horizontal = 3
|
||||
size_flags_vertical = 0
|
||||
script = ExtResource("1_answeritem")
|
||||
|
||||
[node name="Button" type="Button" parent="." unique_id=2087954476]
|
||||
layout_mode = 1
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
|
||||
[node name="TextLabel" type="Label" parent="Button" unique_id=1302827224]
|
||||
layout_mode = 1
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
theme_override_font_sizes/font_size = 22
|
||||
horizontal_alignment = 1
|
||||
vertical_alignment = 1
|
||||
@@ -0,0 +1,106 @@
|
||||
[gd_scene format=3 uid="uid://b8vnxfoixyust"]
|
||||
|
||||
[ext_resource type="Script" uid="uid://b41bti3wq4m88" path="res://mods/dialog_base/src/UI/Dialog/DialogBox.cs" id="1_dialogbox"]
|
||||
|
||||
[ext_resource type="PackedScene" path="res://mods/dialog_base/scenes/ui/answer_box.tscn" id="2_answerbox"]
|
||||
|
||||
[node name="DialogBox" type="Control" unique_id=702809053]
|
||||
layout_mode = 3
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
visible = false
|
||||
script = ExtResource("1_dialogbox")
|
||||
answerBoxScene = ExtResource("2_answerbox")
|
||||
|
||||
[node name="DialogBody" type="ColorRect" parent="." unique_id=1510369637]
|
||||
layout_mode = 1
|
||||
anchors_preset = 12
|
||||
anchor_top = 1.0
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
offset_top = -300.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 0
|
||||
color = Color(0.054902, 0.058824, 0.082353, 0.9)
|
||||
|
||||
[node name="TextField" type="Label" parent="DialogBody" unique_id=2065569930]
|
||||
layout_mode = 1
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
offset_left = 20.0
|
||||
offset_top = 10.0
|
||||
offset_right = -20.0
|
||||
offset_bottom = -10.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
theme_override_font_sizes/font_size = 24
|
||||
theme_override_colors/font_color = Color(0.909804, 0.898039, 0.870588, 1)
|
||||
vertical_alignment = 1
|
||||
autowrap_mode = 2
|
||||
|
||||
[node name="FirstAvatar" type="TextureRect" parent="." unique_id=1696535122]
|
||||
visible = false
|
||||
texture_filter = 1
|
||||
layout_mode = 1
|
||||
anchors_preset = -1
|
||||
anchor_top = 0.6
|
||||
anchor_right = 0.13
|
||||
anchor_bottom = 1.0
|
||||
offset_left = 90.0
|
||||
offset_top = -300.0
|
||||
offset_right = 90.0
|
||||
offset_bottom = -300.0
|
||||
grow_horizontal = 0
|
||||
grow_vertical = 0
|
||||
expand_mode = 1
|
||||
stretch_mode = 4
|
||||
|
||||
[node name="SecondAvatar" type="TextureRect" parent="." unique_id=1913233391]
|
||||
visible = false
|
||||
texture_filter = 1
|
||||
layout_mode = 1
|
||||
anchors_preset = -1
|
||||
anchor_left = 0.87
|
||||
anchor_top = 0.6
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
offset_left = -90.0
|
||||
offset_top = -300.0
|
||||
offset_right = -90.0
|
||||
offset_bottom = -300.0
|
||||
grow_horizontal = 0
|
||||
grow_vertical = 0
|
||||
expand_mode = 1
|
||||
stretch_mode = 4
|
||||
|
||||
[node name="TitleBody" type="Control" parent="." unique_id=1986161675]
|
||||
layout_mode = 1
|
||||
anchors_preset = 8
|
||||
anchor_left = 0.5
|
||||
anchor_top = 0.5
|
||||
anchor_right = 0.5
|
||||
anchor_bottom = 0.5
|
||||
offset_left = -400.0
|
||||
offset_top = -60.0
|
||||
offset_right = 400.0
|
||||
offset_bottom = 60.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
|
||||
[node name="TitleField" type="Label" parent="TitleBody" unique_id=2046072321]
|
||||
visible = false
|
||||
layout_mode = 1
|
||||
anchors_preset = -1
|
||||
anchor_left = -0.5
|
||||
anchor_right = 1.5
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
theme_override_font_sizes/font_size = 28
|
||||
theme_override_colors/font_color = Color(0.956863, 0.941176, 0.905882, 1)
|
||||
horizontal_alignment = 1
|
||||
vertical_alignment = 1
|
||||
@@ -0,0 +1,12 @@
|
||||
[gd_scene format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://mods/dialog_base/src/UI/Dialog/DialogCanvas.cs" id="1_canvas"]
|
||||
|
||||
[node name="DialogCanvas" type="Control"]
|
||||
layout_mode = 3
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
script = ExtResource("1_canvas")
|
||||
@@ -48,8 +48,7 @@ namespace Cthangover.Mods.Dialog
|
||||
if (dlg == null || dlg.Queue.Count == 0)
|
||||
return false;
|
||||
|
||||
dialogBox.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
return true;
|
||||
return dialogBox.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
}
|
||||
|
||||
/// <summary>Runs inline DSL commands (hover effects and similar) through a standalone dialog runtime.</summary>
|
||||
|
||||
@@ -17,8 +17,8 @@ namespace Cthangover.Mods.Dialog
|
||||
return new ScenarioEvent { ScenarioText = scenarioText };
|
||||
}
|
||||
|
||||
/// <summary>Builds an event from a scene event definition's scenario fields.</summary>
|
||||
public IExecutableEvent CreateFromDefinition(string scenarioText, string scenarioId, string condition, bool? lightUseTime, bool isOneRun)
|
||||
/// <summary>Builds an event from a scene event definition's scenario fields, remembering the source file.</summary>
|
||||
public IExecutableEvent CreateFromDefinition(string scenarioText, string scenarioId, string condition, bool? lightUseTime, bool isOneRun, string modId, string filePath)
|
||||
{
|
||||
return new ScenarioEvent
|
||||
{
|
||||
@@ -27,6 +27,8 @@ namespace Cthangover.Mods.Dialog
|
||||
Condition = condition,
|
||||
LightUseTime = lightUseTime,
|
||||
IsOneRun = isOneRun,
|
||||
SourceModId = modId,
|
||||
SourcePath = filePath,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Collections.Generic;
|
||||
using Cthangover.Core.Localization;
|
||||
|
||||
namespace Cthangover.Mods.Dialog.Scenarios
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles the <c>flag name value</c> DSL command: sets a story flag of the
|
||||
/// game through <see cref="DialogQueue.Flag"/>. Flags outlive the dialog
|
||||
/// (saved, reset by a new game) and are what <c>condition:</c> headers read;
|
||||
/// <c>set</c> is the dialog-local counterpart for <c>${var}</c> substitution.
|
||||
/// </summary>
|
||||
public class FlagCommandStrategy : IScenarioCommandStrategy, IScenarioCommandSpec
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public string Command => "flag";
|
||||
/// <inheritdoc/>
|
||||
public int MinPositional => 2;
|
||||
/// <inheritdoc/>
|
||||
public int MaxPositional => 2;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Execute(DialogQueue dlg, List<string> positional, Dictionary<string, string> named, string arrowTarget, ILocalizationProvider locale)
|
||||
=> dlg.Flag(positional[0], positional[1]);
|
||||
}
|
||||
}
|
||||
@@ -36,9 +36,10 @@ namespace Cthangover.Mods.Dialog.Scenarios
|
||||
var lines = text.Split('\n');
|
||||
ActionSelect pendingSelect = null;
|
||||
|
||||
foreach (var rawLine in lines)
|
||||
for (var lineIndex = 0; lineIndex < lines.Length; lineIndex++)
|
||||
{
|
||||
var line = rawLine.Trim();
|
||||
var lineNumber = lineIndex + 1;
|
||||
var line = lines[lineIndex].Trim();
|
||||
if (line.Length == 0 || line.StartsWith('#'))
|
||||
{
|
||||
FinalizePendingSelect(dlg, ref pendingSelect);
|
||||
@@ -48,51 +49,19 @@ namespace Cthangover.Mods.Dialog.Scenarios
|
||||
if (line.StartsWith(':'))
|
||||
{
|
||||
FinalizePendingSelect(dlg, ref pendingSelect);
|
||||
dlg.Point(line.Substring(1));
|
||||
dlg.Point(line.Substring(1)).SourceLine = lineNumber;
|
||||
continue;
|
||||
}
|
||||
|
||||
var tokens = Tokenize(line);
|
||||
if (tokens.Count == 0) continue;
|
||||
|
||||
var cmd = tokens[0].ToLowerInvariant();
|
||||
tokens.RemoveAt(0);
|
||||
|
||||
var positional = new List<string>();
|
||||
var named = new Dictionary<string, string>();
|
||||
var arrowTarget = "";
|
||||
|
||||
for (var i = 0; i < tokens.Count; i++)
|
||||
{
|
||||
var t = tokens[i];
|
||||
if (t == "->")
|
||||
{
|
||||
if (i + 1 < tokens.Count)
|
||||
{
|
||||
arrowTarget = tokens[i + 1].TrimStart(':');
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
var eqIdx = t.IndexOf('=');
|
||||
if (eqIdx > 0)
|
||||
{
|
||||
var name = t.Substring(0, eqIdx);
|
||||
if (IsValidIdent(name))
|
||||
{
|
||||
named[name.ToLowerInvariant()] = t.Substring(eqIdx + 1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
positional.Add(t);
|
||||
}
|
||||
var cmd = SplitLine(line, positional, named, out var arrowTarget);
|
||||
if (cmd == null) continue;
|
||||
|
||||
if (cmd == "select")
|
||||
{
|
||||
FinalizePendingSelect(dlg, ref pendingSelect);
|
||||
pendingSelect = new ActionSelect();
|
||||
pendingSelect = new ActionSelect { SourceLine = lineNumber };
|
||||
var promptText = positional.Count > 0 ? positional[0] : null;
|
||||
|
||||
if (named.TryGetValue("key", out var key) && locale != null)
|
||||
@@ -141,14 +110,67 @@ namespace Cthangover.Mods.Dialog.Scenarios
|
||||
FinalizePendingSelect(dlg, ref pendingSelect);
|
||||
|
||||
var strategy = ScenarioCommandStrategyFactory.Get(cmd);
|
||||
if (strategy != null)
|
||||
if (strategy == null)
|
||||
continue;
|
||||
|
||||
var firstNew = dlg.Queue.Count;
|
||||
strategy.Execute(dlg, positional, named, arrowTarget, locale);
|
||||
for (var i = firstNew; i < dlg.Queue.Count; i++)
|
||||
{
|
||||
if (dlg.Queue[i] != null && dlg.Queue[i].SourceLine == 0)
|
||||
dlg.Queue[i].SourceLine = lineNumber;
|
||||
}
|
||||
}
|
||||
|
||||
FinalizePendingSelect(dlg, ref pendingSelect);
|
||||
return dlg;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits one trimmed, non-empty DSL line the way <see cref="Parse"/> does:
|
||||
/// returns the lowercase command word (null for an empty line) and fills
|
||||
/// the positional tokens, the <c>name=value</c> pairs (names lowercased)
|
||||
/// and the <c>-> :label</c> target. Tools that read scenarios without
|
||||
/// running them (the scenario studio) use it to agree with the parser.
|
||||
/// </summary>
|
||||
public static string SplitLine(string line, List<string> positional, Dictionary<string, string> named, out string arrowTarget)
|
||||
{
|
||||
arrowTarget = "";
|
||||
var tokens = Tokenize(line);
|
||||
if (tokens.Count == 0)
|
||||
return null;
|
||||
|
||||
var cmd = tokens[0].ToLowerInvariant();
|
||||
for (var i = 1; i < tokens.Count; i++)
|
||||
{
|
||||
var t = tokens[i];
|
||||
if (t == "->")
|
||||
{
|
||||
if (i + 1 < tokens.Count)
|
||||
{
|
||||
arrowTarget = tokens[i + 1].TrimStart(':');
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
var eqIdx = t.IndexOf('=');
|
||||
if (eqIdx > 0)
|
||||
{
|
||||
var name = t.Substring(0, eqIdx);
|
||||
if (IsValidIdent(name))
|
||||
{
|
||||
named[name.ToLowerInvariant()] = t.Substring(eqIdx + 1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
positional.Add(t);
|
||||
}
|
||||
|
||||
return cmd;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts YAML-like front-matter metadata from script text. Lines before
|
||||
/// a <c>---</c> separator or the first non-key:value line are parsed as
|
||||
|
||||
@@ -44,6 +44,8 @@ namespace Cthangover.Mods.Dialog.Action
|
||||
public float StartTime { get; private set; }
|
||||
/// <summary>Action IDs whose <see cref="Destruct"/> will be triggered when this action destructs. Used for cross-action cleanup dependencies.</summary>
|
||||
public ISet<string> DelayedDestruct { get; } = new HashSet<string>();
|
||||
/// <summary>1-based scenario line the action was parsed from; 0 when built in code.</summary>
|
||||
public int SourceLine { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Scene node lookup seam for subclasses. Replaces direct
|
||||
@@ -61,12 +63,17 @@ namespace Cthangover.Mods.Dialog.Action
|
||||
ID = Guid.NewGuid().ToString();
|
||||
}
|
||||
|
||||
/// <summary>Idempotent construction: calls <see cref="DoConstruct"/> once and sets <see cref="IsConstructed"/> to true.</summary>
|
||||
/// <summary>
|
||||
/// Idempotent construction: calls <see cref="DoConstruct"/> once and sets <see cref="IsConstructed"/> to true.
|
||||
/// Construction also clears <see cref="IsDestructed"/>: an action reached again through a looping goto is a
|
||||
/// new life of the same object, so its next <see cref="Destruct"/> must release what this construction took.
|
||||
/// </summary>
|
||||
public void Construct()
|
||||
{
|
||||
if(IsConstructed) return;
|
||||
DoConstruct();
|
||||
IsConstructed = true;
|
||||
IsDestructed = false;
|
||||
}
|
||||
|
||||
/// <summary>Idempotent desctruction: calls <see cref="DoDestruct"/> once, then sets <see cref="IsConstructed"/> false and <see cref="IsDestructed"/> true.</summary>
|
||||
@@ -81,7 +88,7 @@ namespace Cthangover.Mods.Dialog.Action
|
||||
/// <summary>Constructs if not already done, records start time, and delegates execution to <see cref="DoRun"/>.</summary>
|
||||
public void Run(DialogRuntime runtime)
|
||||
{
|
||||
if (!IsConstructed) DoConstruct();
|
||||
Construct();
|
||||
StartTime = (float)(Godot.Time.GetTicksUsec() / 1_000_000.0);
|
||||
DoRun(runtime);
|
||||
}
|
||||
|
||||
@@ -39,6 +39,12 @@ namespace Cthangover.Mods.Dialog.Action
|
||||
float WaitTime { get; }
|
||||
/// <summary>Timestamp of the last <see cref="Run"/> call, in seconds since epoch.</summary>
|
||||
float StartTime { get; }
|
||||
/// <summary>
|
||||
/// 1-based line of the scenario text this action was parsed from, 0 for
|
||||
/// actions built in code. Set by <see cref="Scenarios.ScenarioParser"/>;
|
||||
/// debugging tools map the running action back to the script with it.
|
||||
/// </summary>
|
||||
int SourceLine { get; set; }
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using Cthangover.Mods.Effects.Animation;
|
||||
using Cthangover.Core.Factories.Impls;
|
||||
using Cthangover.Mods.Dialog.Action;
|
||||
using Cthangover.Core.UI.Event;
|
||||
using Cthangover.Mods.Interface.View;
|
||||
using Godot;
|
||||
using Cthangover.Core.UI;
|
||||
@@ -15,106 +14,150 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
{
|
||||
/// <summary>
|
||||
/// Frame-animates the scene foreground by swapping ViewBox textures at a
|
||||
/// configurable speed. Loads frames from SpriteIDs on construction
|
||||
/// (OnStartQueue). Unlike AnimationController which crossfades, this does
|
||||
/// hard cuts — simpler but acceptable for foreground effects. The speed
|
||||
/// switches to NextFrameSpeed after the first frame so first-frame delay
|
||||
/// can differ from subsequent frames. Registers as IOnUpdateEvent for
|
||||
/// per-frame advancement. Non-looping mode auto-stops at last frame.
|
||||
/// configurable speed: the first frame lasts 1/<see cref="Speed"/> seconds,
|
||||
/// every later one 1/<see cref="NextFrameSpeed"/>. Hard cuts, no crossfade.
|
||||
/// Frames come from <see cref="Textures"/> or are resolved from
|
||||
/// <see cref="SpriteIDs"/> through <see cref="BackgroundFactory"/> (the same
|
||||
/// texture names a <c>foreground</c> command takes) on construction
|
||||
/// (OnStartQueue).
|
||||
/// <para/>
|
||||
/// Event-driven: each frame schedules one <see cref="SceneTreeTimer"/> for the
|
||||
/// next cut — no per-frame update. The dialog does not wait (NoWait); the
|
||||
/// animation keeps playing while the dialog goes on and stops when the queue
|
||||
/// ends (OnEndQueue), when another animation starts or when a
|
||||
/// <c>foreground</c> command replaces the picture (<see cref="StopActive"/>).
|
||||
/// </summary>
|
||||
public class ActionAnimatedForeground : ActionCommand, IOnUpdateEvent
|
||||
public class ActionAnimatedForeground : ActionCommand
|
||||
{
|
||||
/// <summary>Update priority. Runs after higher-priority listeners. Value 0.</summary>
|
||||
public int Priority => 0;
|
||||
private static ActionAnimatedForeground active;
|
||||
|
||||
/// <summary>List of sprite resource paths to display as animation frames. Loaded in <see cref="DoConstruct"/>.</summary>
|
||||
/// <summary>Texture names resolved through <see cref="BackgroundFactory"/>; ignored when <see cref="Textures"/> is set.</summary>
|
||||
public List<string> SpriteIDs { get; set; }
|
||||
/// <summary>Initial frame rate multiplier for the first frame.</summary>
|
||||
/// <summary>Ready frames used instead of resolving <see cref="SpriteIDs"/> (bypasses the factory like ActionForeground.Texture).</summary>
|
||||
public List<Texture2D> Textures { get; set; }
|
||||
/// <summary>Frames per second of the first frame.</summary>
|
||||
public float Speed { get; set; } = 1f;
|
||||
/// <summary>Frame rate multiplier for subsequent frames after the first. Allows different pacing for the initial frame.</summary>
|
||||
/// <summary>Frames per second of every frame after the first one.</summary>
|
||||
public float NextFrameSpeed { get; set; } = 1f;
|
||||
/// <summary>Whether the animation wraps after the last frame. When false, playback stops at the final frame.</summary>
|
||||
/// <summary>Whether playback restarts from the first frame after the last one; otherwise it stops on the last frame.</summary>
|
||||
public bool IsLoop { get; set; } = true;
|
||||
|
||||
private int currentFrame;
|
||||
private float elapsed;
|
||||
private bool isAnimating;
|
||||
private List<Texture2D> frames;
|
||||
/// <summary>Whether the animation is still cutting frames.</summary>
|
||||
public bool IsAnimating { get; private set; }
|
||||
|
||||
/// <summary>Preloads frames when the dialog queue is first loaded, so textures are ready before playback.</summary>
|
||||
private int currentFrame;
|
||||
private List<Texture2D> frames;
|
||||
private SceneTreeTimer frameTimer;
|
||||
|
||||
/// <summary>Frames are resolved when the queue starts, so the first cut does not stall on loading.</summary>
|
||||
public override ConstructType ConstructType { get; set; } = ConstructType.OnStartQueue;
|
||||
/// <summary>Animation runs in the background — the dialog queue continues immediately.</summary>
|
||||
/// <summary>The animation lives until the dialog ends, not until the next action.</summary>
|
||||
public override DestructType DestructType { get; set; } = DestructType.OnEndQueue;
|
||||
/// <summary>The dialog goes on while the foreground animates.</summary>
|
||||
public override WaitType WaitType { get; set; } = WaitType.NoWait;
|
||||
|
||||
/// <summary>Preloads every sprite in <see cref="SpriteIDs"/> into memory so playback never stalls on I/O.</summary>
|
||||
/// <summary>Stops the animation that currently drives the foreground, if any; the shown frame stays.</summary>
|
||||
public static void StopActive()
|
||||
{
|
||||
active?.Stop();
|
||||
}
|
||||
|
||||
/// <summary>Resolves the frames.</summary>
|
||||
public override void DoConstruct()
|
||||
{
|
||||
base.DoConstruct();
|
||||
LoadFrames();
|
||||
}
|
||||
|
||||
/// <summary>Stops the animation loop; the last shown frame stays on screen.</summary>
|
||||
/// <summary>Stops the frame timer; the last shown frame stays on the ViewBox.</summary>
|
||||
public override void DoDestruct()
|
||||
{
|
||||
base.DoDestruct();
|
||||
isAnimating = false;
|
||||
Stop();
|
||||
}
|
||||
|
||||
private void LoadFrames()
|
||||
{
|
||||
frames = new List<Texture2D>();
|
||||
var source = Textures;
|
||||
if (source != null)
|
||||
{
|
||||
foreach (var tex in source)
|
||||
if (tex != null)
|
||||
frames.Add(tex);
|
||||
return;
|
||||
}
|
||||
|
||||
if (SpriteIDs == null)
|
||||
return;
|
||||
foreach (var id in SpriteIDs)
|
||||
{
|
||||
var tex = GD.Load<Texture2D>(id);
|
||||
var tex = BackgroundFactory.Instance.Get(id);
|
||||
if (tex != null)
|
||||
frames.Add(tex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resets playback to the first frame and shows it on the ViewBox; per-frame stepping happens through <see cref="IOnUpdateEvent.OnUpdate"/>.</summary>
|
||||
/// <summary>Stops a previous animation, shows the first frame on the ViewBox and schedules the next cut.</summary>
|
||||
public override void DoRun(DialogRuntime runtime)
|
||||
{
|
||||
StopActive();
|
||||
currentFrame = 0;
|
||||
elapsed = 0f;
|
||||
isAnimating = frames != null && frames.Count > 0;
|
||||
|
||||
if (isAnimating)
|
||||
{
|
||||
var viewBox = Scene.Find<ViewBox>("ViewBox");
|
||||
viewBox?.SetForegroundTexture(frames[0]);
|
||||
}
|
||||
}
|
||||
|
||||
void IOnUpdateEvent.OnUpdate()
|
||||
{
|
||||
if (!isAnimating || frames == null || frames.Count == 0)
|
||||
IsAnimating = frames != null && frames.Count > 0;
|
||||
if (!IsAnimating)
|
||||
return;
|
||||
|
||||
active = this;
|
||||
ShowFrame();
|
||||
ScheduleNextFrame(Speed);
|
||||
}
|
||||
|
||||
private void ShowFrame()
|
||||
{
|
||||
var viewBox = Scene.Find<ViewBox>("ViewBox");
|
||||
if (viewBox == null)
|
||||
viewBox?.SetForegroundTexture(frames[currentFrame]);
|
||||
}
|
||||
|
||||
private void ScheduleNextFrame(float speed)
|
||||
{
|
||||
if (Godot.Engine.GetMainLoop() is not SceneTree tree)
|
||||
return;
|
||||
|
||||
elapsed += 1f / 60f;
|
||||
var frameDuration = 1f / Mathf.Max(Speed, 0.01f);
|
||||
if (elapsed >= frameDuration)
|
||||
frameTimer = tree.CreateTimer(1f / Mathf.Max(speed, 0.01f));
|
||||
frameTimer.Timeout += OnFrameTimeout;
|
||||
}
|
||||
|
||||
private void OnFrameTimeout()
|
||||
{
|
||||
elapsed -= frameDuration;
|
||||
frameTimer = null;
|
||||
if (!IsAnimating)
|
||||
return;
|
||||
|
||||
currentFrame++;
|
||||
if (currentFrame >= frames.Count)
|
||||
{
|
||||
if (IsLoop)
|
||||
currentFrame = 0;
|
||||
else
|
||||
if (!IsLoop)
|
||||
{
|
||||
isAnimating = false;
|
||||
Stop();
|
||||
return;
|
||||
}
|
||||
currentFrame = 0;
|
||||
}
|
||||
viewBox.SetForegroundTexture(frames[currentFrame]);
|
||||
Speed = NextFrameSpeed;
|
||||
}
|
||||
|
||||
ShowFrame();
|
||||
ScheduleNextFrame(NextFrameSpeed);
|
||||
}
|
||||
|
||||
private void Stop()
|
||||
{
|
||||
IsAnimating = false;
|
||||
if (frameTimer != null)
|
||||
{
|
||||
frameTimer.Timeout -= OnFrameTimeout;
|
||||
frameTimer = null;
|
||||
}
|
||||
if (active == this)
|
||||
active = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,13 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
{
|
||||
/// <summary>
|
||||
/// Tween-driven background fade in/out. Animates the modulate alpha of the
|
||||
/// dialog box's parent Control over Duration seconds. Creates and manages
|
||||
/// its own Tween internally, killing any previous tween before starting a
|
||||
/// new one to prevent overlap. Can optionally set WaitType to WaitTime with
|
||||
/// a matching duration so the dialog pauses during the transition.
|
||||
/// dialog box's parent Control over Duration seconds. The fade belongs to the
|
||||
/// background, not to the action: by default (NoWait) the runtime destructs the
|
||||
/// action right after it runs, and the fade must go on. So the tween is shared
|
||||
/// by all instances — a new fade kills the previous one to prevent overlap —
|
||||
/// and destructing the action leaves it running; the tween is bound to the
|
||||
/// background node and dies with it. Can optionally set WaitType to WaitTime
|
||||
/// with a matching duration so the dialog pauses during the transition.
|
||||
/// </summary>
|
||||
public class ActionBackgroundShowHide : ActionCommand
|
||||
{
|
||||
@@ -25,7 +28,7 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
/// <summary>Duration of the fade tween in seconds.</summary>
|
||||
public float Duration { get; set; } = 1f;
|
||||
|
||||
private Tween activeTween;
|
||||
private static Tween activeTween;
|
||||
|
||||
/// <summary>Default NoWait — overridden by the DialogQueue builder if the wait flag is set, changing to WaitTime to pause during transition.</summary>
|
||||
public override WaitType WaitType { get; set; } = WaitType.NoWait;
|
||||
@@ -47,17 +50,11 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Kills the fade tween so a destructed action cannot keep animating.</summary>
|
||||
public override void DoDestruct()
|
||||
{
|
||||
base.DoDestruct();
|
||||
StopTween();
|
||||
}
|
||||
|
||||
private void StopTween()
|
||||
private static void StopTween()
|
||||
{
|
||||
if (activeTween != null)
|
||||
{
|
||||
if (GodotObject.IsInstanceValid(activeTween))
|
||||
activeTween.Kill();
|
||||
activeTween = null;
|
||||
}
|
||||
|
||||
@@ -9,56 +9,82 @@ using Cthangover.Core.UI.Executable;
|
||||
using Cthangover.Core.Scenarios;
|
||||
using Cthangover.Core.Scenes;
|
||||
using Cthangover.Core.Interactive;
|
||||
using Cthangover.Mods.Interface.View;
|
||||
|
||||
namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
{
|
||||
/// <summary>
|
||||
/// Spawns a visual effect from the EffectFactory by ID. The spawned node
|
||||
/// persists until the action is destructed. Uses DestructType.OnDelayed
|
||||
/// because the effect must outlive the action's run — the effect node's own
|
||||
/// animation or lifetime controls when it disappears. DoRun is a no-op
|
||||
/// because construction handles spawning.
|
||||
/// Spawns a visual effect from the EffectFactory by ID (or a ready
|
||||
/// <see cref="Prefab"/>, bypassing the factory like ActionBackground.Texture).
|
||||
/// The scene is instantiated on construction and put into the ViewBox's UI
|
||||
/// layer (above all scene visuals, below the dialog) when the action runs; the
|
||||
/// node persists until the action is destructed. Uses DestructType.OnDelayed
|
||||
/// because the effect must outlive the action's run: the runtime frees it when
|
||||
/// the dialog ends (End destructs every constructed action), unless the effect
|
||||
/// node frees itself first.
|
||||
/// </summary>
|
||||
public class ActionEffect : ActionCommand
|
||||
{
|
||||
/// <summary>Identifier resolved through <see cref="EffectFactory"/> to a PackedScene. The spawned node persists until destructed.</summary>
|
||||
public string EffectID { get; set; }
|
||||
|
||||
/// <summary>Effect scene to spawn instead of resolving <see cref="EffectID"/>; null resolves through the factory.</summary>
|
||||
public PackedScene Prefab { get; set; }
|
||||
|
||||
private Node spawnedEffect;
|
||||
|
||||
/// <summary>The dialog continues immediately — the spawned effect plays independently.</summary>
|
||||
public override WaitType WaitType { get; set; } = WaitType.NoWait;
|
||||
/// <summary>OnDelayed ensures the effect node outlives the action's run phase. Destruct is called manually when the effect finishes.</summary>
|
||||
/// <summary>OnDelayed keeps the effect node alive past the action's run; it is freed when the dialog ends.</summary>
|
||||
public override DestructType DestructType { get; set; } = DestructType.OnDelayed;
|
||||
|
||||
/// <summary>Resolves <see cref="EffectID"/> through <see cref="EffectFactory"/> and instantiates the effect scene.</summary>
|
||||
/// <summary>Resolves the effect scene (<see cref="Prefab"/> or <see cref="EffectID"/> through <see cref="EffectFactory"/>) and instantiates it.</summary>
|
||||
public override void DoConstruct()
|
||||
{
|
||||
base.DoConstruct();
|
||||
|
||||
var packedScene = Prefab;
|
||||
if (packedScene == null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(EffectID))
|
||||
return;
|
||||
|
||||
var packedScene = EffectFactory.Instance.Get(EffectID);
|
||||
packedScene = EffectFactory.Instance.Get(EffectID);
|
||||
if (packedScene == null)
|
||||
{
|
||||
GameLogger.Log("DIALOG", $"ActionEffect: effect '{EffectID}' not found", LogLevel.Error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
spawnedEffect = packedScene.Instantiate();
|
||||
}
|
||||
|
||||
/// <summary>No-op: spawning happens during construction so the effect is ready before the queue reaches this point.</summary>
|
||||
/// <summary>Shows the instantiated effect: adds it to the ViewBox UI layer. Without a ViewBox the effect is dropped with an error.</summary>
|
||||
public override void DoRun(DialogRuntime runtime)
|
||||
{
|
||||
if (spawnedEffect == null || spawnedEffect.IsInsideTree())
|
||||
return;
|
||||
|
||||
var layer = Scene.Find<ViewBox>("ViewBox")?.GetInteractiveLayer("ui");
|
||||
if (layer == null)
|
||||
{
|
||||
GameLogger.Log("DIALOG", $"ActionEffect: no ViewBox to show effect '{EffectID}'", LogLevel.Error);
|
||||
spawnedEffect.QueueFree();
|
||||
spawnedEffect = null;
|
||||
return;
|
||||
}
|
||||
|
||||
/// <summary>Frees the spawned effect node; paired with the OnDelayed destruct so effects outlive the action's run.</summary>
|
||||
layer.AddChild(spawnedEffect);
|
||||
}
|
||||
|
||||
/// <summary>Frees the spawned effect node (unless it already freed itself); paired with the OnDelayed destruct so effects outlive the action's run.</summary>
|
||||
public override void DoDestruct()
|
||||
{
|
||||
base.DoDestruct();
|
||||
if (spawnedEffect != null)
|
||||
{
|
||||
if (GodotObject.IsInstanceValid(spawnedEffect))
|
||||
spawnedEffect.QueueFree();
|
||||
spawnedEffect = null;
|
||||
}
|
||||
|
||||
@@ -38,9 +38,10 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
Texture = BackgroundFactory.Instance.Get(SpriteID);
|
||||
}
|
||||
|
||||
/// <summary>Applies the preloaded texture to the ViewBox foreground, then nulls it so a reused action cannot re-apply stale data.</summary>
|
||||
/// <summary>Stops a running foreground animation (it would overwrite the picture), applies the preloaded texture to the ViewBox foreground, then nulls it so a reused action cannot re-apply stale data.</summary>
|
||||
public override void DoRun(DialogRuntime runtime)
|
||||
{
|
||||
ActionAnimatedForeground.StopActive();
|
||||
var viewBox = Scene.Find<ViewBox>("ViewBox");
|
||||
viewBox?.SetForegroundTexture(Texture);
|
||||
Texture = null;
|
||||
|
||||
@@ -14,7 +14,10 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
/// <summary>
|
||||
/// Conditional branch: evaluates a Func<bool> and jumps to TrueGoTo or
|
||||
/// FalseGoTo based on the result. If the chosen target is null/empty, falls
|
||||
/// through to Next(). NoWait so branching is transparent to the player.
|
||||
/// through to the next action. NoWait so branching is transparent to the player:
|
||||
/// the runtime itself advances past a NoWait action, so the branch never calls
|
||||
/// <see cref="DialogRuntime.Next"/> — doing it here as well skipped the action
|
||||
/// after the <c>if</c> without running it.
|
||||
/// </summary>
|
||||
public class ActionIf : ActionCommand
|
||||
{
|
||||
@@ -34,7 +37,6 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
if (Condition == null)
|
||||
{
|
||||
GameLogger.Log("DIALOG", "ActionIf: Condition delegate is null", LogLevel.Error);
|
||||
runtime.Next();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -43,8 +45,6 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
|
||||
if (!string.IsNullOrEmpty(goTo))
|
||||
runtime.TryGoTo(goTo);
|
||||
else
|
||||
runtime.Next();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using Cthangover.Core.Scenes;
|
||||
|
||||
namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
{
|
||||
/// <summary>
|
||||
/// Sets a story flag of the running game (<see cref="ScenarioCondition.SetFlag"/>).
|
||||
/// Unlike <see cref="ActionSet"/>, whose variables end with the dialog, a
|
||||
/// flag is game state: it is saved, read by scenario conditions
|
||||
/// (<c>condition: door == "open"</c>) and its change rescans the scene's
|
||||
/// event chain, so a scenario waiting for it can start right after.
|
||||
/// </summary>
|
||||
public class ActionSetFlag : ActionCommand
|
||||
{
|
||||
/// <summary>Flag name, as used in conditions.</summary>
|
||||
public string Name { get; set; }
|
||||
/// <summary>Flag value; numeric values compare as integers in conditions.</summary>
|
||||
public string Value { get; set; }
|
||||
|
||||
/// <summary>Setting a flag is instant — the dialog continues without pause.</summary>
|
||||
public override WaitType WaitType { get; set; } = WaitType.NoWait;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void DoRun(DialogRuntime runtime) => ScenarioCondition.SetFlag(Name, Value ?? string.Empty);
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
/// <summary>Scene switch is deferred — the dialog ends immediately with no return.</summary>
|
||||
public override WaitType WaitType { get; set; } = WaitType.NoWait;
|
||||
|
||||
/// <summary>Marks the dialog locker as OneRun and defers <c>SceneManager.SwitchScene</c> so the tree is not mutated mid-queue.</summary>
|
||||
/// <summary>Defers <c>SceneManager.SwitchScene</c> so the tree is not mutated mid-queue; the owning scenario is not forced into OneRun.</summary>
|
||||
public override void DoRun(DialogRuntime runtime)
|
||||
{
|
||||
if (string.IsNullOrEmpty(SceneName))
|
||||
|
||||
@@ -14,10 +14,12 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
/// subscriber and fires OnUpdateCallback(float t) each frame with a normalized
|
||||
/// progress value (0→1) over WaitTime seconds. WaitType is WaitEvent so the
|
||||
/// dialog runtime pauses until elapsed >= WaitTime, at which point the action
|
||||
/// advances the runtime directly (event-driven — no DialogBox poll) and
|
||||
/// destructs itself. OnStartCallback/OnFinishCallback bracket the animation
|
||||
/// for setup/teardown. Fixed 60fps step for deterministic progress regardless
|
||||
/// of actual frame rate.
|
||||
/// completes itself through <see cref="DialogBox.CompleteAction"/> (event-driven —
|
||||
/// no DialogBox poll) and the box advances the queue, scheduling the timer of a
|
||||
/// following <c>delay</c> like any other advance. OnStartCallback/OnFinishCallback
|
||||
/// bracket the animation for setup/teardown. Progress follows the controller's
|
||||
/// process delta, so the timeline lasts WaitTime seconds of game time at any frame
|
||||
/// rate (and scales with <c>Engine.TimeScale</c> exactly like <c>delay</c> timers).
|
||||
/// </summary>
|
||||
public class ActionTimedUpdate : ActionCommand, IOnUpdateEvent
|
||||
{
|
||||
@@ -31,7 +33,7 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
/// <summary>Fires once when the elapsed time exceeds <see cref="WaitTime"/> or when destructed.</summary>
|
||||
public System.Action OnFinishCallback { get; set; }
|
||||
|
||||
/// <summary>Pauses the dialog until the elapsed time meets WaitTime — the action then advances the runtime itself.</summary>
|
||||
/// <summary>Pauses the dialog until the elapsed time meets WaitTime — the action then completes itself.</summary>
|
||||
public override WaitType WaitType { get; set; } = WaitType.WaitEvent;
|
||||
/// <summary>Total duration in seconds over which <see cref="OnUpdateCallback"/> receives normalized progress.</summary>
|
||||
public override float WaitTime { get; set; } = 1f;
|
||||
@@ -39,12 +41,13 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
private float elapsed;
|
||||
private bool isRunning;
|
||||
private DialogRuntime runtime;
|
||||
private SceneEventController controller;
|
||||
|
||||
/// <summary>Registers this action as an <see cref="IOnUpdateEvent"/> listener on the scene's event controller.</summary>
|
||||
public override void DoConstruct()
|
||||
{
|
||||
base.DoConstruct();
|
||||
var controller = Scene.Find<SceneEventController>("EventController");
|
||||
controller = Scene.Find<SceneEventController>("EventController");
|
||||
controller?.AddUpdateEventListener(this);
|
||||
}
|
||||
|
||||
@@ -63,8 +66,8 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
base.DoDestruct();
|
||||
isRunning = false;
|
||||
runtime = null;
|
||||
var controller = Scene.Find<SceneEventController>("EventController");
|
||||
controller?.RemoveUpdateEventListener(this);
|
||||
controller = null;
|
||||
OnFinishCallback?.Invoke();
|
||||
}
|
||||
|
||||
@@ -73,19 +76,26 @@ namespace Cthangover.Mods.Dialog.Action.Impls
|
||||
if (!isRunning)
|
||||
return;
|
||||
|
||||
elapsed += 1f / 60f;
|
||||
elapsed += (float)(controller?.GetProcessDeltaTime() ?? 0d);
|
||||
|
||||
var t = WaitTime > 0f ? Mathf.Min(elapsed / WaitTime, 1f) : 1f;
|
||||
OnUpdateCallback?.Invoke(t);
|
||||
|
||||
if (elapsed >= WaitTime)
|
||||
{
|
||||
// Advances the runtime directly instead of relying on a DialogBox poll.
|
||||
// Next() destructs this action (firing OnFinishCallback and detaching the
|
||||
// update listener), then Run() continues the queue past the WaitEvent point.
|
||||
if (elapsed < WaitTime)
|
||||
return;
|
||||
|
||||
// Advancing destructs this action, which clears the runtime field:
|
||||
// keep the runtime in a local for the whole completion.
|
||||
isRunning = false;
|
||||
runtime?.Next();
|
||||
runtime?.Run();
|
||||
var owner = runtime;
|
||||
if (owner?.DialogBox != null)
|
||||
{
|
||||
owner.DialogBox.CompleteAction(this);
|
||||
}
|
||||
else if (owner != null)
|
||||
{
|
||||
owner.Next();
|
||||
owner.Run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+128
-18
@@ -80,7 +80,11 @@ namespace Cthangover.Mods.Dialog
|
||||
/// <summary>If false, new dialog queues are rejected. Set externally to prevent dialog during non-dialog scenes.</summary>
|
||||
public bool IsActive { get; set; } = true;
|
||||
|
||||
/// <summary>Called by answer items when the player picks a choice. Hides the answer box and jumps the runtime to the variant's GoTo target.</summary>
|
||||
/// <summary>
|
||||
/// Called by answer items when the player picks a choice. Hides the answer box and jumps the runtime to the
|
||||
/// variant's GoTo target; a variant without a target falls through to the action after the choice (re-running
|
||||
/// the choice itself would show the same answers again forever).
|
||||
/// </summary>
|
||||
public void SelectVariant(SelectVariant variant)
|
||||
{
|
||||
if (answerBox != null)
|
||||
@@ -89,6 +93,9 @@ namespace Cthangover.Mods.Dialog
|
||||
answerBox = null;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(variant.GoTo))
|
||||
Runtime.Next();
|
||||
else
|
||||
Runtime.TryGoTo(variant.GoTo);
|
||||
Runtime.Run();
|
||||
ScheduleWaitTimer();
|
||||
@@ -172,32 +179,51 @@ namespace Cthangover.Mods.Dialog
|
||||
|
||||
/// <summary>
|
||||
/// Loads and starts a dialog sequence. Validates that: (1) dialog is not null, (2) this DialogBox is active,
|
||||
/// (3) no existing dialog locker is running. On success, shows the box and delegates to <see cref="DialogRuntime.SetDialogQueueAndRun"/>.
|
||||
/// (3) no dialog is running — neither one with a locker nor a locker-less one (an interactive's click dialog),
|
||||
/// see <see cref="IsRunning"/>. On success, shows the box and delegates to <see cref="DialogRuntime.SetDialogQueueAndRun"/>.
|
||||
/// Returns false when the queue was rejected, so callers (event chains) do not count a run that never happened.
|
||||
/// </summary>
|
||||
public void SetDialogQueueAndRun(DialogQueue dialog, IEnumerable<IActionCommand> endDialogQueue, int startIndex, ExecutableEvent locker)
|
||||
public bool SetDialogQueueAndRun(DialogQueue dialog, IEnumerable<IActionCommand> endDialogQueue, int startIndex, ExecutableEvent locker)
|
||||
{
|
||||
if (dialog == null)
|
||||
{
|
||||
GameLogger.Log("DIALOG", $"can't run '{locker?.GetType().FullName}', dialog is null", LogLevel.Error);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
if (!IsActive)
|
||||
{
|
||||
GameLogger.Log("DIALOG", $"can't run '{locker?.GetType().FullName}', DialogBox is not active", LogLevel.Error);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Locker != null)
|
||||
if (IsRunning)
|
||||
{
|
||||
GameLogger.Log("DIALOG", $"can't run '{locker?.GetType().FullName}', locker already executing!", LogLevel.Error);
|
||||
return;
|
||||
GameLogger.Log("DIALOG", $"can't run '{locker?.GetType().FullName}', another dialog is already running!", LogLevel.Error);
|
||||
return false;
|
||||
}
|
||||
|
||||
GameLogger.Log("DIALOG", $"SetDialogQueueAndRun: locker='{locker?.GetType().Name}', queue size={dialog?.Queue.Count}");
|
||||
Locker = locker;
|
||||
Show();
|
||||
Runtime.SetDialogQueueAndRun(this, dialog.Queue, endDialogQueue, startIndex);
|
||||
Runtime.Dialog = dialog;
|
||||
Locker = locker;
|
||||
Show();
|
||||
Runtime.Run();
|
||||
ScheduleWaitTimer();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Completion entry point for actions that finish on their own (<see cref="WaitType.WaitEvent"/>): advances
|
||||
/// past <paramref name="action"/> and schedules the wait timer of whatever comes next, exactly like a click
|
||||
/// or an elapsed delay. Ignored when <paramref name="action"/> is no longer the current one (a stale
|
||||
/// completion of an action the dialog already left) or while the debugger holds the runtime.
|
||||
/// </summary>
|
||||
public void CompleteAction(IActionCommand action)
|
||||
{
|
||||
if (Runtime.IsHeld || action == null || Runtime.CurrentAction != action)
|
||||
return;
|
||||
|
||||
Runtime.Next();
|
||||
Runtime.Run();
|
||||
ScheduleWaitTimer();
|
||||
}
|
||||
@@ -209,7 +235,7 @@ namespace Cthangover.Mods.Dialog
|
||||
/// </summary>
|
||||
public void NextAction()
|
||||
{
|
||||
if (Runtime.IsWaitAnswer)
|
||||
if (Runtime.IsHeld || Runtime.IsWaitAnswer)
|
||||
return;
|
||||
if (Runtime.IsEnd)
|
||||
{
|
||||
@@ -242,11 +268,13 @@ namespace Cthangover.Mods.Dialog
|
||||
/// <summary>Advances the dialog on <c>ui_accept</c> or on a click outside the body, unless a choice is pending or the queue has ended.</summary>
|
||||
protected override void OnInput(InputEvent @event)
|
||||
{
|
||||
if (Runtime.IsEnd || Runtime.IsWaitAnswer)
|
||||
if (Runtime.IsHeld || Runtime.IsEnd || Runtime.IsWaitAnswer)
|
||||
return;
|
||||
|
||||
if (@event.IsActionPressed("ui_accept"))
|
||||
{
|
||||
if (IsTyping())
|
||||
return;
|
||||
GameLogger.Log("DIALOG", "input: advancing dialog");
|
||||
NextAction();
|
||||
}
|
||||
@@ -256,6 +284,9 @@ namespace Cthangover.Mods.Dialog
|
||||
if (action == null || action.WaitType == WaitType.WaitTime || action.WaitType == WaitType.WaitEvent)
|
||||
return;
|
||||
|
||||
if (IsOverOtherControl())
|
||||
return;
|
||||
|
||||
if (Body is Control bodyControl)
|
||||
{
|
||||
var bodyRect = bodyControl.GetGlobalRect();
|
||||
@@ -269,8 +300,85 @@ namespace Cthangover.Mods.Dialog
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether a dialog is currently running (Locker is not null).</summary>
|
||||
public bool IsRunning => Locker != null;
|
||||
/// <summary>
|
||||
/// True while a text field has keyboard focus: Enter and Space belong to
|
||||
/// it, not to the dialog (the dialog reads <c>ui_accept</c> in
|
||||
/// <c>_Input</c>, before the GUI).
|
||||
/// </summary>
|
||||
private bool IsTyping() => GetViewport()?.GuiGetFocusOwner() is LineEdit or TextEdit;
|
||||
|
||||
/// <summary>
|
||||
/// True when the mouse is over a control that is not part of this box and
|
||||
/// stops the mouse (a tool panel, a button drawn over the dialog area):
|
||||
/// the click is meant for that control.
|
||||
/// </summary>
|
||||
private bool IsOverOtherControl()
|
||||
{
|
||||
var hovered = GetViewport()?.GuiGetHoveredControl();
|
||||
return hovered != null && hovered != this && !IsAncestorOf(hovered)
|
||||
&& hovered.MouseFilter == MouseFilterEnum.Stop;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Continues a dialog the debugger held (<see cref="DialogRuntime.IsHeld"/>):
|
||||
/// runs from the held action on, exactly as if it had never stopped.
|
||||
/// Does nothing when the runtime is not held.
|
||||
/// </summary>
|
||||
public void Resume()
|
||||
{
|
||||
if (!Runtime.IsHeld)
|
||||
return;
|
||||
|
||||
Runtime.IsHeld = false;
|
||||
Runtime.Run();
|
||||
ScheduleWaitTimer();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a running dialog to another action and holds it there
|
||||
/// (<see cref="DialogRuntime.MoveTo"/>): a pending wait timer and an open
|
||||
/// answer box are dropped, since they belong to the action left behind;
|
||||
/// the shown text stays until the new action replaces it.
|
||||
/// </summary>
|
||||
public bool MoveTo(int queueIndex)
|
||||
{
|
||||
if (!IsRunning)
|
||||
return false;
|
||||
|
||||
ClearWaitTimer();
|
||||
if (answerBox != null)
|
||||
{
|
||||
answerBox.Hide();
|
||||
answerBox = null;
|
||||
}
|
||||
return Runtime.MoveTo(queueIndex);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the running dialog without finishing it (<see cref="DialogRuntime.Abort"/>)
|
||||
/// and frees the box for another queue: closes the answer box, hides
|
||||
/// and releases the locker. The scenario does not count as completed.
|
||||
/// </summary>
|
||||
public void Abort()
|
||||
{
|
||||
ClearWaitTimer();
|
||||
if (answerBox != null)
|
||||
{
|
||||
answerBox.Hide();
|
||||
answerBox = null;
|
||||
}
|
||||
|
||||
Runtime.Abort();
|
||||
Hide();
|
||||
Locker = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a dialog occupies the box: one started by an event (Locker is not null) or a locker-less queue
|
||||
/// that has not ended yet (an interactive's click dialog runs without a locker). Event chains and the click
|
||||
/// runner wait for false before starting anything, which keeps one dialog at a time.
|
||||
/// </summary>
|
||||
public bool IsRunning => Locker != null || !Runtime.IsEnd;
|
||||
|
||||
/// <summary>Whether the current dialog queue reached its end (also true before the first queue loads).</summary>
|
||||
public bool IsDialogEnded => Runtime.IsEnd;
|
||||
@@ -297,13 +405,15 @@ namespace Cthangover.Mods.Dialog
|
||||
/// Schedules a one-shot <see cref="SceneTreeTimer"/> that advances the dialog past the
|
||||
/// current <see cref="WaitType.WaitTime"/> action once its <see cref="ActionCommand.WaitTime"/>
|
||||
/// elapses. Replaces the former per-frame polling: the runtime now yields until the timer
|
||||
/// fires exactly once, so no Update work happens between delays.
|
||||
/// fires exactly once, so no Update work happens between delays. Nothing is scheduled while the
|
||||
/// debugger holds the runtime: the current action has not run yet, its wait starts on
|
||||
/// <see cref="Resume"/>.
|
||||
/// </summary>
|
||||
private void ScheduleWaitTimer()
|
||||
{
|
||||
ClearWaitTimer();
|
||||
|
||||
if (!Runtime.IsWaitTime)
|
||||
if (Runtime.IsHeld || !Runtime.IsWaitTime)
|
||||
return;
|
||||
|
||||
var wait = Runtime.CurrentAction?.WaitTime ?? 0f;
|
||||
@@ -321,13 +431,13 @@ namespace Cthangover.Mods.Dialog
|
||||
/// Fires when the delay timer elapses. The timer already guarantees the wait has
|
||||
/// elapsed, so the runtime is advanced directly — no wall-clock re-check. The
|
||||
/// <see cref="Runtime.IsWaitTime"/> guard skips a stale timer that fired after the
|
||||
/// dialog already moved on.
|
||||
/// dialog already moved on; the hold guard keeps a held, not yet run action in place.
|
||||
/// </summary>
|
||||
private void OnWaitTimerTimeout()
|
||||
{
|
||||
waitTimer = null;
|
||||
|
||||
if (!Runtime.IsWaitTime)
|
||||
if (Runtime.IsHeld || !Runtime.IsWaitTime)
|
||||
return;
|
||||
|
||||
Runtime.Next();
|
||||
|
||||
@@ -130,6 +130,14 @@ namespace Cthangover.Mods.Dialog
|
||||
return action;
|
||||
}
|
||||
|
||||
/// <summary>Sets a story flag of the game (saved, read by scenario conditions) when the queue reaches this point.</summary>
|
||||
public ActionSetFlag Flag(string name, string value)
|
||||
{
|
||||
var action = new ActionSetFlag { Name = name, Value = value };
|
||||
Queue.Add(action);
|
||||
return action;
|
||||
}
|
||||
|
||||
/// <summary>Sets a runtime variable by name, using a lazy-evaluated callback for dynamic values not known at script authoring time.</summary>
|
||||
public ActionSet Set(string name, Func<string> callback)
|
||||
{
|
||||
|
||||
+110
-11
@@ -25,8 +25,14 @@ namespace Cthangover.Mods.Dialog
|
||||
/// GoTo searches the queue linearly by action ID and jumps the index; the
|
||||
/// source action's destruct fires on jump. The isLastGoTo flag prevents double
|
||||
/// advancement when a GoTo is the last action in its branch. End() processes
|
||||
/// an optional cleanup queue (endDialogQueue) before tearing down, and raises
|
||||
/// the dialog-end event via the SceneEventController for chaining.
|
||||
/// an optional cleanup queue (endDialogQueue) before tearing down, and publishes
|
||||
/// <see cref="DialogEndedEvent"/> on the <see cref="ModEventBus"/> exactly once per
|
||||
/// queue — event chains pick the next scenario from it.
|
||||
/// <para/>
|
||||
/// An action may end the queue (<c>end</c>, a goto to a missing label) or start
|
||||
/// another dialog from inside <see cref="Run"/>. Every load, end and abort bumps
|
||||
/// a generation counter, and <see cref="Run"/> stops as soon as the generation
|
||||
/// changed under it: the rest of the loop belongs to a queue that no longer runs.
|
||||
/// Infinite loop protection caps at 100k iterations per Run call.
|
||||
/// </summary>
|
||||
public class DialogRuntime
|
||||
@@ -37,6 +43,7 @@ namespace Cthangover.Mods.Dialog
|
||||
private int goToActionIndex;
|
||||
private int index;
|
||||
private bool isLastGoTo;
|
||||
private int generation;
|
||||
private IDictionary<string, string> variables = new Dictionary<string, string>();
|
||||
|
||||
/// <summary>The dialog box instance this runtime drives. Set when a new queue is loaded.</summary>
|
||||
@@ -57,6 +64,26 @@ namespace Cthangover.Mods.Dialog
|
||||
/// <summary>True when the dialog queue is exhausted (index past end or queue is empty).</summary>
|
||||
public bool IsEnd => Lists.IsEmpty(dialogQueue) || index >= dialogQueue.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Process-wide debugging hook asked before every action (see
|
||||
/// <see cref="IDialogDebugger"/>); null in normal play, which costs one
|
||||
/// null check per action.
|
||||
/// </summary>
|
||||
public static IDialogDebugger Debugger { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// True while the debugger holds the runtime before <see cref="CurrentAction"/>:
|
||||
/// that action has not run yet, so advancing must wait for
|
||||
/// <see cref="DialogBox.Resume"/> instead of skipping it.
|
||||
/// </summary>
|
||||
public bool IsHeld { get; set; }
|
||||
|
||||
/// <summary>Queue index of <see cref="CurrentAction"/>.</summary>
|
||||
public int Index => index;
|
||||
|
||||
/// <summary>Current <c>${name}</c> variables of the dialog, for inspection.</summary>
|
||||
public IReadOnlyDictionary<string, string> Variables => (IReadOnlyDictionary<string, string>)variables;
|
||||
|
||||
/// <summary>Retrieves a stored variable value by name. Returns null if not set.</summary>
|
||||
public string GetVariable(string name)
|
||||
{
|
||||
@@ -111,8 +138,9 @@ namespace Cthangover.Mods.Dialog
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads a new dialog queue and prepares for execution. Resets variables, sets the dialog box reference,
|
||||
/// ends any previous queue (destructing its actions), copies the new queue, and constructs OnStartQueue actions.
|
||||
/// Loads a new dialog queue and prepares for execution. Ends any previous queue first — with its own
|
||||
/// end actions and dialog box, before anything of the new queue is set — then resets variables, sets the
|
||||
/// dialog box reference, copies the new queue, and constructs OnStartQueue actions.
|
||||
/// Note: does NOT call Run() — the caller must call Run() separately.
|
||||
/// </summary>
|
||||
public void SetDialogQueueAndRun(DialogBox dialogBox,
|
||||
@@ -120,13 +148,16 @@ namespace Cthangover.Mods.Dialog
|
||||
IEnumerable<IActionCommand> endQueue,
|
||||
int startIndex = 0)
|
||||
{
|
||||
variables = new Dictionary<string, string>();
|
||||
DialogBox = dialogBox;
|
||||
|
||||
this.endDialogQueue = endQueue == null ? null : endQueue.ToList();
|
||||
if (Lists.IsNotEmpty(this.dialogQueue))
|
||||
End();
|
||||
|
||||
generation++;
|
||||
variables = new Dictionary<string, string>();
|
||||
DialogBox = dialogBox;
|
||||
IsHeld = false;
|
||||
isLastGoTo = false;
|
||||
|
||||
this.endDialogQueue = endQueue == null ? null : endQueue.ToList();
|
||||
this.dialogQueue = queue.ToList();
|
||||
|
||||
index = startIndex;
|
||||
@@ -166,15 +197,42 @@ namespace Cthangover.Mods.Dialog
|
||||
End();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Debugger "set next statement": makes the action at
|
||||
/// <paramref name="queueIndex"/> the next one to run and holds the
|
||||
/// runtime before it (<see cref="IsHeld"/>), so nothing runs until
|
||||
/// <see cref="DialogBox.Resume"/>. The current action is destructed like
|
||||
/// on a goto; actions between the old and the new position neither run
|
||||
/// nor roll back — variables and game state stay as they are. Jumping
|
||||
/// back to an action that already ran re-runs it, exactly like a
|
||||
/// looping goto does. Returns false for an index outside the queue.
|
||||
/// </summary>
|
||||
public bool MoveTo(int queueIndex)
|
||||
{
|
||||
if (Lists.IsEmpty(dialogQueue) || queueIndex < 0 || queueIndex >= dialogQueue.Count)
|
||||
return false;
|
||||
|
||||
var current = index >= 0 && index < dialogQueue.Count ? dialogQueue[index] : null;
|
||||
if (current != null && current.IsConstructed && current.DestructType == DestructType.OnEndAction)
|
||||
current.Destruct();
|
||||
|
||||
index = queueIndex;
|
||||
isLastGoTo = false;
|
||||
IsHeld = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Main execution loop. Iterates through actions, calling <see cref="IActionCommand.Run"/> on each and advancing
|
||||
/// automatically for <see cref="WaitType.NoWait"/> actions. Stops the loop on any wait-type action (WaitClick, WaitSelect,
|
||||
/// WaitTime, WaitEvent) so the runtime yields control until the condition is satisfied. Protected against infinite loops
|
||||
/// WaitTime, WaitEvent) so the runtime yields control until the condition is satisfied. Returns right after an action
|
||||
/// that ended or replaced the queue (see the generation note on the class). Protected against infinite loops
|
||||
/// with a 100,000-iteration cap.
|
||||
/// </summary>
|
||||
public void Run()
|
||||
{
|
||||
var iteration = 0;
|
||||
var runGeneration = generation;
|
||||
for (;;)
|
||||
{
|
||||
var action = CurrentAction;
|
||||
@@ -188,7 +246,15 @@ namespace Cthangover.Mods.Dialog
|
||||
|
||||
GameLogger.Log("DIALOG", $"Run: idx={index}/{dialogQueue.Count-1} type={action.GetType().Name} wait={action.WaitType}", LogLevel.Debug);
|
||||
|
||||
if (Debugger != null && Debugger.ShouldHold(this, action))
|
||||
{
|
||||
IsHeld = true;
|
||||
return;
|
||||
}
|
||||
|
||||
action.Run(this);
|
||||
if (runGeneration != generation)
|
||||
return;
|
||||
|
||||
if (iteration++ > 100000)
|
||||
{
|
||||
@@ -214,7 +280,8 @@ namespace Cthangover.Mods.Dialog
|
||||
|
||||
/// <summary>
|
||||
/// Advances the queue index by one. Destructs the current action if its <see cref="DestructType"/> is OnEndAction.
|
||||
/// Processes any delayed-destruct targets registered by the current action. Calls <see cref="End"/> if the queue is exhausted.
|
||||
/// Processes any delayed-destruct targets registered by the current action. Calls <see cref="End"/> if the queue is
|
||||
/// already exhausted (nothing to advance to).
|
||||
/// Respects <see cref="isLastGoTo"/> — if a GoTo was the final action, the index is not incremented.
|
||||
/// </summary>
|
||||
public void Next()
|
||||
@@ -239,6 +306,7 @@ namespace Cthangover.Mods.Dialog
|
||||
{
|
||||
GameLogger.Log("DIALOG", "Next: queue exhausted, ending");
|
||||
End();
|
||||
return;
|
||||
}
|
||||
|
||||
index++;
|
||||
@@ -246,11 +314,17 @@ namespace Cthangover.Mods.Dialog
|
||||
|
||||
/// <summary>
|
||||
/// Terminates the dialog queue. Destructs all remaining constructed actions, hides the dialog box, processes the
|
||||
/// end-dialog cleanup queue (if any), and raises the dialog-end event via <see cref="SceneEventController"/>.
|
||||
/// end-dialog cleanup queue (if any), and publishes <see cref="DialogEndedEvent"/> on the <see cref="ModEventBus"/>.
|
||||
/// Guards against end-queue actions starting a new dialog mid-cleanup by checking if the queue changed.
|
||||
/// Idempotent: a queue that already ended (or never started) is not ended again, so the event is published
|
||||
/// once per queue however many paths reach the end.
|
||||
/// </summary>
|
||||
public void End()
|
||||
{
|
||||
if (dialogQueue == null)
|
||||
return;
|
||||
|
||||
generation++;
|
||||
GameLogger.Log("DIALOG", $"End: {dialogQueue?.Count ?? 0} actions in queue, {(endDialogQueue?.Count ?? 0)} end actions");
|
||||
|
||||
if (Lists.IsNotEmpty(dialogQueue))
|
||||
@@ -301,6 +375,31 @@ namespace Cthangover.Mods.Dialog
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drops the running queue without finishing it: destructs constructed
|
||||
/// actions and forgets the queue, but — unlike <see cref="End"/> — runs no
|
||||
/// end actions, does not mark a one-run scenario completed and publishes
|
||||
/// no <see cref="DialogEndedEvent"/>. Used to restart a scenario that is
|
||||
/// being edited; the caller hides the box (<see cref="DialogBox.Abort"/>).
|
||||
/// </summary>
|
||||
public void Abort()
|
||||
{
|
||||
if (Lists.IsNotEmpty(dialogQueue))
|
||||
{
|
||||
foreach (var action in dialogQueue)
|
||||
if (action != null && action.IsConstructed)
|
||||
action.Destruct();
|
||||
}
|
||||
|
||||
generation++;
|
||||
dialogQueue = null;
|
||||
endDialogQueue = null;
|
||||
index = 0;
|
||||
isLastGoTo = false;
|
||||
IsHeld = false;
|
||||
GameLogger.Log("DIALOG", "Abort: queue dropped without ending");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records a finished one-run scenario in the per-game completion
|
||||
/// history (<see cref="RuntimeData.CompletedScenarioIds"/>) so the
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
using Cthangover.Mods.Dialog.Action;
|
||||
|
||||
namespace Cthangover.Mods.Dialog
|
||||
{
|
||||
/// <summary>
|
||||
/// Hook a debugging tool installs in <see cref="DialogRuntime.Debugger"/> to
|
||||
/// stop a dialog before an action runs (pause, step, breakpoints). The
|
||||
/// runtime asks before every action of every dialog — including standalone
|
||||
/// runtimes without a <see cref="DialogBox"/> (hover commands) — so the
|
||||
/// implementation must answer quickly and hold only dialogs it can resume
|
||||
/// (<see cref="DialogBox.Resume"/>).
|
||||
/// </summary>
|
||||
public interface IDialogDebugger
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns true to hold <paramref name="runtime"/> before
|
||||
/// <paramref name="action"/>: the runtime marks itself
|
||||
/// <see cref="DialogRuntime.IsHeld"/> and returns without running it;
|
||||
/// clicks are ignored until <see cref="DialogBox.Resume"/>.
|
||||
/// </summary>
|
||||
bool ShouldHold(DialogRuntime runtime, IActionCommand action);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using Cthangover.Core.Scenes;
|
||||
using Cthangover.Mods.Dialog;
|
||||
using Cthangover.Core.UI.Event;
|
||||
using Cthangover.Core.Events;
|
||||
using Cthangover.Core.Utils;
|
||||
using Godot;
|
||||
using Cthangover.Core.UI;
|
||||
@@ -13,21 +13,23 @@ using Cthangover.Core.Interactive;
|
||||
namespace Cthangover.Mods.Dialog.Executable
|
||||
{
|
||||
/// <summary>
|
||||
/// Base for auto-triggering dialog events. A standalone event (not inside an
|
||||
/// IExecutableEventChain) only re-fires when the condition state changes
|
||||
/// (bumped <see cref="ConditionStateMonitor.Version"/>), after its own running
|
||||
/// dialog ends, or on the first run — with a 0.5s debounce. Checks that the
|
||||
/// DialogBox is free (IsRunning == false) before building and executing a
|
||||
/// dialog queue. IsOneRun prevents re-triggering after first execution;
|
||||
/// CanRepeat allows the event to fire again on subsequent scenes/visits.
|
||||
/// CheckConditions is virtual — ScenarioEvent overrides it to evaluate script
|
||||
/// conditions.
|
||||
/// Base for auto-triggering dialog events. Inside an IExecutableEventChain the
|
||||
/// chain decides when the event runs. A standalone event (not inside a chain)
|
||||
/// drives itself, event-driven: it asks for a deferred check when it becomes
|
||||
/// ready, when the condition state changes (<see cref="ConditionStateChangedEvent"/>)
|
||||
/// and when a dialog ends (<see cref="DialogEndedEvent"/>), and runs when the
|
||||
/// state changed since its own last run (or on the first run) and the
|
||||
/// DialogBox is free. Checks that the DialogBox is free (IsRunning == false)
|
||||
/// before building and executing a dialog queue. IsOneRun prevents
|
||||
/// re-triggering after first execution; CanRepeat allows the event to fire
|
||||
/// again on subsequent scenes/visits. CheckConditions is virtual —
|
||||
/// ScenarioEvent overrides it to evaluate script conditions.
|
||||
/// </summary>
|
||||
public partial class ExecutableEvent : Node, IOnUpdateEvent, IExecutableEvent
|
||||
public partial class ExecutableEvent : Node, IExecutableEvent
|
||||
{
|
||||
protected DialogBox dialogBox;
|
||||
private SceneEventController eventController;
|
||||
private float timestamp;
|
||||
private bool isStandalone;
|
||||
private bool checkQueued;
|
||||
|
||||
// Version at which the event last ran (MinValue forces the first run).
|
||||
private long _lastRunVersion = long.MinValue;
|
||||
@@ -35,7 +37,7 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
private bool _awaitingOwnEnd;
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> until <see cref="RunDialog"/> is called for the first time.
|
||||
/// <c>true</c> until <see cref="RunDialog"/> starts the event's dialog for the first time.
|
||||
/// Used by chains to determine whether a one-shot event has already fired.
|
||||
/// </summary>
|
||||
public bool IsFirstRun { get; private set; } = true;
|
||||
@@ -66,13 +68,7 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
/// </summary>
|
||||
public virtual string ID => GetType().FullName;
|
||||
|
||||
/// <summary>
|
||||
/// Priority within the event chain — lower values execute first. Default
|
||||
/// is <c>1</c>, placing this after high-priority handlers.
|
||||
/// </summary>
|
||||
public int Priority => 1;
|
||||
|
||||
/// <summary>Finds the shared <see cref="DialogBox"/> and registers with the event controller for update polling unless a parent chain already drives this event.</summary>
|
||||
/// <summary>Finds the shared <see cref="DialogBox"/>; a standalone event (no parent chain) subscribes to its triggers and asks for the first check.</summary>
|
||||
public override void _Ready()
|
||||
{
|
||||
if (dialogBox == null)
|
||||
@@ -84,30 +80,56 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
}
|
||||
}
|
||||
|
||||
var isInChain = GetParent() is IExecutableEventChain;
|
||||
if (!isInChain)
|
||||
isStandalone = GetParent() is not IExecutableEventChain;
|
||||
if (isStandalone)
|
||||
{
|
||||
eventController = SceneContextNode.FindNode<SceneEventController>("EventController");
|
||||
eventController?.AddUpdateEventListener(this);
|
||||
ModEventBus.Subscribe<ConditionStateChangedEvent>(OnConditionStateChanged);
|
||||
ModEventBus.Subscribe<DialogEndedEvent>(OnDialogEnded);
|
||||
RequestCheck();
|
||||
}
|
||||
|
||||
GameLogger.Log("EVENT", $"{GetType().Name}._Ready: dialogBox={(dialogBox != null ? "found" : "null")}, chain={isInChain}, registered={!isInChain}", LogLevel.Debug);
|
||||
GameLogger.Log("EVENT", $"{GetType().Name}._Ready: dialogBox={(dialogBox != null ? "found" : "null")}, chain={!isStandalone}, standalone={isStandalone}", LogLevel.Debug);
|
||||
}
|
||||
|
||||
/// <summary>Detaches from the event controller's update polling when the event leaves the tree.</summary>
|
||||
/// <summary>Detaches a standalone event from its triggers when it leaves the tree.</summary>
|
||||
public override void _ExitTree()
|
||||
{
|
||||
if (eventController != null)
|
||||
eventController.RemoveUpdateEventListener(this);
|
||||
if (!isStandalone)
|
||||
return;
|
||||
ModEventBus.Unsubscribe<ConditionStateChangedEvent>(OnConditionStateChanged);
|
||||
ModEventBus.Unsubscribe<DialogEndedEvent>(OnDialogEnded);
|
||||
}
|
||||
|
||||
private void OnConditionStateChanged(ConditionStateChangedEvent evt)
|
||||
{
|
||||
RequestCheck();
|
||||
}
|
||||
|
||||
private void OnDialogEnded(DialogEndedEvent evt)
|
||||
{
|
||||
RequestCheck();
|
||||
}
|
||||
|
||||
// Coalesces triggers of one frame into one deferred check.
|
||||
private void RequestCheck()
|
||||
{
|
||||
if (checkQueued)
|
||||
return;
|
||||
checkQueued = true;
|
||||
Callable.From(Check).CallDeferred();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Debounced poll (twice per second) that re-checks the repeat guards and
|
||||
/// the <c>ConditionStateMonitor</c> version, then triggers the dialog when
|
||||
/// the scene state changed since the last run.
|
||||
/// Deferred check of a standalone event: re-checks the repeat guards and the
|
||||
/// <c>ConditionStateMonitor</c> version, then triggers the dialog when the
|
||||
/// scene state changed since the last run.
|
||||
/// </summary>
|
||||
public void OnUpdate()
|
||||
private void Check()
|
||||
{
|
||||
checkQueued = false;
|
||||
if (!IsInstanceValid(this) || !IsInsideTree())
|
||||
return;
|
||||
|
||||
if (!IsFirstRun && !CanRepeat)
|
||||
return;
|
||||
|
||||
@@ -125,11 +147,6 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
if (ConditionStateMonitor.Version == _lastRunVersion)
|
||||
return;
|
||||
|
||||
var time = Godot.Time.GetTicksUsec() / 1_000_000.0;
|
||||
if (time - timestamp < 0.5f)
|
||||
return;
|
||||
timestamp = (float)time;
|
||||
|
||||
if (dialogBox.IsRunning)
|
||||
return;
|
||||
|
||||
@@ -140,8 +157,10 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
/// <summary>
|
||||
/// Builds a <see cref="DialogQueue"/> via <see cref="CreateDialog"/> and queues
|
||||
/// it on the <see cref="DialogBox"/>, passing <c>this</c> as the locker to
|
||||
/// block other dialog attempts. Returns <c>false</c> if the one-shot already
|
||||
/// ran, the dialog box is unavailable, or another locker is active.
|
||||
/// block other dialog attempts. Returns <c>false</c> — and leaves
|
||||
/// <see cref="IsFirstRun"/> untouched — if the one-shot already ran, the dialog
|
||||
/// box is unavailable or busy, or the box rejected the queue (e.g. inactive
|
||||
/// during a scene switch): a run that never happened is not counted.
|
||||
/// </summary>
|
||||
public bool RunDialog()
|
||||
{
|
||||
@@ -151,7 +170,7 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
if (dialogBox == null)
|
||||
return false;
|
||||
|
||||
if (dialogBox.Locker != null)
|
||||
if (dialogBox.IsRunning)
|
||||
return false;
|
||||
|
||||
GameLogger.Log("EVENT", $"{GetType().Name}.RunDialog: starting dialog...");
|
||||
@@ -159,7 +178,8 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
var dlg = new DialogQueue();
|
||||
CreateDialog(dlg);
|
||||
|
||||
dialogBox.SetDialogQueueAndRun(dlg, null, 0, this);
|
||||
if (!dialogBox.SetDialogQueueAndRun(dlg, null, StartIndex(dlg), this))
|
||||
return false;
|
||||
IsFirstRun = false;
|
||||
return true;
|
||||
}
|
||||
@@ -167,6 +187,9 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
protected virtual void CreateDialog(DialogQueue dlg)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Queue index the dialog starts at; 0 unless a subclass starts mid-script.</summary>
|
||||
protected virtual int StartIndex(DialogQueue dlg) => 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
using Cthangover.Mods.Dialog;
|
||||
using Godot;
|
||||
using Cthangover.Core.UI;
|
||||
using Cthangover.Mods.Interface.Base.Lists;
|
||||
using Cthangover.Core.UI.Dialog;
|
||||
using Cthangover.Core.UI.Event;
|
||||
using Cthangover.Core.UI.Executable;
|
||||
using Cthangover.Core.Scenarios;
|
||||
using Cthangover.Core.Scenes;
|
||||
using Cthangover.Core.Interactive;
|
||||
|
||||
namespace Cthangover.Mods.Dialog.Executable
|
||||
{
|
||||
/// <summary>
|
||||
/// Abstract chain base: manages a list of ExecutableEvents and exposes
|
||||
/// Play()/Stop()/IsActive for external control. GetNext() is abstract so
|
||||
/// subclasses define their own selection strategy (sequential, conditional,
|
||||
/// random). Play() calls RunDialog() on the next event, which internally
|
||||
/// calls SetDialogQueueAndRun with `this` as the locker — the chain is
|
||||
/// blocked until the dialog finishes.
|
||||
/// </summary>
|
||||
public abstract partial class ExecutableEventChainBase : Godot.Node, IExecutableEventChain
|
||||
{
|
||||
|
||||
protected bool isActive = true;
|
||||
protected System.Collections.Generic.List<ExecutableEvent> chain;
|
||||
|
||||
protected DialogBox dialogBox;
|
||||
|
||||
/// <summary>
|
||||
/// Controls whether the chain is actively polling. Setting to <c>false</c>
|
||||
/// pauses event dispatch; setting to <c>true</c> resumes.
|
||||
/// </summary>
|
||||
public bool IsActive
|
||||
{
|
||||
get => isActive;
|
||||
set { isActive = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pauses the chain. No further events will be dispatched until
|
||||
/// <see cref="Play"/> is called.
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
{
|
||||
IsActive = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Activates the chain and immediately attempts to run the next event
|
||||
/// returned by <see cref="GetNext"/>. If no event is available, the
|
||||
/// chain deactivates itself.
|
||||
/// </summary>
|
||||
public void Play()
|
||||
{
|
||||
IsActive = true;
|
||||
var next = GetNext();
|
||||
if (next == null)
|
||||
{
|
||||
IsActive = false;
|
||||
return;
|
||||
}
|
||||
next.RunDialog();
|
||||
}
|
||||
|
||||
protected abstract ExecutableEvent GetNext();
|
||||
|
||||
/// <summary>Interface implementation: casts to <see cref="ExecutableEvent"/> and registers it with the chain node.</summary>
|
||||
public virtual void AddEvent(IExecutableEvent evt)
|
||||
{
|
||||
var typed = (ExecutableEvent)evt;
|
||||
AddChild(typed);
|
||||
chain ??= new System.Collections.Generic.List<ExecutableEvent>();
|
||||
chain.Add(typed);
|
||||
}
|
||||
|
||||
/// <summary>Interface implementation: frees every registered event and empties the chain list.</summary>
|
||||
public virtual void ClearEvents()
|
||||
{
|
||||
if (chain == null)
|
||||
return;
|
||||
foreach (var evt in chain)
|
||||
evt.QueueFree();
|
||||
chain.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
using Cthangover.Core.Scenes;
|
||||
using Cthangover.Mods.Dialog;
|
||||
using Cthangover.Core.Utils;
|
||||
using Godot;
|
||||
using Cthangover.Core.UI;
|
||||
using Cthangover.Mods.Interface.Base.Lists;
|
||||
using Cthangover.Core.UI.Dialog;
|
||||
using Cthangover.Core.UI.Event;
|
||||
using Cthangover.Core.UI.Executable;
|
||||
using Cthangover.Core.Scenarios;
|
||||
using Cthangover.Core.Interactive;
|
||||
|
||||
namespace Cthangover.Mods.Dialog.Executable
|
||||
{
|
||||
/// <summary>
|
||||
/// Sequential list-based chain: rescans GetNext() only when the condition
|
||||
/// state changes (bumped <see cref="ConditionStateMonitor.Version"/>), on the
|
||||
/// end of its own running dialog, or on the first scan — with a debounce.
|
||||
/// When an event runs, it's removed from the list first, so it's consumed and
|
||||
/// the chain shrinks until empty (no self-loop is possible, so no skip-guard
|
||||
/// is needed). Respects IsOneRun (skips already-run events) and
|
||||
/// CheckConditions (skips events whose conditions fail). Use for ordered
|
||||
/// event sequences where each event should play once in order.
|
||||
/// </summary>
|
||||
public partial class ExecutableEventListChain : ExecutableEventChainBase
|
||||
{
|
||||
|
||||
private float checkDelay = 1f;
|
||||
private float timestamp;
|
||||
|
||||
private long _lastScanVersion = long.MinValue;
|
||||
private bool _pendingDialog;
|
||||
private bool _wakeup;
|
||||
|
||||
/// <summary>Debounced chain driver: waits out the running dialog, rescans when the condition state changed and starts the next unconsumed event.</summary>
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (!isActive || chain.Count == 0)
|
||||
{
|
||||
IsActive = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (_pendingDialog)
|
||||
{
|
||||
if (dialogBox == null || dialogBox.Locker != null)
|
||||
return;
|
||||
_pendingDialog = false;
|
||||
_lastScanVersion = ConditionStateMonitor.Version;
|
||||
_wakeup = true;
|
||||
return;
|
||||
}
|
||||
|
||||
double time = Godot.Time.GetTicksUsec() / 1_000_000.0;
|
||||
if(time - timestamp < checkDelay)
|
||||
return;
|
||||
timestamp = (float)time;
|
||||
|
||||
var version = ConditionStateMonitor.Version;
|
||||
if (version == _lastScanVersion && !_wakeup)
|
||||
return;
|
||||
_wakeup = false;
|
||||
_lastScanVersion = version;
|
||||
|
||||
var next = GetNext();
|
||||
if(next == null)
|
||||
return;
|
||||
|
||||
chain.Remove(next);
|
||||
next.RunDialog();
|
||||
_pendingDialog = true;
|
||||
}
|
||||
|
||||
protected override ExecutableEvent GetNext()
|
||||
{
|
||||
if (Lists.IsEmpty(chain))
|
||||
return null;
|
||||
foreach (var additional in chain)
|
||||
{
|
||||
if(additional.IsOneRun && !additional.IsFirstRun)
|
||||
continue;
|
||||
if (additional.CheckConditions)
|
||||
return additional;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using Cthangover.Core.Events;
|
||||
using Cthangover.Mods.Dialog;
|
||||
using Cthangover.Core.UI.Event;
|
||||
using Cthangover.Core.Scenes;
|
||||
using Cthangover.Core.Utils;
|
||||
using Godot;
|
||||
@@ -15,35 +14,41 @@ using Cthangover.Core.Interactive;
|
||||
namespace Cthangover.Mods.Dialog.Executable
|
||||
{
|
||||
/// <summary>
|
||||
/// The primary event chain for a scene. Registers as IOnUpdateEvent and
|
||||
/// rescans registered ExecutableEvents only when the condition state changes
|
||||
/// (bumped <see cref="ConditionStateMonitor.Version"/>), on dialog end, or on
|
||||
/// the first scan — with a 0.5s debounce. On _Ready, auto-collects child
|
||||
/// ExecutableEvent nodes and handles deferred scene switches (pending scene
|
||||
/// name from SceneManager). Exposes LastBackgroundID so action commands can
|
||||
/// remember which background was active for scene restore on revisit.
|
||||
/// AddEvent/RemoveEvent/ClearEvents allow dynamic event management via code.
|
||||
/// Events are checked in insertion order; the first satisfying both IsOneRun
|
||||
/// and CheckConditions gets executed. A skip-guard prevents re-running the
|
||||
/// same event at the same state version, breaking self-trigger loops while
|
||||
/// preserving A→B chaining.
|
||||
/// The primary event chain for a scene: picks the next ExecutableEvent to run
|
||||
/// in the dialog box. Event-driven — there is no per-frame work. A scan is
|
||||
/// requested when the condition state changes (<see cref="ConditionStateChangedEvent"/>),
|
||||
/// when a dialog ends (<see cref="DialogEndedEvent"/>), when an event is added,
|
||||
/// when the chain becomes ready and when it is re-activated. Requests are
|
||||
/// coalesced into one deferred scan at the end of the frame: a burst of flag
|
||||
/// changes costs one pass, the state is read after the change completed (some
|
||||
/// publishers raise their event before storing the value), and a scan never
|
||||
/// runs inside the dialog runtime that ended a queue.
|
||||
/// <para/>
|
||||
/// On _Ready the chain collects child ExecutableEvent nodes and replays a
|
||||
/// pending scene switch (pending scene name from SceneManager). Exposes
|
||||
/// LastBackgroundID so action commands can remember which background was
|
||||
/// active for scene restore on revisit. AddEvent/RemoveEvent/ClearEvents allow
|
||||
/// dynamic event management via code. Events are checked in insertion order;
|
||||
/// the first satisfying both IsOneRun and CheckConditions gets executed.
|
||||
/// <para/>
|
||||
/// Self-loop guard: the chain remembers, per event, the condition version at
|
||||
/// the moment its dialog ended, and does not run that event again until the
|
||||
/// state changed after it. An event's own state changes (made during its
|
||||
/// dialog) therefore never re-trigger it, A→B chaining still works, and two
|
||||
/// repeatable events cannot ping-pong A→B→A while nothing changes.
|
||||
/// </summary>
|
||||
public partial class ExecutableMainEventChain : Control, IExecutableEventChain, IOnUpdateEvent
|
||||
public partial class ExecutableMainEventChain : Control, IExecutableEventChain
|
||||
{
|
||||
private bool isActive = true;
|
||||
private List<ExecutableEvent> allEvents = new();
|
||||
private DialogBox dialogBox;
|
||||
private SceneEventController eventController;
|
||||
private float timestamp;
|
||||
|
||||
// Version of the last event scan (MinValue forces the first scan).
|
||||
private long _lastScanVersion = long.MinValue;
|
||||
// Version at the moment the chain's own last-run event finished its dialog.
|
||||
private long _lastRunEndVersion = long.MinValue;
|
||||
// The last event the chain actually started.
|
||||
private ExecutableEvent _lastRunEvent;
|
||||
// "Wake up and rescan" flag, set on dialog end or new event added.
|
||||
private bool _wakeup;
|
||||
// Condition version at the end of each event's last dialog run by this chain.
|
||||
private readonly Dictionary<ExecutableEvent, long> endVersions = new();
|
||||
// The event whose dialog the chain started and is waiting to end.
|
||||
private ExecutableEvent running;
|
||||
// A deferred scan is already queued for this frame.
|
||||
private bool scanQueued;
|
||||
|
||||
/// <summary>
|
||||
/// Stores the last background ID set by action commands (e.g. "bg_home").
|
||||
@@ -52,20 +57,18 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
public string LastBackgroundID { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Event priority for <see cref="SceneEventController"/> sorting. Value
|
||||
/// <c>1</c> places this chain after high-priority handlers but before
|
||||
/// general subscribers.
|
||||
/// </summary>
|
||||
public int Priority => 1;
|
||||
|
||||
/// <summary>
|
||||
/// Enables or disables event polling. When <c>false</c>,
|
||||
/// <see cref="OnUpdate"/> returns immediately without dispatching events.
|
||||
/// Enables or disables event dispatch. While <c>false</c>, scans do nothing;
|
||||
/// switching back to <c>true</c> requests a scan.
|
||||
/// </summary>
|
||||
public bool IsActive
|
||||
{
|
||||
get => isActive;
|
||||
set { isActive = value; }
|
||||
set
|
||||
{
|
||||
isActive = value;
|
||||
if (value)
|
||||
RequestScan();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -83,11 +86,14 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
evt.QueueFree();
|
||||
}
|
||||
allEvents.Clear();
|
||||
endVersions.Clear();
|
||||
running = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds an <see cref="ExecutableEvent"/> to the chain and reparents it via
|
||||
/// <c>AddChild</c>. Events are dispatched in insertion order.
|
||||
/// <c>AddChild</c>. Events are dispatched in insertion order; adding one
|
||||
/// requests a scan.
|
||||
/// </summary>
|
||||
/// <param name="evt">The event to register and parent to this chain.</param>
|
||||
public void AddEvent(IExecutableEvent evt)
|
||||
@@ -97,7 +103,7 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
GameLogger.Log("CHAIN", $"AddEvent: {typed.GetType().Name} [condition={id}] — calling AddChild");
|
||||
AddChild(typed);
|
||||
allEvents.Add(typed);
|
||||
_wakeup = true;
|
||||
RequestScan();
|
||||
GameLogger.Log("CHAIN", $" AddEvent: done, allEvents.Count={allEvents.Count}");
|
||||
}
|
||||
|
||||
@@ -110,21 +116,23 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
{
|
||||
if (allEvents.Remove(evt))
|
||||
{
|
||||
endVersions.Remove(evt);
|
||||
if (running == evt)
|
||||
running = null;
|
||||
evt.QueueFree();
|
||||
GameLogger.Log("CHAIN", $"removed event '{evt.GetType().Name}'");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Finds the shared <see cref="DialogBox"/> and event controller, collects child events, publishes the shell-ready event and replays any pending scene switch.</summary>
|
||||
/// <summary>Finds the shared <see cref="DialogBox"/>, subscribes to the scan triggers, collects child events, publishes the shell-ready event, replays any pending scene switch and requests the first scan.</summary>
|
||||
public override void _Ready()
|
||||
{
|
||||
GameLogger.Log("CHAIN", $"_Ready: starting, tree scene='{GetTree()?.CurrentScene?.Name}'");
|
||||
|
||||
dialogBox = SceneContextNode.FindNode<DialogBox>("DialogBox");
|
||||
|
||||
eventController = SceneContextNode.FindNode<SceneEventController>("EventController");
|
||||
eventController?.AddUpdateEventListener(this);
|
||||
ModEventBus.Subscribe<DialogEndedEvent>(OnDialogEnded);
|
||||
ModEventBus.Subscribe<ConditionStateChangedEvent>(OnConditionStateChanged);
|
||||
|
||||
foreach (var child in GetChildren())
|
||||
{
|
||||
@@ -146,56 +154,66 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
Callable.From(() => sceneManager.SwitchScene(pending)).CallDeferred();
|
||||
}
|
||||
|
||||
RequestScan();
|
||||
GameLogger.Log("CHAIN", $"_Ready: done, allEvents={allEvents.Count}");
|
||||
}
|
||||
|
||||
/// <summary>Detaches the update and dialog-end listeners from the event controller when the chain leaves the tree.</summary>
|
||||
/// <summary>Detaches the scan triggers when the chain leaves the tree.</summary>
|
||||
public override void _ExitTree()
|
||||
{
|
||||
eventController?.RemoveUpdateEventListener(this);
|
||||
ModEventBus.Unsubscribe<DialogEndedEvent>(OnDialogEnded);
|
||||
ModEventBus.Unsubscribe<ConditionStateChangedEvent>(OnConditionStateChanged);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when any dialog queue finishes. Wakes the chain so the next event
|
||||
/// can be picked up without waiting for a state change, and — for the chain's
|
||||
/// own last-run event — records the version at its dialog end so that the
|
||||
/// state bumps it produced are considered accounted for (breaks self-loops).
|
||||
/// Called when any dialog queue finishes. For the chain's own running event
|
||||
/// records the version at its dialog end, so the state changes it produced
|
||||
/// are accounted for (self-loop guard); then requests a scan so the next
|
||||
/// event starts right away.
|
||||
/// </summary>
|
||||
private void OnDialogEnded(DialogEndedEvent evt)
|
||||
{
|
||||
_wakeup = true;
|
||||
if (_lastRunEvent != null && evt.LockerId == _lastRunEvent.ID)
|
||||
_lastRunEndVersion = ConditionStateMonitor.Version;
|
||||
if (running != null && evt.LockerId == running.ID)
|
||||
{
|
||||
endVersions[running] = ConditionStateMonitor.Version;
|
||||
running = null;
|
||||
}
|
||||
RequestScan();
|
||||
}
|
||||
|
||||
/// <summary>Debounced scan that starts the next runnable event when the condition state changed since the last completed run.</summary>
|
||||
public void OnUpdate()
|
||||
private void OnConditionStateChanged(ConditionStateChangedEvent evt)
|
||||
{
|
||||
if (!isActive)
|
||||
RequestScan();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asks for a scan at the end of the frame. Any number of requests within
|
||||
/// one frame result in a single scan.
|
||||
/// </summary>
|
||||
public void RequestScan()
|
||||
{
|
||||
if (scanQueued)
|
||||
return;
|
||||
scanQueued = true;
|
||||
Callable.From(Scan).CallDeferred();
|
||||
}
|
||||
|
||||
/// <summary>Starts the first runnable event, unless the chain is inactive or the dialog box is busy or frozen (a dialog end or a state change asks again).</summary>
|
||||
private void Scan()
|
||||
{
|
||||
scanQueued = false;
|
||||
if (!IsInstanceValid(this) || !IsInsideTree() || !isActive)
|
||||
return;
|
||||
|
||||
var time = Godot.Time.GetTicksUsec() / 1_000_000.0;
|
||||
if (time - timestamp < 0.5f)
|
||||
return;
|
||||
timestamp = (float)time;
|
||||
|
||||
if (dialogBox == null || dialogBox.IsRunning)
|
||||
if (dialogBox == null || !IsInstanceValid(dialogBox) || !dialogBox.IsActive || dialogBox.IsRunning)
|
||||
return;
|
||||
|
||||
var version = ConditionStateMonitor.Version;
|
||||
if (version == _lastScanVersion && !_wakeup)
|
||||
return;
|
||||
|
||||
_wakeup = false;
|
||||
_lastScanVersion = version;
|
||||
|
||||
var dialog = FindEvent(allEvents, _lastRunEvent, _lastRunEndVersion);
|
||||
var dialog = FindEvent();
|
||||
if (dialog == null)
|
||||
return;
|
||||
|
||||
if (dialog.RunDialog())
|
||||
_lastRunEvent = dialog;
|
||||
running = dialog;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -213,13 +231,14 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
isActive = false;
|
||||
}
|
||||
|
||||
private ExecutableEvent FindEvent(List<ExecutableEvent> list, ExecutableEvent skipEvent, long skipEndVersion)
|
||||
private ExecutableEvent FindEvent()
|
||||
{
|
||||
if (Lists.IsEmpty(list))
|
||||
if (Lists.IsEmpty(allEvents))
|
||||
return null;
|
||||
foreach (var nextEvent in list)
|
||||
var version = ConditionStateMonitor.Version;
|
||||
foreach (var nextEvent in allEvents)
|
||||
{
|
||||
if (nextEvent == skipEvent && ConditionStateMonitor.Version <= skipEndVersion)
|
||||
if (endVersions.TryGetValue(nextEvent, out var endVersion) && version <= endVersion)
|
||||
continue;
|
||||
if (nextEvent.IsOneRun && !nextEvent.IsFirstRun)
|
||||
continue;
|
||||
|
||||
@@ -22,7 +22,7 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
/// dialog queue. Resolves the scenario path via convention: if ScenarioPath
|
||||
/// is set, uses that; otherwise searches all mods for a matching file name
|
||||
/// derived from the class name (stripping "Event" suffix), with a fallback
|
||||
/// to res://mods/visual_novel_core/scenarios/. CustomMappings allows code to register
|
||||
/// to res://mods/cthangover_game/scenarios/. CustomMappings allows code to register
|
||||
/// arbitrary class-to-path bindings for mod-provided scenarios. Supports
|
||||
/// inline ScenarioText for embedded scenarios that don't need a separate
|
||||
/// file. Checks conditions through ScenarioCondition.Evaluate before triggering.
|
||||
@@ -81,6 +81,23 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
/// </summary>
|
||||
public override string ID => ScenarioId ?? base.ID;
|
||||
|
||||
/// <summary>
|
||||
/// Mod (or content overlay) the scenario text was read from; null for
|
||||
/// generated text (test play, inline scenarios). With <see cref="SourcePath"/>
|
||||
/// it lets debugging tools open and edit the file behind a running event.
|
||||
/// </summary>
|
||||
public string SourceModId { get; set; }
|
||||
|
||||
/// <summary>Mod-relative path of the scenario file; see <see cref="SourceModId"/>.</summary>
|
||||
public string SourcePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Label (<c>:name</c> in the script, without the colon) to start at
|
||||
/// instead of the first line. Used to restart a scenario from where an
|
||||
/// edited part begins; an unknown label falls back to the start.
|
||||
/// </summary>
|
||||
public string StartLabel { get; set; }
|
||||
|
||||
protected override void CreateDialog(DialogQueue dlg)
|
||||
{
|
||||
if (LightUseTime.HasValue)
|
||||
@@ -111,6 +128,22 @@ namespace Cthangover.Mods.Dialog.Executable
|
||||
dlg.RuntimeObjectList.Add(obj);
|
||||
}
|
||||
|
||||
/// <summary>Index of the <see cref="StartLabel"/> point in the built queue, or 0.</summary>
|
||||
protected override int StartIndex(DialogQueue dlg)
|
||||
{
|
||||
if (string.IsNullOrEmpty(StartLabel))
|
||||
return 0;
|
||||
|
||||
for (var i = 0; i < dlg.Queue.Count; i++)
|
||||
{
|
||||
if (dlg.Queue[i]?.ID == StartLabel)
|
||||
return i;
|
||||
}
|
||||
|
||||
GameLogger.Log("SCENE", $"ScenarioEvent '{ID}': start label '{StartLabel}' not found, starting from the top", LogLevel.Warning);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private long _cachedVersion = long.MinValue;
|
||||
private bool _cachedResult;
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"name": "Test Runner",
|
||||
"description": "Test harness mod: ports the integration DialogAutoDriver into an engine mod. Activated by --choices=/--timeout= user args; auto-plays the active dialog, prints [TEST_RESULT] and quits. Depends on visual_novel_core and dialog_base.",
|
||||
"description": "Test harness mod: ports the integration DialogAutoDriver into an engine mod. Activated by --choices=/--timeout= user args; auto-plays the active dialog, prints [TEST_RESULT] and quits. Depends on cthangover_game and dialog_base.",
|
||||
"sources": [
|
||||
"src/*.cs"
|
||||
],
|
||||
"depends": [
|
||||
"visual_novel_core>=1"
|
||||
"cthangover_game>=1"
|
||||
]
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using Cthangover.Core.Events;
|
||||
using Cthangover.Core.UI.Dialog;
|
||||
using Cthangover.Core.Utils;
|
||||
using Godot;
|
||||
@@ -23,6 +24,9 @@ namespace Mods.TestRunner
|
||||
/// <c>IsDialogEnded</c> истинно до загрузки первой очереди, поэтому
|
||||
/// end-обработка ждёт, пока диалог реально наблюдался запущенным, плюс
|
||||
/// стартовая пауза 0.5с на построение сцены.
|
||||
/// With <c>--dialogs=N</c> the run passes after N <see cref="DialogEndedEvent"/>s
|
||||
/// instead: hub games never go idle, because the next scene's dialog starts
|
||||
/// in the same frame the previous one ends.
|
||||
/// </summary>
|
||||
public partial class DialogAutoDriverNode : Node
|
||||
{
|
||||
@@ -40,6 +44,7 @@ namespace Mods.TestRunner
|
||||
|
||||
private readonly List<int> choices;
|
||||
private readonly float? timeoutSeconds;
|
||||
private readonly int? dialogsTarget;
|
||||
|
||||
private IDialogBox dialogBox;
|
||||
private int choiceIndex;
|
||||
@@ -47,6 +52,7 @@ namespace Mods.TestRunner
|
||||
private double dialogFoundAtSeconds;
|
||||
private bool hasSeenRunningDialog;
|
||||
private bool finished;
|
||||
private int endedDialogs;
|
||||
|
||||
/// <summary>
|
||||
/// Создаёт драйвер; <paramref name="choices"/> — индексы вариантов по
|
||||
@@ -56,11 +62,16 @@ namespace Mods.TestRunner
|
||||
/// вне source-генератора Godot): WaitTime 0.1с с автостартом
|
||||
/// воспроизводит ритм оригинального драйвера, а сигнал
|
||||
/// <c>Timer.Timeout</c> — Godot-сигнал и работает из мод-сборок.
|
||||
/// <paramref name="dialogsTarget"/> — number of finished dialogs that passes
|
||||
/// the run (null — pass when the box goes idle).
|
||||
/// </summary>
|
||||
public DialogAutoDriverNode(List<int> choices, float? timeoutSeconds)
|
||||
public DialogAutoDriverNode(List<int> choices, float? timeoutSeconds, int? dialogsTarget)
|
||||
{
|
||||
this.choices = choices ?? new List<int>();
|
||||
this.timeoutSeconds = timeoutSeconds;
|
||||
this.dialogsTarget = dialogsTarget;
|
||||
if (dialogsTarget.HasValue)
|
||||
ModEventBus.Subscribe<DialogEndedEvent>(OnDialogEnded);
|
||||
|
||||
var timer = new Timer
|
||||
{
|
||||
@@ -112,7 +123,7 @@ namespace Mods.TestRunner
|
||||
var waitingForFirstDialog = !hasSeenRunningDialog
|
||||
&& elapsedSeconds - dialogFoundAtSeconds < FirstDialogGraceSeconds;
|
||||
|
||||
if (dialogBox.IsDialogEnded && !waitingForFirstDialog)
|
||||
if (!dialogsTarget.HasValue && dialogBox.IsDialogEnded && !waitingForFirstDialog)
|
||||
{
|
||||
GameLogger.Log("TEST", "DialogAutoDriverNode: dialog ended, quitting");
|
||||
Finish(1, 0, null);
|
||||
@@ -128,6 +139,15 @@ namespace Mods.TestRunner
|
||||
dialogBox.NextAction();
|
||||
}
|
||||
|
||||
/// <summary>Counts finished dialogs and passes the run once the --dialogs= target is reached.</summary>
|
||||
private void OnDialogEnded(DialogEndedEvent evt)
|
||||
{
|
||||
endedDialogs++;
|
||||
GameLogger.Log("TEST", $"DialogAutoDriverNode: dialog #{endedDialogs} ended");
|
||||
if (endedDialogs >= dialogsTarget.Value)
|
||||
Finish(1, 0, $"{endedDialogs} dialog(s) ended, quitting");
|
||||
}
|
||||
|
||||
/// <summary>Выбирает показанный вариант по индексу из --choices= (вне диапазона — первый).</summary>
|
||||
private void HandleSelection()
|
||||
{
|
||||
@@ -167,6 +187,8 @@ namespace Mods.TestRunner
|
||||
if (finished)
|
||||
return;
|
||||
finished = true;
|
||||
if (dialogsTarget.HasValue)
|
||||
ModEventBus.Unsubscribe<DialogEndedEvent>(OnDialogEnded);
|
||||
|
||||
if (reason != null)
|
||||
GameLogger.Log("TEST", $"DialogAutoDriverNode: {reason}");
|
||||
|
||||
@@ -44,6 +44,7 @@ namespace Mods.TestRunner
|
||||
|
||||
var choices = ParseChoices(args);
|
||||
var timeout = ParseTimeout(args);
|
||||
var dialogs = ParseDialogs(args);
|
||||
|
||||
// Godot. квалифицирован: в dev-компиляции модов (ToolsModCompileTests)
|
||||
// в глобальном пространстве имён существует namespace Engine из тестовой сборки,
|
||||
@@ -57,12 +58,12 @@ namespace Mods.TestRunner
|
||||
|
||||
driverQueued = true;
|
||||
GameLogger.Log("TEST",
|
||||
$"TestRunnerInitializer: activating dialog auto-driver, choices=[{string.Join(",", choices)}], timeout={timeout?.ToString() ?? "none"}s");
|
||||
$"TestRunnerInitializer: activating dialog auto-driver, choices=[{string.Join(",", choices)}], timeout={timeout?.ToString() ?? "none"}s, dialogs={dialogs?.ToString() ?? "idle"}");
|
||||
|
||||
// Deferred: сцена ещё строится; драйвер внутри сам выдерживает
|
||||
// стартовую паузу и лениво ищет DialogBox, поэтому порядок с
|
||||
// загрузкой сцены не важен.
|
||||
root.CallDeferred("add_child", new DialogAutoDriverNode(choices, timeout));
|
||||
root.CallDeferred("add_child", new DialogAutoDriverNode(choices, timeout, dialogs));
|
||||
}
|
||||
|
||||
private static List<int> ParseChoices(string[] args)
|
||||
@@ -80,6 +81,15 @@ namespace Mods.TestRunner
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static int? ParseDialogs(string[] args)
|
||||
{
|
||||
var raw = args
|
||||
.Where(a => a.StartsWith("--dialogs=", System.StringComparison.Ordinal))
|
||||
.Select(a => a.Substring("--dialogs=".Length))
|
||||
.FirstOrDefault();
|
||||
return int.TryParse(raw, out var n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
private static float? ParseTimeout(string[] args)
|
||||
{
|
||||
var raw = args
|
||||
|
||||
@@ -8,6 +8,6 @@
|
||||
"scripts/*.gd"
|
||||
],
|
||||
"depends": [
|
||||
"visual_novel_core>=1"
|
||||
"cthangover_game>=1"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Mods.Dialog.Action.Impls;
|
||||
using Godot;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ActionAnimatedForeground"/> really animates: frames are cut on the
|
||||
/// ViewBox foreground while the dialog goes on, a one-shot animation stops on its
|
||||
/// last frame, and a looping one stops when the dialog ends.
|
||||
/// </summary>
|
||||
public class ActionAnimatedForegroundTests
|
||||
{
|
||||
[ModTest("animation/one_shot_reaches_last_frame", TimeoutSeconds = 10)]
|
||||
static async Task OneShotReachesLastFrame(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
var view = stage.AddViewBox();
|
||||
await DialogStage.Frames(1);
|
||||
try
|
||||
{
|
||||
var frames = Frames(3);
|
||||
var anim = new ActionAnimatedForeground { Textures = frames, Speed = 20f, NextFrameSpeed = 20f, IsLoop = false };
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Queue.Add(anim);
|
||||
dlg.Queue.Add(new ProbeAction());
|
||||
|
||||
stage.Box.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
ModAssert.True(view.Foreground.Texture == frames[0], "first frame is shown at once");
|
||||
ModAssert.True(anim.IsAnimating, "animation outlives its NoWait action");
|
||||
await DialogStage.Seconds(0.6);
|
||||
|
||||
ModAssert.True(view.Foreground.Texture == frames[2], "animation reached the last frame");
|
||||
ModAssert.False(anim.IsAnimating, "one-shot animation stopped");
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
|
||||
[ModTest("animation/loop_stops_with_dialog_end", TimeoutSeconds = 10)]
|
||||
static async Task LoopStopsWithDialogEnd(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
var view = stage.AddViewBox();
|
||||
await DialogStage.Frames(1);
|
||||
try
|
||||
{
|
||||
var frames = Frames(2);
|
||||
var anim = new ActionAnimatedForeground { Textures = frames, Speed = 20f, NextFrameSpeed = 20f, IsLoop = true };
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Queue.Add(anim);
|
||||
dlg.Queue.Add(new ProbeAction());
|
||||
|
||||
stage.Box.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
await DialogStage.Seconds(0.3);
|
||||
ModAssert.True(anim.IsAnimating, "looping animation keeps playing while the dialog waits");
|
||||
|
||||
stage.Box.NextAction();
|
||||
ModAssert.False(anim.IsAnimating, "dialog end stops the animation");
|
||||
var shown = view.Foreground.Texture;
|
||||
await DialogStage.Seconds(0.3);
|
||||
ModAssert.True(view.Foreground.Texture == shown, "no frame is cut after the dialog ended");
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Texture2D> Frames(int count)
|
||||
{
|
||||
var list = new List<Texture2D>();
|
||||
for (var i = 0; i < count; i++)
|
||||
list.Add(ImageTexture.CreateFromImage(Image.CreateEmpty(2, 2, false, Image.Format.Rgba8)));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Mods.Dialog.Action.Impls;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ActionBackgroundShowHide"/> without <c>wait</c>: the dialog goes on at
|
||||
/// once and the fade still plays to the end.
|
||||
/// </summary>
|
||||
public class ActionBackgroundShowHideTests
|
||||
{
|
||||
[ModTest("background_fade/no_wait_fade_completes", TimeoutSeconds = 10)]
|
||||
static async Task NoWaitFadeCompletes(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
try
|
||||
{
|
||||
var after = new ProbeAction();
|
||||
var dlg = new DialogQueue();
|
||||
dlg.BackgroundShowHide(BackgroundActionType.Hide, 0.1f);
|
||||
dlg.Queue.Add(after);
|
||||
|
||||
stage.Box.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
ModAssert.Equal(1, after.Runs, "dialog does not wait for the fade");
|
||||
await DialogStage.Seconds(0.4);
|
||||
|
||||
ModAssert.True(stage.Host.Modulate.A < 0.01f, $"background faded out (alpha {stage.Host.Modulate.A})");
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Mods.Dialog.Action.Impls;
|
||||
using Godot;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ActionEffect"/> shows its effect: the instance lands in the ViewBox UI
|
||||
/// layer when the action runs and is freed when the dialog ends.
|
||||
/// </summary>
|
||||
public class ActionEffectTests
|
||||
{
|
||||
[ModTest("effect/spawned_into_view_until_dialog_end", TimeoutSeconds = 10)]
|
||||
static async Task SpawnedIntoViewUntilDialogEnd(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
var view = stage.AddViewBox();
|
||||
var template = new Node2D { Name = "TestEffect" };
|
||||
var prefab = new PackedScene();
|
||||
prefab.Pack(template);
|
||||
template.Free();
|
||||
try
|
||||
{
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Queue.Add(new ActionEffect { Prefab = prefab });
|
||||
dlg.Queue.Add(new ProbeAction());
|
||||
|
||||
stage.Box.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
var layer = view.GetInteractiveLayer("ui");
|
||||
ModAssert.Equal(1, layer.GetChildCount(), "effect is shown in the UI layer");
|
||||
ModAssert.Equal("TestEffect", layer.GetChild(0).Name.ToString(), "the shown node is the effect");
|
||||
|
||||
stage.Box.NextAction();
|
||||
await DialogStage.Frames(2);
|
||||
ModAssert.Equal(0, layer.GetChildCount(), "effect is freed when the dialog ends");
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Mods.Dialog.Action.Impls;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ActionTimedUpdate"/> completes itself: when its timeline elapses the
|
||||
/// dialog goes on, including the timer of a <c>delay</c> right after it.
|
||||
/// </summary>
|
||||
public class ActionTimedUpdateTests
|
||||
{
|
||||
[ModTest("timed_update/completion_continues_dialog", TimeoutSeconds = 10)]
|
||||
static async Task CompletionContinuesDialog(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
try
|
||||
{
|
||||
var timed = new ActionTimedUpdate { WaitTime = 0.1f };
|
||||
var after = new ProbeAction();
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Queue.Add(timed);
|
||||
dlg.Delay(0.1f);
|
||||
dlg.Queue.Add(after);
|
||||
|
||||
stage.Box.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
ModAssert.True(stage.Box.Runtime.CurrentAction == timed, "dialog waits on the timeline");
|
||||
await DialogStage.Seconds(0.8);
|
||||
|
||||
ModAssert.True(timed.IsDestructed, "timeline is finished and detached");
|
||||
ModAssert.Equal(1, after.Runs, "timeline and the delay after it elapsed, the dialog went on");
|
||||
ModAssert.True(stage.Box.Runtime.CurrentAction == after, "runtime waits on the action after the delay");
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Core.Settings;
|
||||
using Cthangover.Mods.Dialog.Action.Impls;
|
||||
using Cthangover.Mods.Dialog.Executable;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="DialogBox"/> as the single owner of the dialog: a locker-less click
|
||||
/// dialog keeps the box busy, a debugger hold keeps a <c>delay</c> from being
|
||||
/// skipped by its timer, and choice answers advance correctly with and without a
|
||||
/// target.
|
||||
/// </summary>
|
||||
public class DialogBoxTests
|
||||
{
|
||||
[ModTest("box/click_dialog_blocks_event_dialog", TimeoutSeconds = 10)]
|
||||
static async Task ClickDialogBlocksEventDialog(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
try
|
||||
{
|
||||
var click = new ProbeAction();
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Queue.Add(click);
|
||||
ModAssert.True(stage.Box.SetDialogQueueAndRun(dlg, null, 0, null), "click dialog starts");
|
||||
ModAssert.True(stage.Box.IsRunning, "a locker-less dialog occupies the box");
|
||||
|
||||
var evt = new ScenarioEvent { ScenarioText = "text \"event\"", ScenarioId = "dialog_base_test_one_run", IsOneRun = true };
|
||||
stage.Host.AddChild(evt);
|
||||
ModAssert.False(evt.RunDialog(), "event dialog is refused while the click dialog runs");
|
||||
await DialogStage.Frames(3);
|
||||
|
||||
ModAssert.Null(stage.Box.Locker, "the click dialog keeps no locker");
|
||||
ModAssert.True(stage.Box.Visible, "box stays visible");
|
||||
ModAssert.True(stage.Box.Runtime.CurrentAction == click, "click dialog still waits on its action");
|
||||
ModAssert.True(evt.IsFirstRun, "refused event is not counted as run");
|
||||
var completed = GameData.Instance?.Runtime?.CompletedScenarioIds;
|
||||
ModAssert.False(completed != null && completed.Contains("dialog_base_test_one_run"), "refused one-run scenario is not marked completed");
|
||||
|
||||
var other = new DialogQueue();
|
||||
other.Queue.Add(new ProbeAction());
|
||||
ModAssert.False(stage.Box.SetDialogQueueAndRun(other, null, 0, null), "a second click dialog is refused too");
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
|
||||
[ModTest("box/held_delay_is_not_skipped", TimeoutSeconds = 10)]
|
||||
static async Task HeldDelayIsNotSkipped(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
var previous = DialogRuntime.Debugger;
|
||||
try
|
||||
{
|
||||
var delay = new ActionDelay { WaitTime = 0.05f };
|
||||
var after = new ProbeAction();
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Queue.Add(delay);
|
||||
dlg.Queue.Add(after);
|
||||
DialogRuntime.Debugger = new HoldDebugger { Target = delay };
|
||||
|
||||
stage.Box.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
ModAssert.True(stage.Box.Runtime.IsHeld, "runtime is held before the delay");
|
||||
await DialogStage.Seconds(0.3);
|
||||
|
||||
ModAssert.True(stage.Box.Runtime.IsHeld, "hold survives the delay's duration");
|
||||
ModAssert.True(stage.Box.Runtime.CurrentAction == delay, "held delay stays current");
|
||||
ModAssert.Equal(0, after.Runs, "action after the held delay has not run");
|
||||
|
||||
DialogRuntime.Debugger = null;
|
||||
stage.Box.Resume();
|
||||
await DialogStage.Seconds(0.3);
|
||||
|
||||
ModAssert.Equal(1, after.Runs, "after resume the delay elapses and the dialog goes on");
|
||||
ModAssert.True(stage.Box.Runtime.CurrentAction == after, "runtime waits on the action after the delay");
|
||||
}
|
||||
finally
|
||||
{
|
||||
DialogRuntime.Debugger = previous;
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
|
||||
[ModTest("box/option_without_target_falls_through", TimeoutSeconds = 10)]
|
||||
static async Task OptionWithoutTargetFallsThrough(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
try
|
||||
{
|
||||
var after = new ProbeAction();
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Select(new List<SelectVariant> { SelectVariant.New("go on", null) }, "choose");
|
||||
dlg.Queue.Add(after);
|
||||
|
||||
stage.Box.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
ModAssert.True(stage.Box.IsWaitingAnswer, "choice is shown");
|
||||
ModAssert.True(stage.Box.TrySelectVariant(0), "variant is picked");
|
||||
|
||||
ModAssert.False(stage.Box.IsWaitingAnswer, "the same choice is not shown again");
|
||||
ModAssert.Equal(1, after.Runs, "action after the choice runs");
|
||||
ModAssert.True(stage.Box.Runtime.CurrentAction == after, "runtime waits on the action after the choice");
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
|
||||
[ModTest("box/option_to_missing_label_ends_once", TimeoutSeconds = 10)]
|
||||
static async Task OptionToMissingLabelEndsOnce(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
var recorder = new DialogEndRecorder();
|
||||
recorder.Start();
|
||||
try
|
||||
{
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Select(new List<SelectVariant> { SelectVariant.New("broken", "no_such_label") }, "choose");
|
||||
dlg.Queue.Add(new ProbeAction());
|
||||
|
||||
stage.Box.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
stage.Box.TrySelectVariant(0);
|
||||
|
||||
ModAssert.Equal(1, recorder.LockerIds.Count, "DialogEndedEvent count after an option to a missing label");
|
||||
ModAssert.False(stage.Box.IsRunning, "box is free");
|
||||
}
|
||||
finally
|
||||
{
|
||||
recorder.Stop();
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using Cthangover.Core.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Records every <see cref="DialogEndedEvent"/> published on the mod event bus
|
||||
/// between <see cref="Start"/> and <see cref="Stop"/> — the locker id of each, in
|
||||
/// publication order. Tests count how often a queue reported its end.
|
||||
/// </summary>
|
||||
public class DialogEndRecorder
|
||||
{
|
||||
/// <summary>Locker ids of the recorded events (null for a locker-less dialog).</summary>
|
||||
public List<string> LockerIds { get; } = new();
|
||||
|
||||
/// <summary>Subscribes to the event bus.</summary>
|
||||
public void Start()
|
||||
{
|
||||
ModEventBus.Subscribe<DialogEndedEvent>(OnDialogEnded);
|
||||
}
|
||||
|
||||
/// <summary>Unsubscribes; call it in <c>finally</c> so a failed test leaves no handler behind.</summary>
|
||||
public void Stop()
|
||||
{
|
||||
ModEventBus.Unsubscribe<DialogEndedEvent>(OnDialogEnded);
|
||||
}
|
||||
|
||||
private void OnDialogEnded(DialogEndedEvent evt)
|
||||
{
|
||||
LockerIds.Add(evt.LockerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Mods.Dialog.Action.Impls;
|
||||
|
||||
/// <summary>
|
||||
/// Queue mechanics of <see cref="DialogRuntime"/>: a queue ends exactly once however
|
||||
/// it reaches the end, actions reached again through a looping goto get a full
|
||||
/// construct/destruct life every pass, and a fall-through branch does not skip the
|
||||
/// action after it.
|
||||
/// </summary>
|
||||
public class DialogRuntimeTests
|
||||
{
|
||||
[ModTest("runtime/end_command_publishes_dialog_ended_once", TimeoutSeconds = 10)]
|
||||
static async Task EndCommandPublishesOnce(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
var recorder = new DialogEndRecorder();
|
||||
recorder.Start();
|
||||
try
|
||||
{
|
||||
var after = new ProbeAction();
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Set("x", "1");
|
||||
dlg.End();
|
||||
dlg.Queue.Add(after);
|
||||
|
||||
ModAssert.True(stage.Box.SetDialogQueueAndRun(dlg, null, 0, null), "dialog starts");
|
||||
|
||||
ModAssert.Equal(1, recorder.LockerIds.Count, "DialogEndedEvent count after 'end'");
|
||||
ModAssert.Equal(0, after.Runs, "action after 'end' never runs");
|
||||
ModAssert.False(stage.Box.IsRunning, "box is free after 'end'");
|
||||
}
|
||||
finally
|
||||
{
|
||||
recorder.Stop();
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
|
||||
[ModTest("runtime/goto_missing_label_publishes_dialog_ended_once", TimeoutSeconds = 10)]
|
||||
static async Task GotoMissingLabelPublishesOnce(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
var recorder = new DialogEndRecorder();
|
||||
recorder.Start();
|
||||
try
|
||||
{
|
||||
var after = new ProbeAction();
|
||||
var dlg = new DialogQueue();
|
||||
dlg.GoTo("no_such_label");
|
||||
dlg.Queue.Add(after);
|
||||
|
||||
stage.Box.SetDialogQueueAndRun(dlg, null, 0, null);
|
||||
|
||||
ModAssert.Equal(1, recorder.LockerIds.Count, "DialogEndedEvent count after a goto to a missing label");
|
||||
ModAssert.Equal(0, after.Runs, "action after the broken goto never runs");
|
||||
ModAssert.False(stage.Box.IsRunning, "box is free after the broken goto");
|
||||
}
|
||||
finally
|
||||
{
|
||||
recorder.Stop();
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
|
||||
[ModTest("runtime/goto_loop_destructs_every_pass")]
|
||||
static void GotoLoopDestructsEveryPass(ModTestContext ctx)
|
||||
{
|
||||
var probe = new ProbeAction();
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Point("loop");
|
||||
dlg.Queue.Add(probe);
|
||||
dlg.GoTo("loop");
|
||||
|
||||
var runtime = new DialogRuntime();
|
||||
runtime.SetDialogQueueAndRun(null, dlg.Queue, null);
|
||||
runtime.Run();
|
||||
for (var pass = 0; pass < 2; pass++)
|
||||
{
|
||||
runtime.Next();
|
||||
runtime.Run();
|
||||
}
|
||||
|
||||
ModAssert.Equal(3, probe.Runs, "probe ran on every pass");
|
||||
ModAssert.Equal(3, probe.Constructs, "probe constructed on every pass");
|
||||
ModAssert.Equal(2, probe.Destructs, "probe destructed after every finished pass");
|
||||
ModAssert.True(runtime.CurrentAction == probe, "runtime waits on the probe again");
|
||||
runtime.Abort();
|
||||
ModAssert.Equal(3, probe.Destructs, "abort destructs the live pass");
|
||||
}
|
||||
|
||||
[ModTest("runtime/if_fall_through_runs_next_action")]
|
||||
static void IfFallThroughRunsNextAction(ModTestContext ctx)
|
||||
{
|
||||
var probe = new ProbeAction();
|
||||
var dlg = new DialogQueue();
|
||||
dlg.IfGoTo(AlwaysTrue, null, null);
|
||||
dlg.Queue.Add(probe);
|
||||
|
||||
var runtime = new DialogRuntime();
|
||||
runtime.SetDialogQueueAndRun(null, dlg.Queue, null);
|
||||
runtime.Run();
|
||||
|
||||
ModAssert.Equal(1, probe.Runs, "action after a fall-through if runs");
|
||||
ModAssert.True(runtime.CurrentAction == probe, "runtime waits on the action after the if");
|
||||
}
|
||||
|
||||
[ModTest("runtime/if_without_condition_runs_next_action")]
|
||||
static void IfWithoutConditionRunsNextAction(ModTestContext ctx)
|
||||
{
|
||||
var probe = new ProbeAction();
|
||||
var dlg = new DialogQueue();
|
||||
dlg.Queue.Add(new ActionIf { TrueGoTo = "nowhere" });
|
||||
dlg.Queue.Add(probe);
|
||||
|
||||
var runtime = new DialogRuntime();
|
||||
runtime.SetDialogQueueAndRun(null, dlg.Queue, null);
|
||||
runtime.Run();
|
||||
|
||||
ModAssert.Equal(1, probe.Runs, "action after an if without condition runs");
|
||||
ModAssert.True(runtime.CurrentAction == probe, "runtime waits on the action after the if");
|
||||
}
|
||||
|
||||
private static bool AlwaysTrue() => true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Core.Scenes;
|
||||
using Cthangover.Mods.Interface.View;
|
||||
using Godot;
|
||||
|
||||
/// <summary>
|
||||
/// A minimal live dialog stage for mod tests: a host Control under <c>/root</c>
|
||||
/// with the real <c>dialog_box.tscn</c> prefab (named <c>DialogBox</c>, so
|
||||
/// <see cref="SceneContextNode.FindNode{T}"/> and the event classes find it like in
|
||||
/// a scene) and, on request, a bare <see cref="ViewBox"/> with a foreground slot.
|
||||
/// The scene-context lookup cache is cleared on build and on <see cref="Free"/>:
|
||||
/// it remembers misses, and a test box must be found even if an earlier lookup
|
||||
/// failed. The host is the box's parent Control — background fades animate it.
|
||||
/// </summary>
|
||||
public class DialogStage
|
||||
{
|
||||
/// <summary>Parent of every stage node; freed by <see cref="Free"/>.</summary>
|
||||
public Control Host { get; private set; }
|
||||
|
||||
/// <summary>The dialog box built from its prefab.</summary>
|
||||
public DialogBox Box { get; private set; }
|
||||
|
||||
/// <summary>The view box, after <see cref="AddViewBox"/>.</summary>
|
||||
public ViewBox View { get; private set; }
|
||||
|
||||
/// <summary>The running scene tree.</summary>
|
||||
public static SceneTree Tree => (SceneTree)Engine.GetMainLoop();
|
||||
|
||||
/// <summary>Builds the host and the dialog box and waits a frame for their <c>_Ready</c>.</summary>
|
||||
public static async Task<DialogStage> Create()
|
||||
{
|
||||
SceneContextNode.Instance?.ClearData();
|
||||
var stage = new DialogStage { Host = new Control { Name = "DialogTestHost" } };
|
||||
Tree.Root.AddChild(stage.Host);
|
||||
|
||||
stage.Box = new ModScenePrefab("scenes/ui/dialog_box.tscn").Instantiate<DialogBox>();
|
||||
ModAssert.NotNull(stage.Box, "dialog_box.tscn builds a DialogBox");
|
||||
stage.Box.Name = "DialogBox";
|
||||
stage.Host.AddChild(stage.Box);
|
||||
await Frames(1);
|
||||
return stage;
|
||||
}
|
||||
|
||||
/// <summary>Adds a <see cref="ViewBox"/> named <c>ViewBox</c> with a <c>Foreground</c> TextureRect.</summary>
|
||||
public ViewBox AddViewBox()
|
||||
{
|
||||
View = new ViewBox { Name = "ViewBox" };
|
||||
View.AddChild(new TextureRect { Name = "Foreground" });
|
||||
Host.AddChild(View);
|
||||
SceneContextNode.Instance?.ClearData();
|
||||
return View;
|
||||
}
|
||||
|
||||
/// <summary>Removes the stage from the tree and forgets cached lookups of its nodes.</summary>
|
||||
public void Free()
|
||||
{
|
||||
if (Box != null && Box.IsRunning)
|
||||
Box.Abort();
|
||||
if (GodotObject.IsInstanceValid(Host))
|
||||
{
|
||||
Tree.Root.RemoveChild(Host);
|
||||
Host.QueueFree();
|
||||
}
|
||||
SceneContextNode.Instance?.ClearData();
|
||||
}
|
||||
|
||||
/// <summary>Waits <paramref name="count"/> process frames (deferred calls run at the end of each).</summary>
|
||||
public static async Task Frames(int count)
|
||||
{
|
||||
for (var i = 0; i < count; i++)
|
||||
await Tree.ToSignal(Tree, SceneTree.SignalName.ProcessFrame);
|
||||
}
|
||||
|
||||
/// <summary>Waits <paramref name="seconds"/> of game time.</summary>
|
||||
public static async Task Seconds(double seconds)
|
||||
{
|
||||
await Tree.ToSignal(Tree.CreateTimer(seconds), SceneTreeTimer.SignalName.Timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Core.Scenes;
|
||||
using Cthangover.Mods.Dialog.Executable;
|
||||
|
||||
/// <summary>
|
||||
/// A standalone <see cref="ExecutableEvent"/> (not inside a chain): a run the dialog
|
||||
/// box refused is not counted, and the event starts by itself on the next state
|
||||
/// change, without polling.
|
||||
/// </summary>
|
||||
public class ExecutableEventTests
|
||||
{
|
||||
[ModTest("event/refused_run_is_not_counted", TimeoutSeconds = 10)]
|
||||
static async Task RefusedRunIsNotCounted(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
try
|
||||
{
|
||||
stage.Box.IsActive = false;
|
||||
var evt = new ScenarioEvent { ScenarioText = "text \"S\"", ScenarioId = "dialog_base_test_standalone", IsOneRun = true };
|
||||
stage.Host.AddChild(evt);
|
||||
await DialogStage.Frames(2);
|
||||
|
||||
ModAssert.False(stage.Box.IsRunning, "inactive box refused the event");
|
||||
ModAssert.True(evt.IsFirstRun, "refused automatic run is not counted");
|
||||
ModAssert.False(evt.RunDialog(), "direct run is refused too");
|
||||
ModAssert.True(evt.IsFirstRun, "refused direct run is not counted");
|
||||
|
||||
stage.Box.IsActive = true;
|
||||
ConditionStateMonitor.MarkStateChanged();
|
||||
await DialogStage.Frames(2);
|
||||
|
||||
ModAssert.True(stage.Box.Locker == evt, "one-run event starts on the next state change");
|
||||
ModAssert.False(evt.IsFirstRun, "the real run is counted");
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Core.Scenes;
|
||||
using Cthangover.Mods.Dialog.Executable;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ExecutableMainEventChain"/> is event-driven and loop-safe: the next
|
||||
/// event starts within a couple of frames after a dialog ends (no polling delay),
|
||||
/// two repeatable events do not ping-pong while the state stays the same, and a
|
||||
/// state change makes them eligible again.
|
||||
/// </summary>
|
||||
public class ExecutableMainEventChainTests
|
||||
{
|
||||
[ModTest("chain/push_start_and_no_ping_pong", TimeoutSeconds = 15)]
|
||||
static async Task PushStartAndNoPingPong(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
try
|
||||
{
|
||||
var chain = new ExecutableMainEventChain { Name = "TestChain" };
|
||||
stage.Host.AddChild(chain);
|
||||
var a = new ScenarioEvent { ScenarioText = "text \"A\"", ScenarioId = "dialog_base_test_chain_a" };
|
||||
var b = new ScenarioEvent { ScenarioText = "text \"B\"", ScenarioId = "dialog_base_test_chain_b" };
|
||||
chain.AddEvent(a);
|
||||
chain.AddEvent(b);
|
||||
|
||||
await DialogStage.Frames(2);
|
||||
ModAssert.True(stage.Box.Locker == a, "first event starts right after it was added");
|
||||
|
||||
stage.Box.NextAction();
|
||||
await DialogStage.Frames(2);
|
||||
ModAssert.True(stage.Box.Locker == b, "second event starts within two frames after the first ended");
|
||||
|
||||
stage.Box.NextAction();
|
||||
await DialogStage.Frames(4);
|
||||
ModAssert.False(stage.Box.IsRunning, "no event re-runs while the state did not change");
|
||||
|
||||
ConditionStateMonitor.MarkStateChanged();
|
||||
await DialogStage.Frames(2);
|
||||
ModAssert.True(stage.Box.Locker == a, "a state change makes the first event eligible again");
|
||||
}
|
||||
finally
|
||||
{
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using Cthangover.Mods.Dialog.Action;
|
||||
|
||||
/// <summary>
|
||||
/// Debugger stand-in that holds the runtime once, right before
|
||||
/// <see cref="Target"/> — what the scenario studio does on a breakpoint.
|
||||
/// </summary>
|
||||
public class HoldDebugger : IDialogDebugger
|
||||
{
|
||||
private bool held;
|
||||
|
||||
/// <summary>The action to hold before.</summary>
|
||||
public IActionCommand Target { get; set; }
|
||||
|
||||
/// <summary>Holds before <see cref="Target"/> the first time it is reached.</summary>
|
||||
public bool ShouldHold(DialogRuntime runtime, IActionCommand action)
|
||||
{
|
||||
if (held || action != Target)
|
||||
return false;
|
||||
held = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using Cthangover.Core.UI.Event;
|
||||
|
||||
/// <summary>
|
||||
/// Update listener for <see cref="SceneEventController"/> tests: appends its
|
||||
/// <see cref="Name"/> to a shared <see cref="Log"/> on every update and may change
|
||||
/// the controller's listener list from inside the callback — remove
|
||||
/// <see cref="RemoveOnUpdate"/>, add <see cref="AddOnUpdate"/> — to check how a
|
||||
/// dispatch copes with a list changed under it.
|
||||
/// </summary>
|
||||
public class OrderListener : IOnUpdateEvent
|
||||
{
|
||||
/// <summary>Name written to <see cref="Log"/>.</summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>Dispatch priority.</summary>
|
||||
public int Priority { get; set; }
|
||||
|
||||
/// <summary>Shared call log.</summary>
|
||||
public List<string> Log { get; set; }
|
||||
|
||||
/// <summary>Controller whose list the callback changes.</summary>
|
||||
public SceneEventController Controller { get; set; }
|
||||
|
||||
/// <summary>Listener to unregister during the update, if any.</summary>
|
||||
public IOnUpdateEvent RemoveOnUpdate { get; set; }
|
||||
|
||||
/// <summary>Listener to register during the update, if any.</summary>
|
||||
public IOnUpdateEvent AddOnUpdate { get; set; }
|
||||
|
||||
/// <summary>Logs the call and applies the requested list changes once.</summary>
|
||||
public void OnUpdate()
|
||||
{
|
||||
Log.Add(Name);
|
||||
if (RemoveOnUpdate != null)
|
||||
{
|
||||
Controller.RemoveUpdateEventListener(RemoveOnUpdate);
|
||||
RemoveOnUpdate = null;
|
||||
}
|
||||
if (AddOnUpdate != null)
|
||||
{
|
||||
Controller.AddUpdateEventListener(AddOnUpdate);
|
||||
AddOnUpdate = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using Cthangover.Mods.Dialog.Action;
|
||||
using Cthangover.Core.UI.Dialog;
|
||||
|
||||
/// <summary>
|
||||
/// Test action that only counts its lifecycle calls: how often the runtime ran,
|
||||
/// constructed and destructed it. Waits for a click by default, so a test can
|
||||
/// park the dialog on it and look at where the runtime stands.
|
||||
/// </summary>
|
||||
public class ProbeAction : ActionCommand
|
||||
{
|
||||
/// <summary>Number of <see cref="DoRun"/> calls.</summary>
|
||||
public int Runs { get; private set; }
|
||||
|
||||
/// <summary>Number of <see cref="DoConstruct"/> calls.</summary>
|
||||
public int Constructs { get; private set; }
|
||||
|
||||
/// <summary>Number of <see cref="DoDestruct"/> calls.</summary>
|
||||
public int Destructs { get; private set; }
|
||||
|
||||
/// <summary>Counts the run.</summary>
|
||||
public override void DoRun(DialogRuntime runtime)
|
||||
{
|
||||
Runs++;
|
||||
}
|
||||
|
||||
/// <summary>Counts the construction.</summary>
|
||||
public override void DoConstruct()
|
||||
{
|
||||
Constructs++;
|
||||
}
|
||||
|
||||
/// <summary>Counts the destruction.</summary>
|
||||
public override void DoDestruct()
|
||||
{
|
||||
Destructs++;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Core.UI.Event;
|
||||
|
||||
/// <summary>
|
||||
/// Dispatch contract of the core <see cref="SceneEventController"/> (tested here:
|
||||
/// it is a Godot node, xUnit cannot create it; the dialog actions are its main
|
||||
/// listeners): lower priority first, registration order within a priority, and a
|
||||
/// listener list changed during a dispatch neither skips nor double-calls anyone.
|
||||
/// </summary>
|
||||
public class SceneEventControllerTests
|
||||
{
|
||||
[ModTest("event_controller/lower_priority_first_then_registration_order")]
|
||||
static void LowerPriorityFirst(ModTestContext ctx)
|
||||
{
|
||||
var log = new List<string>();
|
||||
var controller = new SceneEventController();
|
||||
try
|
||||
{
|
||||
controller.AddUpdateEventListener(new OrderListener { Name = "b", Priority = 1, Log = log });
|
||||
controller.AddUpdateEventListener(new OrderListener { Name = "a", Priority = 0, Log = log });
|
||||
controller.AddUpdateEventListener(new OrderListener { Name = "c", Priority = 1, Log = log });
|
||||
|
||||
controller._Process(0.0);
|
||||
|
||||
ModAssert.Equal("a,b,c", string.Join(",", log), "dispatch order");
|
||||
}
|
||||
finally
|
||||
{
|
||||
controller.Free();
|
||||
}
|
||||
}
|
||||
|
||||
[ModTest("event_controller/list_changed_during_dispatch")]
|
||||
static void ListChangedDuringDispatch(ModTestContext ctx)
|
||||
{
|
||||
var log = new List<string>();
|
||||
var controller = new SceneEventController();
|
||||
try
|
||||
{
|
||||
var removed = new OrderListener { Name = "removed", Priority = 1, Log = log };
|
||||
var added = new OrderListener { Name = "added", Priority = 0, Log = log };
|
||||
var changer = new OrderListener
|
||||
{
|
||||
Name = "changer", Priority = 0, Log = log, Controller = controller,
|
||||
RemoveOnUpdate = removed, AddOnUpdate = added,
|
||||
};
|
||||
var last = new OrderListener { Name = "last", Priority = 2, Log = log };
|
||||
controller.AddUpdateEventListener(changer);
|
||||
controller.AddUpdateEventListener(removed);
|
||||
controller.AddUpdateEventListener(last);
|
||||
|
||||
controller._Process(0.0);
|
||||
ModAssert.Equal("changer,last", string.Join(",", log), "first dispatch: removed one skipped, added one waits");
|
||||
|
||||
log.Clear();
|
||||
controller._Process(0.0);
|
||||
ModAssert.Equal("changer,added,last", string.Join(",", log), "second dispatch includes the added listener");
|
||||
}
|
||||
finally
|
||||
{
|
||||
controller.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace Cthangover.Mods.Dialog.Tests
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
using Cthangover.Core.Mods.Testing;
|
||||
using Cthangover.Core.Scenes;
|
||||
using Cthangover.Core.Settings;
|
||||
using Cthangover.Mods.Dialog.Scenarios;
|
||||
|
||||
/// <summary>
|
||||
/// The scenario <c>flag</c> command sets a story flag of the game: once the
|
||||
/// dialog reaches it, scenario conditions see the value, the game state
|
||||
/// holds it (so saves carry it), and conditions are rescanned.
|
||||
/// </summary>
|
||||
public class StoryFlagTests
|
||||
{
|
||||
private const string Flag = "__test_story_flag";
|
||||
|
||||
[ModTest("flags/flag_command_sets_game_flag", TimeoutSeconds = 10)]
|
||||
static async Task FlagCommandSetsGameFlag(ModTestContext ctx)
|
||||
{
|
||||
var stage = await DialogStage.Create();
|
||||
var flags = GameData.Instance.Runtime.Flags;
|
||||
try
|
||||
{
|
||||
var dlg = new ScenarioConverter().Convert($"flag {Flag} open\nend\n");
|
||||
var versionBefore = ConditionStateMonitor.Version;
|
||||
|
||||
ModAssert.False(ScenarioCondition.Evaluate($"{Flag} == \"open\""), "condition false before the dialog");
|
||||
ModAssert.True(stage.Box.SetDialogQueueAndRun(dlg, null, 0, null), "dialog starts");
|
||||
|
||||
ModAssert.True(ScenarioCondition.Evaluate($"{Flag} == \"open\""), "condition sees the flag");
|
||||
ModAssert.Equal("open", flags.TryGetValue(Flag, out var value) ? value : null, "game state holds the flag");
|
||||
ModAssert.True(ConditionStateMonitor.Version > versionBefore, "conditions are rescanned");
|
||||
}
|
||||
finally
|
||||
{
|
||||
flags.Remove(Flag);
|
||||
stage.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user