Olympe Engine 2.0
2D Game Engine with ECS Architecture
Loading...
Searching...
No Matches
TaskGraphTemplate.h
Go to the documentation of this file.
1/**
2 * @file TaskGraphTemplate.h
3 * @brief Immutable asset structure shared by all task graph runners
4 * @author Olympe Engine
5 * @date 2026-02-20
6 *
7 * @details
8 * TaskGraphTemplate is a read-only description of a task graph loaded once and
9 * shared by every TaskRunner that executes that graph. It contains:
10 * - Variable definitions (schema for the LocalBlackboard)
11 * - Node definitions (structure and parameters of every graph node)
12 * - A lookup cache (fast O(1) access to nodes by ID)
13 *
14 * C++14 compliant - no std::variant, std::optional, or C++17/20 features.
15 */
16
17#pragma once
18
19#include <string>
20#include <vector>
21#include <unordered_map>
22#include <cstdint>
23
24#include "TaskGraphTypes.h"
25#include "../Editor/ConditionPreset/NodeConditionRef.h"
26#include "../Editor/ConditionPreset/DynamicDataPin.h"
27#include "../Editor/ConditionPreset/ConditionPreset.h" // Phase 24: embedded preset bank
28#include "../BlueprintEditor/ConditionRef.h" // Phase 24: inline operand->pin mapping
29#include "../BlueprintEditor/MathOpOperand.h" // Phase 24: MathOp operand system
30#include "../json_helper.h" // For json type in global variables storage
31
32namespace Olympe {
33
34// ============================================================================
35// Supporting data structures
36// ============================================================================
37
38/**
39 * @struct VariableDefinition
40 * @brief Declares a single variable in the task graph's blackboard schema.
41 */
43 std::string Name; ///< Variable name (must be unique within the template)
44 VariableType Type = VariableType::None; ///< Declared type
45 TaskValue DefaultValue; ///< Initial value (used by LocalBlackboard::Reset)
46 bool IsLocal = true; ///< true = local BB; false = global BB (future)
47};
48
49/**
50 * @struct ParameterBinding
51 * @brief Describes how a single parameter value is supplied to a task node.
52 */
55 TaskValue LiteralValue; ///< Used when Type == Literal
56 std::string VariableName; ///< Used when Type == LocalVariable
57};
58
59// ============================================================================
60// ATS Visual Scripting – Template data structures (Phase 1 - 2026-03-08)
61// ============================================================================
62
63/**
64 * @struct ExecPinConnection
65 * @brief Explicit connection between a named exec-out pin of a source node
66 * and the exec-in pin of a target node.
67 */
70 std::string SourcePinName; ///< e.g. "Then", "Else", "Loop", "Completed"
72 std::string TargetPinName; ///< e.g. "In"
73};
74
75/**
76 * @struct DataPinConnection
77 * @brief Explicit connection between an output data pin of a source node
78 * and an input data pin of a target node.
79 */
86
87/**
88 * @struct BlackboardEntry
89 * @brief Single entry in the graph's declared blackboard schema (local or global).
90 */
92 std::string Key;
95 bool IsGlobal = false; ///< false = local scope, true = global BB
96};
97
98/**
99 * @struct TaskNodeDefinition
100 * @brief Full description of a single node in the task graph.
101 */
103 int32_t NodeID = NODE_INDEX_NONE; ///< Unique ID within this template
104 std::string NodeName; ///< Human-readable name
106
107 /// Child node IDs (control-flow nodes only; empty for AtomicTask/Decorator leaf)
108 std::vector<int32_t> ChildrenIDs;
109
110 /// Atomic task type identifier (used when Type == AtomicTask)
111 std::string AtomicTaskID;
112
113 /// Named parameter bindings passed to the atomic task
114 std::unordered_map<std::string, ParameterBinding> Parameters;
115
116 int32_t NextOnSuccess = NODE_INDEX_NONE; ///< ID of next node on success (NODE_INDEX_NONE = none)
117 int32_t NextOnFailure = NODE_INDEX_NONE; ///< ID of next node on failure (NODE_INDEX_NONE = none)
118
119 // ATS VS extensions (Phase 1)
120 std::vector<DataPinDefinition> DataPins; ///< Data pins declared on this node
121 std::string ConditionID; ///< For Branch/While/Switch: ATS condition ID
122 std::string BBKey; ///< For GetBBValue/SetBBValue: BB key (scope:key)
123 std::string SubGraphPath; ///< For SubGraph: path to the sub-graph JSON
124 std::vector<std::string> SwitchCases; ///< For Switch: ordered case labels (legacy; prefer switchCases)
125 float DelaySeconds = 0.0f; ///< For Delay: duration in seconds
126 std::string MathOperator; ///< For MathOp: "+", "-", "*", "/"
127
128 // ATS VS Switch enhancements (Phase 22-A - 2026-03-14)
129 std::string switchVariable; ///< For Switch: BB key of the variable to switch on
130 std::vector<SwitchCaseDefinition> switchCases; ///< For Switch: structured case definitions
131
132 // ATS VS Unified Condition System (Phase 23-B.4 - 2026-03-15)
133 std::vector<Condition> conditions; ///< For Branch/While: structured condition list (implicit AND)
134
135 // Phase 24.0 — Condition Preset System
136 std::vector<NodeConditionRef> conditionRefs; ///< Multi-condition refs to global presets (Phase 24)
137 std::vector<DynamicDataPin> dynamicPins; ///< Dynamic data-input pins for Pin-mode operands (Phase 24)
138
139 // Phase 24 Milestone 1 — Condition references with operand->pin mapping
140 /// Parallel to conditions[]: each entry stores the OperandRef->DynamicDataPin
141 /// UUID mapping for the corresponding condition expression.
142 /// Populated by DynamicDataPinManager::RegeneratePinsFromConditions().
143 std::vector<ConditionRef> conditionOperandRefs;
144
145 // Phase 24 Milestone 2 — MathOp operand system
146 /// For MathOp: complete operand configuration (left operand, operator, right operand).
147 /// Parallel to MathOp nodes; empty for all other node types.
148 /// Operands in Pin mode automatically generate DynamicDataPin entries.
150
151 /// For VSSequence: dynamically-added exec-out pins beyond the default "Out".
152 /// Each entry is a pin name (e.g. "Out_1", "Out_2"...).
153 std::vector<std::string> DynamicExecOutputPins;
154
155 // SubGraph-specific (Phase 3)
156 std::unordered_map<std::string, ParameterBinding> InputParams; ///< Input parameter bindings
157 std::unordered_map<std::string, std::string> OutputParams; ///< Output param -> BB key mapping
158
159 // Editor-only metadata (not used by runtime AI execution)
160 float EditorPosX = 0.0f; ///< Canvas X position loaded from JSON
161 float EditorPosY = 0.0f; ///< Canvas Y position loaded from JSON
162 bool HasEditorPos = false; ///< True when EditorPosX/Y were loaded from JSON
163};
164
165// ============================================================================
166// TaskGraphTemplate
167// ============================================================================
168
169/**
170 * @class TaskGraphTemplate
171 * @brief Immutable, shareable task graph asset.
172 *
173 * @details
174 * Load once, share across many TaskRunner instances. Call BuildLookupCache()
175 * after populating Nodes so that GetNode() runs in O(1). Call Validate()
176 * before using the template to catch structural errors early.
177 */
179public:
180
181 // -----------------------------------------------------------------------
182 // Asset data (public for direct construction / serialization)
183 // -----------------------------------------------------------------------
184
185 std::string Name; ///< Friendly name of this template (e.g. "PatrolBehaviour")
186 std::string Description; ///< Optional human-readable description
187
188 std::vector<VariableDefinition> LocalVariables; ///< Blackboard schema
189 std::vector<TaskNodeDefinition> Nodes; ///< All graph nodes
190
191 int32_t RootNodeID = NODE_INDEX_NONE; ///< ID of the root node (must exist in Nodes)
192
193 // ATS VS extensions (Phase 1)
194 int32_t EntryPointID = NODE_INDEX_NONE; ///< ID of the EntryPoint node (for VS graphs)
195
196 /// Graph type: "BehaviorTree" (legacy) or "VisualScript" (ATS VS)
197 std::string GraphType = "BehaviorTree";
198
199 /// Local blackboard declared in this graph
200 std::vector<BlackboardEntry> Blackboard;
201
202 /// Explicit exec connections (ATS VS only)
203 std::vector<ExecPinConnection> ExecConnections;
204
205 /// Explicit data connections (ATS VS only)
206 std::vector<DataPinConnection> DataConnections;
207
208 // SubGraph metadata (Phase 3)
209 bool IsSubGraph = false; ///< True if this template is a SubGraph
210 std::vector<SubGraphParameterDef> InputParameters; ///< Declared inputs (for subgraphs)
211 std::vector<SubGraphParameterDef> OutputParameters; ///< Declared outputs (for subgraphs)
212
213 // Phase 24 — Condition Preset Bank (embedded in graph)
214 /// Presets are now stored in the graph JSON, not in external files.
215 /// This makes blueprints self-contained with no external file dependencies.
216 /// Populated during LoadTemplate() from "presets" array in graph JSON.
217 std::vector<ConditionPreset> Presets;
218
219 // Phase 24 Global Blackboard Integration — Global Variable Values (entity-specific overrides)
220 /// Stores JSON representation of global variable values for this specific graph instance.
221 /// These are entity-specific values (different from global registry defaults).
222 /// Loaded from "globalVariableValues" in graph JSON during deserialization.
223 /// Restored to EntityBlackboard after initialization.
224 json GlobalVariableValues = json::object();
225
226 // -----------------------------------------------------------------------
227 // Operations
228 // -----------------------------------------------------------------------
229
230 /**
231 * @brief Validates the structural integrity of the template.
232 *
233 * Rules checked:
234 * - Nodes vector must not be empty.
235 * - RootNodeID must reference an existing node.
236 * - Every ChildrenID referenced by any node must reference an existing node.
237 *
238 * @return true if all validation rules pass; false otherwise.
239 */
240 bool Validate() const;
241
242 /**
243 * @brief Returns a pointer to the node with the given ID, or nullptr.
244 *
245 * Requires BuildLookupCache() to have been called after the last
246 * modification to Nodes.
247 *
248 * @param nodeId Node identifier.
249 * @return Pointer to the node, or nullptr if not found.
250 */
251 const TaskNodeDefinition* GetNode(int32_t nodeId) const;
252
253 /**
254 * @brief Rebuilds the internal ID-to-node lookup map from the Nodes vector.
255 *
256 * Must be called after Nodes is populated or modified.
257 */
258 void BuildLookupCache();
259
260 /**
261 * @brief Phase 24.3 - Poka-Yoke: Sanitizes exec connections to remove invalid links.
262 *
263 * Detects and removes exec connections that violate the data-pure node constraints:
264 * - Removes any exec-in connections TO data-pure nodes (GetBBValue, MathOp)
265 * - Removes any exec-out connections FROM data-pure nodes
266 *
267 * Logs all removed connections to SYSTEM_LOG for debugging.
268 * Safe to call multiple times (idempotent).
269 *
270 * @return Number of invalid connections that were removed.
271 */
273
274private:
275
276 /// Fast lookup: node ID -> pointer into Nodes vector.
277 std::unordered_map<int32_t, const TaskNodeDefinition*> m_nodeLookup;
278};
279
280} // namespace Olympe
ComponentTypeID GetComponentTypeID_Static()
Definition ECS_Entity.h:56
Core enumerations and TaskValue type-safe variant for the Atomic Task System.
Immutable, shareable task graph asset.
std::vector< TaskNodeDefinition > Nodes
All graph nodes.
std::vector< ExecPinConnection > ExecConnections
Explicit exec connections (ATS VS only)
bool IsSubGraph
True if this template is a SubGraph.
std::string Name
Friendly name of this template (e.g. "PatrolBehaviour")
std::vector< BlackboardEntry > Blackboard
Local blackboard declared in this graph.
std::vector< SubGraphParameterDef > InputParameters
Declared inputs (for subgraphs)
int32_t RootNodeID
ID of the root node (must exist in Nodes)
int SanitizeExecConnections()
Phase 24.3 - Poka-Yoke: Sanitizes exec connections to remove invalid links.
void BuildLookupCache()
Rebuilds the internal ID-to-node lookup map from the Nodes vector.
const TaskNodeDefinition * GetNode(int32_t nodeId) const
Returns a pointer to the node with the given ID, or nullptr.
bool Validate() const
Validates the structural integrity of the template.
json GlobalVariableValues
Stores JSON representation of global variable values for this specific graph instance.
std::vector< SubGraphParameterDef > OutputParameters
Declared outputs (for subgraphs)
std::vector< VariableDefinition > LocalVariables
Blackboard schema.
int32_t EntryPointID
ID of the EntryPoint node (for VS graphs)
std::string GraphType
Graph type: "BehaviorTree" (legacy) or "VisualScript" (ATS VS)
std::vector< DataPinConnection > DataConnections
Explicit data connections (ATS VS only)
std::vector< ConditionPreset > Presets
Presets are now stored in the graph JSON, not in external files.
std::unordered_map< int32_t, const TaskNodeDefinition * > m_nodeLookup
Fast lookup: node ID -> pointer into Nodes vector.
std::string Description
Optional human-readable description.
C++14-compliant type-safe value container for task parameters.
< Provides AssetID and INVALID_ASSET_ID
nlohmann::json json
VariableType
Type tags used by TaskValue to identify stored data.
@ None
Uninitialized / empty value.
ParameterBindingType
Describes how a parameter value is provided to a task node.
@ Literal
Value is embedded directly in the template.
TaskNodeType
Identifies the role of a node in the task graph.
@ AtomicTask
Leaf node that executes a single atomic task.
constexpr int32_t NODE_INDEX_NONE
Sentinel value for "no node" in node index / ID fields.
Single entry in the graph's declared blackboard schema (local or global).
bool IsGlobal
false = local scope, true = global BB
Explicit connection between an output data pin of a source node and an input data pin of a target nod...
Explicit connection between a named exec-out pin of a source node and the exec-in pin of a target nod...
std::string SourcePinName
e.g. "Then", "Else", "Loop", "Completed"
std::string TargetPinName
e.g. "In"
Complete reference for a MathOp node: left operand, operator, right operand.
Describes how a single parameter value is supplied to a task node.
TaskValue LiteralValue
Used when Type == Literal.
std::string VariableName
Used when Type == LocalVariable.
ParameterBindingType Type
Binding mode.
Full description of a single node in the task graph.
MathOpRef mathOpRef
For MathOp: complete operand configuration (left operand, operator, right operand).
std::vector< NodeConditionRef > conditionRefs
Multi-condition refs to global presets (Phase 24)
int32_t NextOnSuccess
ID of next node on success (NODE_INDEX_NONE = none)
std::string SubGraphPath
For SubGraph: path to the sub-graph JSON.
std::vector< Condition > conditions
For Branch/While: structured condition list (implicit AND)
std::string BBKey
For GetBBValue/SetBBValue: BB key (scope:key)
std::vector< std::string > SwitchCases
For Switch: ordered case labels (legacy; prefer switchCases)
std::string ConditionID
For Branch/While/Switch: ATS condition ID.
std::vector< int32_t > ChildrenIDs
Child node IDs (control-flow nodes only; empty for AtomicTask/Decorator leaf)
std::string MathOperator
For MathOp: "+", "-", "*", "/".
float EditorPosY
Canvas Y position loaded from JSON.
std::string AtomicTaskID
Atomic task type identifier (used when Type == AtomicTask)
std::string switchVariable
For Switch: BB key of the variable to switch on.
float EditorPosX
Canvas X position loaded from JSON.
int32_t NextOnFailure
ID of next node on failure (NODE_INDEX_NONE = none)
TaskNodeType Type
Node role.
std::vector< DataPinDefinition > DataPins
Data pins declared on this node.
std::vector< ConditionRef > conditionOperandRefs
Parallel to conditions[]: each entry stores the OperandRef->DynamicDataPin UUID mapping for the corre...
std::unordered_map< std::string, ParameterBinding > InputParams
Input parameter bindings.
std::unordered_map< std::string, std::string > OutputParams
Output param -> BB key mapping.
std::vector< SwitchCaseDefinition > switchCases
For Switch: structured case definitions.
std::string NodeName
Human-readable name.
std::unordered_map< std::string, ParameterBinding > Parameters
Named parameter bindings passed to the atomic task.
std::vector< DynamicDataPin > dynamicPins
Dynamic data-input pins for Pin-mode operands (Phase 24)
std::vector< std::string > DynamicExecOutputPins
For VSSequence: dynamically-added exec-out pins beyond the default "Out".
float DelaySeconds
For Delay: duration in seconds.
bool HasEditorPos
True when EditorPosX/Y were loaded from JSON.
int32_t NodeID
Unique ID within this template.
Declares a single variable in the task graph's blackboard schema.
std::string Name
Variable name (must be unique within the template)
bool IsLocal
true = local BB; false = global BB (future)
VariableType Type
Declared type.
TaskValue DefaultValue
Initial value (used by LocalBlackboard::Reset)