concinnity-engine 0.19.1

Runtime engine for Concinnity: ECS schedule, graphics, spawn, streaming
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
// src/gfx/animation/tests.rs

use crate::ecs::SYSTEMS;
use std::time::{Duration, Instant};

use super::resumed_origin;
use crate::components::{Animation, AnimationGraph, AnimationParams};
use crate::ecs::SkinnedMeshHandle;
use crate::ecs::World;
use crate::ecs::asset_id::intern;

// Resuming after a pause must leave clip time `t = now - origin` exactly
// where it was when the pause began, so playback continues from the frozen
// pose with no jump, no matter how long the menu was open.
#[test]
fn resumed_origin_freezes_clip_time_across_pause() {
    let start = Instant::now();
    // Paused at t = 5s, menu held open for 30s of real time.
    let anchor = start + Duration::from_secs(5);
    let now = anchor + Duration::from_secs(30);

    let t_at_pause = (anchor - start).as_secs_f32();
    let new_origin = resumed_origin(start, anchor, now);
    let t_on_resume = (now - new_origin).as_secs_f32();

    assert!(
        (t_on_resume - t_at_pause).abs() < 1e-6,
        "clip time jumped across the pause: {t_at_pause} -> {t_on_resume}"
    );
}

// An `Animation` in the world implies the internal AnimationSystem: it is
// constructed by `World::start`, not declared as an asset.
#[test]
fn animation_component_spawns_internal_system() {
    let mut world = World::new();
    world.add_component(Animation::default());
    world.start(SYSTEMS).unwrap();

    let names: Vec<&str> = world.systems().iter().map(|s| s.name()).collect();
    assert_eq!(names, ["AnimationSystem"]);
}

// No `Animation` means no AnimationSystem; the gate keys purely off world
// content.
#[test]
fn no_animation_no_internal_system() {
    let mut world = World::new();
    world.start(SYSTEMS).unwrap();
    assert!(world.systems().is_empty());
}

// An `AnimationGraph` alone also implies the system (a graph without clips is a
// build error, but the runtime gate must not depend on validation).
#[test]
fn anim_graph_component_spawns_internal_system() {
    let mut world = World::new();
    world.add_component(AnimationGraph::default());
    world.start(SYSTEMS).unwrap();

    let names: Vec<&str> = world.systems().iter().map(|s| s.name()).collect();
    assert_eq!(names, ["AnimationSystem"]);
}

// A clip targeting `hero`, named so graph states can reference it.
fn clip(name: &str, duration: f32) -> Animation {
    // Install the name resolver so the `"target":"hero"` reference deserializes.
    // Must not reset the interner: `intern` below accumulates ids across calls.
    crate::ecs::asset_id::ensure_name_resolver();
    let mut a: Animation = serde_json::from_value(serde_json::json!({
        "target": "hero",
        "duration": duration,
        "looping": true,
    }))
    .unwrap();
    a.asset_id = intern(name);
    a
}

// idle/run graph on `hero`, transitioning on `speed` in both directions with
// snap fades (duration 0) so state flips are visible after one step.
fn hero_graph() -> AnimationGraph {
    let mut g: AnimationGraph = serde_json::from_value(serde_json::json!({
        "target": "hero",
        "parameters": [{"name": "speed", "default": 0.0}],
        "initial": "idle",
        "states": [
            {"name": "idle", "clip": "idle_clip"},
            {"name": "run", "clip": "run_clip"}
        ],
        "transitions": [
            {"from": "idle", "to": "run",
             "conditions": [{"parameter": "speed", "op": "gt", "value": 0.5}]},
            {"from": "run", "to": "idle",
             "conditions": [{"parameter": "speed", "op": "le", "value": 0.5}]}
        ]
    }))
    .unwrap();
    g.asset_id = intern("hero_graph");
    g
}

fn graph_world() -> World {
    let mut world = World::new();
    world.add_component(clip("idle_clip", 1.0));
    world.add_component(clip("run_clip", 0.8));
    world.add_component(hero_graph());
    world.start(SYSTEMS).unwrap();
    world
}

fn hero() -> SkinnedMeshHandle {
    // The authored "hero" references deserialize through the resolver's
    // interner fallback, so the handle carries the interned id.
    SkinnedMeshHandle(intern("hero").0)
}

// Match the system back out of the world for report assertions.
fn with_anim<R>(world: &mut World, f: impl FnOnce(&mut super::AnimationSystem) -> R) -> R {
    for system in world.systems_mut() {
        if let Some(anim) = system.downcast_mut::<super::AnimationSystem>() {
            return f(anim);
        }
    }
    panic!("AnimationSystem not constructed");
}

// Init publishes one `AnimationParams` per graph, seeded with the declared
// defaults, and the graph starts in its initial state.
#[test]
fn graph_init_seeds_params_and_initial_state() {
    let mut world = graph_world();
    world.step();

    let params: Vec<&AnimationParams> = world.query::<AnimationParams>().collect();
    assert_eq!(params.len(), 1);
    assert_eq!(params[0].target, hero());
    assert_eq!(params[0].values, vec![0.0]);

    let report = with_anim(&mut world, |anim| anim.graph_report(hero()).unwrap());
    assert_eq!(report.state, "idle");
    assert_eq!(report.params, vec![("speed".to_string(), 0.0)]);
    assert!(
        report.blend_weights.is_none(),
        "single-clip states report no blend weights"
    );
}

// A blendspace state's reported member weights track the parameter: parked
// on the first point at default, split across the bracketing pair mid-range.
#[test]
fn blendspace_weights_follow_the_parameter() {
    let target = SkinnedMeshHandle(intern("hero_blend").0);
    let mut world = World::new();
    for (name, duration) in [("bl_idle", 1.0), ("bl_walk", 0.8), ("bl_run", 0.6)] {
        let mut a = clip(name, duration);
        a.target = Some(SkinnedMeshHandle(target.0));
        world.add_component(a);
    }
    let mut g: AnimationGraph = serde_json::from_value(serde_json::json!({
        "target": "hero_blend",
        "parameters": [{"name": "speed", "default": 0.0}],
        "states": [
            {"name": "locomotion", "blend": {"kind": "blend1d", "parameter": "speed",
             "sync": true,
             "points": [
                 {"value": 0.0, "clip": "bl_idle"},
                 {"value": 1.6, "clip": "bl_walk"},
                 {"value": 5.0, "clip": "bl_run"}
             ]}}
        ]
    }))
    .unwrap();
    g.asset_id = intern("hero_blend_graph");
    world.add_component(g);
    world.start(SYSTEMS).unwrap();
    world.step();

    let report = with_anim(&mut world, |anim| anim.graph_report(target).unwrap());
    assert_eq!(report.state, "locomotion");
    assert_eq!(report.blend_weights, Some(vec![1.0, 0.0, 0.0]));

    // Half-way between the walk (1.6) and run (5.0) points.
    with_anim(&mut world, |anim| {
        anim.queue_param(target, "speed", 3.3).unwrap();
    });
    world.step();
    let w = with_anim(&mut world, |anim| anim.graph_report(target).unwrap())
        .blend_weights
        .unwrap();
    assert_eq!(w[0], 0.0);
    assert!(
        (w[1] - 0.5).abs() < 1e-4 && (w[2] - 0.5).abs() < 1e-4,
        "{w:?}"
    );
}

// Writing the `AnimationParams` component (the gameplay surface) drives a
// transition on the next step; writing it back returns to the source state.
#[test]
fn graph_transitions_on_component_write() {
    let mut world = graph_world();
    world.step();

    for p in world.query_mut::<AnimationParams>() {
        p.set(0, 2.0);
    }
    world.step();
    let report = with_anim(&mut world, |anim| anim.graph_report(hero()).unwrap());
    assert_eq!(report.state, "run");

    for p in world.query_mut::<AnimationParams>() {
        p.set(0, 0.0);
    }
    world.step();
    let report = with_anim(&mut world, |anim| anim.graph_report(hero()).unwrap());
    assert_eq!(report.state, "idle");
}

// The `anim-param` path: a queued write lands in the component on the next
// step and the graph reacts to it; unknown names and flat targets fail.
#[test]
fn queued_param_writes_component_and_drives_graph() {
    let mut world = graph_world();
    world.step();

    with_anim(&mut world, |anim| {
        anim.queue_param(hero(), "speed", 3.0).unwrap();
        assert!(
            anim.queue_param(hero(), "nope", 1.0)
                .unwrap_err()
                .contains("no parameter"),
        );
    });
    world.step();

    let params: Vec<&AnimationParams> = world.query::<AnimationParams>().collect();
    assert_eq!(params[0].values, vec![3.0], "write landed in the component");
    let report = with_anim(&mut world, |anim| anim.graph_report(hero()).unwrap());
    assert_eq!(report.state, "run");
}

// Crossfade commands are the flat-bucket surface; a graph target must reject
// them (and point at anim-param), and a flat target must reject param
// commands (and point at anim-crossfade).
#[test]
fn mode_mismatched_commands_are_rejected() {
    let mut world = graph_world();
    world.step();
    with_anim(&mut world, |anim| {
        let err = anim
            .apply_crossfade(hero(), vec![1.0, 0.0], 0.0, 0.0)
            .unwrap_err();
        assert!(err.contains("graph-driven"));
        assert!(err.contains("anim-param"));
    });

    let mut flat_world = World::new();
    let mut a = clip("solo_clip", 1.0);
    a.target = Some(SkinnedMeshHandle(intern("flat_hero").0));
    flat_world.add_component(a);
    flat_world.start(SYSTEMS).unwrap();
    flat_world.step();
    with_anim(&mut flat_world, |anim| {
        let target = SkinnedMeshHandle(intern("flat_hero").0);
        anim.apply_crossfade(target, vec![0.5], 0.0, 0.0).unwrap();
        let err = anim.queue_param(target, "speed", 1.0).unwrap_err();
        assert!(err.contains("anim-crossfade"));
        let err = anim.graph_report(target).unwrap_err();
        assert!(err.contains("no AnimationGraph"));
    });
}

// A clip with a baked root track publishes per-frame `RootMotionEvent` events
// carrying the mesh-local displacement; clips without one stay silent.
#[test]
fn root_motion_clip_publishes_displacement_events() {
    let target = SkinnedMeshHandle(intern("hero_rm").0);
    let mut world = World::new();
    let mut a: Animation = serde_json::from_value(serde_json::json!({
        "target": "hero_rm",
        "duration": 1.0,
        "looping": true,
        "root_motion": true,
        "root_track": [
            {"time": 0.0, "translation": [0.0, 0.0, 0.0]},
            {"time": 1.0, "translation": [2.0, 0.0, 0.0]}
        ],
    }))
    .unwrap();
    a.asset_id = intern("hero_rm_walk");
    world.add_component(a);
    world.start(SYSTEMS).unwrap();

    world.step();
    std::thread::sleep(Duration::from_millis(5));
    world.step();

    let events = world
        .events::<crate::components::RootMotionEvent>()
        .expect("RootMotionEvent queue exists");
    let mut cursor = crate::ecs::EventCursor::default();
    let motions: Vec<_> = events.read(&mut cursor).collect();
    assert!(!motions.is_empty(), "expected displacement events");
    let total: f32 = motions
        .iter()
        .filter(|m| m.target == target)
        .map(|m| m.delta[0])
        .sum();
    assert!(total > 0.0, "walk moves +X: {total}");
    assert!(
        motions
            .iter()
            .all(|m| m.delta[1] == 0.0 && m.delta[2] == 0.0)
    );
}

// Root-motion events for several targets are published in handle order every
// step (the target map iterates ordered), so event consumers see the same
// sequence run to run.
#[test]
fn root_motion_events_emit_in_handle_order() {
    let mut world = World::new();
    let mut handles = Vec::new();
    for name in ["rm_ord_c", "rm_ord_a", "rm_ord_b"] {
        handles.push(SkinnedMeshHandle(intern(name).0));
        let mut a: Animation = serde_json::from_value(serde_json::json!({
            "target": name,
            "duration": 1.0,
            "looping": true,
            "root_motion": true,
            "root_track": [
                {"time": 0.0, "translation": [0.0, 0.0, 0.0]},
                {"time": 1.0, "translation": [2.0, 0.0, 0.0]}
            ],
        }))
        .unwrap();
        a.asset_id = intern(&format!("{name}_clip"));
        world.add_component(a);
    }
    world.start(SYSTEMS).unwrap();

    // The first step has no time delta; the second emits one event per target.
    world.step();
    std::thread::sleep(Duration::from_millis(5));
    world.step();

    let events = world
        .events::<crate::components::RootMotionEvent>()
        .expect("RootMotionEvent queue exists");
    let mut cursor = crate::ecs::EventCursor::default();
    let order: Vec<_> = events.read(&mut cursor).map(|m| m.target).collect();
    assert_eq!(order.len(), handles.len(), "one event per moving target");
    let mut sorted = order.clone();
    sorted.sort();
    assert_eq!(order, sorted, "events are published in handle order");
}

// The full rig chain: a skinned mesh with a capsule + a root-motion clip
// moves its CharacterRig through PhysicsSystem, staying grounded.
// Full IK chain: the graph authors an ik_chain on a three-joint leg whose
// foot hangs over a raised ledge (off to the side of the capsule, which
// stands on the flat floor). Probe rays go out, physics answers them, and
// the solve bends the leg so the foot rests on the ledge instead of
// clipping through it.
#[test]
fn ik_pins_the_foot_to_a_raised_ledge() {
    use crate::gfx::skeleton::{Joint, JointPose, Skeleton};

    let target = SkinnedMeshHandle(intern("hero_ik").0);
    let mut world = World::new();

    // A leg hanging from x = 0.6: hip at y = 2, knee at y = 1, foot at
    // y = 0 (bind). Named joints so the chain resolves.
    let joint = |name: &str, parent: Option<usize>, t: [f32; 3]| Joint {
        name: name.to_string(),
        parent,
        bind: JointPose {
            translation: t,
            ..JointPose::default()
        },
    };
    let skeleton = Skeleton::new(vec![
        joint("hip", None, [0.6, 2.0, 0.0]),
        joint("knee", Some(0), [0.0, -1.0, 0.0]),
        joint("foot", Some(1), [0.0, -1.0, 0.0]),
    ]);
    world.add_component(crate::components::SkeletonPose::new(target, 0, skeleton));
    world.add_component(crate::components::CharacterRig::new(
        target,
        0,
        crate::gfx::transform::IDENTITY,
        0.5,
        0.3,
    ));

    // A constant clip (the bind pose) so the graph has something to play.
    let mut stand: Animation = serde_json::from_value(serde_json::json!({
        "target": "hero_ik",
        "duration": 1.0,
        "looping": true,
        "tracks": [{"joint": 0, "keyframes": [
            {"time": 0.0, "translation": [0.6, 2.0, 0.0]},
            {"time": 1.0, "translation": [0.6, 2.0, 0.0]}
        ]}],
    }))
    .unwrap();
    stand.asset_id = intern("hero_ik_stand");
    world.add_component(stand);

    let mut graph: AnimationGraph = serde_json::from_value(serde_json::json!({
        "target": "hero_ik",
        "states": [{"name": "stand", "clip": "hero_ik_stand"}],
        "ik_chains": [{"joints": ["hip", "knee", "foot"], "pole": [0.0, 0.0, 1.0]}],
    }))
    .unwrap();
    graph.asset_id = intern("hero_ik_graph");
    world.add_component(graph);

    // Flat floor for the capsule; a ledge (top at y = 0.25) under the foot
    // only, clear of the capsule standing at the origin.
    world.add_component(crate::components::PhysicsConfig::default());
    world.add_component(crate::components::Prop {
        asset_id: intern("ledge"),
        position: [0.75, 0.1, 0.0],
        collider: Some(crate::components::PropCollider {
            shape: "cuboid".to_string(),
            half_extents: [0.3, 0.15, 0.3],
            radius: 0.0,
            half_height: 0.0,
            layer: String::new(),
        }),
        ..Default::default()
    });
    world.start(SYSTEMS).unwrap();

    // Ray out -> physics answer -> solve; a few extra steps let the capsule
    // settle onto the floor.
    for _ in 0..8 {
        world.step();
        std::thread::sleep(Duration::from_millis(5));
    }

    let pose = world
        .query::<crate::components::SkeletonPose>()
        .next()
        .expect("pose survives");
    let foot_mesh = {
        let m = pose.joint_matrices[2];
        let b = pose.skeleton.bind_position(2);
        [
            m[0][0] * b[0] + m[1][0] * b[1] + m[2][0] * b[2] + m[3][0],
            m[0][1] * b[0] + m[1][1] * b[1] + m[2][1] * b[2] + m[3][1],
            m[0][2] * b[0] + m[1][2] * b[1] + m[2][2] * b[2] + m[3][2],
        ]
    };
    let rig_y = world
        .query::<crate::components::CharacterRig>()
        .next()
        .unwrap()
        .position[1];
    // The ledge top is at world 0.25; the foot's mesh-space height plus the
    // rig's world height must land there (the animated pose kept it at ~0).
    let foot_world_y = foot_mesh[1] + rig_y;
    assert!(
        (foot_world_y - 0.25).abs() < 0.03,
        "foot pinned to the ledge top: world y = {foot_world_y}"
    );
    // The foot stays put horizontally: pinning only lifts it.
    assert!((foot_mesh[0] - 0.6).abs() < 0.02, "{foot_mesh:?}");
}

#[test]
fn rig_capsule_follows_root_motion() {
    let target = SkinnedMeshHandle(intern("hero_rig").0);
    let mut world = World::new();
    let mut a: Animation = serde_json::from_value(serde_json::json!({
        "target": "hero_rig",
        "duration": 1.0,
        "looping": true,
        "root_motion": true,
        "root_track": [
            {"time": 0.0, "translation": [0.0, 0.0, 0.0]},
            {"time": 1.0, "translation": [2.0, 0.0, 0.0]}
        ],
    }))
    .unwrap();
    a.asset_id = intern("hero_rig_walk");
    world.add_component(a);
    world.add_component(crate::components::PhysicsConfig::default());
    // GraphicsSystem publishes rigs in a rendering world; this headless test
    // seeds one directly before start so PhysicsSystem::init sees it.
    world.add_component(crate::components::CharacterRig::new(
        target,
        0,
        crate::gfx::transform::IDENTITY,
        0.5,
        0.3,
    ));
    world.start(SYSTEMS).unwrap();

    for _ in 0..4 {
        world.step();
        std::thread::sleep(Duration::from_millis(5));
    }

    let rig = world
        .query::<crate::components::CharacterRig>()
        .next()
        .expect("rig survives");
    assert!(
        rig.position[0] > 0.0,
        "capsule advanced along the walk: {:?}",
        rig.position
    );
    assert!(
        rig.moved,
        "render follow flag set (no GraphicsSystem to clear it)"
    );
    assert!(
        rig.position[1] > -0.2,
        "flat floor holds the capsule up: {:?}",
        rig.position
    );
}

// While a menu is open the animation step returns early, so graph clocks and
// transitions freeze with the pose.
#[test]
fn graph_freezes_while_menu_open() {
    let mut world = graph_world();
    world.step();

    world.insert_resource(crate::ecs::MenuActive(true));
    for p in world.query_mut::<AnimationParams>() {
        p.set(0, 2.0);
    }
    world.step();
    let report = with_anim(&mut world, |anim| anim.graph_report(hero()).unwrap());
    assert_eq!(
        report.state, "idle",
        "paused step must not take transitions"
    );

    world.insert_resource(crate::ecs::MenuActive(false));
    world.step();
    let report = with_anim(&mut world, |anim| anim.graph_report(hero()).unwrap());
    assert_eq!(report.state, "run", "resumed step sees the parameter");
}

// A bare runtime clip of a given length, no tracks or root motion. Enough to
// re-seat a bucket slot via `apply_reloaded_clip`.
fn runtime_clip(duration: f32) -> crate::gfx::skeleton::AnimationClip {
    crate::gfx::skeleton::AnimationClip {
        morph_keys: Vec::new(),
        duration,
        looping: true,
        tracks: Vec::new(),
        root: None,
    }
}

// A single flat clip targeting `target`, weight 1.
fn flat_clip(name: &str, target: SkinnedMeshHandle) -> Animation {
    let mut a = clip(name, 1.0);
    a.target = Some(SkinnedMeshHandle(target.0));
    a
}

// A flat bucket accepts a re-imported clip into a valid slot and refuses a bad
// target or an out-of-range slot without mutating anything.
#[test]
fn apply_reloaded_clip_reseats_a_flat_slot_and_rejects_bad_targets() {
    let target = SkinnedMeshHandle(intern("flat_reload").0);
    let mut world = World::new();
    world.add_component(flat_clip("fr_solo", target));
    world.start(SYSTEMS).unwrap();
    world.step();

    with_anim(&mut world, |anim| {
        assert!(
            anim.apply_reloaded_clip(target, 0, runtime_clip(3.0), 0.5),
            "a valid slot accepts the reload"
        );
        assert!(
            !anim.apply_reloaded_clip(
                SkinnedMeshHandle(intern("nobody").0),
                0,
                runtime_clip(1.0),
                1.0
            ),
            "an unknown target is refused"
        );
        assert!(
            !anim.apply_reloaded_clip(target, 9, runtime_clip(1.0), 1.0),
            "an out-of-range slot is refused"
        );
    });
}

// Reloading a clip a graph plays refreshes the state machine's compiled
// duration for that slot; the graph keeps running afterward.
#[test]
fn apply_reloaded_clip_refreshes_graph_clip_duration() {
    let mut world = graph_world();
    world.step();

    let applied = with_anim(&mut world, |anim| {
        anim.apply_reloaded_clip(hero(), 0, runtime_clip(2.5), 1.0)
    });
    assert!(applied, "the graph bucket's idle slot reloads");
    // The refresh path ran without disturbing the running graph.
    world.step();
    let report = with_anim(&mut world, |anim| anim.graph_report(hero()).unwrap());
    assert_eq!(report.state, "idle");
}

// With hot-reload off (no `cn debug`) and inline clips, the reload catalogue
// is empty: the getter returns an empty slice.
#[test]
fn reload_entries_is_empty_without_captured_sources() {
    let mut world = graph_world();
    world.step();
    let count = with_anim(&mut world, |anim| anim.reload_entries().len());
    assert_eq!(count, 0);
}

// The Debug impl summarizes the bucket and reload-catalogue counts rather than
// dumping their contents.
#[test]
fn debug_impl_summarizes_target_and_reload_counts() {
    let mut world = graph_world();
    world.step();
    let text = with_anim(&mut world, |anim| format!("{anim:?}"));
    assert!(text.contains("AnimationSystem"), "{text}");
    assert!(text.contains("targets: 1"), "{text}");
    assert!(text.contains("reload_entries: 0"), "{text}");
}

// A one-joint pose for `target`, used to observe the flat sampling arms.
fn single_joint_pose(target: SkinnedMeshHandle) -> crate::components::SkeletonPose {
    use crate::gfx::skeleton::{Joint, JointPose, Skeleton};
    let skeleton = Skeleton::new(vec![Joint {
        name: "root".to_string(),
        parent: None,
        bind: JointPose::default(),
    }]);
    crate::components::SkeletonPose::new(target, 0, skeleton)
}

// One flat clip drives the single-clip sampling arm: the pose gets one skinning
// matrix per joint, at full strength regardless of the clip's weight.
#[test]
fn flat_single_clip_samples_the_pose() {
    let target = SkinnedMeshHandle(intern("flat_single_pose").0);
    let mut world = World::new();
    world.add_component(flat_clip("fs_solo", target));
    world.add_component(single_joint_pose(target));
    world.start(SYSTEMS).unwrap();
    world.step();

    let matrices = world
        .query::<crate::components::SkeletonPose>()
        .next()
        .map(|p| p.joint_matrices.len())
        .unwrap();
    assert_eq!(matrices, 1, "one skinning matrix for the one joint");
}

// Two flat clips with a fade-in drive the startup ramp and the multi-clip
// weighted-blend arm: the fade transition anchors and advances on the first
// steps and the blended pose is written every frame.
#[test]
fn flat_fade_in_blends_multiple_clips_into_the_pose() {
    let target = SkinnedMeshHandle(intern("flat_blend_pose").0);
    let mut world = World::new();
    // One clip requests a fade-in, so init builds a startup weight ramp.
    let mut faded = flat_clip("fb_a", target);
    faded.fade_in_secs = 0.5;
    world.add_component(faded);
    world.add_component(flat_clip("fb_b", target));
    world.add_component(single_joint_pose(target));
    world.start(SYSTEMS).unwrap();
    // First step anchors the fade ramp; second advances it further. Both run
    // the multi-clip blend arm and write the pose.
    world.step();
    world.step();

    let matrices = world
        .query::<crate::components::SkeletonPose>()
        .next()
        .map(|p| p.joint_matrices.len())
        .unwrap();
    assert_eq!(matrices, 1, "the weighted blend produced a pose");
}

// A pose's static morph base layer composes with a clip's morph track: the
// clip weights are added onto the base and clamped, and a clip without a
// morph track leaves the base layer uploaded as-is.
#[test]
fn morph_base_layer_composes_with_clip_morph_tracks() {
    use crate::components::MorphKey;
    use crate::gfx::proportions::ProportionLayer;

    let target = SkinnedMeshHandle(intern("morph_base_pose").0);
    let mut world = World::new();
    let mut a = flat_clip("mb_clip", target);
    a.morph_track = vec![
        MorphKey {
            time: 0.0,
            weights: vec![0.3, 0.9],
        },
        MorphKey {
            time: 1.0,
            weights: vec![0.3, 0.9],
        },
    ];
    world.add_component(a);
    world.add_component(
        single_joint_pose(target).with_shape(vec![0.5, 0.5], ProportionLayer::default()),
    );
    world.start(SYSTEMS).unwrap();
    world.step();
    let weights = world
        .query::<crate::components::SkeletonPose>()
        .next()
        .map(|p| p.morph_weights.clone())
        .unwrap();
    assert!((weights[0] - 0.8).abs() < 1e-5, "{weights:?}");
    assert_eq!(weights[1], 1.0, "base + clip clamps at 1");

    // Without a morph track, the base layer stays in place.
    let target = SkinnedMeshHandle(intern("morph_base_only").0);
    let mut world = World::new();
    world.add_component(flat_clip("mb_plain", target));
    world.add_component(
        single_joint_pose(target).with_shape(vec![0.25], ProportionLayer::default()),
    );
    world.start(SYSTEMS).unwrap();
    world.step();
    let pose = world
        .query::<crate::components::SkeletonPose>()
        .next()
        .unwrap();
    assert_eq!(pose.morph_weights, [0.25]);
    assert!(pose.updated);
}

// The proportion layer re-shapes every sampled pose: a scaled root shows up in
// the skinning matrix the clip writes each frame.
#[test]
fn proportions_apply_to_the_sampled_pose() {
    use crate::components::JointProportion;
    use crate::gfx::proportions::ProportionLayer;

    let target = SkinnedMeshHandle(intern("proportioned_pose").0);
    let mut world = World::new();
    world.add_component(flat_clip("pp_clip", target));
    let pose = single_joint_pose(target);
    let layer = ProportionLayer::resolve(
        &pose.skeleton,
        &[JointProportion {
            joint: "root".into(),
            scale: 3.0,
            length: 0.0,
        }],
    );
    world.add_component(pose.with_shape(Vec::new(), layer));
    world.start(SYSTEMS).unwrap();
    world.step();
    let pose = world
        .query::<crate::components::SkeletonPose>()
        .next()
        .unwrap();
    assert_eq!(pose.joint_matrices[0][0][0], 3.0);
}