concinnity-asset 0.18.66

User-facing asset schema for the Concinnity engine
Documentation
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
// Behavior schema: declarative logic over typed state, world reads, and a
// per-frame tick.

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;

use crate::{AssetId, AudioClipHandle, StoryPlayback, de_opt_asset_ref, de_opt_audio_clip_handle};

/// A unit of world logic: an event source, the entities it runs against, its
/// state, the world it reads, and the nodes it runs.
///
/// A behavior with an empty `scope` runs once per firing, world-scoped. A
/// behavior with a `scope` runs once per matching entity, each with its own
/// copy of `locals`, and `"self"` resolves to that entity.
///
/// `locals` and `queries` are declared here and resolved to dense slots once,
/// when the world starts, so nothing is looked up by name while it runs. A
/// query naming an unknown component is a build error.
///
/// `once` limits a behavior to a single firing; `cooldown` enforces a minimum
/// number of seconds between firings; `delay` postpones the nodes after the
/// firing decision, which is made at fire time rather than after the delay.
/// Timers, delays, and cooldowns freeze while a menu is open, like the rest of
/// the world clock.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct Behavior {
    /// Asset identity; injected via `inject_name`. Not part of `args`.
    #[serde(skip)]
    pub asset_id: AssetId,
    /// The event that fires this behavior.
    pub on: BehaviorSource,
    /// Component names selecting the entities this behavior runs against. An
    /// empty list runs it once, world-scoped, with no `"self"`.
    ///
    /// The names are matched against the components entities carry while the
    /// world runs, which are not always the ones a world declares: the build
    /// expands some types away, compiles others into the resource stream, and a
    /// load-time pass decomposes the rest. `"Prop"` is the common case and
    /// works, resolving to the marker decomposition leaves on every prop's
    /// entity, model- and mesh-backed alike. A name with no runtime counterpart
    /// is a build error rather than a scope that silently matches nothing.
    pub scope: Vec<String>,
    /// Per-entity state. Each matching entity gets its own copy, reset to the
    /// declared value when the world starts. Locals are never persisted.
    pub locals: Vec<BehaviorLocal>,
    /// World reads, resolved once per tick into a stable-ordered entity list.
    pub queries: Vec<BehaviorQuery>,
    /// The nodes run, in order, each time the behavior fires.
    #[serde(rename = "do")]
    pub body: Vec<BehaviorNode>,
    /// Fire at most once per run.
    pub once: bool,
    /// Seconds between the firing decision and the nodes running (`0` runs
    /// them immediately).
    pub delay: f32,
    /// Minimum seconds between firings (`0` allows every firing).
    pub cooldown: f32,
}

/// The event that fires a [Behavior](#behavior).
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BehaviorSource {
    /// Fires once when the world starts.
    #[default]
    Start,
    /// Fires every tick.
    Tick,
    /// Fires when `interval` seconds have elapsed; with `repeat`, every
    /// `interval` seconds.
    Timer {
        /// Seconds before the behavior fires.
        #[serde(default)]
        interval: f32,
        /// `true` fires every `interval` seconds; `false` fires once.
        #[serde(default)]
        repeat: bool,
    },
    /// Fires whenever the named world variable changes value.
    Variable(String),
    /// Fires when something enters the named [TriggerVolume](#triggervolume).
    Enter(#[serde(deserialize_with = "de_opt_asset_ref")] Option<AssetId>),
    /// Fires when something leaves the named [TriggerVolume](#triggervolume).
    Exit(#[serde(deserialize_with = "de_opt_asset_ref")] Option<AssetId>),
    /// Fires when the interact key is pressed on the named entity (a
    /// [Prop](#prop) declared `interactable`).
    Interact(#[serde(deserialize_with = "de_opt_asset_ref")] Option<AssetId>),
    /// Fires on an entity the tick after it spawns.
    Spawned,
}

/// A per-entity state slot declared by a [Behavior](#behavior). The declared
/// value fixes both the slot's type and its starting value.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct BehaviorLocal {
    /// The name nodes read the slot by.
    pub name: String,
    /// The slot's type and starting value.
    pub value: BehaviorLiteral,
}

/// A world read declared by a [Behavior](#behavior), resolved once per tick
/// into the entities carrying every named component.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct BehaviorQuery {
    /// The name expressions read the result by.
    pub name: String,
    /// Component names an entity must all carry to match. Resolved the same
    /// way as a behavior's [`scope`](Behavior::scope).
    pub has: Vec<String>,
}

/// A typed literal in a [Behavior](#behavior).
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BehaviorLiteral {
    /// A boolean.
    Bool(bool),
    /// A signed integer.
    Int(i32),
    /// A 32-bit float.
    Float(f32),
    /// A 3-component vector.
    Vec3([f32; 3]),
}

impl Default for BehaviorLiteral {
    fn default() -> Self {
        BehaviorLiteral::Int(0)
    }
}

/// A value expression in a [Behavior](#behavior).
///
/// Expressions are pure: they read state, entities, and the clock, and never
/// change the world. Arithmetic works on both scalars and vectors, and mixing
/// the two is a build error.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BehaviorExpr {
    /// A boolean literal.
    Bool(bool),
    /// An integer literal.
    Int(i32),
    /// A float literal.
    Float(f32),
    /// A vector literal.
    Vec3([f32; 3]),
    /// Reads a world variable.
    Var(String),
    /// Reads one of this behavior's per-entity locals.
    Local(String),
    /// Reads a name bound earlier by a `let` or `for_each` node.
    Bind(String),
    /// An entity declared in the world, addressed by asset name.
    Named(#[serde(deserialize_with = "de_opt_asset_ref")] Option<AssetId>),
    /// The entity this behavior instance runs for. Only valid with a `scope`.
    #[serde(rename = "self")]
    SelfEntity,
    /// Seconds elapsed since the previous tick.
    Dt,
    /// Seconds elapsed since the world started.
    Elapsed,
    /// World-space position of an entity.
    Position(Box<BehaviorExpr>),
    /// Distance between two entities.
    Distance(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// The first entity of a declared query, or none when it is empty.
    First(String),
    /// How many entities a declared query matched.
    Count(String),
    /// Whether an entity is still alive.
    Alive(Box<BehaviorExpr>),
    /// Sum of two values.
    Add(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// Difference of two values.
    Sub(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// Product of two values; a vector may be scaled by a scalar.
    Mul(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// Quotient of two values; dividing by zero yields zero.
    Div(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// A vector rescaled to unit length; a zero vector stays zero.
    Normalize(Box<BehaviorExpr>),
    /// Equality test.
    Eq(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// Inequality test.
    Ne(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// Less-than test.
    Lt(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// Less-than-or-equal test.
    Le(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// Greater-than test.
    Gt(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// Greater-than-or-equal test.
    Ge(Box<BehaviorExpr>, Box<BehaviorExpr>),
    /// True when every operand is true.
    All(Vec<BehaviorExpr>),
    /// True when any operand is true.
    Any(Vec<BehaviorExpr>),
    /// Logical negation.
    Not(Box<BehaviorExpr>),
}

impl Default for BehaviorExpr {
    fn default() -> Self {
        BehaviorExpr::Bool(false)
    }
}

/// One node run by a firing [Behavior](#behavior).
///
/// Nodes are the only way a behavior changes the world. There is no unbounded
/// loop and no recursion, so a behavior body always terminates.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BehaviorNode {
    /// Runs `then` when `cond` holds, `else` otherwise.
    If {
        /// The tested expression.
        cond: BehaviorExpr,
        /// Nodes run when `cond` holds.
        #[serde(default)]
        then: Vec<BehaviorNode>,
        /// Nodes run when `cond` does not hold.
        #[serde(default, rename = "else")]
        otherwise: Vec<BehaviorNode>,
    },
    /// Runs `do` once per entity a declared query matched, binding each to
    /// `bind`.
    ForEach {
        /// The declared query iterated.
        query: String,
        /// The name each entity is bound to.
        bind: String,
        /// Nodes run per entity.
        #[serde(default, rename = "do")]
        body: Vec<BehaviorNode>,
    },
    /// Binds an expression to a name for the rest of the body.
    Let {
        /// The bound name.
        name: String,
        /// The bound expression.
        value: BehaviorExpr,
    },
    /// Writes a world variable: assign `value`, or add it to the current value
    /// when `add` is `true`.
    Set {
        /// The variable written.
        var: String,
        /// The value assigned (or added).
        value: BehaviorExpr,
        /// `false` assigns `value`; `true` adds it to the current value.
        #[serde(default)]
        add: bool,
    },
    /// Writes one of this behavior's per-entity locals.
    SetLocal {
        /// The local written.
        local: String,
        /// The value assigned (or added).
        value: BehaviorExpr,
        /// `false` assigns `value`; `true` adds it to the current value.
        #[serde(default)]
        add: bool,
    },
    /// Writes an entity's transform. An omitted field is left unchanged.
    SetTransform {
        /// The entity moved.
        entity: BehaviorExpr,
        /// New world-space position.
        #[serde(default)]
        position: Option<BehaviorExpr>,
        /// New Euler rotation in degrees.
        #[serde(default)]
        rotation_deg: Option<BehaviorExpr>,
        /// New scale.
        #[serde(default)]
        scale: Option<BehaviorExpr>,
    },
    /// Creates a copy of an existing placement at a world position. Binding
    /// `bind` makes the copy addressable for the rest of the body.
    Spawn {
        /// The placement copied (e.g. a [Prop](#prop)).
        #[serde(default, deserialize_with = "de_opt_asset_ref")]
        template: Option<AssetId>,
        /// World-space position of the copy.
        #[serde(default)]
        position: [f32; 3],
        /// Euler rotation of the copy in degrees.
        #[serde(default)]
        rotation_deg: [f32; 3],
        /// Scale of the copy (`[1, 1, 1]` keeps the template's size).
        #[serde(default = "unit_scale")]
        scale: [f32; 3],
        /// Seconds the copy lives before auto-despawning (`0` lives forever).
        #[serde(default)]
        lifetime: f32,
        /// Name the new entity is bound to for the rest of the body.
        #[serde(default)]
        bind: Option<String>,
    },
    /// Removes an entity and its children from the world.
    Despawn {
        /// The entity removed.
        target: BehaviorExpr,
    },
    /// Re-points an entity's parent edge.
    Reparent {
        /// The entity moved.
        child: BehaviorExpr,
        /// The new parent, or unset to detach to a root.
        #[serde(default)]
        parent: Option<BehaviorExpr>,
    },
    /// Makes a hidden entity (and its children) visible again.
    Show {
        /// The entity revealed.
        target: BehaviorExpr,
    },
    /// Makes an entity (and its children) invisible without removing it. A
    /// hidden entity keeps simulating; `show` reverses this.
    Hide {
        /// The entity hidden.
        target: BehaviorExpr,
    },
    /// Plays an [AudioClip](#audioclip) flat on the main mix (no 3D position).
    Sound {
        /// The clip played.
        #[serde(default, deserialize_with = "de_opt_audio_clip_handle")]
        clip: Option<AudioClipHandle>,
        /// Playback behavior: a looping `music` track or a one-shot `sound`.
        #[serde(default)]
        kind: crate::CueKind,
        /// Linear gain applied to the clip (`1.0` leaves it unchanged).
        #[serde(default = "unit_volume")]
        volume: f32,
    },
    /// Jumps the world to a named [Scene](#scene).
    Scene {
        /// The scene jumped to.
        #[serde(default, deserialize_with = "de_opt_asset_ref")]
        scene: Option<AssetId>,
        /// The transition: `"Cut"` or `"FadeBlack"`.
        #[serde(default = "default_transition")]
        transition: String,
    },
    /// Shows a [Screen](#screen), replacing the top of the screen stack.
    Screen {
        /// The screen shown.
        #[serde(default, deserialize_with = "de_opt_asset_ref")]
        screen: Option<AssetId>,
    },
    /// Controls the world's [Story](#story) playback.
    Story(StoryPlayback),
    /// Writes the world's logic state to disk: every world variable, plus
    /// which `once` behaviors have fired. Per-entity locals are not saved. The
    /// state is restored the next time the world starts, so a behavior gated
    /// on a saved variable carries across runs. Timers, delays, and cooldowns
    /// restart fresh; entities are not saved. A world with no `save` node
    /// never reads or writes state.
    Save,
}

impl Behavior {
    /// Whether any node plays an audio clip, so the runtime knows this
    /// behavior needs the audio system and its clip payloads cached.
    pub fn plays_sound(&self) -> bool {
        self.visit(&mut |n| matches!(n, BehaviorNode::Sound { .. }))
    }

    /// Whether any node saves the world's logic state, so the runtime knows to
    /// restore persisted state when the world starts.
    pub fn saves_state(&self) -> bool {
        self.visit(&mut |n| matches!(n, BehaviorNode::Save))
    }

    /// Whether the behavior runs against individual entities rather than the
    /// world as a whole.
    pub fn is_scoped(&self) -> bool {
        !self.scope.is_empty()
    }

    // True when any node in the body, at any nesting depth, satisfies `pred`.
    fn visit(&self, pred: &mut impl FnMut(&BehaviorNode) -> bool) -> bool {
        fn walk(nodes: &[BehaviorNode], pred: &mut impl FnMut(&BehaviorNode) -> bool) -> bool {
            nodes.iter().any(|n| {
                pred(n)
                    || match n {
                        BehaviorNode::If {
                            then, otherwise, ..
                        } => walk(then, pred) || walk(otherwise, pred),
                        BehaviorNode::ForEach { body, .. } => walk(body, pred),
                        _ => false,
                    }
            })
        }
        walk(&self.body, pred)
    }
}

fn unit_scale() -> [f32; 3] {
    [1.0, 1.0, 1.0]
}

fn unit_volume() -> f32 {
    1.0
}

fn default_transition() -> String {
    String::from("FadeBlack")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(json: &str) -> Behavior {
        serde_json::from_str(json).expect("behavior parses")
    }

    // Destructuring helpers, each `None` for any other kind. The parse tests
    // read as assertions on the parts rather than nested pattern matches.
    fn as_if(node: &BehaviorNode) -> Option<(&BehaviorExpr, &[BehaviorNode], &[BehaviorNode])> {
        match node {
            BehaviorNode::If {
                cond,
                then,
                otherwise,
            } => Some((cond, then, otherwise)),
            _ => None,
        }
    }

    fn as_spawn(node: &BehaviorNode) -> Option<(Option<&str>, [f32; 3])> {
        match node {
            BehaviorNode::Spawn { bind, scale, .. } => Some((bind.as_deref(), *scale)),
            _ => None,
        }
    }

    fn as_set(node: &BehaviorNode) -> Option<(&str, &BehaviorExpr, bool)> {
        match node {
            BehaviorNode::Set { var, value, add } => Some((var, value, *add)),
            _ => None,
        }
    }

    fn as_despawn(node: &BehaviorNode) -> Option<&BehaviorExpr> {
        match node {
            BehaviorNode::Despawn { target } => Some(target),
            _ => None,
        }
    }

    fn as_lt(expr: &BehaviorExpr) -> Option<(&BehaviorExpr, &BehaviorExpr)> {
        match expr {
            BehaviorExpr::Lt(lhs, rhs) => Some((lhs, rhs)),
            _ => None,
        }
    }

    fn as_distance(expr: &BehaviorExpr) -> Option<(&BehaviorExpr, &BehaviorExpr)> {
        match expr {
            BehaviorExpr::Distance(a, b) => Some((a, b)),
            _ => None,
        }
    }

    #[test]
    fn the_destructuring_helpers_only_match_their_own_kind() {
        let b = parse(r#"{"do":[{"save":null}]}"#);
        let save = &b.body[0];
        assert!(as_if(save).is_none());
        assert!(as_spawn(save).is_none());
        assert!(as_set(save).is_none());
        assert!(as_despawn(save).is_none());
        assert!(as_lt(&BehaviorExpr::Bool(true)).is_none());
        assert!(as_distance(&BehaviorExpr::Bool(true)).is_none());
    }

    #[test]
    fn defaults_are_world_scoped_and_empty() {
        let b = Behavior::default();
        assert!(!b.is_scoped());
        assert!(b.body.is_empty());
        assert_eq!(b.on, BehaviorSource::Start);
        assert!(!b.plays_sound());
        assert!(!b.saves_state());
    }

    #[test]
    fn tick_source_parses() {
        let b = parse(r#"{"on":"tick"}"#);
        assert_eq!(b.on, BehaviorSource::Tick);
    }

    #[test]
    fn spawned_source_parses() {
        let b = parse(r#"{"on":"spawned"}"#);
        assert_eq!(b.on, BehaviorSource::Spawned);
    }

    #[test]
    fn scope_and_locals_parse() {
        let b = parse(
            r#"{"on":"tick","scope":["Prop"],"locals":[{"name":"speed","value":{"float":3.0}}]}"#,
        );
        assert!(b.is_scoped());
        assert_eq!(b.scope, ["Prop"]);
        assert_eq!(b.locals.len(), 1);
        assert_eq!(b.locals[0].name, "speed");
        assert_eq!(b.locals[0].value, BehaviorLiteral::Float(3.0));
    }

    #[test]
    fn query_parses() {
        let b = parse(r#"{"queries":[{"name":"player","has":["Camera3D","Prop"]}]}"#);
        assert_eq!(b.queries.len(), 1);
        assert_eq!(b.queries[0].name, "player");
        assert_eq!(b.queries[0].has, ["Camera3D", "Prop"]);
    }

    #[test]
    fn comparison_expression_parses_as_pair() {
        let b = parse(
            r#"{"do":[{"if":{"cond":{"lt":[{"distance":["self",{"bind":"t"}]},{"float":20.0}]}}}]}"#,
        );
        let (cond, then, otherwise) = as_if(&b.body[0]).expect("an if node");
        assert!(then.is_empty());
        assert!(otherwise.is_empty());
        let (lhs, rhs) = as_lt(cond).expect("a less-than comparison");
        assert_eq!(*rhs, BehaviorExpr::Float(20.0));
        let (a, b) = as_distance(lhs).expect("a distance expression");
        assert_eq!(*a, BehaviorExpr::SelfEntity);
        assert_eq!(*b, BehaviorExpr::Bind(String::from("t")));
    }

    #[test]
    fn spawn_binds_the_new_entity() {
        let b = parse(r#"{"do":[{"spawn":{"bind":"made"}}]}"#);
        let (bind, scale) = as_spawn(&b.body[0]).expect("a spawn node");
        assert_eq!(bind, Some("made"));
        assert_eq!(scale, [1.0, 1.0, 1.0]);
    }

    #[test]
    fn nested_nodes_are_visited_for_sound_and_save() {
        let b = parse(
            r#"{"do":[{"for_each":{"query":"q","bind":"e","do":[{"if":{"cond":{"bool":true},"then":[{"sound":{}}],"else":[{"save":null}]}}]}}]}"#,
        );
        assert!(b.plays_sound());
        assert!(b.saves_state());
    }

    #[test]
    fn round_trips_through_json() {
        let b = parse(
            r#"{"on":{"timer":{"interval":5.0,"repeat":true}},"do":[{"set":{"var":"visits","value":{"int":1},"add":true}}]}"#,
        );
        let encoded = serde_json::to_string(&b).expect("behavior encodes");
        let again: Behavior = serde_json::from_str(&encoded).expect("behavior re-parses");
        assert_eq!(again.on, b.on);
        let (var, value, add) = as_set(&again.body[0]).expect("a set node");
        assert_eq!(var, "visits");
        assert_eq!(*value, BehaviorExpr::Int(1));
        assert!(add);
    }

    #[test]
    fn a_blank_expression_is_false() {
        // Lets a node's expression field carry `#[serde(default)]` without the
        // omission reading as "fires".
        assert_eq!(BehaviorExpr::default(), BehaviorExpr::Bool(false));
    }

    #[test]
    fn a_scene_node_fades_unless_told_to_cut() {
        crate::test_support::install_resolvers();
        let b = parse(r#"{"do":[{"scene":{"scene":"hub"}},{"scene":{"transition":"Cut"}}]}"#);
        assert!(matches!(
            (&b.body[0], &b.body[1]),
            (
                BehaviorNode::Scene { transition: a, .. },
                BehaviorNode::Scene { transition: c, .. },
            ) if a == "FadeBlack" && c == "Cut"
        ));
    }

    #[test]
    fn a_sound_node_plays_at_unit_gain_unless_told_otherwise() {
        let b = parse(r#"{"do":[{"sound":{}}]}"#);
        assert!(matches!(b.body[0], BehaviorNode::Sound { volume, .. } if volume == 1.0));
        assert!(b.plays_sound());
    }

    #[test]
    fn round_trips_through_postcard() {
        let b = parse(r#"{"on":"tick","scope":["Prop"],"do":[{"despawn":{"target":"self"}}]}"#);
        let bytes = postcard::to_allocvec(&b).expect("behavior encodes");
        let again: Behavior = postcard::from_bytes(&bytes).expect("behavior decodes");
        assert_eq!(again.on, BehaviorSource::Tick);
        let target = as_despawn(&again.body[0]).expect("a despawn node");
        assert_eq!(*target, BehaviorExpr::SelfEntity);
    }
}