Skip to main content

sm64_binds/
sm64.rs

1use anyhow::{Error, Result};
2use wasmer::*;
3
4mod dirty;
5mod game_pad;
6mod game_state;
7mod generator;
8mod memory;
9pub mod mupen;
10pub mod portable;
11mod portable_game;
12#[cfg(all(
13    feature = "precompiled",
14    target_arch = "x86_64",
15    target_os = "linux",
16    target_env = "gnu"
17))]
18mod precompiled;
19mod save_state;
20mod sync;
21mod util;
22mod wasm_module;
23
24pub use game_pad::GamePad;
25pub use game_state::{GAME_STATE_SIZE, GameState};
26pub use generator::{Backend, SM64GameGenerator};
27pub use portable_game::PortableLoadReport;
28pub use save_state::SaveState;
29
30use generator::GameSource;
31use memory::MemoryLayout;
32use sync::SyncState;
33use wasm_module::BuildId;
34
35/// How [`SM64Game::set_object_freeze`] freezes objects.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum FreezeMode {
38    /// Exact play (the default).
39    Off,
40    /// Every object except Mario and doors, using the game's own time stop.
41    All,
42}
43
44/// A single playable instance of the game, made by
45/// [`SM64GameGenerator::create_game`] (`sm64/generator.rs`).
46///
47/// Its memory is handled in `sm64/memory.rs` (reads, copies),
48/// `sm64/save_state.rs` ([`SaveState`]) and `sm64/sync.rs`
49/// ([`SM64Game::sync_from`]).
50pub struct SM64Game {
51    store: Store,
52    exports: Exports,
53    precompiled: bool,
54    /// Which build of the game this is, for [`SaveState`]s.
55    build_id: BuildId,
56    /// Which parts of memory are constant.
57    layout: MemoryLayout,
58    sync: SyncState,
59}
60
61/// The instance and its exports, cached so the hot paths don't look them up on
62/// every call.
63struct Exports {
64    /// Kept so optional exports can be looked up by name without being
65    /// required at load time.
66    instance: Instance,
67    memory: Memory,
68    step_game: TypedFunction<(u32, i32, i32), ()>,
69    get_game_state: TypedFunction<(), i32>,
70}
71
72impl SM64Game {
73    /// A new game from `source`: [`SM64GameGenerator::create_game`].
74    fn from_source(source: &GameSource) -> Result<Self> {
75        let mut store = Store::new(source.engine.clone());
76        let import_object = imports! {
77            "wasi_snapshot_preview1" => {
78                "proc_exit" => Function::new_typed(&mut store, |_exit_code: i32| {}),
79                // The headless build must not try to talk to a terminal; the
80                // return values keep libc's stdio happy.
81                "fd_write" => Function::new_typed(&mut store, |_fd: i32, _iovs: i32, _iovs_len: i32, _bytes_written: i32| -> i32 { 0 }),
82                "fd_close" => Function::new_typed(&mut store, |_fd: i32| -> i32 { 0 }),
83                "fd_seek" => Function::new_typed(&mut store, |_fd: i32, _offset: i64, _whence: i32, _new_offset: i32| -> i32 { 0 }),
84            },
85        };
86
87        let instance = Instance::new(&mut store, &source.module, &import_object)?;
88        let exports = &instance.exports;
89
90        let memory = exports.get_memory("memory")?.clone();
91        if let Some(segments) = &source.segments {
92            // What instantiating the full WASM would have placed.
93            let view = memory.view(&store);
94            for (offset, bytes) in segments.iter() {
95                view.write(*offset as u64, bytes)?;
96            }
97        }
98        let step_game = exports.get_typed_function(&store, "step_game")?;
99        let get_game_state = exports.get_typed_function(&store, "get_game_state")?;
100
101        let main_func: TypedFunction<(), ()> = exports.get_typed_function(&store, "main_func")?;
102        main_func.call(&mut store)?;
103
104        Ok(SM64Game {
105            store,
106            exports: Exports {
107                instance,
108                memory,
109                step_game,
110                get_game_state,
111            },
112            precompiled: source.segments.is_some(),
113            build_id: source.build_id,
114            layout: source.layout,
115            sync: SyncState::new(),
116        })
117    }
118
119    /// Which way this game's code was compiled: `"precompiled"` (ahead of
120    /// time, shipped in the crate) or `"cranelift"` (when it was loaded).
121    pub fn backend(&self) -> &'static str {
122        if self.precompiled {
123            "precompiled"
124        } else {
125            "cranelift"
126        }
127    }
128
129    /// The store and exports, for running the game's code or growing its
130    /// memory. Counts as a change to the game's memory, for
131    /// [`SM64Game::sync_from`]: every call into the game goes through here.
132    fn parts_mut(&mut self) -> (&mut Store, &Exports) {
133        self.sync.touch();
134        (&mut self.store, &self.exports)
135    }
136
137    pub fn step_game(&mut self, pad: GamePad) -> Result<()> {
138        let (store, exports) = self.parts_mut();
139        exports.step_game.call(
140            store,
141            pad.button.into(),
142            pad.stick_x.into(),
143            pad.stick_y.into(),
144        )?;
145        Ok(())
146    }
147
148    pub fn get_game_state(&mut self) -> Result<GameState, Error> {
149        let (store, exports) = self.parts_mut();
150        let pointer = exports.get_game_state.call(store)? as u32;
151
152        let mut buffer: [u8; GAME_STATE_SIZE] = [0; GAME_STATE_SIZE];
153        self.read_memory(pointer, &mut buffer)?;
154        Ok(GameState::new(&buffer))
155    }
156
157    /// Turns the display-list interpreter on or off.
158    ///
159    /// Headless builds start with it off: the game never reads its output, so
160    /// it only costs time. Turning it on is for checking exactly that. The
161    /// setting lives in linear memory, so copies and save states carry it.
162    /// Fails on WASM built before the export existed.
163    pub fn set_render_enabled(&mut self, enabled: bool) -> Result<()> {
164        self.call_i32("set_render_enabled", enabled.into())
165    }
166
167    /// Turns audio synthesis on or off. Headless builds start with it off.
168    ///
169    /// Like [`SM64Game::set_render_enabled`], the setting is part of the
170    /// game's memory and so travels with copies and save states.
171    pub fn set_audio_enabled(&mut self, enabled: bool) -> Result<()> {
172        self.call_i32("set_audio_enabled", enabled.into())
173    }
174
175    /// Freezes objects so frames are cheaper, at the cost of exactness.
176    ///
177    /// A frozen game no longer plays like the real one: frozen enemies can't
178    /// be defeated, `!` boxes and red coins don't spawn stars, and so on. Use
179    /// it to screen candidates, then replay the ones that matter on an exact
180    /// game. Switching back to [`FreezeMode::Off`] does not make a game exact
181    /// again. The mode is stored in linear memory, so copies inherit it.
182    /// Needs a headless build with the `set_object_freeze` export.
183    pub fn set_object_freeze(&mut self, mode: FreezeMode) -> Result<()> {
184        let code = match mode {
185            FreezeMode::Off => 0,
186            FreezeMode::All => 1,
187        };
188        self.call_i32("set_object_freeze", code)
189    }
190
191    /// False once objects have been frozen in this game, or in the game (or
192    /// save state) it was copied from. The marker lives in linear memory, so
193    /// it travels with the state. Builds without freezing are always exact.
194    pub fn is_exact(&mut self) -> Result<bool> {
195        if !self.has_export("objects_ever_frozen") {
196            return Ok(true);
197        }
198        Ok(self.call_export_u32("objects_ever_frozen")? == 0)
199    }
200
201    /// Calls an export that takes an i32 and returns nothing.
202    fn call_i32(&mut self, name: &str, value: i32) -> Result<()> {
203        let (store, exports) = self.parts_mut();
204        let f: TypedFunction<i32, ()> = exports.instance.exports.get_typed_function(store, name)?;
205        f.call(store, value)?;
206        Ok(())
207    }
208
209    /// Calls a zero-argument export that returns an `i32` (typically a
210    /// pointer into linear memory) and returns it as a `u32`.
211    ///
212    /// Looked up by name on every call, so this is for occasional use (such as
213    /// `get_mario_state`), not hot paths. Fails if the WASM lacks the export.
214    pub fn call_export_u32(&mut self, name: &str) -> Result<u32> {
215        let (store, exports) = self.parts_mut();
216        let f: TypedFunction<(), i32> = exports.instance.exports.get_typed_function(store, name)?;
217        Ok(f.call(store)? as u32)
218    }
219
220    /// Whether the loaded WASM has an export called `name`.
221    pub fn has_export(&self, name: &str) -> bool {
222        self.exports.instance.exports.get_extern(name).is_some()
223    }
224
225    /// Low-level escape hatch: the wasmer store and instance, for calling
226    /// exports with signatures the typed methods above don't cover. Re-exported as
227    /// `sm64_binds::wasmer` so callers use the same wasmer version.
228    pub fn wasm_parts(&mut self) -> (&mut Store, &Instance, &Memory) {
229        let (store, exports) = self.parts_mut();
230        (store, &exports.instance, &exports.memory)
231    }
232}