summaryrefslogtreecommitdiff
path: root/src/animation.zig
blob: 25abf4213fcdb2361d6ea0e1f86c5f7fc61d392c (plain) (blame)
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
//! The springs that settle a view and the cursor, and the Motion flavours
//! they move by (colors.zig fades the chrome).
const std = @import("std");

/// The curves a theme change's chrome fades on (colors.ChromeAnimation).
pub const Easing = enum(u8) { smooth, out_cubic };

pub fn sample(easing: Easing, raw: f32) f32 {
    const t = std.math.clamp(raw, 0.0, 1.0);
    return switch (easing) {
        .smooth => t * t * (3.0 - 2.0 * t),
        .out_cubic => 1.0 - (1.0 - t) * (1.0 - t) * (1.0 - t),
    };
}

/// A fractional box in grid cells: the cursor's quad aims at one.
pub const Box = extern struct {
    x: f32 = 0,
    y: f32 = 0,
    w: f32 = 0,
    h: f32 = 0,
};

pub const frame_ms: u32 = 16;
pub const frame_ns: u64 = frame_ms * std.time.ns_per_ms;
pub const transition_steps: u16 = 10;

/// How the fx track moves (`Motion <flavour>`, docs/effects.md): one set of
/// parameters a flavour picks, read by every animation that follows the
/// classic principles, so a flavour is data and no effect branches on it.
pub const Motion = struct {
    pub const Flavour = enum(u8) { off, crisp, smooth, bouncy, playful };

    /// Nothing moves: every change lands at once (reduced motion).
    instant: bool = false,
    /// Timing: the spring's natural frequency, rad/s; slow in / slow out
    /// come from the spring itself.
    omega: f32 = 36,
    /// Follow-through: 1 is critically damped (no overshoot); below 1 it
    /// settles past its target and back.
    zeta: f32 = 1,
    /// Anticipation: a move from rest first winds up the other way, by
    /// this fraction of the distance.
    anticipate: f32 = 0,
    /// Squash and stretch: how much a moving thing lengthens along its
    /// velocity and squashes as it lands (G3's cursor, G7's panes).
    stretch: f32 = 0,
    /// Secondary action: how far behind a follower trails its leader (the
    /// shadow behind a pane, a notice's text behind its chip), as the
    /// follower's frequency over the leader's; 1 is in step.
    follow: f32 = 1,
    /// Arcs: how far a two-dimensional path bows, as a fraction of its
    /// length (the cursor's glide).
    arc: f32 = 0,
    /// Exaggeration: how far a small motion goes, as a multiple of its
    /// plain distance (a lift of 1 rises `gain`), so a flavour's character
    /// shows on a motion only a few pixels big.
    gain: f32 = 1,
    /// Timing: a move from rest leaves at this fraction of full speed (1:
    /// out of the gate at once and easing in, 0: slow in and slow out).
    launch: f32 = 0,
    /// For a motion of fixed length (a pane's move, a notice's drop): its
    /// length as a multiple of the effect's own, and the spring's frequency
    /// over that length (`ease`).
    span: f32 = 1,
    norm: f32 = 10,

    pub fn of(flavour: Flavour) Motion {
        return switch (flavour) {
            .off => .{ .instant = true },
            // Productivity: quick and exact, nothing past its mark.
            .crisp => .{ .omega = 60, .launch = 1, .span = 0.6, .norm = 10 },
            // Longer and softer, easing in and out, still without a bounce.
            // The default: within §8.1's 220 ms for an arrival.
            .smooth => .{ .omega = 34, .follow = 0.85, .arc = 0.04, .span = 1.1, .norm = 6 },
            // Clearly past its mark and back, once or twice, stretching
            // with its speed.
            .bouncy => .{ .omega = 24, .zeta = 0.35, .stretch = 0.15, .follow = 0.8, .arc = 0.08, .gain = 1.25, .span = 1.4, .norm = 13 },
            // A cartoon's: winds up, flies past, squashes as it lands,
            // its followers trailing.
            .playful => .{ .omega = 18, .zeta = 0.28, .anticipate = 0.15, .stretch = 0.35, .follow = 0.55, .arc = 0.15, .gain = 1.4, .span = 1.7, .norm = 18 },
        };
    }

    /// A move of fixed length from 0 to 1, `u` of the way through it: the
    /// flavour's spring (wind-up, overshoot and all), landing exactly on 1
    /// at its end. `instant` is there at once.
    pub fn ease(motion: Motion, u: f32) f32 {
        return motion.easeFrom(u, 0);
    }

    /// `ease` for a move that starts already moving at `launch` lengths
    /// per unit of `u` (a retarget): no wind-up then, the speed carried on.
    pub fn easeFrom(motion: Motion, u: f32, launch: f32) f32 {
        if (motion.instant or u >= 1) return 1;
        if (u <= 0) return 0;
        const kick = if (launch != 0) launch else (motion.launch - 2 * motion.anticipate) * motion.norm;
        const spring: Spring = .{ .omega = motion.norm, .zeta = motion.zeta, .target = 1, .from = 0, .velocity = kick, .settled = false };
        return spring.value(@intFromFloat(u * std.time.ns_per_s));
    }

    /// The same move's speed at `u`, in lengths per unit of `u`, set off at
    /// `launch` as `easeFrom` is.
    pub fn speedFrom(motion: Motion, u: f32, launch: f32) f32 {
        const h: f32 = 1.0 / 256.0;
        return (motion.easeFrom(@min(1, u + h), launch) - motion.easeFrom(@max(0, u - h), launch)) / (@min(1, u + h) - @max(0, u - h));
    }
};

/// A value that follows its target on a damped spring, in closed form
/// (docs/render-pipeline.md §7.2), critically damped or under: a new target
/// taken partway keeps the value AND its velocity, so a quick run of changes
/// never snaps or starts over. A move from rest can wind up first
/// (Motion.anticipate). Settled, it is exactly its target and asks for no
/// frames.
pub const Spring = struct {
    omega: f32 = 36,
    zeta: f32 = 1,
    target: f32 = 0,
    /// The value and velocity (per second) at `from_ns`.
    from: f32 = 0,
    velocity: f32 = 0,
    from_ns: u64 = 0,
    settled: bool = true,

    const State = struct { value: f32, velocity: f32 };

    fn at(spring: *const Spring, now_ns: u64) State {
        if (spring.settled) return .{ .value = spring.target, .velocity = 0 };
        const t: f32 = @floatCast(@as(f64, @floatFromInt(now_ns -| spring.from_ns)) / std.time.ns_per_s);
        const w = spring.omega;
        const x0 = spring.from - spring.target;
        const v0 = spring.velocity;
        if (spring.zeta >= 1) {
            const c = v0 + w * x0;
            const decay = @exp(-w * t);
            return .{ .value = spring.target + (x0 + c * t) * decay, .velocity = (v0 - w * t * c) * decay };
        }
        // Underdamped: it rings about its target as it decays.
        const z = spring.zeta;
        const wd = w * @sqrt(1 - z * z);
        const b = (v0 + z * w * x0) / wd;
        const decay = @exp(-z * w * t);
        const cos = @cos(wd * t);
        const sin = @sin(wd * t);
        return .{
            .value = spring.target + decay * (x0 * cos + b * sin),
            .velocity = decay * ((b * wd - z * w * x0) * cos - (x0 * wd + z * w * b) * sin),
        };
    }

    pub fn value(spring: *const Spring, now_ns: u64) f32 {
        return spring.at(now_ns).value;
    }

    /// Moves what it shows by `by` at `now_ns`, its speed kept, toward the
    /// same target (a scroll's picture falling behind the text it follows),
    /// at `motion`'s pace, never past its mark.
    pub fn carry(spring: *Spring, by: f32, now_ns: u64, motion: Motion) void {
        const state = spring.at(now_ns);
        spring.* = .{ .omega = motion.omega, .zeta = 1, .target = spring.target, .from = state.value + by, .velocity = state.velocity, .from_ns = now_ns, .settled = false };
    }

    /// Heads for `target` from wherever it is at `now_ns`, moving as it was,
    /// at the pace and damping `motion` gives: at once when it is `off`.
    pub fn retarget(spring: *Spring, target: f32, now_ns: u64, motion: Motion) void {
        if (target == spring.target) return;
        if (motion.instant) {
            spring.* = .{ .omega = motion.omega, .zeta = motion.zeta, .target = target, .from = target };
            return;
        }
        const state = spring.at(now_ns);
        // From rest, a launch, or a wind-up: set off the other way, a little.
        const kick: f32 = if (spring.settled) (motion.launch - 2 * motion.anticipate) * (target - state.value) * motion.omega else 0;
        spring.* = .{ .omega = motion.omega, .zeta = motion.zeta, .target = target, .from = state.value, .velocity = state.velocity + kick, .from_ns = now_ns, .settled = false };
    }

    /// Settles once it is within half a percent of its target and barely
    /// moving (no pixel of a shadow tells the rest): it is its target from
    /// then on. True while it still moves.
    pub fn step(spring: *Spring, now_ns: u64) bool {
        if (spring.settled) return false;
        const state = spring.at(now_ns);
        if (@abs(state.value - spring.target) < 5e-3 and @abs(state.velocity) < 5e-2) spring.settled = true;
        return !spring.settled;
    }
};

test "a carried spring keeps its speed, heads back to its mark and never passes it" {
    const ms = std.time.ns_per_ms;
    var spring: Spring = .{};
    const smooth = Motion.of(.smooth);
    spring.carry(-3, 0, smooth);
    try std.testing.expectEqual(@as(f32, -3), spring.value(0));
    const mid = spring.at(40 * ms);
    try std.testing.expect(mid.value > -3 and mid.value < 0 and mid.velocity > 0);
    // Another notch mid-way: one more row behind, still moving back.
    spring.carry(-1, 40 * ms, smooth);
    const after = spring.at(40 * ms);
    try std.testing.expectApproxEqAbs(mid.value - 1, after.value, 1e-5);
    try std.testing.expectApproxEqAbs(mid.velocity, after.velocity, 1e-4);
    var t: u64 = 40 * ms;
    while (spring.step(t)) : (t += frame_ns) try std.testing.expect(spring.value(t) <= 1e-4);
    try std.testing.expect(t < 400 * ms);
}

test "a spring settles without overshoot and keeps its velocity when retargeted" {
    var spring: Spring = .{};
    const ms = std.time.ns_per_ms;
    const crisp = Motion.of(.crisp);
    spring.retarget(1, 0, crisp);
    var last: f32 = 0;
    var t: u64 = 0;
    while (spring.step(t)) : (t += frame_ns) {
        const v = spring.value(t);
        try std.testing.expect(v >= last and v <= 1);
        last = v;
    }
    try std.testing.expect(t >= 80 * ms and t <= 200 * ms);
    try std.testing.expectEqual(@as(f32, 1), spring.value(t + 5 * ms));
    // Back the other way partway up: it carries on up for a moment, then
    // turns, never jumping.
    spring = .{};
    spring.retarget(1, 0, crisp);
    const before = spring.at(60 * ms);
    spring.retarget(0, 60 * ms, crisp);
    const after = spring.at(60 * ms);
    try std.testing.expectApproxEqAbs(before.value, after.value, 1e-6);
    try std.testing.expectApproxEqAbs(before.velocity, after.velocity, 1e-4);
    try std.testing.expect(spring.value(60 * ms + 500_000) > before.value);
}

test "each flavour is its own motion: off lands at once, bouncy overshoots, playful winds up first" {
    const ms = std.time.ns_per_ms;
    var spring: Spring = .{};
    spring.retarget(1, 0, Motion.of(.off));
    try std.testing.expect(spring.settled);
    try std.testing.expectEqual(@as(f32, 1), spring.value(0));
    var settle: [5]u64 = @splat(0);
    for ([_]Motion.Flavour{ .crisp, .smooth, .bouncy, .playful }) |flavour| {
        spring = .{};
        spring.retarget(1, 0, Motion.of(flavour));
        var peak: f32 = 0;
        var low: f32 = 0;
        var t: u64 = 0;
        var last = spring.at(0);
        while (spring.step(t)) : (t += ms) {
            const now = spring.at(t);
            peak = @max(peak, now.value);
            low = @min(low, now.value);
            // Continuous, a millisecond at a time: no jump anywhere.
            try std.testing.expect(@abs(now.value - last.value) < 0.07);
            last = now;
        }
        try std.testing.expect(t < 1600 * ms);
        settle[@backingInt(flavour)] = t;
        switch (flavour) {
            .crisp, .smooth => try std.testing.expect(peak <= 1.0005 and low >= 0),
            // Clearly past the mark, not a hint of it.
            .bouncy => try std.testing.expect(peak > 1.25 and low >= 0),
            .playful => try std.testing.expect(peak > 1.35 and low < -0.03),
            .off => unreachable,
        }
    }
    // Smooth takes twice crisp's time and more: a character, not a tuning.
    // Yet as the default a pane's arrival (a slide's 12 frames, scaled) is
    // inside §8.1's 220 ms, and a lift is still before 300 ms.
    try std.testing.expect(settle[@backingInt(Motion.Flavour.smooth)] > 2 * settle[@backingInt(Motion.Flavour.crisp)]);
    try std.testing.expect(settle[@backingInt(Motion.Flavour.smooth)] <= 300 * ms);
    try std.testing.expect(@round(@as(f32, 12) * Motion.of(.smooth).span) * frame_ms <= 220);
    // A fixed-length move lands exactly on its mark, whatever the flavour.
    for (std.enums.values(Motion.Flavour)) |flavour| try std.testing.expectEqual(@as(f32, 1), Motion.of(flavour).ease(1));
}

/// A view that follows its input (anim 9, 11): the picture's offset from
/// the core's position now (in the view's own unit: rows of text, pixels of
/// a PDF strip; negative, the picture still shows what is above), its speed
/// (units a second), when it was last integrated, and what has been feeding
/// it. The text body (the GUI's Glide) and a PDF strip are each one.
pub const Follow = struct {
    offset: f32 = 0,
    speed: f32 = 0,
    at_ns: u64 = 0,
    /// The last inputs (down positive), their spacing, the last's time, and
    /// how many came as one stream.
    feed: struct { amount: f32 = 0, gap_ns: u64 = 0, last_ns: u64 = 0, count: u16 = 0 } = .{},

    /// How far the picture may lag, in bodies (a flick past that jumps);
    /// how fast it may move, in bodies a second, so moving text stays
    /// readable.
    pub const reach = 2;
    pub const bodies_per_s: f32 = 15;
    /// Inputs this close, each the way the last went, are one stream.
    pub const stream_ns = 150 * std.time.ns_per_ms;

    /// What a view's size and the flavour make of the rules: the spring at
    /// 1.5x the flavour's pace, the speed cap, the lag cap, and the offset
    /// under which it is at rest (a tenth of a pixel, in its unit).
    pub const Pace = struct { omega: f32, cap: f32, limit: f32, rest: f32 };

    pub fn pace(motion: Motion, body: f32, rest: f32) Pace {
        return .{ .omega = motion.omega * 1.5, .cap = body * bodies_per_s, .limit = body * reach, .rest = rest };
    }

    pub fn moving(follow: *const Follow) bool {
        return follow.offset != 0 or follow.speed != 0;
    }

    /// An input: the core moved `amount` (down positive). The picture now
    /// lags by as much more, its speed as it was.
    pub fn kick(follow: *Follow, amount: f32, now_ns: u64, p: Pace) void {
        follow.advance(now_ns, p);
        follow.offset = std.math.clamp(follow.offset - amount, -p.limit, p.limit);
        const f = &follow.feed;
        const like = f.count > 0 and (amount > 0) == (f.amount > 0) and now_ns -| f.last_ns < stream_ns;
        if (like) {
            const gap = now_ns -| f.last_ns;
            f.gap_ns = if (f.count == 1) gap else (f.gap_ns + gap) / 2;
            f.amount = (f.amount + amount) / 2;
            f.count +|= 1;
        } else f.* = .{ .amount = amount, .count = 1 };
        f.last_ns = now_ns;
    }

    /// The system moved on to `now_ns`. Fed by a stream, at the stream's
    /// rate (an input's amount over their spacing), held a lag `lead`
    /// behind so a late input never finds it stopped and the stream's end
    /// never runs it past its mark; else on the spring, critically damped,
    /// from the speed it has. Never faster than `p.cap`.
    pub fn advance(follow: *Follow, now_ns: u64, p: Pace) void {
        const dt: f32 = @floatCast(@as(f64, @floatFromInt(@min(now_ns -| follow.at_ns, 2 * frame_ns))) / std.time.ns_per_s);
        follow.at_ns = now_ns;
        if (follow.offset == 0 and follow.speed == 0) return;
        const omega = p.omega;
        const toward: f32 = if (follow.offset < 0) 1 else -1;
        const f = follow.feed;
        if (f.count >= 2 and f.gap_ns > 0 and now_ns -| f.last_ns < f.gap_ns * 3 / 2) {
            const gap: f32 = @floatCast(@as(f64, @floatFromInt(f.gap_ns)) / std.time.ns_per_s);
            const rate = @abs(f.amount) / gap;
            const lead = @max(@abs(f.amount), rate / omega);
            // ponytail: a gentle pull to the lead (a tenth an input), so the
            // per-frame step varies by a tenth; a stream's own jitter beyond
            // that shows. An estimate of the input clock if it ever matters.
            // A slow stream's lag runs out before its next input: never
            // faster than the spring's own pace from there (omega a unit of
            // lag a second), so it eases onto the mark, not into it at speed.
            const v = std.math.clamp(rate + 0.1 / gap * (@abs(follow.offset) - lead), 0, @min(p.cap, omega * @abs(follow.offset)));
            const step = @min(v * dt, @abs(follow.offset));
            follow.offset += toward * step;
            follow.speed = if (follow.offset == 0) 0 else toward * v;
            return;
        }
        const x = follow.offset;
        // Coming to rest from a stream: never faster than the spring's own
        // pace from here (omega a unit of lag a second), so it eases in and
        // does not pass its mark.
        if (follow.speed * x < 0 and @abs(follow.speed) > omega * @abs(x)) follow.speed = std.math.sign(follow.speed) * omega * @abs(x);
        const lead_v = follow.speed + omega * x;
        const decay = @exp(-omega * dt);
        var next = (x + lead_v * dt) * decay;
        var speed = (follow.speed - omega * dt * lead_v) * decay;
        if (@abs(next - x) > p.cap * dt) {
            next = x + std.math.sign(next - x) * p.cap * dt;
            speed = std.math.sign(next - x) * p.cap;
        }
        follow.offset = next;
        follow.speed = speed;
        if (@abs(next) < p.rest and @abs(speed) < 10 * p.rest) follow.* = .{ .at_ns = now_ns };
    }
};

test "a follow comes to rest without a snap: past its fastest frame each step is shorter, the last under a tenth of a pixel" {
    // A flick's spin (a stream of notches, then nothing), one page, and
    // notches slow enough that each lag runs out before the next (its
    // stream must ease onto each mark, never pass it).
    const p = Follow.pace(.{}, 600, 0.1);
    for ([_]struct { n: u16, gap_ms: u64 }{ .{ .n = 12, .gap_ms = 16 }, .{ .n = 1, .gap_ms = 16 }, .{ .n = 6, .gap_ms = 144 } }) |run| {
        var f: Follow = .{};
        var now: u64 = std.time.ns_per_s;
        for (0..run.n) |_| {
            f.kick(if (run.n == 1) 600 else 25, now, p);
            var waited: u64 = 0;
            while (waited < run.gap_ms) : (waited += 8) {
                now += 8 * std.time.ns_per_ms;
                const was = f.offset;
                f.advance(now, p);
                // Toward its mark only, and onto it from under a pixel.
                try std.testing.expect(f.offset <= 0 and f.offset >= was);
                if (f.offset == 0) try std.testing.expect(-was <= 3 * p.rest);
            }
        }
        var last: f32 = std.math.inf(f32);
        var before = f.offset;
        var frames: usize = 0;
        var fastest: f32 = 0;
        while (f.moving()) : (frames += 1) {
            now += frame_ns;
            f.advance(now, p);
            const step = @abs(f.offset - before);
            try std.testing.expect(@abs(f.offset) <= @abs(before));
            if (f.offset == 0) try std.testing.expect(step <= 3 * p.rest);
            fastest = @max(fastest, step);
            if (step < fastest) try std.testing.expect(step <= last);
            last = step;
            before = f.offset;
            try std.testing.expect(frames < 120);
        }
        try std.testing.expect(last <= 0.1);
    }
}

/// The focused cursor's quad (docs/render-pipeline.md §5.4), in grid cells:
/// four corners, each on its own springs, so a jump smears along its path
/// (the leading corners stiffer than the trailing ones, Motion.follow) and
/// collapses at rest; a long jump bows (Motion.arc). A step of a cell or
/// less (a key held, typing) eases there whole, its corners together, on a
/// spring `step_pace` times stiffer still: in ~60 ms on the default, so at
/// a keyboard's repeat it trails by half a cell and never smears a caret.
/// Any move the caller calls a snap, and every move under Motion off,
/// lands at once.
pub const CursorGlide = struct {
    /// Top left, top right, bottom right, bottom left; x then y.
    corners: [4][2]Spring = @splat(@splat(.{})),
    target: Box = .{},
    from_centre: [2]f32 = .{ 0, 0 },
    placed: bool = false,
    /// When the last step (a move of a cell or less) came.
    step_ns: u64 = 0,

    /// How much faster than the flavour's own pace a cursor moves: it
    /// follows input (§8.1: settles in 90-150 ms on the default).
    pub const pace: f32 = 2.4;
    /// A jump longer than this, in cells, bows.
    pub const arc_from: f32 = 8;
    /// How much stiffer a step's spring is than a jump's.
    pub const step_pace: f32 = 1.5;
    /// Steps this close are a stream (a held key, typing): each lands, the
    /// caret at the keys' own rate, as an eased step a key would bounce.
    pub const stream_ns: u64 = 150 * std.time.ns_per_ms;

    fn cornersOf(box: Box) [4][2]f32 {
        return .{ .{ box.x, box.y }, .{ box.x + box.w, box.y }, .{ box.x + box.w, box.y + box.h }, .{ box.x, box.y + box.h } };
    }

    fn centre(box: Box) [2]f32 {
        return .{ box.x + box.w / 2, box.y + box.h / 2 };
    }

    /// Heads for `box` at `now_ns`.
    /// How a new mark is gone to: eased (a step, or a jump's smear and
    /// bow), or landed at once (a scroll: the text moved under it, not the
    /// caret; a shell carries it with the text's own glide).
    pub const How = enum { ease, land };

    pub fn aim(glide: *CursorGlide, box: Box, now_ns: u64, motion: Motion, how: How) void {
        // The same mark: nothing to do, unless a snap lands a glide under way.
        if (glide.placed and std.meta.eql(box, glide.target) and !(how == .land and glide.moving())) return;
        const to = cornersOf(box);
        const from_c = if (glide.placed) glide.centreAt(now_ns) else centre(box);
        const to_c = centre(box);
        const dx = to_c[0] - from_c[0];
        const dy = to_c[1] - from_c[1];
        const jump = @abs(dx) > 1.01 or @abs(dy) > 1.01;
        // A step is measured mark to mark, not from where an ease under way
        // has got to (a held key's steps read as jumps from there).
        const last = centre(glide.target);
        const one_step = glide.placed and @abs(to_c[0] - last[0]) <= 1.01 and @abs(to_c[1] - last[1]) <= 1.01;
        const streaming = one_step and glide.step_ns != 0 and now_ns -| glide.step_ns < stream_ns;
        if (one_step) glide.step_ns = now_ns;
        const land = !glide.placed or how == .land or motion.instant or streaming;
        glide.from_centre = from_c;
        glide.target = box;
        glide.placed = true;
        for (&glide.corners, to) |*corner, point| {
            // Leading: the corner ahead of the move, on the side it goes.
            const ahead = (point[0] - to_c[0]) * dx + (point[1] - to_c[1]) * dy;
            var own = motion;
            own.omega *= if (jump) pace * (if (ahead > 0) 1 else motion.follow) else pace * step_pace;
            // A step neither winds up nor overshoots: it is a caret moving.
            if (!jump) {
                own.zeta = 1;
                own.anticipate = 0;
            }
            if (land) {
                for (corner, point) |*axis, value| axis.* = .{ .omega = own.omega, .zeta = own.zeta, .target = value, .from = value };
                continue;
            }
            for (corner, point) |*axis, value| axis.retarget(value, now_ns, own);
        }
    }

    pub fn centreAt(glide: *const CursorGlide, now_ns: u64) [2]f32 {
        var c: [2]f32 = .{ 0, 0 };
        for (glide.corners) |corner| for (&c, corner) |*sum, axis| {
            sum.* += axis.value(now_ns) / 4;
        };
        return c;
    }

    /// Text under the cursor moved by (dx, dy) cells (a scroll): the quad
    /// moves with it, rather than gliding against text that jumped.
    pub fn shift(glide: *CursorGlide, dx: f32, dy: f32) void {
        for (&glide.corners) |*corner| for (corner, [2]f32{ dx, dy }) |*axis, d| {
            axis.from += d;
            axis.target += d;
        };
        glide.from_centre = .{ glide.from_centre[0] + dx, glide.from_centre[1] + dy };
        glide.target.x += dx;
        glide.target.y += dy;
    }

    /// The quad at `now_ns`, bowed on a long jump by the flavour's arc.
    pub fn sample(glide: *const CursorGlide, now_ns: u64, motion: Motion) [4][2]f32 {
        var out: [4][2]f32 = undefined;
        for (&out, glide.corners) |*point, corner| for (point, corner) |*value, axis| {
            value.* = axis.value(now_ns);
        };
        const to_c = centre(glide.target);
        const dx = to_c[0] - glide.from_centre[0];
        const dy = to_c[1] - glide.from_centre[1];
        const length = @sqrt(dx * dx + dy * dy);
        if (motion.arc == 0 or length < arc_from) return out;
        const now_c = glide.centreAt(now_ns);
        const left = @sqrt((to_c[0] - now_c[0]) * (to_c[0] - now_c[0]) + (to_c[1] - now_c[1]) * (to_c[1] - now_c[1]));
        const travelled = std.math.clamp(1 - left / length, 0, 1);
        const bow = motion.arc * length * 4 * travelled * (1 - travelled);
        // Perpendicular to the path, to its left.
        for (&out) |*point| {
            point[0] += -dy / length * bow;
            point[1] += dx / length * bow;
        }
        return out;
    }

    /// Steps the springs to `now_ns`; true while the quad still moves.
    pub fn step(glide: *CursorGlide, now_ns: u64) bool {
        var any = false;
        for (&glide.corners) |*corner| for (corner) |*axis| {
            if (axis.step(now_ns)) any = true;
        };
        return any;
    }

    /// How far, in cells, the furthest corner still is from its mark.
    pub fn remaining(glide: *const CursorGlide, now_ns: u64) f32 {
        var most: f32 = 0;
        for (glide.corners) |corner| for (corner) |axis| {
            most = @max(most, @abs(axis.value(now_ns) - axis.target));
        };
        return most;
    }

    pub fn moving(glide: *const CursorGlide) bool {
        for (glide.corners) |corner| for (corner) |axis| {
            if (!axis.settled) return true;
        };
        return false;
    }
};

/// The cursor's opacity under blink (§5.4): solid while typing and for
/// `hold_ns` after, then on and off with an eased edge, solid again after
/// `idle_ns` of no input. `edge` says whether it is mid-edge (a frame is
/// owed), `next_ns` when the next edge starts (a wake).
pub const Blink = struct {
    pub const hold_ns: u64 = 500 * std.time.ns_per_ms;
    pub const idle_ns: u64 = 10 * std.time.ns_per_s;
    pub const half_ns: u64 = 530 * std.time.ns_per_ms;
    pub const edge_ns: u64 = 80 * std.time.ns_per_ms;

    alpha: f32,
    edge: bool,
    next_ns: ?u64,

    pub fn at(now_ns: u64, input_ns: u64) Blink {
        const since = now_ns -| input_ns;
        if (since < hold_ns) return .{ .alpha = 1, .edge = false, .next_ns = input_ns + hold_ns + half_ns - edge_ns };
        if (since >= hold_ns + idle_ns) return .{ .alpha = 1, .edge = false, .next_ns = null };
        const t = (since - hold_ns) % (2 * half_ns);
        const cycle_start = now_ns - t;
        // On for a half, easing out over its last `edge_ns`; off for a half,
        // easing back in over its last.
        if (t < half_ns - edge_ns) return .{ .alpha = 1, .edge = false, .next_ns = cycle_start + half_ns - edge_ns };
        if (t < half_ns) return .{ .alpha = 1 - smooth(@as(f32, @floatFromInt(t - (half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null };
        if (t < 2 * half_ns - edge_ns) return .{ .alpha = 0, .edge = false, .next_ns = cycle_start + 2 * half_ns - edge_ns };
        return .{ .alpha = smooth(@as(f32, @floatFromInt(t - (2 * half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null };
    }

    fn smooth(x: f32) f32 {
        const u = std.math.clamp(x, 0, 1);
        return u * u * (3 - 2 * u);
    }
};

test "a cursor eases a cell at a time, keeps up with typing, and glides a jump, smearing, bowing and landing exactly" {
    const ms = std.time.ns_per_ms;
    const smooth_motion = Motion.of(.smooth);
    var glide: CursorGlide = .{};
    const cell: Box = .{ .x = 3, .y = 4, .w = 1, .h = 1 };
    glide.aim(cell, 0, smooth_motion, .ease);
    try std.testing.expect(!glide.moving());
    // One cell over: eases there whole, no wider than a cell, in ~60 ms.
    glide.aim(.{ .x = 4, .y = 4, .w = 1, .h = 1 }, ms, smooth_motion, .ease);
    try std.testing.expect(glide.moving());
    var step_t: u64 = ms;
    while (glide.step(step_t)) : (step_t += ms) {
        const q = glide.sample(step_t, smooth_motion);
        try std.testing.expect(q[1][0] - q[0][0] <= 1.0 + 1e-3 and q[0][0] >= 3 - 1e-3 and q[0][0] <= 4 + 1e-3);
    }
    try std.testing.expect(step_t - ms >= 30 * ms and step_t - ms <= 90 * ms);
    // At a keyboard's repeat the steps are a stream: each lands.
    var typed: f32 = 4;
    var key_t: u64 = step_t;
    for (0..20) |_| {
        typed += 1;
        glide.aim(.{ .x = typed, .y = 4, .w = 1, .h = 1 }, key_t, smooth_motion, .ease);
        key_t += 33 * ms;
        try std.testing.expect(typed - glide.sample(key_t, smooth_motion)[0][0] <= 0.6);
    }
    while (glide.step(key_t)) key_t += ms;
    // A jump of 30 cells: glides, the leading edge ahead of the trailing one.
    glide.aim(cell, key_t, smooth_motion, .land);
    const j0 = key_t;
    const far: Box = .{ .x = 34, .y = 4, .w = 1, .h = 1 };
    glide.aim(far, j0 + 2 * ms, smooth_motion, .ease);
    try std.testing.expect(glide.moving());
    const mid = glide.sample(j0 + 40 * ms, smooth_motion);
    const width = mid[1][0] - mid[0][0];
    try std.testing.expect(width > 1.5);
    // Bowed off the straight line on a long jump.
    try std.testing.expect(@abs(mid[0][1] - 4) > 0.05);
    var t: u64 = j0 + 2 * ms;
    while (glide.step(t)) t += ms;
    // Arrives within §8.1's 90-150 ms on the default, within a twentieth of
    // a cell (under a pixel); settles to rest just after, landing exactly.
    const arrived = glide.sample(j0 + 152 * ms, smooth_motion);
    try std.testing.expect(@abs(arrived[3][0] - 34) < 0.05 and @abs(arrived[1][0] - 35) < 0.05);
    try std.testing.expect(t - j0 <= 220 * ms);
    const rest = glide.sample(t, smooth_motion);
    try std.testing.expectEqual([2]f32{ 34, 4 }, rest[0]);
    try std.testing.expectEqual([2]f32{ 35, 5 }, rest[2]);
    // A scroll carries it with the text.
    glide.shift(0, -3);
    try std.testing.expectEqual([2]f32{ 34, 1 }, glide.sample(t, smooth_motion)[0]);
}

test "a blink holds while typing, eases at its edges and stops when idle" {
    const ms = std.time.ns_per_ms;
    try std.testing.expectEqual(@as(f32, 1), Blink.at(100 * ms, 0).alpha);
    const out = Blink.at(Blink.hold_ns + Blink.half_ns + 100 * ms, 0);
    try std.testing.expectEqual(@as(f32, 0), out.alpha);
    const edge = Blink.at(Blink.hold_ns + Blink.half_ns - Blink.edge_ns / 2, 0);
    try std.testing.expect(edge.edge and edge.alpha > 0.2 and edge.alpha < 0.8);
    try std.testing.expectEqual(@as(?u64, null), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).next_ns);
    try std.testing.expectEqual(@as(f32, 1), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).alpha);
}