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
//! The postcard behind the menu: a beach at rest.
//!
//! Bottom to top: sand furnished with the props the game is played with,
//! the waterline, a sea with a rolling swell, and sky. Crabs scuttle the
//! sand, gulls glide, clouds drift and little boats cross. None of it is
//! sim: the menu runs no board, and every animation here is decoration
//! driven by frame time.

use super::VisualRng;
use crate::app::art;
use crate::app::palette;
use crate::sim::CrabKind;
use bevy::prelude::*;

/// What kind of ambient traveller is crossing the scene.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum CritterKind {
    Crab,
    Gull,
    Cloud,
    Boat,
}

/// An ambient traveller: signed horizontal speed, an animation clock, its
/// kind, and the lane it bobs around.
#[derive(Component)]
pub struct MenuCritter {
    speed: f32,
    frame_clock: f32,
    kind: CritterKind,
    base_y: f32,
}

/// One short segment of a wave crest. A whole crest is a row of these, each
/// riding the same travelling sine a little further along, so the line
/// undulates instead of merely sliding.
#[derive(Component)]
pub struct WaveSegment {
    /// Resting position; `x` doubles as the phase along the crest.
    base: Vec2,
    /// Height of the swell here, in pixels.
    amp: f32,
    /// Radians per pixel along the shore: how tight the swell is.
    freq: f32,
    /// Radians per second: how fast it rolls.
    speed: f32,
    /// This crest's offset, so lanes do not rise in unison.
    phase: f32,
    /// Peak whiteness of the crest.
    brightness: f32,
}

/// The foam lip at the waterline, which breathes with the tide.
#[derive(Component)]
pub struct ShoreFoam {
    base_y: f32,
}

/// Crests between the horizon and the shore. Near ones are taller,
/// brighter and quicker; far ones flatten out toward the horizon, which is
/// the whole of the perspective trick.
const WAVE_LANES: usize = 7;

/// Segments per crest. Fine enough that the step between neighbours is
/// smaller than a segment is tall, so the row of them reads as one
/// continuous curve.
const WAVE_SEGMENTS: usize = 110;

/// The sand strip's vertical extent, from the bottom of the window.
const SHORE_H: f32 = 208.0;

/// The horizon, as a fraction of window height from the bottom: the sea
/// runs from the shore to here, sky above.
const HORIZON: f32 = 0.62;

/// Marker for the shore backdrop pieces, so a resize can rebuild them
/// without touching the rest of the menu.
#[derive(Component)]
pub struct MenuShore;

/// The dusk over the postcard everywhere but the menu: one translucent
/// sheet between the scene and the cards, so the same beach can stand
/// behind every screen without shouting over the rows in front of it.
#[derive(Component)]
pub struct Scrim;

/// How big the scrim is for a postcard of `size`: the whole window and a
/// margin past it, so no edge of daylight shows round the dusk. One rule
/// for the spawn and for [`refit_shore`], which resizes it beside the
/// shore.
fn scrim_size(size: Vec2) -> Vec2 {
    size + Vec2::splat(80.0)
}

/// Keep the postcard on the screens that want it, and only there.
///
/// The shore itself is spawned and resized by [`refit_shore`]; this system
/// owns the two transitions refit cannot see: leaving the postcard set for
/// a board screen, and the menu against every other postcard screen (the
/// menu gets the scene at full daylight, the rest behind the scrim).
pub fn tend_backdrop(
    mut commands: Commands,
    screen: Res<State<crate::app::Screen>>,
    viewport: crate::app::menu_ui::Viewport,
    shore: Query<Entity, With<MenuShore>>,
    critters: Query<Entity, With<MenuCritter>>,
    scrim: Query<Entity, With<Scrim>>,
) {
    // Reconciled every frame rather than on the transition: the window can
    // be missing on the exact frame the state flips, and a scrim lost to
    // that race would leave a whole screen at full daylight.
    let on_postcard = crate::app::postcard_screen(*screen.get());
    if !on_postcard {
        for entity in shore.iter().chain(critters.iter()).chain(scrim.iter()) {
            commands.entity(entity).despawn();
        }
        return;
    }
    let wants_scrim = *screen.get() != crate::app::Screen::Menu;
    if wants_scrim && scrim.is_empty() {
        let Some(size) = viewport.size() else {
            return;
        };
        commands.spawn((
            Scrim,
            Sprite::from_color(Color::srgba(0.07, 0.09, 0.12, 0.55), scrim_size(size)),
            Transform::from_translation(Vec3::new(0.0, 0.0, 5.0)),
        ));
    } else if !wants_scrim {
        for entity in &scrim {
            commands.entity(entity).despawn();
        }
    }
}

// The postcard is laid out in the window's size in interface units
// ([`crate::app::menu_ui::Viewport::size`]). The camera over it zooms by
// the interface's scale (`boot::fit_camera`), so a postcard that size fills
// the window and every pixel measure in this file is one of the
// interface's own. Laid out in window pixels, the scenery stayed its 720p
// size while the cards grew with the window, and on a big screen the props
// shrank to specks beside them.

/// The whole postcard, bottom to top: sand with shells, a wet line, the
/// open sea up to the horizon, and sky above. World-space sprites behind
/// the UI, in interface units ([`crate::app::menu_ui::Viewport::size`]).
fn spawn_shore(commands: &mut Commands, art: &art::Art, rng: &mut VisualRng, size: Vec2) {
    let (w, h) = (size.x, size.y);
    let bottom = -h / 2.0;
    let horizon = bottom + h * HORIZON;
    let band = |y: f32, height: f32, color: Color, z: f32| {
        (
            MenuShore,
            Sprite::from_color(color, Vec2::new(w + 40.0, height)),
            Transform::from_translation(Vec3::new(0.0, y, z)),
        )
    };
    // A band of one colour with a second washed over it, opaque at one
    // edge and gone at the other.
    //
    // As four flat bands, two of the three joins showed: a hard line across
    // the sky a third of the way up, and another where the sea changed its
    // mind. This is the same four colours with the steps taken out. `ramp`
    // is opaque at its top, so a wash strongest at the *bottom* is turned
    // over, which mirrors it left to right and does not matter here.
    let wash = |y: f32, height: f32, color: Color, z: f32, upward: bool| {
        (
            MenuShore,
            Sprite {
                image: art.ramp.clone(),
                color,
                custom_size: Some(Vec2::new(w + 40.0, height)),
                ..default()
            },
            Transform::from_translation(Vec3::new(0.0, y, z)).with_rotation(if upward {
                Quat::from_rotation_z(std::f32::consts::PI)
            } else {
                Quat::IDENTITY
            }),
        )
    };
    // Sky: pale at the horizon, deepening all the way up.
    let sky_h = h / 2.0 - horizon;
    let sky_mid = horizon + sky_h / 2.0;
    commands.spawn(band(sky_mid, sky_h, Color::srgb(0.62, 0.79, 0.90), 0.0));
    commands.spawn(wash(
        sky_mid,
        sky_h,
        Color::srgb(0.42, 0.65, 0.85),
        0.05,
        false,
    ));
    // Sea: deep at the horizon, brightening toward the shore, and a hazy
    // horizon line where sea and sky meet.
    let sea_top = SHORE_H + 18.0;
    let sea_h = (horizon - bottom) - sea_top;
    let sea_mid = horizon - sea_h / 2.0;
    commands.spawn(band(sea_mid, sea_h, Color::srgb(0.16, 0.36, 0.52), 0.0));
    commands.spawn(wash(
        sea_mid,
        sea_h,
        Color::srgb(0.27, 0.51, 0.63),
        0.02,
        true,
    ));
    commands.spawn(band(horizon, 3.0, Color::srgb(0.72, 0.84, 0.92), 0.1));
    // The beach: dry sand, damper the nearer the water gets, and a wet
    // line where the last wave reached.
    commands.spawn(band(
        bottom + SHORE_H / 2.0,
        SHORE_H,
        Color::srgb(0.86, 0.77, 0.57),
        0.0,
    ));
    commands.spawn(wash(
        bottom + SHORE_H / 2.0,
        SHORE_H,
        Color::srgba(0.70, 0.62, 0.45, 0.65),
        0.02,
        false,
    ));
    commands.spawn(band(
        bottom + SHORE_H + 9.0,
        18.0,
        Color::srgb(0.72, 0.64, 0.47),
        0.0,
    ));
    // The foam lip where the sea meets the sand; it laps in and out.
    let foam_y = bottom + SHORE_H + 20.0;
    commands.spawn((
        MenuShore,
        ShoreFoam { base_y: foam_y },
        Sprite {
            image: art.foam.clone(),
            color: Color::srgba(1.0, 1.0, 1.0, 0.65),
            custom_size: Some(Vec2::new(w + 40.0, 12.0)),
            ..default()
        },
        Transform::from_translation(Vec3::new(0.0, foam_y, 0.1)),
    ));
    spawn_swell(commands, rng, w, sea_top, sea_h, bottom);
    seed_travellers(commands, art, rng, w, h);
    spawn_beach_props(commands, art, rng, w, bottom);
}

/// What a beach prop is made of: one sprite, sometimes a shadow under it.
struct Prop {
    image: Handle<Image>,
    tint: Color,
    size: Vec2,
    /// Ground shadow width, or zero for flat things like shells.
    shadow: f32,
    rotation: f32,
    /// A second layer over the first, tinted: a signpost's paint on its
    /// board.
    paint: Option<(Handle<Image>, Color)>,
}

/// The swell: a stack of crests rolling shoreward. Each is a row of
/// segments sampling one travelling sine, so a crest rises and falls along
/// its length instead of sliding across rigidly.
fn spawn_swell(
    commands: &mut Commands,
    rng: &mut VisualRng,
    w: f32,
    sea_top: f32,
    sea_h: f32,
    bottom: f32,
) {
    let seg_w = (w + 40.0) / WAVE_SEGMENTS as f32;
    for lane in 0..WAVE_LANES {
        // 0 at the horizon, 1 at the beach.
        let near = (lane as f32 + 0.5) / WAVE_LANES as f32;
        let y = bottom + sea_top + sea_h * (1.0 - near) * 0.98;
        let amp = 1.5 + near * near * 9.0;
        // Shorter wavelength close in: a swell you can see the shape of,
        // not a straight streak with a hint of a bend.
        let freq = 0.020 + near * 0.055;
        let speed = 0.6 + near * 2.2;
        let phase = rng.range(0.0, std::f32::consts::TAU);
        let brightness = 0.10 + near * 0.42;
        for segment in 0..WAVE_SEGMENTS {
            let x = -w / 2.0 - 20.0 + seg_w * (segment as f32 + 0.5);
            let base = Vec2::new(x, y);
            commands.spawn((
                MenuShore,
                WaveSegment {
                    base,
                    amp,
                    freq,
                    speed,
                    phase,
                    brightness,
                },
                Sprite::from_color(
                    Color::srgba(1.0, 1.0, 1.0, 0.0),
                    // Overlap slightly: a crest should be a line, not a
                    // dotted one.
                    Vec2::new(seg_w + 1.5, 2.0 + near * 3.0),
                ),
                Transform::from_translation(base.extend(0.2)),
            ));
        }
    }
}

/// Pre-seed the sky and sea so the postcard never starts empty: the ambient
/// travellers are slow and would otherwise take minutes to arrive from the
/// edges.
fn seed_travellers(commands: &mut Commands, art: &art::Art, rng: &mut VisualRng, w: f32, h: f32) {
    for _ in 0..3 {
        let x = rng.range(-w * 0.45, w * 0.45);
        spawn_critter(commands, art, rng, w, h, CritterKind::Cloud, Some(x));
    }
    let boat_x = rng.range(-w * 0.35, w * 0.35);
    spawn_critter(commands, art, rng, w, h, CritterKind::Boat, Some(boat_x));
    let crab_x = rng.range(-w * 0.4, w * 0.4);
    spawn_critter(commands, art, rng, w, h, CritterKind::Crab, Some(crab_x));
}

/// One prop, rolled from the beach's furniture list. `scale` shrinks the
/// far ones; the weights are the mix that makes a beach read as a beach:
/// mostly rocks and kelp, a castle or two, the odd landmark.
fn roll_prop(art: &art::Art, rng: &mut VisualRng, scale: f32) -> Prop {
    match rng.next() % 12 {
        0 | 1 => Prop {
            // A castle from some earlier game, still standing.
            image: art.castle.clone(),
            tint: crate::app::board_render::castle_body(palette::player_color(
                (rng.next() % 4) as u8,
            )),
            size: Vec2::splat(52.0 * scale),
            shadow: 44.0 * scale,
            rotation: 0.0,
            paint: None,
        },
        2 => Prop {
            // Driftwood: the turnstile log, washed up.
            image: art.log.clone(),
            tint: Color::srgb(1.15, 1.12, 1.05),
            size: Vec2::splat(50.0 * scale),
            shadow: 40.0 * scale,
            rotation: if rng.next().is_multiple_of(2) {
                0.0
            } else {
                std::f32::consts::FRAC_PI_2
            },
            paint: None,
        },
        3 | 4 => Prop {
            image: art.kelp.clone(),
            tint: Color::srgba(1.0, 1.0, 1.0, 0.92),
            size: Vec2::splat(rng.range(26.0, 38.0) * scale),
            shadow: 0.0,
            rotation: rng.range(-0.25, 0.25),
            paint: None,
        },
        5 => Prop {
            // A tide pool left behind by the water.
            image: art.pool.clone(),
            tint: Color::srgba(1.0, 1.0, 1.0, 0.9),
            size: Vec2::splat(rng.range(46.0, 62.0) * scale),
            shadow: 0.0,
            rotation: 0.0,
            paint: None,
        },
        6 => Prop {
            // A crab burrow.
            image: art.hole.clone(),
            tint: Color::WHITE,
            size: Vec2::splat(rng.range(26.0, 34.0) * scale),
            shadow: 0.0,
            rotation: 0.0,
            paint: None,
        },
        7 => Prop {
            // A signpost nobody picked up, still pointing somewhere.
            image: art.sign_board.clone(),
            tint: Color::WHITE,
            paint: Some((
                art.sign_paint.clone(),
                palette::player_color((rng.next() % 4) as u8).lighter(0.08),
            )),
            size: Vec2::splat(rng.range(30.0, 38.0) * scale),
            shadow: 24.0 * scale,
            rotation: (rng.next() % 4) as f32 * std::f32::consts::FRAC_PI_2,
        },
        8..=10 => Prop {
            image: art.rock.clone(),
            tint: Color::WHITE,
            size: Vec2::splat(rng.range(22.0, 38.0) * scale),
            shadow: 22.0 * scale,
            rotation: rng.range(0.0, std::f32::consts::TAU),
            paint: None,
        },
        _ => Prop {
            // A shell in the sand.
            image: art.star.clone(),
            tint: Color::srgba(0.95, 0.78, 0.6, 0.85),
            size: Vec2::splat(rng.range(9.0, 15.0) * scale),
            shadow: 0.0,
            rotation: rng.range(0.0, std::f32::consts::TAU),
            paint: None,
        },
    }
}

/// The beach's furniture: the same props the game is played with, so the
/// postcard reads as a board at rest rather than as an empty strip:
/// sandcastles, driftwood turnstiles, kelp, a tide pool, rocks, burrows,
/// and the odd signpost still standing from the last round.
fn spawn_beach_props(
    commands: &mut Commands,
    art: &art::Art,
    rng: &mut VisualRng,
    w: f32,
    bottom: f32,
) {
    // Props are laid along the strip in jittered slots rather than at
    // random: a purely random scatter clumps, and a beach reads better
    // with things spread out and a few deliberate landmarks.
    let slots = ((w / 58.0) as usize).clamp(10, 26);
    for slot in 0..slots {
        let lane = (slot as f32 + 0.5) / slots as f32;
        let x = (lane - 0.5) * w + rng.range(-38.0, 38.0);
        // Up the beach (higher y) is further away: smaller and dimmer.
        // The band starts above the legend card, which owns the very
        // bottom of the window.
        let depth = rng.range(0.0, 1.0);
        let y = bottom + 88.0 + depth * (SHORE_H - 104.0);
        let scale = 1.0 - depth * 0.35;
        let prop = roll_prop(art, rng, scale);
        // Nearer props draw in front, so the strip has depth.
        let z = 0.6 - depth * 0.25;
        if prop.shadow > 0.0 {
            commands.spawn((
                MenuShore,
                Sprite {
                    image: art.shadow.clone(),
                    color: Color::srgba(0.36, 0.28, 0.18, 0.28),
                    custom_size: Some(Vec2::new(prop.shadow, prop.shadow * 0.42)),
                    ..default()
                },
                // Leaning the way the board's shadows fall (`layout::SUN`):
                // the sun is over the same shoulder on every screen.
                Transform::from_translation(Vec3::new(
                    x + prop.shadow * 0.12,
                    y - prop.size.y * 0.36,
                    z - 0.01,
                )),
            ));
        }
        let mut piece = commands.spawn((
            MenuShore,
            Sprite {
                image: prop.image,
                color: prop.tint,
                custom_size: Some(prop.size),
                ..default()
            },
            Transform::from_translation(Vec3::new(x, y, z))
                .with_rotation(Quat::from_rotation_z(prop.rotation)),
        ));
        if let Some((image, color)) = prop.paint {
            piece.with_child((
                Sprite {
                    image,
                    color,
                    custom_size: Some(prop.size),
                    ..default()
                },
                Transform::from_translation(Vec3::new(0.0, 0.0, 0.001)),
            ));
        }
    }
    // Grain: the flat sand band reads as paint without a little speckle,
    // the same way the board's sand tiles do.
    for _ in 0..90 {
        let pale = rng.next().is_multiple_of(3);
        let tint = if pale {
            Color::srgba(1.0, 0.97, 0.88, 0.30)
        } else {
            Color::srgba(0.55, 0.46, 0.31, 0.22)
        };
        let size = rng.range(2.5, 7.0);
        commands.spawn((
            MenuShore,
            Sprite::from_color(tint, Vec2::splat(size)),
            Transform::from_translation(Vec3::new(
                rng.range(-w / 2.0, w / 2.0),
                rng.range(bottom + 4.0, bottom + SHORE_H - 6.0),
                0.12,
            )),
        ));
    }
    // Damp patches where the last waves reached: darker sand, faint, and
    // only just below the waterline.
    for _ in 0..5 {
        commands.spawn((
            MenuShore,
            Sprite {
                image: art.foam.clone(),
                color: Color::srgba(0.55, 0.47, 0.34, 0.22),
                custom_size: Some(Vec2::new(rng.range(120.0, 240.0), rng.range(10.0, 18.0))),
                ..default()
            },
            Transform::from_translation(Vec3::new(
                rng.range(-w / 2.0, w / 2.0),
                bottom + SHORE_H - rng.range(6.0, 34.0),
                0.15,
            )),
        ));
    }
}

/// Everything a rebuild of the postcard sweeps away: the shore and the
/// travellers crossing it.
type PostcardPieces = Or<(With<MenuShore>, With<MenuCritter>)>;

/// (Re)build the shore whenever the window size changes or the menu is
/// freshly entered: the backdrop is world-space and sized to the window,
/// so maximizing must stretch it.
pub fn refit_shore(
    mut commands: Commands,
    art: Res<art::Art>,
    mut rng: ResMut<VisualRng>,
    viewport: crate::app::menu_ui::Viewport,
    mut last: Local<Vec2>,
    scene: Query<(Entity, Has<MenuShore>), PostcardPieces>,
    mut scrim: Query<&mut Sprite, With<Scrim>>,
) {
    // In interface units, so turning the UI scale rebuilds it as surely as
    // resizing the window does.
    let Some(size) = viewport.size() else {
        return;
    };
    if *last == size && scene.iter().any(|(_, shore)| shore) {
        return;
    }
    *last = size;
    // Travellers carry lane positions from the old window size; sweep
    // them with the backdrop and let the pre-seeding repopulate.
    for (entity, _) in &scene {
        commands.entity(entity).despawn();
    }
    spawn_shore(&mut commands, &art, &mut rng, size);
    // The dusk over it is sized to the window too. It is not part of the
    // shore, and outlives a rebuild, so it is stretched here rather than
    // left at the size of the window it was spawned in: a window grown
    // past it showed a frame of full daylight round the edges.
    for mut sprite in &mut scrim {
        sprite.custom_size = Some(scrim_size(size));
    }
}

/// Spawn one ambient traveller. `at_x` places it mid-scene (used to
/// pre-seed clouds and a boat when the postcard is built); otherwise it
/// enters from just past the upwind edge.
fn spawn_critter(
    commands: &mut Commands,
    art: &art::Art,
    rng: &mut VisualRng,
    w: f32,
    h: f32,
    kind: CritterKind,
    at_x: Option<f32>,
) {
    let bottom = -h / 2.0;
    let horizon = bottom + h * HORIZON;
    let rightward = rng.next().is_multiple_of(2);
    let (y, speed, image, size, tint) = match kind {
        CritterKind::Gull => (
            rng.range(horizon + 30.0, h / 2.0 - 40.0),
            rng.range(130.0, 190.0),
            art.gull_fly.clone(),
            Vec2::splat(46.0),
            Color::WHITE,
        ),
        CritterKind::Cloud => (
            rng.range(horizon + h * 0.08, h / 2.0 - 30.0),
            rng.range(9.0, 20.0),
            art.cloud.clone(),
            Vec2::new(rng.range(110.0, 190.0), rng.range(55.0, 95.0)),
            Color::srgba(1.0, 1.0, 1.0, rng.range(0.75, 0.95)),
        ),
        CritterKind::Boat => (
            rng.range(horizon - 60.0, horizon - 14.0),
            rng.range(18.0, 30.0),
            art.boat.clone(),
            Vec2::splat(rng.range(38.0, 54.0)),
            Color::WHITE,
        ),
        CritterKind::Crab => {
            const KINDS: [CrabKind; 6] = [
                CrabKind::Common,
                CrabKind::Common,
                CrabKind::Juvenile,
                CrabKind::Giant,
                CrabKind::Molting,
                CrabKind::Golden,
            ];
            let crab = KINDS[(rng.next() % 6) as usize];
            (
                rng.range(bottom + 18.0, bottom + SHORE_H - 40.0),
                rng.range(28.0, 55.0),
                art.crab.clone(),
                Vec2::splat(30.0),
                crate::app::creatures::body_color(crab),
            )
        }
    };
    let speed = if rightward { speed } else { -speed };
    // Crabs and gulls face their travel. Their sprites are authored facing
    // +X (`tools/gen_sprites.py`), the same convention the board uses, so
    // this is the board's own rotation for Right or Left rather than a
    // quarter turn, which had them crossing the postcard sideways. Clouds
    // and boats stay level, boats flipping to sail forward.
    let rotation = match kind {
        CritterKind::Crab | CritterKind::Gull => crate::app::layout::dir_rotation(if rightward {
            crate::sim::Direction::Right
        } else {
            crate::sim::Direction::Left
        }),
        CritterKind::Cloud | CritterKind::Boat => Quat::IDENTITY,
    };
    let z = match kind {
        CritterKind::Cloud => 1.5,
        CritterKind::Gull => 2.0,
        CritterKind::Boat => 0.3,
        CritterKind::Crab => 0.5,
    };
    let x = at_x.unwrap_or(-speed.signum() * (w / 2.0 + 110.0));
    // A crab carries its big claw, on whichever side it was born with, as
    // it does on the board: the body alone is a crab with one small claw.
    let handed = if rng.next().is_multiple_of(2) {
        crate::sim::Handedness::Left
    } else {
        crate::sim::Handedness::Right
    };
    let flip_y = kind == CritterKind::Crab && crate::app::creatures::mirrored(handed);
    let mut critter = commands.spawn((
        MenuCritter {
            speed,
            frame_clock: rng.range(0.0, 3.0),
            kind,
            base_y: y,
        },
        Sprite {
            image,
            color: tint,
            custom_size: Some(size),
            flip_x: kind == CritterKind::Boat && !rightward,
            flip_y,
            ..default()
        },
        Transform::from_translation(Vec3::new(x, y, z)).with_rotation(rotation),
    ));
    if kind == CritterKind::Crab {
        critter.with_child((
            Sprite {
                image: art.claw.clone(),
                color: crate::app::creatures::claw_color(handed),
                custom_size: Some(size),
                flip_y,
                ..default()
            },
            Transform::from_translation(Vec3::new(0.0, 0.0, 0.01)),
        ));
    }
}

/// A piece of the sea that rolls in place: the marker saying which, and
/// what rolling it moves.
type SeaPart<Marker> = (&'static Marker, &'static mut Transform, &'static mut Sprite);

/// What moves on the postcard: the travellers, and the sea's two layers.
#[derive(bevy::ecs::system::SystemParam)]
pub struct Movers<'w, 's> {
    critters: Query<
        'w,
        's,
        (
            Entity,
            &'static mut MenuCritter,
            &'static mut Transform,
            &'static mut Sprite,
        ),
    >,
    waves: Query<'w, 's, SeaPart<WaveSegment>, Without<MenuCritter>>,
    foam: Query<'w, 's, SeaPart<ShoreFoam>, (Without<MenuCritter>, Without<WaveSegment>)>,
}

/// Every so often something traverses the postcard: crabs scuttle the
/// sand, gulls glide the sky, clouds drift high, and little sailboats
/// cross the sea with a gentle bob. Waves roll shoreward on a loop.
pub fn menu_ambience(
    mut commands: Commands,
    time: Res<Time>,
    art: Res<art::Art>,
    mut rng: ResMut<VisualRng>,
    mut countdown: Local<f32>,
    viewport: crate::app::menu_ui::Viewport,
    movers: Movers,
) {
    let Movers {
        mut critters,
        mut waves,
        mut foam,
    } = movers;
    let Some(size) = viewport.size() else {
        return;
    };
    let (w, h) = (size.x, size.y);
    let dt = time.delta_secs();

    *countdown -= dt;
    if *countdown <= 0.0 {
        *countdown = rng.range(2.0, 5.0);
        let kind = match rng.next() % 10 {
            0..=2 => CritterKind::Gull,
            3..=4 => CritterKind::Cloud,
            5 => CritterKind::Boat,
            _ => CritterKind::Crab,
        };
        spawn_critter(&mut commands, &art, &mut rng, w, h, kind, None);
    }

    for (entity, mut critter, mut transform, mut sprite) in &mut critters {
        transform.translation.x += critter.speed * dt;
        if transform.translation.x.abs() > w / 2.0 + 130.0 {
            commands.entity(entity).despawn();
            continue;
        }
        critter.frame_clock += dt;
        match critter.kind {
            CritterKind::Crab => {
                let frame_b = (critter.frame_clock / 0.16) as u32 % 2 == 1;
                let want = if frame_b { &art.crab_b } else { &art.crab };
                if sprite.image != *want {
                    sprite.image = want.clone();
                }
            }
            // Boats ride a slow swell.
            CritterKind::Boat => {
                transform.translation.y = critter.base_y + (critter.frame_clock * 1.6).sin() * 2.5;
            }
            CritterKind::Gull | CritterKind::Cloud => {}
        }
    }

    // The swell. Each segment samples one travelling sine at its own place
    // along the crest, so the line rolls: the crest rides up, the trough
    // sinks, and the two chase each other shoreward. Whiteness follows the
    // same wave: foam gathers at the top of a swell.
    let now = time.elapsed_secs();
    for (wave, mut transform, mut sprite) in &mut waves {
        let angle = wave.base.x * wave.freq - now * wave.speed + wave.phase;
        // Two sines at unrelated wavelengths: one alone is a corrugated
        // roof, two make a sea.
        let long = (angle * 0.37 - now * wave.speed * 0.55).sin();
        let swell = (angle.sin() + long * 0.55) / 1.55;
        transform.translation.y = wave.base.y + swell * wave.amp;
        // Sharpen the crest: foam should be a line along the top of the
        // swell, not an even glow over the whole thing.
        let crest = ((swell + 1.0) * 0.5).powf(2.2);
        sprite.color.set_alpha(wave.brightness * crest);
    }
    // The waterline breathes: the foam lip creeps up the sand and back.
    for (shore, mut transform, mut sprite) in &mut foam {
        let breath = (now * 0.42).sin();
        transform.translation.y = shore.base_y + breath * 5.0;
        sprite.color.set_alpha(0.5 + 0.22 * (breath * 0.5 + 0.5));
    }
}