1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
//! Behavior tree loader for creating trees from JSON configuration
//!
//! This module provides the `BehaviorLoader` for loading behavior trees from
//! `BehaviorConfig` definitions using a `NodeRegistry`.
use crate::composition::{
ForceFailureNode, ForceSuccessNode, InverterNode, ParallelNode, RepeatNode, RetryNode, SelectOrNode, SequenceNode,
SubsumptionNode, TimeoutNode, WatchNode,
};
use crate::config::{BehaviorConfig, CompositionConfig};
use crate::registry::NodeRegistry;
use crate::BoxedBehavior;
use anyhow::{anyhow, Context as AnyhowContext, Result};
use serde_json::Value;
use tracing::{debug, info};
#[derive(Clone)]
pub struct BehaviorLoader {
registry: NodeRegistry,
}
impl BehaviorLoader {
/// Create a new behavior loader with the given node registry.
///
/// # Arguments
///
/// * `registry` - The node registry containing registered node types
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::{NodeRegistry, BehaviorLoader};
///
/// let registry = NodeRegistry::new();
/// let loader = BehaviorLoader::new(registry);
/// ```
pub fn new(registry: NodeRegistry) -> Self {
Self { registry }
}
/// Load a behavior tree from a configuration.
///
/// This is the main entry point for loading behavior trees. It takes a
/// `BehaviorConfig` (typically loaded from JSON) and recursively instantiates
/// all nodes in the tree.
///
/// # Arguments
///
/// * `config` - The behavior configuration to load
///
/// # Returns
///
/// A boxed behavior node representing the root of the tree, or an error if:
/// - A referenced node type is not registered
/// - A config reference is invalid
/// - A factory function fails
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::{BehaviorConfig, NodeRegistry, BehaviorLoader};
///
/// # let mut registry = NodeRegistry::new();
/// # registry.register("test", |_| Ok(Box::new(mecha10_behavior_runtime::SequenceNode::new(vec![]))));
/// let loader = BehaviorLoader::new(registry);
///
/// let json = r#"{
/// "name": "test",
/// "root": {
/// "type": "node",
/// "node": "test"
/// }
/// }"#;
///
/// let config = BehaviorConfig::from_json(json).unwrap();
/// let behavior = loader.load(&config).unwrap();
/// ```
pub fn load(&self, config: &BehaviorConfig) -> Result<BoxedBehavior> {
info!("Loading behavior tree: {}", config.name);
if let Some(desc) = &config.description {
debug!("Description: {}", desc);
}
self.load_composition(&config.root, config)
.with_context(|| format!("Failed to load behavior tree '{}'", config.name))
}
/// Load a behavior tree from a JSON string.
///
/// This is a convenience method that combines parsing and loading.
///
/// # Arguments
///
/// * `json` - JSON string containing a BehaviorConfig
///
/// # Example
///
/// ```rust
/// use mecha10_behavior_runtime::{NodeRegistry, BehaviorLoader};
///
/// # let mut registry = NodeRegistry::new();
/// # registry.register("test", |_| Ok(Box::new(mecha10_behavior_runtime::SequenceNode::new(vec![]))));
/// let loader = BehaviorLoader::new(registry);
///
/// let json = r#"{
/// "name": "test",
/// "root": {
/// "type": "node",
/// "node": "test"
/// }
/// }"#;
///
/// let behavior = loader.load_from_json(json).unwrap();
/// ```
pub fn load_from_json(&self, json: &str) -> Result<BoxedBehavior> {
self.load(&BehaviorConfig::from_json(json)?)
}
/// Load a behavior tree from a JSON file.
///
/// This is a convenience method that reads a file and loads the behavior tree.
///
/// # Arguments
///
/// * `path` - Path to the JSON file
///
/// # Example
///
/// ```rust,no_run
/// use mecha10_behavior_runtime::{NodeRegistry, BehaviorLoader};
///
/// # let registry = NodeRegistry::new();
/// let loader = BehaviorLoader::new(registry);
/// let behavior = loader.load_from_file("configs/behaviors/@mecha10/patrol/config.json").unwrap();
/// ```
pub fn load_from_file(&self, path: impl AsRef<std::path::Path>) -> Result<BoxedBehavior> {
self.load(&BehaviorConfig::from_file(path)?)
}
/// Recursively load a composition node and its children.
fn load_composition(&self, composition: &CompositionConfig, config: &BehaviorConfig) -> Result<BoxedBehavior> {
match composition {
CompositionConfig::Sequence { children, name } => {
debug!(
"Loading sequence node{}",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default()
);
let child_nodes = children
.iter()
.enumerate()
.map(|(i, child)| {
self.load_composition(child, config)
.with_context(|| format!("Failed to load sequence child {}", i))
})
.collect::<Result<Vec<_>>>()?;
debug!("Sequence node loaded with {} children", child_nodes.len());
Ok(Box::new(SequenceNode::new(child_nodes)))
}
CompositionConfig::Selector { children, name } => {
debug!(
"Loading selector node{}",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default()
);
let child_nodes = children
.iter()
.enumerate()
.map(|(i, child)| {
self.load_composition(child, config)
.with_context(|| format!("Failed to load selector child {}", i))
})
.collect::<Result<Vec<_>>>()?;
debug!("Selector node loaded with {} children", child_nodes.len());
Ok(Box::new(SelectOrNode::new(child_nodes)))
}
CompositionConfig::Parallel { children, policy, name } => {
debug!(
"Loading parallel node{} with policy {:?}",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default(),
policy
);
let child_nodes = children
.iter()
.enumerate()
.map(|(i, child)| {
self.load_composition(child, config)
.with_context(|| format!("Failed to load parallel child {}", i))
})
.collect::<Result<Vec<_>>>()?;
debug!("Parallel node loaded with {} children", child_nodes.len());
Ok(Box::new(ParallelNode::new(child_nodes, policy.clone().into())))
}
CompositionConfig::Watch { children, policy, name } => {
debug!(
"Loading watch node{} with policy {:?}",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default(),
policy
);
let child_nodes = children
.iter()
.enumerate()
.map(|(i, child)| {
self.load_composition(child, config)
.with_context(|| format!("Failed to load watch child {}", i))
})
.collect::<Result<Vec<_>>>()?;
debug!("Watch node loaded with {} children", child_nodes.len());
Ok(Box::new(WatchNode::new(child_nodes, policy.clone().into())))
}
CompositionConfig::Subsumption { layers, name } => {
debug!(
"Loading subsumption node{} with {} layers",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default(),
layers.len()
);
let mut node = SubsumptionNode::default();
for (i, layer) in layers.iter().enumerate() {
let behavior = self
.load_composition(&layer.node, config)
.with_context(|| format!("Failed to load subsumption layer {}", i))?;
let mut subsumption_layer = crate::composition::SubsumptionLayer::new(layer.priority, behavior);
if let Some(layer_name) = &layer.name {
subsumption_layer = subsumption_layer.with_name(layer_name.clone());
}
node.layers.push(subsumption_layer);
}
node.layers.sort_by_key(|l| std::cmp::Reverse(l.priority));
debug!("Subsumption node loaded with {} layers", node.layers.len());
Ok(Box::new(node))
}
CompositionConfig::Inverter { child, name } => {
debug!(
"Loading inverter node{}",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default()
);
let child_node = self
.load_composition(child, config)
.with_context(|| "Failed to load inverter child")?;
Ok(Box::new(InverterNode::new(child_node)))
}
CompositionConfig::ForceSuccess { child, name } => {
debug!(
"Loading force_success node{}",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default()
);
let child_node = self
.load_composition(child, config)
.with_context(|| "Failed to load force_success child")?;
Ok(Box::new(ForceSuccessNode::new(child_node)))
}
CompositionConfig::ForceFailure { child, name } => {
debug!(
"Loading force_failure node{}",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default()
);
let child_node = self
.load_composition(child, config)
.with_context(|| "Failed to load force_failure child")?;
Ok(Box::new(ForceFailureNode::new(child_node)))
}
CompositionConfig::Repeat { child, count, name } => {
debug!(
"Loading repeat node{} (count: {:?})",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default(),
count
);
let child_node = self
.load_composition(child, config)
.with_context(|| "Failed to load repeat child")?;
Ok(Box::new(RepeatNode::new(child_node, *count)))
}
CompositionConfig::Retry {
child,
max_attempts,
name,
} => {
debug!(
"Loading retry node{} (max_attempts: {})",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default(),
max_attempts
);
let child_node = self
.load_composition(child, config)
.with_context(|| "Failed to load retry child")?;
Ok(Box::new(RetryNode::new(child_node, *max_attempts)))
}
CompositionConfig::Timeout {
child,
timeout_secs,
name,
} => {
debug!(
"Loading timeout node{} (timeout_secs: {})",
name.as_ref().map(|n| format!(" '{}'", n)).unwrap_or_default(),
timeout_secs
);
let child_node = self
.load_composition(child, config)
.with_context(|| "Failed to load timeout child")?;
Ok(Box::new(TimeoutNode::new(
child_node,
std::time::Duration::from_secs_f64(timeout_secs.max(0.0)),
)))
}
CompositionConfig::Node {
node,
config_ref,
config: inline_config,
name,
} => {
debug!(
"Loading leaf node '{}' (type: {}){}",
name.as_ref().unwrap_or(node),
node,
config_ref
.as_ref()
.map(|r| format!(" with config_ref '{}'", r))
.unwrap_or_default()
);
let node_config = if let Some(inline) = inline_config {
debug!("Using inline config for node '{}'", node);
inline.clone()
} else if let Some(ref_key) = config_ref {
config
.get_config(ref_key)
.ok_or_else(|| {
anyhow!(
"Config reference '{}' not found in configs map for node '{}'",
ref_key,
node
)
})?
.clone()
} else {
debug!("No config provided for node '{}'", node);
Value::Null
};
self.registry
.create(node, node_config)
.with_context(|| format!("Failed to create node '{}'", node))
}
}
}
/// Get a reference to the underlying node registry.
///
/// This can be useful for inspecting registered types or adding new types
/// after the loader has been created.
pub fn registry(&self) -> &NodeRegistry {
&self.registry
}
}
impl std::fmt::Debug for BehaviorLoader {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BehaviorLoader")
.field("registry", &self.registry)
.finish()
}
}