Skip to main content

sm64_binds/sm64/
portable_game.rs

1//! [`SM64Game`] and portable states: exporting the headless game's state in a
2//! form the rendering build loads too, and loading one from either build.
3
4use anyhow::{Error, Result};
5use wasmer::TypedFunction;
6
7use super::SM64Game;
8use super::portable::{self, Build, Portable};
9
10/// What [`SM64Game::load_portable`] did.
11#[derive(Debug, Clone, Default)]
12pub struct PortableLoadReport {
13    /// Blocks the state needed, of which this many reused the game's own.
14    pub blocks: usize,
15    pub reused: usize,
16    /// Bytes written.
17    pub bytes: usize,
18    /// Pointers the state had that this build has no equivalent of (set to
19    /// null): zero for states from a build of the same sources.
20    pub untranslated: u32,
21    /// Bytes of ghosts (copies of freed memory that stale pointers read) allocated and
22    /// never freed by this load.
23    pub ghost_bytes: usize,
24}
25
26impl SM64Game {
27    /// This game's state in portable form: what [`SM64Game::load_portable`]
28    /// of any build loads, so the game goes on identically.
29    pub fn export_portable(&self) -> Result<Portable> {
30        self.with_memory(|m| portable::export(m, Build::Headless))
31            .map_err(Error::msg)
32    }
33
34    /// Makes this game the one `state` was exported from, by either build.
35    ///
36    /// The game's variables are overwritten, and its heap blocks are reused
37    /// (or, for the ones that do not fit, allocated with the game's `malloc`)
38    /// to hold the state's. Display lists, audio output and the like are not
39    /// part of a state: the next frame rebuilds them.
40    pub fn load_portable(&mut self, state: &Portable) -> Result<PortableLoadReport> {
41        let old = self
42            .with_memory(|m| portable::game_blocks(m, Build::Headless))
43            .map_err(Error::msg)?;
44        let addrs = state.place(&old);
45        self.load_portable_at(state, addrs)
46    }
47
48    /// [`SM64Game::load_portable`] with the blocks' addresses given (0 to
49    /// have one allocated): for tests.
50    #[doc(hidden)]
51    pub fn load_portable_at(
52        &mut self,
53        state: &Portable,
54        mut addrs: Vec<u32>,
55    ) -> Result<PortableLoadReport> {
56        let sizes = state.chunk_sizes();
57        let reused = addrs.iter().filter(|&&a| a != 0).count();
58        for (i, a) in addrs.iter_mut().enumerate() {
59            if *a == 0 {
60                let (store, exports) = self.parts_mut();
61                let malloc: TypedFunction<i32, i32> = exports
62                    .instance
63                    .exports
64                    .get_typed_function(store, "malloc")?;
65                *a = malloc.call(store, sizes[i] as i32)? as u32;
66                if *a == 0 {
67                    return Err(Error::msg("malloc failed while loading a portable state"));
68                }
69            }
70        }
71        let (patches, bad) = state.patches(Build::Headless, &addrs).map_err(Error::msg)?;
72        if bad > 0 && std::env::var("SM64_PORTABLE_DEBUG").is_ok() {
73            eprintln!(
74                "untranslatable pointers: {:?}",
75                state.untranslatable(Build::Headless, &addrs)
76            );
77        }
78        let [gen_at, count_at] = Portable::geo_cache();
79        let (ptr, size) = self.mem_mut();
80        let mut bytes = 0;
81        for (a, data) in &patches {
82            let end = *a as usize + data.len();
83            if end > size {
84                return Err(Error::msg(format!("patch at {a:#x} is outside memory")));
85            }
86            // SAFETY: in bounds, and `data` is a separate allocation.
87            unsafe {
88                std::ptr::copy_nonoverlapping(data.as_ptr(), ptr.add(*a as usize), data.len())
89            };
90            bytes += data.len();
91        }
92        // The render walk's cache holds nodes of the old state: invalidate it.
93        // SAFETY: the cache's two words are inside the headless build's memory.
94        unsafe {
95            let gen_p = ptr.add(gen_at as usize) as *mut u32;
96            gen_p.write_unaligned(gen_p.read_unaligned().wrapping_add(1));
97            (ptr.add(count_at as usize) as *mut u32).write_unaligned(0);
98        }
99        Ok(PortableLoadReport {
100            blocks: addrs.len(),
101            reused,
102            bytes,
103            untranslated: bad,
104            ghost_bytes: state.ghost_bytes(),
105        })
106    }
107}