summaryrefslogtreecommitdiff
path: root/src/host/Host.zig
blob: 3a2a25f54334bbb03aac5e2e7f3cf6f536e28741 (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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
//! The runtime around a sketch: window, memory, audio, timeline and console.
//! One `frame` serves both the interactive loop and test scripts, so scripts
//! exercise exactly what a player does.
const Host = @This();
const std = @import("std");
const tracy = @import("tracy");
const c = @import("c");
const abi = @import("abi");
const memory = @import("memory.zig");
const playback = @import("timeline.zig");
const Timeline = playback.Timeline;
const gfx = @import("gfx.zig");
const sound = @import("audio.zig");
const Gpu = @import("gpu");
const overlay = @import("overlay.zig");
const Console = @import("Console.zig");
const Timing = @import("Timing.zig");
const Presentation = @import("Presentation.zig");
const timing_marker = @import("timing_marker.zig");
const Control = @import("control.zig").Control;
const Library = @import("library.zig").Library;
const Sessions = @import("Sessions.zig");
const Watch = @import("library.zig").Watch;

pub const Options = struct {
    /// A hot-reloaded sketch library. Unused when a sketch is linked in.
    library: ?[]const u8 = null,
    /// Local 9P control socket, opt-in.
    ninep: ?[]const u8 = null,
    /// State file; the sessions database goes next to it, `<name>.xitdb`
    /// for `<name>.state`. Empty: `$XDG_DATA_HOME/<name>/<name>.state`
    /// (`~/.local/share` without it), for a shipped game.
    state: []const u8 = "",
    /// Playing a script: from fresh state, sessions go to memory only.
    script: bool = false,
    /// Offscreen video, silent audio, no vsync: for scripts and CI.
    headless: bool = false,
    /// Forget the state file's contents: scripts start from a known place.
    fresh: bool = false,
    /// Time every GPU command alone and print the times at exit.
    profile_gpu: bool = false,
    /// Binary frame/time marker for external video measurements.
    timing_marker: bool = false,
    /// Export every frame: PNGs `<dir>/000000.png`, ..., or for "-" raw RGBA
    /// rows on stdout. Frames run on a clock of their own (see `fps`).
    export_to: ?[]const u8 = null,
    /// Export: frame k is k/fps seconds in, each tick exactly 1/fps.
    fps: u32 = 60,
    /// Export: stop after this many frames; null: when the sketch quits.
    frames: ?u64 = null,
    /// The first canvas and, headless, the room for it (`window_width`).
    size: ?[2]u32 = null,
};

gpa: std.mem.Allocator,
io: std.Io,
environ: *const std.process.Environ.Map,
options: Options,
window: *c.SDL_Window,
renderer: *c.SDL_Renderer,
/// Runs sketches' GPU passes, and the 2D renderer draws through it too.
/// Null when the machine has no usable GPU driver.
gpu: ?*c.SDL_GPUDevice,
presentation: ?*Presentation = null,
passes: ?Gpu = null,
/// GPU canvas, shared by native/headless drawing, backdrop filters and screenshots.
offscreen: ?*c.SDL_Texture = null,
pointer_cursor: ?*c.SDL_Cursor = null,
images: gfx.Images,
/// Plays the 2D commands: targets, blend, antialiased shapes.
painter: gfx.Painter,
audio: sound.Audio,
state: memory.StateFile,
session: memory.Session,
/// A failed resource setup disables app callbacks while keeping host controls alive.
session_ready: bool = false,
/// Images and buffers the sketch made (`newImage`, `decodeImage`,
/// `newBuffer`): Session holds their handles, so they go when it resets.
made: struct { images: std.ArrayList(abi.Image) = .empty, buffers: std.ArrayList(abi.Buffer) = .empty } = .{},
timeline: Timeline,
/// This run's session and the ones before it (Sessions.zig).
sessions: Sessions,
console: Console = .{},
timing: Timing = .{},
timing_atlas: overlay.TimingAtlas = .{},
sketch: abi.Sketch,
library: ?Library = null,
watch: ?Watch = null,
reloads: usize = 0,
/// Identifies the running build of the sketch (its library or executable
/// file's inode, size and modification time): sessions' stretches carry it,
/// and `play` warns on a mismatch.
build: u64 = 0,
/// The state file's path when the host chose it (`Options.state`), `gpa`'s.
state_path: []const u8 = "",
/// Copies of the sketch's info strings, replaced on every load.
info_arena: std.heap.ArenaAllocator,
name: []const u8 = "",
/// The sketch's `Info.source`, for the session's stretches.
source: []const u8 = "",
completions: []const []const u8 = &.{},
/// Frame lifetime: sketch scratch and this frame's commands.
frame_arena: std.heap.ArenaAllocator,
commands: std.ArrayList(abi.Command) = .empty,
/// Events routed since the last frame, fed to `update` by the next one.
pending: std.ArrayList(abi.Event) = .empty,
input: abi.Input = .{},
files: std.StringHashMapUnmanaged([]align(memory.page) const u8) = .empty,
/// Mappings of files `writeFile` replaced: the sketch may still hold them.
retired: std.ArrayList([]align(memory.page) const u8) = .empty,
/// The paths `appendFile` wrote, each once, 0-terminated: the sketch keeps
/// them.
written: std.StringHashMapUnmanaged(void) = .empty,
canvas: [2]u32 = .{ 0, 0 },
cursor: abi.Cursor = .arrow,
quit: bool = false,
reloaded: bool = true,
/// For `Input.jumped`: state changed other than by `update` since the
/// last `draw` (a seek, a load, a `set`...). The first frame is one.
jumped: bool = true,
started: bool = true,
last_now: u64 = 0,
last_frame_end: u64 = 0,
/// Saved after the next frame is drawn (scripts).
screenshot: ?[:0]const u8 = null,
/// Frames exported so far (`Options.export_to`).
exported: u64 = 0,
dialog: Dialog = .{},
control: ?*Control = null,

pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, given: Options, linked: ?abi.Sketch) !void {
    var options = given;
    if (options.headless) {
        // Overriding: a plain hint loses to the environment, and a user's
        // SDL_VIDEO_DRIVER=wayland would open real windows during tests.
        _ = c.SDL_SetHintWithPriority(c.SDL_HINT_VIDEO_DRIVER, "offscreen", c.SDL_HINT_OVERRIDE);
        _ = c.SDL_SetHintWithPriority(c.SDL_HINT_AUDIO_DRIVER, "dummy", c.SDL_HINT_OVERRIDE);
        _ = c.SDL_SetHintWithPriority(c.SDL_HINT_RENDER_DRIVER, "software", c.SDL_HINT_OVERRIDE);
    }
    if (!c.SDL_Init(c.SDL_INIT_VIDEO | c.SDL_INIT_EVENTS | c.SDL_INIT_AUDIO)) return sdlError("SDL_Init");
    errdefer c.SDL_Quit();

    var library: ?Library = null;
    const sketch = linked orelse blk: {
        const path = options.library orelse return error.NoSketch;
        library = try Library.openFresh(io, path, scratchDir(environ), 0);
        break :blk library.?.sketch;
    };
    errdefer if (library) |*l| l.close();
    const info = sketch.info();

    var title_buf: [256]u8 = undefined;
    const title = std.mem.printSentinel(&title_buf, "{s}", .{info.name}, 0) catch "sketch";
    const window = c.SDL_CreateWindow(title.ptr, @intCast(info.width), @intCast(info.height), c.SDL_WINDOW_RESIZABLE) orelse return sdlError("SDL_CreateWindow");
    errdefer c.SDL_DestroyWindow(window);
    // The 2D renderer runs on the GPU device that also runs sketches' GPU
    // passes; without one, SDL picks whatever renderer works. Headless, it
    // gets no window (an offscreen window has no Vulkan surface everywhere)
    // and draws into a texture instead (`setCanvas`).
    var gpu = c.SDL_CreateGPUDevice(c.SDL_GPU_SHADERFORMAT_SPIRV, false, null);
    var renderer: ?*c.SDL_Renderer = if (gpu) |device| c.SDL_CreateGPURenderer(device, if (options.headless) null else window) else null;
    if (renderer == null) {
        if (gpu) |device| c.SDL_DestroyGPUDevice(device);
        gpu = null;
        std.log.warn("no GPU renderer ({s}); drawing without one", .{c.SDL_GetError()});
        renderer = c.SDL_CreateRenderer(window, null) orelse return sdlError("SDL_CreateRenderer");
    }
    // Deferred in reverse: the renderer goes first, then the device it
    // draws through (the other order crashed in SDL_DestroyRenderer).
    errdefer if (gpu) |device| c.SDL_DestroyGPUDevice(device);
    errdefer c.SDL_DestroyRenderer(renderer);
    if (!options.headless) _ = c.SDL_SetRenderVSync(renderer, 1);
    // Colors carry alpha: fills blend, as they do on the web.
    _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND);

    var data_buf: [std.fs.max_path_bytes]u8 = undefined;
    const state_path = if (given.state.len > 0) "" else blk: {
        const data = environ.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{environ.get("HOME") orelse "."});
        const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.state", .{ data, info.name, info.name });
        errdefer gpa.free(path);
        try std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(path).?);
        break :blk path;
    };
    errdefer gpa.free(state_path);
    if (state_path.len > 0) options.state = state_path;
    var state = try memory.StateFile.open(gpa, options.state);
    errdefer state.close();

    self.* = .{
        .gpa = gpa,
        .io = io,
        .environ = environ,
        .options = options,
        .window = window,
        .renderer = renderer.?,
        .gpu = gpu,
        .images = .{ .gpa = gpa, .renderer = renderer.? },
        .painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null },
        .audio = .{ .gpa = gpa },
        .state = state,
        .session = .init(gpa),
        .timeline = undefined,
        .sessions = .{ .gpa = gpa, .io = io },
        .sketch = sketch,
        .library = library,
        .state_path = state_path,
        .info_arena = .init(gpa),
        .frame_arena = .init(gpa),
        .input = .{ .exporting = options.export_to != null },
    };
    self.timeline = .{ .gpa = gpa, .state = &self.state, .defaults = sketch.defaults };
    self.painter.images = &self.images;
    if (gpu) |device| self.passes = .init(gpa, device);
    if (options.profile_gpu) if (self.passes) |*g| {
        g.profile = .init(gpa);
    };
    self.audio.open() catch |err| std.log.warn("audio unavailable: {t}", .{err});
    if (options.library) |path| if (linked == null) {
        self.watch = Watch.init(path) catch null;
    };
    const size = options.size orelse [2]u32{ info.width, info.height };
    self.setCanvas(size[0], size[1]);
    _ = c.SDL_StartTextInput(self.window);
    self.build = fileId(io, options.library orelse "/proc/self/exe");
    try self.adopt(sketch);
    self.openSessions(info.record);
    // Before --fresh: it never touches the history.
    if (importSnapshots(&self.state, &self.sessions)) |n| {
        if (n > 0) self.print("{d} snapshots of {s} are marks now", .{ n, options.state });
    } else |err| self.print("snapshots of {s} kept in it: {t}", .{ options.state, err });
    if (options.fresh) self.resetState();
    if (!options.headless and options.export_to == null) {
        self.presentation = Presentation.init(gpa, self.window) catch null;
        if (options.timing_marker) self.print("presentation tracing: {s}", .{if (self.presentation) |p| p.status else "disabled_or_allocation_failed"});
    }
}

pub fn deinit(self: *Host) void {
    self.sessions.close(self.live(), wallClock(self.io));
    if (self.control) |control| control.deinit();
    self.dialog.deinit();
    if (self.watch) |w| w.deinit();
    self.audio.deinit();
    self.painter.deinit();
    self.images.deinit();
    if (self.passes) |*g| g.deinit();
    if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor);
    if (self.offscreen) |texture| c.SDL_DestroyTexture(texture);
    if (self.presentation) |p| p.deinit(self.gpa);
    c.SDL_DestroyRenderer(self.renderer);
    if (self.gpu) |device| c.SDL_DestroyGPUDevice(device);
    c.SDL_DestroyWindow(self.window);
    var files = self.files.iterator();
    while (files.next()) |entry| {
        self.gpa.free(entry.key_ptr.*);
        std.posix.munmap(entry.value_ptr.*);
    }
    self.files.deinit(self.gpa);
    for (self.retired.items) |bytes| std.posix.munmap(bytes);
    self.retired.deinit(self.gpa);
    var written = self.written.keyIterator();
    while (written.next()) |path| self.gpa.free(path.ptr[0 .. path.len + 1]);
    self.written.deinit(self.gpa);
    self.timeline.deinit();
    self.session.deinit(self.gpa);
    self.made.images.deinit(self.gpa);
    self.made.buffers.deinit(self.gpa);
    self.state.close();
    self.pending.deinit(self.gpa);
    self.frame_arena.deinit();
    self.info_arena.deinit();
    self.gpa.free(self.state_path);
    if (self.library) |*l| l.close();
    c.SDL_Quit();
}

/// The interactive loop. An export runs it on a clock of its own, frame k
/// at k/fps seconds (from 1 s, as scripts do), whatever the wall clock says.
pub fn run(self: *Host) !void {
    if (self.options.ninep) |path| self.control = try Control.init(self.gpa, path);
    while (!self.quit) {
        if (self.control) |control| control.poll(self);
        try self.poll();
        if (self.presentation) |p| p.poll();
        if (!self.options.headless and self.options.export_to == null and
            c.SDL_GetWindowFlags(self.window) & (c.SDL_WINDOW_OCCLUDED | c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_HIDDEN) != 0 and
            self.screenshot == null and !(self.control != null and self.control.?.capture_pending))
        {
            // Occluded Wayland presentation can block for a second; keep controls alive and resume without a camera jump.
            self.last_now = 0;
            self.last_frame_end = 0;
            _ = c.SDL_Delay(10);
            continue;
        }
        // GPU fences do not limit presentation rate; follow the measured display clock.
        const wait_ns = if (self.presentation) |p| p.waitNs() else 0;
        if (wait_ns != 0) {
            c.SDL_DelayPrecise(@min(wait_ns, std.time.ns_per_ms));
            continue;
        }
        const wall = c.SDL_GetTicksNS();
        const now = if (self.options.export_to != null)
            std.time.ns_per_s + self.exported * std.time.ns_per_s / self.options.fps
        else
            frameTime(wall, if (self.presentation) |p| p.sampleNs(wall) else wall, self.last_now, self.timeline.mode, self.pending.items);
        try self.frame(now);
    }
    self.timeline.stop();
}

// Live animation uses the display clock, but a tick must not predate its input.
fn frameTime(wall: u64, scheduled: u64, previous: u64, mode: abi.Mode, events: []const abi.Event) u64 {
    if (mode != .live and mode != .recording) return wall;
    var now = @max(scheduled, previous);
    for (events) |event| now = @max(now, event.time);
    return now;
}

test "timing clock drives ordinary ticks without moving input or replay time" {
    const expectEqual = std.testing.expectEqual;
    try expectEqual(@as(u64, 100), frameTime(103, 100, 80, .live, &.{}));
    try expectEqual(@as(u64, 120), frameTime(127, 120, 100, .recording, &.{}));
    const events = [_]abi.Event{ .{ .kind = .key_down, .time = 102 }, .{ .kind = .key_up, .time = 101 } };
    try expectEqual(@as(u64, 102), frameTime(103, 100, 80, .live, &events));
    try expectEqual(@as(u64, 102), events[0].time);
    try expectEqual(@as(u64, 101), events[1].time);
    try expectEqual(@as(u64, 103), frameTime(103, 103, 80, .live, &.{})); // No feedback.
    try expectEqual(@as(u64, 110), frameTime(103, 100, 110, .live, &.{})); // Clock reversal.
    for ([_]abi.Mode{ .playing, .paused }) |mode| try expectEqual(@as(u64, 103), frameTime(103, 100, 110, mode, &events));
}

pub fn live(self: *Host) []u8 {
    return self.state.slot(0);
}

/// One frame: reload if a build replaced the library, feed input through
/// `update`, then `draw` and present.
pub fn frame(self: *Host, now: u64) !void {
    const started = c.SDL_GetTicksNS();
    const zone = tracy.zone(@src(), "frame");
    tracy.frameMark();
    defer zone.end();
    _ = self.frame_arena.reset(.retain_capacity);
    self.commands = .empty;
    if (self.watch) |w| if (w.changed()) self.reload() catch |err| self.print("reload failed: {t}", .{err});

    const dt = if (self.last_now == 0) 0 else now -| self.last_now;
    self.last_now = now;
    const h = &self.timeline;
    switch (h.mode) {
        .playing => {
            self.sessions.away = true;
            self.update(h.tick(now));
        },
        .paused => self.sessions.away = true,
        .live, .recording => {
            // One frame: what was routed since the last one, then its tick.
            // Recorded first, so `update` sees the times a replay will.
            var tick = abi.Event.tick(now, dt);
            // An export's tick is 1/fps itself, not whole nanoseconds of it.
            if (self.options.export_to != null and dt != 0) tick.x = 1 / @as(f32, @floatFromInt(self.options.fps));
            try self.pending.append(self.gpa, tick);
            const why: ?Sessions.Why = if (self.sessions.frames == 0) .start else if (self.reloaded) .after_reload else if (self.jumped or self.sessions.away) .jump else null;
            self.sessions.away = false;
            self.sessions.frame(self.pending.items, self.live(), why) catch |err| self.print("session: {t}", .{err});
            self.update(self.pending.items);
        },
    }
    self.pending.clearRetainingCapacity();
    const work = try self.draw(if (h.mode == .live or h.mode == .recording) now else h.base + h.position, started);
    const ended = c.SDL_GetTicksNS();
    self.timing.add(.{ .frame = ended - (if (self.last_frame_end == 0) started else self.last_frame_end), .work = work });
    self.last_frame_end = ended;
}

/// Feeds whole frames to the sketch's deterministic `update`, one call per
/// frame (events up to and including a tick), live or replayed alike.
pub fn update(self: *Host, events: []const abi.Event) void {
    if (!self.session_ready) return;
    var frames = playback.frames(events);
    while (frames.next()) |one| {
        // Input follows the events actually fed, frame by frame.
        for (one) |e| self.input.track(e);
        const tick = one[one.len - 1];
        self.input.now = tick.time;
        self.input.dt = tick.tickDt();
        self.input.events = one;
        self.input.mode = self.timeline.mode;
        self.input.started = self.started;
        self.started = false;
        const ctx = self.context();
        self.sketch.update(&ctx, self.live().ptr);
        if (self.timeline.mode == .playing or self.timeline.mode == .paused) self.resync();
    }
    self.input.events = &.{};
}

/// After a replayed frame of a past session: at each keyframe it reaches,
/// live state is compared with the keyframe (over the leaves migration
/// kept), any difference said, and the keyframe restored.
fn resync(self: *Host) void {
    const h = &self.timeline;
    h.fed += 1;
    const session = h.session orelse return;
    const reached = h.key.?.frame + h.fed;
    while (h.next_check < h.checks.items.len and h.checks.items[h.next_check].frame <= reached) {
        const check = h.checks.items[h.next_check];
        h.next_check += 1;
        if (check.frame < reached) continue;
        const key = self.sessions.load(session, check.key) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err });
        defer key.free(self.gpa);
        var arena: std.heap.ArenaAllocator = .init(self.gpa);
        defer arena.deinit();
        const saved = arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), self.state.layout.size) catch return;
        const from = memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, saved, self.sketch.defaults) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err });
        if (check.observed) {
            const diff = memory.compareKept(from, self.state.layout, self.live(), saved);
            if (diff.first) |first| {
                var buf: [96]u8 = undefined;
                var w: std.Io.Writer = .fixed(&buf);
                first.leaf.name(first.offset, &w) catch {};
                self.print("diverged before frame {d}: {d} values, first {s}", .{ reached, diff.count, w.buffered() });
            }
        }
        @memcpy(self.live(), saved);
    }
}

/// After live state was restored from a snapshot: the pointer, buttons and
/// keys tracked so far belong to other bytes, so they start over. A new
/// recording then begins with events that bring back what is held now, so
/// its replay starts from the same input (they are fed and recorded as the
/// first frame's first events).
fn restoredInput(self: *Host, now: u64) !void {
    const h = &self.timeline;
    if (!h.restored) return;
    h.restored = false;
    const was = self.input;
    self.input.mouse_x = 0;
    self.input.mouse_y = 0;
    self.input.buttons = 0;
    self.input.keys = .empty;
    if (h.mode != .recording) return;
    var seed: std.ArrayList(abi.Event) = .empty;
    defer seed.deinit(self.gpa);
    if (was.mouse_x != 0 or was.mouse_y != 0) try seed.append(self.gpa, .{ .kind = .mouse_move, .time = now, .x = was.mouse_x, .y = was.mouse_y });
    for (0..32) |bit| if (was.buttons & (@as(u32, 1) << @intCast(bit)) != 0) {
        try seed.append(self.gpa, .{ .kind = .mouse_down, .time = now, .x = was.mouse_x, .y = was.mouse_y, .code = @intCast(bit + 1) });
    };
    var keys = was.keys.iterator(.{});
    while (keys.next()) |key| try seed.append(self.gpa, .{ .kind = .key_down, .time = now, .code = @intCast(key) });
    try self.pending.insertSlice(self.gpa, 0, seed.items);
}

fn draw(self: *Host, now: u64, started: u64) !u64 {
    const zone = tracy.zone(@src(), "Host.zig:draw");
    defer zone.end();
    const arena = self.frame_arena.allocator();
    self.input.now = now;
    self.input.mode = self.timeline.mode;
    self.input.reloaded = self.reloaded;
    self.input.jumped = self.jumped or self.reloaded;
    self.reloaded = false;
    self.jumped = false;
    self.input.console = self.console.visible;
    self.input.width = @floatFromInt(self.canvas[0]);
    self.input.height = @floatFromInt(self.canvas[1]);
    // Headless runs have no window to fill: the canvas is all the room,
    // unless `--size` gives one.
    const room = if (self.options.size) |size| size else self.canvas;
    self.input.window_width = @floatFromInt(room[0]);
    self.input.window_height = @floatFromInt(room[1]);
    if (!self.options.headless) {
        var w: c_int = 0;
        var h: c_int = 0;
        if (c.SDL_GetWindowSize(self.window, &w, &h) and w > 0 and h > 0) {
            self.input.window_width = @floatFromInt(w);
            self.input.window_height = @floatFromInt(h);
        }
    }
    self.input.streams = self.audio.streamStatus();
    self.input.sample_rate = sound.sample_rate;
    self.input.microphone = self.audio.record(arena);
    self.input.downloads = if (self.passes) |*g| try g.collect(arena) else &.{};
    self.input.frame += 1;
    const ctx = self.context();
    if (self.session_ready) self.sketch.draw(&ctx, self.live().ptr);

    _ = c.SDL_SetRenderTarget(self.renderer, self.offscreen);
    _ = c.SDL_SetRenderClipRect(self.renderer, null);
    _ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 255);
    _ = c.SDL_RenderClear(self.renderer);
    self.audio.beginFrame();
    self.painter.begin(self.offscreen, self.canvas, arena);
    var lines: std.ArrayList([]const u8) = .empty;
    {
        const paint_zone = tracy.zone(@src(), "paint commands");
        defer paint_zone.end();
        for (self.commands.items) |command| switch (command) {
            .canvas => |size| {
                self.painter.end();
                self.setCanvas(size.w, size.h);
                self.painter.begin(self.offscreen, self.canvas, arena);
            },
            .cursor => |kind| self.cursor = kind,
            .voice => |voice| self.audio.declare(voice),
            .gain => |g| self.audio.gains[g.group] = g.gain,
            .audio => |a| self.audio.push(a.key, a.samples, a.clear),
            .quit => self.quit = true,
            .gpu => |pass| if (self.passes) |*g| self.runGpu(g, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }),
            .post_process => |p| if (self.passes) |*g| self.runPostProcess(g, p.source, p.target, p.effect) catch |err| self.print("gpu postprocess: {t} ({s})", .{ err, c.SDL_GetError() }),
            .upload => |u| if (self.passes) |*g| g.write(u.buffer, u.offset, u.bytes) catch |err| self.print("gpu upload: {t} ({s})", .{ err, c.SDL_GetError() }),
            .compute => |d| if (self.passes) |*g| g.compute(d) catch |err| self.print("gpu compute: {t} ({s})", .{ err, c.SDL_GetError() }),
            .microphone => self.audio.listen(),
            .download => |d| if (self.passes) |*g| g.download(d) catch |err| self.print("gpu download: {t} ({s})", .{ err, c.SDL_GetError() }),
            .open_file => |o| self.openFile(o.command, o.pattern),
            .run => |line| try lines.append(arena, line),
            else => self.painter.draw(command),
        };
        self.painter.end();
        self.audio.endFrame();
    }
    for (lines.items) |line| self.runLine(line, now) catch {};

    var extra: std.ArrayList(abi.Command) = .empty;
    if (self.console.overlay_memory) try overlay.drawMemory(&extra, arena, self.state.layout, self.live(), self.input.width);
    if (self.console.overlay_sound) {
        const samples = self.audio.scope.snapshot();
        try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.canvas);
    }
    if (self.timing.visible) {
        if (self.timing_atlas.image == .none) self.timing_atlas = try overlay.TimingAtlas.init(&self.images, &self.painter);
        for (extra.items) |command| self.painter.draw(command);
        extra.clearRetainingCapacity();
        try overlay.drawTiming(&self.painter, &self.timing, self.canvas, self.timing_atlas);
    }
    if (self.console.visible) try self.console.draw(self, &extra, arena);
    if (self.options.timing_marker) try timing_marker.draw(&extra, arena, self.canvas, self.input.frame, self.input.now);
    for (extra.items) |command| self.painter.draw(command);
    self.painter.end();
    self.applyCursor();

    if (self.screenshot != null or self.options.export_to != null or (self.control != null and self.control.?.capture_pending)) {
        const surface = c.SDL_RenderReadPixels(self.renderer, null) orelse return sdlError("SDL_RenderReadPixels");
        defer c.SDL_DestroySurface(surface);
        if (self.screenshot) |path| {
            self.screenshot = null;
            if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG");
        }
        if (self.control) |control| if (control.capture_pending) control.capture(surface);
        if (self.options.export_to) |to| try self.exportFrame(surface, to);
    }
    if (!self.options.headless) if (self.offscreen) |canvas| {
        _ = c.SDL_SetRenderTarget(self.renderer, null);
        _ = c.SDL_SetTextureBlendMode(canvas, c.SDL_BLENDMODE_NONE);
        _ = c.SDL_RenderTexture(self.renderer, canvas, null, null);
    };
    // Present otherwise encodes the deferred 2D commands after the work timestamp.
    if (!c.SDL_FlushRenderer(self.renderer)) return sdlError("SDL_FlushRenderer");
    const work = c.SDL_GetTicksNS() - started;
    const present_zone = tracy.zone(@src(), "present");
    if (self.presentation) |p| p.request(self.input.frame, self.input.now);
    _ = c.SDL_RenderPresent(self.renderer);
    present_zone.end();
    if (self.passes) |*g| g.endFrame();
    return work;
}

/// One exported frame: `<to>/<its number, six digits>.png`, or for "-" its
/// RGBA rows on stdout (`ffmpeg -f rawvideo -pix_fmt rgba`).
fn exportFrame(self: *Host, surface: *c.SDL_Surface, to: []const u8) !void {
    if (std.mem.eql(u8, to, "-")) {
        // The offscreen canvas is RGBA already; a renderer without a GPU may not be.
        const rgba = if (surface.*.format == c.SDL_PIXELFORMAT_RGBA32) surface else c.SDL_ConvertSurface(surface, c.SDL_PIXELFORMAT_RGBA32) orelse return sdlError("SDL_ConvertSurface");
        defer if (rgba != surface) c.SDL_DestroySurface(rgba);
        const pixels: [*]const u8 = @ptrCast(rgba.*.pixels.?);
        const row: usize = @intCast(rgba.*.w * 4);
        const pitch: usize = @intCast(rgba.*.pitch);
        const rows: usize = @intCast(rgba.*.h);
        const out = std.Io.File.stdout();
        if (pitch == row) try out.writeStreamingAll(self.io, pixels[0 .. row * rows]) else for (0..rows) |y| try out.writeStreamingAll(self.io, pixels[y * pitch ..][0..row]);
    } else {
        var buf: [std.fs.max_path_bytes]u8 = undefined;
        const path = std.mem.printSentinel(&buf, "{s}/{d:0>6}.png", .{ to, self.exported }, 0) catch return error.NameTooLong;
        if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG");
    }
    self.exported += 1;
    if (self.options.frames) |n| if (self.exported >= n) {
        self.quit = true;
    };
}

/// A file dialog: shown on request, its answer run as a console line from
/// the main loop. SDL may answer on another thread.
const Dialog = struct {
    mutex: ?*c.SDL_Mutex = null,
    /// Shown and not yet answered (main thread only).
    showing: bool = false,
    command: [64]u8 = undefined,
    command_len: usize = 0,
    /// The filter SDL reads until it answers.
    pattern: [128:0]u8 = @splat(0),
    filter: c.SDL_DialogFileFilter = undefined,
    /// "<command> <path>" once answered; empty when cancelled.
    answer: [std.fs.max_path_bytes + 64]u8 = undefined,
    answer_len: ?usize = null,

    fn deinit(self: *Dialog) void {
        if (self.mutex) |m| c.SDL_DestroyMutex(m);
        self.mutex = null;
    }

    fn callback(userdata: ?*anyopaque, files: [*c]const [*c]const u8, _: c_int) callconv(.c) void {
        const self: *Dialog = @ptrCast(@alignCast(userdata orelse return));
        const m = self.mutex orelse return;
        c.SDL_LockMutex(m);
        defer c.SDL_UnlockMutex(m);
        const first = if (files != null and files[0] != null) std.mem.span(files[0]) else "";
        const line = if (first.len == 0) "" else std.mem.print(&self.answer, "{s} {s}", .{ self.command[0..self.command_len], first }) catch "";
        self.answer_len = line.len;
    }

    /// The answer's console line, once; empty when cancelled.
    fn take(self: *Dialog, out: []u8) ?[]const u8 {
        const m = self.mutex orelse return null;
        c.SDL_LockMutex(m);
        defer c.SDL_UnlockMutex(m);
        const len = self.answer_len orelse return null;
        self.answer_len = null;
        self.showing = false;
        @memcpy(out[0..len], self.answer[0..len]);
        return out[0..len];
    }
};

fn openFile(self: *Host, command: []const u8, pattern: []const u8) void {
    const d = &self.dialog;
    if (self.options.headless or d.showing) return;
    if (command.len > d.command.len or pattern.len > d.pattern.len) return self.print("open_file: command or pattern too long", .{});
    if (d.mutex == null) d.mutex = c.SDL_CreateMutex() orelse return self.print("open_file: {s}", .{c.SDL_GetError()});
    @memcpy(d.command[0..command.len], command);
    d.command_len = command.len;
    @memset(&d.pattern, 0);
    @memcpy(d.pattern[0..pattern.len], pattern);
    d.filter = .{ .name = "Files", .pattern = &d.pattern };
    d.showing = true;
    c.SDL_ShowOpenFileDialog(Dialog.callback, d, self.window, if (pattern.len > 0) &d.filter else null, @intFromBool(pattern.len > 0), null, false);
}

fn context(self: *Host) abi.Context {
    return .{
        .host = .{ .ctx = self, .vtable = &api },
        .input = &self.input,
        .scratch = self.frame_arena.allocator(),
        .session = self.session.heap.allocator(),
        .session_root = self.session.bytes.ptr,
        .commands = &self.commands,
    };
}

/// Sends one event to the console or towards the sketch. Backtick toggles the
/// console; while it is open it owns the keyboard, and pointer events over it
/// become a cancel, so a half-made click never lands behind it.
pub fn route(self: *Host, e: abi.Event) !void {
    if (e.kind == .key_down and e.code == @backingInt(abi.Key.grave)) {
        if (e.flags & abi.Event.repeat != 0) return;
        self.console.visible = !self.console.visible;
        return self.pending.append(self.gpa, .{ .kind = .cancel, .time = e.time });
    }
    if (self.console.visible) switch (e.kind) {
        .text => {
            var buf: [4]u8 = undefined;
            const len = std.unicode.utf8Encode(@intCast(@min(e.value, 0x10ffff)), &buf) catch return;
            self.console.insert(buf[0..len]);
            return;
        },
        .key_down => {
            const key = consoleKey(e) orelse return;
            if (self.console.edit(key, self.completions)) |line| self.runLine(line, e.time) catch {};
            return;
        },
        .key_up => return,
        .mouse_move, .mouse_down, .mouse_up, .wheel, .wheel_horizontal => if (e.y >= @as(f32, @floatFromInt(self.canvas[1])) - Console.panel_height) {
            return self.pending.append(self.gpa, .{ .kind = .cancel, .time = e.time });
        },
        else => {},
    };
    try self.pending.append(self.gpa, e);
}

/// Runs a console line now, replaying whatever a seek asks for. An error is
/// printed to the console, and returned for scripts to fail on.
pub fn runLine(self: *Host, line: []const u8, now: u64) !void {
    const zone = tracy.zone(@src(), "Host.zig:runLine");
    defer zone.end();
    const replay = self.console.execute(self, line, now) catch |err| {
        // The sketch has printed its own error already.
        if (err == error.NotRecording) {
            self.console.log("Not recording (a release build: .record = true collects): no marks or clips.");
        } else if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err});
        if (self.timeline.restored) self.jumped = true;
        try self.restoredInput(now);
        return err;
    };
    if (self.timeline.restored or movesState(line)) {
        self.jumped = true;
        self.sessions.noteLine(line);
    }
    try self.restoredInput(now);
    if (self.timeline.mode == .paused) self.update(replay);
}

/// Whether a console line that succeeded may have changed State other than
/// through `update` (restoring a snapshot is caught apart from this).
fn movesState(line: []const u8) bool {
    var words = std.mem.tokenizeAny(u8, line, " \t");
    const verb = words.next() orelse return false;
    const still = [_][]const u8{ "help", "overlay", "timing", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit", "sessions", "marks", "clips", "export-session", "import" };
    for (still) |w| if (std.mem.eql(u8, verb, w)) return false;
    return true;
}

/// Offers a line to the sketch.
pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) abi.Outcome {
    if (!self.session_ready) {
        self.print("session setup failed; restart after fixing the resource error", .{});
        return .failed;
    }
    self.input.now = now;
    const ctx = self.context();
    return self.sketch.command(&ctx, self.live().ptr, &line);
}

/// Fresh state: declared defaults, then the sketch's `init`.
pub fn resetState(self: *Host) void {
    const bytes = self.live();
    @memset(bytes, 0);
    self.sketch.defaults(.state, bytes.ptr);
    const ctx = self.context();
    self.sketch.init(&ctx, bytes.ptr);
    self.state.markUsed(0, true);
}

/// Loads the watched library again.
pub fn reload(self: *Host) !void {
    try self.load(self.options.library orelse return error.NoLibrary);
}

/// Replaces the running sketch with the library at `path`, keeping state.
pub fn load(self: *Host, path: []const u8) !void {
    var library = try Library.openFresh(self.io, path, scratchDir(self.environ), self.reloads + 1);
    errdefer library.close();
    // The State in the layout it is leaving, before migration drops any of it.
    if (self.sessions.mode() != .off) _ = self.sessions.keyframe(.before_reload, self.live()) catch |err| self.print("session: {t}", .{err});
    try self.adopt(library.sketch);
    if (self.library) |*old| old.close();
    self.library = library;
    self.reloads += 1;
    self.build = fileId(self.io, path);
    self.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.layoutBytes() }) catch |err| self.print("session: {t}", .{err});
    self.print("reload {d}: {s}", .{ self.reloads, path });
}

fn adopt(self: *Host, sketch: abi.Sketch) !void {
    const info = sketch.info();
    if (info.abi != abi.hash) return error.AbiMismatch;
    const adoption = try self.state.adopt(self.gpa, info.state, sketch.defaults);
    const session_reset = try self.session.adopt(self.gpa, info.session, sketch.defaults);
    if (session_reset) self.releaseMade();
    _ = self.info_arena.reset(.retain_capacity);
    const arena = self.info_arena.allocator();
    self.name = try arena.dupe(u8, info.name);
    self.source = try arena.dupe(u8, info.source);
    const completions = try arena.alloc([]const u8, info.commands.len);
    for (completions, info.commands) |*to, from| to.* = try arena.dupe(u8, from);
    self.completions = completions;
    self.sketch = sketch;
    self.timeline.defaults = sketch.defaults;
    self.reloaded = true;
    switch (adoption) {
        .unchanged => {},
        .created => {},
        .migrated => |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }),
    }
    if (!self.state.used(0)) self.resetState();
    if (session_reset) {
        const ctx = self.context();
        self.session_ready = self.sketch.setup(&ctx);
        if (!self.session_ready) self.console.visible = true;
    }
    if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{});
}

/// Frees what the old Session made: its handles are gone with it.
fn releaseMade(self: *Host) void {
    for (self.made.images.items) |image| {
        self.images.unwrap(image);
        if (self.passes) |*g| g.forget(image);
        self.images.free(image);
    }
    if (self.passes) |*g| for (self.made.buffers.items) |buffer| g.freeBuffer(buffer);
    self.made.images.clearRetainingCapacity();
    self.made.buffers.clearRetainingCapacity();
}

fn remember(self: *Host, comptime kind: enum { images, buffers }, handle: anytype) @TypeOf(handle) {
    if (handle != .none) @field(self.made, @tagName(kind)).append(self.gpa, handle) catch {};
    return handle;
}

fn forget(list: anytype, handle: anytype) void {
    for (list.items, 0..) |h, i| if (h == handle) {
        _ = list.swapRemove(i);
        return;
    };
}

fn setCanvas(self: *Host, w: u32, h: u32) void {
    if (w == 0 or h == 0 or (self.canvas[0] == w and self.canvas[1] == h)) return;
    self.canvas = .{ w, h };
    _ = c.SDL_SetRenderTarget(self.renderer, null);
    _ = c.SDL_SetRenderLogicalPresentation(self.renderer, @intCast(w), @intCast(h), c.SDL_LOGICAL_PRESENTATION_LETTERBOX);
    if (self.gpu != null) {
        if (self.offscreen) |texture| c.SDL_DestroyTexture(texture);
        self.offscreen = c.SDL_CreateTexture(self.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(w), @intCast(h));
        _ = c.SDL_SetRenderTarget(self.renderer, self.offscreen);
    }
    _ = c.SDL_SetWindowSize(self.window, @intCast(w), @intCast(h));
}

fn applyCursor(self: *Host) void {
    const kind: abi.Cursor = if (self.console.visible) .arrow else self.cursor;
    switch (kind) {
        .hidden => _ = c.SDL_HideCursor(),
        .arrow => {
            _ = c.SDL_SetCursor(c.SDL_GetDefaultCursor());
            _ = c.SDL_ShowCursor();
        },
        .pointer => {
            if (self.pointer_cursor == null) self.pointer_cursor = c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_POINTER);
            _ = c.SDL_SetCursor(self.pointer_cursor orelse c.SDL_GetDefaultCursor());
            _ = c.SDL_ShowCursor();
        },
    }
}

pub fn print(self: *Host, comptime fmt: []const u8, args: anytype) void {
    var buf: [512]u8 = undefined;
    const message = std.mem.print(&buf, fmt, args) catch "(message too long)";
    self.console.log(message);
    // Headless runs are tests: they report through their own results.
    if (!self.options.headless) std.debug.print("{s}\n", .{message});
}

/// Translates SDL events into sketch events and routes them.
pub fn poll(self: *Host) !void {
    const zone = tracy.zone(@src(), "Host.zig:poll");
    defer zone.end();
    var event: c.SDL_Event = undefined;
    while (c.SDL_PollEvent(&event)) {
        _ = c.SDL_ConvertEventToRenderCoordinates(self.renderer, &event);
        const time = event.common.timestamp;
        switch (event.type) {
            c.SDL_EVENT_QUIT => self.quit = true,
            c.SDL_EVENT_WINDOW_FOCUS_LOST => try self.route(.{ .kind = .cancel, .time = time }),
            c.SDL_EVENT_MOUSE_MOTION => try self.route(.{ .kind = .mouse_move, .time = time, .x = event.motion.x, .y = event.motion.y, .flags = held() }),
            c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP => try self.route(.{
                .kind = if (event.type == c.SDL_EVENT_MOUSE_BUTTON_DOWN) .mouse_down else .mouse_up,
                .time = time,
                .x = event.button.x,
                .y = event.button.y,
                .code = event.button.button,
                .flags = held(),
            }),
            c.SDL_EVENT_MOUSE_WHEEL => {
                const direction: f32 = if (event.wheel.direction == c.SDL_MOUSEWHEEL_FLIPPED) -1 else 1;
                const dx = event.wheel.x * direction;
                const dy = event.wheel.y * direction;
                if (std.math.isFinite(dy) and dy != 0) try self.route(.{ .kind = .wheel, .time = time, .x = event.wheel.mouse_x, .y = event.wheel.mouse_y, .value = @bitCast(dy), .flags = held() });
                if (std.math.isFinite(dx) and dx != 0) try self.route(.{ .kind = .wheel_horizontal, .time = time, .x = event.wheel.mouse_x, .y = event.wheel.mouse_y, .value = @bitCast(dx), .flags = held() });
            },
            c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_KEY_UP => try self.route(.{
                .kind = if (event.type == c.SDL_EVENT_KEY_DOWN) .key_down else .key_up,
                .time = time,
                .code = @intCast(event.key.scancode),
                .flags = if (event.key.repeat) abi.Event.repeat else 0,
                .value = modifiers(event.key.mod),
            }),
            c.SDL_EVENT_TEXT_INPUT => {
                var it = (std.unicode.Utf8View.init(std.mem.span(event.text.text)) catch continue).iterator();
                while (it.nextCodepoint()) |cp| try self.route(.{ .kind = .text, .time = time, .value = cp });
            },
            else => {},
        }
    }
    var buf: [@sizeOf(@FieldType(Dialog, "answer"))]u8 = undefined;
    if (self.dialog.take(&buf)) |line| if (line.len > 0) {
        self.console.print("> {s}", .{line});
        self.runLine(line, c.SDL_GetTicksNS()) catch {};
    };
}

/// The modifiers held now, for a pointer event's `flags`.
fn held() u8 {
    return abi.Event.withModifiers(modifiers(c.SDL_GetModState()));
}

fn modifiers(mod: c.SDL_Keymod) u32 {
    var m: u32 = 0;
    if (mod & c.SDL_KMOD_SHIFT != 0) m |= abi.Key.Mod.shift;
    if (mod & c.SDL_KMOD_CTRL != 0) m |= abi.Key.Mod.ctrl;
    if (mod & c.SDL_KMOD_ALT != 0) m |= abi.Key.Mod.alt;
    if (mod & c.SDL_KMOD_GUI != 0) m |= abi.Key.Mod.gui;
    return m;
}

fn consoleKey(e: abi.Event) ?Console.Key {
    const key: abi.Key = @fromBackingInt(@intCast(@as(u8, @truncate(e.code))));
    if (key == .u and e.value & abi.Key.Mod.ctrl != 0) return .clear;
    if (e.flags & abi.Event.repeat != 0 and key.isEnter()) return null;
    if (key.isEnter()) return .submit;
    return switch (key) {
        .left => .left,
        .right => .right,
        .home => .home,
        .end => .end,
        .backspace => .backspace,
        .delete => .delete,
        .escape => .clear,
        .tab => .tab,
        else => null,
    };
}

/// Starts this run's session (Sessions.zig): in a file beside the state
/// file when the build records, in memory for a script from fresh state,
/// nowhere for an export. A database that cannot be opened is said, and
/// the run goes on unrecorded.
fn openSessions(self: *Host, record: bool) void {
    const o = self.options;
    const mode: Sessions.Mode = if (o.export_to != null) .off else if (o.script and o.fresh) .memory else if (record) .file else .off;
    var buf: [std.fs.max_path_bytes]u8 = undefined;
    const stem = if (std.mem.endsWith(u8, o.state, ".state")) o.state[0 .. o.state.len - ".state".len] else o.state;
    const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{stem}) catch "sketch.xitdb";
    const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.layoutBytes() };
    self.sessions = Sessions.open(self.gpa, self.io, mode, path, first, wallClock(self.io)) catch |err| blk: {
        self.print("not recording: {s}: {t}", .{ path, err });
        break :blk .{ .gpa = self.gpa, .io = self.io };
    };
    if (o.headless) return;
    switch (self.sessions.mode()) {
        .file => self.print("recording to {s}", .{path}),
        .memory => {},
        .off => if (o.export_to == null) self.print("not recording (release build: .record = true collects)", .{}),
    }
}

/// Snapshots of a state file from before sessions become marks "1".."7",
/// then the file holds live state only. While nothing records, they stay.
fn importSnapshots(state: *memory.StateFile, sessions: *Sessions) !usize {
    if (state.slots == 1 or sessions.mode() == .off) return 0;
    var n: usize = 0;
    for (1..state.slots) |i| if (state.used(i)) {
        _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, state.slot(i));
        n += 1;
    };
    try state.dropSnapshots();
    return n;
}

fn wallClock(io: std.Io) u64 {
    return @intCast(@max(0, std.Io.Timestamp.now(io, .real).nanoseconds));
}

/// Identifies the file at `path` without reading it (a Debug library is tens
/// of megabytes): a hash of its inode, size and modification time; 0 when
/// there is none. A build replaces the file, so each build gets a new one.
fn fileId(io: std.Io, path: []const u8) u64 {
    const stat = std.Io.Dir.cwd().statFile(io, path, .{}) catch return 0;
    const id = [3]u64{ stat.inode, stat.size, @truncate(@as(u96, @bitCast(stat.mtime.nanoseconds))) };
    return std.hash.Wyhash.hash(0, std.mem.asBytes(&id)) | 1;
}

fn scratchDir(environ: *const std.process.Environ.Map) []const u8 {
    return environ.get("XDG_RUNTIME_DIR") orelse "/tmp";
}

fn sdlError(what: []const u8) error{Sdl} {
    std.log.err("{s}: {s}", .{ what, c.SDL_GetError() });
    return error.Sdl;
}

// Host services, as seen by sketches.
const api: abi.Host.VTable = .{
    .log = apiLog,
    .loadImage = apiLoadImage,
    .decodeImage = apiDecodeImage,
    .newImage = apiNewImage,
    .freeImage = apiFreeImage,
    .gpu = apiGpu,
    .newBuffer = apiNewBuffer,
    .freeBuffer = apiFreeBuffer,
    .writeBuffer = apiWriteBuffer,
    .imageSize = apiImageSize,
    .textSize = apiTextSize,
    .loadSound = apiLoadSound,
    .decodeSound = apiDecodeSound,
    .newSound = apiNewSound,
    .samples = apiSamples,
    .readFile = apiReadFile,
    .appendFile = apiAppendFile,
    .env = apiEnv,
    .clock = apiClock,
};

fn hostOf(ctx: *anyopaque) *Host {
    return @ptrCast(@alignCast(ctx));
}
fn apiLog(ctx: *anyopaque, message: []const u8) void {
    hostOf(ctx).print("{s}", .{message});
}
fn apiLoadImage(ctx: *anyopaque, path: []const u8) abi.Image {
    return hostOf(ctx).images.load(path);
}
fn apiDecodeImage(ctx: *anyopaque, png: []const u8) abi.Image {
    const self = hostOf(ctx);
    return self.remember(.images, self.images.decode(png));
}
fn apiNewImage(ctx: *anyopaque, w: u32, h: u32) abi.Image {
    const self = hostOf(ctx);
    return self.remember(.images, self.images.new(w, h));
}
fn apiFreeImage(ctx: *anyopaque, image: abi.Image) void {
    const self = hostOf(ctx);
    forget(&self.made.images, image);
    self.images.unwrap(image);
    if (self.passes) |*g| g.forget(image);
    self.images.free(image);
}
fn apiGpu(ctx: *anyopaque) bool {
    return hostOf(ctx).gpu != null;
}
fn apiNewBuffer(ctx: *anyopaque, size: u32) abi.Buffer {
    const self = hostOf(ctx);
    const g = if (self.passes) |*passes| passes else return .none;
    return self.remember(.buffers, g.newBuffer(size) catch |err| blk: {
        self.print("gpu buffer: {t} ({s})", .{ err, c.SDL_GetError() });
        break :blk .none;
    });
}
fn apiWriteBuffer(ctx: *anyopaque, buffer: abi.Buffer, offset: u32, bytes: []const u8) !void {
    const self = hostOf(ctx);
    const gpu = if (self.passes) |*passes| passes else return error.GpuUnavailable;
    try gpu.write(buffer, offset, bytes);
}
fn apiFreeBuffer(ctx: *anyopaque, buffer: abi.Buffer) void {
    const self = hostOf(ctx);
    forget(&self.made.buffers, buffer);
    if (self.passes) |*g| g.freeBuffer(buffer);
}
fn apiSamples(ctx: *anyopaque, audio: abi.Audio) []const f32 {
    return hostOf(ctx).audio.samplesOf(audio);
}
fn apiImageSize(ctx: *anyopaque, image: abi.Image) [2]u32 {
    return hostOf(ctx).images.size(image);
}
fn apiTextSize(ctx: *anyopaque, scale: f32, bytes: []const u8, face: abi.Face) [2]f32 {
    return gfx.textSize(hostOf(ctx).renderer, scale, bytes, face);
}
fn apiLoadSound(ctx: *anyopaque, path: []const u8) abi.Audio {
    return hostOf(ctx).audio.load(path);
}
fn apiDecodeSound(ctx: *anyopaque, wav: []const u8) abi.Audio {
    return hostOf(ctx).audio.decode(wav);
}
fn apiNewSound(ctx: *anyopaque, samples: [*]const f32, len: usize) callconv(.c) abi.Audio {
    return hostOf(ctx).audio.new(samples[0..len]);
}
fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 {
    const self = hostOf(ctx);
    if (self.files.get(path)) |bytes| return bytes;
    const bytes = memory.mapReadOnly(path);
    if (bytes.len == 0) return &.{};
    const key = self.gpa.dupe(u8, path) catch return bytes;
    self.files.put(self.gpa, key, bytes) catch self.gpa.free(key);
    return bytes;
}
fn apiAppendFile(ctx: *anyopaque, name_ptr: [*]const u8, name_len: usize, bytes: [*]const u8, len: usize, replace: bool) callconv(.c) [*:0]const u8 {
    const self = hostOf(ctx);
    const name = name_ptr[0..name_len];
    if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null) {
        self.print("appendFile: {s}: a name, not a path", .{name});
        return "";
    }
    var buf: [std.fs.max_path_bytes]u8 = undefined;
    const path = std.mem.print(&buf, "{s}.{s}", .{ self.options.state, name }) catch return "";
    if (replace) {
        // A new file: a mapping of the old one stays valid.
        std.Io.Dir.cwd().deleteFile(self.io, path) catch {};
        if (self.files.fetchRemove(path)) |old| {
            self.gpa.free(old.key);
            self.retired.append(self.gpa, old.value) catch {};
        }
    }
    const file = std.Io.Dir.cwd().createFile(self.io, path, .{ .truncate = false }) catch |err| {
        self.print("appendFile: {s}: {t}", .{ path, err });
        return "";
    };
    defer file.close(self.io);
    const end = file.length(self.io) catch return "";
    file.writePositionalAll(self.io, bytes[0..len], end) catch |err| {
        self.print("appendFile: {s}: {t}", .{ path, err });
        return "";
    };
    const kept = self.written.getOrPut(self.gpa, path) catch return "";
    if (!kept.found_existing) {
        const copy = self.gpa.dupeSentinel(u8, path, 0) catch {
            self.written.removeByPtr(kept.key_ptr);
            return "";
        };
        kept.key_ptr.* = copy;
    }
    return @ptrCast(kept.key_ptr.*.ptr);
}
fn apiClock(_: *anyopaque) u64 {
    return c.SDL_GetTicksNS();
}
fn apiEnv(ctx: *anyopaque, name: []const u8) ?[]const u8 {
    return hostOf(ctx).environ.get(name);
}

fn runPostProcess(self: *Host, g: *Gpu, source: abi.Image, target: abi.Image, post: abi.gpu.PostProcess) !void {
    const input = g.output(source) orelse return error.MissingImage;
    const before = g.output(target);
    const changed = if (before) |t| t.width != input.width or t.height != input.height else true;
    if (changed) self.images.unwrap(target);
    try g.runPostProcess(source, target, post);
    if (g.output(target)) |t| try self.images.wrap(target, t.texture, t.width, t.height);
}

fn runGpu(self: *Host, g: *Gpu, pass: abi.gpu.Pass) !void {
    const before = g.output(pass.image);
    const changed = if (before) |t| t.width != pass.width or t.height != pass.height else true;
    if (changed) self.images.unwrap(pass.image);
    try g.run(pass);
    if (g.output(pass.image)) |t| try self.images.wrap(pass.image, t.texture, t.width, t.height);
}

test "session setup runs for restored state and layout reset, not same-layout reload or state reset" {
    const Fixture = struct {
        const State = extern struct { value: u32 = 1 };
        const Session1 = extern struct { ready: u32 = 0 };
        const Session2 = extern struct { ready: u32 = 0, extra: u32 = 0 };
        var setup_calls: usize = 0;
        var init_calls: usize = 0;
        var fail_setup = false;
        const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session) };
        const changed: abi.Info = blk: {
            var value = description;
            value.session = abi.layout.of(Session2, .session);
            break :blk value;
        };
        fn info() callconv(.c) *const abi.Info {
            return &description;
        }
        fn info2() callconv(.c) *const abi.Info {
            return &changed;
        }
        fn defaults(kind: abi.Memory, ptr: [*]u8) callconv(.c) void {
            switch (kind) {
                .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{},
                .session => @as(*Session1, @ptrCast(@alignCast(ptr))).* = .{},
            }
        }
        fn defaults2(kind: abi.Memory, ptr: [*]u8) callconv(.c) void {
            if (kind == .session) @as(*Session2, @ptrCast(@alignCast(ptr))).* = .{} else defaults(kind, ptr);
        }
        fn init(_: *const abi.Context, _: [*]u8) callconv(.c) void {
            init_calls += 1;
        }
        fn setup(ctx: *const abi.Context) callconv(.c) bool {
            setup_calls += 1;
            @as(*u32, @ptrCast(@alignCast(ctx.session_root))).* += 1;
            return !fail_setup;
        }
        fn update(_: *const abi.Context, _: [*]u8) callconv(.c) void {}
        fn draw(_: *const abi.Context, _: [*]const u8) callconv(.c) void {}
        fn command(_: *const abi.Context, _: [*]u8, _: *const []const u8) callconv(.c) abi.Outcome {
            return .unknown;
        }
        const sketch: abi.Sketch = .{ .info = info, .defaults = defaults, .init = @This().init, .setup = setup, .update = @This().update, .draw = @This().draw, .command = command };
    };
    Fixture.setup_calls = 0;
    Fixture.init_calls = 0;
    Fixture.fail_setup = false;
    const a = std.testing.allocator;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var state_buf: [std.fs.max_path_bytes]u8 = undefined;
    const state_path = try std.mem.print(&state_buf, ".zig-cache/tmp/{s}/setup.state", .{&tmp.sub_path});
    {
        var state = try memory.StateFile.open(a, state_path);
        defer state.close();
        _ = try state.adopt(a, Fixture.description.state, Fixture.defaults);
        @as(*Fixture.State, @ptrCast(state.slot(0).ptr)).value = 77;
        state.markUsed(0, true);
    }
    // Exercise adoption with real persisted memory, without opening SDL devices.
    var host: Host = undefined;
    host.gpa = a;
    host.state = try memory.StateFile.open(a, state_path);
    defer host.state.close();
    host.session = .init(a);
    defer host.session.deinit(a);
    host.info_arena = .init(a);
    defer host.info_arena.deinit();
    host.frame_arena = .init(a);
    defer host.frame_arena.deinit();
    host.options = .{ .headless = true };
    host.console = .{};
    host.reloads = 0;
    host.made = .{};
    host.passes = null;
    host.input = .{};
    host.commands = .empty;
    try host.adopt(Fixture.sketch);
    try std.testing.expectEqual(@as(u32, 77), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value);
    try std.testing.expectEqual(@as(usize, 0), Fixture.init_calls);
    try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls);
    const session_ptr = host.session.bytes.ptr;
    try host.adopt(Fixture.sketch);
    try std.testing.expectEqual(session_ptr, host.session.bytes.ptr);
    try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls);
    host.resetState();
    try std.testing.expectEqual(@as(usize, 1), Fixture.init_calls);
    try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls);
    var changed = Fixture.sketch;
    changed.info = Fixture.info2;
    changed.defaults = Fixture.defaults2;
    try host.adopt(changed);
    try std.testing.expectEqual(@as(usize, 2), Fixture.setup_calls);
    try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.Session2, @ptrCast(host.session.bytes.ptr)).ready);
    try std.testing.expect(host.session_ready);
    Fixture.fail_setup = true;
    defer Fixture.fail_setup = false;
    try host.adopt(Fixture.sketch);
    try std.testing.expect(!host.session_ready);
    try std.testing.expect(host.console.visible);
    try std.testing.expectEqual(abi.Outcome.failed, host.forward(&host.console, "anything", 0));
    try host.adopt(Fixture.sketch);
    try std.testing.expect(!host.session_ready); // A compatible reload cannot bless partial resources.
    try std.testing.expectEqual(@as(usize, 3), Fixture.setup_calls);
}

test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload errors" {
    const a = std.testing.allocator;
    var host: Host = undefined;
    host.passes = null;
    const client: abi.Host = .{ .ctx = &host, .vtable = &api };
    try std.testing.expectError(error.GpuUnavailable, client.writeBuffer(.none, 0, "data"));
    host.passes = .{ .gpa = a, .device = undefined, .stencil_format = undefined };
    defer host.passes.?.buffers.deinit(a);
    try std.testing.expectError(error.UnknownBuffer, client.writeBuffer(.none, 0, "data"));
    try host.passes.?.buffers.append(a, .{ .buffer = undefined, .size = 4 });
    try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data"));
}

test "a state file's snapshots from before sessions become marks, and the file one slot" {
    const State = extern struct { v: u32 = 0 };
    const D = struct {
        fn f(_: abi.Memory, p: [*]u8) callconv(.c) void {
            @as(*State, @ptrCast(@alignCast(p))).* = .{};
        }
    };
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var buf: [std.fs.max_path_bytes]u8 = undefined;
    const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/old.state", .{&tmp.sub_path});
    // An eight-slot SKETCH02 file, slots 0, 1 and 3 used: built from a new
    // one-slot file's header.
    {
        var file = try memory.StateFile.open(gpa, path);
        defer file.close();
        _ = try file.adopt(gpa, abi.layout.of(State, .state), D.f);
    }
    const one = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited);
    defer gpa.free(one);
    const stride = memory.page;
    const old = try gpa.alloc(u8, memory.header_len + memory.old_slot_count * stride);
    defer gpa.free(old);
    @memset(old, 0);
    @memcpy(old[0..memory.header_len], one[0..memory.header_len]);
    const h: *memory.Header = @ptrCast(@alignCast(old.ptr));
    h.magic = memory.file_magic_v2;
    h.used = 0b1011;
    for ([_][2]u32{ .{ 0, 5 }, .{ 1, 11 }, .{ 3, 33 } }) |slot| std.mem.writeInt(u32, old[memory.header_len + slot[0] * stride ..][0..4], slot[1], .little);
    try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = old });

    var state = try memory.StateFile.open(gpa, path);
    defer state.close();
    try std.testing.expectEqual(memory.old_slot_count, state.slots);
    var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.layoutBytes() }, 0);
    defer sessions.deinit();
    try std.testing.expectEqual(@as(usize, 2), try importSnapshots(&state, &sessions));
    for ([_][2]u32{ .{ '1', 11 }, .{ '3', 33 } }) |want| {
        const m = (try sessions.findMark(&.{@intCast(want[0])})).?;
        const key = try sessions.load(m.session, m.key);
        defer key.free(gpa);
        try std.testing.expectEqual(Sessions.Why.import, key.why);
        try std.testing.expectEqual(want[1], std.mem.readInt(u32, key.state[0..4], .little));
    }
    try std.testing.expectEqual(@as(?Sessions.Entry, null), try sessions.findMark("2"));
    // One slot now, live state kept, and it reopens so.
    try std.testing.expectEqual(@as(usize, 1), state.slots);
    try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.slot(0)[0..4], .little));
    var again = try memory.StateFile.open(gpa, path);
    defer again.close();
    try std.testing.expectEqualStrings(&memory.file_magic, &again.header().magic);
    try std.testing.expectEqual(@as(usize, 1), again.slots);
    try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, again.slot(0)[0..4], .little));
}

test "appendFile appends to a file beside the state and names it for readFile" {
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    var buf: [std.fs.max_path_bytes]u8 = undefined;
    var host: Host = undefined;
    host.gpa = std.testing.allocator;
    host.io = io;
    host.written = .empty;
    host.files = .empty;
    host.options = .{ .state = try std.mem.print(&buf, ".zig-cache/tmp/{s}/t.state", .{&tmp.sub_path}) };
    defer {
        var written = host.written.keyIterator();
        while (written.next()) |path| host.gpa.free(path.ptr[0 .. path.len + 1]);
        host.written.deinit(host.gpa);
    }
    const name = "take-1.f32";
    const path = std.mem.span(apiAppendFile(&host, name, name.len, "ab", 2, false));
    try std.testing.expect(std.mem.endsWith(u8, path, "/t.state.take-1.f32"));
    try std.testing.expectEqual(path.ptr, apiAppendFile(&host, name, name.len, "cd", 2, false));
    const bytes = try tmp.dir.readFileAlloc(io, "t.state.take-1.f32", host.gpa, .unlimited);
    defer host.gpa.free(bytes);
    try std.testing.expectEqualStrings("abcd", bytes);
    // writeFile: a new file, its old bytes gone.
    _ = apiAppendFile(&host, name, name.len, "e", 1, true);
    const again = try tmp.dir.readFileAlloc(io, "t.state.take-1.f32", host.gpa, .unlimited);
    defer host.gpa.free(again);
    try std.testing.expectEqualStrings("e", again);
}