1use serde::{Deserialize, Serialize};
21
22use crate::chain::Module;
23
24#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
26pub struct Node {
27 pub id: u32,
28 pub module: Module,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Link {
34 pub from: u32,
35 pub to: u32,
36}
37
38#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
40pub struct FxGraph {
41 pub nodes: Vec<Node>,
42 pub links: Vec<Link>,
43}
44
45#[derive(Clone, Debug, PartialEq)]
47pub enum GraphError {
48 KeinEmitter,
49 MehrereEmittenten,
50 DoppelteId(u32),
51 UnbekannterKnoten(u32),
52 Selbstschleife(u32),
53 Verzweigung { von: u32 },
54 Zulauf { knoten: u32 },
55 Zyklus,
56 Verwaist(Vec<u32>),
57 UngueltigeKurve { knoten: u32 },
58}
59
60impl core::fmt::Display for GraphError {
61 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62 match self {
63 GraphError::KeinEmitter => write!(f, "kein Emitter-Knoten"),
64 GraphError::MehrereEmittenten => write!(f, "mehrere Emitter-Knoten"),
65 GraphError::DoppelteId(id) => write!(f, "doppelte Knoten-Id {id}"),
66 GraphError::UnbekannterKnoten(id) => {
67 write!(f, "Kante zeigt auf unbekannten Knoten {id}")
68 }
69 GraphError::Selbstschleife(id) => write!(f, "Knoten {id} verknüpft sich selbst"),
70 GraphError::Verzweigung { von } => write!(f, "Knoten {von} hat mehrere Ausgänge"),
71 GraphError::Zulauf { knoten } => write!(f, "Knoten {knoten} hat mehrere Zuläufe"),
72 GraphError::Zyklus => write!(f, "Kantengerüst enthält einen Zyklus"),
73 GraphError::Verwaist(ids) => write!(f, "verwaiste Knoten: {ids:?}"),
74 GraphError::UngueltigeKurve { knoten } => {
75 write!(f, "Knoten {knoten} trägt einen unsortierten Kurvenzug")
76 }
77 }
78 }
79}
80
81impl std::error::Error for GraphError {}
82
83impl FxGraph {
84 pub fn new() -> Self {
85 Self::default()
86 }
87
88 pub fn add(&mut self, module: Module) -> u32 {
90 let id = self.nodes.len() as u32;
91 self.nodes.push(Node { id, module });
92 id
93 }
94
95 pub fn link(&mut self, from: u32, to: u32) {
97 self.links.push(Link { from, to });
98 }
99
100 pub fn compile(&self) -> Result<Vec<Module>, GraphError> {
106 let mut ids: Vec<u32> = self.nodes.iter().map(|n| n.id).collect();
108 ids.sort_unstable();
109 if let Some(w) = ids.windows(2).find(|w| w[0] == w[1]) {
110 return Err(GraphError::DoppelteId(w[0]));
111 }
112
113 let emitter: Vec<u32> = self
115 .nodes
116 .iter()
117 .filter(|n| matches!(n.module, Module::Emit(_)))
118 .map(|n| n.id)
119 .collect();
120 match emitter.len() {
121 0 => return Err(GraphError::KeinEmitter),
122 1 => {}
123 _ => return Err(GraphError::MehrereEmittenten),
124 }
125
126 for l in &self.links {
128 if !self.nodes.iter().any(|n| n.id == l.from)
129 || !self.nodes.iter().any(|n| n.id == l.to)
130 {
131 return Err(GraphError::UnbekannterKnoten(
132 if self.nodes.iter().any(|n| n.id == l.from) {
133 l.to
134 } else {
135 l.from
136 },
137 ));
138 }
139 if l.from == l.to {
140 return Err(GraphError::Selbstschleife(l.from));
141 }
142 }
143 for n in &self.nodes {
144 let aus = self.links.iter().filter(|l| l.from == n.id).count();
145 let ein = self.links.iter().filter(|l| l.to == n.id).count();
146 if aus > 1 {
147 return Err(GraphError::Verzweigung { von: n.id });
148 }
149 if ein > 1 {
150 return Err(GraphError::Zulauf { knoten: n.id });
151 }
152 }
153
154 let mut chain: Vec<Module> = Vec::new();
156 let mut besucht: Vec<u32> = Vec::new();
157 let mut cur = emitter[0];
158 loop {
159 if besucht.contains(&cur) {
160 return Err(GraphError::Zyklus);
161 }
162 besucht.push(cur);
163 let knoten = self.nodes.iter().find(|n| n.id == cur).expect("bekannt");
164 match &knoten.module {
167 Module::SizeRamp { curve } if !curve.valide() => {
168 return Err(GraphError::UngueltigeKurve { knoten: cur })
169 }
170 Module::ColorRamp { ramp } if !ramp.valide() => {
171 return Err(GraphError::UngueltigeKurve { knoten: cur })
172 }
173 _ => {}
174 }
175 chain.push(knoten.module.clone());
176 match self.links.iter().find(|l| l.from == cur) {
177 Some(l) => cur = l.to,
178 None => break,
179 }
180 }
181
182 let mut verwaist: Vec<u32> = self
184 .nodes
185 .iter()
186 .filter(|n| !besucht.contains(&n.id))
187 .map(|n| n.id)
188 .collect();
189 if !verwaist.is_empty() {
190 verwaist.sort_unstable();
191 return Err(GraphError::Verwaist(verwaist));
192 }
193 Ok(chain)
194 }
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200 use crate::chain::Emitter;
201 use crate::curve::{ColorKey, ColorRamp, Curve, Key};
202
203 fn brunnen() -> Module {
204 Module::Emit(Emitter::default())
205 }
206
207 #[test]
208 fn kantentreue_kette_unabhaengig_von_der_speicherfolge() {
209 let mut g = FxGraph::new();
211 let grav = g.add(Module::Gravity {
212 g: [0.0, -9.81, 0.0],
213 });
214 let emit = g.add(brunnen());
215 let dreh = g.add(Module::Swirl { per_step: 0.1 });
216 g.link(emit, dreh);
217 g.link(dreh, grav);
218 let chain = g.compile().expect("kompiliert");
219 assert!(matches!(chain[0], Module::Emit(_)));
220 assert!(matches!(chain[1], Module::Swirl { .. }));
221 assert!(matches!(chain[2], Module::Gravity { .. }));
222 assert_eq!(chain.len(), 3);
223 }
224
225 #[test]
226 fn einzelner_emitter_ohne_kanten_reicht() {
227 let mut g = FxGraph::new();
228 g.add(brunnen());
229 let chain = g.compile().expect("kompiliert");
230 assert_eq!(chain.len(), 1);
231 }
232
233 #[test]
234 fn regelbrueche_werden_erkannt() {
235 let leer = FxGraph {
237 nodes: vec![Node {
238 id: 0,
239 module: Module::Drag { per_step: 0.1 },
240 }],
241 links: vec![],
242 };
243 assert_eq!(leer.compile(), Err(GraphError::KeinEmitter));
244
245 let mut zwei = FxGraph::new();
247 zwei.add(brunnen());
248 zwei.add(brunnen());
249 assert_eq!(zwei.compile(), Err(GraphError::MehrereEmittenten));
250
251 let mut g = FxGraph::new();
253 let e = g.add(brunnen());
254 let a = g.add(Module::Drag { per_step: 0.1 });
255 let b = g.add(Module::Gravity { g: [0.0, 0.0, 0.0] });
256 g.link(e, a);
257 g.link(e, b);
258 assert_eq!(g.compile(), Err(GraphError::Verzweigung { von: e }));
259
260 let mut g = FxGraph::new();
262 let e = g.add(brunnen());
263 let a = g.add(Module::Drag { per_step: 0.1 });
264 let b = g.add(Module::Gravity { g: [0.0, 0.0, 0.0] });
265 g.link(e, a);
266 g.link(b, a);
267 g.link(a, b); assert_eq!(g.compile(), Err(GraphError::Zulauf { knoten: a }));
269
270 let mut g = FxGraph::new();
272 let e = g.add(brunnen());
273 let a = g.add(Module::Drag { per_step: 0.1 });
274 g.link(e, a);
275 g.link(a, e);
276 assert_eq!(g.compile(), Err(GraphError::Zyklus));
277
278 let mut g = FxGraph::new();
280 let e = g.add(brunnen());
281 g.link(e, e);
282 assert_eq!(g.compile(), Err(GraphError::Selbstschleife(e)));
283
284 let mut g = FxGraph::new();
286 g.add(brunnen());
287 g.add(Module::Drag { per_step: 0.1 });
288 g.add(Module::Gravity { g: [0.0, 1.0, 0.0] });
289 assert_eq!(g.compile(), Err(GraphError::Verwaist(vec![1, 2])));
290
291 let mut g = FxGraph::new();
293 let e = g.add(brunnen());
294 g.link(e, 42);
295 assert_eq!(g.compile(), Err(GraphError::UnbekannterKnoten(42)));
296
297 let doppel = FxGraph {
299 nodes: vec![
300 Node {
301 id: 7,
302 module: brunnen(),
303 },
304 Node {
305 id: 7,
306 module: Module::Drag { per_step: 0.1 },
307 },
308 ],
309 links: vec![],
310 };
311 assert_eq!(doppel.compile(), Err(GraphError::DoppelteId(7)));
312
313 let mut g = FxGraph::new();
315 let e = g.add(brunnen());
316 let k = g.add(Module::SizeRamp {
317 curve: Curve {
318 keys: vec![Key { t: 1.0, value: 1.0 }, Key { t: 0.0, value: 2.0 }],
319 },
320 });
321 g.link(e, k);
322 assert_eq!(g.compile(), Err(GraphError::UngueltigeKurve { knoten: k }));
323 }
324
325 #[test]
326 fn json_roundtrip_ist_verlustfrei() {
327 let mut g = FxGraph::new();
328 let e = g.add(Module::Emit(Emitter {
329 origin: [1.0, 2.0, 3.0],
330 axis: [0.0, 1.0, 0.0],
331 spread: 0.5,
332 speed: [1.0, 2.0],
333 life: [0.5, 1.5],
334 rate: 60.0,
335 burst: 8,
336 }));
337 let r = g.add(Module::ColorRamp {
338 ramp: ColorRamp {
339 keys: vec![
340 ColorKey {
341 t: 0.0,
342 color: [1.0, 0.6, 0.1, 1.0],
343 },
344 ColorKey {
345 t: 0.55,
346 color: [0.9, 0.1, 0.05, 0.8],
347 },
348 ColorKey {
349 t: 1.0,
350 color: [0.05, 0.05, 0.1, 0.0],
351 },
352 ],
353 },
354 });
355 let s = g.add(Module::SizeRamp {
356 curve: Curve {
357 keys: vec![
358 Key { t: 0.0, value: 0.4 },
359 Key {
360 t: 1.0,
361 value: 0.01,
362 },
363 ],
364 },
365 });
366 g.link(e, r);
367 g.link(r, s);
368 let text = serde_json::to_string(&g).expect("JSON");
369 let zurueck: FxGraph = serde_json::from_str(&text).expect("zurück");
370 assert_eq!(zurueck, g);
371 assert_eq!(zurueck.compile().expect("kompiliert").len(), 3);
372 }
373
374 #[test]
375 fn graph_und_handkette_sind_bitgleich() {
376 use crate::sim::FxWorld;
377 let mut g = FxGraph::new();
378 let e = g.add(Module::Emit(Emitter {
379 rate: 80.0,
380 burst: 10,
381 life: [0.8, 1.6],
382 speed: [1.0, 2.0],
383 spread: 0.8,
384 ..Emitter::default()
385 }));
386 let kette = [
387 Module::Gravity {
388 g: [0.0, -5.0, 0.0],
389 },
390 Module::Drag { per_step: 0.02 },
391 Module::Swirl { per_step: 0.05 },
392 Module::ColorRamp {
393 ramp: ColorRamp::lerp2([1.0, 0.7, 0.2, 1.0], [0.4, 0.0, 0.0, 0.0]),
394 },
395 Module::SizeRamp {
396 curve: Curve::lerp2(0.35, 0.02),
397 },
398 ];
399 for m in &kette {
400 let id = g.add(m.clone());
401 let letzter = g.links.last().map(|l| l.to).unwrap_or(e);
402 if id != letzter {
403 g.link(letzter, id);
404 }
405 }
406 let hand = std::iter::once(Module::Emit(Emitter {
407 rate: 80.0,
408 burst: 10,
409 life: [0.8, 1.6],
410 speed: [1.0, 2.0],
411 spread: 0.8,
412 ..Emitter::default()
413 }))
414 .chain(kette.iter().cloned())
415 .collect::<Vec<_>>();
416
417 let mut welta = FxWorld::new(crate::sim::FxCfg::default());
418 let mut weltb = FxWorld::new(crate::sim::FxCfg::default());
419 welta.play_graph(&g).expect("Graph startet");
420 weltb.play(hand);
421 for _ in 0..80 {
422 welta.step(1.0 / 60.0);
423 weltb.step(1.0 / 60.0);
424 }
425 assert_eq!(
426 welta.charge_bytes(),
427 weltb.charge_bytes(),
428 "Graph-Kompilat muss bitgleich zur Handkette sein"
429 );
430 }
431}