compiler_global/
compiler_global.rs1use animgraph::compiler::prelude::*;
4use std::sync::Arc;
5
6const TEST_EVENT: &str = "TestEvent";
7
8fn main() -> anyhow::Result<()> {
9 const ALMOST_PI: &str = "ALMOST_PI";
11
12 fn construct_data() -> AnimGraph {
13 fn global_number(name: &str) -> Expression {
14 Expression::CompilerGlobal(name.to_owned())
15 }
16
17 let condition = bind_parameter::<f32>("a").ge(global_number(ALMOST_PI));
18 let endpoint = endpoint(state_event(TEST_EVENT, condition, EventEmit::Always));
19
20 let machines = [state_machine("Root", [state("StateA").with(endpoint, [])])];
21
22 AnimGraph {
23 state_machines: machines.into(),
24 ..Default::default()
25 }
26 }
27
28 fn compile_data(graph: &AnimGraph) -> Result<GraphDefinitionBuilder, CompileError> {
29 let mut registry = NodeCompilationRegistry::default();
30 add_default_nodes(&mut registry);
31
32 let mut definition = GraphDefinitionCompilation::default();
34 definition.add_global_constant(ALMOST_PI, 3.0)?;
35
36 let mut context = GraphCompilationContext::build_context(&graph, ®istry)?;
37 run_graph_definition_compilation(&mut definition, &mut context)?;
38 Ok(definition.builder)
39 }
40
41 fn serialize_definition() -> serde_json::Value {
43 let animgraph = construct_data();
44 let definition_builder = compile_data(&animgraph).unwrap();
45 serde_json::to_value(definition_builder).unwrap()
46 }
47
48 fn deserialize_definition(
50 serialized: serde_json::Value,
51 ) -> anyhow::Result<Arc<GraphDefinition>> {
52 let deserialized: GraphDefinitionBuilder = serde_json::from_value(serialized)?;
53 let mut provider = GraphNodeRegistry::default();
55 add_default_constructors(&mut provider);
56 Ok(deserialized.build(&provider)?)
57 }
58
59 let serialized = serialize_definition();
61 let definition = deserialize_definition(serialized)?;
62
63 perform_runtime_test(definition);
64
65 Ok(())
66}
67
68fn perform_runtime_test(definition: Arc<GraphDefinition>) {
69 let mut graph = definition
71 .clone()
72 .build_with_empty_skeleton(Arc::new(EmptyResourceProvider));
73
74 let event = definition.get_event_by_name(TEST_EVENT).unwrap();
76 assert!(event.get(&graph) == FlowState::Exited);
77
78 let mut context = DefaultRunContext::new(1.0);
80 context.run(&mut graph);
81 assert!(context.events.emitted.is_empty());
82
83 assert!(event.get(&graph) == FlowState::Entered);
84
85 let a = definition.get_number_parameter::<f32>("a").unwrap();
87 a.set(&mut graph, 4.0);
88
89 context.run(&mut graph);
90 assert_eq!(&context.events.emitted, &[Id::from_str(TEST_EVENT)]);
91}