summaryrefslogtreecommitdiff
path: root/addons/snake_shader/snake_shader.zig
blob: d6f803d5b2e598fee4b73d63616b6d53999a8626 (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
//! A resizable snake with buffered turns and an optional CRT GPU picture.
//! h j k l or arrows steer; r restarts. Losing focus pauses movement.
const std = @import("std");
const addon = @import("addon");
const scene = @import("gpu_scene");
const shaders = @import("shaders");

const max_side = 126; // 4096 pixels / minimum 32-pixel tile, less the walls.
const period = 150 * std.time.ns_per_ms;
const grace = 60 * std.time.ns_per_ms;
const animation_period = 50 * std.time.ns_per_ms;
const Pt = extern struct { x: u8, y: u8 };
const Dir = [2]i8;
const Size = extern struct { cols: u16 = 0, rows: u16 = 0, cell_w: u16 = 0, cell_h: u16 = 0, glyphs: bool = false };
const Layout = struct { tile: u32, x: u32, y: u32 };
const Uniforms = extern struct { status: [4]f32, points: [4]f32, grid: [4]f32, motion: [4]f32, rows: [128][4]u32 };

// Version 1's exact record, so a live addon reload keeps the game.
const Legacy = extern struct {
    segs: [100]Pt,
    len: u16,
    food: Pt,
    dir: Dir,
    turn: Dir,
    dead: bool,
    score: u32,
    steps: u32,
    rng: u64,
    next: addon.Deadline,
};

pub const Snake = extern struct {
    segs: [max_side * max_side]Pt,
    len: u16,
    food: Pt,
    dir: Dir,
    turns: [2]Dir,
    queued: u8,
    dead: bool,
    score: u32,
    steps: u32,
    rng: u64,
    next: addon.Deadline,
    collision_at: u64,
    input_pending: bool,
    grace_given: bool,
    now: u64,
    width: u8,
    height: u8,
    owner: u8,
    sizes: [256]Size,
    hover_view: u8,
    hover_x: i16,
    hover_y: i16,

    pub const head: addon.Head = .{ .name = "snake_shader", .version = 2, .words = &.{
        .{ .name = "SnakeShader", .opens = true, .doc = "a resizable game of snake: h j k l steer, r restarts" },
    } };

    fn rnd(s: *Snake) u64 {
        s.rng ^= s.rng << 13;
        s.rng ^= s.rng >> 7;
        s.rng ^= s.rng << 17;
        return s.rng;
    }

    fn on(s: *const Snake, x: i32, y: i32, n: usize) bool {
        for (s.segs[0..n]) |q| if (q.x == x and q.y == y) return true;
        return false;
    }

    fn bits(s: *const Snake) [128][4]u32 {
        var out: [128][4]u32 = @splat(@splat(0));
        for (s.segs[0..s.len]) |p| out[p.y][p.x / 32] |= @as(u32, 1) << @intCast(p.x % 32);
        return out;
    }

    fn placeFood(s: *Snake) void {
        const area = @as(u32, s.width) * s.height;
        if (s.len == area) {
            s.dead = true;
            return;
        }
        var k = s.rnd() % (area - s.len);
        const occupied = s.bits();
        for (0..area) |i| {
            const p: Pt = .{ .x = @intCast(i % s.width), .y = @intCast(i / s.width) };
            if (occupied[p.y][p.x / 32] & (@as(u32, 1) << @intCast(p.x % 32)) != 0) continue;
            if (k == 0) {
                s.food = p;
                return;
            }
            k -= 1;
        }
    }

    fn restart(s: *Snake) void {
        if (s.width == 0) s.width = 20;
        if (s.height == 0) s.height = 5;
        s.len = 3;
        for (s.segs[0..3], 0..) |*p, i| p.* = .{ .x = @intCast(@max(2, s.width / 2) - i), .y = s.height / 2 };
        s.dir = .{ 1, 0 };
        s.queued = 0;
        s.dead = false;
        s.score = 0;
        s.steps = 0;
        s.next = .{};
        s.collision_at = 0;
        s.input_pending = false;
        s.grace_given = false;
        s.placeFood();
    }

    // A rejected move changes no coordinates: a late turn can still save it.
    fn step(s: *Snake) bool {
        const d = if (s.queued > 0) s.turns[0] else s.dir;
        const x = @as(i32, s.segs[0].x) + d[0];
        const y = @as(i32, s.segs[0].y) + d[1];
        const eats = x == s.food.x and y == s.food.y;
        if (x < 0 or y < 0 or x >= s.width or y >= s.height or s.on(x, y, if (eats) s.len else s.len - 1)) {
            s.queued = 0;
            return false;
        }
        s.dir = d;
        if (s.queued > 0) {
            s.turns[0] = s.turns[1];
            s.queued -= 1;
        }
        if (eats) s.len += 1;
        std.mem.copyBackwards(Pt, s.segs[1..s.len], s.segs[0 .. s.len - 1]);
        s.segs[0] = .{ .x = @intCast(x), .y = @intCast(y) };
        s.steps += 1;
        s.collision_at = 0;
        s.grace_given = false;
        if (eats) {
            s.score += 1;
            s.placeFood();
        }
        return true;
    }

    pub fn open(s: *Snake, _: ?[]const u8, _: ?[]const u8) void {
        s.rng = addon.seed() | 1;
        s.hover_x = -1;
        s.hover_y = -1;
        s.restart();
    }

    pub fn tick(s: *Snake, now: u64, flags: addon.Flags) u64 {
        s.now = now;
        // Only visible panes animate; the food and phosphor breathe at 20 Hz.
        const visible = for (s.sizes) |v| {
            if (v.cols > 0 and v.rows > 0) break true;
        } else false;
        if (!flags.focused or s.dead or !visible) {
            _ = s.next.stop();
            s.collision_at = 0;
            s.grace_given = false;
        } else {
            if (s.next.at == 0) s.next.at = now + period;
            if (s.input_pending and s.collision_at == 0 and !s.grace_given) {
                s.next.at = @max(s.next.at, now + grace);
                s.grace_given = true;
            }
            if (s.next.due(now) or (s.collision_at != 0 and s.input_pending)) {
                if (s.collision_at != 0 and now >= s.collision_at) {
                    s.dead = true;
                    _ = s.next.stop();
                } else if (s.step()) {
                    s.next.at = now + period;
                } else if (s.collision_at == 0) {
                    s.collision_at = now + grace;
                    s.next.at = s.collision_at;
                }
            }
        }
        s.input_pending = false;
        const animation = if (visible) now + animation_period else std.math.maxInt(u64);
        const next = @min(if (s.next.at == 0) std.math.maxInt(u64) else s.next.at, animation);
        return if (next == std.math.maxInt(u64)) 0 else next;
    }

    fn resize(s: *Snake, width: u8, height: u8) void {
        if (s.width == width and s.height == height) return;
        s.width = width;
        s.height = height;
        var lo = s.segs[0];
        var hi = lo;
        var keep: usize = 1;
        for (s.segs[1..s.len]) |p| {
            const low: Pt = .{ .x = @min(lo.x, p.x), .y = @min(lo.y, p.y) };
            const high: Pt = .{ .x = @max(hi.x, p.x), .y = @max(hi.y, p.y) };
            if (high.x - low.x >= width or high.y - low.y >= height) break;
            lo = low;
            hi = high;
            keep += 1;
        }
        // Keep the head and score; only an unfit tail is shortened on shrink.
        s.len = @intCast(keep);
        const dx = @max(@as(i16, hi.x) - width + 1, 0);
        const dy = @max(@as(i16, hi.y) - height + 1, 0);
        for (s.segs[0..s.len]) |*p| {
            p.x = @intCast(@as(i16, p.x) - dx);
            p.y = @intCast(@as(i16, p.y) - dy);
        }
        if (s.food.x >= width or s.food.y >= height or s.on(s.food.x, s.food.y, s.len)) s.placeFood();
        s.collision_at = 0;
        s.next = .{};
        s.hover_x = -1;
        s.hover_y = -1;
    }

    fn useView(s: *Snake, id: u8) void {
        const v = s.sizes[id];
        if (id == 0 or v.cols == 0 or v.rows == 0) return;
        s.owner = id;
        const tile = @max(32, v.cell_h);
        const cols = if (v.glyphs) v.cols else @min(4096, @as(u32, v.cols) * v.cell_w) / tile;
        const rows = if (v.glyphs) v.rows else @min(4096, @as(u32, v.rows) * v.cell_h) / tile;
        s.resize(@intCast(std.math.clamp(cols -| 2, 3, max_side)), @intCast(std.math.clamp(rows -| 2, 3, max_side)));
    }

    pub fn view(s: *Snake, v: addon.View) void {
        s.sizes[v.id] = .{ .cols = v.cols, .rows = v.rows, .cell_w = v.cell_w, .cell_h = v.cell_h, .glyphs = v.glyphs };
        if (s.hover_view == v.id and (v.cols == 0 or v.rows == 0)) {
            s.hover_x = -1;
            s.hover_y = -1;
        }
        if (s.owner == v.id and (v.cols == 0 or v.rows == 0)) s.owner = 0;
        if (s.owner == 0) for (s.sizes, 0..) |size, i| {
            if (i > 0 and size.cols > 0 and size.rows > 0) {
                s.useView(@intCast(i));
                break;
            }
        };
        if (s.owner == v.id) s.useView(v.id);
    }

    fn layout(s: *const Snake, width: u32, height: u32) Layout {
        const tile = @max(1, @min(width / (@as(u32, s.width) + 2), height / (@as(u32, s.height) + 2)));
        return .{ .tile = tile, .x = (width -| tile * (@as(u32, s.width) + 2)) / 2, .y = (height -| tile * (@as(u32, s.height) + 2)) / 2 };
    }

    pub fn mouse(s: *Snake, m: addon.Mouse) bool {
        if (m.action != .motion and m.action != .drag and m.button != .left) return false;
        if (m.action == .press) s.useView(m.view);
        const v = s.sizes[m.view];
        s.hover_view = m.view;
        s.hover_x = -1;
        s.hover_y = -1;
        if (m.col == 0xffff or m.row == 0xffff or v.cols == 0 or v.rows == 0) return true;
        if (v.glyphs) {
            if (m.col < @as(u16, s.width) + 2 and m.row < @as(u16, s.height) + 2) {
                s.hover_x = @intCast(m.col);
                s.hover_y = @intCast(m.row);
            }
        } else {
            const l = s.layout(@min(4096, @as(u32, v.cols) * v.cell_w), @min(4096, @as(u32, v.rows) * v.cell_h));
            const x = @as(u32, m.col) * v.cell_w + v.cell_w / 2;
            const y = @as(u32, m.row) * v.cell_h + v.cell_h / 2;
            if (x >= l.x and y >= l.y and (x - l.x) / l.tile < @as(u32, s.width) + 2 and (y - l.y) / l.tile < @as(u32, s.height) + 2) {
                s.hover_x = @intCast((x - l.x) / l.tile);
                s.hover_y = @intCast((y - l.y) / l.tile);
            }
        }
        return true;
    }

    fn opposite(a: Dir, b: Dir) bool {
        return a[0] == -b[0] and a[1] == -b[1];
    }
    fn same(a: Dir, b: Dir) bool {
        return a[0] == b[0] and a[1] == b[1];
    }

    pub fn key(s: *Snake, k: addon.Key) bool {
        if (k.code == .esc) return false;
        s.useView(k.view);
        if (s.dead or k.code == addon.char('r')) {
            s.restart();
            return true;
        }
        const d: Dir = switch (k.code) {
            .left, addon.char('h') => .{ -1, 0 },
            .right, addon.char('l') => .{ 1, 0 },
            .up, addon.char('k') => .{ 0, -1 },
            .down, addon.char('j') => .{ 0, 1 },
            else => return false,
        };
        const last = if (s.queued > 0) s.turns[s.queued - 1] else s.dir;
        if (same(d, last)) return true;
        if (opposite(d, last)) {
            // A quick j/k correction replaces an uncommitted turn, never a move.
            const before = if (s.queued > 1) s.turns[s.queued - 2] else s.dir;
            if (s.queued == 0 or opposite(d, before)) return true;
            s.turns[s.queued - 1] = d;
        } else {
            if (s.queued == s.turns.len) return true;
            s.turns[s.queued] = d;
            s.queued += 1;
        }
        s.input_pending = true;
        return true;
    }

    pub fn prefix(s: *const Snake, w: *std.Io.Writer) !void {
        try w.print("SnakeShader {d} {d}x{d}{s}", .{ s.score, s.width, s.height, if (s.dead) " over" else "" });
    }

    pub fn paint(s: *const Snake, w: addon.Window, out: addon.Paint) void {
        const wall: addon.Style = .{ .fg = .index(8) };
        for (0..@as(usize, s.height) + 2) |y| for (0..@as(usize, s.width) + 2) |x| if (x == 0 or x == s.width + 1 or y == 0 or y == s.height + 1) w.put(x, y, "#", wall);
        w.put(1 + s.food.x, 1 + s.food.y, "*", .{ .fg = .index(1), .attrs = .{ .bold = true } });
        for (s.segs[0..s.len], 0..) |p, i| w.put(1 + p.x, 1 + p.y, if (i > 0) "o" else if (s.dead) "x" else "@", .{ .fg = .index(2), .attrs = .{ .bold = i == 0 } });
        if (s.dead) w.put(0, s.height + 2, "game over: any key", .{ .fg = .index(1) }) else if (!w.focused) w.put(0, s.height + 2, "paused", wall);
        s.gpuPaint(w, out);
    }

    fn gpuPaint(s: *const Snake, w: addon.Window, out: addon.Paint) void {
        if (addon.api.abi < 0x30001 or out.out.gpu == null) return;
        const width: u32 = @min(4096, @max(1, @as(u32, w.cols) * w.cell_w));
        const height: u32 = @min(4096, @max(1, @as(u32, w.rows) * w.cell_h));
        const phase: f32 = @as(f32, @floatFromInt(s.now % (4 * std.time.ns_per_s))) / std.time.ns_per_s;
        const l = s.layout(width, height);
        const hover = s.hover_view == w.view;
        const uniforms: Uniforms = .{
            .status = .{ @floatFromInt(@intFromBool(s.dead)), @floatFromInt(@intFromBool(w.focused)), @floatFromInt(width), @floatFromInt(height) },
            .points = .{ @floatFromInt(s.segs[0].x), @floatFromInt(s.segs[0].y), @floatFromInt(s.food.x), @floatFromInt(s.food.y) },
            .grid = .{ @floatFromInt(s.width), @floatFromInt(s.height), @floatFromInt(if (hover) s.hover_x else @as(i16, -1)), @floatFromInt(if (hover) s.hover_y else @as(i16, -1)) },
            .motion = .{ phase, @floatFromInt(l.tile), @floatFromInt(l.x), @floatFromInt(l.y) },
            .rows = s.bits(),
        };
        const post: [4]f32 = .{ phase, 0, 0, 0 };
        const pipelines = [_]scene.abi.gpu.Pipeline{.{ .vertex = .{ .code = shaders.vert }, .fragment = .{ .code = shaders.frag, .uniform_buffers = 1 }, .stride = 0, .attributes = &.{} }};
        var buffer: [32768]u8 = undefined;
        var writer: std.Io.Writer = .fixed(&buffer);
        scene.encodePostProcess(&writer, .{ .image = .none, .width = width, .height = height, .pipelines = &pipelines, .draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = std.mem.asBytes(&uniforms) }} }, .{ .vertex = .{ .code = shaders.vert }, .fragment = .{ .code = shaders.post, .uniform_buffers = 1 }, .fragment_uniforms = std.mem.asBytes(&post) }) catch return;
        _ = out.gpu(writer.buffered());
    }

    pub fn body(s: *const Snake, w: *std.Io.Writer) !void {
        try w.print("score {d}\nlength {d}\nsteps {d}\n{s}\nboard {d}x{d}\nhover {d} {d}\n", .{ s.score, s.len, s.steps, if (s.dead) "over" else "alive", s.width, s.height, s.hover_x, s.hover_y });
    }
    pub fn ctlRead(s: *const Snake, w: *std.Io.Writer) !void {
        try s.body(w);
    }
    pub const dump = addon.dumpBytes;

    pub fn load(s: *Snake, bytes: []const u8, version: u32) bool {
        if (version == 1 and bytes.len == @sizeOf(Legacy)) {
            const old = std.mem.bytesToValue(Legacy, bytes);
            if (old.len == 0 or old.len > old.segs.len) return false;
            s.* = std.mem.zeroInit(Snake, .{ .width = 20, .height = 5, .len = old.len, .food = old.food, .dir = old.dir, .dead = old.dead, .score = old.score, .steps = old.steps, .rng = old.rng });
            @memcpy(s.segs[0..old.len], old.segs[0..old.len]);
            if (!same(old.dir, old.turn) and !opposite(old.dir, old.turn)) {
                s.turns[0] = old.turn;
                s.queued = 1;
            }
        } else if (!addon.loadBytes(s, bytes, version)) return false;
        if (s.width < 3 or s.height < 3 or s.width > max_side or s.height > max_side or s.len == 0 or s.len > @as(u32, s.width) * s.height or s.queued > 2) return false;
        for (s.segs[0..s.len]) |p| if (p.x >= s.width or p.y >= s.height) return false;
        if (s.food.x >= s.width or s.food.y >= s.height or @abs(s.dir[0]) + @as(u16, @abs(s.dir[1])) != 1) return false;
        for (s.turns[0..s.queued]) |d| if (@abs(d[0]) + @as(u16, @abs(d[1])) != 1) return false;
        s.hover_x = -1;
        s.hover_y = -1;
        s.next = .{};
        s.collision_at = 0;
        s.input_pending = false;
        s.grace_given = false;
        return true;
    }
};

pub const pardes_addon = addon.ops(Snake);
comptime {
    addon.exportLib(&pardes_addon);
}

fn testGame() Snake {
    var s = std.mem.zeroInit(Snake, .{ .rng = 3, .hover_x = -1, .hover_y = -1 });
    s.restart();
    s.view(testView(44, 7, 1));
    return s;
}
fn testView(cols: u16, rows: u16, id: u8) addon.View {
    return .{ .cols = cols, .rows = rows, .cell_w = 16, .cell_h = 32, .fg = .default, .bg = .default, .sel = .default, .link = .default, .dpi = 96, .max_px = 4096, .fill = true, .glyphs = false, .id = id };
}
const focused: addon.Flags = .{ .focused = true, .framed = true, ._ = 0 };

test "quick opposite corrections and consecutive corners retain intent without reversing" {
    var s = testGame();
    const start = s.segs[0];
    _ = s.key(.{ .code = addon.char('j') });
    _ = s.key(.{ .code = addon.char('k') });
    try std.testing.expectEqual(@as(u8, 1), s.queued);
    try std.testing.expect(s.step());
    try std.testing.expectEqual(start.y - 1, s.segs[0].y);
    _ = s.key(.{ .code = addon.char('j') });
    try std.testing.expectEqual(@as(u8, 0), s.queued);
    s.restart();
    _ = s.key(.{ .code = addon.char('j') });
    _ = s.key(.{ .code = addon.char('h') });
    try std.testing.expect(s.step());
    try std.testing.expectEqualDeep(Dir{ 0, 1 }, s.dir);
    try std.testing.expect(s.step());
    try std.testing.expectEqualDeep(Dir{ -1, 0 }, s.dir);
}

test "late turn gets sixty milliseconds and repeated keys cannot stall movement" {
    var s = testGame();
    _ = s.tick(1, focused);
    const due = s.next.at;
    _ = s.key(.{ .code = addon.char('j') });
    _ = s.tick(due - std.time.ns_per_ms, focused);
    const extended = s.next.at;
    try std.testing.expectEqual(due - std.time.ns_per_ms + grace, extended);
    _ = s.key(.{ .code = addon.char('k') });
    _ = s.tick(extended - 1, focused);
    try std.testing.expectEqual(extended, s.next.at);
    try std.testing.expectEqual(@as(u32, 0), s.steps);
    _ = s.tick(extended, focused);
    try std.testing.expectEqual(@as(u32, 1), s.steps);
    try std.testing.expectEqualDeep(Dir{ 0, -1 }, s.dir);
}

test "a late wall turn recovers during collision grace and missing it ends the round" {
    var s = testGame();
    for (s.segs[0..3], 0..) |*p, i| p.* = .{ .x = @intCast(s.width - 1 - i), .y = 2 };
    s.food = .{ .x = 0, .y = 0 };
    _ = s.tick(1, focused);
    const due = s.next.at;
    _ = s.tick(due, focused);
    try std.testing.expect(!s.dead);
    try std.testing.expectEqual(due + grace, s.collision_at);
    var missed = s;
    _ = missed.key(.{ .code = addon.char('k') });
    _ = missed.tick(due + grace, focused);
    try std.testing.expect(missed.dead);
    _ = s.key(.{ .code = addon.char('k') });
    _ = s.tick(due + grace - 1, focused);
    try std.testing.expect(!s.dead);
    try std.testing.expectEqual(@as(u32, 1), s.steps);
    try std.testing.expectEqual(@as(u8, 1), s.segs[0].y);
}

test "board uses whole square cells, resizes safely, and a replica does not change it" {
    var s = testGame();
    s.view(testView(80, 30, 1));
    try std.testing.expectEqual(@as(u8, 38), s.width);
    try std.testing.expectEqual(@as(u8, 28), s.height);
    s.view(testView(30, 10, 2));
    try std.testing.expectEqual(@as(u8, 38), s.width);
    const old_head = s.segs[0];
    s.view(testView(80, 40, 1));
    try std.testing.expectEqualDeep(old_head, s.segs[0]);
    s.score = 7;
    s.len = 5;
    for (s.segs[0..s.len], 0..) |*p, i| p.* = .{ .x = @intCast(10 - i), .y = 2 };
    s.resize(3, 3);
    try std.testing.expectEqual(@as(u32, 7), s.score);
    try std.testing.expectEqual(@as(u16, 3), s.len);
    for (s.segs[0..s.len]) |p| try std.testing.expect(p.x < 3 and p.y < 3);
    try std.testing.expect(!s.on(s.food.x, s.food.y, s.len));
    const l = s.layout(1333, 977);
    try std.testing.expect(l.tile * (s.width + @as(u32, 2)) <= 1333);
    try std.testing.expect(l.tile * (s.height + @as(u32, 2)) <= 977);
    s.width = max_side;
    s.height = max_side;
    s.len = 1;
    s.segs[0] = .{ .x = 125, .y = 125 };
    const occupied = s.bits();
    try std.testing.expectEqual(@as(u32, 1) << 29, occupied[125][3]);
}

test "hover maps to discrete cells, clears on leave, and idle animation never moves the snake" {
    var s = testGame();
    s.view(testView(80, 30, 1));
    const m: addon.Mouse = .{ .button = .left, .action = .motion, .ctrl = false, .alt = false, .shift = false, .view = 1, .col = 4, .row = 3, .amount = 0 };
    try std.testing.expect(s.mouse(m));
    try std.testing.expectEqual(@as(i16, 2), s.hover_x);
    try std.testing.expectEqual(@as(i16, 3), s.hover_y);
    const before = s.segs[0];
    try std.testing.expectEqual(10 + animation_period, s.tick(10, .{ .focused = false, .framed = true, ._ = 0 }));
    _ = s.tick(10 + animation_period, .{ .focused = false, .framed = true, ._ = 0 });
    try std.testing.expectEqualDeep(before, s.segs[0]);
    var leave = m;
    leave.col = 0xffff;
    leave.row = 0xffff;
    _ = s.mouse(leave);
    try std.testing.expectEqual(@as(i16, -1), s.hover_x);
    _ = s.mouse(m);
    s.view(testView(0, 0, 1));
    try std.testing.expectEqual(@as(i16, -1), s.hover_x);
    try std.testing.expectEqual(@as(u64, 0), s.tick(100, .{ .focused = false, .framed = false, ._ = 0 }));
}

test "old records migrate and current records retain geometry and game state on reload" {
    var old = std.mem.zeroInit(Legacy, .{ .len = 3, .food = .{ .x = 1, .y = 1 }, .dir = .{ 1, 0 }, .turn = .{ 0, -1 }, .score = 4, .steps = 12, .rng = 3 });
    for (old.segs[0..3], 0..) |*p, i| p.* = .{ .x = @intCast(10 - i), .y = 2 };
    var s: Snake = undefined;
    try std.testing.expect(Snake.load(&s, std.mem.asBytes(&old), 1));
    try std.testing.expectEqual(@as(u32, 4), s.score);
    try std.testing.expectEqual(@as(u32, 12), s.steps);
    try std.testing.expectEqualDeep(old.segs[0], s.segs[0]);
    s.view(testView(80, 30, 1));
    var record: [@sizeOf(Snake)]u8 = undefined;
    var back: Snake = undefined;
    try std.testing.expect(Snake.load(&back, record[0..Snake.dump(&s, &record)], 2));
    try std.testing.expectEqualDeep(s.sizes, back.sizes);
    try std.testing.expectEqual(s.score, back.score);
    try std.testing.expectEqualDeep(s.segs[0..s.len], back.segs[0..back.len]);
    try std.testing.expect(!Snake.load(&back, &record, 3));
    old.len = 101;
    try std.testing.expect(!Snake.load(&back, std.mem.asBytes(&old), 1));
}

test "GPU fallback stays optional and dynamic board and post uniforms encode without mutation" {
    var api = std.mem.zeroes(addon.c.pa_api);
    api.abi = 0x30000;
    addon.api = &api;
    var output = std.mem.zeroes(addon.c.pa_paint);
    const paint: addon.Paint = .{ .out = &output };
    try std.testing.expect(!paint.gpu("unused"));
    api.abi = 0x30001;
    try std.testing.expect(!paint.gpu("unused"));
    var s = testGame();
    s.view(testView(80, 30, 1));
    const before = s;
    const Capture = struct {
        called: bool = false,
        fn emit(ctx: ?*anyopaque, bytes: [*c]const u8, n: u32) callconv(.c) c_int {
            const self: *@This() = @ptrCast(@alignCast(ctx.?));
            var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
            defer arena.deinit();
            const frame = scene.decodeFrame(arena.allocator(), bytes[0..n]) catch return 1;
            self.called = frame.pass.draws[0].fragment_uniforms.len == @sizeOf(Uniforms) and frame.post != null and frame.post.?.fragment_uniforms.len == 16 and frame.pass.width == 1280 and frame.pass.height == 960;
            return 0;
        }
    };
    var capture: Capture = .{};
    output.gpu = Capture.emit;
    output.gpu_ctx = &capture;
    var cells: [80 * 30]addon.c.pa_cell = @splat(std.mem.zeroes(addon.c.pa_cell));
    s.paint(.{ .cells = &cells, .stride = 80, .cols = 80, .rows = 30, .cell_w = 16, .cell_h = 32, .focused = true, .view = 1, .glyphs = false }, paint);
    try std.testing.expect(capture.called);
    try std.testing.expectEqualDeep(s, before);
}