sm64_binds/sm64/
generator.rs1use anyhow::{Error, Result};
6use wasmer::{Engine, Module};
7
8use super::SM64Game;
9use super::memory::MemoryLayout;
10use super::util::{check_hash, unzip_bytes, xor_bytes};
11use super::wasm_module::{self, BuildId, DataSegments};
12
13const XOR_BYTES: &[u8] = include_bytes!("../../pkg/sm64_headless.us.wasm.zip.xor");
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum Backend {
19 #[default]
24 Auto,
25 Cranelift,
27 Precompiled,
30}
31
32#[derive(Debug, Clone)]
35pub struct SM64GameGenerator {
36 source: GameSource,
37}
38
39impl SM64GameGenerator {
40 pub fn new(rom_bytes: Vec<u8>) -> Result<Self, Error> {
42 if !check_hash(&rom_bytes) {
43 return Err(Error::msg(
44 "Invalid ROM. Should be a US copy, in z64 format (8.00MB)",
45 ));
46 };
47 Self::from_wasm(Self::rom_to_wasm_bytes(rom_bytes))
48 }
49
50 #[cfg(feature = "fs")]
51 pub fn from_file(rom_path: &str) -> Result<Self, Error> {
52 let rom_bytes = std::fs::read(rom_path)?;
53 Self::new(rom_bytes)
54 }
55
56 pub fn from_wasm(wasm_bytes: impl AsRef<[u8]>) -> Result<Self, Error> {
59 Self::from_wasm_with(wasm_bytes, Backend::Auto)
60 }
61
62 pub fn from_wasm_with(wasm_bytes: impl AsRef<[u8]>, backend: Backend) -> Result<Self, Error> {
64 let wasm = wasm_bytes.as_ref();
65 let source = match backend {
66 Backend::Auto => GameSource::for_wasm(wasm)?,
67 Backend::Cranelift => GameSource::cranelift(wasm)?,
68 Backend::Precompiled => GameSource::precompiled(wasm)?.ok_or_else(|| {
69 Error::msg("the precompiled module is not for this platform or this WASM")
70 })?,
71 };
72 Ok(SM64GameGenerator { source })
73 }
74
75 pub fn create_game(&self) -> Result<SM64Game, Error> {
76 SM64Game::from_source(&self.source)
77 }
78
79 pub fn rom_to_wasm_bytes(rom_bytes: Vec<u8>) -> Vec<u8> {
81 unzip_bytes(&xor_bytes(XOR_BYTES, &rom_bytes))
82 }
83
84 pub fn copy_from(&self, game: &SM64Game) -> Result<SM64Game, Error> {
86 let mut copy = self.create_game()?;
87 copy.copy_from(game)?;
88 Ok(copy)
89 }
90}
91
92#[derive(Debug, Clone)]
96pub(super) struct GameSource {
97 pub(super) engine: Engine,
98 pub(super) module: Module,
99 pub(super) segments: Option<std::sync::Arc<DataSegments>>,
102 pub(super) build_id: BuildId,
104 pub(super) layout: MemoryLayout,
106}
107
108impl GameSource {
109 fn for_wasm(wasm: &[u8]) -> Result<GameSource> {
114 let wanted = std::env::var("SM64_BACKEND").ok();
115 match wanted.as_deref() {
116 None | Some("cranelift") | Some("precompiled") => {}
117 Some(other) => {
118 return Err(Error::msg(format!(
119 "SM64_BACKEND={other}: expected cranelift or precompiled"
120 )));
121 }
122 }
123 if wanted.as_deref() != Some("cranelift") {
124 if let Some(source) = Self::precompiled(wasm)? {
125 return Ok(source);
126 }
127 if wanted.as_deref() == Some("precompiled") {
128 return Err(Error::msg(
129 "SM64_BACKEND=precompiled, but the precompiled module is not for this \
130 platform or was made from a different WASM",
131 ));
132 }
133 }
134 Self::cranelift(wasm)
135 }
136
137 fn cranelift(wasm: &[u8]) -> Result<GameSource> {
138 let (code, data) = wasm_module::separate_data(wasm)?;
139 let engine = Engine::default();
140 let module = Module::new(&engine, wasm)?;
141 Ok(GameSource {
142 engine,
143 module,
144 segments: None,
145 build_id: wasm_module::build_id(&code),
146 layout: MemoryLayout::from_data(&data),
147 })
148 }
149
150 fn precompiled(wasm: &[u8]) -> Result<Option<GameSource>> {
152 #[cfg(all(
153 feature = "precompiled",
154 target_arch = "x86_64",
155 target_os = "linux",
156 target_env = "gnu"
157 ))]
158 {
159 let (code, segments) = wasm_module::separate_data(wasm)?;
160 let build_id = wasm_module::build_id(&code);
161 Ok(
162 super::precompiled::load(&build_id)?.map(|(engine, module)| GameSource {
163 engine,
164 module,
165 layout: MemoryLayout::from_data(&segments),
166 segments: Some(std::sync::Arc::new(segments)),
167 build_id,
168 }),
169 )
170 }
171 #[cfg(not(all(
172 feature = "precompiled",
173 target_arch = "x86_64",
174 target_os = "linux",
175 target_env = "gnu"
176 )))]
177 {
178 let _ = wasm;
179 Ok(None)
180 }
181 }
182}