1use anyhow::{Result, bail};
15
16use super::MupenState;
17use super::layout::{Counts, convert, named, var};
18use super::tables::{BUILD_ID, N64_ONLY, PORT_ONLY, TARGETS, VARS};
19use super::translate::Translator;
20use crate::sm64::SM64Game;
21
22#[derive(Debug, Clone, Default)]
24pub struct MupenLoadReport {
25 pub level: i16,
26 pub area: i16,
27 pub vars_copied: usize,
29 pub pointers: u32,
32 pub pointers_kept: u32,
33 pub pairs_learned: usize,
35 pub static_surfaces: (u32, u32, u32),
39 pub dynamic_surfaces: (u32, u32),
42 pub objects_differing: u32,
46 pub kept: Vec<(String, u32, u32)>,
49 pub notes: Vec<String>,
50 pub envfx: Option<(u32, u32, u32)>,
52}
53
54impl std::fmt::Display for MupenLoadReport {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 writeln!(
57 f,
58 "level {} area {}: {} variables, {} pointers ({} kept as the port's), {} learned pairs",
59 self.level,
60 self.area,
61 self.vars_copied,
62 self.pointers,
63 self.pointers_kept,
64 self.pairs_learned
65 )?;
66 writeln!(
67 f,
68 "static surfaces n64 {} port {} differing {}; dynamic surfaces n64 {} copied {}; objects differing {}",
69 self.static_surfaces.0,
70 self.static_surfaces.1,
71 self.static_surfaces.2,
72 self.dynamic_surfaces.0,
73 self.dynamic_surfaces.1,
74 self.objects_differing
75 )?;
76 for n in &self.notes {
77 writeln!(f, "note: {n}")?;
78 }
79 Ok(())
80 }
81}
82
83fn n64_only(name: &str) -> Option<u32> {
84 N64_ONLY.iter().find(|(n, _)| *n == name).map(|(_, a)| *a)
85}
86
87fn port_only(name: &str) -> Option<u32> {
88 PORT_ONLY.iter().find(|(n, _)| *n == name).map(|(_, a)| *a)
89}
90
91fn p32(m: &[u8], a: u32) -> u32 {
93 m.get(a as usize..a as usize + 4)
94 .map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap()))
95}
96fn p16(m: &[u8], a: u32) -> u16 {
97 m.get(a as usize..a as usize + 2)
98 .map_or(0, |b| u16::from_le_bytes(b.try_into().unwrap()))
99}
100
101fn n64_int(st: &MupenState, name: &str) -> Option<i64> {
103 let v = var(name)?;
104 Some(match v.size {
105 1 => st.u8(v.n64)? as i8 as i64,
106 2 => st.s16(v.n64)? as i64,
107 _ => st.u32(v.n64)? as i32 as i64,
108 })
109}
110fn port_int(m: &[u8], name: &str) -> Option<i64> {
111 let v = var(name)?;
112 Some(match v.size {
113 1 => *m.get(v.port as usize)? as i8 as i64,
114 2 => p16(m, v.port) as i16 as i64,
115 _ => p32(m, v.port) as i32 as i64,
116 })
117}
118
119fn pool_items(m: &[u8], pool: u32, item: u32, count: u32) -> Vec<u32> {
123 let mut blocks = Vec::new();
124 let mut b = p32(m, pool);
125 while b != 0 && blocks.len() < 64 {
126 blocks.push(b);
127 b = p32(m, b);
128 }
129 blocks.reverse();
130 let mut out = Vec::with_capacity(count as usize);
131 let mut size = 100u32;
132 for (i, &blk) in blocks.iter().enumerate() {
133 let n = if i + 1 == blocks.len() {
134 p32(m, pool + 8) / item
135 } else {
136 size / item
137 };
138 for j in 0..n {
139 out.push(blk + 8 + j * item);
140 }
141 size = size.saturating_mul(2).max(item);
142 }
143 out.truncate(count as usize);
144 out
145}
146
147fn describe(a: u32) -> String {
149 let i = VARS.partition_point(|v| v.n64 <= a);
150 if let Some(v) = i.checked_sub(1).map(|i| &VARS[i])
151 && a - v.n64 < v.size
152 {
153 return format!("{}+{:#x}", v.name, a - v.n64);
154 }
155 format!("heap {a:#010x}")
156}
157
158const OBJECT_SIZE: u32 = 0x260;
159const POOL_CAPACITY: u32 = 240;
160const OBJ_BEHAVIOR: u32 = 0x20C;
161const OBJ_ANIMATIONS: u32 = 0x88 + 0x26 * 4;
162const OBJ_COLLISION: u32 = 0x218;
163const OBJ_CUR_ANIM: u32 = 0x3C;
164const OBJ_ANIM_ID: u32 = 0x38;
165const OBJ_SHARED_CHILD: u32 = 0x14;
166const OBJ_SPAWN_INFO: u32 = 0x4C;
167const OBJ_RESPAWN_INFO: u32 = 0x25C;
168
169impl MupenState {
170 pub fn level(&self) -> Option<i16> {
172 self.s16(var("gCurrLevelNum")?.n64)
173 }
174 pub fn area(&self) -> Option<i16> {
176 self.s16(var("gCurrAreaIndex")?.n64)
177 }
178 pub fn global_timer(&self) -> Option<u32> {
180 self.u32(var("gGlobalTimer")?.n64)
181 }
182 pub fn mario_state_bytes(&self) -> Option<Vec<u8>> {
186 let v = var("gMarioStates")?;
187 let src = self.bytes(v.n64, v.size as usize)?;
188 let mut out = vec![0u8; v.size as usize];
189 let mut tr = Translator::new(self, None, None);
190 convert(
191 v.layout,
192 src,
193 &mut out,
194 v.n64,
195 &mut tr,
196 &mut Counts::default(),
197 );
198 for (&at, &val) in &tr.failures {
201 let o = (at - v.n64) as usize;
202 out[o..o + 4].copy_from_slice(&val.to_le_bytes());
203 }
204 Some(out)
205 }
206}
207
208impl SM64Game {
209 pub fn load_mupen_state(&mut self, st: &MupenState) -> Result<MupenLoadReport> {
219 let id: String = self.build_id.iter().map(|b| format!("{b:02x}")).collect();
220 if id != BUILD_ID {
221 bail!("Mupen state tables are for build {BUILD_ID}, this game is build {id}");
222 }
223 let mut report = MupenLoadReport::default();
224 if !st.is_us_rom() {
225 report.notes.push(format!(
226 "state is for ROM MD5 {}, not the US ROM",
227 st.rom_md5
228 ));
229 }
230 let snap: Vec<u8> = self.with_memory(|m| m.to_vec());
231 let (Some(level), Some(area)) = (st.level(), st.area()) else {
232 bail!("state has no level/area");
233 };
234 let port_level = port_int(&snap, "gCurrLevelNum").unwrap_or(-1) as i16;
235 let port_area = port_int(&snap, "gCurrAreaIndex").unwrap_or(-1) as i16;
236 if (level, area) != (port_level, port_area) {
237 bail!(
238 "the state is in level {level} area {area}, this game is in level {port_level} area {port_area}: \
239 bring the game to the same area first"
240 );
241 }
242 report.level = level;
243 report.area = area;
244
245 let dynamic = |all: &str, stat: &str| {
249 (n64_int(st, all).unwrap_or(0) - n64_int(st, stat).unwrap_or(0)).max(0) as u32
250 };
251 let (d_surfaces, d_nodes) = (
252 dynamic("gSurfacesAllocated", "gNumStaticSurfaces"),
253 dynamic("gSurfaceNodesAllocated", "gNumStaticSurfaceNodes"),
254 );
255 let mut fresh = None;
256 if d_surfaces > 0 && d_nodes > 0 && self.has_export("malloc") {
257 let sb = self.malloc(8 + 48 * d_surfaces)?;
258 let nb = self.malloc(8 + 8 * d_nodes)?;
259 if sb != 0 && nb != 0 {
260 fresh = Some((sb, d_surfaces, nb, d_nodes));
261 }
262 }
263 let snap: Vec<u8> = self.with_memory(|m| m.to_vec());
264
265 let mut tr = Translator::new(st, n64_only("sSegmentTable"), Some(&snap));
266 learn_behaviors(&mut tr, &snap);
267 let level_copies = learn_tables(&mut tr, st, &snap, &mut report);
268 let surfaces = learn_surfaces(&mut tr, st, &snap, &mut report, fresh);
269 let object_pool = learn_object_pool(&mut tr, st, &snap, &mut report);
270 let object_heap = learn_objects(
271 &mut tr,
272 st,
273 &snap,
274 &mut report,
275 object_pool.as_ref().map(|p| p.space),
276 );
277 let paintings = learn_paintings(&mut tr, st, &snap, level);
278 report.pairs_learned = tr.pair_count();
279
280 let mut writes: Vec<(u32, Vec<u8>)> = Vec::new();
282 let mut counts = Counts::default();
283 for v in VARS.iter().filter(|v| v.copy) {
284 let (Some(src), Some(dst)) = (
285 st.bytes(v.n64, v.size as usize),
286 snap.get(v.port as usize..(v.port + v.size) as usize),
287 ) else {
288 continue;
289 };
290 let mut out = dst.to_vec();
291 convert(v.layout, src, &mut out, v.n64, &mut tr, &mut counts);
292 writes.push((v.port, out));
293 report.vars_copied += 1;
294 }
295
296 fix_s16_fields(st, &mut writes, &tr);
297
298 if let (Some((nb, pb, count)), Some((size, layout))) =
299 (report.envfx, named("EnvFxParticle"))
300 {
301 for k in 0..count {
302 heap_struct(
303 &mut writes,
304 &mut tr,
305 &mut counts,
306 st,
307 &snap,
308 nb + k * size,
309 pb + k * size,
310 size,
311 layout,
312 );
313 }
314 }
315
316 let read_only = self.read_only_memory();
319 for &(n, p, size, unit) in &level_copies {
320 if read_only.contains(&(p as usize)) {
321 continue;
322 }
323 if let Some(src) = st.bytes(n, size as usize) {
324 let out: Vec<u8> = src
325 .chunks_exact(unit)
326 .flat_map(|h| h.iter().rev().copied())
327 .collect();
328 writes.push((p, out));
329 }
330 }
331
332 if let Some((size, layout)) = named("Painting") {
334 for &(n, p) in &paintings {
335 heap_struct(
336 &mut writes,
337 &mut tr,
338 &mut counts,
339 st,
340 &snap,
341 n,
342 p,
343 size,
344 layout,
345 );
346 }
347 }
348
349 if let Some(pool) = object_pool {
352 writes.extend(pool.writes);
353 }
354 if let Some((size, layout)) = named("ChainSegment") {
355 for &(n, p, len) in &object_heap {
356 debug_assert_eq!(len, size);
357 heap_struct(
358 &mut writes,
359 &mut tr,
360 &mut counts,
361 st,
362 &snap,
363 n,
364 p,
365 size,
366 layout,
367 );
368 }
369 }
370
371 if let (Some(gc), Some((size, layout))) = (var("gCamera"), named("Camera")) {
373 let (n, p) = (st.u32(gc.n64).unwrap_or(0), p32(&snap, gc.port));
374 if n != 0 && p != 0 {
375 heap_struct(
376 &mut writes,
377 &mut tr,
378 &mut counts,
379 st,
380 &snap,
381 n,
382 p,
383 size,
384 layout,
385 );
386 }
387 }
388
389 if let Some(s) = surfaces {
392 writes.extend(s.writes.iter().cloned());
393 for (kind, n64s, ports, statics, item) in [
394 (
395 "Surface",
396 &s.n64_surfaces,
397 &s.port_surfaces,
398 s.static_surfaces,
399 48u32,
400 ),
401 (
402 "SurfaceNode",
403 &s.n64_nodes,
404 &s.port_nodes,
405 s.static_nodes,
406 8u32,
407 ),
408 ] {
409 let Some((size, layout)) = named(kind) else {
410 continue;
411 };
412 debug_assert_eq!(size, item);
413 for (i, (&n, &p)) in n64s.iter().zip(ports.iter()).enumerate() {
414 if (i as u32) < statics {
415 let mut out = snap[p as usize..(p + size) as usize].to_vec();
416 let mut c = Counts::default();
417 convert(
418 layout,
419 st.bytes(n, size as usize).unwrap_or(&[]),
420 &mut out,
421 n,
422 &mut tr,
423 &mut c,
424 );
425 if kind == "Surface" && out != snap[p as usize..(p + size) as usize] {
426 report.static_surfaces.2 += 1;
427 }
428 } else {
429 heap_struct(
430 &mut writes,
431 &mut tr,
432 &mut counts,
433 st,
434 &snap,
435 n,
436 p,
437 size,
438 layout,
439 );
440 if kind == "Surface" {
441 report.dynamic_surfaces.1 += 1;
442 }
443 }
444 }
445 }
446 }
447
448 report.pointers = counts.pointers;
449 report.pointers_kept = counts.kept;
450 report.kept = tr
451 .failures
452 .iter()
453 .take(400)
454 .map(|(&at, &v)| (describe(at), at, v))
455 .collect();
456
457 let (ptr, len) = self.mem_mut();
459 let mem = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
462 for (addr, bytes) in &writes {
463 let a = *addr as usize;
464 if let Some(dst) = mem.get_mut(a..a + bytes.len()) {
465 dst.copy_from_slice(bytes);
466 }
467 }
468 fix_mario_animation(st, mem, &mut report);
469 Ok(report)
470 }
471}
472
473impl SM64Game {
474 fn malloc(&mut self, size: u32) -> Result<u32> {
476 let (store, exports) = self.parts_mut();
477 let f: wasmer::TypedFunction<i32, i32> = exports
478 .instance
479 .exports
480 .get_typed_function(store, "malloc")?;
481 Ok(f.call(store, size as i32)? as u32)
482 }
483
484 pub fn warp_to_mupen_area(&mut self, st: &MupenState, max_frames: u32) -> Result<u32> {
493 let (Some(level), Some(area)) = (st.level(), st.area()) else {
494 bail!("state has no level/area");
495 };
496 let here = |g: &SM64Game| {
497 g.with_memory(|m| {
498 (
499 port_int(m, "gCurrLevelNum").unwrap_or(-1) as i16,
500 port_int(m, "gCurrAreaIndex").unwrap_or(-1) as i16,
501 port_int(m, "sCurrPlayMode").unwrap_or(-1),
502 p32(m, var("gMarioStates").map_or(0, |v| v.port) + 0x0C),
503 )
504 })
505 };
506 let transition = |g: &SM64Game| {
507 g.with_memory(|m| p32(m, var("sTransitionUpdate").map_or(0, |v| v.port)))
508 };
509 if here(self).0 == level && here(self).1 == area {
510 return Ok(0);
511 }
512 let mut waited = 0;
514 loop {
515 let (l, a, mode, action) = here(self);
516 if (l, a) == (level, area) && mode == 0 && action != 0 {
517 return Ok(waited);
518 }
519 if l > 1 && mode == 0 && action != 0 && transition(self) == 0 {
520 break;
521 }
522 if waited >= max_frames || l <= 1 {
523 bail!(
524 "the game must be playing a level to warp (it is in level {l}, play mode {mode})"
525 );
526 }
527 self.step_game(crate::GamePad::default())?;
528 waited += 1;
529 }
530 let areas = var("gAreaData").ok_or_else(|| anyhow::anyhow!("no gAreaData"))?;
533 let mut node = st.u32(areas.n64 + 60 * area as u32 + 0x14).unwrap_or(0);
534 let mut ids = Vec::new();
535 while node != 0 && ids.len() < 256 {
536 ids.push(st.u8(node).unwrap_or(0));
537 node = st.u32(node + 8).unwrap_or(0);
538 }
539 let Some(&first) = ids.first() else {
540 bail!("the state's area has no warp nodes to arrive at");
541 };
542 let id = if ids.contains(&0x0A) { 0x0A } else { first };
543 let writes: Vec<(&str, Vec<u8>)> = vec![
544 (
545 "gCurrSaveFileNum",
546 (st.s16(var("gCurrSaveFileNum").unwrap().n64).unwrap_or(1))
547 .to_le_bytes()
548 .to_vec(),
549 ),
550 (
551 "gCurrActNum",
552 (st.s16(var("gCurrActNum").unwrap().n64).unwrap_or(1))
553 .to_le_bytes()
554 .to_vec(),
555 ),
556 ("sWarpCheckpointActive", vec![1]),
557 ("sTransitionTimer", 0i16.to_le_bytes().to_vec()),
558 ("sDelayedWarpOp", 0i16.to_le_bytes().to_vec()),
559 (
560 "sWarpDest",
561 vec![1, level as u8, area as u8, id, 0, 0, 0, 0],
562 ),
563 ("sCurrPlayMode", 4i16.to_le_bytes().to_vec()),
566 ];
567 {
568 let (ptr, len) = self.mem_mut();
569 let mem = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
571 for (name, bytes) in writes {
572 let v = var(name).unwrap();
573 mem[v.port as usize..v.port as usize + bytes.len()].copy_from_slice(&bytes);
574 }
575 }
576 for frame in 1..=max_frames {
577 self.step_game(crate::GamePad::default())?;
578 let (l, a, mode, action) = here(self);
579 if (l, a) == (level, area) && mode == 0 && action != 0 {
580 return Ok(waited + frame);
581 }
582 }
583 bail!("the warp to level {level} area {area} did not finish in {max_frames} frames")
584 }
585}
586
587#[allow(clippy::too_many_arguments)]
588fn heap_struct(
589 writes: &mut Vec<(u32, Vec<u8>)>,
590 tr: &mut Translator,
591 counts: &mut Counts,
592 st: &MupenState,
593 snap: &[u8],
594 n64: u32,
595 port: u32,
596 size: u32,
597 layout: u16,
598) {
599 let (Some(src), Some(dst)) = (
600 st.bytes(n64, size as usize),
601 snap.get(port as usize..(port + size) as usize),
602 ) else {
603 return;
604 };
605 let mut out = dst.to_vec();
606 convert(layout, src, &mut out, n64, tr, counts);
607 writes.push((port, out));
608}
609
610fn fix_s16_fields(st: &MupenState, writes: &mut [(u32, Vec<u8>)], tr: &Translator) {
616 use super::tables::{POINTER_SLOTS, S16_SLOTS, S16_SLOTS_ALL};
617 let Some((n_pool, p_pool, _)) = super::translate::target_by_name("gObjectPool") else {
618 return;
619 };
620 let Some(w) = writes.iter_mut().find(|w| w.0 == p_pool) else {
621 return;
622 };
623 for i in 0..POOL_CAPACITY {
624 let no = n_pool + i * OBJECT_SIZE;
625 let bhv = st.u32(no + OBJ_BEHAVIOR).unwrap_or(0);
626 let mut mask = S16_SLOTS_ALL;
627 if let Some(name) = bhv_name(tr, bhv)
628 && let Some((_, m)) = S16_SLOTS.iter().find(|(n, _)| *n == name)
629 {
630 mask |= m;
631 }
632 for slot in 0..0x50u32 {
633 let at = no + 0x88 + 4 * slot;
634 let Some(v) = st.u32(at) else { continue };
635 let o = (i * OBJECT_SIZE + 0x88 + 4 * slot) as usize;
636 if mask >> slot & 1 == 0 {
637 if POINTER_SLOTS >> slot & 1 == 0 && super::layout::looks_like_segmented(v) {
640 w.1[o..o + 4].copy_from_slice(&v.to_le_bytes());
641 }
642 continue;
643 }
644 let (hi, lo) = ((v >> 16) as u16, v as u16);
646 w.1[o..o + 2].copy_from_slice(&hi.to_le_bytes());
647 w.1[o + 2..o + 4].copy_from_slice(&lo.to_le_bytes());
648 }
649 }
650}
651
652fn learn_behaviors(tr: &mut Translator, snap: &[u8]) {
657 let mut anim_tables = Vec::new();
658 for t in TARGETS.iter().filter(|t| t.0 >> 24 == 0x13) {
659 let Some(base) = tr.segmented_to_virtual(t.0) else {
660 continue;
661 };
662 let words = t.2 / 4;
663 let mut prev_cmd = 0u32;
664 for i in 0..words {
665 let (Some(n), p) = (tr.st.u32(base + 4 * i), p32(snap, t.1 + 4 * i)) else {
666 break;
667 };
668 if n != p {
669 if (0x0100_0000..0x2000_0000).contains(&n) {
670 if let Some(v) = tr.segmented_to_virtual(n) {
671 tr.pair(v, p);
672 if prev_cmd >> 24 == 0x27 {
673 anim_tables.push((v, p));
674 }
675 }
676 } else if super::layout::looks_like_pointer(n) {
677 tr.pair(n, p);
678 }
679 }
680 prev_cmd = n;
681 }
682 }
683 for (n, p) in anim_tables {
684 pair_anim_table(tr, snap, n, p);
685 }
686}
687
688fn pair_anim_table(tr: &mut Translator, snap: &[u8], n: u32, p: u32) {
690 for i in 0..64 {
691 let (Some(ne), pe) = (tr.st.u32(n + 4 * i), p32(snap, p + 4 * i)) else {
692 break;
693 };
694 if ne == 0 || pe == 0 {
695 break;
696 }
697 let Some(nv) = tr
698 .segmented_to_virtual(ne)
699 .or_else(|| super::layout::looks_like_pointer(ne).then_some(ne))
700 else {
701 break;
702 };
703 tr.pair(nv, pe);
704 }
705}
706
707type LevelCopies = Vec<(u32, u32, u32, usize)>;
712
713fn learn_tables(
714 tr: &mut Translator,
715 st: &MupenState,
716 snap: &[u8],
717 report: &mut MupenLoadReport,
718) -> LevelCopies {
719 let mut copies = Vec::new();
720 learn_envfx(tr, st, snap, report);
721 if let Some(v) = var("gLoadedGraphNodes") {
722 let (n, p) = (st.u32(v.n64).unwrap_or(0), p32(snap, v.port));
723 if n != 0 && p != 0 {
724 for i in 0..256 {
725 tr.pair(st.u32(n + 4 * i).unwrap_or(0), p32(snap, p + 4 * i));
726 }
727 }
728 }
729 for (name, len) in [
730 ("gMarioAnimsMemAlloc", 0x4000),
731 ("gDemoInputsMemAlloc", 0x800),
732 ] {
733 if let Some(v) = var(name) {
734 tr.region(st.u32(v.n64).unwrap_or(0), len, p32(snap, v.port));
735 }
736 }
737 let camera = named("Camera").map_or(0, |c| c.0);
738 let spawn = named("SpawnInfo").map_or(32, |c| c.0);
739 let warp = named("ObjectWarpNode").map_or(12, |c| c.0);
740 if let Some(v) = var("gCamera") {
741 tr.region(st.u32(v.n64).unwrap_or(0), camera, p32(snap, v.port));
742 }
743 let Some(areas) = var("gAreaData") else {
744 return copies;
745 };
746 if named("Area").map(|a| a.0) != Some(60) {
747 report
748 .notes
749 .push("struct Area is not 60 bytes; areas not paired".into());
750 return copies;
751 }
752 for i in 0..areas.size / 60 {
753 let (na, pa) = (areas.n64 + 60 * i, areas.port + 60 * i);
754 let n = |o: u32| st.u32(na + o).unwrap_or(0);
755 let p = |o: u32| p32(snap, pa + o);
756 tr.pair(n(0x04), p(0x04));
757 tr.region(n(0x24), camera, p(0x24));
758 tr.region(n(0x1C), 32, p(0x1C));
759 for o in [0x2C, 0x30] {
760 tr.region(n(o), 8, p(o));
761 }
762 let (nm, pm) = (n(0x10), p(0x10));
764 if nm != 0 && pm != 0 {
765 let mut len = 0;
766 while len < 0x8000 && p16(snap, pm + len) != 0x1E {
767 len += 10;
768 }
769 tr.region(nm, len + 2, pm);
770 copies.push((nm, pm, len + 2, 2));
772 }
773 for (head, size, next) in [(0x20, spawn, 0x1C), (0x14, warp, 0x08)] {
775 let (mut ns, mut ps) = (n(head), p(head));
776 let mut k = 0;
777 while ns != 0 && ps != 0 && k < 1024 {
778 tr.region(ns, size, ps);
779 if head == 0x20 {
782 copies.push((ns + 0x10, ps + 0x10, 4, 4));
783 }
784 ns = st.u32(ns + next).unwrap_or(0);
785 ps = p32(snap, ps + next);
786 k += 1;
787 }
788 if (ns == 0) != (ps == 0) {
789 report.notes.push(format!(
790 "area {i}: lists at {head:#x} have different lengths"
791 ));
792 }
793 }
794 }
795 copies
796}
797
798fn learn_paintings(
802 tr: &mut Translator,
803 st: &MupenState,
804 snap: &[u8],
805 level: i16,
806) -> Vec<(u32, u32)> {
807 let list = match level {
808 6 => "sInsideCastlePaintings",
809 7 => "sHmcPaintings",
810 36 => "sTtmPaintings",
811 _ => return Vec::new(),
812 };
813 let (Some(v), Some((size, _))) = (var(list), named("Painting")) else {
814 return Vec::new();
815 };
816 let mut out = Vec::new();
817 for i in 0..v.size / 4 {
818 let (n, p) = (
819 st.u32(v.n64 + 4 * i).unwrap_or(0),
820 p32(snap, v.port + 4 * i),
821 );
822 let n = if super::layout::looks_like_pointer(n) {
823 Some(n)
824 } else {
825 tr.segmented_to_virtual(n)
826 };
827 if let Some(n) = n
828 && p != 0
829 {
830 tr.region(n, size, p);
831 out.push((n, p));
832 }
833 }
834 out
835}
836
837fn learn_envfx(tr: &mut Translator, st: &MupenState, snap: &[u8], report: &mut MupenLoadReport) {
840 let (Some(buf), Some(mode), Some((size, _))) = (
841 var("gEnvFxBuffer"),
842 n64_int(st, "gEnvFxMode"),
843 named("EnvFxParticle"),
844 ) else {
845 return;
846 };
847 let count = if mode == 0 {
848 return;
849 } else if mode < 10 {
850 "gSnowParticleMaxCount"
851 } else {
852 "sBubbleParticleCount"
853 };
854 let n = n64_int(st, count)
855 .unwrap_or(0)
856 .min(port_int(snap, count).unwrap_or(0));
857 let (nb, pb) = (st.u32(buf.n64).unwrap_or(0), p32(snap, buf.port));
858 if n > 0 && nb != 0 && pb != 0 && port_int(snap, "gEnvFxMode") == Some(mode) {
859 tr.region(nb, n as u32 * size, pb);
860 report.envfx = Some((nb, pb, n as u32));
861 }
862}
863
864struct Surfaces {
865 n64_surfaces: Vec<u32>,
866 port_surfaces: Vec<u32>,
867 static_surfaces: u32,
868 n64_nodes: Vec<u32>,
869 port_nodes: Vec<u32>,
870 static_nodes: u32,
871 writes: Vec<(u32, Vec<u8>)>,
873}
874
875fn learn_surfaces(
878 tr: &mut Translator,
879 st: &MupenState,
880 snap: &[u8],
881 report: &mut MupenLoadReport,
882 fresh: Option<(u32, u32, u32, u32)>,
883) -> Option<Surfaces> {
884 let n_pool = st.u32(n64_only("sSurfacePool")?)?;
885 let n_nodes = st.u32(n64_only("sSurfaceNodePool")?)?;
886 let get = |name: &str| {
887 (
888 n64_int(st, name).unwrap_or(0) as u32,
889 port_int(snap, name).unwrap_or(0) as u32,
890 )
891 };
892 let (n_static, p_static_count) = get("gNumStaticSurfaces");
893 let (n_all, p_all) = get("gSurfacesAllocated");
894 let (n_static_nodes, p_static_nodes_count) = get("gNumStaticSurfaceNodes");
895 let (n_all_nodes, p_all_nodes) = get("gSurfaceNodesAllocated");
896 report.dynamic_surfaces = (n_all.saturating_sub(n_static), 0);
897 let pool = |name| p32(snap, port_only(name).unwrap_or(0));
901 let mut port_surfaces = pool_items(snap, pool("sStaticSurfacePool"), 48, u32::MAX);
902 let mut port_nodes = pool_items(snap, pool("sStaticSurfaceNodePool"), 8, u32::MAX);
903 let (p_static, p_static_nodes) = (port_surfaces.len() as u32, port_nodes.len() as u32);
904 report.static_surfaces = (n_static, p_static, 0);
905 if n_static != p_static || n_static_nodes != p_static_nodes {
906 report.notes.push(format!(
907 "static collision differs (surfaces {n_static} vs {p_static}, nodes {n_static_nodes} vs {p_static_nodes}): \
908 surfaces not paired"
909 ));
910 return None;
911 }
912 let mut writes = Vec::new();
913 if let Some((sb, ns, nb, nn)) = fresh {
914 for (pool_var, block, count, item, all, stat) in [
918 (
919 "sDynamicSurfacePool",
920 sb,
921 ns,
922 48,
923 "gSurfacesAllocated",
924 p_static_count,
925 ),
926 (
927 "sDynamicSurfaceNodePool",
928 nb,
929 nn,
930 8,
931 "gSurfaceNodesAllocated",
932 p_static_nodes_count,
933 ),
934 ] {
935 let pool_at = pool(pool_var);
936 if pool_at == 0 {
937 return None;
938 }
939 let mut header = p32(snap, pool_at).to_le_bytes().to_vec();
940 header.extend_from_slice(&[0; 4]);
941 writes.push((block, header));
942 let mut fields = block.to_le_bytes().to_vec();
943 fields.extend_from_slice(&(count * item).to_le_bytes());
944 fields.extend_from_slice(&(count * item).to_le_bytes());
945 writes.push((pool_at, fields));
946 if let Some(v) = var(all) {
947 writes.push((
948 v.port,
949 (stat + count).to_le_bytes()[..v.size as usize].to_vec(),
950 ));
951 }
952 }
953 port_surfaces.extend((0..ns).map(|j| sb + 8 + 48 * j));
954 port_nodes.extend((0..nn).map(|j| nb + 8 + 8 * j));
955 } else {
956 port_surfaces.extend(pool_items(
957 snap,
958 pool("sDynamicSurfacePool"),
959 48,
960 p_all.saturating_sub(p_static_count),
961 ));
962 port_nodes.extend(pool_items(
963 snap,
964 pool("sDynamicSurfaceNodePool"),
965 8,
966 p_all_nodes.saturating_sub(p_static_nodes_count),
967 ));
968 }
969 let n64_surfaces: Vec<u32> = (0..n_all).map(|i| n_pool + 48 * i).collect();
970 let n64_nodes: Vec<u32> = (0..n_all_nodes).map(|i| n_nodes + 8 * i).collect();
971 for (n, p) in n64_surfaces.iter().zip(&port_surfaces) {
972 tr.pair(*n, *p);
973 }
974 for (n, p) in n64_nodes.iter().zip(&port_nodes) {
975 tr.pair(*n, *p);
976 }
977 let n = n64_surfaces.len().min(port_surfaces.len());
978 let m = n64_nodes.len().min(port_nodes.len());
979 Some(Surfaces {
980 n64_surfaces: n64_surfaces[..n].to_vec(),
981 port_surfaces: port_surfaces[..n].to_vec(),
982 static_surfaces: n_static,
983 n64_nodes: n64_nodes[..m].to_vec(),
984 port_nodes: port_nodes[..m].to_vec(),
985 static_nodes: n_static_nodes,
986 writes,
987 })
988}
989
990struct ObjectPool {
995 space: (u32, u32, u32),
997 writes: Vec<(u32, Vec<u8>)>,
999}
1000
1001fn learn_object_pool(
1009 tr: &mut Translator,
1010 st: &MupenState,
1011 snap: &[u8],
1012 report: &mut MupenLoadReport,
1013) -> Option<ObjectPool> {
1014 let v = var("gObjectMemoryPool")?;
1015 let (n_pool, p_pool) = (st.u32(v.n64)?, p32(snap, v.port));
1016 let (size, _) = named("MemoryPool")?;
1017 if n_pool == 0 || p_pool == 0 {
1018 return None;
1019 }
1020 let fixed = p_pool + size - 16;
1023 let n_total = st.u32(n_pool)?;
1024 let n_space = st.u32(n_pool + 4)?;
1025 let (p_total, p_first) = (p32(snap, fixed), p32(snap, fixed + 4));
1026 if n_total != p_total || n_total == 0 || n_space != n_pool + 16 || p_first != size {
1027 report.notes.push(format!(
1028 "object memory pool not copied: N64 {n_total:#x} bytes at {n_space:#x}, port {p_total:#x} at offset {p_first:#x}"
1029 ));
1030 return None;
1031 }
1032 let p_space = p_pool + p_first;
1033 let offset = |a: u32| {
1034 if a >= n_space && a - n_space < n_total {
1035 a - n_space + p_first
1036 } else {
1037 0
1038 }
1039 };
1040 let mut free = std::collections::HashSet::new();
1041 let mut at = st.u32(n_pool + 8)?;
1042 while at != 0 && free.len() < 1024 {
1043 if offset(at) == 0 || !free.insert(at - n_space) {
1044 break;
1045 }
1046 at = st.u32(at)?;
1047 }
1048 let mut space = vec![0u8; n_total as usize];
1049 let mut off = 0u32;
1050 while off < n_total {
1051 let (next, len) = (st.u32(n_space + off)?, st.u32(n_space + off + 4)?);
1052 if len < 8 || len % 4 != 0 || off + len > n_total {
1053 report.notes.push(format!(
1054 "object memory pool not copied: a block of {len:#x} bytes at offset {off:#x}"
1055 ));
1056 return None;
1057 }
1058 let o = off as usize;
1059 space[o..o + 4].copy_from_slice(&offset(next).to_le_bytes());
1060 space[o + 4..o + 8].copy_from_slice(&len.to_le_bytes());
1061 if !free.contains(&off) {
1062 for w in (8..len).step_by(4) {
1063 space[o + w as usize..o + w as usize + 4]
1064 .copy_from_slice(&st.u32(n_space + off + w)?.to_le_bytes());
1065 }
1066 }
1067 off += len;
1068 }
1069 let mut head = Vec::with_capacity(12);
1071 for w in [n_total, p_first, offset(st.u32(n_pool + 8)?)] {
1072 head.extend_from_slice(&w.to_le_bytes());
1073 }
1074 tr.region(n_space, n_total, p_space);
1075 Some(ObjectPool {
1076 space: (n_space, n_total, p_space),
1077 writes: vec![(fixed, head), (p_space, space)],
1078 })
1079}
1080
1081fn learn_objects(
1082 tr: &mut Translator,
1083 st: &MupenState,
1084 snap: &[u8],
1085 report: &mut MupenLoadReport,
1086 pool: Option<(u32, u32, u32)>,
1087) -> Vec<(u32, u32, u32)> {
1088 let mut heap = Vec::new();
1089 let Some((n_pool, p_pool, _)) = super::translate::target_by_name("gObjectPool") else {
1090 return heap;
1091 };
1092 for i in 0..POOL_CAPACITY {
1093 let (no, po) = (n_pool + i * OBJECT_SIZE, p_pool + i * OBJECT_SIZE);
1094 let nb = st.u32(no + OBJ_BEHAVIOR).unwrap_or(0);
1095 let pb = p32(snap, po + OBJ_BEHAVIOR);
1096 learn_path(tr, st, snap, no, nb);
1097 if tr.lookup(nb) != Some(pb) {
1098 report.objects_differing += 1;
1099 continue;
1100 }
1101 if nb == 0 {
1102 continue;
1103 }
1104 let n = |o: u32| st.u32(no + o).unwrap_or(0);
1105 let p = |o: u32| p32(snap, po + o);
1106 for o in [
1107 OBJ_ANIMATIONS,
1108 OBJ_COLLISION,
1109 OBJ_SHARED_CHILD,
1110 OBJ_RESPAWN_INFO,
1111 ] {
1112 if super::layout::looks_like_pointer(n(o)) && p(o) != 0 && tr.lookup(n(o)).is_none() {
1113 tr.pair(n(o), p(o));
1114 }
1115 }
1116 if n(OBJ_ANIMATIONS) != 0 && p(OBJ_ANIMATIONS) != 0 {
1117 pair_anim_table(tr, snap, n(OBJ_ANIMATIONS), p(OBJ_ANIMATIONS));
1118 }
1119 if st.u16(no + OBJ_ANIM_ID) == Some(p16(snap, po + OBJ_ANIM_ID))
1120 && tr.lookup(n(OBJ_CUR_ANIM)).is_none()
1121 {
1122 tr.pair(n(OBJ_CUR_ANIM), p(OBJ_CUR_ANIM));
1123 }
1124 if let Some((size, _)) = named("SpawnInfo")
1125 && tr.lookup(n(OBJ_SPAWN_INFO)).is_none()
1126 {
1127 tr.region(n(OBJ_SPAWN_INFO), size, p(OBJ_SPAWN_INFO));
1128 }
1129 let name = bhv_name(tr, nb);
1130 for &(bhv, slot, count) in CHAIN_SEGMENTS {
1135 let o = 0x88 + 4 * slot;
1136 if name != Some(bhv) || !super::layout::looks_like_pointer(n(o)) {
1137 continue;
1138 }
1139 let len = count * CHAIN_SEGMENT_SIZE;
1140 let at = match pool {
1141 Some((ns, nl, ps)) if n(o) >= ns && n(o) - ns + len <= nl => ps + (n(o) - ns),
1142 _ if p(o) != 0 => {
1143 tr.region(n(o), len, p(o));
1144 p(o)
1145 }
1146 _ => continue,
1147 };
1148 for k in 0..count {
1149 heap.push((
1150 n(o) + k * CHAIN_SEGMENT_SIZE,
1151 at + k * CHAIN_SEGMENT_SIZE,
1152 CHAIN_SEGMENT_SIZE,
1153 ));
1154 }
1155 }
1156 }
1157 heap
1158}
1159
1160fn learn_path(tr: &mut Translator, st: &MupenState, snap: &[u8], no: u32, nb: u32) {
1164 let start = st.u32(no + 0x88 + 4 * WAYPOINT_START_SLOT).unwrap_or(0);
1165 if !super::layout::looks_like_pointer(start)
1166 || !bhv_name(tr, nb).is_some_and(|b| super::tables::PATH_BEHAVIORS.contains(&b))
1167 {
1168 return;
1169 }
1170 let mut want = Vec::new();
1171 loop {
1172 let Some(w) = st.bytes(start + want.len() as u32, 8) else {
1173 return;
1174 };
1175 if w[0] == 0xFF && w[1] == 0xFF {
1177 want.extend_from_slice(&[0xFF, 0xFF]);
1178 break;
1179 }
1180 for k in 0..4 {
1181 want.extend_from_slice(&[w[2 * k + 1], w[2 * k]]);
1182 }
1183 if want.len() > 0x1000 {
1184 return;
1185 }
1186 }
1187 let at = tr
1190 .lookup(start)
1191 .filter(|&p| snap.get(p as usize..p as usize + want.len()) == Some(&want[..]));
1192 if let Some(p) = at.or_else(|| find_first(snap, &want)) {
1193 tr.region(start, want.len() as u32, p);
1194 }
1195}
1196
1197fn find_first(mem: &[u8], want: &[u8]) -> Option<u32> {
1200 let mut at = 0;
1201 while at + want.len() <= mem.len() {
1202 if mem[at] == want[0] && mem[at + 1] == want[1] && mem[at..at + want.len()] == *want {
1203 return Some(at as u32);
1204 }
1205 at += 2;
1206 }
1207 None
1208}
1209
1210const WAYPOINT_START_SLOT: u32 = 0x1D;
1212
1213const CHAIN_SEGMENTS: &[(&str, u32, u32)] =
1216 &[("bhvChainChomp", 0x1B, 5), ("bhvWigglerHead", 0x1C, 4)];
1217const CHAIN_SEGMENT_SIZE: u32 = 0x14;
1218
1219fn bhv_name(tr: &Translator, bhv: u32) -> Option<&'static str> {
1221 let seg = tr.virtual_to_segmented(bhv)?;
1222 TARGETS.iter().find(|t| t.0 == seg).map(|t| t.3)
1223}
1224
1225fn fix_mario_animation(st: &MupenState, mem: &mut [u8], report: &mut MupenLoadReport) {
1229 let Some(v) = var("gMarioAnimsBuf") else {
1230 return;
1231 };
1232 let rd = |m: &[u8], a: u32| p32(m, a);
1233 let (Some(n_table), Some(n_current)) = (st.u32(v.n64), st.u32(v.n64 + 4)) else {
1235 return;
1236 };
1237 let n_count = st.u32(n_table).unwrap_or(0);
1238 let n_src = st.u32(n_table + 4).unwrap_or(0);
1239 let index = (0..n_count.min(1024))
1240 .find(|&i| st.u32(n_table + 8 + 8 * i).map(|o| n_src.wrapping_add(o)) == Some(n_current));
1241 let Some(index) = index else {
1242 report
1243 .notes
1244 .push("could not tell which Mario animation the state has loaded".into());
1245 return;
1246 };
1247 let (p_table, p_current, p_buf) = (rd(mem, v.port), rd(mem, v.port + 4), rd(mem, v.port + 8));
1248 if p_table == 0 || p_buf == 0 || index >= rd(mem, p_table) {
1249 return;
1250 }
1251 let src = rd(mem, p_table + 4).wrapping_add(rd(mem, p_table + 8 + 8 * index));
1252 let size = rd(mem, p_table + 12 + 8 * index);
1253 if src == p_current {
1254 return;
1255 }
1256 let (s, d, n) = (src as usize, p_buf as usize, size as usize);
1257 if s + n > mem.len() || d + n > mem.len() || n > 0x4000 {
1258 report
1259 .notes
1260 .push("Mario's animation is out of bounds; not loaded".into());
1261 return;
1262 }
1263 mem.copy_within(s..s + n, d);
1264 for o in [0x0C, 0x10] {
1266 let off = rd(mem, p_buf + o);
1267 mem[d + o as usize..d + o as usize + 4]
1268 .copy_from_slice(&p_buf.wrapping_add(off).to_le_bytes());
1269 }
1270 mem[v.port as usize + 4..v.port as usize + 8].copy_from_slice(&src.to_le_bytes());
1271}