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
//! Crab sprite lifecycle and render interpolation.
//!
//! One sprite entity per live crab, keyed by the sim's stable crab id. Every
//! frame, transforms are interpolated between the crab's previous and current
//! sub-tile positions using the fixed-timestep overstep fraction (spec §7.4).

use crate::app::art::Art;
use crate::app::layout::{self, TILE};
use crate::app::palette;
use crate::app::{Sim, effects};
use crate::sim::{Crab, CrabKind, Gull, GullState, Handedness};
use bevy::color::Mix;
use bevy::platform::collections::HashMap;
use bevy::prelude::*;

#[derive(Component)]
pub struct CrabSprite {
    pub id: u32,
    pub kind: CrabKind,
    /// A per-crab lift or drop on the shell colour, drawn once from the id,
    /// so twenty crabs of one kind are a crowd rather than twenty copies of
    /// one sprite. Small enough that a kind is still read by its colour.
    pub(crate) shade: f32,
}

/// How far a crab has been nudged out of a crowd, and how much smaller it
/// is drawn there, eased toward what [`crowd_target`] asks each frame so a
/// pile forming or breaking up is a drift and not a jump.
#[derive(Component, Default)]
pub struct Crowding {
    spread: Vec2,
    shrink: f32,
}

/// How close another crab has to be, centre to centre, to count as company.
const CROWD_RADIUS: f32 = TILE * 0.45;

/// How far across its heading a crab in a thick crowd is moved: the outer
/// of its five lanes, in world units.
const CROWD_SPREAD: f32 = TILE * 0.32;

/// How much smaller a crab in a thick crowd is drawn.
const CROWD_SHRINK: f32 = 0.28;

/// How crowded a crab is, 0 to 1, from how many others are within
/// [`CROWD_RADIUS`]: none is 0, three or more is a pile.
fn crowd_level(neighbours: usize) -> f32 {
    (neighbours as f32 / 3.0).min(1.0)
}

/// Which of five lanes across its heading a crab takes in a crowd, -1 to
/// 1: fixed by its id, so the same crab always moves the same way and a
/// stream fans out into a band instead of shuffling.
fn crowd_lane(id: u32) -> f32 {
    let lane = (id.wrapping_mul(2_654_435_761) >> 16) % 5;
    lane as f32 / 2.0 - 1.0
}

/// Where a crab should be drawn relative to its true place, and how much
/// smaller, given how crowded it is and which way it faces.
///
/// A crowd is where crabs are drawn on top of each other: a stream out of
/// a spawner walks single file, each half over the one ahead, and a lure
/// or Crab Mania heaps them into a pile of legs nobody can count. Moved
/// across their heading into lanes and drawn a little smaller, they read
/// as that many crabs. A crab on its own is drawn exactly where it is:
/// the offset is render-side only and never reaches the sim.
fn crowd_target(neighbours: usize, id: u32, heading: Vec2) -> (Vec2, f32) {
    let level = crowd_level(neighbours);
    let across = Vec2::new(-heading.y, heading.x);
    (
        across * crowd_lane(id) * CROWD_SPREAD * level,
        CROWD_SHRINK * level,
    )
}

/// How many other crabs are within [`CROWD_RADIUS`] of each crab, by id.
/// Bucketed by radius-sized cells, so each crab checks its own cell and the
/// eight round it rather than the whole beach.
fn count_neighbours(board: &crate::sim::Board, into: &mut HashMap<u32, usize>) {
    into.clear();
    let at: Vec<(u32, Vec2)> = board
        .crabs()
        .iter()
        .map(|crab| (crab.id, layout::pose_pos(board, crab.pose())))
        .collect();
    let cell = |p: Vec2| {
        (
            (p.x / CROWD_RADIUS).floor() as i32,
            (p.y / CROWD_RADIUS).floor() as i32,
        )
    };
    let mut cells: HashMap<(i32, i32), Vec<Vec2>> = HashMap::default();
    for &(_, p) in &at {
        cells.entry(cell(p)).or_default().push(p);
    }
    for &(id, p) in &at {
        let (cx, cy) = cell(p);
        let mut near = 0;
        for dx in -1..=1 {
            for dy in -1..=1 {
                if let Some(others) = cells.get(&(cx + dx, cy + dy)) {
                    near += others
                        .iter()
                        .filter(|o| o.distance_squared(p) < CROWD_RADIUS * CROWD_RADIUS)
                        .count();
                }
            }
        }
        // Itself, counted once in its own cell.
        into.insert(id, near.saturating_sub(1));
    }
}

/// The widest a shell strays from its kind's colour, either way.
const SHADE_SPREAD: f32 = 0.05;

/// One crab's shell: its kind's colour, nudged by its own shade.
///
/// Only the kinds a beach is *crowded* with. Twenty is never how many
/// golden crabs are on the sand, and a golden lightened by a twentieth
/// lands nearer a juvenile's pale orange than its own yellow: fifty points
/// wearing the face of two.
pub(crate) fn shell_color(kind: CrabKind, shade: f32) -> Color {
    let base = body_color(kind);
    match kind {
        CrabKind::Molting | CrabKind::Golden | CrabKind::Sparkling => base,
        CrabKind::Common | CrabKind::Juvenile | CrabKind::Giant => {
            if shade >= 0.0 {
                base.lighter(shade)
            } else {
                base.darker(-shade)
            }
        }
    }
}

/// The shade a crab is born with. A hash of the id rather than a draw from
/// [`effects::VisualRng`], so a crab keeps its shell for as long as it
/// lives however many times the sprite is rebuilt around it.
pub(crate) fn shade_of(id: u32) -> f32 {
    let mixed = id.wrapping_mul(2_654_435_761) >> 16;
    (mixed % 1000) as f32 / 1000.0 * SHADE_SPREAD * 2.0 - SHADE_SPREAD
}

#[derive(Component)]
pub struct GullSprite(pub u32);

/// The soft blob under a creature. Gull shadows detach in flight.
#[derive(Component)]
pub struct CreatureShadow;

const CLAW_LEFT: Color = Color::srgb(0.18, 0.49, 0.82); // blue = left-clawed
const CLAW_RIGHT: Color = Color::srgb(0.97, 0.82, 0.17); // yellow = right-clawed

/// The big claw's colour: the handedness tell.
pub(crate) fn claw_color(handed: Handedness) -> Color {
    match handed {
        Handedness::Left => CLAW_LEFT,
        Handedness::Right => CLAW_RIGHT,
    }
}

pub(crate) fn body_color(kind: CrabKind) -> Color {
    match kind {
        CrabKind::Common => Color::srgb(0.91, 0.50, 0.29),
        CrabKind::Juvenile => Color::srgb(0.96, 0.76, 0.42),
        CrabKind::Giant => Color::srgb(0.70, 0.25, 0.17),
        CrabKind::Molting => Color::srgb(0.61, 0.48, 0.82),
        CrabKind::Golden => Color::srgb(1.0, 0.88, 0.20),
        CrabKind::Sparkling => Color::srgb(0.75, 0.95, 1.0),
    }
}

/// The side of the square a crab's sprites are drawn in: the body, and the
/// big claw laid over it in the same frame. The sprites are square with
/// the legs reaching toward the corners, so the side is wider than the
/// shell's footprint ([`body_size`]), which is what the shadow is cut to.
pub(crate) fn sprite_side(kind: CrabKind) -> f32 {
    body_size(kind).x * 1.45
}

/// Which way up a crab's sprites are drawn. They are authored right-
/// handed, big claw on the crab's right; a left-handed crab is the same
/// crab mirrored across its own heading.
pub(crate) fn mirrored(handed: Handedness) -> bool {
    match handed {
        Handedness::Left => true,
        Handedness::Right => false,
    }
}

pub(crate) fn body_size(kind: CrabKind) -> Vec2 {
    match kind {
        CrabKind::Giant => Vec2::new(TILE * 0.80, TILE * 0.62),
        CrabKind::Juvenile => Vec2::new(TILE * 0.42, TILE * 0.34),
        CrabKind::Common | CrabKind::Molting | CrabKind::Golden | CrabKind::Sparkling => {
            Vec2::new(TILE * 0.56, TILE * 0.44)
        }
    }
}

/// Spawn sprites for new crabs, despawn sprites for banked ones.
pub fn sync_crab_sprites(
    mut commands: Commands,
    sim: Res<Sim>,
    art: Res<Art>,
    mut live: Local<HashMap<u32, Crab>>,
    existing: Query<(Entity, &CrabSprite)>,
) {
    let board = &sim.0;
    // Reused buffer: rebuilt each frame without reallocating. Bank/eaten
    // storytelling happens in sim_events + effects; this system only keeps
    // sprites in step with the population.
    live.clear();
    live.extend(board.crabs().iter().map(|c| (c.id, *c)));
    for (entity, sprite) in &existing {
        if live.remove(&sprite.id).is_none() {
            commands.entity(entity).despawn();
        }
    }
    // Remaining entries are crabs without a sprite yet.
    for (&id, crab) in live.iter() {
        let pos = layout::creature_pos(board, crab.tile, crab.dir, crab.progress);
        let size = body_size(crab.kind);
        let side = Vec2::splat(sprite_side(crab.kind));
        let claw = claw_color(crab.handed);
        let flip_y = mirrored(crab.handed);
        commands
            .spawn((
                CrabSprite {
                    id,
                    kind: crab.kind,
                    shade: shade_of(id),
                },
                Crowding::default(),
                Sprite {
                    image: art.crab.clone(),
                    color: shell_color(crab.kind, shade_of(id)),
                    custom_size: Some(side),
                    flip_y,
                    ..default()
                },
                Transform::from_translation(pos.extend(layout::z::CREATURE))
                    .with_rotation(layout::dir_rotation(crab.dir)),
            ))
            .with_children(|parent| {
                parent.spawn((
                    CreatureShadow,
                    Sprite {
                        image: art.shadow.clone(),
                        custom_size: Some(Vec2::new(size.x * 1.35, size.y * 1.15)),
                        ..default()
                    },
                    Transform::from_translation(Vec3::new(0.0, 0.0, -0.5)),
                ));
                // The big claw: the handedness tell, and the one thing a
                // player reads a crab by. Drawn in the body's own frame, so
                // it sits where the body's arm reaches whatever the crab's
                // size, and tinted by hand rather than by kind.
                parent.spawn((
                    Sprite {
                        image: art.claw.clone(),
                        color: claw,
                        custom_size: Some(side),
                        flip_y,
                        ..default()
                    },
                    Transform::from_translation(Vec3::new(0.0, 0.0, 0.1)),
                ));
            });
    }
}

/// A crab Crab Monopoly is carrying home, by id: drawn from the sim's own
/// flight ([`crate::sim::Sweeping`]), since it banks on the tick it lands.
#[derive(Component)]
pub struct SweepSprite(u32);

/// Draw the crabs a Crab Monopoly sweep is carrying home: glowing gold
/// where they were picked up until they set off, then thrown over the
/// beach into the banker's castle, each landing on the tick it banks.
pub fn draw_sweeps(
    mut commands: Commands,
    sim: Res<Sim>,
    art: Res<Art>,
    settings: Res<crate::app::settings::GameSettings>,
    mut tween: Tween,
    mut sprites: Query<(Entity, &SweepSprite, &mut Transform, &mut Sprite)>,
) {
    let board = &sim.0;
    let flights = board.sweeping();
    if flights.is_empty() && sprites.is_empty() {
        return;
    }
    let time = &tween.time;
    let alpha = smoothing_alpha(
        board.ticks(),
        &mut tween.watch,
        time.delta_secs(),
        &tween.fixed_time,
    );
    // The last tick run, and how far into the next one this frame is.
    let now = board.ticks() as f32 - 1.0 + alpha;
    // A steady glow for reduced motion: the sweep is the rule, so the
    // crabs are still drawn, only not pulsing.
    let glow = if settings.reduced_motion {
        0.6
    } else {
        0.5 + 0.3 * (time.elapsed_secs() * 9.0).sin()
    };
    let mut drawn: Vec<u32> = Vec::with_capacity(flights.len());
    for (entity, sweep, mut transform, mut sprite) in &mut sprites {
        let Some(flight) = flights.iter().find(|f| f.crab.id == sweep.0) else {
            commands.entity(entity).despawn();
            continue;
        };
        drawn.push(sweep.0);
        let crab = &flight.crab;
        let from = layout::creature_pos(board, crab.tile, crab.dir, crab.progress);
        let keep = board
            .castle_of(flight.owner)
            .map_or(from, |(x, y)| layout::tile_center(board, x, y));
        let shell = shell_color(crab.kind, shade_of(crab.id));
        let launch = flight.launch as f32;
        if now < launch {
            transform.translation = from.extend(layout::z::CREATURE + 0.3);
            transform.scale = Vec3::ONE;
            sprite.color = shell.mix(&palette::GOLD, glow);
            continue;
        }
        let span = (flight.lands - flight.launch).max(1) as f32;
        let progress = ((now - launch) / span).clamp(0.0, 1.0);
        // Higher the further it goes, but never off the top of the beach:
        // a crab thrown corner to corner left the board at a third of it.
        let lift = (from.distance(keep) * 0.35).min(TILE * 1.2);
        let (at, scale) = effects::arc(from, keep, lift, progress);
        // Over the fences while it is in the air.
        transform.translation = at.extend(layout::z::WALL + 0.3);
        transform.scale = Vec3::splat(scale);
        sprite.color = shell;
    }
    for flight in flights {
        let crab = &flight.crab;
        if drawn.contains(&crab.id) {
            continue;
        }
        let pos = layout::creature_pos(board, crab.tile, crab.dir, crab.progress);
        let side = Vec2::splat(sprite_side(crab.kind));
        let flip_y = mirrored(crab.handed);
        commands
            .spawn((
                SweepSprite(crab.id),
                Sprite {
                    image: art.crab.clone(),
                    color: shell_color(crab.kind, shade_of(crab.id)).mix(&palette::GOLD, glow),
                    custom_size: Some(side),
                    flip_y,
                    ..default()
                },
                Transform::from_translation(pos.extend(layout::z::CREATURE + 0.3))
                    .with_rotation(layout::dir_rotation(crab.dir)),
            ))
            .with_child((
                Sprite {
                    image: art.claw.clone(),
                    color: claw_color(crab.handed),
                    custom_size: Some(side),
                    flip_y,
                    ..default()
                },
                Transform::from_translation(Vec3::new(0.0, 0.0, 0.1)),
            ));
    }
}

/// Smoothing factor for creature sprites. Normally the fixed-clock overstep
/// fraction; when the sim has been frozen for clearly longer than one fixed
/// period (pause, results, round over), hold at the final position instead of
/// oscillating. The 1.5-period threshold is the load-bearing part: at 60+ fps
/// most render frames legitimately fall *between* ticks, and treating those
/// as frozen snaps sprites forward on alternating frames (visible chop).
fn smoothing_alpha(
    ticks: u64,
    watch: &mut (u64, f32),
    delta_secs: f32,
    fixed_time: &Time<Fixed>,
) -> f32 {
    let (last_tick, frozen_for) = watch;
    if ticks == *last_tick {
        *frozen_for += delta_secs;
    } else {
        *last_tick = ticks;
        *frozen_for = 0.0;
    }
    if *frozen_for > fixed_time.timestep().as_secs_f32() * 1.5 {
        1.0
    } else {
        fixed_time.overstep_fraction()
    }
}

/// The clocks a creature is drawn between ticks by: the frame's, the
/// sim's fixed one, and the watch [`smoothing_alpha`] keeps on the tick.
#[derive(bevy::ecs::system::SystemParam)]
pub struct Tween<'w, 's> {
    time: Res<'w, Time>,
    fixed_time: Res<'w, Time<Fixed>>,
    watch: Local<'s, (u64, f32)>,
}

/// A crab's sprite, as the interpolation moves and dresses it.
type CrabBody = (
    &'static CrabSprite,
    &'static mut Crowding,
    &'static mut Transform,
    &'static mut Sprite,
    &'static Children,
);

/// The crabs on screen and the shadows under them.
#[derive(bevy::ecs::system::SystemParam)]
pub struct CrabSprites<'w, 's> {
    bodies: Query<'w, 's, CrabBody, Without<CreatureShadow>>,
    shadows: Query<'w, 's, &'static mut Transform, (With<CreatureShadow>, Without<CrabSprite>)>,
}

/// Interpolate each crab sprite between its previous and current sim position.
pub fn interpolate_crabs(
    sim: Res<Sim>,
    fx: effects::Fx,
    tween: Tween,
    mut glint_clock: Local<f32>,
    mut by_id: Local<HashMap<u32, Crab>>,
    mut crowds: Local<HashMap<u32, usize>>,
    crabs: CrabSprites,
) {
    let effects::Fx {
        mut commands,
        art,
        mut rng,
        settings,
    } = fx;
    let Tween {
        time,
        fixed_time,
        mut watch,
    } = tween;
    let CrabSprites {
        bodies: mut sprites,
        mut shadows,
    } = crabs;
    let board = &sim.0;
    let alpha = smoothing_alpha(board.ticks(), &mut watch, time.delta_secs(), &fixed_time);
    by_id.clear();
    by_id.extend(board.crabs().iter().map(|c| (c.id, *c)));
    // Precious crabs glint on one clock: they twinkle together, and the
    // scatter `glint` puts on each star's position keeps that from reading
    // as a metronome.
    *glint_clock += time.delta_secs();
    let glint_now = *glint_clock >= 0.22;
    if glint_now {
        *glint_clock = 0.0;
    }
    // During a molting lure every loose crab ignores arrows; tint them all
    // toward the luring player's colour so the takeover is visible.
    let lure_tint = board.lure().map(|(owner, _)| palette::player_color(owner));
    count_neighbours(board, &mut crowds);
    // The same easing whatever the frame rate: about a third of a second
    // to settle into, or out of, a crowd.
    let ease = 1.0 - (-time.delta_secs() * 8.0).exp();
    for (sprite, mut crowding, mut transform, mut body, children) in &mut sprites {
        let Some(crab) = by_id.get(&sprite.id) else {
            continue; // despawns this frame
        };
        let base = shell_color(crab.kind, sprite.shade);
        body.color = match lure_tint {
            Some(tint) => base.mix(&tint, 0.55),
            None => base,
        };
        let prev = layout::pose_pos(board, crab.prev);
        let curr = layout::pose_pos(board, crab.pose());
        // A wrap-around crossing is a teleport, not a walk: snap, don't slide.
        let pos = if prev.distance(curr) > TILE * 2.0 {
            curr
        } else {
            prev.lerp(curr, alpha)
        };
        let (dx, dy) = crab.dir.offset();
        // Sim y runs down, world y runs up.
        let heading = Vec2::new(dx as f32, -(dy as f32));
        let neighbours = crowds.get(&sprite.id).copied().unwrap_or(0);
        let (spread, shrink) = crowd_target(neighbours, sprite.id, heading);
        let (was_spread, was_shrink) = (crowding.spread, crowding.shrink);
        crowding.spread = was_spread + (spread - was_spread) * ease;
        crowding.shrink = was_shrink + (shrink - was_shrink) * ease;
        transform.translation = (pos + crowding.spread).extend(layout::z::CREATURE);
        // Scuttle: a small heading wiggle while actually moving, phased per
        // crab so a crowd shimmers instead of marching.
        let moving = prev != curr;
        let wobble = if moving {
            (time.elapsed_secs() * 11.0 + f32::from(sprite.id as u16 % 32)).sin() * 0.06
        } else {
            0.0
        };
        transform.rotation = layout::dir_rotation(crab.dir) * Quat::from_rotation_z(wobble);
        // Two-frame leg cycle while walking.
        let frame_b = moving
            && ((time.elapsed_secs() * 7.0 + f32::from(sprite.id as u16 % 8)) as u32)
                .is_multiple_of(2);
        let wanted = if frame_b { &art.crab_b } else { &art.crab };
        if body.image != *wanted {
            body.image = wanted.clone();
        }
        // Drawn a little smaller in a crowd, and molting crabs pulse
        // gently on top of that: they are worth chasing.
        let pulse = if sprite.kind == CrabKind::Molting {
            1.0 + (time.elapsed_secs() * 5.0).sin() * 0.06
        } else {
            1.0
        };
        transform.scale = Vec3::splat(pulse * (1.0 - crowding.shrink));
        // The shadow: pushed out from under the body, the same way as
        // every other thing standing on this sand, since one sitting
        // exactly beneath the crab is never seen.
        //
        // After the pulse, and divided by it: a child's translation is in
        // the parent's frame, so a molting crab would otherwise swing its
        // shadow in time with its own breathing.
        let body_scale = transform.scale.x.max(f32::EPSILON);
        for child in children {
            if let Ok(mut shadow) = shadows.get_mut(*child) {
                shadow.translation = unturned(&transform, layout::SUN / body_scale, -0.5);
            }
        }
        // Sparkling and golden crabs actually sparkle. The golden one is
        // fifty points walking, so it draws a ribbon of sparks behind it
        // and a table of four can see which way the jackpot is heading.
        if glint_now {
            match sprite.kind {
                CrabKind::Sparkling => effects::glint(
                    &mut commands,
                    &mut rng,
                    &art,
                    curr,
                    Color::srgba(0.8, 0.95, 1.0, 0.95),
                ),
                CrabKind::Golden => {
                    effects::glint(
                        &mut commands,
                        &mut rng,
                        &art,
                        curr,
                        Color::srgba(1.0, 0.9, 0.3, 0.95),
                    );
                    if moving && !settings.reduced_motion {
                        let (dx, dy) = crab.dir.offset();
                        // Sim y runs down, world y runs up.
                        let heading = Vec2::new(dx as f32, -(dy as f32));
                        effects::spark_trail(
                            &mut commands,
                            &mut rng,
                            &art,
                            curr - heading * TILE * 0.3,
                            -heading,
                        );
                    }
                }
                CrabKind::Common | CrabKind::Juvenile | CrabKind::Giant | CrabKind::Molting => {}
            }
        }
    }
}

/// Spawn sprites for new gulls, despawn sprites for departed ones.
pub fn sync_gull_sprites(
    sim: Res<Sim>,
    fx: effects::Fx,
    mut live: Local<HashMap<u32, Gull>>,
    // The gulls that were on the board last frame, and the clock they were
    // on. A *sprite* being new is not a gull arriving: a level with gulls
    // written into it, a retry, a resumed round and an editor test run all
    // wipe the sprites and rebuild them.
    mut before: Local<(Option<u64>, Vec<u32>)>,
    existing: Query<(Entity, &GullSprite)>,
) {
    let effects::Fx {
        mut commands,
        art,
        mut rng,
        settings,
    } = fx;
    let board = &sim.0;
    // A clock that has run backwards is a different board, whose gull ids
    // start again at zero, and a board at tick zero has not run at all:
    // nothing on either has "arrived", the birds on it are the ones it was
    // written with. So the memory is reseeded from those birds rather than
    // emptied, which otherwise puffs sand under every pre-placed gull.
    let (last_ticks, seen) = &mut *before;
    let fresh = board.ticks() == 0 || last_ticks.is_none_or(|last| board.ticks() < last);
    if fresh {
        seen.clear();
        seen.extend(board.gulls().iter().map(|g| g.id));
    }
    *last_ticks = Some(board.ticks());
    live.clear();
    live.extend(board.gulls().iter().map(|g| (g.id, *g)));
    for (entity, sprite) in &existing {
        if live.remove(&sprite.0).is_none() {
            commands.entity(entity).despawn();
        }
    }
    for (&id, gull) in live.iter() {
        let pos = layout::creature_pos(board, gull.tile, gull.dir, gull.progress);
        // A gull arriving is the worst news on the beach and used to
        // appear in silence at the edge of the sand.
        if !settings.reduced_motion && !seen.contains(&id) {
            kick_up(&mut commands, &mut rng, &art, pos);
        }
        commands
            .spawn((
                GullSprite(id),
                Sprite {
                    image: art.gull.clone(),
                    custom_size: Some(Vec2::splat(TILE * 0.78)),
                    ..default()
                },
                Transform::from_translation(pos.extend(layout::z::CREATURE + 0.2))
                    .with_rotation(layout::dir_rotation(gull.dir)),
            ))
            .with_children(|parent| {
                parent.spawn((
                    CreatureShadow,
                    Sprite {
                        image: art.shadow.clone(),
                        custom_size: Some(Vec2::new(TILE * 0.72, TILE * 0.54)),
                        ..default()
                    },
                    Transform::from_translation(Vec3::new(0.0, 0.0, -0.5)),
                ));
            });
    }
    seen.clear();
    seen.extend(board.gulls().iter().map(|gull| gull.id));
}

/// A gull's sprite, as the interpolation moves and dresses it.
type GullBody = (
    &'static GullSprite,
    &'static mut Transform,
    &'static mut Sprite,
    &'static Children,
);

/// The gulls on screen and the shadows under them.
#[derive(bevy::ecs::system::SystemParam)]
pub struct GullSprites<'w, 's> {
    bodies: Query<'w, 's, GullBody, Without<CreatureShadow>>,
    shadows: Query<'w, 's, (&'static mut Transform, &'static mut Sprite), With<CreatureShadow>>,
}

/// Interpolate gull sprites, and fly the flying ones.
///
/// A gull's hop is two to four tiles in a straight line (spec §3.5), and
/// the sim says nothing about height: it is on a tile or it is not. The
/// altitude here is invented whole, out of how much of the hop is left,
/// and it is what turns a bird sliding over the sand into a bird that
/// takes off, crosses, and comes down.
///
/// It also buys the telegraph for free. The shadow is pinned to the
/// ground, so it slides out from under the bird as it climbs and comes
/// back under it as it drops: a tile from landing, its shadow is already
/// on the tile it will land on.
///
/// The flight scale is kept modest. Walls draw above creatures, but a
/// border plank is thirteen pixels of a tile-sized frame, so a gull scaled
/// far past its tile hangs over the edge of the board with nothing to
/// occlude it.
pub fn interpolate_gulls(
    sim: Res<Sim>,
    fx: effects::Fx,
    tween: Tween,
    mut by_id: Local<HashMap<u32, Gull>>,
    // Gulls currently in the air. Presence is the flight: a gull that
    // turns up here without an entry has just taken off, and one whose
    // entry outlives its flight has just landed.
    mut aloft: Local<HashMap<u32, Flight>>,
    gulls: GullSprites,
) {
    let effects::Fx {
        mut commands,
        art,
        mut rng,
        settings,
    } = fx;
    let Tween {
        time,
        fixed_time,
        mut watch,
    } = tween;
    let GullSprites {
        bodies: mut sprites,
        mut shadows,
    } = gulls;
    let board = &sim.0;
    // Read before `smoothing_alpha`, which writes this frame's tick into
    // the watch: after it, the two always agree and the test below is dead.
    let fresh = board.ticks() < watch.0 || board.ticks() == 0;
    let alpha = smoothing_alpha(board.ticks(), &mut watch, time.delta_secs(), &fixed_time);
    by_id.clear();
    by_id.extend(board.gulls().iter().map(|g| (g.id, *g)));
    // A clock that has run backwards is a different board, and gull ids
    // start again at zero on every one of them. Pruned by id alone, a
    // recycled id inherits a latched descent and a frozen altitude, and the
    // bird slides flat over the sand with its shadow pinned under it.
    if fresh {
        aloft.clear();
    }
    aloft.retain(|id, _| by_id.contains_key(id));
    let t = time.elapsed_secs();
    for (sprite, mut transform, mut image, children) in &mut sprites {
        let Some(gull) = by_id.get(&sprite.0) else {
            continue;
        };
        let prev = layout::pose_pos(board, gull.prev);
        let curr = layout::pose_pos(board, gull.pose());
        let pos = if prev.distance(curr) > TILE * 2.0 {
            curr
        } else {
            prev.lerp(curr, alpha)
        };
        transform.translation = pos.extend(layout::z::CREATURE + 0.2);
        let phase = f32::from(sprite.0 as u16 % 32);
        let altitude = match gull.state {
            GullState::Walking => {
                aloft.remove(&sprite.0);
                0.0
            }
            GullState::Flying { remaining } => {
                let calm = settings.reduced_motion;
                let flight = aloft.entry(gull.id).or_insert_with(|| {
                    // Just off the ground: the sand it pushed away.
                    if !calm {
                        kick_up(&mut commands, &mut rng, &art, pos);
                    }
                    Flight {
                        start: remaining,
                        altitude: 0.0,
                        descending: false,
                    }
                });
                let across = f32::from(gull.progress) / f32::from(crate::sim::SUBUNITS_PER_TILE);
                flight.height(remaining, across)
            }
        };
        let flying = altitude > 0.0 || matches!(gull.state, GullState::Flying { .. });
        // Spread-wing art in flight, and it flaps: the upstroke frame for
        // the rising half of the same wing-beat the scale pulses with
        // below, so the two agree (write-on-change).
        let beat = (t * 16.0 + phase).sin();
        let wanted = match (flying, beat > 0.35) {
            (true, true) => &art.gull_fly_b,
            (true, false) => &art.gull_fly,
            (false, _) => &art.gull,
        };
        if image.image != *wanted {
            image.image = wanted.clone();
        }
        let (scale, waddle) = if flying {
            (1.0 + 0.22 * altitude + beat * 0.05, 0.0)
        } else if prev == curr {
            (1.0, 0.0)
        } else {
            (1.0, (t * 9.0 + phase).sin() * 0.05)
        };
        transform.rotation = layout::dir_rotation(gull.dir) * Quat::from_rotation_z(waddle);
        transform.scale = Vec3::splat(scale);
        for child in children {
            let Ok((mut shadow_tf, mut shadow_sprite)) = shadows.get_mut(*child) else {
                continue;
            };
            // Left behind on the ground, further out the higher the bird
            // is, with a slow circling drift on top of the drop: the cue
            // that it is airborne. A walking gull's shadow sits at its
            // feet, at the offset everything else on the beach casts.
            let drift = Vec2::new((t * 2.1 + phase).cos() * 2.5, (t * 1.7 + phase).sin() * 2.5);
            let drop = 26.0 * altitude;
            let world = layout::SUN + Vec2::new(-drop * 0.5, -drop) + drift * altitude;
            // Divided by the parent's scale for the same reason the
            // shadow's own scale is: a child's translation is in the
            // parent's frame, so a bird pulsing at its wing-beat would
            // otherwise drag its shadow back and forth under it.
            shadow_tf.translation = unturned(&transform, world / scale, -0.5);
            // Compensating the parent's scale keeps the shadow the size of
            // the bird's footprint rather than of the bird.
            shadow_tf.scale = Vec3::splat((1.0 - 0.25 * altitude) / scale);
            // It stays dark as the bird climbs: the shadow is the warning,
            // and a warning that fades as the danger nears is no warning.
            shadow_sprite.color = Color::srgba(1.0, 1.0, 1.0, 1.0 - 0.15 * altitude);
        }
    }
}

/// One gull's hop, as the render layer sees it.
///
/// The sim never says how high a gull is - it is on a tile or it is not -
/// so the height is invented here out of how much of the hop is left, and
/// carried between frames, because a bird that has started coming down
/// must not go back up.
pub struct Flight {
    /// Tiles left when it took off.
    start: u8,
    /// Where it was last frame.
    altitude: f32,
    /// Whether it has begun its descent. Latched, never cleared: it is
    /// only ever true for the rest of one hop.
    descending: bool,
}

impl Flight {
    /// How high the bird is, `across` of the way over a tile with
    /// `remaining` tiles of hop still to go.
    ///
    /// The load-bearing part is that the last airborne tile is the one with
    /// `remaining == 1`, not zero. The sim lands a gull on the tick its
    /// counter would reach zero, so `Flying { remaining: 0 }` is a state no
    /// frame observes: reading the descent off it holds the bird at full
    /// height and then drops it in one frame.
    ///
    /// A gull whose landing tile turns out to be rock or kelp is given one
    /// more tile to glide, and its `across` starts over: without the latch
    /// it would bob back to full height for that tile.
    fn height(&mut self, remaining: u8, across: f32) -> f32 {
        if remaining <= 1 {
            self.descending = true;
        }
        let climb = if remaining >= self.start { across } else { 1.0 };
        let descend = if remaining <= 1 { 1.0 - across } else { 1.0 };
        let wanted = climb.min(descend).clamp(0.0, 1.0);
        self.altitude = if self.descending {
            wanted.min(self.altitude)
        } else {
            wanted
        };
        self.altitude
    }
}

/// A world-space offset expressed in the local space of a sprite that has
/// been turned to face its heading.
///
/// Creature sprites are rotated to their direction and their shadows are
/// children of them, so a shadow given a plain local offset swings round
/// the creature as it turns corners. Undoing the parent's rotation is what
/// keeps the sun still while the crab walks under it.
fn unturned(parent: &Transform, world: Vec2, z: f32) -> Vec3 {
    let local = parent.rotation.inverse() * world.extend(0.0);
    Vec3::new(local.x, local.y, z)
}

/// The sand a gull throws down when it beats its way off the beach.
fn kick_up(commands: &mut Commands, rng: &mut effects::VisualRng, art: &Art, pos: Vec2) {
    effects::burst(
        commands,
        rng,
        &effects::Burst {
            image: art.puff.clone(),
            pos,
            color: Color::srgba(0.93, 0.87, 0.7, 0.75),
            count: 5,
            size: 13.0,
            speed: 52.0,
            gravity: 80.0,
        },
    );
}

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

    /// A left-handed crab is the right-handed drawing mirrored, and the two
    /// hands wear different claws: the tell a player reads a crab by.
    #[test]
    fn a_left_handed_crab_is_the_other_one_mirrored() {
        assert!(mirrored(Handedness::Left));
        assert!(!mirrored(Handedness::Right));
        assert_ne!(claw_color(Handedness::Left), claw_color(Handedness::Right));
    }

    /// A crab's square is bigger than its shell, legs out to the corners,
    /// and the kinds keep their sizes: a giant over a common over a young.
    #[test]
    fn a_crab_is_drawn_bigger_than_its_shell_and_in_its_size() {
        for kind in CrabKind::ALL {
            assert!(sprite_side(kind) > body_size(kind).x, "{kind:?}");
        }
        let side = sprite_side;
        assert!(side(CrabKind::Giant) > side(CrabKind::Common));
        assert!(side(CrabKind::Common) > side(CrabKind::Juvenile));
    }

    /// How crowded a crab is climbs with its company and stops at full:
    /// nothing alone, a third with one neighbour, full at three, no further.
    #[test]
    fn a_crowd_fills_up_at_three_neighbours() {
        assert_eq!(crowd_level(0), 0.0);
        assert!((crowd_level(1) - 1.0 / 3.0).abs() < 1e-6);
        assert_eq!(crowd_level(3), 1.0);
        assert_eq!(crowd_level(20), 1.0);
    }

    /// A crab on its own is drawn exactly where it is; in a crowd it moves
    /// across its heading, never along it, by at most the outer lane, and
    /// always to the same side for the same crab.
    #[test]
    fn a_crowd_fans_out_across_its_heading_and_a_lone_crab_stays_put() {
        let east = Vec2::X;
        for id in 0..40 {
            assert_eq!(
                crowd_target(0, id, east),
                (Vec2::ZERO, 0.0),
                "crab {id} alone"
            );
            let (spread, shrink) = crowd_target(5, id, east);
            assert_eq!(spread.x, 0.0, "crab {id} moved along its heading");
            assert!(spread.y.abs() <= CROWD_SPREAD + 1e-4, "{spread}");
            assert_eq!(shrink, CROWD_SHRINK, "a pile is a full crowd");
            assert_eq!(
                crowd_target(5, id, east),
                (spread, shrink),
                "same crab, same lane"
            );
        }
        // One neighbour is a third of a crowd.
        let (_, some) = crowd_target(1, 3, east);
        assert!((some - CROWD_SHRINK / 3.0).abs() < 1e-6);
        // The five lanes are all in use across a crowd of crabs.
        let lanes: std::collections::BTreeSet<i32> =
            (0..40).map(|id| (crowd_lane(id) * 2.0) as i32).collect();
        assert_eq!(lanes.len(), 5, "{lanes:?}");
    }

    /// A crab keeps its shell for as long as it lives. The shade is a hash
    /// of the id rather than a draw, so a sprite rebuilt around a crab, as
    /// they constantly are, does not hand it a new colour.
    #[test]
    fn a_crab_keeps_the_shell_it_was_born_with() {
        for id in [0u32, 1, 7, 64, 1_000, 65_535, u32::MAX] {
            assert_eq!(shade_of(id), shade_of(id), "id {id} drifted");
            let shade = shade_of(id);
            assert!(
                (-SHADE_SPREAD..=SHADE_SPREAD).contains(&shade),
                "id {id} strayed off the band: {shade}"
            );
        }
    }

    /// And the crowd has to actually be a crowd: a hash that answered the
    /// same for every id would compile, pass the test above, and leave
    /// twenty identical crabs on the sand.
    #[test]
    fn a_crowd_is_not_twenty_copies_of_one_crab() {
        let shades: Vec<f32> = (0..40).map(shade_of).collect();
        let spread = shades.iter().fold(f32::MIN, |a, &b| a.max(b))
            - shades.iter().fold(f32::MAX, |a, &b| a.min(b));
        assert!(
            spread > SHADE_SPREAD,
            "forty crabs covered only {spread} of the band"
        );
    }

    /// A shell is its kind's colour, nudged - never another kind's.
    ///
    /// The kinds are told apart by colour on a crowded beach, and what that
    /// needs is not a small *number* (the nudge is a perceptual lighten, so
    /// a saturated gold moves a long way in blue for little visible change)
    /// but a guarantee about neighbours: whatever the shade does, the shell
    /// must still be nearer its own kind than any other.
    #[test]
    fn a_shade_never_carries_a_shell_into_another_kind() {
        const KINDS: [CrabKind; 6] = [
            CrabKind::Common,
            CrabKind::Juvenile,
            CrabKind::Giant,
            CrabKind::Molting,
            CrabKind::Golden,
            CrabKind::Sparkling,
        ];
        let apart = |a: Color, b: Color| {
            let (a, b) = (a.to_srgba(), b.to_srgba());
            ((a.red - b.red).powi(2) + (a.green - b.green).powi(2) + (a.blue - b.blue).powi(2))
                .sqrt()
        };
        for kind in KINDS {
            for id in 0..40u32 {
                let shell = shell_color(kind, shade_of(id));
                let own = apart(shell, body_color(kind));
                for other in KINDS.into_iter().filter(|&k| k != kind) {
                    assert!(
                        own < apart(shell, body_color(other)),
                        "a shaded {kind:?} (id {id}) is nearer {other:?} than itself"
                    );
                }
                let srgba = shell.to_srgba();
                for channel in [srgba.red, srgba.green, srgba.blue] {
                    assert!((0.0..=1.0).contains(&channel), "{kind:?} left the channel");
                }
            }
        }
    }

    /// The sun stays put while the creature turns: a shadow given a plain
    /// local offset swings round its owner at every corner, and `unturned`
    /// has to undo that exactly, for every heading.
    #[test]
    fn a_shadow_holds_its_bearing_through_every_turn() {
        for dir in [
            crate::sim::Direction::Up,
            crate::sim::Direction::Down,
            crate::sim::Direction::Left,
            crate::sim::Direction::Right,
        ] {
            let parent = Transform::from_rotation(layout::dir_rotation(dir));
            let local = unturned(&parent, layout::SUN, -0.5);
            // Put back through the parent's own rotation, it is the world
            // offset again: that is the whole contract.
            let world = parent.rotation * local;
            assert!(
                world.truncate().distance(layout::SUN) < 1e-4,
                "{dir:?} bent the sun to {:?}",
                world.truncate()
            );
            assert_eq!(local.z, -0.5, "and the layer is left alone");
        }
    }

    /// The last tile a gull flies is the one with `remaining == 1`, because
    /// the sim lands it on the tick the counter would reach zero. Reading
    /// the descent off zero holds the bird at full height and then drops it
    /// in a single frame.
    #[test]
    fn a_gull_climbs_once_and_only_ever_comes_down() {
        let mut flight = Flight {
            start: 3,
            altitude: 0.0,
            descending: false,
        };
        assert_eq!(flight.height(3, 0.0), 0.0, "leaves the sand at nothing");
        assert!((flight.height(3, 0.5) - 0.5).abs() < 1e-6, "climbing");
        assert_eq!(flight.height(2, 0.5), 1.0, "level across the middle");
        assert!(
            (flight.height(1, 0.25) - 0.75).abs() < 1e-6,
            "and coming down over the last tile, which is `remaining == 1`"
        );
        let low = flight.height(1, 0.9);
        assert!(low < 0.15, "all but on the sand: {low}");
        // A rock or kelp under the landing tile buys one more tile, and
        // its `across` starts over. The bird glides on; it does not bob.
        assert!(flight.height(1, 0.0) <= low, "went back up to {low}");
    }

    /// A 30 Hz fixed clock with `overstep` of a period already accumulated,
    /// so the "between ticks" answer is a fraction the "frozen" answer
    /// cannot be mistaken for.
    fn fixed_clock(overstep: f32) -> Time<Fixed> {
        let mut fixed = Time::<Fixed>::from_hz(30.0);
        fixed.accumulate_overstep(fixed.timestep().mul_f32(overstep));
        fixed
    }

    /// The 1.5-period threshold is the load-bearing part: a render frame
    /// that falls between ticks at 60+ fps is not a frozen sim, and calling
    /// it one snaps sprites forward on alternating frames. So a sim that
    /// has not ticked for 1.2 periods still interpolates, 1.6 periods holds
    /// at the final position, and the first new tick starts the count over.
    #[test]
    fn the_sim_counts_as_frozen_only_past_one_and_a_half_periods() {
        let fixed = fixed_clock(0.4);
        let period = fixed.timestep().as_secs_f32();
        let between = fixed.overstep_fraction();
        assert!((0.0..1.0).contains(&between), "a fraction, got {between}");
        let mut watch = (5u64, 0.0f32);
        // Three frames of 0.4 periods: 1.2 periods without a tick.
        let mut alpha = 0.0;
        for _ in 0..3 {
            alpha = smoothing_alpha(5, &mut watch, period * 0.4, &fixed);
        }
        assert_eq!(
            alpha, between,
            "1.2 periods without a tick still interpolates"
        );
        // One more frame makes 1.6 periods: frozen, hold the final position.
        let alpha = smoothing_alpha(5, &mut watch, period * 0.4, &fixed);
        assert_eq!(alpha, 1.0, "1.6 periods without a tick holds still");
        // The sim ticks: the frozen count resets and interpolation resumes.
        let alpha = smoothing_alpha(6, &mut watch, period * 0.4, &fixed);
        assert_eq!(alpha, between, "a fresh tick resets the frozen count");
        assert_eq!(watch, (6, 0.0), "the watch follows the new tick");
    }
}