Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

lua scripting!

Laylec3f60d2e5bfa
diff --git a/.gitignore b/.gitignore
index 469f79f..5aeab31 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,4 +2,8 @@ target/
rsrc/*.dol
rsrc/*.bin
.idea/
-.vscode/
\ No newline at end of file
+.vscode/
+perf.*
+profile.json.gz
+out*.txt
+*-dump/
\ No newline at end of file
diff --git a/Cargo.lock b/Cargo.lock
index 4a26499..701deaa 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -260,6 +260,16 @@ dependencies = [
"objc2 0.5.2",
]
+[[package]]
+name = "bstr"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab"
+dependencies = [
+ "memchr",
+ "serde",
+]
+
[[package]]
name = "bumpalo"
version = "3.20.2"
@@ -641,6 +651,7 @@ dependencies = [
"gekko",
"image 0.1.0",
"pollster",
+ "scripting",
"wgpu",
"winit",
]
@@ -792,6 +803,12 @@ dependencies = [
"emath",
]
+[[package]]
+name = "either"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
+
[[package]]
name = "emath"
version = "0.33.3"
@@ -1554,6 +1571,32 @@ dependencies = [
"simd-adler32",
]
+[[package]]
+name = "mlua"
+version = "0.10.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
+dependencies = [
+ "bstr",
+ "either",
+ "mlua-sys",
+ "num-traits",
+ "parking_lot",
+ "rustc-hash 2.1.1",
+ "rustversion",
+]
+
+[[package]]
+name = "mlua-sys"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "pkg-config",
+]
+
[[package]]
name = "moxcms"
version = "0.8.1"
@@ -2356,6 +2399,15 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "scripting"
+version = "0.1.0"
+dependencies = [
+ "gekko",
+ "mlua",
+ "tracing",
+]
+
[[package]]
name = "sctk-adwaita"
version = "0.10.1"
@@ -2721,6 +2773,7 @@ dependencies = [
"gekko",
"image 0.1.0",
"pollster",
+ "scripting",
"tracing-subscriber",
"wgpu",
"winit",
diff --git a/Cargo.toml b/Cargo.toml
index bca3626..1210b13 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -9,6 +9,7 @@ members = [
"crates/tinyapp",
"crates/backend-wgpu",
"crates/debugger",
+ "crates/scripting",
]
[patch.crates-io]
@@ -24,6 +25,15 @@ lto = "fat"
codegen-units = 1
debug = false
opt-level = 3
+debug-assertions = false
[profile.dev]
+debug = true
opt-level = 3
+debug-assertions = false
+
+[profile.fast]
+inherits = "dev"
+debug-assertions = true
+opt-level = 3
+lto = false
\ No newline at end of file
diff --git a/crates/debugger/Cargo.toml b/crates/debugger/Cargo.toml
index beac018..1c21791 100644
--- a/crates/debugger/Cargo.toml
+++ b/crates/debugger/Cargo.toml
@@ -3,8 +3,12 @@ name = "debugger"
version = "0.1.0"
edition = "2024"
+[features]
+scripting-mut-traps = ["gekko/scripting-mut-traps", "scripting/scripting-mut-traps"]
+
[dependencies]
-gekko = { path = "../gekko" }
+gekko = { path = "../gekko", features = ["scripting"] }
+scripting = { path = "../scripting" }
image = { path = "../image" }
disasm = { path = "../disasm" }
backend-wgpu = { path = "../backend-wgpu" }
diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rs
index 8ebd557..17248dd 100644
--- a/crates/debugger/src/main.rs
+++ b/crates/debugger/src/main.rs
@@ -88,6 +88,7 @@ fn main() {
.position(|a| a == "--rom")
.map(|i| &args[i + 1])
.or_else(|| args.get(1).filter(|a| !a.starts_with("--")));
+ let script_path = args.iter().position(|a| a == "--script").map(|i| &args[i + 1]);
let mut emulator = if let Some(ipl) = ipl_path {
let ipl_data = std::fs::read(ipl).expect("failed to read IPL");
@@ -104,6 +105,11 @@ fn main() {
std::process::exit(1);
};
+ if let Some(path) = script_path {
+ let host = scripting::LuaScriptHost::from_file(path).expect("failed to load script");
+ emulator.set_script_host(Box::new(host));
+ }
+
emulator.add_primary_controller(PadStatus {
connected: true,
..PadStatus::default()
diff --git a/crates/gctool/src/iso.rs b/crates/gctool/src/iso.rs
index 144a306..51eea0d 100644
--- a/crates/gctool/src/iso.rs
+++ b/crates/gctool/src/iso.rs
@@ -1,4 +1,7 @@
-use image::{Executable, dvd::{DVD_APPLOADER_OFFSET, FstNode}};
+use image::{
+ Executable,
+ dvd::{DVD_APPLOADER_OFFSET, FstNode},
+};
use owo_colors::OwoColorize;
use termtree::Tree;
@@ -110,4 +113,4 @@ fn extract_main_dol(dvd: &image::dvd::Dvd, path: &std::path::Path) {
let dol_offset = dvd.header.offset_main_executable.get() as usize;
let main_dol = image::Dol::parse(dvd.data()[dol_offset..].to_vec());
std::fs::write(path.join("main.dol"), &main_dol.data()[..main_dol.size()]).unwrap();
-}
\ No newline at end of file
+}
diff --git a/crates/gekko/Cargo.toml b/crates/gekko/Cargo.toml
index 2ebadb2..510bc09 100644
--- a/crates/gekko/Cargo.toml
+++ b/crates/gekko/Cargo.toml
@@ -3,10 +3,14 @@ name = "gekko"
version = "0.1.0"
edition = "2024"
+[features]
+scripting = []
+scripting-mut-traps = ["scripting"]
+
[build-dependencies]
chipi = "0.5.3"
[dependencies]
chapa = { git = "https://github.com/ioncodes/chapa.git" }
tracing = { version = "0.1.44", features = ["release_max_level_off"] }
-image = { path = "../image" }
\ No newline at end of file
+image = { path = "../image" }
diff --git a/crates/gekko/src/exi/macronix.rs b/crates/gekko/src/exi/macronix.rs
index 8fbddbe..5b216f9 100644
--- a/crates/gekko/src/exi/macronix.rs
+++ b/crates/gekko/src/exi/macronix.rs
@@ -192,25 +192,26 @@ pub struct Sram {
impl Sram {
/// Dumped from NTSC IPL
+ #[rustfmt::skip]
pub fn ntsc_default() -> Self {
Self {
data: [
- 0x01, 0x04, 0xFE, 0xFB,
- 0x00, 0x14, 0xFF, 0xE8,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x14,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00,
+ 0x01, 0x04, 0xFE, 0xFB,
+ 0x00, 0x14, 0xFF, 0xE8,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x14,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00,
0x01, 0x04, 0xFE, 0xFB, // TODO: start and end is cooked? isnt it supposed to be 64 bytes?
],
}
diff --git a/crates/gekko/src/gekko.rs b/crates/gekko/src/gekko.rs
index eb10bcd..c515f36 100644
--- a/crates/gekko/src/gekko.rs
+++ b/crates/gekko/src/gekko.rs
@@ -1,3 +1,5 @@
+#[cfg(feature = "scripting")]
+use crate::scripting::{HookFlags, ScriptHookFilters, ScriptHookState, ScriptHost};
use crate::{
cpu::{self, Cpu, IPL_RESET_VECTOR, semantics::Instruction},
exi::{Exi, macronix::ExiMacronix},
@@ -36,9 +38,37 @@ pub struct Gekko {
pub ai: Ai,
pub mi: Mi,
idle: IdleDetector,
+
+ #[cfg(feature = "scripting")]
+ pub script_host: Option<Box<dyn ScriptHost>>,
+ #[cfg(feature = "scripting")]
+ pub script_hook_flags: HookFlags,
+ #[cfg(feature = "scripting")]
+ pub script_hook_filters: ScriptHookFilters,
}
impl Gekko {
+ #[cfg(feature = "scripting")]
+ #[inline(always)]
+ pub(crate) fn apply_script_hook_state(&mut self, state: ScriptHookState) {
+ self.script_hook_flags = state.flags;
+ self.script_hook_filters = state.filters;
+ }
+
+ #[cfg(feature = "scripting")]
+ #[inline(always)]
+ pub(crate) fn sync_pending_script_hook_state(&mut self, host: &mut dyn ScriptHost) {
+ #[cfg(feature = "scripting-mut-traps")]
+ match host.take_pending_hook_state() {
+ Ok(Some(state)) => self.apply_script_hook_state(state),
+ Ok(None) => {}
+ Err(err) => tracing::error!(target: "script", error = %err, "failed to refresh script traps"),
+ }
+
+ #[cfg(not(feature = "scripting-mut-traps"))]
+ let _ = host;
+ }
+
pub fn new(entrypoint: u32, idle_skip: bool) -> Self {
Gekko {
vsync_pending: false,
@@ -57,6 +87,13 @@ impl Gekko {
ai: Ai::new(),
mi: Mi::new(),
idle: IdleDetector::new(idle_skip),
+
+ #[cfg(feature = "scripting")]
+ script_host: None,
+ #[cfg(feature = "scripting")]
+ script_hook_flags: HookFlags::empty(),
+ #[cfg(feature = "scripting")]
+ script_hook_filters: ScriptHookFilters::default(),
}
}
@@ -153,6 +190,19 @@ impl Gekko {
// self.cpu.pc += 4;
// }
+ // CPU pre-hook
+ #[cfg(feature = "scripting")]
+ if self.script_hook_flags.contains(HookFlags::CPU_PRE) {
+ let pc = self.cpu.pc;
+ if self.script_hook_filters.cpu_pre.matches(pc) {
+ if let Some(mut host) = self.script_host.take() {
+ host.on_cpu_pre(self);
+ self.sync_pending_script_hook_state(host.as_mut());
+ self.script_host = Some(host);
+ }
+ }
+ }
+
// Fetch and execute next instruction
self.cpu.cia = self.cpu.pc;
self.cpu.nia = self.cpu.cia.wrapping_add(4);
@@ -160,6 +210,19 @@ impl Gekko {
cpu::lut::dispatch(self, instr);
self.scheduler.cycles += 1;
+ // CPU post-hook
+ #[cfg(feature = "scripting")]
+ if self.script_hook_flags.contains(HookFlags::CPU_POST) {
+ let pc = self.cpu.cia;
+ if self.script_hook_filters.cpu_post.matches(pc) {
+ if let Some(mut host) = self.script_host.take() {
+ host.on_cpu_post(self);
+ self.sync_pending_script_hook_state(host.as_mut());
+ self.script_host = Some(host);
+ }
+ }
+ }
+
match self.idle.check(self.cpu.cia, self.cpu.nia) {
IdleCheck::Skip => {
if let Some(deadline) = self.scheduler.next_event_deadline() {
@@ -202,6 +265,32 @@ impl Gekko {
crate::idle::validate_polling_loop(&buf[..count.min(buf.len())], &self.cpu.gprs)
}
+ #[cfg(feature = "scripting")]
+ pub fn set_script_host(&mut self, host: Box<dyn ScriptHost>) {
+ self.apply_script_hook_state(host.hook_state());
+ self.script_host = Some(host);
+ }
+
+ #[cfg(all(feature = "scripting", feature = "scripting-mut-traps"))]
+ pub fn refresh_script_traps(&mut self) -> Result<(), String> {
+ let Some(mut host) = self.script_host.take() else {
+ return Ok(());
+ };
+
+ let refresh_result = host.force_refresh_traps();
+ match refresh_result {
+ Ok(state) => {
+ self.apply_script_hook_state(state);
+ self.script_host = Some(host);
+ Ok(())
+ }
+ Err(err) => {
+ self.script_host = Some(host);
+ Err(err)
+ }
+ }
+ }
+
pub fn frame_size(&self) -> (usize, usize) {
let fmt = self.vi.dcr.video_format();
(fmt.columns(), fmt.lines())
diff --git a/crates/gekko/src/lib.rs b/crates/gekko/src/lib.rs
index 4f82402..a5d3dd9 100644
--- a/crates/gekko/src/lib.rs
+++ b/crates/gekko/src/lib.rs
@@ -5,3 +5,6 @@ pub mod gekko;
pub mod idle;
pub mod mmio;
pub mod scheduler;
+
+#[cfg(feature = "scripting")]
+pub mod scripting;
diff --git a/crates/gekko/src/mmio/bus.rs b/crates/gekko/src/mmio/bus.rs
index c4fc868..48e2467 100644
--- a/crates/gekko/src/mmio/bus.rs
+++ b/crates/gekko/src/mmio/bus.rs
@@ -1,3 +1,5 @@
+#[cfg(feature = "scripting")]
+use crate::scripting::HookFlags;
use crate::{
gekko::Gekko,
mmio::{
@@ -28,6 +30,7 @@ enum BusTarget {
}
#[rustfmt::skip]
+#[inline(always)]
fn route(phys: u32) -> (BusTarget, u32) {
match phys {
RAM_BASE..=RAM_END => (BusTarget::Ram, phys),
@@ -47,356 +50,389 @@ fn route(phys: u32) -> (BusTarget, u32) {
}
}
-impl Gekko {
- #[rustfmt::skip]
- pub fn read_u8(&mut self, addr: u32) -> u8 {
- let (target, offset) = route(Mmio::virt_to_phys(addr));
- match target {
- BusTarget::Ram => self.mmio.ram_read_u8(offset),
- BusTarget::Cp => self.cp.mmio_read_u8(offset),
- BusTarget::Vi => {
- if offset == 0x2E {
- return (self.vi.dph_value(self.scheduler.cycles) >> 8) as u8;
- }
- if offset == 0x2F {
- return self.vi.dph_value(self.scheduler.cycles) as u8;
- }
- self.vi.mmio_read_u8(offset)
- }
- BusTarget::Pe => self.pe.mmio_read_u8(offset),
- BusTarget::Pi => self.pi.mmio_read_u8(offset),
- BusTarget::Mi => self.mi.mmio_read_u8(offset),
- BusTarget::Dsp => self.dsp.mmio_read_u8(offset),
- BusTarget::Di => self.di.mmio_read_u8(offset),
- BusTarget::Si => self.si.mmio_read_u8(offset),
- BusTarget::Exi => self.exi.mmio_read_u8(offset),
- BusTarget::Ai => {
- if offset == 0x08 {
- return self.ai.sample_count(self.scheduler.cycles) as u8;
- }
- self.ai.mmio_read_u8(offset)
- }
- BusTarget::Gx => {
- tracing::error!(addr = format!("{:08X}", addr), "Invalid GX FIFO read");
- 0
+macro_rules! bus_read_hooks {
+ ($self:ident, $addr:ident, $phys:ident, $size:literal, $body:expr) => {{
+ #[cfg(feature = "scripting")]
+ if $self.script_hook_flags.contains(HookFlags::BUS_READ_PRE) {
+ if $self.script_hook_filters.bus_read_pre.matches($addr, $phys) {
+ if let Some(mut host) = $self.script_host.take() {
+ if let Some(val) = host.on_bus_read_pre($self, $addr, $phys, $size) {
+ $self.sync_pending_script_hook_state(host.as_mut());
+ $self.script_host = Some(host);
+ return val as _;
+ }
+ $self.sync_pending_script_hook_state(host.as_mut());
+ $self.script_host = Some(host);
+ }
}
- BusTarget::Ipl => self.mmio.phys_read_u8(offset),
- BusTarget::Fallback => self.mmio.phys_read_u8(offset),
}
- }
- #[rustfmt::skip]
- pub fn read_u16(&mut self, addr: u32) -> u16 {
- let (target, offset) = route(Mmio::virt_to_phys(addr));
- match target {
- BusTarget::Ram => self.mmio.ram_read_u16(offset),
- BusTarget::Cp => self.cp.mmio_read_u16(offset),
- BusTarget::Vi => {
- if offset == 0x2E {
- return self.vi.dph_value(self.scheduler.cycles);
- }
- self.vi.mmio_read_u16(offset)
- }
- BusTarget::Pe => self.pe.mmio_read_u16(offset),
- BusTarget::Pi => self.pi.mmio_read_u16(offset),
- BusTarget::Mi => self.mi.mmio_read_u16(offset),
- BusTarget::Dsp => self.dsp.mmio_read_u16(offset),
- BusTarget::Di => self.di.mmio_read_u16(offset),
- BusTarget::Si => self.si.mmio_read_u16(offset),
- BusTarget::Exi => self.exi.mmio_read_u16(offset),
- BusTarget::Ai => {
- if offset == 0x08 || offset == 0x0A {
- return self.ai.sample_count(self.scheduler.cycles) as u16;
- }
- self.ai.mmio_read_u16(offset)
- }
- BusTarget::Gx => {
- tracing::error!(addr = format!("{:08X}", addr), "Invalid GX FIFO read");
- 0
- }
- BusTarget::Ipl => self.mmio.phys_read_u16(offset),
- BusTarget::Fallback => self.mmio.phys_read_u16(offset),
- }
- }
+ let result = $body;
- #[rustfmt::skip]
- pub fn read_u32(&mut self, addr: u32) -> u32 {
- let (target, offset) = route(Mmio::virt_to_phys(addr));
- match target {
- BusTarget::Ram => self.mmio.ram_read_u32(offset),
- BusTarget::Cp => self.cp.mmio_read_u32(offset),
- BusTarget::Vi => {
- if offset == 0x2C {
- let dpv = self.vi.mmio_read_u16(0x2C) as u32;
- let dph = self.vi.dph_value(self.scheduler.cycles) as u32;
- return (dpv << 16) | dph;
- }
- self.vi.mmio_read_u32(offset)
- }
- BusTarget::Pe => self.pe.mmio_read_u32(offset),
- BusTarget::Pi => self.pi.mmio_read_u32(offset),
- BusTarget::Mi => self.mi.mmio_read_u32(offset),
- BusTarget::Dsp => self.dsp.mmio_read_u32(offset),
- BusTarget::Di => self.di.mmio_read_u32(offset),
- BusTarget::Si => self.si.mmio_read_u32(offset),
- BusTarget::Exi => self.exi.mmio_read_u32(offset),
- BusTarget::Ai => {
- if offset == 0x08 {
- return self.ai.sample_count(self.scheduler.cycles);
- }
- self.ai.mmio_read_u32(offset)
- }
- BusTarget::Gx => {
- tracing::error!(addr = format!("{:08X}", addr), "Invalid GX FIFO read");
- 0
+ #[cfg(feature = "scripting")]
+ if $self.script_hook_flags.contains(HookFlags::BUS_READ_POST) {
+ if $self.script_hook_filters.bus_read_post.matches($addr, $phys) {
+ if let Some(mut host) = $self.script_host.take() {
+ host.on_bus_read_post($self, $addr, $phys, $size, result as u32);
+ $self.sync_pending_script_hook_state(host.as_mut());
+ $self.script_host = Some(host);
+ }
}
- BusTarget::Ipl => self.mmio.phys_read_u32(offset),
- BusTarget::Fallback => self.mmio.phys_read_u32(offset),
}
- }
- #[rustfmt::skip]
- pub fn write_u8(&mut self, addr: u32, val: u8) {
- let (target, offset) = route(Mmio::virt_to_phys(addr));
- match target {
- BusTarget::Ram => self.mmio.ram_write_u8(offset, val),
- BusTarget::Cp => {
- self.cp.mmio_write_u8(offset, val);
- self.check_cp_interrupts();
- }
- BusTarget::Vi => {
- self.vi.mmio_write_u8(offset, val);
- self.maybe_schedule_vi_half_line();
- if (0x30..=0x3F).contains(&offset) {
- self.check_vi_interrupts();
- }
- }
- BusTarget::Pe => {
- self.pe.mmio_write_u8(offset, val);
- self.check_pe_interrupts();
- }
- BusTarget::Pi => self.pi.mmio_write_u8(offset, val),
- BusTarget::Mi => self.mi.mmio_write_u8(offset, val),
- BusTarget::Dsp => {
- self.dsp.mmio_write_u8(offset, val);
- self.dsp.process_pending_dma(&mut self.mmio);
- self.check_dsp_interrupts();
- }
- BusTarget::Di => {
- self.di.mmio_write_u8(offset, val);
- self.check_di_interrupts();
- }
- BusTarget::Si => {
- self.si.mmio_write_u8(offset, val);
- self.check_si_interrupts();
- }
- BusTarget::Exi => {
- self.exi.mmio_write_u8(offset, val);
- self.exi.process_cs_changes();
- self.exi.process_dma_transfers(&mut self.mmio);
- self.check_exi_interrupts();
- }
- BusTarget::Ai => {
- self.ai.mmio_write_u8(offset, val);
- self.check_sample_counter_reset();
- self.check_ai_interrupts();
- }
- BusTarget::Gx => {
- if self.pi.is_fifo_redirected() {
- let wptr = self.pi.fifo_wptr as usize;
- self.mmio.ram[wptr] = val;
- self.pi.fifo_wptr = self.pi.fifo_wptr.wrapping_add(1);
+ result
+ }};
+}
+
+macro_rules! bus_write_hooks {
+ ($self:ident, $addr:ident, $phys:ident, $size:literal, $val:ident, $body:expr) => {{
+ #[cfg(feature = "scripting")]
+ let $val = if $self.script_hook_flags.contains(HookFlags::BUS_WRITE_PRE) {
+ if $self.script_hook_filters.bus_write_pre.matches($addr, $phys) {
+ if let Some(mut host) = $self.script_host.take() {
+ let v = host.on_bus_write_pre($self, $addr, $phys, $size, $val as u32) as _;
+ $self.sync_pending_script_hook_state(host.as_mut());
+ $self.script_host = Some(host);
+ v
} else {
- self.gx.mmio_write_u8(&mut self.mmio, val);
- self.check_gx_pe_finish();
+ $val
}
+ } else {
+ $val
}
- BusTarget::Ipl => self.mmio.phys_write_u8(offset, val),
- BusTarget::Fallback => self.mmio.phys_write_u8(offset, val),
- }
- }
+ } else {
+ $val
+ };
- #[rustfmt::skip]
- pub fn write_u16(&mut self, addr: u32, val: u16) {
- let (target, offset) = route(Mmio::virt_to_phys(addr));
- match target {
- BusTarget::Ram => self.mmio.ram_write_u16(offset, val),
- BusTarget::Cp => {
- self.cp.mmio_write_u16(offset, val);
- self.check_cp_interrupts();
- }
- BusTarget::Vi => {
- self.vi.mmio_write_u16(offset, val);
- self.maybe_schedule_vi_half_line();
- if (0x30..=0x3F).contains(&offset) {
- self.check_vi_interrupts();
- }
- }
- BusTarget::Pe => {
- self.pe.mmio_write_u16(offset, val);
- self.check_pe_interrupts();
- }
- BusTarget::Pi => self.pi.mmio_write_u16(offset, val),
- BusTarget::Mi => self.mi.mmio_write_u16(offset, val),
- BusTarget::Dsp => {
- self.dsp.mmio_write_u16(offset, val);
- self.dsp.process_pending_dma(&mut self.mmio);
- self.check_dsp_interrupts();
- }
- BusTarget::Di => {
- self.di.mmio_write_u16(offset, val);
- self.check_di_interrupts();
- }
- BusTarget::Si => {
- self.si.mmio_write_u16(offset, val);
- self.check_si_interrupts();
- }
- BusTarget::Exi => {
- self.exi.mmio_write_u16(offset, val);
- self.exi.process_cs_changes();
- self.exi.process_dma_transfers(&mut self.mmio);
- self.check_exi_interrupts();
- }
- BusTarget::Ai => {
- self.ai.mmio_write_u16(offset, val);
- self.check_sample_counter_reset();
- self.check_ai_interrupts();
- }
- BusTarget::Gx => {
- if self.pi.is_fifo_redirected() {
- let wptr = self.pi.fifo_wptr as usize;
- let bytes = val.to_be_bytes();
- self.mmio.ram[wptr..wptr + 2].copy_from_slice(&bytes);
- self.pi.fifo_wptr = self.pi.fifo_wptr.wrapping_add(2);
- } else {
- self.gx.mmio_write_u16(&mut self.mmio, val);
- self.check_gx_pe_finish();
+ $body;
+
+ #[cfg(feature = "scripting")]
+ if $self.script_hook_flags.contains(HookFlags::BUS_WRITE_POST) {
+ if $self.script_hook_filters.bus_write_post.matches($addr, $phys) {
+ if let Some(mut host) = $self.script_host.take() {
+ host.on_bus_write_post($self, $addr, $phys, $size, $val as u32);
+ $self.sync_pending_script_hook_state(host.as_mut());
+ $self.script_host = Some(host);
}
}
- BusTarget::Ipl => self.mmio.phys_write_u16(offset, val),
- BusTarget::Fallback => self.mmio.phys_write_u16(offset, val),
}
- }
+ }};
+}
+impl Gekko {
#[rustfmt::skip]
- pub fn write_u32(&mut self, addr: u32, val: u32) {
- let (target, offset) = route(Mmio::virt_to_phys(addr));
- match target {
- BusTarget::Ram => self.mmio.ram_write_u32(offset, val),
- BusTarget::Cp => {
- self.cp.mmio_write_u32(offset, val);
- self.check_cp_interrupts();
- }
- BusTarget::Vi => {
- self.vi.mmio_write_u32(offset, val);
- self.maybe_schedule_vi_half_line();
- if (0x30..=0x3F).contains(&offset) {
- self.check_vi_interrupts();
+ #[inline(always)]
+ pub fn read_u8(&mut self, addr: u32) -> u8 {
+ let phys = Mmio::virt_to_phys(addr);
+ bus_read_hooks!(self, addr, phys, 1, {
+ let (target, offset) = route(phys);
+ match target {
+ BusTarget::Ram => self.mmio.ram_read_u8(offset),
+ BusTarget::Cp => self.cp.mmio_read_u8(offset),
+ BusTarget::Vi => {
+ if offset == 0x2E {
+ return (self.vi.dph_value(self.scheduler.cycles) >> 8) as u8;
+ }
+ if offset == 0x2F {
+ return self.vi.dph_value(self.scheduler.cycles) as u8;
+ }
+ self.vi.mmio_read_u8(offset)
}
- }
- BusTarget::Pe => {
- self.pe.mmio_write_u32(offset, val);
- self.check_pe_interrupts();
- }
- BusTarget::Pi => self.pi.mmio_write_u32(offset, val),
- BusTarget::Mi => self.mi.mmio_write_u32(offset, val),
- BusTarget::Dsp => {
- self.dsp.mmio_write_u32(offset, val);
- self.dsp.process_pending_dma(&mut self.mmio);
- self.check_dsp_interrupts();
- }
- BusTarget::Di => {
- self.di.mmio_write_u32(offset, val);
- self.check_di_interrupts();
- }
- BusTarget::Si => {
- self.si.mmio_write_u32(offset, val);
- self.check_si_interrupts();
- }
- BusTarget::Exi => {
- self.exi.mmio_write_u32(offset, val);
- self.exi.process_cs_changes();
- self.exi.process_dma_transfers(&mut self.mmio);
- self.check_exi_interrupts();
- }
- BusTarget::Ai => {
- self.ai.mmio_write_u32(offset, val);
- self.check_sample_counter_reset();
- self.check_ai_interrupts();
- }
- BusTarget::Gx => {
- if self.pi.is_fifo_redirected() {
- let wptr = self.pi.fifo_wptr as usize;
- let bytes = val.to_be_bytes();
- self.mmio.ram[wptr..wptr + 4].copy_from_slice(&bytes);
- self.pi.fifo_wptr = self.pi.fifo_wptr.wrapping_add(4);
- } else {
- self.gx.mmio_write_u32(&mut self.mmio, val);
- self.check_gx_pe_finish();
+ BusTarget::Pe => self.pe.mmio_read_u8(offset),
+ BusTarget::Pi => self.pi.mmio_read_u8(offset),
+ BusTarget::Mi => self.mi.mmio_read_u8(offset),
+ BusTarget::Dsp => self.dsp.mmio_read_u8(offset),
+ BusTarget::Di => self.di.mmio_read_u8(offset),
+ BusTarget::Si => self.si.mmio_read_u8(offset),
+ BusTarget::Exi => self.exi.mmio_read_u8(offset),
+ BusTarget::Ai => {
+ if offset == 0x08 {
+ return self.ai.sample_count(self.scheduler.cycles) as u8;
+ }
+ self.ai.mmio_read_u8(offset)
+ }
+ BusTarget::Gx => {
+ tracing::error!(addr = format!("{:08X}", addr), "Invalid GX FIFO read");
+ 0
}
+ BusTarget::Ipl => self.mmio.phys_read_u8(offset),
+ BusTarget::Fallback => self.mmio.phys_read_u8(offset),
}
- BusTarget::Ipl => self.mmio.phys_write_u32(offset, val),
- BusTarget::Fallback => self.mmio.phys_write_u32(offset, val),
- }
- }
-
- #[inline(always)]
- pub fn load_u8_data(&mut self, addr: u32) -> u8 {
- let phys = Mmio::virt_to_phys(addr);
- if phys <= RAM_END {
- self.mmio.ram_read_u8(phys)
- } else {
- self.read_u8(addr)
- }
+ })
}
+ #[rustfmt::skip]
#[inline(always)]
- pub fn load_u16_data(&mut self, addr: u32) -> u16 {
+ pub fn read_u16(&mut self, addr: u32) -> u16 {
let phys = Mmio::virt_to_phys(addr);
- if phys <= RAM_END - 1 {
- self.mmio.ram_read_u16(phys)
- } else {
- self.read_u16(addr)
- }
+ bus_read_hooks!(self, addr, phys, 2, {
+ let (target, offset) = route(phys);
+ match target {
+ BusTarget::Ram => self.mmio.ram_read_u16(offset),
+ BusTarget::Cp => self.cp.mmio_read_u16(offset),
+ BusTarget::Vi => {
+ if offset == 0x2E {
+ return self.vi.dph_value(self.scheduler.cycles);
+ }
+ self.vi.mmio_read_u16(offset)
+ }
+ BusTarget::Pe => self.pe.mmio_read_u16(offset),
+ BusTarget::Pi => self.pi.mmio_read_u16(offset),
+ BusTarget::Mi => self.mi.mmio_read_u16(offset),
+ BusTarget::Dsp => self.dsp.mmio_read_u16(offset),
+ BusTarget::Di => self.di.mmio_read_u16(offset),
+ BusTarget::Si => self.si.mmio_read_u16(offset),
+ BusTarget::Exi => self.exi.mmio_read_u16(offset),
+ BusTarget::Ai => {
+ if offset == 0x08 || offset == 0x0A {
+ return self.ai.sample_count(self.scheduler.cycles) as u16;
+ }
+ self.ai.mmio_read_u16(offset)
+ }
+ BusTarget::Gx => {
+ tracing::error!(addr = format!("{:08X}", addr), "Invalid GX FIFO read");
+ 0
+ }
+ BusTarget::Ipl => self.mmio.phys_read_u16(offset),
+ BusTarget::Fallback => self.mmio.phys_read_u16(offset),
+ }
+ })
}
+ #[rustfmt::skip]
#[inline(always)]
- pub fn load_u32_data(&mut self, addr: u32) -> u32 {
+ pub fn read_u32(&mut self, addr: u32) -> u32 {
let phys = Mmio::virt_to_phys(addr);
- if phys <= RAM_END - 3 {
- self.mmio.ram_read_u32(phys)
- } else {
- self.read_u32(addr)
- }
+ bus_read_hooks!(self, addr, phys, 4, {
+ let (target, offset) = route(phys);
+ match target {
+ BusTarget::Ram => self.mmio.ram_read_u32(offset),
+ BusTarget::Cp => self.cp.mmio_read_u32(offset),
+ BusTarget::Vi => {
+ if offset == 0x2C {
+ let dpv = self.vi.mmio_read_u16(0x2C) as u32;
+ let dph = self.vi.dph_value(self.scheduler.cycles) as u32;
+ return (dpv << 16) | dph;
+ }
+ self.vi.mmio_read_u32(offset)
+ }
+ BusTarget::Pe => self.pe.mmio_read_u32(offset),
+ BusTarget::Pi => self.pi.mmio_read_u32(offset),
+ BusTarget::Mi => self.mi.mmio_read_u32(offset),
+ BusTarget::Dsp => self.dsp.mmio_read_u32(offset),
+ BusTarget::Di => self.di.mmio_read_u32(offset),
+ BusTarget::Si => self.si.mmio_read_u32(offset),
+ BusTarget::Exi => self.exi.mmio_read_u32(offset),
+ BusTarget::Ai => {
+ if offset == 0x08 {
+ return self.ai.sample_count(self.scheduler.cycles);
+ }
+ self.ai.mmio_read_u32(offset)
+ }
+ BusTarget::Gx => {
+ tracing::error!(addr = format!("{:08X}", addr), "Invalid GX FIFO read");
+ 0
+ }
+ BusTarget::Ipl => self.mmio.phys_read_u32(offset),
+ BusTarget::Fallback => self.mmio.phys_read_u32(offset),
+ }
+ })
}
+ #[rustfmt::skip]
#[inline(always)]
- pub fn store_u8_data(&mut self, addr: u32, val: u8) {
+ pub fn write_u8(&mut self, addr: u32, val: u8) {
let phys = Mmio::virt_to_phys(addr);
- if phys <= RAM_END {
- self.mmio.ram_write_u8(phys, val);
- } else {
- self.write_u8(addr, val);
- }
+ bus_write_hooks!(self, addr, phys, 1, val, {
+ let (target, offset) = route(phys);
+ match target {
+ BusTarget::Ram => self.mmio.ram_write_u8(offset, val),
+ BusTarget::Cp => {
+ self.cp.mmio_write_u8(offset, val);
+ self.check_cp_interrupts();
+ }
+ BusTarget::Vi => {
+ self.vi.mmio_write_u8(offset, val);
+ self.maybe_schedule_vi_half_line();
+ if (0x30..=0x3F).contains(&offset) {
+ self.check_vi_interrupts();
+ }
+ }
+ BusTarget::Pe => {
+ self.pe.mmio_write_u8(offset, val);
+ self.check_pe_interrupts();
+ }
+ BusTarget::Pi => self.pi.mmio_write_u8(offset, val),
+ BusTarget::Mi => self.mi.mmio_write_u8(offset, val),
+ BusTarget::Dsp => {
+ self.dsp.mmio_write_u8(offset, val);
+ self.dsp.process_pending_dma(&mut self.mmio);
+ self.check_dsp_interrupts();
+ }
+ BusTarget::Di => {
+ self.di.mmio_write_u8(offset, val);
+ self.check_di_interrupts();
+ }
+ BusTarget::Si => {
+ self.si.mmio_write_u8(offset, val);
+ self.check_si_interrupts();
+ }
+ BusTarget::Exi => {
+ self.exi.mmio_write_u8(offset, val);
+ self.exi.process_cs_changes();
+ self.exi.process_dma_transfers(&mut self.mmio);
+ self.check_exi_interrupts();
+ }
+ BusTarget::Ai => {
+ self.ai.mmio_write_u8(offset, val);
+ self.check_sample_counter_reset();
+ self.check_ai_interrupts();
+ }
+ BusTarget::Gx => {
+ if self.pi.is_fifo_redirected() {
+ let wptr = self.pi.fifo_wptr as usize;
+ self.mmio.ram[wptr] = val;
+ self.pi.fifo_wptr = self.pi.fifo_wptr.wrapping_add(1);
+ } else {
+ self.gx.mmio_write_u8(&mut self.mmio, val);
+ self.check_gx_pe_finish();
+ }
+ }
+ BusTarget::Ipl => self.mmio.phys_write_u8(offset, val),
+ BusTarget::Fallback => self.mmio.phys_write_u8(offset, val),
+ }
+ });
}
+ #[rustfmt::skip]
#[inline(always)]
- pub fn store_u16_data(&mut self, addr: u32, val: u16) {
+ pub fn write_u16(&mut self, addr: u32, val: u16) {
let phys = Mmio::virt_to_phys(addr);
- if phys <= RAM_END - 1 {
- self.mmio.ram_write_u16(phys, val);
- } else {
- self.write_u16(addr, val);
- }
+ bus_write_hooks!(self, addr, phys, 2, val, {
+ let (target, offset) = route(phys);
+ match target {
+ BusTarget::Ram => self.mmio.ram_write_u16(offset, val),
+ BusTarget::Cp => {
+ self.cp.mmio_write_u16(offset, val);
+ self.check_cp_interrupts();
+ }
+ BusTarget::Vi => {
+ self.vi.mmio_write_u16(offset, val);
+ self.maybe_schedule_vi_half_line();
+ if (0x30..=0x3F).contains(&offset) {
+ self.check_vi_interrupts();
+ }
+ }
+ BusTarget::Pe => {
+ self.pe.mmio_write_u16(offset, val);
+ self.check_pe_interrupts();
+ }
+ BusTarget::Pi => self.pi.mmio_write_u16(offset, val),
+ BusTarget::Mi => self.mi.mmio_write_u16(offset, val),
+ BusTarget::Dsp => {
+ self.dsp.mmio_write_u16(offset, val);
+ self.dsp.process_pending_dma(&mut self.mmio);
+ self.check_dsp_interrupts();
+ }
+ BusTarget::Di => {
+ self.di.mmio_write_u16(offset, val);
+ self.check_di_interrupts();
+ }
+ BusTarget::Si => {
+ self.si.mmio_write_u16(offset, val);
+ self.check_si_interrupts();
+ }
+ BusTarget::Exi => {
+ self.exi.mmio_write_u16(offset, val);
+ self.exi.process_cs_changes();
+ self.exi.process_dma_transfers(&mut self.mmio);
+ self.check_exi_interrupts();
+ }
+ BusTarget::Ai => {
+ self.ai.mmio_write_u16(offset, val);
+ self.check_sample_counter_reset();
+ self.check_ai_interrupts();
+ }
+ BusTarget::Gx => {
+ if self.pi.is_fifo_redirected() {
+ let wptr = self.pi.fifo_wptr as usize;
+ let bytes = val.to_be_bytes();
+ self.mmio.ram[wptr..wptr + 2].copy_from_slice(&bytes);
+ self.pi.fifo_wptr = self.pi.fifo_wptr.wrapping_add(2);
+ } else {
+ self.gx.mmio_write_u16(&mut self.mmio, val);
+ self.check_gx_pe_finish();
+ }
+ }
+ BusTarget::Ipl => self.mmio.phys_write_u16(offset, val),
+ BusTarget::Fallback => self.mmio.phys_write_u16(offset, val),
+ }
+ });
}
+ #[rustfmt::skip]
#[inline(always)]
- pub fn store_u32_data(&mut self, addr: u32, val: u32) {
+ pub fn write_u32(&mut self, addr: u32, val: u32) {
let phys = Mmio::virt_to_phys(addr);
- if phys <= RAM_END - 3 {
- self.mmio.ram_write_u32(phys, val);
- } else {
- self.write_u32(addr, val);
- }
+ bus_write_hooks!(self, addr, phys, 4, val, {
+ let (target, offset) = route(phys);
+ match target {
+ BusTarget::Ram => self.mmio.ram_write_u32(offset, val),
+ BusTarget::Cp => {
+ self.cp.mmio_write_u32(offset, val);
+ self.check_cp_interrupts();
+ }
+ BusTarget::Vi => {
+ self.vi.mmio_write_u32(offset, val);
+ self.maybe_schedule_vi_half_line();
+ if (0x30..=0x3F).contains(&offset) {
+ self.check_vi_interrupts();
+ }
+ }
+ BusTarget::Pe => {
+ self.pe.mmio_write_u32(offset, val);
+ self.check_pe_interrupts();
+ }
+ BusTarget::Pi => self.pi.mmio_write_u32(offset, val),
+ BusTarget::Mi => self.mi.mmio_write_u32(offset, val),
+ BusTarget::Dsp => {
+ self.dsp.mmio_write_u32(offset, val);
+ self.dsp.process_pending_dma(&mut self.mmio);
+ self.check_dsp_interrupts();
+ }
+ BusTarget::Di => {
+ self.di.mmio_write_u32(offset, val);
+ self.check_di_interrupts();
+ }
+ BusTarget::Si => {
+ self.si.mmio_write_u32(offset, val);
+ self.check_si_interrupts();
+ }
+ BusTarget::Exi => {
+ self.exi.mmio_write_u32(offset, val);
+ self.exi.process_cs_changes();
+ self.exi.process_dma_transfers(&mut self.mmio);
+ self.check_exi_interrupts();
+ }
+ BusTarget::Ai => {
+ self.ai.mmio_write_u32(offset, val);
+ self.check_sample_counter_reset();
+ self.check_ai_interrupts();
+ }
+ BusTarget::Gx => {
+ if self.pi.is_fifo_redirected() {
+ let wptr = self.pi.fifo_wptr as usize;
+ let bytes = val.to_be_bytes();
+ self.mmio.ram[wptr..wptr + 4].copy_from_slice(&bytes);
+ self.pi.fifo_wptr = self.pi.fifo_wptr.wrapping_add(4);
+ } else {
+ self.gx.mmio_write_u32(&mut self.mmio, val);
+ self.check_gx_pe_finish();
+ }
+ }
+ BusTarget::Ipl => self.mmio.phys_write_u32(offset, val),
+ BusTarget::Fallback => self.mmio.phys_write_u32(offset, val),
+ }
+ });
}
}
diff --git a/crates/gekko/src/mmio/fp.rs b/crates/gekko/src/mmio/fp.rs
index ab21fbf..7db2079 100644
--- a/crates/gekko/src/mmio/fp.rs
+++ b/crates/gekko/src/mmio/fp.rs
@@ -12,8 +12,8 @@ impl Gekko {
return f64::from_bits(self.mmio.ram_read_u64(phys));
}
- let hi = self.load_u32_data(addr) as u64;
- let lo = self.load_u32_data(addr.wrapping_add(4)) as u64;
+ let hi = self.read_u32(addr) as u64;
+ let lo = self.read_u32(addr.wrapping_add(4)) as u64;
f64::from_bits((hi << 32) | lo)
}
@@ -27,19 +27,19 @@ impl Gekko {
return;
}
- self.store_u32_data(addr, (bits >> 32) as u32);
- self.store_u32_data(addr.wrapping_add(4), bits as u32);
+ self.write_u32(addr, (bits >> 32) as u32);
+ self.write_u32(addr.wrapping_add(4), bits as u32);
}
/// Load a 32-bit float from memory, return as f64
#[inline]
pub fn read_f32(&mut self, addr: u32) -> f64 {
- f32::from_bits(self.load_u32_data(addr)) as f64
+ f32::from_bits(self.read_u32(addr)) as f64
}
/// Store f64 as 32-bit float to memory
#[inline]
pub fn write_f32(&mut self, addr: u32, val: f64) {
- self.store_u32_data(addr, (val as f32).to_bits());
+ self.write_u32(addr, (val as f32).to_bits());
}
}
diff --git a/crates/gekko/src/scripting.rs b/crates/gekko/src/scripting.rs
new file mode 100644
index 0000000..7a75371
--- /dev/null
+++ b/crates/gekko/src/scripting.rs
@@ -0,0 +1,128 @@
+use crate::gekko::Gekko;
+
+#[derive(Clone, Copy, Default)]
+pub struct HookFlags(u16);
+
+impl HookFlags {
+ pub const CPU_PRE: Self = Self(1 << 0);
+ pub const CPU_POST: Self = Self(1 << 1);
+ pub const BUS_READ_PRE: Self = Self(1 << 2);
+ pub const BUS_READ_POST: Self = Self(1 << 3);
+ pub const BUS_WRITE_PRE: Self = Self(1 << 4);
+ pub const BUS_WRITE_POST: Self = Self(1 << 5);
+
+ #[inline(always)]
+ pub const fn empty() -> Self {
+ Self(0)
+ }
+
+ #[inline(always)]
+ pub const fn contains(&self, other: Self) -> bool {
+ self.0 & other.0 == other.0
+ }
+}
+
+impl core::ops::BitOrAssign for HookFlags {
+ #[inline(always)]
+ fn bitor_assign(&mut self, rhs: Self) {
+ self.0 |= rhs.0;
+ }
+}
+
+#[derive(Clone, Default)]
+pub enum AddressFilter {
+ #[default]
+ None,
+ Exact(u32),
+ Set(Box<[u32]>),
+}
+
+impl AddressFilter {
+ pub fn from_addresses<I>(addresses: I) -> Self
+ where
+ I: IntoIterator<Item = u32>,
+ {
+ let mut values: Vec<u32> = addresses.into_iter().collect();
+ values.sort_unstable();
+ values.dedup();
+
+ match values.len() {
+ 0 => Self::None,
+ 1 => Self::Exact(values[0]),
+ _ => Self::Set(values.into_boxed_slice()),
+ }
+ }
+
+ #[inline(always)]
+ pub fn matches(&self, address: u32) -> bool {
+ match self {
+ Self::None => false,
+ Self::Exact(value) => *value == address,
+ Self::Set(values) => values.binary_search(&address).is_ok(),
+ }
+ }
+}
+
+#[derive(Clone, Default)]
+pub struct BusAddressFilter {
+ pub virt: AddressFilter,
+ pub phys: AddressFilter,
+}
+
+impl BusAddressFilter {
+ #[inline(always)]
+ pub fn matches(&self, virt_addr: u32, phys_addr: u32) -> bool {
+ self.virt.matches(virt_addr) || self.phys.matches(phys_addr)
+ }
+}
+
+#[derive(Clone, Default)]
+pub struct ScriptHookFilters {
+ pub cpu_pre: AddressFilter,
+ pub cpu_post: AddressFilter,
+ pub bus_read_pre: BusAddressFilter,
+ pub bus_read_post: BusAddressFilter,
+ pub bus_write_pre: BusAddressFilter,
+ pub bus_write_post: BusAddressFilter,
+}
+
+#[derive(Clone, Default)]
+pub struct ScriptHookState {
+ pub flags: HookFlags,
+ pub filters: ScriptHookFilters,
+}
+
+pub trait ScriptHost {
+ /// Current cached hook state for the host.
+ fn hook_state(&self) -> ScriptHookState;
+
+ /// Forcefully rebuild trap state immediately.
+ #[cfg(feature = "scripting-mut-traps")]
+ fn force_refresh_traps(&mut self) -> Result<ScriptHookState, String> {
+ Ok(self.hook_state())
+ }
+
+ /// Apply any pending trap refresh requested by the script.
+ #[cfg(feature = "scripting-mut-traps")]
+ fn take_pending_hook_state(&mut self) -> Result<Option<ScriptHookState>, String> {
+ Ok(None)
+ }
+
+ /// Called before each CPU instruction executes.
+ fn on_cpu_pre(&mut self, emu: &mut Gekko);
+
+ /// Called after each CPU instruction executes.
+ fn on_cpu_post(&mut self, emu: &mut Gekko);
+
+ /// Called before a bus read. Return Some(val) to override the read value.
+ fn on_bus_read_pre(&mut self, emu: &mut Gekko, virt_addr: u32, phys_addr: u32, size: u8) -> Option<u32>;
+
+ /// Called after a bus read completes.
+ fn on_bus_read_post(&mut self, emu: &mut Gekko, virt_addr: u32, phys_addr: u32, size: u8, value: u32);
+
+ /// Called before a bus write. Returns the (possibly modified) value to write.
+ fn on_bus_write_pre(&mut self, emu: &mut Gekko, virt_addr: u32, phys_addr: u32, size: u8, value: u32) -> u32;
+
+ /// Called after a bus write completes.
+ fn on_bus_write_post(&mut self, emu: &mut Gekko, virt_addr: u32, phys_addr: u32, size: u8, value: u32);
+}
diff --git a/crates/scripting/Cargo.toml b/crates/scripting/Cargo.toml
new file mode 100644
index 0000000..9f206e0
--- /dev/null
+++ b/crates/scripting/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "scripting"
+version = "0.1.0"
+edition = "2024"
+
+[features]
+scripting-mut-traps = ["gekko/scripting-mut-traps"]
+
+[dependencies]
+gekko = { path = "../gekko", features = ["scripting"] }
+mlua = { version = "0.10", features = ["lua54", "send"] }
+tracing = "0.1"
diff --git a/crates/scripting/src/lib.rs b/crates/scripting/src/lib.rs
new file mode 100644
index 0000000..7c2c26a
--- /dev/null
+++ b/crates/scripting/src/lib.rs
@@ -0,0 +1,558 @@
+use std::collections::HashMap;
+#[cfg(feature = "scripting-mut-traps")]
+use std::sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+};
+
+use gekko::gekko::Gekko;
+use gekko::scripting::{AddressFilter, BusAddressFilter, HookFlags, ScriptHookFilters, ScriptHookState, ScriptHost};
+use mlua::{Function, Lua, RegistryKey, Result as LuaResult, Table, UserDataMethods, Value};
+
+pub struct LuaScriptHost {
+ lua: Lua,
+ flags: HookFlags,
+ #[cfg(feature = "scripting-mut-traps")]
+ refresh_requested: Arc<AtomicBool>,
+ cpu_pre: CpuHookDispatch,
+ cpu_post: CpuHookDispatch,
+ bus_read_pre: BusHookDispatch,
+ bus_read_post: BusHookDispatch,
+ bus_write_pre: BusHookDispatch,
+ bus_write_post: BusHookDispatch,
+}
+
+type CpuHookDispatch = HashMap<u32, LuaCallback>;
+
+struct LoadedDispatches {
+ state: ScriptHookState,
+ cpu_pre: CpuHookDispatch,
+ cpu_post: CpuHookDispatch,
+ bus_read_pre: BusHookDispatch,
+ bus_read_post: BusHookDispatch,
+ bus_write_pre: BusHookDispatch,
+ bus_write_post: BusHookDispatch,
+}
+
+#[derive(Default)]
+struct BusHookDispatch {
+ virt_traps: HashMap<u32, LuaCallback>,
+ phys_traps: HashMap<u32, LuaCallback>,
+}
+
+impl BusHookDispatch {
+ fn has_handler(&self) -> bool {
+ !self.virt_traps.is_empty() || !self.phys_traps.is_empty()
+ }
+
+ fn resolve(&self, virt_addr: u32, phys_addr: u32) -> Option<&LuaCallback> {
+ self.virt_traps
+ .get(&virt_addr)
+ .or_else(|| self.phys_traps.get(&phys_addr))
+ }
+
+ fn filter(&self) -> BusAddressFilter {
+ BusAddressFilter {
+ virt: AddressFilter::from_addresses(self.virt_traps.keys().copied()),
+ phys: AddressFilter::from_addresses(self.phys_traps.keys().copied()),
+ }
+ }
+}
+
+impl LoadedDispatches {
+ fn from_lua(lua: &Lua) -> LuaResult<Self> {
+ let globals = lua.globals();
+ let trap_root = load_optional_table(&globals, "traps", "traps")?;
+ let cpu_pre_traps = match trap_root.as_ref() {
+ Some(root) => load_optional_table(root, "cpu_pre", "traps.cpu_pre")?,
+ None => None,
+ };
+ let cpu_post_traps = match trap_root.as_ref() {
+ Some(root) => load_optional_table(root, "cpu_post", "traps.cpu_post")?,
+ None => None,
+ };
+
+ let cpu_pre = load_address_traps(lua, cpu_pre_traps.as_ref(), "traps.cpu_pre")?;
+ let cpu_post = load_address_traps(lua, cpu_post_traps.as_ref(), "traps.cpu_post")?;
+ let bus_read_pre = load_bus_dispatch(lua, trap_root.as_ref(), "bus_read_pre")?;
+ let bus_read_post = load_bus_dispatch(lua, trap_root.as_ref(), "bus_read_post")?;
+ let bus_write_pre = load_bus_dispatch(lua, trap_root.as_ref(), "bus_write_pre")?;
+ let bus_write_post = load_bus_dispatch(lua, trap_root.as_ref(), "bus_write_post")?;
+
+ let mut flags = HookFlags::empty();
+ if !cpu_pre.is_empty() {
+ flags |= HookFlags::CPU_PRE;
+ }
+ if !cpu_post.is_empty() {
+ flags |= HookFlags::CPU_POST;
+ }
+ if bus_read_pre.has_handler() {
+ flags |= HookFlags::BUS_READ_PRE;
+ }
+ if bus_read_post.has_handler() {
+ flags |= HookFlags::BUS_READ_POST;
+ }
+ if bus_write_pre.has_handler() {
+ flags |= HookFlags::BUS_WRITE_PRE;
+ }
+ if bus_write_post.has_handler() {
+ flags |= HookFlags::BUS_WRITE_POST;
+ }
+
+ Ok(Self {
+ state: ScriptHookState {
+ flags,
+ filters: ScriptHookFilters {
+ cpu_pre: AddressFilter::from_addresses(cpu_pre.keys().copied()),
+ cpu_post: AddressFilter::from_addresses(cpu_post.keys().copied()),
+ bus_read_pre: bus_read_pre.filter(),
+ bus_read_post: bus_read_post.filter(),
+ bus_write_pre: bus_write_pre.filter(),
+ bus_write_post: bus_write_post.filter(),
+ },
+ },
+ cpu_pre,
+ cpu_post,
+ bus_read_pre,
+ bus_read_post,
+ bus_write_pre,
+ bus_write_post,
+ })
+ }
+}
+
+enum LuaCallback {
+ Stored(RegistryKey),
+}
+
+impl LuaCallback {
+ fn from_function(lua: &Lua, function: Function) -> LuaResult<Self> {
+ Ok(Self::Stored(lua.create_registry_value(function)?))
+ }
+
+ fn from_value(lua: &Lua, value: Value, context: &str) -> LuaResult<Self> {
+ match value {
+ Value::Function(function) => Self::from_function(lua, function),
+ other => Err(mlua::Error::runtime(format!(
+ "{context} must map to a Lua function, got {}",
+ other.type_name()
+ ))),
+ }
+ }
+
+ fn resolve(&self, lua: &Lua) -> LuaResult<Function> {
+ match self {
+ Self::Stored(key) => lua.registry_value(key),
+ }
+ }
+}
+
+impl LuaScriptHost {
+ pub fn from_file(path: &str) -> LuaResult<Self> {
+ let source = std::fs::read_to_string(path).map_err(|e| mlua::Error::runtime(e.to_string()))?;
+ Self::from_source(path, &source)
+ }
+
+ pub fn from_source(name: &str, source: &str) -> LuaResult<Self> {
+ let lua = Lua::new();
+ #[cfg(feature = "scripting-mut-traps")]
+ let refresh_requested = Arc::new(AtomicBool::new(false));
+
+ let log_fn = lua.create_function(|_, msg: String| {
+ tracing::info!("{}", msg);
+ Ok(())
+ })?;
+ lua.globals().set("log", log_fn)?;
+
+ #[cfg(feature = "scripting-mut-traps")]
+ {
+ let refresh_requested_fn = refresh_requested.clone();
+ let refresh_fn = lua.create_function(move |_, ()| {
+ refresh_requested_fn.store(true, Ordering::Relaxed);
+ Ok(())
+ })?;
+ lua.globals().set("refresh_traps", refresh_fn)?;
+ }
+
+ lua.load(source).set_name(name).exec()?;
+
+ let mut host = LuaScriptHost {
+ lua,
+ flags: HookFlags::empty(),
+ #[cfg(feature = "scripting-mut-traps")]
+ refresh_requested,
+ cpu_pre: CpuHookDispatch::default(),
+ cpu_post: CpuHookDispatch::default(),
+ bus_read_pre: BusHookDispatch::default(),
+ bus_read_post: BusHookDispatch::default(),
+ bus_write_pre: BusHookDispatch::default(),
+ bus_write_post: BusHookDispatch::default(),
+ };
+ host.reload_dispatches()?;
+ Ok(host)
+ }
+
+ fn reload_dispatches(&mut self) -> LuaResult<ScriptHookState> {
+ let loaded = LoadedDispatches::from_lua(&self.lua)?;
+ let state = loaded.state.clone();
+ self.flags = state.flags;
+ self.cpu_pre = loaded.cpu_pre;
+ self.cpu_post = loaded.cpu_post;
+ self.bus_read_pre = loaded.bus_read_pre;
+ self.bus_read_post = loaded.bus_read_post;
+ self.bus_write_pre = loaded.bus_write_pre;
+ self.bus_write_post = loaded.bus_write_post;
+ #[cfg(feature = "scripting-mut-traps")]
+ self.refresh_requested.store(false, Ordering::Relaxed);
+ Ok(state)
+ }
+
+ fn register_emu_methods(methods: &mut impl UserDataMethods<GekkoRef>) {
+ methods.add_method("gpr", |_, this, i: u8| Ok(this.cpu.read_gpr(i)));
+ methods.add_method_mut("set_gpr", |_, this, (i, val): (u8, u32)| {
+ this.cpu.write_gpr(i, val);
+ Ok(())
+ });
+ methods.add_method("fpr", |_, this, i: u8| Ok(this.cpu.read_fpr(i)));
+ methods.add_method_mut("set_fpr", |_, this, (i, val): (u8, f64)| {
+ this.cpu.write_fpr(i, val);
+ Ok(())
+ });
+ methods.add_method("ps1", |_, this, i: u8| Ok(this.cpu.read_ps1(i)));
+ methods.add_method_mut("set_ps1", |_, this, (i, val): (u8, f64)| {
+ this.cpu.write_ps1(i, val);
+ Ok(())
+ });
+ methods.add_method("pc", |_, this, ()| Ok(this.cpu.pc));
+ methods.add_method_mut("set_pc", |_, this, val: u32| {
+ this.cpu.nia = val;
+ Ok(())
+ });
+ methods.add_method("lr", |_, this, ()| Ok(this.cpu.spr.lr));
+ methods.add_method_mut("set_lr", |_, this, val: u32| {
+ this.cpu.spr.lr = val;
+ Ok(())
+ });
+ methods.add_method("ctr", |_, this, ()| Ok(this.cpu.spr.ctr));
+ methods.add_method_mut("set_ctr", |_, this, val: u32| {
+ this.cpu.spr.ctr = val;
+ Ok(())
+ });
+ methods.add_method("cr", |_, this, ()| Ok(this.cpu.cr.raw()));
+ methods.add_method("msr", |_, this, ()| Ok(this.cpu.msr.raw()));
+ methods.add_method("xer", |_, this, ()| Ok(this.cpu.spr.xer.raw()));
+ methods.add_method("fpscr", |_, this, ()| Ok(this.cpu.fpscr));
+ methods.add_method("cycles", |_, this, ()| Ok(this.scheduler.cycles));
+
+ methods.add_method("read_u8", |_, this, addr: u32| Ok(this.mmio.virt_read_u8(addr)));
+ methods.add_method("read_u16", |_, this, addr: u32| Ok(this.mmio.virt_read_u16(addr)));
+ methods.add_method("read_u32", |_, this, addr: u32| Ok(this.mmio.virt_read_u32(addr)));
+ methods.add_method_mut("write_u8", |_, this, (addr, val): (u32, u8)| {
+ this.mmio.virt_write_u8(addr, val);
+ Ok(())
+ });
+ methods.add_method_mut("write_u16", |_, this, (addr, val): (u32, u16)| {
+ this.mmio.virt_write_u16(addr, val);
+ Ok(())
+ });
+ methods.add_method_mut("write_u32", |_, this, (addr, val): (u32, u32)| {
+ this.mmio.virt_write_u32(addr, val);
+ Ok(())
+ });
+ methods.add_method("read_phys_u8", |_, this, addr: u32| Ok(this.mmio.phys_read_u8(addr)));
+ methods.add_method("read_phys_u16", |_, this, addr: u32| Ok(this.mmio.phys_read_u16(addr)));
+ methods.add_method("read_phys_u32", |_, this, addr: u32| Ok(this.mmio.phys_read_u32(addr)));
+ methods.add_method_mut("write_phys_u8", |_, this, (addr, val): (u32, u8)| {
+ this.mmio.phys_write_u8(addr, val);
+ Ok(())
+ });
+ methods.add_method_mut("write_phys_u16", |_, this, (addr, val): (u32, u16)| {
+ this.mmio.phys_write_u16(addr, val);
+ Ok(())
+ });
+ methods.add_method_mut("write_phys_u32", |_, this, (addr, val): (u32, u32)| {
+ this.mmio.phys_write_u32(addr, val);
+ Ok(())
+ });
+ methods.add_method("virt_to_phys", |_, _this, addr: u32| {
+ Ok(gekko::mmio::Mmio::virt_to_phys(addr))
+ });
+ }
+
+ fn call_cpu_hook(&self, hook_name: &str, callback: &LuaCallback, emu: &mut Gekko) -> LuaResult<()> {
+ self.lua
+ .scope(|scope| {
+ let ud = scope.create_userdata(GekkoRef(emu as *mut Gekko))?;
+ let func = callback.resolve(&self.lua)?;
+ func.call::<()>(&ud)
+ })
+ .map_err(|err| annotate_hook_error(hook_name, err))
+ }
+
+ fn call_bus_read_pre_hook(
+ &self,
+ hook_name: &str,
+ callback: &LuaCallback,
+ emu: &mut Gekko,
+ virt_addr: u32,
+ phys_addr: u32,
+ size: u8,
+ ) -> LuaResult<Option<u32>> {
+ self.lua
+ .scope(|scope| {
+ let ud = scope.create_userdata(GekkoRef(emu as *mut Gekko))?;
+ let func = callback.resolve(&self.lua)?;
+ func.call::<Option<u32>>((&ud, virt_addr, phys_addr, size))
+ })
+ .map_err(|err| annotate_hook_error(hook_name, err))
+ }
+
+ fn call_bus_read_post_hook(
+ &self,
+ hook_name: &str,
+ callback: &LuaCallback,
+ emu: &mut Gekko,
+ virt_addr: u32,
+ phys_addr: u32,
+ size: u8,
+ value: u32,
+ ) -> LuaResult<()> {
+ self.lua
+ .scope(|scope| {
+ let ud = scope.create_userdata(GekkoRef(emu as *mut Gekko))?;
+ let func = callback.resolve(&self.lua)?;
+ func.call::<()>((&ud, virt_addr, phys_addr, size, value))
+ })
+ .map_err(|err| annotate_hook_error(hook_name, err))
+ }
+
+ fn call_bus_write_pre_hook(
+ &self,
+ hook_name: &str,
+ callback: &LuaCallback,
+ emu: &mut Gekko,
+ virt_addr: u32,
+ phys_addr: u32,
+ size: u8,
+ value: u32,
+ ) -> LuaResult<Option<u32>> {
+ self.lua
+ .scope(|scope| {
+ let ud = scope.create_userdata(GekkoRef(emu as *mut Gekko))?;
+ let func = callback.resolve(&self.lua)?;
+ func.call::<Option<u32>>((&ud, virt_addr, phys_addr, size, value))
+ })
+ .map_err(|err| annotate_hook_error(hook_name, err))
+ }
+
+ fn call_bus_write_post_hook(
+ &self,
+ hook_name: &str,
+ callback: &LuaCallback,
+ emu: &mut Gekko,
+ virt_addr: u32,
+ phys_addr: u32,
+ size: u8,
+ value: u32,
+ ) -> LuaResult<()> {
+ self.lua
+ .scope(|scope| {
+ let ud = scope.create_userdata(GekkoRef(emu as *mut Gekko))?;
+ let func = callback.resolve(&self.lua)?;
+ func.call::<()>((&ud, virt_addr, phys_addr, size, value))
+ })
+ .map_err(|err| annotate_hook_error(hook_name, err))
+ }
+}
+
+fn annotate_hook_error(hook_name: &str, err: mlua::Error) -> mlua::Error {
+ mlua::Error::runtime(format!("{hook_name} failed: {err}"))
+}
+
+fn log_hook_error(hook_name: &str, err: &mlua::Error) {
+ tracing::error!(hook = hook_name, error = %err, "script hook failed");
+}
+
+fn load_optional_table(parent: &Table, key: &str, context: &str) -> LuaResult<Option<Table>> {
+ match parent.get::<Value>(key)? {
+ Value::Nil => Ok(None),
+ Value::Table(table) => Ok(Some(table)),
+ other => Err(mlua::Error::runtime(format!(
+ "{context} must be a table, got {}",
+ other.type_name()
+ ))),
+ }
+}
+
+fn load_address_traps(lua: &Lua, table: Option<&Table>, context: &str) -> LuaResult<HashMap<u32, LuaCallback>> {
+ let Some(table) = table else {
+ return Ok(HashMap::new());
+ };
+
+ let mut traps = HashMap::new();
+ for pair in table.pairs::<Value, Value>() {
+ let (key, value) = pair?;
+ let address = parse_address_key(key, context)?;
+ let callback = LuaCallback::from_value(lua, value, context)?;
+ traps.insert(address, callback);
+ }
+ Ok(traps)
+}
+
+fn load_bus_dispatch(lua: &Lua, trap_root: Option<&Table>, trap_name: &str) -> LuaResult<BusHookDispatch> {
+ let trap_table = trap_root
+ .map(|root| load_optional_table(root, trap_name, &format!("traps.{trap_name}")))
+ .transpose()?
+ .flatten();
+
+ let mut dispatch = BusHookDispatch::default();
+
+ let Some(table) = trap_table else {
+ return Ok(dispatch);
+ };
+
+ let virt_table = load_optional_table(&table, "virt", &format!("traps.{trap_name}.virt"))?;
+ let phys_table = load_optional_table(&table, "phys", &format!("traps.{trap_name}.phys"))?;
+
+ if virt_table.is_some() || phys_table.is_some() {
+ dispatch.virt_traps = load_address_traps(lua, virt_table.as_ref(), &format!("traps.{trap_name}.virt"))?;
+ dispatch.phys_traps = load_address_traps(lua, phys_table.as_ref(), &format!("traps.{trap_name}.phys"))?;
+ } else {
+ dispatch.virt_traps = load_address_traps(lua, Some(&table), &format!("traps.{trap_name}"))?;
+ }
+
+ Ok(dispatch)
+}
+
+fn parse_address_key(value: Value, context: &str) -> LuaResult<u32> {
+ match value {
+ Value::Integer(address) if (0..=u32::MAX as i64).contains(&address) => Ok(address as u32),
+ Value::Number(address)
+ if address.is_finite() && address.fract() == 0.0 && (0.0..=u32::MAX as f64).contains(&address) =>
+ {
+ Ok(address as u32)
+ }
+ other => Err(mlua::Error::runtime(format!(
+ "{context} keys must be integer addresses, got {}",
+ other.type_name()
+ ))),
+ }
+}
+
+struct GekkoRef(*mut Gekko);
+
+unsafe impl Send for GekkoRef {}
+
+impl mlua::UserData for GekkoRef {
+ fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
+ LuaScriptHost::register_emu_methods(methods);
+ }
+}
+
+impl std::ops::Deref for GekkoRef {
+ type Target = Gekko;
+
+ fn deref(&self) -> &Gekko {
+ unsafe { &*self.0 }
+ }
+}
+
+impl std::ops::DerefMut for GekkoRef {
+ fn deref_mut(&mut self) -> &mut Gekko {
+ unsafe { &mut *self.0 }
+ }
+}
+
+impl ScriptHost for LuaScriptHost {
+ fn hook_state(&self) -> ScriptHookState {
+ ScriptHookState {
+ flags: self.flags,
+ filters: ScriptHookFilters {
+ cpu_pre: AddressFilter::from_addresses(self.cpu_pre.keys().copied()),
+ cpu_post: AddressFilter::from_addresses(self.cpu_post.keys().copied()),
+ bus_read_pre: self.bus_read_pre.filter(),
+ bus_read_post: self.bus_read_post.filter(),
+ bus_write_pre: self.bus_write_pre.filter(),
+ bus_write_post: self.bus_write_post.filter(),
+ },
+ }
+ }
+
+ #[cfg(feature = "scripting-mut-traps")]
+ fn force_refresh_traps(&mut self) -> Result<ScriptHookState, String> {
+ self.reload_dispatches().map_err(|err| err.to_string())
+ }
+
+ #[cfg(feature = "scripting-mut-traps")]
+ fn take_pending_hook_state(&mut self) -> Result<Option<ScriptHookState>, String> {
+ if !self.refresh_requested.swap(false, Ordering::Relaxed) {
+ return Ok(None);
+ }
+
+ self.reload_dispatches().map(Some).map_err(|err| err.to_string())
+ }
+
+ fn on_cpu_pre(&mut self, emu: &mut Gekko) {
+ let pc = emu.cpu.pc;
+ if let Some(callback) = self.cpu_pre.get(&pc) {
+ if let Err(err) = self.call_cpu_hook("cpu_pre", callback, emu) {
+ log_hook_error("cpu_pre", &err);
+ }
+ }
+ }
+
+ fn on_cpu_post(&mut self, emu: &mut Gekko) {
+ let pc = emu.cpu.cia;
+ if let Some(callback) = self.cpu_post.get(&pc) {
+ if let Err(err) = self.call_cpu_hook("cpu_post", callback, emu) {
+ log_hook_error("cpu_post", &err);
+ }
+ }
+ }
+
+ fn on_bus_read_pre(&mut self, emu: &mut Gekko, virt_addr: u32, phys_addr: u32, size: u8) -> Option<u32> {
+ let callback = self.bus_read_pre.resolve(virt_addr, phys_addr)?;
+ match self.call_bus_read_pre_hook("bus_read_pre", callback, emu, virt_addr, phys_addr, size) {
+ Ok(value) => value,
+ Err(err) => {
+ log_hook_error("bus_read_pre", &err);
+ None
+ }
+ }
+ }
+
+ fn on_bus_read_post(&mut self, emu: &mut Gekko, virt_addr: u32, phys_addr: u32, size: u8, value: u32) {
+ if let Some(callback) = self.bus_read_post.resolve(virt_addr, phys_addr) {
+ if let Err(err) =
+ self.call_bus_read_post_hook("bus_read_post", callback, emu, virt_addr, phys_addr, size, value)
+ {
+ log_hook_error("bus_read_post", &err);
+ }
+ }
+ }
+
+ fn on_bus_write_pre(&mut self, emu: &mut Gekko, virt_addr: u32, phys_addr: u32, size: u8, value: u32) -> u32 {
+ let Some(callback) = self.bus_write_pre.resolve(virt_addr, phys_addr) else {
+ return value;
+ };
+
+ match self.call_bus_write_pre_hook("bus_write_pre", callback, emu, virt_addr, phys_addr, size, value) {
+ Ok(Some(updated)) => updated,
+ Ok(None) => value,
+ Err(err) => {
+ log_hook_error("bus_write_pre", &err);
+ value
+ }
+ }
+ }
+
+ fn on_bus_write_post(&mut self, emu: &mut Gekko, virt_addr: u32, phys_addr: u32, size: u8, value: u32) {
+ if let Some(callback) = self.bus_write_post.resolve(virt_addr, phys_addr) {
+ if let Err(err) =
+ self.call_bus_write_post_hook("bus_write_post", callback, emu, virt_addr, phys_addr, size, value)
+ {
+ log_hook_error("bus_write_post", &err);
+ }
+ }
+ }
+}
diff --git a/crates/tinyapp/Cargo.toml b/crates/tinyapp/Cargo.toml
index 2f7de19..102c7d0 100644
--- a/crates/tinyapp/Cargo.toml
+++ b/crates/tinyapp/Cargo.toml
@@ -3,8 +3,13 @@ name = "tinyapp"
version = "0.1.0"
edition = "2024"
+[features]
+scripting = ["gekko/scripting", "dep:scripting"]
+scripting-mut-traps = ["scripting", "gekko/scripting-mut-traps", "scripting/scripting-mut-traps"]
+
[dependencies]
gekko = { path = "../gekko" }
+scripting = { path = "../scripting", optional = true }
image = { path = "../image" }
backend-wgpu = { path = "../backend-wgpu" }
wgpu = "28.0.0"
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index 6b06994..847cca6 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -489,6 +489,8 @@ fn main() {
.position(|a| a == "--rom")
.map(|i| &args[i + 1])
.or_else(|| args.get(1).filter(|a| !a.starts_with("--")));
+ #[cfg(feature = "scripting")]
+ let script_path = args.iter().position(|a| a == "--script").map(|i| &args[i + 1]);
let no_ansi = std::env::args().any(|arg| arg == "--no-ansi");
@@ -516,6 +518,12 @@ fn main() {
std::process::exit(1);
};
+ #[cfg(feature = "scripting")]
+ if let Some(path) = script_path {
+ let host = scripting::LuaScriptHost::from_file(path).expect("failed to load script");
+ emulator.set_script_host(Box::new(host));
+ }
+
// Channel 0 always has a controller connected
emulator.add_primary_controller(PadStatus {
connected: true,