pixel8-runtime 0.1.0

Pixel8 fantasy console runtime: VM, framebuffer, input, audio, assets, carts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
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
//! WASM game execution: sandbox, host ABI, and lifecycle calls.
//!
//! Carts are `wasm32-unknown-unknown` modules executed with wasmi. The
//! only way a cart can touch the outside world is through the small,
//! C-like import set in the `"pixel8"` module — no WASI, no filesystem,
//! no network. Fuel metering keeps runaway loops from hanging the
//! console; they surface as a friendly error screen instead.

use crate::{
    assets::{Assets, MapData, SpriteSheet},
    audio::AudioHandle,
    fb::Framebuffer,
    input::InputState,
    storage::Storage,
};
use anyhow::{anyhow, Context as _, Result};
use wasmi::{
    Caller, Config, Engine, Instance, Linker, Module, Store, StoreLimits, StoreLimitsBuilder,
    TypedFunc,
};

/// A cart's logical frames per second when it doesn't say otherwise.
pub const DEFAULT_FPS: u32 = 60;

/// The console's own tick rate: editors, menus and cart pickers. Independent
/// of the cart rate, which the cart chooses via `pixel8_fps`.
pub const UI_FPS: u32 = 30;

/// Fuel budget for a single lifecycle call. wasmi charges ~1 fuel per
/// instruction, so this is a hard cap of 131,072 (128 K) wasm instructions
/// per call — one number shared with the memory and cart-size limits. A real
/// frame uses a few thousand; exceeding this means the cart is stuck or doing
/// far too much, and surfaces as a friendly error screen.
const FUEL_PER_CALL: u64 = 131_072;

/// Hard cap on a cart's total linear memory: 128 K, the same number as the
/// fuel and cart-size limits. Covers static data, the shadow stack and the
/// heap together (wasm cannot separate them). Carts default to a 32 KiB stack
/// reserve (set per-cart in `.cargo/config.toml`), leaving up to ~96 KiB for
/// static data and heap above it; carts may tune it.
const MAX_MEMORY: usize = crate::cart::MEMORY_CAP;

/// A loaded, running cart.
pub struct GameVm {
    store: Store<HostState>,
    _instance: Instance,
    update: TypedFunc<(), ()>,
    draw: TypedFunc<(), ()>,
}

macro_rules! link {
    ($linker:expr, $name:literal, $f:expr) => {
        $linker
            .func_wrap("pixel8", $name, $f)
            .with_context(|| format!("registering host fn {}", $name))?;
    };
}

impl GameVm {
    /// Load a cart module, wire up the ABI, and run `pixel8_init`.
    ///
    /// `storage` is the cart's persistent key-value store, loaded before
    /// `pixel8_init` runs so the cart can read its save data from the first
    /// frame. Frontends without persistence pass `Storage::default()`.
    pub fn load(
        wasm: &[u8],
        assets: &Assets,
        audio: AudioHandle,
        storage: Storage,
    ) -> Result<Self> {
        // The single chokepoint every frontend runs a cart through: the
        // desktop console, the standalone player, the web player and headless
        // verify all land here. Reject mis-sized asset bundles before they
        // reach the renderer, regardless of where the cart came from (a PNG
        // cart, an on-disk project, or a hand-built module).
        crate::assets::validate(assets)?;

        let mut config = Config::default();
        config.consume_fuel(true);
        let engine = Engine::new(&config);
        let module = Module::new(&engine, wasm).map_err(|e| anyhow!("Invalid cart wasm: {e}"))?;

        audio.load(assets.sfx.clone(), assets.music.clone());
        let mut store = Store::new(&engine, HostState::new(assets, audio, storage));
        store.limiter(|state| &mut state.limits);
        let mut linker = <Linker<HostState>>::new(&engine);

        link!(linker, "clear", |mut c: Caller<'_, HostState>, col: i32| {
            c.data_mut().fb.cls(col as u8)
        });
        link!(linker, "camera", |mut c: Caller<'_, HostState>,
                                 x: i32,
                                 y: i32| {
            c.data_mut().fb.camera(x, y)
        });
        link!(linker, "clip", |mut c: Caller<'_, HostState>,
                               x: i32,
                               y: i32,
                               w: i32,
                               h: i32| {
            c.data_mut().fb.clip(x, y, w, h)
        });
        link!(
            linker,
            "set_pixel",
            |mut c: Caller<'_, HostState>, x: i32, y: i32, col: i32| {
                c.data_mut().fb.pset(x, y, col as u8)
            }
        );
        link!(linker, "pixel", |c: Caller<'_, HostState>,
                                x: i32,
                                y: i32|
         -> i32 {
            c.data().fb.pget(x, y) as i32
        });
        link!(linker, "line", |mut c: Caller<'_, HostState>,
                               x0: i32,
                               y0: i32,
                               x1: i32,
                               y1: i32,
                               col: i32| {
            c.data_mut().fb.line(x0, y0, x1, y1, col as u8)
        });
        link!(linker, "rect", |mut c: Caller<'_, HostState>,
                               x0: i32,
                               y0: i32,
                               x1: i32,
                               y1: i32,
                               col: i32| {
            c.data_mut().fb.rect(x0, y0, x1, y1, col as u8)
        });
        link!(
            linker,
            "rect_fill",
            |mut c: Caller<'_, HostState>, x0: i32, y0: i32, x1: i32, y1: i32, col: i32| {
                c.data_mut().fb.rectfill(x0, y0, x1, y1, col as u8)
            }
        );
        link!(
            linker,
            "circle",
            |mut c: Caller<'_, HostState>, x: i32, y: i32, r: i32, col: i32| {
                c.data_mut().fb.circ(x, y, r, col as u8)
            }
        );
        link!(
            linker,
            "circle_fill",
            |mut c: Caller<'_, HostState>, x: i32, y: i32, r: i32, col: i32| {
                c.data_mut().fb.circfill(x, y, r, col as u8)
            }
        );
        link!(linker, "print", |mut c: Caller<'_, HostState>,
                                ptr: u32,
                                len: u32,
                                x: i32,
                                y: i32,
                                col: i32|
         -> i32 {
            let s = read_guest_str(&c, ptr, len);
            c.data_mut().fb.print(&s, x, y, col as u8)
        });
        link!(linker, "is_button_down", |c: Caller<'_, HostState>,
                                         b: u32|
         -> i32 {
            c.data().input.btn(b) as i32
        });
        link!(linker, "is_button_pressed", |c: Caller<'_, HostState>,
                                            b: u32|
         -> i32 {
            c.data().input.btnp(b) as i32
        });
        link!(linker, "buttons_down", |c: Caller<'_, HostState>| -> i32 {
            c.data().input.btn_mask() as i32
        });
        link!(
            linker,
            "buttons_pressed",
            |c: Caller<'_, HostState>| -> i32 { c.data().input.btnp_mask() as i32 }
        );
        link!(
            linker,
            "sprite",
            |mut c: Caller<'_, HostState>,
             n: u32,
             x: i32,
             y: i32,
             w: i32,
             h: i32,
             flip_x: i32,
             flip_y: i32| {
                let HostState { fb, sprites, .. } = c.data_mut();
                fb.spr(sprites, n, x, y, w, h, flip_x != 0, flip_y != 0);
            }
        );
        link!(linker, "map", |mut c: Caller<'_, HostState>,
                              cel_x: i32,
                              cel_y: i32,
                              sx: i32,
                              sy: i32,
                              cel_w: i32,
                              cel_h: i32,
                              layers: u32| {
            let HostState {
                fb, sprites, map, ..
            } = c.data_mut();
            fb.map(
                map,
                sprites,
                cel_x,
                cel_y,
                sx,
                sy,
                cel_w,
                cel_h,
                layers as u8,
            );
        });
        link!(linker, "map_tile", |c: Caller<'_, HostState>,
                                   x: i32,
                                   y: i32|
         -> i32 {
            c.data().map.get(x, y) as i32
        });
        link!(
            linker,
            "set_map_tile",
            |mut c: Caller<'_, HostState>, x: i32, y: i32, v: u32| {
                c.data_mut().map.set(x, y, v as u8)
            }
        );
        link!(linker, "sprite_flags", |c: Caller<'_, HostState>,
                                       n: u32|
         -> i32 {
            c.data().sprites.flags(n) as i32
        });
        link!(
            linker,
            "set_sprite_flags",
            |mut c: Caller<'_, HostState>, n: u32, flags: u32| {
                c.data_mut().sprites.flags[(n as usize) % crate::assets::SPRITE_COUNT] =
                    flags as u8;
            }
        );
        link!(linker, "sfx", |c: Caller<'_, HostState>,
                              n: i32,
                              channel: i32| {
            c.data().audio.play_sfx(n, channel)
        });
        link!(linker, "music", |c: Caller<'_, HostState>,
                                n: i32,
                                fade: i32,
                                mask: i32,
                                token: i32|
         -> i32 {
            c.data().audio.play_music(n, fade, mask, token)
        });
        link!(linker, "cpu_update", |c: Caller<'_, HostState>| -> f32 {
            c.data().last_update_cpu
        });
        link!(linker, "cpu_draw", |c: Caller<'_, HostState>| -> f32 {
            c.data().last_draw_cpu
        });
        link!(linker, "fps", |c: Caller<'_, HostState>| -> f32 {
            c.data().measured_fps_or_target()
        });
        link!(linker, "time", |c: Caller<'_, HostState>| -> f32 {
            let st = c.data();
            st.frame as f32 / st.fps as f32
        });
        link!(linker, "rnd", |mut c: Caller<'_, HostState>| -> f32 {
            c.data_mut().next_rand()
        });
        link!(linker, "log", |mut c: Caller<'_, HostState>,
                              ptr: u32,
                              len: u32| {
            let s = read_guest_str(&c, ptr, len);
            c.data_mut().logs.push(s);
        });
        link!(linker, "panic", |mut c: Caller<'_, HostState>,
                                ptr: u32,
                                len: u32| {
            let s = read_guest_str(&c, ptr, len);
            c.data_mut().panic_message = Some(s);
        });
        link!(
            linker,
            "seed_rng",
            |mut c: Caller<'_, HostState>, seed: u32| { c.data_mut().seed_rand(seed) }
        );
        link!(linker, "sprite_pixel", |c: Caller<'_, HostState>,
                                       x: i32,
                                       y: i32|
         -> i32 {
            c.data().sprites.get(x, y) as i32
        });
        link!(
            linker,
            "set_sprite_pixel",
            |mut c: Caller<'_, HostState>, x: i32, y: i32, col: i32| {
                c.data_mut().sprites.set(x, y, col as u8)
            }
        );
        link!(
            linker,
            "sprite_stretch",
            |mut c: Caller<'_, HostState>,
             sx: i32,
             sy: i32,
             sw: i32,
             sh: i32,
             dx: i32,
             dy: i32,
             dw: i32,
             dh: i32,
             flip_x: i32,
             flip_y: i32| {
                let HostState { fb, sprites, .. } = c.data_mut();
                fb.sspr(
                    sprites,
                    sx,
                    sy,
                    sw,
                    sh,
                    dx,
                    dy,
                    dw,
                    dh,
                    flip_x != 0,
                    flip_y != 0,
                );
            }
        );
        link!(
            linker,
            "ellipse",
            |mut c: Caller<'_, HostState>, x0: i32, y0: i32, x1: i32, y1: i32, col: i32| {
                c.data_mut().fb.oval(x0, y0, x1, y1, col as u8)
            }
        );
        link!(
            linker,
            "ellipse_fill",
            |mut c: Caller<'_, HostState>, x0: i32, y0: i32, x1: i32, y1: i32, col: i32| {
                c.data_mut().fb.ovalfill(x0, y0, x1, y1, col as u8)
            }
        );
        link!(
            linker,
            "set_transparent_color",
            |mut c: Caller<'_, HostState>, col: i32, t: i32| {
                c.data_mut().fb.set_transparent_color(col as u8, t != 0)
            }
        );
        link!(linker, "reset_transparency", |mut c: Caller<
            '_,
            HostState,
        >| {
            c.data_mut().fb.reset_transparency()
        });
        link!(
            linker,
            "remap_color",
            |mut c: Caller<'_, HostState>, from: i32, to: i32, mode: i32| {
                let fb = &mut c.data_mut().fb;
                if mode == 0 {
                    fb.remap_color(from as u8, to as u8);
                } else {
                    fb.remap_display_color(from as u8, to as u8);
                }
            }
        );
        link!(linker, "reset_palette", |mut c: Caller<'_, HostState>| {
            c.data_mut().fb.reset_palette()
        });
        link!(
            linker,
            "set_fill_pattern",
            |mut c: Caller<'_, HostState>, pattern: i32, secondary: i32, transparent: i32| {
                c.data_mut()
                    .fb
                    .set_fill_pattern(pattern as u16, secondary as u8, transparent != 0)
            }
        );
        link!(
            linker,
            "set_pen_color",
            |mut c: Caller<'_, HostState>, col: i32| { c.data_mut().fb.set_pen_color(col as u8) }
        );
        link!(
            linker,
            "set_cursor",
            |mut c: Caller<'_, HostState>, x: i32, y: i32| { c.data_mut().fb.set_cursor(x, y) }
        );
        link!(linker, "print_pen", |mut c: Caller<'_, HostState>,
                                    ptr: u32,
                                    len: u32|
         -> i32 {
            let s = read_guest_str(&c, ptr, len);
            c.data_mut().fb.print_pen(&s)
        });
        link!(linker, "storage_set", |mut c: Caller<'_, HostState>,
                                      key_ptr: u32,
                                      key_len: u32,
                                      val_ptr: u32,
                                      val_len: u32|
         -> i32 {
            let key = read_guest_str(&c, key_ptr, key_len);
            let val = read_guest_str(&c, val_ptr, val_len);
            c.data_mut().storage.set_json(&key, &val) as i32
        });
        link!(linker, "storage_get", |mut c: Caller<'_, HostState>,
                                      key_ptr: u32,
                                      key_len: u32,
                                      buf_ptr: u32,
                                      buf_cap: u32|
         -> i32 {
            let key = read_guest_str(&c, key_ptr, key_len);
            let Some(json) = c.data().storage.get_json(&key) else {
                return -1;
            };
            // MAX_BYTES caps the whole store at 128 K, so the length
            // always fits an i32.
            if json.len() <= buf_cap as usize {
                write_guest_bytes(&mut c, buf_ptr, json.as_bytes());
            }
            json.len() as i32
        });
        link!(linker, "storage_remove", |mut c: Caller<'_, HostState>,
                                         key_ptr: u32,
                                         key_len: u32|
         -> i32 {
            let key = read_guest_str(&c, key_ptr, key_len);
            c.data_mut().storage.remove(&key) as i32
        });
        link!(linker, "storage_clear", |mut c: Caller<'_, HostState>| {
            c.data_mut().storage.clear()
        });

        store
            .set_fuel(FUEL_PER_CALL)
            .map_err(|e| anyhow!("Fuel setup: {e}"))?;
        let instance = linker
            .instantiate_and_start(&mut store, &module)
            .map_err(|e| {
                let s = e.to_string();
                if s.contains("resource limiter denied") {
                    anyhow!("Cart needs more than 128K of memory to start")
                } else {
                    anyhow!("Cart does not match the Pixel8 ABI: {e}")
                }
            })?;

        let init = instance
            .get_typed_func::<(), ()>(&store, "pixel8_init")
            .map_err(|e| anyhow!("Cart is missing pixel8_init: {e}"))?;
        let update = instance
            .get_typed_func::<(), ()>(&store, "pixel8_update")
            .map_err(|e| anyhow!("Cart is missing pixel8_update: {e}"))?;
        let draw = instance
            .get_typed_func::<(), ()>(&store, "pixel8_draw")
            .map_err(|e| anyhow!("Cart is missing pixel8_draw: {e}"))?;

        let mut vm = Self {
            store,
            _instance: instance,
            update,
            draw,
        };
        vm.call("init", init).map_err(|e| anyhow!(e.to_string()))?;
        vm.store.data_mut().fps = vm.query_fps();
        Ok(vm)
    }

    /// Read the cart's `pixel8_fps` export. The SDK emits it from every cart;
    /// 30 and 60 are honored, and anything else (or a hand-written cart with
    /// no such export) falls back to the default.
    fn query_fps(&mut self) -> u32 {
        let Ok(func) = self
            ._instance
            .get_typed_func::<(), u32>(&self.store, "pixel8_fps")
        else {
            return DEFAULT_FPS;
        };
        self.store.set_fuel(FUEL_PER_CALL).ok();
        match func.call(&mut self.store, ()) {
            Ok(30) => 30,
            Ok(60) => 60,
            _ => DEFAULT_FPS,
        }
    }

    fn call(
        &mut self,
        phase: &'static str,
        func: TypedFunc<(), ()>,
    ) -> std::result::Result<(), RuntimeError> {
        self.store.set_fuel(FUEL_PER_CALL).ok();
        let result = func.call(&mut self.store, ()).map_err(|err| {
            let message = match self.store.data_mut().panic_message.take() {
                Some(panic) => panic,
                None => {
                    let s = err.to_string();
                    if s.contains("fuel") {
                        format!("{phase}() ran too long\n(infinite loop?)")
                    } else if s.contains("growth operation limited") {
                        format!("{phase}() ran out of memory\n(128K limit)")
                    } else {
                        s
                    }
                }
            };
            RuntimeError { phase, message }
        });
        if result.is_ok() {
            let remaining = self.store.get_fuel().unwrap_or(0);
            let frac = FUEL_PER_CALL.saturating_sub(remaining) as f32 / FUEL_PER_CALL as f32;
            match phase {
                "update" => self.store.data_mut().last_update_cpu = frac,
                "draw" => self.store.data_mut().last_draw_cpu = frac,
                _ => {}
            }
        }
        result
    }

    /// Run one logical frame: tick input, call `pixel8_update`.
    pub fn call_update(&mut self) -> std::result::Result<(), RuntimeError> {
        self.store.data_mut().input.tick();
        let r = self.call("update", self.update);
        self.store.data_mut().frame += 1;
        r
    }

    /// Call `pixel8_draw`.
    pub fn call_draw(&mut self) -> std::result::Result<(), RuntimeError> {
        self.call("draw", self.draw)
    }

    /// The cart's logical frame rate: 30, or 60 if it opted in.
    pub fn fps(&self) -> u32 {
        self.store.data().fps
    }

    /// Fraction (0.0..1.0) of `update`'s fuel budget used last completed frame.
    pub fn cpu_update(&self) -> f32 {
        self.store.data().last_update_cpu
    }

    /// Fraction (0.0..1.0) of `draw`'s fuel budget used last completed frame.
    pub fn cpu_draw(&self) -> f32 {
        self.store.data().last_draw_cpu
    }

    /// Fraction (0.0..1.0) of the 128K memory cap currently in use.
    pub fn memory_used_fraction(&self) -> f32 {
        let Some(mem) = self._instance.get_memory(&self.store, "memory") else {
            return 0.0;
        };
        mem.data_size(&self.store) as f32 / MAX_MEMORY as f32
    }

    /// The cart's committed-memory high-water in bytes (shadow-stack reserve +
    /// statics + the highest the heap has reached), via its `pixel8_mem_used`
    /// export, or 0 for carts without it (hand-written or allocation-free).
    /// Tracks real pressure closely but is not an exact OOM line — the
    /// allocator keeps a small reserve above the last allocation.
    pub fn mem_used_bytes(&mut self) -> u32 {
        let Ok(func) = self
            ._instance
            .get_typed_func::<(), u32>(&self.store, "pixel8_mem_used")
        else {
            return 0;
        };
        self.store.set_fuel(FUEL_PER_CALL).ok();
        func.call(&mut self.store, ()).unwrap_or(0)
    }

    pub fn state(&self) -> &HostState {
        self.store.data()
    }

    pub fn state_mut(&mut self) -> &mut HostState {
        self.store.data_mut()
    }
}

/// Everything the host exposes to a running cart.
pub struct HostState {
    pub fb: Framebuffer,
    pub input: InputState,
    pub sprites: SpriteSheet,
    pub map: MapData,
    pub audio: AudioHandle,
    /// The cart's persistent key-value store (the save file). The frontend
    /// decides the backing: a cache-dir JSON file on the desktop console and
    /// player, in-memory in the browser and headless `verify`.
    pub storage: Storage,
    /// Messages from the cart's `log` calls, drained by the console.
    pub logs: Vec<String>,
    /// Message from the cart's panic hook, captured just before the trap.
    pub panic_message: Option<String>,
    pub frame: u64,
    /// The cart's logical frames per second (30 or 60), from its `pixel8_fps`
    /// export. Drives `time()` and the host's update/draw cadence.
    pub fps: u32,
    /// Fraction (0.0..1.0) of `update`'s fuel budget used last completed frame.
    last_update_cpu: f32,
    /// Fraction (0.0..1.0) of `draw`'s fuel budget used last completed frame.
    last_draw_cpu: f32,
    /// Real frames per second measured by the host frontend; `0.0` until fed.
    measured_fps: f32,
    rng: u64,
    /// Enforces `MAX_MEMORY` on linear-memory growth, including the initial
    /// allocation at instantiation.
    limits: StoreLimits,
}

impl HostState {
    fn new(assets: &Assets, audio: AudioHandle, storage: Storage) -> Self {
        Self {
            fb: Framebuffer::new(),
            input: InputState::default(),
            sprites: assets.sprites.clone(),
            map: assets.map.clone(),
            audio,
            storage,
            logs: Vec::new(),
            panic_message: None,
            frame: 0,
            fps: DEFAULT_FPS,
            last_update_cpu: 0.0,
            last_draw_cpu: 0.0,
            measured_fps: 0.0,
            rng: 0x2545_f491_4f6c_dd1d,
            limits: StoreLimitsBuilder::new()
                .memory_size(MAX_MEMORY)
                .trap_on_grow_failure(true)
                .build(),
        }
    }

    fn next_rand(&mut self) -> f32 {
        // xorshift64*; carts that need determinism can bring their own RNG.
        let mut x = self.rng;
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        self.rng = x;
        let bits = (x.wrapping_mul(0x2545_f491_4f6c_dd1d) >> 40) as u32;
        bits as f32 / (1u32 << 24) as f32
    }

    /// Feed the host frontend's measured frame rate, surfaced to carts via `fps`.
    pub fn set_measured_fps(&mut self, fps: f32) {
        self.measured_fps = fps;
    }

    /// The measured frame rate, or the cart's target rate until a frontend
    /// measures one. Keeps `fps()` sane on frontends that never measure.
    pub fn measured_fps_or_target(&self) -> f32 {
        if self.measured_fps > 0.0 {
            self.measured_fps
        } else {
            self.fps as f32
        }
    }

    fn seed_rand(&mut self, seed: u32) {
        // Force a nonzero xorshift state; all-zero is a fixed point.
        self.rng = (((seed as u64) << 32) | (seed as u64)) | 1;
    }
}

/// A cart-side runtime error, formatted for the error screen.
#[derive(Debug, Clone)]
pub struct RuntimeError {
    /// Which lifecycle call failed: "init", "update" or "draw".
    pub phase: &'static str,
    pub message: String,
}

impl std::fmt::Display for RuntimeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Runtime error in {}:\n{}", self.phase, self.message)
    }
}

fn read_guest_str(caller: &Caller<'_, HostState>, ptr: u32, len: u32) -> String {
    let Some(mem) = caller
        .get_export("memory")
        .and_then(wasmi::Extern::into_memory)
    else {
        return String::new();
    };
    let data = mem.data(caller);
    let start = ptr as usize;
    let end = start.saturating_add(len as usize).min(data.len());
    if start >= end {
        return String::new();
    }
    String::from_utf8_lossy(&data[start..end]).into_owned()
}

/// Copy `bytes` into guest memory at `ptr`. Writes nothing when the
/// destination range does not fit the guest's linear memory.
fn write_guest_bytes(caller: &mut Caller<'_, HostState>, ptr: u32, bytes: &[u8]) {
    let Some(mem) = caller
        .get_export("memory")
        .and_then(wasmi::Extern::into_memory)
    else {
        return;
    };
    let data = mem.data_mut(caller);
    let start = ptr as usize;
    let Some(end) = start.checked_add(bytes.len()) else {
        return;
    };
    if end <= data.len() {
        data[start..end].copy_from_slice(bytes);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A minimal hand-written cart exercising the ABI from WAT.
    const TEST_CART: &str = r#"
        (module
          (import "pixel8" "clear" (func $cls (param i32)))
          (import "pixel8" "set_pixel" (func $pset (param i32 i32 i32)))
          (import "pixel8" "pixel" (func $pget (param i32 i32) (result i32)))
          (import "pixel8" "is_button_down" (func $btn (param i32) (result i32)))
          (import "pixel8" "print" (func $print (param i32 i32 i32 i32 i32) (result i32)))
          (import "pixel8" "log" (func $log (param i32 i32)))
          (memory (export "memory") 1)
          (data (i32.const 16) "hi from cart")
          (global $x (mut i32) (i32.const 5))
          (func (export "pixel8_init")
            (call $log (i32.const 16) (i32.const 12)))
          (func (export "pixel8_update")
            (if (i32.ne (call $btn (i32.const 1)) (i32.const 0))
              (then (global.set $x (i32.add (global.get $x) (i32.const 1))))))
          (func (export "pixel8_draw")
            (call $cls (i32.const 1))
            (call $pset (global.get $x) (i32.const 7) (i32.const 8))
            (drop (call $print (i32.const 16) (i32.const 2) (i32.const 0) (i32.const 0) (i32.const 7))))
        )
    "#;

    const LOOPING_CART: &str = r#"
        (module
          (func (export "pixel8_init"))
          (func (export "pixel8_update") (loop $l (br $l)))
          (func (export "pixel8_draw"))
        )
    "#;

    const FPS30_CART: &str = r#"
        (module
          (func (export "pixel8_init"))
          (func (export "pixel8_fps") (result i32) (i32.const 30))
          (func (export "pixel8_update"))
          (func (export "pixel8_draw")))
    "#;

    const MEM_EXPORT_CART: &str = r#"
        (module
          (func (export "pixel8_init"))
          (func (export "pixel8_update"))
          (func (export "pixel8_draw"))
          (func (export "pixel8_mem_used") (result i32) (i32.const 32768)))
    "#;

    /// Update loops ~10k times — well under the 131,072-fuel budget.
    const BUDGET_OK_CART: &str = r#"
        (module
          (func (export "pixel8_init"))
          (func (export "pixel8_update")
            (local $i i32)
            (local.set $i (i32.const 10000))
            (loop $l
              (local.set $i (i32.add (local.get $i) (i32.const -1)))
              (br_if $l (local.get $i))))
          (func (export "pixel8_draw")))
    "#;

    /// Update loops ~100k times — comfortably over the 131,072-fuel budget.
    const BUDGET_OVER_CART: &str = r#"
        (module
          (func (export "pixel8_init"))
          (func (export "pixel8_update")
            (local $i i32)
            (local.set $i (i32.const 100000))
            (loop $l
              (local.set $i (i32.add (local.get $i) (i32.const -1)))
              (br_if $l (local.get $i))))
          (func (export "pixel8_draw")))
    "#;

    /// 1-page initial + grow by 1 page = 2 pages = exactly the 128 K cap (allowed).
    const GROW_TO_CAP_CART: &str = r#"
        (module
          (memory (export "memory") 1)
          (func (export "pixel8_init"))
          (func (export "pixel8_update") (drop (memory.grow (i32.const 1))))
          (func (export "pixel8_draw")))
    "#;

    /// Update grows linear memory far past the 128 K cap (denied -> trap).
    const GROW_PAST_CAP_CART: &str = r#"
        (module
          (memory (export "memory") 1)
          (func (export "pixel8_init"))
          (func (export "pixel8_update") (drop (memory.grow (i32.const 10))))
          (func (export "pixel8_draw")))
    "#;

    /// Declares 3 pages (192 KiB) of initial memory — over the 128 K cap, so it
    /// is denied at instantiation before the cart ever runs.
    const HUGE_INITIAL_MEMORY_CART: &str = r#"
        (module
          (memory (export "memory") 3)
          (func (export "pixel8_init"))
          (func (export "pixel8_update"))
          (func (export "pixel8_draw")))
    "#;

    const PARITY_CART: &str = r#"
        (module
          (import "pixel8" "ellipse" (func $ovalo (param i32 i32 i32 i32 i32)))
          (import "pixel8" "ellipse_fill" (func $oval (param i32 i32 i32 i32 i32)))
          (import "pixel8" "set_transparent_color" (func $palt (param i32 i32)))
          (import "pixel8" "reset_transparency" (func $paltr))
          (import "pixel8" "remap_color" (func $pal (param i32 i32 i32)))
          (import "pixel8" "reset_palette" (func $palr))
          (import "pixel8" "set_fill_pattern" (func $fillp (param i32 i32 i32)))
          (import "pixel8" "set_sprite_pixel" (func $sset (param i32 i32 i32)))
          (import "pixel8" "sprite_pixel" (func $sget (param i32 i32) (result i32)))
          (import "pixel8" "sprite_stretch"
            (func $sspr (param i32 i32 i32 i32 i32 i32 i32 i32 i32 i32)))
          (import "pixel8" "seed_rng" (func $srand (param i32)))
          (import "pixel8" "set_pen_color" (func $color (param i32)))
          (import "pixel8" "set_cursor" (func $cursor (param i32 i32)))
          (import "pixel8" "print_pen" (func $printp (param i32 i32) (result i32)))
          (import "pixel8" "cpu_update" (func $cpuu (result f32)))
          (import "pixel8" "cpu_draw" (func $cpud (result f32)))
          (import "pixel8" "fps" (func $fps (result f32)))
          (memory (export "memory") 1)
          (data (i32.const 0) "hi")
          (func (export "pixel8_init"))
          (func (export "pixel8_update")
            (call $srand (i32.const 42))
            (call $sset (i32.const 0) (i32.const 0) (i32.const 9))
            (drop (call $sget (i32.const 0) (i32.const 0))))
          (func (export "pixel8_draw")
            (call $pal (i32.const 8) (i32.const 12) (i32.const 0))
            (call $palt (i32.const 0) (i32.const 1))
            (call $paltr)
            (call $fillp (i32.const 0) (i32.const 0) (i32.const 0))
            (call $color (i32.const 7))
            (call $cursor (i32.const 0) (i32.const 0))
            (drop (call $printp (i32.const 0) (i32.const 2)))
            (call $sspr (i32.const 0) (i32.const 0) (i32.const 8) (i32.const 8)
                        (i32.const 64) (i32.const 0) (i32.const 8) (i32.const 8)
                        (i32.const 0) (i32.const 0))
            (call $ovalo (i32.const 20) (i32.const 20) (i32.const 28) (i32.const 28)
                         (i32.const 7))
            (call $palr)
            (call $oval (i32.const 0) (i32.const 0) (i32.const 8) (i32.const 8) (i32.const 8))
            (drop (call $cpuu))
            (drop (call $cpud))
            (drop (call $fps))))
    "#;

    fn load_test_vm(wat_src: &str) -> Result<GameVm> {
        let wasm = wat::parse_str(wat_src).unwrap();
        GameVm::load(
            &wasm,
            &Assets::default(),
            AudioHandle::dummy(),
            Storage::default(),
        )
    }

    #[test]
    fn parity_imports_link_and_run() {
        let mut vm = load_test_vm(PARITY_CART).unwrap();
        vm.call_update().unwrap();
        vm.call_draw().unwrap();
        // sset wrote sprite-sheet pixel (0,0) = 9.
        assert_eq!(vm.state().sprites.get(0, 0), 9);
        // ellipse_fill drew color 8 after reset_palette, so no remap applies.
        assert_eq!(vm.state().fb.pget(4, 4), 8, "oval filled the box center");
    }

    #[test]
    fn abi_lifecycle_and_drawing() {
        let mut vm = load_test_vm(TEST_CART).unwrap();
        assert_eq!(vm.state_mut().logs.pop().as_deref(), Some("hi from cart"));

        vm.call_update().unwrap();
        vm.call_draw().unwrap();
        assert_eq!(vm.state().fb.pget(5, 7), 8, "set_pixel through ABI");
        assert_eq!(vm.state().fb.pget(0, 0), 7, "print drew a glyph pixel");

        // Hold right; update should move the pixel.
        vm.state_mut().input.set_button(1, true);
        vm.call_update().unwrap();
        vm.call_draw().unwrap();
        assert_eq!(
            vm.state().fb.pget(6, 7),
            8,
            "is_button_down(right) moved pixel"
        );
    }

    #[test]
    fn default_fps_is_60() {
        // A cart with no pixel8_fps export (e.g. hand-written WAT) takes the
        // default rate.
        let vm = load_test_vm(TEST_CART).unwrap();
        assert_eq!(vm.fps(), 60);
    }

    #[test]
    fn cart_can_select_30fps() {
        let vm = load_test_vm(FPS30_CART).unwrap();
        assert_eq!(vm.fps(), 30);
    }

    #[test]
    fn mem_used_reads_export_else_zero() {
        // A cart exporting pixel8_mem_used reports that many bytes used.
        let mut vm = load_test_vm(MEM_EXPORT_CART).unwrap();
        assert_eq!(vm.mem_used_bytes(), 32768);
        // A cart without the export reports 0 (hand-written / allocation-free).
        let mut vm2 = load_test_vm(TEST_CART).unwrap();
        assert_eq!(vm2.mem_used_bytes(), 0);
    }

    #[test]
    fn infinite_loop_is_trapped() {
        let mut vm = load_test_vm(LOOPING_CART).unwrap();
        let err = vm.call_update().unwrap_err();
        assert_eq!(err.phase, "update");
        assert!(err.message.contains("ran too long"), "{}", err.message);
    }

    #[test]
    fn missing_exports_is_a_load_error() {
        let wasm = wat::parse_str("(module)").unwrap();
        let err = match GameVm::load(
            &wasm,
            &Assets::default(),
            AudioHandle::dummy(),
            Storage::default(),
        ) {
            Err(e) => e,
            Ok(_) => panic!("empty module should not load"),
        };
        assert!(err.to_string().contains("pixel8_init"));
    }

    #[test]
    fn unknown_imports_are_rejected() {
        let wasm = wat::parse_str(
            r#"(module (import "env" "evil" (func))
                 (func (export "pixel8_init"))
                 (func (export "pixel8_update"))
                 (func (export "pixel8_draw")))"#,
        )
        .unwrap();
        assert!(GameVm::load(
            &wasm,
            &Assets::default(),
            AudioHandle::dummy(),
            Storage::default()
        )
        .is_err());
    }

    #[test]
    fn fuel_budget_allows_modest_work() {
        let mut vm = load_test_vm(BUDGET_OK_CART).unwrap();
        assert!(
            vm.call_update().is_ok(),
            "10k-iteration frame must fit the 128K-fuel budget"
        );
    }

    #[test]
    fn fuel_budget_traps_runaway_work() {
        let mut vm = load_test_vm(BUDGET_OVER_CART).unwrap();
        let err = vm.call_update().unwrap_err();
        assert!(err.message.contains("ran too long"), "got: {}", err.message);
    }

    #[test]
    fn memory_growth_up_to_cap_is_allowed() {
        let mut vm = load_test_vm(GROW_TO_CAP_CART).unwrap();
        assert!(
            vm.call_update().is_ok(),
            "growing to exactly 128 K must succeed"
        );
    }

    #[test]
    fn memory_growth_past_cap_is_a_friendly_error() {
        let mut vm = load_test_vm(GROW_PAST_CAP_CART).unwrap();
        let err = vm.call_update().unwrap_err();
        assert!(
            err.message.contains("out of memory"),
            "got: {}",
            err.message
        );
    }

    #[test]
    fn oversized_initial_memory_is_rejected_at_load() {
        let wasm = wat::parse_str(HUGE_INITIAL_MEMORY_CART).unwrap();
        let err = match GameVm::load(
            &wasm,
            &Assets::default(),
            AudioHandle::dummy(),
            Storage::default(),
        ) {
            Err(e) => e,
            Ok(_) => panic!("oversized cart should not load"),
        };
        assert!(err.to_string().contains("128K of memory"), "got: {err}");
    }

    #[test]
    fn reports_cpu_usage_per_phase() {
        // BUDGET_OK_CART loops ~10k times in update and has an empty draw, so
        // the update phase must report a higher CPU fraction than draw.
        let mut vm = load_test_vm(BUDGET_OK_CART).unwrap();
        vm.call_update().unwrap();
        vm.call_draw().unwrap();
        let u = vm.cpu_update();
        let d = vm.cpu_draw();
        assert!(u > 0.0 && u < 1.0, "update cpu fraction in range: {u}");
        assert!(u > d, "heavy update beats empty draw: {u} vs {d}");
    }

    #[test]
    fn reports_memory_usage() {
        // TEST_CART declares one 64 KiB page of the 128 KiB cap.
        let vm = load_test_vm(TEST_CART).unwrap();
        let frac = vm.memory_used_fraction();
        assert!(
            (frac - 0.5).abs() < 0.01,
            "one page is half the cap: {frac}"
        );
    }

    /// Exercises all four storage imports from a cart. Init proves a
    /// checked remove (pixel (2,0)), wipes the store with `storage_clear`,
    /// and leaves `"score" = 42` behind. Draw probes every `storage_get`
    /// branch: value length at (0,0), missing key at (1,0), cleared key at
    /// (3,0), cap-0 size query at (4,0), too-small buffer leaving memory
    /// untouched at (5,0), and an exact-fit write at (6,0).
    const STORAGE_CART: &str = r#"
        (module
          (import "pixel8" "storage_set" (func $sset (param i32 i32 i32 i32) (result i32)))
          (import "pixel8" "storage_get" (func $sget (param i32 i32 i32 i32) (result i32)))
          (import "pixel8" "storage_remove" (func $srem (param i32 i32) (result i32)))
          (import "pixel8" "storage_clear" (func $sclr))
          (import "pixel8" "set_pixel" (func $pset (param i32 i32 i32)))
          (memory (export "memory") 1)
          (data (i32.const 0) "score")
          (data (i32.const 8) "42")
          (data (i32.const 16) "gone")
          (data (i32.const 24) "tmp")
          (data (i32.const 28) "1")
          (data (i32.const 63) "\05")
          (func (export "pixel8_init")
            ;; Removing an existing key returns 1 -> (2,0) = 5.
            (drop (call $sset (i32.const 24) (i32.const 3) (i32.const 28) (i32.const 1)))
            (if (i32.eq (call $srem (i32.const 24) (i32.const 3)) (i32.const 1))
              (then (call $pset (i32.const 2) (i32.const 0) (i32.const 5))))
            ;; Re-add "tmp", wipe everything, then store the real value.
            (drop (call $sset (i32.const 24) (i32.const 3) (i32.const 28) (i32.const 1)))
            (call $sclr)
            (drop (call $sset (i32.const 0) (i32.const 5) (i32.const 8) (i32.const 2))))
          (func (export "pixel8_update"))
          (func (export "pixel8_draw")
            ;; (0,0) = the JSON length of the "score" value (2).
            (call $pset (i32.const 0) (i32.const 0)
              (call $sget (i32.const 0) (i32.const 5) (i32.const 64) (i32.const 16)))
            ;; A key never stored returns -1 -> (1,0) = 7.
            (if (i32.eq (call $sget (i32.const 16) (i32.const 4) (i32.const 64) (i32.const 16))
                        (i32.const -1))
              (then (call $pset (i32.const 1) (i32.const 0) (i32.const 7))))
            ;; "tmp" was wiped by storage_clear -> (3,0) = 7.
            (if (i32.eq (call $sget (i32.const 24) (i32.const 3) (i32.const 64) (i32.const 16))
                        (i32.const -1))
              (then (call $pset (i32.const 3) (i32.const 0) (i32.const 7))))
            ;; Cap 0 still reports the length -> (4,0) = 2.
            (call $pset (i32.const 4) (i32.const 0)
              (call $sget (i32.const 0) (i32.const 5) (i32.const 64) (i32.const 0)))
            ;; A too-small buffer gets nothing written: the sentinel byte at
            ;; 63 survives a cap-1 read of the 2-byte value -> (5,0) = 5.
            (drop (call $sget (i32.const 0) (i32.const 5) (i32.const 63) (i32.const 1)))
            (call $pset (i32.const 5) (i32.const 0) (i32.load8_u (i32.const 63)))
            ;; An exactly-sized buffer is filled: "42" lands at 80..82 -> (6,0) = 7.
            (drop (call $sget (i32.const 0) (i32.const 5) (i32.const 80) (i32.const 2)))
            (if (i32.and
                  (i32.eq (i32.load8_u (i32.const 80)) (i32.const 52))
                  (i32.eq (i32.load8_u (i32.const 81)) (i32.const 50)))
              (then (call $pset (i32.const 6) (i32.const 0) (i32.const 7))))))
    "#;

    #[test]
    fn storage_abi_set_get_remove_clear() {
        let mut vm = load_test_vm(STORAGE_CART).unwrap();
        vm.call_update().unwrap();
        vm.call_draw().unwrap();
        // The host sees what the cart stored, as canonical JSON — and only
        // that: storage_clear wiped the earlier "tmp" key.
        assert_eq!(vm.state().storage.get_json("score").as_deref(), Some("42"));
        assert_eq!(vm.state().storage.get_json("tmp"), None);
        let px = |x| vm.state().fb.pget(x, 0);
        assert_eq!(px(0), 2, "storage_get returned the value length");
        assert_eq!(px(1), 7, "missing key returned -1");
        assert_eq!(px(2), 5, "removing an existing key returned 1");
        assert_eq!(px(3), 7, "storage_clear wiped the store");
        assert_eq!(px(4), 2, "cap-0 call sized the read");
        assert_eq!(px(5), 5, "too-small buffer left guest memory untouched");
        assert_eq!(px(6), 7, "exact-fit buffer was filled");
    }

    #[test]
    fn storage_persists_across_vm_loads() {
        let path =
            std::env::temp_dir().join(format!("pixel8_vm_storage_{}.json", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let wasm = wat::parse_str(STORAGE_CART).unwrap();
        {
            let _vm = GameVm::load(
                &wasm,
                &Assets::default(),
                AudioHandle::dummy(),
                Storage::at_path(path.clone()),
            )
            .unwrap();
            // Dropping the VM drops (and saves) the storage.
        }
        let reloaded = Storage::at_path(path.clone());
        assert_eq!(reloaded.get_json("score").as_deref(), Some("42"));
        std::fs::remove_file(&path).unwrap();
    }

    #[test]
    fn fps_falls_back_to_target_until_measured() {
        // No frontend measurement yet: report the cart's target rate (30).
        let mut vm = load_test_vm(FPS30_CART).unwrap();
        assert_eq!(vm.state().measured_fps_or_target(), 30.0);
        // Once a frontend feeds a real rate, report that.
        vm.state_mut().set_measured_fps(58.0);
        assert_eq!(vm.state().measured_fps_or_target(), 58.0);
    }
}