gasm-sdk 0.5.0

Write games for gasm, a portable game runtime on WebAssembly: bindings for the gasm ABI (video, audio, input, WebGPU, network, storage) plus a Game trait
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
//! Rust bindings for the gasm game ABI v0 — see `spec/ABI.md`.
//!
//! ```ignore
//! struct MyGame { t: u32 }
//! impl gasm::Game for MyGame {
//!     fn init() -> Result<Self, String> { gasm::set_frame_rate(60.0); Ok(MyGame { t: 0 }) }
//!     fn frame(&mut self) { self.t += 1; /* simulate, draw */ }
//! }
//! gasm::game!(MyGame);
//! ```
//!
//! Build with `--target wasm32-unknown-unknown` and `crate-type = ["cdylib"]`.
//! On native targets the same code links against an in-process stub host
//! ([`native`]) for tests and benchmarks.

pub mod sys;

#[cfg(not(target_arch = "wasm32"))]
pub mod native;

use std::cell::UnsafeCell;

pub const ABI_VERSION: i32 = 0;

// ---- core --------------------------------------------------------------------

pub fn log(msg: &str) {
    unsafe { sys::log(msg.as_ptr(), msg.len() as u32) }
}

/// `format!`-style logging: `gasm::log!("x = {x}")`.
#[macro_export]
macro_rules! log {
    ($($t:tt)*) => { $crate::log(&::std::format!($($t)*)) };
}

/// Monotonic milliseconds (virtual, frame-derived time in headless runs).
pub fn time_ms() -> f64 {
    unsafe { sys::time_ms() }
}

/// Rate at which the runner calls `frame()`. Default 60.
pub fn set_frame_rate(hz: f64) {
    unsafe { sys::set_frame_rate(hz) }
}

/// Launch parameter (`--param k=v` natively, `?k=v` in the browser).
pub fn param(name: &str) -> Option<String> {
    let len = unsafe { sys::param(name.as_ptr(), name.len() as u32, std::ptr::null_mut(), 0) };
    if len < 0 {
        return None;
    }
    let mut buf = vec![0u8; len as usize];
    unsafe { sys::param(name.as_ptr(), name.len() as u32, buf.as_mut_ptr(), len as u32) };
    Some(String::from_utf8_lossy(&buf).into_owned())
}

/// End the game (WASI `proc_exit`). Runners treat code 0 as a clean exit.
pub fn exit(code: i32) -> ! {
    unsafe { sys::proc_exit(code) }
}

// ---- video / audio / input / assets --------------------------------------------

/// Present an RGBA8 frame (`stride` bytes per row).
pub fn present(rgba: &[u8], width: u32, height: u32, stride: u32) {
    assert!(rgba.len() >= (stride * (height - 1) + width * 4) as usize, "present: buffer too small");
    unsafe { sys::video_present(rgba.as_ptr(), width, height, stride) }
}

pub mod audio {
    use std::sync::atomic::{AtomicU32, Ordering};
    static CHANNELS: AtomicU32 = AtomicU32::new(2);

    /// Format for [`push`]: sample rate (8–192 kHz) and 1 or 2 channels.
    pub fn config(sample_rate: u32, channels: u32) {
        CHANNELS.store(channels, Ordering::Relaxed);
        unsafe { crate::sys::audio_config(sample_rate, channels) }
    }

    /// Queue interleaved f32 samples in [-1, 1].
    pub fn push(samples: &[f32]) {
        let ch = CHANNELS.load(Ordering::Relaxed).max(1);
        unsafe { crate::sys::audio_push(samples.as_ptr(), samples.len() as u32 / ch) }
    }
}

/// Virtual gamepad buttons (bit positions per spec/ABI.md).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Buttons(pub u32);

impl Buttons {
    pub const A: u32 = 1 << 0;
    pub const B: u32 = 1 << 1;
    pub const X: u32 = 1 << 2;
    pub const Y: u32 = 1 << 3;
    pub const L: u32 = 1 << 4;
    pub const R: u32 = 1 << 5;
    pub const SELECT: u32 = 1 << 6;
    pub const START: u32 = 1 << 7;
    pub const UP: u32 = 1 << 8;
    pub const DOWN: u32 = 1 << 9;
    pub const LEFT: u32 = 1 << 10;
    pub const RIGHT: u32 = 1 << 11;

    pub fn held(self, mask: u32) -> bool {
        self.0 & mask != 0
    }
}

/// Buttons held on virtual pad `player` (0..=3) this frame.
pub fn pad(player: u32) -> Buttons {
    Buttons(unsafe { sys::input_pad(player) })
}

/// Text typed since the previous frame (`'\u{8}'` = backspace, `'\n'` = enter),
/// or `None` if the runner has no keyboard.
pub fn text_input() -> Option<String> {
    let len = unsafe { sys::text_input(std::ptr::null_mut(), 0) };
    if len < 0 {
        return None;
    }
    let mut buf = vec![0u8; len as usize];
    if len > 0 {
        unsafe { sys::text_input(buf.as_mut_ptr(), len as u32) };
    }
    Some(String::from_utf8_lossy(&buf).into_owned())
}

/// All asset names, sorted (by UTF-8 bytes). Folder entries keep their on-disk case.
pub fn asset_names() -> Vec<String> {
    let n = unsafe { sys::asset_count() };
    (0..n)
        .filter_map(|i| {
            let len = unsafe { sys::asset_name(i, std::ptr::null_mut(), 0) };
            if len < 0 {
                return None;
            }
            let mut buf = vec![0u8; len as usize];
            if len > 0 {
                unsafe { sys::asset_name(i, buf.as_mut_ptr(), len as u32) };
            }
            Some(String::from_utf8_lossy(&buf).into_owned())
        })
        .collect()
}

/// Read a whole asset.
pub fn asset(name: &str) -> Option<Vec<u8>> {
    let n = unsafe { sys::asset_size(name.as_ptr(), name.len() as u32) };
    if n < 0 {
        return None;
    }
    let mut buf = vec![0u8; n as usize];
    let got = unsafe { sys::asset_read(name.as_ptr(), name.len() as u32, buf.as_mut_ptr(), n as u32) };
    buf.truncate(got.max(0) as usize);
    Some(buf)
}

/// Read up to `buf.len()` bytes of an asset starting at `offset` (for streaming
/// large assets). Returns bytes read (0 at the end), or `None` if missing.
pub fn asset_read_at(name: &str, offset: u32, buf: &mut [u8]) -> Option<usize> {
    let n = unsafe {
        sys::asset_read_at(name.as_ptr(), name.len() as u32, offset, buf.as_mut_ptr(), buf.len() as u32)
    };
    (n >= 0).then_some(n as usize)
}

// ---- storage ------------------------------------------------------------------------

/// Persistent per-game key/value store (`gasm:storage`): saves, settings, scores.
///
/// Keys: 1–128 bytes of `[A-Za-z0-9._-]`. Values up to 1 MiB, 16 MiB per game.
/// The runner picks the namespace; headless runs start with an empty store.
pub mod storage {
    use crate::sys;

    pub fn get(key: &str) -> Option<Vec<u8>> {
        let n = unsafe { sys::storage_get(key.as_ptr(), key.len() as u32, std::ptr::null_mut(), 0) };
        if n < 0 {
            return None;
        }
        let mut buf = vec![0u8; n as usize];
        unsafe { sys::storage_get(key.as_ptr(), key.len() as u32, buf.as_mut_ptr(), n as u32) };
        Some(buf)
    }

    /// Store a value. False on invalid key, size/quota limits or I/O error.
    pub fn set(key: &str, value: &[u8]) -> bool {
        unsafe { sys::storage_set(key.as_ptr(), key.len() as u32, value.as_ptr(), value.len() as u32) == 0 }
    }

    /// Delete a key. False if it didn't exist.
    pub fn delete(key: &str) -> bool {
        unsafe { sys::storage_delete(key.as_ptr(), key.len() as u32) == 0 }
    }

    /// All keys of this game, sorted.
    pub fn keys() -> Vec<String> {
        let n = unsafe { sys::storage_count() };
        (0..n)
            .filter_map(|i| {
                let len = unsafe { sys::storage_key(i, std::ptr::null_mut(), 0) };
                if len < 0 {
                    return None;
                }
                let mut buf = vec![0u8; len as usize];
                unsafe { sys::storage_key(i, buf.as_mut_ptr(), len as u32) };
                Some(String::from_utf8_lossy(&buf).into_owned())
            })
            .collect()
    }
}

// ---- raw input ---------------------------------------------------------------------

/// Raw keyboard, pointer and gamepads (next to the virtual [`pad`]s).
///
/// ```ignore
/// use gasm::{input, keys};
/// input::set_mode(input::KEYS_RAW);              // read the keyboard directly, no keymap pads
/// let k = input::keys().unwrap_or_default();
/// if k.held(keys::SHIFT_LEFT) && k.held(keys::ARROW_LEFT) { … }
/// if let Some(p) = input::pointer() && p.pressed & input::MOUSE_LEFT != 0 { click(p.frame_x, p.frame_y) }
/// ```
pub mod input {
    use crate::sys;

    /// The runner stops mapping the keyboard to pads (gamepads still map).
    pub const KEYS_RAW: u32 = 1 << 0;
    /// Hide the system cursor over the game.
    pub const POINTER_HIDDEN: u32 = 1 << 1;
    /// Capture the pointer for relative motion (best effort; the browser needs a click).
    pub const POINTER_LOCKED: u32 = 1 << 2;

    pub const MOUSE_LEFT: u32 = 1 << 0;
    pub const MOUSE_RIGHT: u32 = 1 << 1;
    pub const MOUSE_MIDDLE: u32 = 1 << 2;
    pub const MOUSE_BACK: u32 = 1 << 3;
    pub const MOUSE_FORWARD: u32 = 1 << 4;

    /// `KEYS_RAW | POINTER_HIDDEN | POINTER_LOCKED`, any combination.
    pub fn set_mode(flags: u32) {
        unsafe { sys::input_mode(flags) }
    }

    /// Keys held this frame; index with [`crate::keys`] constants.
    #[derive(Clone, Copy, Default, PartialEq, Eq)]
    pub struct Keys(pub [u8; 32]);

    impl Keys {
        pub fn held(&self, code: u32) -> bool {
            (code as usize) < 256 && self.0[code as usize / 8] & (1 << (code % 8)) != 0
        }
    }

    /// `None` if the runner has no keyboard.
    pub fn keys() -> Option<Keys> {
        let mut k = Keys::default();
        (unsafe { sys::key_state(k.0.as_mut_ptr(), 32) } >= 0).then_some(k)
    }

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct KeyEvent {
        pub code: u32,
        pub down: bool,
    }

    /// Presses and releases since the previous frame, in order (`None`: no keyboard).
    pub fn key_events() -> Option<Vec<KeyEvent>> {
        let n = unsafe { sys::key_events(std::ptr::null_mut(), 0) };
        if n < 0 {
            return None;
        }
        let mut b = vec![0u8; n as usize];
        if n > 0 {
            unsafe { sys::key_events(b.as_mut_ptr(), n as u32) };
        }
        Some(b.chunks_exact(4).map(|e| KeyEvent { code: u16::from_le_bytes([e[0], e[1]]) as u32, down: e[2] != 0 }).collect())
    }

    #[derive(Clone, Copy, Debug, Default, PartialEq)]
    pub struct Pointer {
        /// position in drawable pixels (gfx width/height space)
        pub x: f32,
        pub y: f32,
        /// position in the last presented frame's pixels (2D games)
        pub frame_x: f32,
        pub frame_y: f32,
        /// relative motion since the previous frame (also while locked)
        pub dx: f32,
        pub dy: f32,
        /// about 1 per wheel notch; y > 0 = down
        pub wheel_x: f32,
        pub wheel_y: f32,
        pub buttons: u32,
        /// went down / up since the previous frame (a quick click shows in both)
        pub pressed: u32,
        pub released: u32,
        pub flags: u32,
    }

    impl Pointer {
        pub fn inside(&self) -> bool {
            self.flags & 1 != 0
        }
        pub fn locked(&self) -> bool {
            self.flags & 4 != 0
        }
    }

    /// `None` if the runner has no pointer.
    pub fn pointer() -> Option<Pointer> {
        let mut b = [0u8; 48];
        if unsafe { sys::pointer(b.as_mut_ptr(), 48) } < 0 {
            return None;
        }
        let f = |i: usize| f32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
        let u = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
        Some(Pointer {
            x: f(0), y: f(4), frame_x: f(8), frame_y: f(12), dx: f(16), dy: f(20), wheel_x: f(24), wheel_y: f(28),
            buttons: u(32), pressed: u(36), released: u(40), flags: u(44),
        })
    }

    /// Raw gamepad or joystick. With `standard`, W3C order: buttons 0 south, 1 east,
    /// 2 west, 3 north, 4/5 shoulders, 6/7 triggers, 8 select, 9 start, 10/11 sticks,
    /// 12-15 d-pad, 16 home; axes 0/1 left stick, 2/3 right stick (y > 0 = down).
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct Gamepad {
        pub connected: bool,
        pub standard: bool,
        pub buttons: Vec<f32>,
        pub axes: Vec<f32>,
    }

    /// Slot 0-3 (connection order). `None` if the runner has no gamepad support.
    pub fn gamepad(slot: u32) -> Option<Gamepad> {
        let mut b = [0u8; 204];
        if unsafe { sys::gamepad(slot, b.as_mut_ptr(), 204) } < 0 {
            return None;
        }
        let u = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
        let f = |i: usize| f32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
        let (flags, nb, na) = (u(0), (u(4) as usize).min(32), (u(8) as usize).min(16));
        Some(Gamepad {
            connected: flags & 1 != 0,
            standard: flags & 2 != 0,
            buttons: (0..nb).map(|i| f(12 + i * 4)).collect(),
            axes: (0..na).map(|i| f(140 + i * 4)).collect(),
        })
    }

    /// Device name, if a gamepad is connected in `slot`.
    pub fn gamepad_name(slot: u32) -> Option<String> {
        let n = unsafe { sys::gamepad_name(slot, std::ptr::null_mut(), 0) };
        if n < 0 {
            return None;
        }
        let mut b = vec![0u8; n as usize];
        if n > 0 {
            unsafe { sys::gamepad_name(slot, b.as_mut_ptr(), n as u32) };
        }
        Some(String::from_utf8_lossy(&b).into_owned())
    }
}

/// Raw key codes (`GASM_KEY_*`, W3C `KeyboardEvent.code` names in [`keys::NAMES`]).
pub use sys::keys;

// ---- gfx ---------------------------------------------------------------------------

/// GPU rendering through `gasm:gfx` (a WebGPU subset; descriptors are JSON).
pub mod gfx {
    use crate::sys;

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct Shader(pub u32);
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct Buffer(pub u32);
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct Pipeline(pub u32);
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct BindGroup(pub u32);
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct BindGroupLayout(pub u32);
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct Texture(pub u32);
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct Sampler(pub u32);

    pub const COPY_DST: u32 = 0x08;
    pub const INDEX: u32 = 0x10;
    pub const VERTEX: u32 = 0x20;
    pub const UNIFORM: u32 = 0x40;
    pub const STORAGE: u32 = 0x80;

    /// Bind group layout entry visibility.
    pub const STAGE_VERTEX: u32 = 0x1;
    pub const STAGE_FRAGMENT: u32 = 0x2;
    /// Dynamic offsets must be multiples of this.
    pub const OFFSET_ALIGNMENT: u32 = 256;

    #[derive(Clone, Copy)]
    pub enum IndexFormat {
        U16 = 0,
        U32 = 1,
    }

    /// Plain-old-data that can be uploaded byte for byte.
    ///
    /// # Safety
    /// Implementors must have no padding and no pointers.
    pub unsafe trait Pod: Copy {}
    unsafe impl Pod for u8 {}
    unsafe impl Pod for u16 {}
    unsafe impl Pod for u32 {}
    unsafe impl Pod for f32 {}
    unsafe impl<T: Pod, const N: usize> Pod for [T; N] {}

    pub fn as_bytes<T: Pod>(data: &[T]) -> &[u8] {
        unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, std::mem::size_of_val(data)) }
    }

    /// Drawable size in pixels.
    pub fn size() -> (u32, u32) {
        unsafe { (sys::gfx_width(), sys::gfx_height()) }
    }
    pub fn create_shader(wgsl: &str) -> Shader {
        Shader(unsafe { sys::gfx_create_shader(wgsl.as_ptr(), wgsl.len() as u32) })
    }
    pub fn create_buffer(size: u32, usage: u32) -> Buffer {
        Buffer(unsafe { sys::gfx_create_buffer(size, usage) })
    }
    /// WebGPU `GPURenderPipelineDescriptor` as JSON (handles as numbers,
    /// color format `"surface"`, depth format `"depth24plus"`).
    pub fn create_pipeline(json: &str) -> Pipeline {
        Pipeline(unsafe { sys::gfx_create_pipeline(json.as_ptr(), json.len() as u32) })
    }
    /// `{"layout":L,"entries":[...]}` or `{"pipeline":P,"group":0,"entries":[...]}`; entries
    /// `{"binding":0,"buffer":B,"offset":0,"size":N}`, `{"binding":1,"texture":T}`, `{"binding":2,"sampler":S}`.
    pub fn create_bind_group(json: &str) -> BindGroup {
        BindGroup(unsafe { sys::gfx_create_bind_group(json.as_ptr(), json.len() as u32) })
    }
    /// `{"entries":[{"binding":0,"visibility":STAGE_VERTEX,"buffer":{"type":"uniform","hasDynamicOffset":true}}, ...]}`.
    /// Bind groups made from it work with every pipeline whose `"layout":[...]` lists it.
    pub fn create_bind_group_layout(json: &str) -> BindGroupLayout {
        BindGroupLayout(unsafe { sys::gfx_create_bind_group_layout(json.as_ptr(), json.len() as u32) })
    }
    /// `{"size":[w,h],"format":"rgba8unorm","mipLevelCount":n}`
    pub fn create_texture(json: &str) -> Texture {
        Texture(unsafe { sys::gfx_create_texture(json.as_ptr(), json.len() as u32) })
    }
    /// Upload a tightly packed RGBA8 region (`rgba.len() == w * h * 4`) of mip level `mip`.
    pub fn write_texture(t: Texture, mip: u32, x: u32, y: u32, w: u32, h: u32, rgba: &[u8]) {
        unsafe { sys::gfx_write_texture(t.0, mip, x, y, w, h, rgba.as_ptr(), rgba.len() as u32) }
    }
    /// `{"addressModeU":"repeat","magFilter":"linear","minFilter":"linear","mipmapFilter":"linear"}`
    pub fn create_sampler(json: &str) -> Sampler {
        Sampler(unsafe { sys::gfx_create_sampler(json.as_ptr(), json.len() as u32) })
    }
    /// Offset and byte length must be multiples of 4.
    pub fn write_buffer<T: Pod>(buf: Buffer, offset: u32, data: &[T]) {
        let b = as_bytes(data);
        unsafe { sys::gfx_write_buffer(buf.0, offset, b.as_ptr(), b.len() as u32) }
    }
    /// Returns false if the runner will discard this frame (you may skip drawing).
    pub fn begin_frame(clear: [f32; 4]) -> bool {
        unsafe { sys::gfx_begin_frame(clear[0], clear[1], clear[2], clear[3]) != 0 }
    }
    pub fn set_pipeline(p: Pipeline) {
        unsafe { sys::gfx_set_pipeline(p.0) }
    }
    pub fn set_bind_group(index: u32, bg: BindGroup) {
        unsafe { sys::gfx_set_bind_group(index, bg.0) }
    }
    /// One offset (multiple of [`OFFSET_ALIGNMENT`]) per dynamic-offset entry, in binding order.
    pub fn set_bind_group_offsets(index: u32, bg: BindGroup, offsets: &[u32]) {
        unsafe { sys::gfx_set_bind_group_offsets(index, bg.0, offsets.as_ptr(), offsets.len() as u32) }
    }
    /// Viewport in drawable pixels (clamped to the drawable), depth range 0..=1.
    pub fn set_viewport(x: f32, y: f32, w: f32, h: f32, min_depth: f32, max_depth: f32) {
        unsafe { sys::gfx_set_viewport(x, y, w, h, min_depth, max_depth) }
    }
    /// Scissor rectangle in drawable pixels (clamped to the drawable).
    pub fn set_scissor_rect(x: u32, y: u32, w: u32, h: u32) {
        unsafe { sys::gfx_set_scissor_rect(x, y, w, h) }
    }
    pub fn set_vertex_buffer(slot: u32, buf: Buffer, offset: u32) {
        unsafe { sys::gfx_set_vertex_buffer(slot, buf.0, offset) }
    }
    pub fn set_index_buffer(buf: Buffer, format: IndexFormat, offset: u32) {
        unsafe { sys::gfx_set_index_buffer(buf.0, format as u32, offset) }
    }
    pub fn draw(vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) {
        unsafe { sys::gfx_draw(vertices, instances, first_vertex, first_instance) }
    }
    pub fn draw_indexed(indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) {
        unsafe { sys::gfx_draw_indexed(indices, instances, first_index, base_vertex, first_instance) }
    }
    pub fn end_frame() {
        unsafe { sys::gfx_end_frame() }
    }
}

// ---- net ---------------------------------------------------------------------------

/// Message connections through `gasm:net` (WebSocket semantics, non-blocking).
pub mod net {
    use crate::sys;

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub enum State {
        Connecting,
        Open,
        Closed,
        Error,
    }

    pub enum Recv {
        Message(Vec<u8>),
        Empty,
        Closed,
    }

    #[derive(Debug)]
    pub struct Conn(i32);

    impl Conn {
        /// Open `ws://` / `wss://`. `None` if the runner denies it.
        pub fn open(url: &str) -> Option<Conn> {
            let h = unsafe { sys::net_open(url.as_ptr(), url.len() as u32) };
            (h > 0).then_some(Conn(h))
        }
        pub fn state(&self) -> State {
            match unsafe { sys::net_state(self.0) } {
                0 => State::Connecting,
                1 => State::Open,
                2 => State::Closed,
                _ => State::Error,
            }
        }
        /// Send one message. False if the connection is not open.
        pub fn send(&self, msg: &[u8]) -> bool {
            !msg.is_empty() && unsafe { sys::net_send(self.0, msg.as_ptr(), msg.len() as u32) } == 0
        }
        /// Next queued message, if any.
        pub fn recv(&self) -> Recv {
            let mut buf = [0u8; 1024];
            let n = unsafe { sys::net_recv(self.0, buf.as_mut_ptr(), buf.len() as u32) };
            match n {
                0 => Recv::Empty,
                n if n < 0 => Recv::Closed,
                n if n as usize <= buf.len() => Recv::Message(buf[..n as usize].to_vec()),
                n => {
                    let mut big = vec![0u8; n as usize];
                    unsafe { sys::net_recv(self.0, big.as_mut_ptr(), n as u32) };
                    Recv::Message(big)
                }
            }
        }
    }

    impl Drop for Conn {
        fn drop(&mut self) {
            unsafe { sys::net_close(self.0) }
        }
    }
}

// ---- game entry points ----------------------------------------------------------------

/// A gasm game. `init` runs once; `frame` runs at the configured frame rate.
pub trait Game: Sized + 'static {
    fn init() -> Result<Self, String>;
    fn frame(&mut self);
    /// Called (best effort) when the player closes the game: flush saves here.
    /// Not called after `gasm::exit`, a trap, or a crash, so also save periodically.
    fn exit(&mut self) {}
}

#[doc(hidden)]
pub struct GameCell<T>(pub UnsafeCell<Option<T>>);
// Wasm guests are single-threaded; the runner never calls exports concurrently.
unsafe impl<T> Sync for GameCell<T> {}

#[doc(hidden)]
pub fn __init<G: Game>(cell: &GameCell<G>) -> i32 {
    std::panic::set_hook(Box::new(|info| log(&format!("panic: {info}"))));
    match G::init() {
        Ok(g) => {
            unsafe { *cell.0.get() = Some(g) };
            0
        }
        Err(e) => {
            log(&format!("init failed: {e}"));
            1
        }
    }
}

#[doc(hidden)]
pub fn __frame<G: Game>(cell: &GameCell<G>) {
    if let Some(g) = unsafe { (*cell.0.get()).as_mut() } {
        g.frame();
    }
}

#[doc(hidden)]
pub fn __exit<G: Game>(cell: &GameCell<G>) {
    if let Some(g) = unsafe { (*cell.0.get()).as_mut() } {
        g.exit();
    }
}

/// Export the gasm entry points for a [`Game`] type.
#[macro_export]
macro_rules! game {
    ($t:ty) => {
        static __GASM_GAME: $crate::GameCell<$t> = $crate::GameCell(::std::cell::UnsafeCell::new(None));

        #[unsafe(no_mangle)]
        pub extern "C" fn gasm_abi_version() -> i32 {
            $crate::ABI_VERSION
        }
        #[unsafe(no_mangle)]
        pub extern "C" fn gasm_init() -> i32 {
            $crate::__init::<$t>(&__GASM_GAME)
        }
        #[unsafe(no_mangle)]
        pub extern "C" fn gasm_frame() {
            $crate::__frame::<$t>(&__GASM_GAME)
        }
        #[unsafe(no_mangle)]
        pub extern "C" fn gasm_exit() {
            $crate::__exit::<$t>(&__GASM_GAME)
        }
    };
}