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
//! The frame, in order: what the app is built from, what each screen puts
//! up and takes down, and which systems run when.
//!
//! Split from `mod.rs`, which keeps the types the whole shell shares: only
//! this half changes when a system moves.

use super::*;

pub fn run() {
    run_with(watch::Watch::default());
}

/// The game, opened on whatever `watching` says to watch (usually nothing).
pub(super) fn run_with(watching: watch::Watch) {
    let mut app = App::new();
    app.insert_resource(watching);
    embedded::register(&mut app);
    // Read before the window is built, so a fullscreen player never sees a
    // window open and then grow. The same read seeds the resources below.
    let saved = settings::GameSettings::load_saved();
    let mode = settings::window_mode(
        saved
            .as_ref()
            .map_or(&settings::GameSettings::default(), |(settings, _)| settings),
    );
    app.add_plugins(
        DefaultPlugins
            .set(WindowPlugin {
                primary_window: Some(Window {
                    title: "Pinch Points".into(),
                    resolution: dev::window_size().map_or_else(default, |(w, h)| {
                        bevy::window::WindowResolution::new(w as u32, h as u32)
                    }),
                    mode,
                    window_level: if dev::on_top() {
                        bevy::window::WindowLevel::AlwaysOnTop
                    } else {
                        default()
                    },
                    ..default()
                }),
                ..default()
            })
            .set(bevy::log::LogPlugin {
                // Japanese has no word spaces, so a line of it is broken
                // with a dictionary, and the one baked into the text
                // stack's segmenter does not carry the CJK model. The lines
                // still lay out (they break between characters, which is
                // how Japanese wraps anyway); what it does is warn once per
                // line per frame, so this one target is turned off.
                filter: format!(
                    "{},icu_provider=off",
                    bevy::log::LogPlugin::default().filter
                ),
                ..bevy::log::LogPlugin::default()
            })
            .set(TaskPoolPlugin {
                task_pool_options: TaskPoolOptions {
                    // Bevy caps the io and async-compute pools at four
                    // threads each and hands the compute pool everything
                    // left over, uncapped. On a 24-core machine that is
                    // sixteen workers for this game's hundred small
                    // systems, and a `perf` profile of a six-seat XL round
                    // is then mostly the workers finding each other: queue
                    // pops, work stealing and a contended mutex come to
                    // about 18% of samples.
                    //
                    // Swept on that machine with `PINCH_THREADS`, 30 s of
                    // that round each, CPU seconds (user + sys):
                    //
                    //     cap  1     8.8     cap  4    13.3
                    //     cap  2     9.2     cap  6    15.9
                    //     cap  3    10.8     uncapped  21.2
                    //
                    // Nothing else moves: every one of those runs holds the
                    // fixed tick exactly, and the round clock reads 2:30 in
                    // all of them.
                    //
                    // Two rather than one, because the machines this has to
                    // be right on are not this one: the second worker costs
                    // 0.4 CPU-seconds here and is the one that absorbs a
                    // heavy frame on a slow laptop. A two-core machine gets
                    // what its own core count allows either way.
                    compute: TaskPoolThreadAssignmentPolicy {
                        // `PINCH_THREADS=n` sweeps the cap, and `=0` puts
                        // Bevy's own default back, which is how the table
                        // above was measured and how to re-measure it on a
                        // machine that is not this one.
                        max_threads: dev::compute_threads().unwrap_or(2),
                        ..TaskPoolOptions::default().compute
                    },
                    ..TaskPoolOptions::default()
                },
            })
            .set(RenderPlugin {
                render_creation: RenderCreation::Automatic(Box::new(WgpuSettings {
                    // Debug builds default to the Vulkan validation
                    // layer, which floods the log with a known
                    // wgpu-internal swapchain finding
                    // (VUID-VkPresentInfoKHR-pImageIndices /
                    // acquire-semaphore) we cannot act on. Run with
                    // WGPU_VALIDATION=1 to opt back in when debugging
                    // rendering.
                    instance_flags: InstanceFlags::empty().with_env(),
                    ..WgpuSettings::default()
                })),
                ..RenderPlugin::default()
            }),
    );
    insert_resources(&mut app, saved);
    failsafe::install(&mut app);
    add_startup(&mut app);
    add_screen_transitions(&mut app);
    add_phase_transitions(&mut app);
    add_frame_systems(&mut app);
    // Dev hook: `PINCH_ST_EXEC=1` swaps every main-world schedule to the
    // single-threaded executor, for the backlog's CPU measurement. The
    // render sub-app keeps its own schedules and its parallelism. `new()`
    // rather than `default()`: the derived default leaves
    // `apply_final_deferred` false, and the app dies on the first frame
    // missing every command-queued resource.
    if dev::single_threaded_executor() {
        use bevy::ecs::schedule::{Schedules, SingleThreadedExecutor};
        let mut schedules = app.world_mut().resource_mut::<Schedules>();
        let swapped = schedules
            .iter_mut()
            .map(|(_, schedule)| schedule.set_executor(SingleThreadedExecutor::new()))
            .count();
        info!("single-threaded executor on {swapped} main-world schedules");
    }
    // Dev hook: `PINCH_SHUFFLE=<seed>` (with `--features shuffle`) shuffles
    // the unordered systems of every main-world schedule. See
    // `dev::shuffle_seed`.
    #[cfg(feature = "shuffle")]
    if let Some(seed) = dev::shuffle_seed() {
        use bevy::ecs::schedule::Schedules;
        let mut schedules = app.world_mut().resource_mut::<Schedules>();
        let shuffled = schedules
            .iter_mut()
            .map(|(_, schedule)| {
                let mut settings = schedule.get_build_settings();
                settings.shuffle_seed = Some(seed);
                schedule.set_build_settings(settings);
            })
            .count();
        info!("PINCH_SHUFFLE: {shuffled} main-world schedules shuffled with seed {seed}");
    }
    app.run();
}

/// The resources, states and message types the whole shell shares.
fn insert_resources(app: &mut App, saved: Option<(settings::GameSettings, keycaps::KeyCaps)>) {
    app.insert_resource(Time::<Fixed>::from_hz(f64::from(
        crate::sim::TICKS_PER_SECOND,
    )));
    app.insert_resource(Sandbox(dev::sandbox()));
    let (levels, builtins) = campaign::tide_pool_levels();
    app.insert_resource(Coop(dev::coop()));
    app.insert_resource(Campaign {
        kind: CampaignKind::TidePool,
        levels,
        index: 0,
        builtins,
    });
    // Replaced on mode entry; a 1x1 board just keeps the resource non-null.
    app.insert_resource(Sim(Board::new(1, 1, 0)));
    app.init_resource::<PendingActions>();
    app.init_resource::<Paused>();
    app.init_resource::<editor::EditorState>();
    app.init_resource::<Recorder>();
    app.init_resource::<awards::RoundTally>();
    app.init_resource::<Highlight>();
    app.init_resource::<ReelThread>();
    app.init_resource::<Controllers>();
    app.init_resource::<bot_seats::BotSeats>();
    app.init_resource::<art::Art>();
    app.init_resource::<match_setup::MatchConfig>();
    app.init_resource::<match_setup::CustomBeaches>();
    app.init_resource::<board_render::CastleFlight>();
    app.init_resource::<match_setup::MatchMenu>();
    app.init_resource::<Playback>();
    app.init_resource::<net::Online>();
    app.init_resource::<lobby::LobbyState>();
    app.init_resource::<lobby::Homecoming>();
    app.init_resource::<Seats>();
    app.init_resource::<Resuming>();
    app.init_resource::<RoundNotice>();
    app.init_resource::<menu_scene::MenuList>();
    app.init_resource::<stage_select::StageList>();
    app.init_resource::<hint::Hints>();
    app.init_resource::<hint::DeniedNote>();
    app.init_resource::<replays::Library>();
    app.init_resource::<replays::PlaybackSpeed>();
    app.init_resource::<gamepad::PadSeats>();
    app.init_resource::<gamepad::Bridged>();
    app.init_resource::<effects::VisualRng>();
    app.init_resource::<effects::Trauma>();
    app.init_resource::<pause::PauseMenu>();
    app.init_resource::<countdown::Countdown>();
    app.init_resource::<spectators::SpectatorChat>();
    app.init_resource::<spectators::SpectatorCard>();
    app.init_resource::<spectators::PickCard>();
    app.init_resource::<audio::Muted>();
    app.init_resource::<Daily>();
    app.init_resource::<SeatNames>();
    app.init_resource::<SeatKinds>();
    app.init_resource::<tournament::Tournament>();
    app.init_resource::<side_panels::EventLog>();
    app.init_resource::<announce::Announcer>();
    app.init_resource::<update::UpdateCheck>();
    // A first run has no settings file, and opens on the language picker
    // rather than on a menu written in a language nobody chose. One read
    // answers both questions: what the settings are, and whether there
    // were any. A dev hook still wins - `dev::kickoff` sets NextState in
    // Startup, which lands before the first state transition.
    let opens_on = language::opening_screen(saved.is_some());
    // Two resources off one read: the preferences, and the learned caps
    // table that shares their file (see [`keycaps::KeyCaps`]).
    let (settings, caps) = saved.unwrap_or_default();
    app.insert_resource(settings);
    app.insert_resource(caps);
    app.init_resource::<settings::screen::SettingsMenu>();
    app.init_resource::<controls::ControlsMenu>();
    app.insert_state(opens_on);
    app.init_state::<Phase>();
    app.init_state::<VersusPhase>();
    app.add_message::<LoadLevel>();
    app.add_message::<PlacementDenied>();
    app.add_message::<LevelSaved>();
    app.add_message::<CodeShared>();
    app.add_message::<CodeTaken>();
    app.add_message::<sim_events::SimEvent>();
    app.init_resource::<achievements::PuzzleAttempt>();
}

/// One-time setup: camera, font, HUD, sounds, saved stats, dev hooks.
fn add_startup(app: &mut App) {
    app.add_systems(
        Startup,
        (
            boot::setup_camera,
            boot::install_ui_font,
            hud::spawn_hud,
            audio::load_sounds,
            achievements::load,
            progress::load,
            dev::kickoff,
            watch::begin,
            // Off-thread; the menu polls for the answer.
            update::start_check,
        ),
    );
}

/// What each screen builds on entry and tears down on exit.
fn add_screen_transitions(app: &mut App) {
    app.add_systems(
        OnEnter(Screen::Puzzle),
        (
            // Before the first load, whose message this stage's retry count
            // is about to be measured against.
            achievements::reset_puzzle_attempt,
            cursor::spawn_stage_cursors,
            send_first_load,
        )
            .chain(),
    );
    app.add_systems(
        OnEnter(Screen::Achievements),
        achievements::enter_achievements,
    );
    app.add_systems(
        OnEnter(Screen::StageSelect),
        stage_select::enter_stage_select,
    );
    app.add_systems(
        OnExit(Screen::StageSelect),
        menu_ui::despawn_marked::<stage_select::StageSelectUi>,
    );
    app.add_systems(OnEnter(Screen::Language), language::enter_language);
    app.add_systems(OnEnter(Screen::NewVersion), update::enter_new_version);
    app.add_systems(OnExit(Screen::NewVersion), update::exit_new_version);
    app.add_systems(
        OnExit(Screen::Language),
        menu_ui::despawn_marked::<language::LanguageUi>,
    );
    app.add_systems(OnEnter(Screen::Replays), replays::enter_library);
    app.add_systems(
        OnExit(Screen::Replays),
        menu_ui::despawn_marked::<replays::LibraryUi>,
    );
    app.add_systems(
        OnExit(Screen::Achievements),
        menu_ui::despawn_marked::<achievements::AchievementsUi>,
    );
    app.add_systems(
        OnEnter(Screen::Versus),
        // Chained so the cursor spawn commands apply before load_versus
        // positions the cursors, and the side panels see the seat count.
        (
            // A local match on a handmade beach reads it off the shelf, so
            // the shelf has to be current before the board is built.
            match_setup::refresh_custom_beaches,
            // An arena being watched puts its next game on first, so the
            // cursors and the board both see it.
            watch::install,
            cursor::spawn_versus_cursors,
            load_versus,
            countdown::show_countdown,
            resolve_seat_names,
            // Bots' seats are named for their bots, over what was resolved.
            bot_seats::begin_round,
            side_panels::spawn_side_panels,
            achievements::reset_round_scratch,
        )
            .chain(),
    );
    app.add_systems(
        OnEnter(Screen::Editor),
        (
            editor::enter_editor,
            editor::spawn_editor_ui,
            cursor::spawn_puzzle_cursor,
            cursor::center_cursors,
        )
            .chain(),
    );
    app.add_systems(
        OnEnter(Screen::Menu),
        (
            menu_scene::enter_menu,
            tournament::reset_on_menu,
            bot_seats::close_door,
            // Whatever kept a session alive between rounds, the menu is the
            // end of it: the socket closes and the beach comes off the air.
            |mut online: ResMut<net::Online>| online.0 = None,
        ),
    );
    app.add_systems(
        OnExit(Screen::Menu),
        (
            menu_ui::despawn_marked::<menu_scene::MenuArt>,
            despawn_board_sprites,
            // The notice is news about one round; it is read on the menu and
            // does not follow the player into the next thing they pick.
            |mut notice: ResMut<RoundNotice>| notice.0.clear(),
        ),
    );
    app.add_systems(
        OnEnter(Screen::Lobby),
        (match_setup::refresh_custom_beaches, lobby::enter_lobby),
    );
    app.add_systems(
        OnExit(Screen::Lobby),
        (lobby::exit_lobby, menu_ui::despawn_marked::<lobby::LobbyUi>),
    );
    app.add_systems(OnEnter(Screen::Settings), settings::screen::enter_settings);
    app.add_systems(
        OnExit(Screen::Settings),
        menu_ui::save_and_despawn::<settings::screen::SettingsUi>,
    );
    app.add_systems(OnEnter(Screen::Controls), controls::enter_controls);
    app.add_systems(
        OnExit(Screen::Controls),
        menu_ui::save_and_despawn::<controls::ControlsUi>,
    );
    app.add_systems(
        OnEnter(Screen::MatchSetup),
        (
            match_setup::refresh_custom_beaches,
            match_setup::enter_match_setup,
        ),
    );
    app.add_systems(
        OnExit(Screen::MatchSetup),
        menu_ui::save_and_despawn::<match_setup::MatchUi>,
    );
    app.add_systems(OnEnter(Screen::Interlude), tournament::enter_interlude);
    app.add_systems(
        OnExit(Screen::Interlude),
        menu_ui::despawn_marked::<tournament::InterludeUi>,
    );
    app.add_systems(
        OnExit(Screen::Editor),
        (
            menu_ui::despawn_marked::<cursor::Cursor>,
            menu_ui::despawn_marked::<cursor::PostGhost>,
            menu_ui::despawn_marked::<effects::Particle>,
            menu_ui::despawn_marked::<effects::Hop>,
            menu_ui::despawn_marked::<editor::EditorUi>,
            despawn_board_sprites,
            editor::exit_editor,
        ),
    );
    app.add_systems(
        OnExit(Screen::Puzzle),
        (
            menu_ui::despawn_marked::<cursor::Cursor>,
            menu_ui::despawn_marked::<cursor::PostGhost>,
            despawn_board_sprites,
            menu_ui::despawn_marked::<results::ResultsPanel>,
            menu_ui::despawn_marked::<effects::Particle>,
            menu_ui::despawn_marked::<effects::Hop>,
            announce::clear_announcements,
            hint::clear_hint_ghosts,
            pause::reset_pause,
            reset_puzzle_phase,
            achievements::save_now,
        ),
    );
    app.add_systems(
        OnExit(Screen::Versus),
        (
            menu_ui::despawn_marked::<cursor::Cursor>,
            menu_ui::despawn_marked::<cursor::PostGhost>,
            despawn_board_sprites,
            end_versus,
            bot_seats::end_round,
            menu_ui::despawn_marked::<results::ResultsPanel>,
            menu_ui::despawn_marked::<side_panels::SidePanelRoot>,
            menu_ui::despawn_marked::<effects::Particle>,
            menu_ui::despawn_marked::<effects::Hop>,
            menu_ui::despawn_marked::<countdown::CountdownText>,
            announce::clear_announcements,
            pause::reset_pause,
            spectators::forget_spectating,
            achievements::save_now,
            |mut daily: ResMut<Daily>| daily.active = false,
        ),
    );
}

/// Round outcomes: the puzzle win/lose cards and the versus results.
fn add_phase_transitions(app: &mut App) {
    app.add_systems(
        OnEnter(Phase::Won),
        (
            audio::play_win.run_if(in_state(Screen::Puzzle)),
            results::spawn_puzzle_won.run_if(in_state(Screen::Puzzle)),
            progress::record_cleared.run_if(in_state(Screen::Puzzle)),
            // After the clear is recorded: the campaign-finished trophy asks
            // whether every stage is done, and the last one is this one.
            achievements::record_puzzle
                .run_if(in_state(Screen::Puzzle))
                .after(progress::record_cleared),
        ),
    );
    app.add_systems(
        OnEnter(Phase::Running),
        achievements::note_posts_spent.run_if(in_state(Screen::Puzzle)),
    );
    app.add_systems(
        OnExit(Phase::Won),
        menu_ui::despawn_marked::<results::ResultsPanel>,
    );
    app.add_systems(
        OnEnter(Phase::Lost),
        (
            audio::play_lose.run_if(in_state(Screen::Puzzle)),
            results::spawn_puzzle_lost.run_if(in_state(Screen::Puzzle)),
            hint::record_loss.run_if(in_state(Screen::Puzzle)),
        ),
    );
    app.add_systems(
        OnExit(Phase::Lost),
        menu_ui::despawn_marked::<results::ResultsPanel>,
    );
    // A banner raised in the last second of a round would otherwise sit on
    // top of the results card; the round is over, the news can go.
    app.add_systems(OnEnter(Phase::Won), announce::clear_announcements);
    app.add_systems(OnEnter(Phase::Lost), announce::clear_announcements);
    app.add_systems(OnEnter(VersusPhase::Over), announce::clear_announcements);
    app.add_systems(
        OnEnter(VersusPhase::Over),
        (
            tournament::record_series_round.run_if(in_state(Screen::Versus)),
            // The stats before the card: the card quotes today's daily
            // best, and it should be the best with this round counted.
            // A replay being watched counts for nothing.
            achievements::record_round.run_if(in_state(Screen::Versus).and_then(not_watching)),
            // A spectator's call, scored before the card that says how it went.
            spectators::score_the_call.run_if(in_state(Screen::Versus)),
            results::spawn_versus_results.run_if(in_state(Screen::Versus)),
        )
            .chain(),
    );
    app.add_systems(
        OnExit(VersusPhase::Over),
        menu_ui::despawn_marked::<results::ResultsPanel>,
    );
}

/// The frame, in order. Every `Update` system belongs to exactly one of
/// these, and the sets are chained, so the order is declared here instead
/// of being implied by a system's position in a hundred-line tuple.
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Frame {
    /// Menus and the screens that only read input.
    Ui,
    /// Settings pushed out into Bevy: sink volume, UI scale, tick rate.
    Apply,
    /// Play input, level loading, and the round-outcome checks.
    Play,
    /// Sprites and particles catching up with the sim.
    Render,
    /// Consumers of the observed sim-event stream. After `Render` on
    /// purpose: the effects read the previous frame's events, as they
    /// always have.
    Events,
    /// HUD text, sidebars, results chrome.
    Chrome,
    /// Camera, audio, dev hooks: the last word on the frame.
    Finish,
}

/// The per-frame schedule: the fixed-timestep sim driver, and the `Update`
/// systems grouped into the [`Frame`] sets.
fn add_frame_systems(app: &mut App) {
    app.add_systems(FixedUpdate, advance_sim.run_if(sim_should_run));
    app.add_systems(Update, watch::pump);
    app.add_systems(
        Update,
        watch::dropped_replays.run_if(in_state(Screen::Menu).or_else(in_state(Screen::Replays))),
    );
    // A hosted beach keeps its beacon up for the whole match, not just the
    // lobby, so a player arriving late sees a game in progress with a chair
    // free rather than an empty network. In `Update` rather than beside the
    // sim, because it must go on saying so while the round is paused.
    app.add_systems(
        Update,
        (|time: Res<Time>, mut online: ResMut<net::Online>| {
            if let Some(session) = &mut online.0 {
                session.keep_announcing(time.delta_secs());
            }
        })
        .in_set(Frame::Play),
    );
    // Learns what the keys say before anything this frame spells one out:
    // the controls screen labelling a rebind, the prompt line naming the
    // move keys. After Bevy's own input pass, so the modifier check sees
    // this frame's Shift, not last frame's.
    app.add_systems(
        PreUpdate,
        keycaps::learn_keycaps.after(bevy::input::InputSystems),
    );
    // Asked once, before the first frame draws a legend: the platform
    // knows the whole board, including the punctuation nobody will press.
    // What it will not answer, the presses above go on answering.
    app.add_systems(Startup, keymap::read_keymap);
    app.configure_sets(
        Update,
        (
            Frame::Ui,
            Frame::Apply,
            Frame::Play,
            Frame::Render,
            Frame::Events,
            Frame::Chrome,
            Frame::Finish,
        )
            .chain(),
    );
    add_ui_systems(app);
    add_apply_systems(app);
    add_play_systems(app);
    add_render_systems(app);
    add_event_systems(app);
    add_chrome_systems(app);
    add_finish_systems(app);
}

/// Menu, lobby, settings, controls and match setup: the screens that only
/// read input and repaint their own rows.
fn add_ui_systems(app: &mut App) {
    app.add_systems(
        Update,
        (
            (
                gamepad::keep_pad_order,
                gamepad::pad_menu_bridge.run_if(
                    in_state(Screen::Menu)
                        .or_else(in_state(Screen::Settings))
                        .or_else(in_state(Screen::Controls))
                        .or_else(in_state(Screen::MatchSetup))
                        .or_else(in_state(Screen::Lobby))
                        .or_else(in_state(Screen::StageSelect))
                        .or_else(in_state(Screen::Language))
                        .or_else(in_state(Screen::NewVersion))
                        .or_else(in_state(Screen::Replays))
                        .or_else(in_state(Screen::Achievements))
                        .or_else(versus_over)
                        .or_else(
                            in_state(Screen::Puzzle)
                                .and_then(in_state(Phase::Won).or_else(in_state(Phase::Lost))),
                        ),
                ),
                // On every screen: a press lets go wherever its finger comes
                // off, which is often a screen the bridge does not run on.
                gamepad::pad_bridge_release,
            )
                .chain(),
            // The check's answer is read on the menu, and a newer release
            // takes the menu to the page. Before the menu's own input, so
            // the two never both set the screen from one keypress.
            (
                update::poll_check,
                menu_scene::paste_round,
                menu_scene::menu_input,
                menu_scene::update_menu_rows,
            )
                .chain()
                .run_if(in_state(Screen::Menu)),
            (update::new_version_input, update::update_new_version_rows)
                .chain()
                .run_if(in_state(Screen::NewVersion)),
            (
                lobby::discover,
                lobby::host_tick,
                lobby::join_tick,
                lobby::lobby_input,
                lobby::update_lobby_list,
                lobby::update_lobby_view,
                lobby::update_lobby_players,
                lobby::update_lobby_robots,
                lobby::update_lobby_terms,
                lobby::update_lobby_beach_note,
                lobby::update_lobby_chat,
            )
                .chain()
                .run_if(in_state(Screen::Lobby)),
            (
                settings::screen::settings_input,
                settings::screen::update_settings_ui,
            )
                .chain()
                .run_if(in_state(Screen::Settings)),
            (controls::controls_input, controls::update_controls_ui)
                .chain()
                .run_if(in_state(Screen::Controls)),
            (
                stage_select::stage_select_input,
                stage_select::update_stage_tiles,
            )
                .chain()
                .run_if(in_state(Screen::StageSelect)),
            (replays::library_input, replays::update_library)
                .chain()
                .run_if(in_state(Screen::Replays)),
            (language::language_input, language::update_language_ui)
                .chain()
                .run_if(in_state(Screen::Language)),
            (replays::playback_speed_input, replays::playback_pause_input)
                .run_if(in_state(Screen::Versus).and_then(keys_are_free)),
            (
                spectators::spectator_chat_input,
                spectators::spectator_vote_input,
                spectators::spectator_pick_input,
                spectators::settle_spectator_vote,
            )
                .chain()
                .run_if(in_state(Screen::Versus).and_then(keys_are_free)),
            bot_seats::announce.run_if(in_state(Screen::Versus)),
            (
                gamepad::pad_claim_seats,
                match_setup::match_setup_input,
                match_setup::update_match_ui,
                match_setup::update_match_pad_info,
            )
                .chain()
                .run_if(in_state(Screen::MatchSetup)),
            // After the screens' own input, which stands down while a
            // doorway card is up, so the card's Esc is read once.
            (bot_seats::door_input, bot_seats::door_card)
                .chain()
                .run_if(in_state(Screen::MatchSetup).or_else(in_state(Screen::Lobby))),
        )
            .chain()
            .in_set(Frame::Ui),
    );
}

/// Settings reaching the engine, and the two small input reactions.
fn add_apply_systems(app: &mut App) {
    app.add_systems(
        Update,
        (
            cursor::flash_cursors,
            audio::play_denied,
            settings::apply_music_volume,
            settings::apply_accessibility,
            settings::apply_sim_speed,
            settings::toggle_fullscreen,
            settings::apply_window_mode,
        )
            .chain()
            .in_set(Frame::Apply),
    );
}

/// Play: level loading, cursors, the editor, pauses, and the checks that
/// end a round.
fn add_play_systems(app: &mut App) {
    app.add_systems(
        Update,
        (
            handle_load_level,
            // Nested: the two that a fresh level starts, and the outer
            // tuple is at Bevy's arity limit.
            (
                hint::reset_on_level,
                achievements::track_puzzle_attempt.run_if(in_state(Screen::Puzzle)),
            )
                .run_if(on_message::<LoadLevel>),
            cursor::move_cursor.run_if(
                not(in_state(Screen::Menu))
                    .and_then(not(editor::editor_naming))
                    .and_then(keys_are_free),
            ),
            (play_input::setup_input, play_input::browse_levels)
                .chain()
                .run_if(puzzle_setup.and_then(keys_are_free)),
            dev::debug_autoplay.run_if(puzzle_setup),
            hint::hint_input.run_if(puzzle_setup.or_else(puzzle_done).and_then(keys_are_free)),
            // One nested group so the tuple stays inside Bevy's arity limit
            // of 20, which this list was already sitting on. The chain still
            // runs them in written order, and that order matters: the note
            // is aged before it is raised, so a denial arriving this frame
            // survives to be drawn this frame.
            (
                hint::draw_hint.run_if(in_state(Screen::Puzzle)),
                hint::tick_denied_note,
                hint::note_denials,
            ),
            play_input::running_input.run_if(puzzle_running.and_then(keys_are_free)),
            // Under the pause card a pad's Start can open on the card,
            // and the card's South is the card's, not "next stage".
            play_input::done_input.run_if(puzzle_done.and_then(keys_are_free)),
            check_outcome.run_if(puzzle_running),
            play_input::versus_input.run_if(versus_running.and_then(keys_are_free)),
            // C is a letter in a spectator's line of chat.
            suspend::copy_round_code.run_if(
                versus_running
                    .and_then(keys_are_free)
                    .and_then(not(text_entry_open)),
            ),
            (
                dev::debug_net_probe,
                dev::debug_autopilot,
                dev::debug_spectator,
            )
                .run_if(versus_running),
            (
                dev::debug_banner.run_if(versus_running.or_else(puzzle_running)),
                dev::debug_moments,
            ),
            // Paired into one slot: the list is at Bevy's twenty-element
            // limit. Both only do anything with their variable set.
            (dev::debug_tide, dev::debug_lure).run_if(versus_running.or_else(puzzle_running)),
            // A player who stops sending holds the whole table on one
            // frame. The host gives up on them and hands the seat to an AI;
            // every peer does it on the host's word, so they all do it on
            // the same frame. When it is the *host* that has gone, no word
            // is coming and no seat can be filled, so the joiners are told
            // rather than left watching a still beach. Paired into tuple
            // slots because the list around it is at Bevy's limit.
            (
                check_versus_over,
                net::abandon_the_departed,
                net::leave_a_hostless_round,
                net::catch_up_again,
            )
                .run_if(versus_running),
            // The sim is stopped on the results card, so the session has to
            // be drained by hand: this is when a latecomer greets to queue
            // and when the host's next-round invitation arrives. Chained
            // ahead of the input, so an invitation that lands this frame is
            // acted on this frame.
            //
            // The host can vanish while the card is up as easily as during
            // a round, and the card is where a table sits longest, so that
            // watch goes last in the chain.
            (
                net::poll_between_rounds,
                play_input::versus_over_input,
                net::leave_a_hostless_round,
            )
                .chain()
                .run_if(versus_over),
            // `editor_input` is what types the name, so it runs while naming;
            // the command keys do not, or the letters of a name would flip
            // wrap and start the solver, and Enter would begin a playtest.
            (
                editor::editor_input,
                editor::editor_commands.run_if(not(editor::editor_naming)),
            )
                .chain()
                .run_if(in_state(Screen::Editor).and_then(not(editor::editor_testing))),
            editor::editor_test_input
                .run_if(in_state(Screen::Editor).and_then(editor::editor_testing)),
            // Paired into one slot because the list around it is at Bevy's
            // twenty-element limit.
            (
                editor::poll_solver,
                editor::update_editor_palette,
                editor::rebuild_statics,
            )
                .run_if(in_state(Screen::Editor)),
        )
            .chain()
            .in_set(Frame::Play),
    );
    app.add_systems(
        Update,
        (
            // The pad walks the card's rows with the same stick the board
            // cursor answers to, so it needs the gate as much as the keys.
            gamepad::pad_move_cursor.run_if(
                not(in_state(Screen::Menu))
                    .and_then(not(editor::editor_naming))
                    .and_then(keys_are_free),
            ),
            gamepad::pad_setup_input.run_if(puzzle_setup.and_then(keys_are_free)),
            gamepad::pad_versus_input.run_if(versus_running.and_then(keys_are_free)),
            (pause::pause_input, pause::update_pause_rows)
                .chain()
                .run_if(play_screens),
        )
            .chain()
            .in_set(Frame::Play)
            .after(editor::rebuild_statics),
    );
}

/// Everything that redraws the board from sim state.
fn add_render_systems(app: &mut App) {
    app.add_systems(
        Update,
        (
            board_render::sync_signposts,
            board_render::dress_signposts,
            board_render::sync_turnstiles,
            board_render::sync_castles,
            board_render::kick_castles,
            board_render::cheer_tier_ups,
            // After the kick, which also writes scale: a bank landing in
            // the same frame as a swap must not fight the flight.
            board_render::fly_castles,
            board_render::wave_pennants,
            // Paired: the list is at Bevy's twenty-element limit.
            (creatures::sync_crab_sprites, creatures::draw_sweeps),
            creatures::sync_gull_sprites,
            creatures::interpolate_crabs,
            creatures::interpolate_gulls,
            // Grouped: the tide's two systems in one slot, because the
            // list around them is at Bevy's twenty-element limit.
            (
                board_render::update_waterline,
                board_render::update_water_foam,
            )
                .chain(),
            board_render::pulse_spawners,
            // Paired for the same twenty-element limit: pools and logs are
            // the terrain that moves.
            (board_render::animate_turnstiles, board_render::ripple_pools),
            board_render::drift_cloud_shadows,
            (
                board_render::start_tide_wash,
                board_render::advance_tide_wash,
            )
                .chain(),
            (cursor::glide_cursors, cursor::ghost_pending_posts).chain(),
            effects::moment_effects,
            // Paired for the twenty-element limit: both are the beach
            // answering what walks on it.
            (
                effects::crab_trails,
                effects::splash_ponds,
                effects::golden_call_rings,
            ),
        )
            .chain()
            .run_if(board_screens)
            .in_set(Frame::Render),
    );
    // On every screen: the sprites load while the menu is up, and the menu
    // draws them too.
    app.add_systems(Update, art::mipmap_sprites);
    // On every screen too: it is also what puts the prompt back to its own
    // size and wrapping once there is no legend under it.
    app.add_systems(Update, hud::fit_prompt);
}

/// The sim observer and its consumers, plus the ambient screens.
fn add_event_systems(app: &mut App) {
    app.add_systems(
        Update,
        (
            sim_events::observe_sim.run_if(board_screens),
            audio::play_events,
            gamepad::rumble_on_raid.run_if(play_screens.and_then(not_watching)),
            achievements::track_events.run_if(play_screens.and_then(not_watching)),
            (
                announce::collect_announcements,
                announce::drive_announcements,
            )
                .chain()
                .run_if(play_screens),
            achievements::record_level_built.run_if(in_state(Screen::Editor)),
            achievements::record_codes.run_if(in_state(Screen::Editor)),
            achievements::update_toasts,
            (
                achievements::achievements_input,
                achievements::update_shelf_scrollbar,
            )
                .chain()
                .run_if(in_state(Screen::Achievements)),
            tournament::interlude_tick.run_if(in_state(Screen::Interlude)),
            menu_scene::menu_ambience.run_if(postcard_screens),
            menu_scene::refit_shore.run_if(postcard_screens),
            menu_scene::tend_backdrop,
            (menu_ui::dress_cards, menu_ui::scale_card_frames).chain(),
        )
            .chain()
            .in_set(Frame::Events),
    );
}

/// The readouts: header, sidebars, clocks, hints.
fn add_chrome_systems(app: &mut App) {
    app.add_systems(
        Update,
        (
            hud::update_hud,
            hud::header_backdrop,
            hud::field_guide_visibility,
            hud::update_field_guide,
            side_panels::update_side_panels,
            side_panels::update_arrow_dots.run_if(any_with_component::<side_panels::ArrowDot>),
            side_panels::update_side_clock.run_if(in_state(Screen::Versus)),
            (side_panels::collect_log, side_panels::collect_chat)
                .chain()
                .run_if(in_state(Screen::Versus)),
            side_panels::update_log,
            hud::update_tide_clock,
            hud::update_hint,
            (
                countdown::run_countdown
                    .run_if(in_state(Screen::Versus).and_then(in_state(VersusPhase::Countdown))),
                countdown::draw_countdown.run_if(any_with_component::<countdown::CountdownText>),
            )
                .chain(),
            (replays::tend_replay_bar, replays::update_replay_bar).chain(),
            // The reel lands after the card is up; the card's line waits.
            (poll_reel, results::update_highlight_line)
                .chain()
                .run_if(versus_over),
        )
            .chain()
            .in_set(Frame::Chrome),
    );
}

/// Particles, camera, music, and the screenshot hook.
fn add_finish_systems(app: &mut App) {
    app.add_systems(
        Update,
        (
            effects::update_particles,
            effects::advance_hops,
            // Until it lands: the font it names is registered by a system
            // of Bevy's own, and is not there to be named before that has
            // run once.
            boot::teach_the_kanji_fallback,
            boot::fit_camera,
            // After the fit, which writes the camera's resting place: the
            // shake is an offset from there.
            boot::shake_camera,
            audio::toggle_mute.run_if(not(text_entry_open)),
            audio::drive_music,
            audio::rotate_music,
            audio::fade_music,
            dev::debug_screenshot,
        )
            .chain()
            .in_set(Frame::Finish),
    );
    app.add_systems(Update, dev::frame_times);
    // Last in the frame, so a panic caught anywhere in it is seen in it.
    app.add_systems(Last, failsafe::leave_a_broken_round);
    // Last, so an exit asked for anywhere in the frame is seen in it: the
    // app stops once the frame is over.
    app.add_systems(Last, achievements::save_on_exit);
}

use conditions::*;
use session::*;