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