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
|
//! 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 c = @import("c");
const abi = @import("abi");
const memory = @import("memory.zig");
const Timeline = @import("timeline.zig").Timeline;
const mapRecordings = @import("timeline.zig").mapRecordings;
const gfx = @import("gfx.zig");
const sound = @import("audio.zig");
const Gpu = @import("gpu.zig");
const overlay = @import("overlay.zig");
const Console = @import("Console.zig");
const Library = @import("library.zig").Library;
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,
/// State file; recordings go next to it with an `.inputs` suffix.
state: []const u8 = "sketch.state",
/// 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,
};
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,
passes: ?Gpu = null,
/// Headless with a GPU: the renderer has no window and draws into this
/// canvas-sized texture, which screenshots read.
offscreen: ?*c.SDL_Texture = null,
pointer_cursor: ?*c.SDL_Cursor = null,
images: gfx.Images,
audio: sound.Audio,
state: memory.StateFile,
session: memory.Session,
store: memory.StoreFile,
/// 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 } = .{},
recordings: []align(memory.page) u8,
timeline: Timeline,
console: Console = .{},
sketch: abi.Sketch,
library: ?Library = null,
watch: ?Watch = null,
reloads: usize = 0,
/// Copies of the sketch's info strings, replaced on every load.
info_arena: std.heap.ArenaAllocator,
name: []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,
canvas: [2]u32 = .{ 0, 0 },
cursor: abi.Cursor = .arrow,
quit: bool = false,
reloaded: bool = true,
started: bool = true,
last_now: u64 = 0,
/// Saved after the next frame is drawn (scripts).
screenshot: ?[:0]const u8 = null,
dialog: Dialog = .{},
pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void {
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.openCopy(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");
}
errdefer c.SDL_DestroyRenderer(renderer);
errdefer if (gpu) |device| c.SDL_DestroyGPUDevice(device);
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 state = try memory.StateFile.open(gpa, options.state);
errdefer state.close();
var inputs_buf: [std.fs.max_path_bytes]u8 = undefined;
const recordings = try mapRecordings(try std.mem.print(&inputs_buf, "{s}.inputs", .{options.state}));
errdefer std.posix.munmap(recordings);
var store_buf: [std.fs.max_path_bytes]u8 = undefined;
var store = memory.StoreFile.open(gpa, try std.mem.print(&store_buf, "{s}.store", .{options.state}), options.fresh) catch |err| {
if (err == error.StoreInUse) std.log.err("{s}.store is open in another process", .{options.state});
return err;
};
errdefer store.close();
self.* = .{
.gpa = gpa,
.io = io,
.environ = environ,
.options = options,
.window = window,
.renderer = renderer.?,
.gpu = gpu,
.images = .{ .gpa = gpa, .renderer = renderer.? },
.audio = .{ .gpa = gpa },
.state = state,
.session = .init(gpa),
.store = store,
.recordings = recordings,
.timeline = undefined,
.sketch = sketch,
.library = library,
.info_arena = .init(gpa),
.frame_arena = .init(gpa),
};
self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } };
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;
};
self.setCanvas(info.width, info.height);
_ = c.SDL_StartTextInput(self.window);
try self.adopt(sketch);
if (options.fresh) {
self.state.header().used = 0;
@memset(self.recordings, 0);
self.resetState();
}
}
pub fn deinit(self: *Host) void {
self.dialog.deinit();
if (self.watch) |w| w.deinit();
self.audio.deinit();
if (self.passes) |*g| g.deinit(&self.images);
self.images.deinit();
if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor);
if (self.offscreen) |texture| c.SDL_DestroyTexture(texture);
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);
std.posix.munmap(self.recordings);
self.session.deinit(self.gpa);
self.store.close();
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();
if (self.library) |*l| l.close();
c.SDL_Quit();
}
/// The interactive loop.
pub fn run(self: *Host) !void {
while (!self.quit) {
try self.poll();
try self.frame(c.SDL_GetTicksNS());
}
self.timeline.stop(c.SDL_GetTicksNS());
}
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 {
_ = 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.update(h.tick(now)),
.paused => {},
.live, .recording => {
try self.pending.append(self.gpa, .{ .kind = .tick, .time = now, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) });
for (self.pending.items) |e| h.capture(e) catch |err| self.print("Recording stopped: {t}", .{err});
self.input.now = now;
self.input.dt = dt;
self.update(self.pending.items);
},
}
self.pending.clearRetainingCapacity();
try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position);
}
/// Feeds events to the sketch's deterministic `update`.
pub fn update(self: *Host, events: []const abi.Event) void {
// Input follows the events actually fed, live or replayed.
for (events) |e| self.input.track(e);
if (events.len > 0 and self.timeline.mode != .live and self.timeline.mode != .recording) self.input.now = events[events.len - 1].time;
self.input.events = events;
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);
self.input.events = &.{};
}
fn draw(self: *Host, now: u64) !void {
const arena = self.frame_arena.allocator();
self.input.now = now;
self.input.mode = self.timeline.mode;
self.input.reloaded = self.reloaded;
self.reloaded = 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.
self.input.window_width = self.input.width;
self.input.window_height = self.input.height;
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();
self.sketch.draw(&ctx, self.live().ptr);
_ = c.SDL_SetRenderClipRect(self.renderer, null);
_ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 255);
_ = c.SDL_RenderClear(self.renderer);
self.audio.beginFrame();
var lines: std.ArrayList([]const u8) = .empty;
for (self.commands.items) |command| switch (command) {
.canvas => |size| self.setCanvas(size.w, size.h),
.cursor => |kind| self.cursor = kind,
.voice => |voice| self.audio.declare(voice),
.audio => |a| self.audio.push(a.key, a.samples, a.clear),
.quit => self.quit = true,
.gpu => |pass| if (self.passes) |*g| g.run(&self.images, pass) catch |err| self.print("gpu pass: {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 => gfx.draw(self.renderer, &self.images, command),
};
self.audio.endFrame();
for (lines.items) |line| self.runLine(line, now) catch {};
_ = c.SDL_SetRenderClipRect(self.renderer, null);
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.console.visible) try self.console.draw(self, &extra, arena);
for (extra.items) |command| gfx.draw(self.renderer, &self.images, command);
self.applyCursor();
if (self.screenshot) |path| {
self.screenshot = null;
const surface = c.SDL_RenderReadPixels(self.renderer, null) orelse return sdlError("SDL_RenderReadPixels");
defer c.SDL_DestroySurface(surface);
if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG");
}
_ = c.SDL_RenderPresent(self.renderer);
if (self.passes) |*g| g.endFrame();
}
/// 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(),
.store = self.store.allocator(),
.session_root = self.session.bytes.ptr,
.store_root = self.store.root(),
.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 replay = self.console.execute(self, line, now) catch |err| {
// The sketch has printed its own error already.
if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err});
return err;
};
if (self.timeline.mode == .paused) self.update(replay);
}
/// Offers a line to the sketch.
pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) abi.Outcome {
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.openCopy(self.io, path, scratchDir(self.environ), self.reloads + 1);
errdefer library.close();
try self.adopt(library.sketch);
if (self.library) |*old| old.close();
self.library = library;
self.reloads += 1;
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();
const stored = try self.store.adopt(self.gpa, info.store, sketch.defaults);
_ = self.info_arena.reset(.retain_capacity);
const arena = self.info_arena.allocator();
self.name = try arena.dupe(u8, info.name);
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.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 and self.reloads > 0) self.print("session layout changed: session reset", .{});
switch (stored) {
.unchanged, .created => {},
.migrated => |m| self.print("store layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }),
}
}
/// Frees what the old Session made: its handles are gone with it.
fn releaseMade(self: *Host) void {
for (self.made.images.items) |image| {
if (self.passes) |*g| g.forget(&self.images, 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 };
if (self.options.headless and 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);
} else {
_ = c.SDL_SetRenderLogicalPresentation(self.renderer, @intCast(w), @intCast(h), c.SDL_LOGICAL_PRESENTATION_LETTERBOX);
}
_ = 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 {
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,
};
}
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,
.imageSize = apiImageSize,
.loadSound = apiLoadSound,
.decodeSound = apiDecodeSound,
.samples = apiSamples,
.readFile = apiReadFile,
.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);
if (self.passes) |*g| g.forget(&self.images, 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 = &(self.passes orelse 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 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 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 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 apiClock(_: *anyopaque) u64 {
return c.SDL_GetTicksNS();
}
fn apiEnv(ctx: *anyopaque, name: []const u8) ?[]const u8 {
return hostOf(ctx).environ.get(name);
}
|