1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
use std::io::{BufReader, Read};
use once_cell::sync::OnceCell;
use sha::sha1;
use sha::utils::{Digest, DigestExt};
const VALID_HASH: &str = "9bef1128717f958171a4afac3ed78ee2bb4e86ce";
static SM64: once_cell::sync::OnceCell<Sm64Inner> = OnceCell::new();
#[derive(Debug)]
pub enum Error {
Io(std::io::Error),
InvalidMarioPosition,
InvalidRom(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Io(err) => write!(f, "{}", err),
Error::InvalidMarioPosition => write!(
f,
"Invalid Mario position, ensure coordinates are above ground"
),
Error::InvalidRom(hash) => write!(
f,
"Invalid Super Mario 64 rom: found hash '{}', expected hash '{}'",
hash, VALID_HASH
),
}
}
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Self {
Error::Io(err)
}
}
struct Sm64Inner {
texture_data: Vec<u8>,
#[allow(dead_code)]
rom_data: Vec<u8>,
}
pub struct Sm64;
impl Sm64 {
pub fn new<R: Read>(rom: R) -> Result<Self, Error> {
let mut rom_file = BufReader::new(rom);
let mut rom_data = Vec::new();
rom_file.read_to_end(&mut rom_data)?;
let rom_hash = sha1::Sha1::default().digest(&*rom_data).to_hex();
if rom_hash != VALID_HASH {
return Err(Error::InvalidRom(rom_hash));
}
let _sm64 = SM64.get_or_init(|| {
let mut texture_data = vec![
0;
(libsm64_sys::SM64_TEXTURE_WIDTH * libsm64_sys::SM64_TEXTURE_HEIGHT)
as usize
* 4
];
unsafe {
libsm64_sys::sm64_global_init(
rom_data.as_mut_ptr(),
texture_data.as_mut_ptr(),
None,
);
}
Sm64Inner {
texture_data,
rom_data,
}
});
Ok(Self)
}
pub fn texture(&self) -> Texture {
let texture_data = &SM64
.get()
.expect("Sm64::new() must of been called")
.texture_data;
Texture {
data: texture_data.as_slice(),
width: libsm64_sys::SM64_TEXTURE_WIDTH,
height: libsm64_sys::SM64_TEXTURE_HEIGHT,
}
}
pub fn create_mario(&mut self, x: i16, y: i16, z: i16) -> Result<Mario, Error> {
let mario_id = unsafe { libsm64_sys::sm64_mario_create(x, y, z) };
if mario_id < 0 {
Err(Error::InvalidMarioPosition)
} else {
Ok(Mario::new(mario_id))
}
}
pub fn create_dynamic_surface(
&mut self,
geometry: &[LevelTriangle],
transform: SurfaceTransform,
) -> DynamicSurface {
let id = unsafe {
let surface_object = libsm64_sys::SM64SurfaceObject {
transform: transform.into(),
surfaceCount: geometry.len() as u32,
surfaces: geometry.as_ptr() as *mut _,
};
libsm64_sys::sm64_surface_object_create(&surface_object as *const _)
};
DynamicSurface::new(id)
}
pub fn load_level_geometry(&mut self, geometry: &[LevelTriangle]) {
unsafe {
libsm64_sys::sm64_static_surfaces_load(
geometry.as_ptr() as *const _,
geometry.len() as u32,
)
}
}
}
pub struct Mario {
id: i32,
geometry: MarioGeometry,
}
impl Mario {
fn new(id: i32) -> Self {
let geometry = MarioGeometry::new();
Self { id, geometry }
}
pub fn tick(&mut self, input: MarioInput) -> MarioState {
let input = input.into();
let mut state = libsm64_sys::SM64MarioState {
position: [0.0, 0.0, 0.0],
velocity: [0.0, 0.0, 0.0],
faceAngle: 0.0,
health: 0,
};
let tris = unsafe {
let mut geometry: libsm64_sys::SM64MarioGeometryBuffers = (&mut self.geometry).into();
libsm64_sys::sm64_mario_tick(
self.id,
&input as *const _,
&mut state as *mut _,
&mut geometry as *mut _,
);
geometry.numTrianglesUsed
};
self.geometry.num_triangles = tris as usize;
state.into()
}
pub fn geometry(&self) -> &MarioGeometry {
&self.geometry
}
}
impl Drop for Mario {
fn drop(&mut self) {
unsafe { libsm64_sys::sm64_mario_delete(self.id) }
}
}
pub struct DynamicSurface {
id: u32,
}
impl DynamicSurface {
fn new(id: u32) -> Self {
Self { id }
}
pub fn transform(&mut self, transform: SurfaceTransform) {
unsafe {
let transform = transform.into();
libsm64_sys::sm64_surface_object_move(self.id, &transform as *const _)
}
}
}
impl Drop for DynamicSurface {
fn drop(&mut self) {
unsafe { libsm64_sys::sm64_surface_object_delete(self.id) }
}
}
#[derive(Copy, Clone, Debug)]
pub struct SurfaceTransform {
pub position: Point3<f32>,
pub euler_rotation: Point3<f32>,
}
impl From<SurfaceTransform> for libsm64_sys::SM64ObjectTransform {
fn from(transform: SurfaceTransform) -> Self {
Self {
position: [
transform.position.x,
transform.position.y,
transform.position.z,
],
eulerRotation: [
transform.euler_rotation.x,
transform.euler_rotation.y,
transform.euler_rotation.z,
],
}
}
}
pub struct Texture {
pub data: &'static [u8],
pub width: u32,
pub height: u32,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Point3<T>
where
T: Copy,
{
pub x: T,
pub y: T,
pub z: T,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Point2<T>
where
T: Copy,
{
pub x: T,
pub y: T,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct Color {
pub r: f32,
pub g: f32,
pub b: f32,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct LevelTriangle {
pub kind: Surface,
pub force: i16,
pub terrain: Terrain,
pub vertices: (Point3<i16>, Point3<i16>, Point3<i16>),
}
#[derive(Copy, Clone, Debug, Default)]
pub struct MarioInput {
pub cam_look_x: f32,
pub cam_look_z: f32,
pub stick_x: f32,
pub stick_y: f32,
pub button_a: bool,
pub button_b: bool,
pub button_z: bool,
}
impl From<MarioInput> for libsm64_sys::SM64MarioInputs {
fn from(input: MarioInput) -> Self {
libsm64_sys::SM64MarioInputs {
camLookX: input.cam_look_x,
camLookZ: input.cam_look_z,
stickX: input.stick_x,
stickY: input.stick_y,
buttonA: input.button_a as u8,
buttonB: input.button_b as u8,
buttonZ: input.button_z as u8,
}
}
}
#[derive(Debug, Default, Copy, Clone)]
pub struct MarioState {
pub position: Point3<f32>,
pub velocity: Point3<f32>,
pub face_angle: f32,
pub health: i16,
}
impl From<libsm64_sys::SM64MarioState> for MarioState {
fn from(state: libsm64_sys::SM64MarioState) -> Self {
let position = Point3 {
x: state.position[0],
y: state.position[1],
z: state.position[2],
};
let velocity = Point3 {
x: state.velocity[0],
y: state.velocity[1],
z: state.velocity[2],
};
MarioState {
position,
velocity,
face_angle: state.faceAngle,
health: state.health,
}
}
}
pub struct MarioGeometry {
position: Vec<Point3<f32>>,
normal: Vec<Point3<f32>>,
color: Vec<Color>,
uv: Vec<Point2<f32>>,
num_triangles: usize,
}
impl MarioGeometry {
fn new() -> Self {
Self {
position: vec![Point3::default(); libsm64_sys::SM64_GEO_MAX_TRIANGLES as usize * 3],
normal: vec![Point3::default(); libsm64_sys::SM64_GEO_MAX_TRIANGLES as usize * 3],
color: vec![Color::default(); libsm64_sys::SM64_GEO_MAX_TRIANGLES as usize * 3],
uv: vec![Point2::default(); libsm64_sys::SM64_GEO_MAX_TRIANGLES as usize * 3],
num_triangles: 0,
}
}
pub fn vertcies(&self) -> impl Iterator<Item = MarioVertex> + '_ {
let positions = self.position.iter().copied();
let normals = self.normal.iter().copied();
let color = self.color.iter().copied();
let uv = self.uv.iter().copied();
positions
.zip(normals)
.zip(color)
.zip(uv)
.take(self.num_triangles * 3)
.map(|(((position, normal), color), uv)| MarioVertex {
position,
normal,
color,
uv,
})
}
pub fn triangles(&self) -> impl Iterator<Item = (MarioVertex, MarioVertex, MarioVertex)> + '_ {
let positions = self.position.chunks_exact(3);
let normals = self.normal.chunks_exact(3);
let color = self.color.chunks_exact(3);
let uv = self.uv.chunks_exact(3);
positions
.zip(normals)
.zip(color)
.zip(uv)
.take(self.num_triangles)
.map(|(((positions, normals), colors), uvs)| {
let a = MarioVertex {
position: positions[0],
normal: normals[0],
color: colors[0],
uv: uvs[0],
};
let b = MarioVertex {
position: positions[1],
normal: normals[1],
color: colors[1],
uv: uvs[1],
};
let c = MarioVertex {
position: positions[2],
normal: normals[2],
color: colors[2],
uv: uvs[2],
};
(a, b, c)
})
}
pub fn positions(&self) -> &[Point3<f32>] {
&self.position[0..self.num_triangles * 3]
}
pub fn normals(&self) -> &[Point3<f32>] {
&self.normal[0..self.num_triangles * 3]
}
pub fn colors(&self) -> &[Color] {
&self.color[0..self.num_triangles * 3]
}
pub fn uvs(&self) -> &[Point2<f32>] {
&self.uv[0..self.num_triangles * 3]
}
}
impl<'a> From<&'a mut MarioGeometry> for libsm64_sys::SM64MarioGeometryBuffers {
fn from(geo: &'a mut MarioGeometry) -> libsm64_sys::SM64MarioGeometryBuffers {
libsm64_sys::SM64MarioGeometryBuffers {
position: geo.position.as_mut_ptr() as *mut _,
normal: geo.normal.as_mut_ptr() as *mut _,
color: geo.color.as_mut_ptr() as *mut _,
uv: geo.uv.as_mut_ptr() as *mut _,
numTrianglesUsed: geo.position.len() as u16 / 3,
}
}
}
#[derive(Debug, Copy, Clone)]
pub struct MarioVertex {
pub position: Point3<f32>,
pub normal: Point3<f32>,
pub color: Color,
pub uv: Point2<f32>,
}
#[repr(u16)]
#[derive(Copy, Clone, Debug)]
pub enum Terrain {
Grass = 0x0000,
Stone = 0x0001,
Snow = 0x0002,
Sand = 0x0003,
Spooky = 0x0004,
Water = 0x0005,
Slide = 0x0006,
Mask = 0x0007,
}
#[repr(u16)]
#[derive(Copy, Clone, Debug)]
pub enum Surface {
Default = 0x0000,
Burning = 0x0001,
_0004 = 0x0004,
Hangable = 0x0005,
Slow = 0x0009,
DeathPlane = 0x000A,
CloseCamera = 0x000B,
Water = 0x000D,
FlowingWater = 0x000E,
Intangible = 0x0012,
VerySlippery = 0x0013,
Slippery = 0x0014,
NotSlippery = 0x0015,
TtmVines = 0x0016,
MgrMusic = 0x001A,
InstantWarp1b = 0x001B,
InstantWarp1c = 0x001C,
InstantWarp1d = 0x001D,
InstantWarp1e = 0x001E,
ShallowQuicksand = 0x0021,
DeepQuicksand = 0x0022,
InstantQuicksand = 0x0023,
DeepMovingQuicksand = 0x0024,
ShallowMovingQuicksand = 0x0025,
Quicksand = 0x0026,
MovingQuicksand = 0x0027,
WallMisc = 0x0028,
NoiseDefault = 0x0029,
NoiseSlippery = 0x002A,
HorizontalWind = 0x002C,
InstantMovingQuicksand = 0x002D,
Ice = 0x002E,
LookUpWarp = 0x002F,
Hard = 0x0030,
Warp = 0x0032,
TimerStart = 0x0033,
TimerEnd = 0x0034,
HardSlippery = 0x0035,
HardVerySlippery = 0x0036,
HardNotSlippery = 0x0037,
VerticalWind = 0x0038,
BossFightCamera = 0x0065,
CameraFreeRoam = 0x0066,
Thi3Wallkick = 0x0068,
CameraPlatform = 0x0069,
CameraMiddle = 0x006E,
CameraRotateRight = 0x006F,
CameraRotateLeft = 0x0070,
CameraBoundary = 0x0072,
NoiseVerySlippery73 = 0x0073,
NoiseVerySlippery74 = 0x0074,
NoiseVerySlippery = 0x0075,
NoCamCollision = 0x0076,
NoCamCollision77 = 0x0077,
NoCamColVerySlippery = 0x0078,
NoCamColSlippery = 0x0079,
Switch = 0x007A,
VanishCapWalls = 0x007B,
PaintingWobbleA6 = 0x00A6,
PaintingWobbleA7 = 0x00A7,
PaintingWobbleA8 = 0x00A8,
PaintingWobbleA9 = 0x00A9,
PaintingWobbleAA = 0x00AA,
PaintingWobbleAB = 0x00AB,
PaintingWobbleAC = 0x00AC,
PaintingWobbleAD = 0x00AD,
PaintingWobbleAE = 0x00AE,
PaintingWobbleAF = 0x00AF,
PaintingWobbleB0 = 0x00B0,
PaintingWobbleB1 = 0x00B1,
PaintingWobbleB2 = 0x00B2,
PaintingWobbleB3 = 0x00B3,
PaintingWobbleB4 = 0x00B4,
PaintingWobbleB5 = 0x00B5,
PaintingWobbleB6 = 0x00B6,
PaintingWobbleB7 = 0x00B7,
PaintingWobbleB8 = 0x00B8,
PaintingWobbleB9 = 0x00B9,
PaintingWobbleBA = 0x00BA,
PaintingWobbleBB = 0x00BB,
PaintingWobbleBC = 0x00BC,
PaintingWobbleBD = 0x00BD,
PaintingWobbleBE = 0x00BE,
PaintingWobbleBF = 0x00BF,
PaintingWobbleC0 = 0x00C0,
PaintingWobbleC1 = 0x00C1,
PaintingWobbleC2 = 0x00C2,
PaintingWobbleC3 = 0x00C3,
PaintingWobbleC4 = 0x00C4,
PaintingWobbleC5 = 0x00C5,
PaintingWobbleC6 = 0x00C6,
PaintingWobbleC7 = 0x00C7,
PaintingWobbleC8 = 0x00C8,
PaintingWobbleC9 = 0x00C9,
PaintingWobbleCA = 0x00CA,
PaintingWobbleCB = 0x00CB,
PaintingWobbleCC = 0x00CC,
PaintingWobbleCD = 0x00CD,
PaintingWobbleCE = 0x00CE,
PaintingWobbleCF = 0x00CF,
PaintingWobbleD0 = 0x00D0,
PaintingWobbleD1 = 0x00D1,
PaintingWobbleD2 = 0x00D2,
PaintingWarpD3 = 0x00D3,
PaintingWarpD4 = 0x00D4,
PaintingWarpD5 = 0x00D5,
PaintingWarpD6 = 0x00D6,
PaintingWarpD7 = 0x00D7,
PaintingWarpD8 = 0x00D8,
PaintingWarpD9 = 0x00D9,
PaintingWarpDA = 0x00DA,
PaintingWarpDB = 0x00DB,
PaintingWarpDC = 0x00DC,
PaintingWarpDD = 0x00DD,
PaintingWarpDE = 0x00DE,
PaintingWarpDF = 0x00DF,
PaintingWarpE0 = 0x00E0,
PaintingWarpE1 = 0x00E1,
PaintingWarpE2 = 0x00E2,
PaintingWarpE3 = 0x00E3,
PaintingWarpE4 = 0x00E4,
PaintingWarpE5 = 0x00E5,
PaintingWarpE6 = 0x00E6,
PaintingWarpE7 = 0x00E7,
PaintingWarpE8 = 0x00E8,
PaintingWarpE9 = 0x00E9,
PaintingWarpEA = 0x00EA,
PaintingWarpEB = 0x00EB,
PaintingWarpEC = 0x00EC,
PaintingWarpED = 0x00ED,
PaintingWarpEE = 0x00EE,
PaintingWarpEF = 0x00EF,
PaintingWarpF0 = 0x00F0,
PaintingWarpF1 = 0x00F1,
PaintingWarpF2 = 0x00F2,
PaintingWarpF3 = 0x00F3,
TtcPainting1 = 0x00F4,
TtcPainting2 = 0x00F5,
TtcPainting3 = 0x00F6,
PaintingWarpF7 = 0x00F7,
PaintingWarpF8 = 0x00F8,
PaintingWarpF9 = 0x00F9,
PaintingWarpFA = 0x00FA,
PaintingWarpFB = 0x00FB,
PaintingWarpFC = 0x00FC,
WobblingWarp = 0x00FD,
Trapdoor = 0x00FF,
}
#[test]
fn basic_loading() {
let rom = std::env::var("SM64_ROM_PATH")
.expect("Path to SM64 rom must be proivided in 'SM64_ROM_PATH' env var");
let rom = std::fs::File::open(rom).unwrap();
let mut sm64 = Sm64::new(rom).unwrap();
let mario = sm64.create_mario(1, 2, 3);
match mario {
Err(Error::InvalidMarioPosition) => (),
_ => panic!("Expected InvalidMarioPosition error"),
}
}
#[test]
fn correct_repr() {
assert_eq!(
std::mem::size_of::<LevelTriangle>(),
std::mem::size_of::<libsm64_sys::SM64Surface>()
);
let tri = LevelTriangle {
kind: Surface::Default,
force: 333,
terrain: Terrain::Grass,
vertices: (
Point3 { x: 1, y: 2, z: 3 },
Point3 { x: 4, y: 5, z: 6 },
Point3 { x: 7, y: 8, z: 9 },
),
};
let c_tri = libsm64_sys::SM64Surface {
type_: 0,
force: 333,
terrain: 0,
vertices: [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
};
let my_c_tri = unsafe { std::mem::transmute::<_, libsm64_sys::SM64Surface>(tri) };
assert_eq!(c_tri.type_, my_c_tri.type_);
assert_eq!(c_tri.force, my_c_tri.force);
assert_eq!(c_tri.terrain, my_c_tri.terrain);
assert_eq!(c_tri.vertices, my_c_tri.vertices);
}