pinch-points 0.8.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
//! Sound effects, driven by the [`SimEvent`] stream (one observer diffs the
//! sim; this module just maps events to one-shots and rumble). Win/lose
//! stingers hook the puzzle phase transitions; denied placements arrive on
//! their own message from the input layer.
//!
//! Anything that happens *somewhere* on the beach is panned to that side of
//! the stereo field ([`pan_pos`]); banners and stingers, which belong to the
//! whole round rather than a tile, stay centred.
//!
//! Three things can silence the game, and they compose rather than fight:
//! the two settings switches (music and effects, each with its own volume
//! underneath), the master mute on M ([`Muted`]), and the pause card, which
//! puts the music down for as long as it is up. Everything reads them
//! through [`sfx_gain`] and [`music_audible`], so no sink is left holding
//! an opinion of its own.

use crate::app::sim_events::SimEvent;
use crate::app::{PlacementDenied, Screen, Sim};
use bevy::audio::{SpatialListener, SpatialScale, Volume};
use bevy::input::gamepad::{GamepadRumbleIntensity, GamepadRumbleRequest};
use bevy::prelude::*;
use std::time::Duration;

/// The background theme entity, and which set it was drawn from.
#[derive(Component)]
pub struct Music(Mood);

/// Which of the two sets of tracks a screen plays.
///
/// Players loved the dance tracks and wanted them where the game is fast:
/// a versus round gets the drums, and everywhere a player sits and thinks
/// (the menus, the puzzles, the editor) keeps the calmer tracks.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mood {
    Calm,
    Battle,
}

impl Mood {
    /// The set this screen plays. The interlude between the rounds of a
    /// series is still the battle, so a track is not cut off by it.
    pub fn of(screen: Screen) -> Mood {
        match screen {
            Screen::Versus | Screen::Interlude => Mood::Battle,
            Screen::Menu
            | Screen::Puzzle
            | Screen::Editor
            | Screen::Lobby
            | Screen::Settings
            | Screen::Controls
            | Screen::MatchSetup
            | Screen::Achievements
            | Screen::StageSelect
            | Screen::Replays
            | Screen::Language
            | Screen::NewVersion => Mood::Calm,
        }
    }

    /// How long the beach goes quiet between two tracks, seconds.
    ///
    /// Calm rests are longer than most of the tracks themselves, on
    /// purpose: the rest is what lets a short playlist last a session
    /// without wearing thin. A battle only takes a breath: a round is a
    /// few minutes long, and a minute of it in silence is a round without
    /// its music.
    fn rest_secs(self) -> std::ops::Range<f32> {
        match self {
            Mood::Calm => 30.0..90.0,
            Mood::Battle => 3.0..6.0,
        }
    }
}

/// A track on its way out because the screen changed sets: it fades over
/// [`FADE_SECS`] under the new one and then goes. Seconds left.
#[derive(Component)]
pub struct FadingOut(f32);

/// How long a track takes to fade out when the set changes under it.
const FADE_SECS: f32 = 0.8;

/// The master mute on M: everything off, now, without touching what the
/// player has set.
///
/// Deliberately not a setting. The two switches on the settings card are
/// preferences and are written to disk; this is the key you hit when
/// somebody walks in, and the game comes back the way you left it. So
/// unmuting restores the settings, which may still say off.
#[derive(Resource, Default)]
pub struct Muted(pub bool);

/// Effects gain right now: the settings switch and slider, with the master
/// mute able to veto. Zero means nothing is spawned at all.
pub(crate) fn sfx_gain(settings: &crate::app::settings::GameSettings, muted: &Muted) -> f32 {
    if muted.0 { 0.0 } else { settings.sfx_gain() }
}

/// The three voices [`music_audible`] hears.
#[derive(bevy::ecs::system::SystemParam)]
pub struct Loudness<'w> {
    settings: Res<'w, crate::app::settings::GameSettings>,
    muted: Res<'w, Muted>,
    menu: Res<'w, crate::app::pause::PauseMenu>,
}

/// Whether the theme should be audible this frame. The pause card is the
/// third voice here, and the one that is not a player preference: it holds
/// the music down for as long as it is up and gives back exactly that.
///
/// Derived from all three every frame rather than pushed at the sink, so
/// nothing has to remember whether a silence is its to lift.
fn music_audible(
    settings: &crate::app::settings::GameSettings,
    muted: &Muted,
    card_open: bool,
) -> bool {
    settings.music_gain() > 0.0 && !muted.0 && !card_open
}

#[derive(Resource, Default)]
pub struct Sounds {
    place: Handle<AudioSource>,
    remove: Handle<AudioSource>,
    bank: Handle<AudioSource>,
    eat: Handle<AudioSource>,
    raid: Handle<AudioSource>,
    win: Handle<AudioSource>,
    lose: Handle<AudioSource>,
    takeoff: Handle<AudioSource>,
    screech: Handle<AudioSource>,
    event: Handle<AudioSource>,
    golden: Handle<AudioSource>,
    tier: Handle<AudioSource>,
    surge: Handle<AudioSource>,
    horn: Handle<AudioSource>,
    denied: Handle<AudioSource>,
    evict: Handle<AudioSource>,
}

/// The background playlist; a track spawns, plays once, despawns, and
/// after a rest `rotate_music` starts another from the set the screen asks
/// for ([`Mood`]).
///
/// Players called the music repetitive, and it was: seven short loops,
/// two and a half minutes in all, back to back in a fixed order that
/// opened every launch on the same track. So each set is a shuffle bag
/// (every track once before any comes round again, never the same one
/// twice running, a different one first each launch), between tracks the
/// beach goes quiet for a while, and longer tracks joined them.
#[derive(Resource)]
pub struct MusicPlaylist {
    calm: Shelf,
    battle: Shelf,
    rest: Rest,
    rng: crate::app::effects::VisualRng,
}

/// One set's tracks and its shuffle bag.
struct Shelf {
    tracks: Vec<Handle<AudioSource>>,
    /// What is left to play this time round, drawn from the back.
    bag: Vec<usize>,
    /// The track drawn last, which the next refill must not open with.
    last: Option<usize>,
}

/// Where the playlist is between two tracks, and for which set.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Rest {
    /// Nothing has played yet: the first track starts without a wait.
    Due,
    /// A track is alive, playing or held down.
    Playing(Mood),
    /// Seconds of quiet left before the next track.
    Waiting(Mood, f32),
}

impl Shelf {
    fn new(tracks: Vec<Handle<AudioSource>>) -> Self {
        Shelf {
            tracks,
            bag: Vec::new(),
            last: None,
        }
    }

    /// The next track to play, from a bag refilled and shuffled whenever it
    /// runs dry.
    fn draw(&mut self, rng: &mut crate::app::effects::VisualRng) -> usize {
        if self.bag.is_empty() {
            self.bag = (0..self.tracks.len()).collect();
            for i in (1..self.bag.len()).rev() {
                // The high bits: an LCG's low bits cycle with short periods.
                let j = (rng.next() >> 16) as usize % (i + 1);
                self.bag.swap(i, j);
            }
            // The last of one round and the first of the next would
            // otherwise be the same song twice, one rest apart.
            if self.bag.len() > 1 && self.bag.last() == self.last.as_ref() {
                let end = self.bag.len() - 1;
                self.bag.swap(0, end);
            }
        }
        let track = self.bag.pop().unwrap_or(0);
        self.last = Some(track);
        track
    }
}

impl MusicPlaylist {
    fn new(
        calm: Vec<Handle<AudioSource>>,
        battle: Vec<Handle<AudioSource>>,
        rng: crate::app::effects::VisualRng,
    ) -> Self {
        MusicPlaylist {
            calm: Shelf::new(calm),
            battle: Shelf::new(battle),
            rest: Rest::Due,
            rng,
        }
    }

    /// The next track from `mood`'s set.
    fn draw(&mut self, mood: Mood) -> Handle<AudioSource> {
        let MusicPlaylist {
            calm, battle, rng, ..
        } = self;
        let shelf = match mood {
            Mood::Calm => calm,
            Mood::Battle => battle,
        };
        let index = shelf.draw(rng);
        shelf.tracks[index].clone()
    }
}

/// How far, in listener units, the edge of the board sits from the centre
/// of the stereo field. Small on purpose: rodio only attenuates by distance
/// beyond one unit, so keeping the whole beach inside that radius leaves
/// panning as the only thing that varies.
const PAN_WIDTH: f32 = 0.5;
/// Distance between the listener's ears, same units.
const EAR_GAP: f32 = 0.3;
/// A panned one-shot's two channels sum to less than a centred one's, so
/// positional sounds get a lift to sit level with the stingers.
const SPATIAL_GAIN: f32 = 1.4;

/// Whether a post going down at `owner`'s hand is one to be heard here.
///
/// `seated_here` reads correctly wherever this machine answers for a seat:
/// alone in a puzzle it is your seat, at a table every human seat sharing
/// the speaker, online your seat and nobody else's.
///
/// Where this machine answers for *no* seat it says "nobody" and means it.
/// An online spectator and a replay both spawn no cursor at all (see
/// `cursor::spawn_versus_cursors`), so every post on the beach fell silent
/// while the banks, the gulls and the horn played on. A machine holding no
/// seat is watching, and a watcher hears the whole beach.
pub(crate) fn post_is_heard(cursors: &Query<&crate::app::cursor::Cursor>, owner: u8) -> bool {
    cursors.is_empty() || crate::app::cursor::seated_here(cursors, owner)
}

/// Where a board position lands in the listener's little stereo field.
///
/// The x is mirrored: rodio's spatial mixer boosts the ear *further* from
/// the emitter, so without the flip a raid on the left of the beach would
/// come out of the right speaker.
pub(crate) fn pan_pos(half_width: f32, pos: Vec2) -> Vec3 {
    let x = (pos.x / half_width.max(1.0)).clamp(-1.0, 1.0);
    Vec3::new(-x * PAN_WIDTH, 0.0, 0.0)
}

pub fn load_sounds(mut commands: Commands, assets: Res<AssetServer>) {
    // One listener, parked at the origin; emitters are placed relative to it
    // by `pan_pos` rather than at their true board positions, so the camera
    // zooming or sliding never changes how the beach sounds.
    commands.spawn(SpatialListener::new(EAR_GAP));
    commands.insert_resource(MusicPlaylist::new(
        // Calm: the menus, the puzzles and the editor.
        vec![
            // theme.wav predates the sound generator and has no source to
            // re-encode from; the generated loops ship as OGG. It was also
            // mixed 10 dB hotter than the rest and has been turned down to
            // their -23 dB, so it no longer jumps out of the shuffle.
            assets.load("sounds/theme.wav"),
            assets.load("sounds/theme_b.ogg"),
            assets.load("sounds/theme_c.ogg"),
            assets.load("sounds/theme_d.ogg"),
            assets.load("sounds/theme_e.ogg"),
            assets.load("sounds/theme_f.ogg"),
            assets.load("sounds/theme_g.ogg"),
            // The soft three, twice as long and gentler on the ear.
            assets.load("sounds/theme_h.ogg"),
            assets.load("sounds/theme_i.ogg"),
            assets.load("sounds/theme_j.ogg"),
        ],
        // Battle: the dance tracks, drums and a pumping bass, for versus.
        vec![
            assets.load("sounds/theme_k.ogg"),
            assets.load("sounds/theme_l.ogg"),
            assets.load("sounds/theme_m.ogg"),
            assets.load("sounds/theme_n.ogg"),
            assets.load("sounds/theme_o.ogg"),
            assets.load("sounds/theme_p.ogg"),
        ],
        crate::app::effects::VisualRng::from_clock(),
    ));
    commands.insert_resource(Sounds {
        place: assets.load("sounds/place.wav"),
        remove: assets.load("sounds/remove.wav"),
        bank: assets.load("sounds/bank.wav"),
        eat: assets.load("sounds/eat.wav"),
        raid: assets.load("sounds/raid.wav"),
        win: assets.load("sounds/win.wav"),
        lose: assets.load("sounds/lose.wav"),
        takeoff: assets.load("sounds/takeoff.wav"),
        screech: assets.load("sounds/screech.wav"),
        event: assets.load("sounds/event.wav"),
        golden: assets.load("sounds/golden.wav"),
        tier: assets.load("sounds/tier.wav"),
        surge: assets.load("sounds/surge.wav"),
        horn: assets.load("sounds/horn.wav"),
        denied: assets.load("sounds/denied.wav"),
        evict: assets.load("sounds/evict.wav"),
    });
}

/// A one-shot at the given gain, centred in the stereo field. A gain of
/// zero (the slider at the bottom) spawns nothing at all.
fn play(commands: &mut Commands, sound: &Handle<AudioSource>, gain: f32) {
    if gain <= 0.0 {
        return;
    }
    commands.spawn((
        AudioPlayer::new(sound.clone()),
        PlaybackSettings {
            volume: Volume::Linear(gain),
            ..PlaybackSettings::DESPAWN
        },
    ));
}

/// A one-shot panned to a spot in the listener's field (see [`pan_pos`]).
fn play_at(commands: &mut Commands, sound: &Handle<AudioSource>, gain: f32, at: Vec3) {
    if gain <= 0.0 {
        return;
    }
    commands.spawn((
        AudioPlayer::new(sound.clone()),
        PlaybackSettings {
            volume: Volume::Linear(gain * SPATIAL_GAIN),
            spatial: true,
            spatial_scale: Some(SpatialScale::new_2d(1.0)),
            ..PlaybackSettings::DESPAWN
        },
        Transform::from_translation(at),
    ));
}

/// A panned one-shot that sounds at most once a frame: `used` is the
/// caller's "already played this one" flag, and the first call through it
/// wins.
///
/// The sim reports per tile and per crab, so one frame can hold a great
/// many of a kind: every seat may act on the same tick, posts placed
/// together wear out together, and a castle can take a whole stream of
/// crabs at once. Sample-aligned copies do not read as several things
/// happening, they read as one louder, dirtier version of it, and four at
/// full gain clip.
///
/// What `used` counts is the caller's to choose, and it is the axis a
/// listener could tell apart: one flag for all the posts, since they knock
/// alike wherever they are, and one per seat for banks, since each seat's
/// crabs arrive at its own castle and pan to its own side of the beach.
fn once(
    commands: &mut Commands,
    used: &mut bool,
    sound: &Handle<AudioSource>,
    gain: f32,
    at: Vec3,
) {
    if !std::mem::replace(used, true) {
        play_at(commands, sound, gain, at);
    }
}

/// What playing a one-shot takes: somewhere to spawn it, the sounds, and
/// how loud the player wants them (see [`sfx_gain`]).
#[derive(bevy::ecs::system::SystemParam)]
pub struct Speaker<'w, 's> {
    commands: Commands<'w, 's>,
    sounds: Res<'w, Sounds>,
    settings: Res<'w, crate::app::settings::GameSettings>,
    muted: Res<'w, Muted>,
}

/// The pads plugged in, and the requests that shake them.
#[derive(bevy::ecs::system::SystemParam)]
pub struct Rumble<'w, 's> {
    pads: Query<'w, 's, Entity, With<Gamepad>>,
    requests: MessageWriter<'w, GamepadRumbleRequest>,
}

/// Map each sim event to its one-shot (and rumble where it matters).
pub fn play_events(
    speaker: Speaker,
    mut events: MessageReader<SimEvent>,
    screen: Res<State<Screen>>,
    sim: Res<Sim>,
    cursors: Query<&crate::app::cursor::Cursor>,
    rumble: Rumble,
) {
    let Speaker {
        mut commands,
        sounds,
        settings,
        muted,
    } = speaker;
    let Rumble {
        pads,
        requests: mut rumble,
    } = rumble;
    // The whole table's knocks, felt by whoever holds a pad here, which
    // is nobody while a replay or someone else's match is watched: no
    // cursor, no hands on the beach.
    let hands_here = !cursors.is_empty();
    let mut buzz = |ms: u64, strength: f32| {
        if !settings.rumble || !hands_here {
            return;
        }
        for gamepad in &pads {
            rumble.write(GamepadRumbleRequest::Add {
                duration: Duration::from_millis(ms),
                intensity: GamepadRumbleIntensity::strong_motor(strength),
                gamepad,
            });
        }
    };
    let gain = sfx_gain(&settings, &muted);
    let half_width = f32::from(sim.0.width()) * crate::app::layout::TILE / 2.0;
    let pan = |pos: &Vec2| pan_pos(half_width, *pos);
    let (mut placed, mut removed, mut evicted) = (false, false, false);
    // Banks are the busiest thing on the beach, and the one cue the sim
    // raises per crab rather than per act: twelve six-seat rounds of bots
    // put eight into one castle on a single tick.
    //
    // Per seat rather than one flag for the lot, because unlike posts these
    // are distinguishable: a seat's crabs walk into that seat's castle, so
    // six castles filling at once still read as six.
    let mut banked = [false; crate::sim::MAX_PLAYERS];
    let mut goldened = [false; crate::sim::MAX_PLAYERS];
    for event in events.read() {
        match event {
            SimEvent::CrabBanked {
                owner, kind, pos, ..
            } => {
                let seat = usize::from(*owner);
                let at = pan(pos);
                if let Some(used) = banked.get_mut(seat) {
                    once(&mut commands, used, &sounds.bank, gain, at);
                }
                if *kind == crate::sim::CrabKind::Golden
                    && let Some(used) = goldened.get_mut(seat)
                {
                    once(&mut commands, used, &sounds.golden, gain, at);
                }
            }
            SimEvent::CrabEaten { pos } => play_at(&mut commands, &sounds.eat, gain, pan(pos)),
            // No buzz here: a raid happens to *one* seat, and
            // `gamepad::rumble_on_raid` puts it in that seat's own hands.
            // Buzzing every pad in the room told five other players that
            // something had happened to them when nothing had.
            SimEvent::CastleRaided { pos, .. } => {
                play_at(&mut commands, &sounds.raid, gain, pan(pos));
            }
            SimEvent::GullArrived => play(&mut commands, &sounds.screech, gain),
            SimEvent::GullTookOff => play(&mut commands, &sounds.takeoff, gain),
            // The wingbeat of a bird leaving, from where it leaves: not the
            // raid's crash, which is the sound of losing something.
            SimEvent::GullShooed { pos, .. } | SimEvent::GullFlewOff { pos } => {
                play_at(&mut commands, &sounds.takeoff, gain, pan(pos));
            }
            // Only your own posts knock: the bots place far more often
            // than the players do, and online this was announcing arrows
            // that went down in somebody else's room. Unless nobody here
            // holds a seat, which is what watching is: see `post_is_heard`.
            SimEvent::SignpostPlaced { owner, pos } => {
                if post_is_heard(&cursors, *owner) {
                    once(&mut commands, &mut placed, &sounds.place, gain, pan(pos));
                }
            }
            // The other end of the same rule. In versus a post wears out
            // on its own, so ungated every bot post knocks on the way out.
            SimEvent::SignpostRemoved { owner, pos } => {
                if post_is_heard(&cursors, *owner) {
                    once(&mut commands, &mut removed, &sounds.remove, gain, pan(pos));
                }
            }
            // Its own sample, not the denial knock: a fourth post at the
            // cap is a placement that *worked*, and answering it with the
            // sound of a refusal told the player the opposite of what
            // happened. The placement sounds too, from the new tile.
            SimEvent::SignpostEvicted { owner, pos, .. } => {
                // The third end of the same rule. `CapPolicy` defaults to
                // `Evict` in versus, so every bot placement past the cap
                // raises one of these.
                if post_is_heard(&cursors, *owner) {
                    once(&mut commands, &mut evicted, &sounds.evict, gain, pan(pos));
                }
            }
            SimEvent::TierUp { .. } => play(&mut commands, &sounds.tier, gain),
            SimEvent::TideEventFired { .. } => play(&mut commands, &sounds.event, gain),
            SimEvent::LureStarted { .. } => {}
            // The chime a golden crab banks with, from the hole it will
            // come out of: the sound of the prize, before it is anyone's.
            SimEvent::GoldenCalled { pos } => {
                play_at(&mut commands, &sounds.golden, gain, pan(pos));
            }
            // And again as it comes out, with the event sting under it so
            // the arrival is not mistaken for another call.
            SimEvent::GoldenOut { pos } => {
                play_at(&mut commands, &sounds.golden, gain, pan(pos));
                play_at(&mut commands, &sounds.event, gain * 0.6, pan(pos));
            }
            SimEvent::SurgeStarted => {
                play(&mut commands, &sounds.surge, gain);
                buzz(300, 0.4);
            }
            SimEvent::RoundEnded => {
                // The horn calls the tide in versus; puzzle endings have
                // their own win/lose stingers.
                if *screen.get() == Screen::Versus {
                    play(&mut commands, &sounds.horn, gain);
                    buzz(500, 0.5);
                }
            }
            SimEvent::CrabSpawned { .. }
            | SimEvent::GullLanded { .. }
            | SimEvent::WheelLocked { .. } => {}
        }
    }
}

/// The puzzle's win stinger. Versus ends on the horn instead, which is why
/// this is gated at all; the gate is the schedule's `in_state`, as it is
/// for every other system in the same phase transition.
pub fn play_win(
    mut commands: Commands,
    sounds: Res<Sounds>,
    settings: Res<crate::app::settings::GameSettings>,
    muted: Res<Muted>,
) {
    play(&mut commands, &sounds.win, sfx_gain(&settings, &muted));
}

/// The puzzle's lose stinger; gated like [`play_win`].
pub fn play_lose(
    mut commands: Commands,
    sounds: Res<Sounds>,
    settings: Res<crate::app::settings::GameSettings>,
    muted: Res<Muted>,
) {
    play(&mut commands, &sounds.lose, sfx_gain(&settings, &muted));
}

/// One dull knock per frame with at least one rejected placement.
pub fn play_denied(
    mut commands: Commands,
    mut denials: MessageReader<PlacementDenied>,
    sounds: Res<Sounds>,
    settings: Res<crate::app::settings::GameSettings>,
    muted: Res<Muted>,
) {
    let any = denials.read().next().is_some();
    denials.clear();
    if any {
        play(&mut commands, &sounds.denied, sfx_gain(&settings, &muted));
    }
}

/// A bright unlock chime (the tier fanfare doing double duty).
pub fn play_chime(commands: &mut Commands, sounds: &Sounds, gain: f32) {
    play(commands, &sounds.tier, gain);
}

/// Which set of music this moment wants, if any.
///
/// None once a versus round is over: the results card is where the win
/// fanfare plays and the awards are read out, and a dance track carrying
/// on under them buried both. The next round of a series brings it back.
fn wanted(screen: Screen, phase: crate::app::VersusPhase) -> Option<Mood> {
    match (screen, phase) {
        (Screen::Versus, crate::app::VersusPhase::Over) => None,
        (screen, _) => Some(Mood::of(screen)),
    }
}

/// Keep the playlist rolling: when a track ends, rest, then start the next
/// from the set this screen plays.
///
/// A track that is merely down - muted, paused, switched off - is still
/// alive and still here, so it is the same song that comes back, from
/// where it left off. Nothing new is started while none of it would be
/// audible, which is what keeps a silenced game from decoding a playlist
/// nobody is listening to, and the rest only counts down while the music
/// could be heard: a pause card does not eat it.
///
/// When the screen changes sets, the track from the other one fades out
/// and one from this set starts at once, rest or no rest: a round opening
/// on a lull is a round opening without its music.
///
/// When a versus round is over the playing track fades and nothing takes
/// its place (see [`wanted`]).
pub fn rotate_music(
    mut commands: Commands,
    mut playlist: ResMut<MusicPlaylist>,
    loudness: Loudness,
    screen: Res<State<Screen>>,
    phase: Res<State<crate::app::VersusPhase>>,
    time: Res<Time>,
    playing: Query<(Entity, &Music), Without<FadingOut>>,
) {
    let Loudness {
        settings,
        muted,
        menu,
    } = loudness;
    let mood = wanted(*screen.get(), *phase.get());
    let mut live = false;
    for (entity, music) in &playing {
        if Some(music.0) == mood {
            live = true;
        } else {
            commands.entity(entity).try_insert(FadingOut(FADE_SECS));
        }
    }
    let Some(mood) = mood else {
        // Quiet until something wants music again, which then starts at
        // once rather than after a rest: the next round of a series should
        // open on its music, as the first one did.
        playlist.rest = Rest::Due;
        return;
    };
    if live {
        playlist.rest = Rest::Playing(mood);
        return;
    }
    if !music_audible(&settings, &muted, menu.stops_the_round()) {
        return;
    }
    match playlist.rest {
        Rest::Playing(was) if was == mood => {
            let rest = mood.rest_secs();
            let secs = playlist.rng.range(rest.start, rest.end);
            playlist.rest = Rest::Waiting(mood, secs);
            return;
        }
        Rest::Waiting(was, left) if was == mood => {
            let left = left - time.delta_secs();
            if left > 0.0 {
                playlist.rest = Rest::Waiting(mood, left);
                return;
            }
        }
        // Nothing yet, or the other set was playing or resting.
        Rest::Due | Rest::Playing(_) | Rest::Waiting(..) => {}
    }
    let track = playlist.draw(mood);
    playlist.rest = Rest::Playing(mood);
    commands.spawn((
        Music(mood),
        AudioPlayer::new(track),
        PlaybackSettings {
            volume: Volume::Linear(settings.music_gain()),
            ..PlaybackSettings::DESPAWN
        },
    ));
}

/// Take a track that is leaving down to nothing, then away.
///
/// Counted without a sink too: a track faded before its audio had started
/// has no sink to turn down, and must still go.
pub fn fade_music(
    mut commands: Commands,
    settings: Res<crate::app::settings::GameSettings>,
    time: Res<Time>,
    mut fading: Query<(Entity, &mut FadingOut, Option<&mut AudioSink>)>,
) {
    for (entity, mut fade, sink) in &mut fading {
        fade.0 -= time.delta_secs();
        if fade.0 <= 0.0 {
            commands.entity(entity).try_despawn();
        } else if let Some(mut sink) = sink {
            sink.set_volume(Volume::Linear(settings.music_gain() * fade.0 / FADE_SECS));
        }
    }
}

/// M mutes the game: the cap that says M, on whatever keyboard this is.
///
/// The master mute: the effects go quiet with the music, since the beach
/// is noisier than the theme is. Works while the pause card is up, the two
/// no longer touching the same sink, and is held off only while a name or
/// a chat line is being typed, where M is a letter.
pub fn toggle_mute(
    keys: Res<ButtonInput<KeyCode>>,
    caps: Res<crate::app::keycaps::KeyCaps>,
    mut muted: ResMut<Muted>,
) {
    if caps.just_pressed(&keys, 'M') {
        muted.0 = !muted.0;
    }
}

/// Hold the theme's sink to whatever [`music_audible`] says this frame.
///
/// The pause card is one of the three voices in that answer, rather than
/// something that reaches in and pauses on its own. It is also the signal
/// rather than [`crate::app::Paused`], because that flag is an offline
/// one: an online pause deliberately leaves the ticker running so the
/// network pump can carry the resume, and the beach there is held still by
/// the lockstep instead. The card is open in both.
pub fn drive_music(
    settings: Res<crate::app::settings::GameSettings>,
    muted: Res<Muted>,
    menu: Res<crate::app::pause::PauseMenu>,
    sinks: Query<&AudioSink, With<Music>>,
) {
    let audible = music_audible(&settings, &muted, menu.stops_the_round());
    for sink in &sinks {
        // Only when the sink disagrees with the answer: this runs every
        // frame, and the theme is the one sound that is always there.
        if audible && sink.is_paused() {
            sink.play();
        } else if !audible && !sink.is_paused() {
            sink.pause();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::cursor::Cursor;
    use crate::app::effects::VisualRng;
    use crate::app::settings::GameSettings;
    use crate::sim::classic_arena;

    /// Between the rounds of a series the music plays on: only the results
    /// card is quiet, and the interlude that follows it is the battle set,
    /// whatever phase the round it came from was left in.
    #[test]
    fn the_series_interlude_keeps_its_music() {
        use crate::app::VersusPhase;
        for phase in [VersusPhase::Running, VersusPhase::Over] {
            assert_eq!(
                wanted(Screen::Interlude, phase),
                Some(Mood::Battle),
                "{phase:?}"
            );
        }
    }

    /// The results card is quiet: once a versus round is over, the track
    /// that played it out fades and no other starts, while every other
    /// moment, the round itself included, still wants its set.
    #[test]
    fn the_music_stops_when_a_versus_round_is_over() {
        use crate::app::VersusPhase;
        assert_eq!(wanted(Screen::Versus, VersusPhase::Over), None);
        assert_eq!(
            wanted(Screen::Versus, VersusPhase::Running),
            Some(Mood::Battle)
        );
        // A phase left over from the last round means nothing off the beach.
        assert_eq!(wanted(Screen::Menu, VersusPhase::Over), Some(Mood::Calm));

        let mut app = App::new();
        app.insert_resource(MusicPlaylist::new(
            vec![Handle::default()],
            vec![Handle::default()],
            VisualRng::default(),
        ));
        app.insert_resource(GameSettings::default());
        app.init_resource::<Muted>();
        app.init_resource::<crate::app::pause::PauseMenu>();
        app.insert_resource(State::new(Screen::Versus));
        app.insert_resource(State::new(VersusPhase::Over));
        app.init_resource::<Time>();
        app.add_systems(Update, rotate_music);
        let track = app.world_mut().spawn(Music(Mood::Battle)).id();
        app.update();
        assert!(
            app.world().get::<FadingOut>(track).is_some(),
            "the round's track fades out"
        );
        let mut music = app.world_mut().query::<&Music>();
        assert_eq!(
            music.iter(app.world()).count(),
            1,
            "and nothing starts in its place"
        );
    }

    /// A beach with `humans` seats answered for at this machine. Bots and
    /// rivals down a wire are exactly the seats with no cursor, which is
    /// how they are spelled here: seats `humans..` have none.
    fn table(humans: u8) -> App {
        let mut app = App::new();
        app.add_plugins(bevy::state::app::StatesPlugin);
        app.init_state::<Screen>();
        app.insert_resource(State::new(Screen::Versus));
        app.insert_resource(Sim(classic_arena(false, 6)));
        app.insert_resource(GameSettings::default());
        app.insert_resource(Muted(false));
        app.insert_resource(Sounds::default());
        app.add_message::<SimEvent>();
        app.add_message::<GamepadRumbleRequest>();
        for seat in 0..humans {
            app.world_mut().spawn(Cursor::seated(seat));
        }
        app.add_systems(Update, play_events);
        app
    }

    /// Everything `events` sets off on one frame, counted, with the stage
    /// swept clear for the next call.
    ///
    /// Every test below is some version of "how many sounds did that
    /// make": write, update, count, despawn.
    fn heard(app: &mut App, events: impl IntoIterator<Item = SimEvent>) -> usize {
        for event in events {
            app.world_mut().write_message(event);
        }
        app.update();
        let live: Vec<Entity> = app
            .world_mut()
            .query_filtered::<Entity, With<AudioPlayer>>()
            .iter(app.world())
            .collect();
        let played = live.len();
        for entity in live {
            app.world_mut().entity_mut(entity).despawn();
        }
        played
    }

    fn placed(owner: u8) -> SimEvent {
        SimEvent::SignpostPlaced {
            owner,
            pos: Vec2::ZERO,
        }
    }

    /// A crab of `kind` walking into `owner`'s castle.
    fn banked(owner: u8, kind: crate::sim::CrabKind) -> SimEvent {
        SimEvent::CrabBanked {
            id: 0,
            owner,
            pos: Vec2::ZERO,
            keep: Vec2::ZERO,
            points: 1,
            kind,
            handed: crate::sim::Handedness::Right,
        }
    }

    /// The rule the whole beach turns on: a post knocks when the seat that
    /// put it down is one this machine answers for. One human of six is the
    /// shape that matters: five bots placing was five clicks a second.
    #[test]
    fn only_the_seats_at_this_machine_are_heard() {
        let mut app = table(1);
        assert_eq!(heard(&mut app, [placed(0)]), 1, "your own post knocks");
        for bot in 1..6 {
            let played = heard(&mut app, [placed(bot)]);
            assert_eq!(played, 0, "seat {bot} is not at this table");
        }
    }

    /// Both ends of a post's life follow the same rule. In versus every
    /// post expires on its own, so gating the placement and not the removal
    /// left the click track running at nearly its old rate.
    #[test]
    fn a_post_leaving_is_as_quiet_as_a_post_arriving() {
        let mut app = table(1);
        let gone = |owner| SimEvent::SignpostRemoved {
            owner,
            pos: Vec2::ZERO,
        };
        let played = heard(&mut app, [gone(0)]);
        assert_eq!(played, 1, "your own post going is worth hearing");
        assert_eq!(heard(&mut app, [gone(3)]), 0, "a bot's expiring is not");
    }

    /// And the third end: a post traded away at the cap. Versus defaults
    /// to the evicting rule, so this is the one a six-seat beach raises
    /// most of all - every bot placement past its third post.
    #[test]
    fn a_post_traded_away_is_as_quiet_as_the_other_two() {
        let mut app = table(1);
        let traded = |owner| SimEvent::SignpostEvicted {
            owner,
            pos: Vec2::ZERO,
            dir: crate::sim::Direction::Up,
        };
        let played = heard(&mut app, [traded(0)]);
        assert_eq!(played, 1, "losing your own oldest is worth hearing");
        let played = heard(&mut app, [traded(4)]);
        assert_eq!(played, 0, "a bot trading one of its own is not");
    }

    /// Two people on one couch share a speaker, so both are heard; the
    /// four bots beside them are not.
    #[test]
    fn a_shared_couch_hears_everybody_sitting_at_it() {
        let mut app = table(2);
        assert_eq!(heard(&mut app, [placed(0)]), 1);
        let played = heard(&mut app, [placed(1)]);
        assert_eq!(played, 1, "the seat beside you is in the room");
        assert_eq!(heard(&mut app, [placed(2)]), 0, "the bot is not");
    }

    /// A machine that answers for no seat is watching, an online spectator
    /// or a replay, and hears the whole beach rather than none of it: the
    /// seat rule read "nobody" there and took every post out of a replay.
    #[test]
    fn a_watcher_hears_every_seat_because_it_holds_none() {
        let mut app = table(0);
        assert_eq!(heard(&mut app, [placed(0)]), 1, "somebody's post knocks");
        let played = heard(&mut app, [placed(4)]);
        assert_eq!(played, 1, "and so does a seat right across the beach");
    }

    /// Banks are the one cue the sim raises per crab, and a castle can take
    /// a stream of them on one tick, so a seat's castle filling is one
    /// sound. Per seat, though, and not one for the lot: six castles
    /// filling at once is six things happening in six places.
    #[test]
    fn a_castle_taking_a_stream_of_crabs_banks_once_for_it() {
        use crate::sim::CrabKind;
        let mut app = table(1);
        let common = |owner| banked(owner, CrabKind::Common);
        assert_eq!(heard(&mut app, [common(0)]), 1, "one crab, one sound");
        let played = heard(&mut app, (0..40).map(|_| common(0)));
        assert_eq!(played, 1, "and forty into the one castle is still one");
        // Unlike a post, a bank is not gated by the seat: a rival banking
        // is news, and hearing where it happened is the point of the pan.
        assert_eq!(heard(&mut app, [common(3)]), 1, "a rival's castle too");
        let played = heard(&mut app, (0..6).map(common));
        assert_eq!(played, 6, "six castles at once are six things");
        let played = heard(&mut app, (0..60).map(|i| common(i % 6)));
        assert_eq!(played, 6, "however many crabs each of them took");
    }

    /// The golden chime rides along with the bank and is held to the same
    /// seat: a castle taking two golden crabs on one tick is one arrival
    /// worth announcing, not two of them stacked on top of each other.
    #[test]
    fn a_golden_arrival_chimes_once_a_castle_too() {
        use crate::sim::CrabKind;
        let mut app = table(1);
        let golden = |owner| banked(owner, CrabKind::Golden);
        let played = heard(&mut app, [golden(0)]);
        assert_eq!(played, 2, "the bank it is, and the chime it is worth");
        let played = heard(&mut app, [golden(0), golden(0)]);
        assert_eq!(played, 2, "two into one castle are still one of each");
        let played = heard(&mut app, [golden(0), golden(1)]);
        assert_eq!(played, 4, "two castles are two of each");
    }

    /// The three ways to silence the theme, and how they compose. Each one
    /// is a veto, so the card gives back exactly what it took and no more:
    /// a game muted with M before the pause is still muted after it.
    #[test]
    fn every_silence_is_a_veto_and_none_of_them_lifts_another() {
        let settings = |on: bool, volume: u8| GameSettings {
            music_on: on,
            music_volume: volume,
            ..GameSettings::default()
        };
        let audible =
            |on, volume, mute, card| music_audible(&settings(on, volume), &Muted(mute), card);

        assert!(audible(true, 45, false, false), "on, up, unmuted, playing");
        assert!(!audible(false, 45, false, false), "the settings switch");
        assert!(!audible(true, 0, false, false), "the slider at the bottom");
        assert!(!audible(true, 45, true, false), "the master mute");
        assert!(!audible(true, 45, false, true), "the pause card");

        // Muted, then paused, then unpaused: still muted. The card is not
        // a way to get the music back, only a way to lose it for a while.
        assert!(!audible(true, 45, true, true), "both, on the way in");
        assert!(!audible(true, 45, true, false), "and M still holds it");
        // And unmuting under an open card does not play over the pause.
        assert!(!audible(true, 45, false, true), "the card still holds it");
    }

    /// The master mute takes the effects with it: reaching for M because
    /// someone walked in should not leave every gull on the beach audible.
    #[test]
    fn the_master_mute_silences_the_effects_too() {
        let settings = GameSettings {
            sfx_on: true,
            sfx_volume: 80,
            ..GameSettings::default()
        };
        assert!(sfx_gain(&settings, &Muted(false)) > 0.0, "heard by default");
        assert_eq!(sfx_gain(&settings, &Muted(true)), 0.0, "M silences them");

        // The switch on the settings card does it on its own, and keeps
        // the volume it was set to for when it comes back on.
        let off = GameSettings {
            sfx_on: false,
            ..settings.clone()
        };
        assert_eq!(sfx_gain(&off, &Muted(false)), 0.0, "switched off");
        assert_eq!(off.sfx_volume, 80, "the slider is where it was left");
    }

    /// Every track once before any comes round again, and never the same
    /// one twice running, across as many rounds of the bag as it takes.
    #[test]
    fn the_shuffle_plays_everything_and_never_repeats_back_to_back() {
        let tracks = vec![Handle::default(); 7];
        for seed in 0..50 {
            let mut rng = VisualRng::seeded(seed);
            let mut shelf = Shelf::new(tracks.clone());
            let mut previous = None;
            for _ in 0..20 {
                let mut round: Vec<usize> = (0..7).map(|_| shelf.draw(&mut rng)).collect();
                for &track in &round {
                    assert_ne!(Some(track), previous, "seed {seed}: {track} twice running");
                    previous = Some(track);
                }
                round.sort_unstable();
                assert_eq!(
                    round,
                    (0..7).collect::<Vec<_>>(),
                    "seed {seed}: one of each"
                );
            }
        }
        // And launches do not all open on the same track.
        let openers: std::collections::HashSet<usize> = (0..50)
            .map(|seed| Shelf::new(tracks.clone()).draw(&mut VisualRng::seeded(seed)))
            .collect();
        assert!(openers.len() > 1, "every launch opened on {openers:?}");
    }

    /// The versus screens play the battle set, and every other one the
    /// calm set.
    #[test]
    fn only_a_round_plays_the_battle_set() {
        for screen in Screen::ALL {
            let battle = matches!(screen, Screen::Versus | Screen::Interlude);
            let want = if battle { Mood::Battle } else { Mood::Calm };
            assert_eq!(Mood::of(screen), want, "{screen:?}");
        }
    }

    /// A world with the playlist's systems: two calm tracks, two battle
    /// tracks, on the menu, with the clock under the test's hand.
    fn radio() -> App {
        let mut app = App::new();
        app.insert_resource(GameSettings::default());
        app.insert_resource(Muted(false));
        app.insert_resource(crate::app::pause::PauseMenu::default());
        app.insert_resource(State::new(Screen::Menu));
        app.insert_resource(State::new(crate::app::VersusPhase::Running));
        app.insert_resource(Time::<()>::default());
        app.insert_resource(MusicPlaylist::new(
            vec![Handle::default(), Handle::default()],
            vec![Handle::default(), Handle::default()],
            VisualRng::seeded(7),
        ));
        app.add_systems(Update, (rotate_music, fade_music).chain());
        app
    }

    /// The tracks alive, by set, with whether each is on its way out.
    fn on_air(app: &mut App) -> Vec<(Mood, bool)> {
        app.world_mut()
            .query::<(&Music, Has<FadingOut>)>()
            .iter(app.world())
            .map(|(music, fading)| (music.0, fading))
            .collect()
    }

    fn wait(app: &mut App, secs: f32) {
        app.world_mut()
            .resource_mut::<Time>()
            .advance_by(Duration::from_secs_f32(secs));
        app.update();
    }

    fn end_it(app: &mut App) {
        let live: Vec<Entity> = app
            .world_mut()
            .query_filtered::<Entity, With<Music>>()
            .iter(app.world())
            .collect();
        for entity in live {
            app.world_mut().entity_mut(entity).despawn();
        }
    }

    /// The playlist rests between tracks, and it only moves when somebody
    /// could hear it.
    ///
    /// A track that is merely down (muted, paused, switched off) is still
    /// alive and still the same song, so nothing new starts over the top of
    /// it, and nothing starts at all while none of it would be audible.
    #[test]
    fn the_playlist_rests_between_tracks_and_only_while_somebody_could_hear_it() {
        let mut app = radio();
        let rest = Mood::Calm.rest_secs();
        let playing = |app: &mut App| on_air(app).len();

        app.update();
        assert_eq!(playing(&mut app), 1, "the first track starts at once");

        // The one that is playing is the one that stays: a second is not
        // stacked on top of it, however many frames go by.
        app.update();
        wait(&mut app, 200.0);
        assert_eq!(playing(&mut app), 1, "still the one song");

        // It ends, and the beach goes quiet for the whole of the shortest
        // rest before anything else starts.
        end_it(&mut app);
        app.update();
        wait(&mut app, rest.start - 1.0);
        assert_eq!(playing(&mut app), 0, "resting");

        // Silenced, the rest holds where it is, however long it lasts:
        // not by the master mute, the switch, the slider, the pause card.
        for silence in 0..4 {
            {
                let world = app.world_mut();
                let mut settings = world.resource_mut::<GameSettings>();
                settings.music_on = silence != 1;
                settings.music_volume = if silence == 2 { 0 } else { 45 };
                world.resource_mut::<Muted>().0 = silence == 0;
                world.resource_mut::<crate::app::pause::PauseMenu>().open = silence == 3;
            }
            wait(&mut app, 500.0);
            assert_eq!(playing(&mut app), 0, "silence {silence} starts nothing");
        }
        *app.world_mut().resource_mut::<GameSettings>() = GameSettings::default();
        app.world_mut()
            .resource_mut::<crate::app::pause::PauseMenu>()
            .open = false;
        wait(&mut app, 0.5);
        assert_eq!(playing(&mut app), 0, "the rest was held, not spent");

        // Past the longest rest, the next track is on.
        wait(&mut app, rest.end);
        assert_eq!(playing(&mut app), 1, "and then the next one");
    }

    /// Walking into a round swaps the calm track for a battle one at once,
    /// the old one fading under it, and walking out swaps them back, even
    /// in the middle of a rest.
    #[test]
    fn a_round_changes_the_set_without_waiting_for_a_rest() {
        let mut app = radio();
        app.update();
        assert_eq!(on_air(&mut app), [(Mood::Calm, false)], "the menu is calm");

        app.insert_resource(State::new(Screen::Versus));
        wait(&mut app, 0.1);
        app.update();
        let mut air = on_air(&mut app);
        air.sort_by_key(|&(mood, _)| mood == Mood::Battle);
        assert_eq!(
            air,
            [(Mood::Calm, true), (Mood::Battle, false)],
            "the calm one fades under the battle one"
        );
        wait(&mut app, FADE_SECS);
        assert_eq!(on_air(&mut app), [(Mood::Battle, false)], "and is gone");

        // A battle track ends and the round takes only a breath.
        end_it(&mut app);
        app.update();
        wait(&mut app, Mood::Battle.rest_secs().end);
        assert_eq!(on_air(&mut app), [(Mood::Battle, false)], "the next one");

        // Out of the round mid-rest: the calm set does not wait out the
        // battle's breath, nor start one of its own.
        end_it(&mut app);
        app.update();
        app.insert_resource(State::new(Screen::Menu));
        wait(&mut app, 0.1);
        assert_eq!(on_air(&mut app), [(Mood::Calm, false)], "straight back");
    }

    /// The stereo field mirrors the board (rodio boosts the far ear), tops
    /// out at the edges, and never reaches far enough from the listener for
    /// distance attenuation to make a far-off bank quieter than a near one.
    #[test]
    fn panning_mirrors_the_board_and_stays_inside_the_listener() {
        let half = 6.0 * crate::app::layout::TILE;
        assert_eq!(pan_pos(half, Vec2::ZERO).x, 0.0, "the middle is centred");
        let left = pan_pos(half, Vec2::new(-half, 0.0));
        let right = pan_pos(half, Vec2::new(half, 0.0));
        assert_eq!(left.x, PAN_WIDTH, "mirrored: left of the beach, left ear");
        assert_eq!(right.x, -left.x, "the two edges are symmetric");
        // Off-board positions clamp rather than sliding out of the field.
        assert_eq!(pan_pos(half, Vec2::new(-9.0 * half, 0.0)).x, PAN_WIDTH);
        // rodio attenuates beyond one unit; every ear-to-emitter distance
        // must stay inside that, or the pan would double as a volume drop.
        const { assert!(PAN_WIDTH + EAR_GAP / 2.0 < 1.0) };
    }
}