Compare commits
65
Commits
v0.2.1
...
4bcf743e91
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4bcf743e91 | ||
|
|
bdb14f8f23 | ||
|
|
a6c06fd3ac | ||
|
|
d71be6ddcc | ||
|
|
ac93dcadb5 | ||
|
|
aaca75df26 | ||
|
|
5901a21465 | ||
|
|
a19d4bbc89 | ||
|
|
9f4989cd4c | ||
|
|
ae7ab1e204 | ||
|
|
492c04316d | ||
|
|
1cae0c8e54 | ||
|
|
707dd3a200 | ||
|
|
16a2aaee92 | ||
|
|
d59da1009a | ||
|
|
9d37d22a22 | ||
|
|
e1a8006af7 | ||
|
|
9f7895a457 | ||
|
|
5ce39fb70e | ||
|
|
0fff4d427f | ||
|
|
17d3811124 | ||
|
|
b79f35ac61 | ||
|
|
89128b8207 | ||
|
|
b0404a5da2 | ||
|
|
16cf54e5cf | ||
|
|
f031bb17b2 | ||
|
|
102aff1580 | ||
|
|
f1c5571aa6 | ||
|
|
af9a4ae8ee | ||
|
|
fd7298d24e | ||
|
|
d99344eb15 | ||
|
|
423743ea5c | ||
|
|
005ed509d5 | ||
|
|
0585bc2740 | ||
|
|
62de97384d | ||
|
|
fda738fb93 | ||
|
|
2cf99dbc21 | ||
|
|
84f2cf7ece | ||
|
|
6fd8d8f5cf | ||
|
|
d6eb8ec7ef | ||
|
|
856ee00999 | ||
|
|
11df670ff4 | ||
|
|
a5b5f8e80f | ||
|
|
be8cdd958a | ||
|
|
82c3104ab9 | ||
|
|
8707a5196b | ||
|
|
d016538408 | ||
|
|
9519897711 | ||
|
|
24487b21b7 | ||
|
|
2c5084d317 | ||
|
|
b94ae4d586 | ||
|
|
014b9ebbfa | ||
|
|
0a5e223ba7 | ||
|
|
47a05968fb | ||
|
|
1a54c2e6fc | ||
|
|
d109c71c15 | ||
|
|
1628a45f7d | ||
|
|
cebdcfe220 | ||
|
|
cb05a1e5e6 | ||
|
|
8113b003f7 | ||
|
|
2e8b39a74d | ||
|
|
1c730b3d77 | ||
|
|
249a44e278 | ||
|
|
826bc23a41 | ||
|
|
a13c1e622f |
Generated
+340
-219
File diff suppressed because it is too large
Load Diff
+13
-7
@@ -4,22 +4,25 @@ description = "An emulator for the Virtual Boy."
|
|||||||
repository = "https://git.virtual-boy.com/PVB/lemur"
|
repository = "https://git.virtual-boy.com/PVB/lemur"
|
||||||
publish = false
|
publish = false
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
version = "0.2.1"
|
version = "0.3.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
|
atoi = "2"
|
||||||
|
atomic = "0.6"
|
||||||
bitflags = { version = "2", features = ["serde"] }
|
bitflags = { version = "2", features = ["serde"] }
|
||||||
bytemuck = { version = "1", features = ["derive"] }
|
bytemuck = { version = "1", features = ["derive"] }
|
||||||
clap = { version = "4", features = ["derive"] }
|
clap = { version = "4", features = ["derive"] }
|
||||||
cpal = { git = "https://github.com/sidit77/cpal.git", rev = "66ed6be" }
|
cpal = { git = "https://github.com/sidit77/cpal.git", rev = "66ed6be" }
|
||||||
directories = "5"
|
directories = "5"
|
||||||
egui = { version = "0.29", features = ["serde"] }
|
egui = { version = "0.30", features = ["serde"] }
|
||||||
egui_extras = { version = "0.29", features = ["image"] }
|
egui_extras = { version = "0.30", features = ["image"] }
|
||||||
egui-toast = "0.15"
|
egui-toast = { git = "https://github.com/urholaukkarinen/egui-toast.git", rev = "d0bcf97" }
|
||||||
egui-winit = "0.29"
|
egui-winit = "0.30"
|
||||||
egui-wgpu = { version = "0.29", features = ["winit"] }
|
egui-wgpu = { version = "0.30", features = ["winit"] }
|
||||||
gilrs = { version = "0.11", features = ["serde-serialize"] }
|
gilrs = { version = "0.11", features = ["serde-serialize"] }
|
||||||
|
hex = "0.4"
|
||||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||||
itertools = "0.13"
|
itertools = "0.13"
|
||||||
num-derive = "0.4"
|
num-derive = "0.4"
|
||||||
@@ -32,7 +35,10 @@ rubato = "0.16"
|
|||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
thread-priority = "1"
|
thread-priority = "1"
|
||||||
wgpu = "22.1"
|
tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "sync", "time"] }
|
||||||
|
tracing = { version = "0.1", features = ["release_max_level_info"] }
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
|
wgpu = "23"
|
||||||
winit = { version = "0.30", features = ["serde"] }
|
winit = { version = "0.30", features = ["serde"] }
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ A Virtual Boy emulator built around the shrooms-vb core. Written in Rust, using
|
|||||||
## Setup
|
## Setup
|
||||||
|
|
||||||
Install the following dependencies:
|
Install the following dependencies:
|
||||||
- `cargo`
|
- `cargo` (via [rustup](https://rustup.rs/), the version from your package manager is too old)
|
||||||
|
|
||||||
Run
|
Run
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
+4
-1
@@ -23,6 +23,10 @@ ENV PATH="/osxcross/bin:$PATH" \
|
|||||||
CXX_x86_64-apple-darwin="o64-clang++" \
|
CXX_x86_64-apple-darwin="o64-clang++" \
|
||||||
CC_aarch64-apple-darwin="oa64-clang" \
|
CC_aarch64-apple-darwin="oa64-clang" \
|
||||||
CXX_aarch64-apple-darwin="o6a4-clang++" \
|
CXX_aarch64-apple-darwin="o6a4-clang++" \
|
||||||
|
SHROOMS_CFLAGS_x86_64-unknown-linux-gnu="-flto" \
|
||||||
|
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUSTFLAGS="-Clinker-plugin-lto -Clinker=clang -Clink-arg=-fuse-ld=lld" \
|
||||||
|
SHROOMS_CFLAGS_x86_64-pc-windows-msvc="-flto" \
|
||||||
|
CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS="-Lnative=/xwin/crt/lib/x86_64 -Lnative=/xwin/sdk/lib/um/x86_64 -Lnative=/xwin/sdk/lib/ucrt/x86_64 -Clinker-plugin-lto -Clink-arg=-fuse-ld=lld" \
|
||||||
CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER="lld-link-19" \
|
CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER="lld-link-19" \
|
||||||
CARGO_TARGET_X86_64_APPLE_DARWIN_LINKER="o64-clang" \
|
CARGO_TARGET_X86_64_APPLE_DARWIN_LINKER="o64-clang" \
|
||||||
CARGO_TARGET_X86_64_APPLE_DARWIN_AR="llvm-ar-19" \
|
CARGO_TARGET_X86_64_APPLE_DARWIN_AR="llvm-ar-19" \
|
||||||
@@ -30,5 +34,4 @@ ENV PATH="/osxcross/bin:$PATH" \
|
|||||||
CARGO_TARGET_AARCH64_APPLE_DARWIN_AR="llvm-ar-19" \
|
CARGO_TARGET_AARCH64_APPLE_DARWIN_AR="llvm-ar-19" \
|
||||||
CROSS_COMPILE="setting-this-to-silence-a-warning-" \
|
CROSS_COMPILE="setting-this-to-silence-a-warning-" \
|
||||||
RC_PATH="llvm-rc-19" \
|
RC_PATH="llvm-rc-19" \
|
||||||
RUSTFLAGS="-Lnative=/xwin/crt/lib/x86_64 -Lnative=/xwin/sdk/lib/um/x86_64 -Lnative=/xwin/sdk/lib/ucrt/x86_64" \
|
|
||||||
MACOSX_DEPLOYMENT_TARGET="14.5"
|
MACOSX_DEPLOYMENT_TARGET="14.5"
|
||||||
|
|||||||
@@ -8,13 +8,25 @@ fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
println!("cargo::rerun-if-changed=shrooms-vb-core");
|
println!("cargo::rerun-if-changed=shrooms-vb-core");
|
||||||
cc::Build::new()
|
|
||||||
|
let mut builder = cc::Build::new();
|
||||||
|
let _ = builder.try_flags_from_environment("SHROOMS_CFLAGS");
|
||||||
|
let opt_level = if builder.get_compiler().is_like_msvc() {
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
3
|
||||||
|
};
|
||||||
|
builder
|
||||||
.include(Path::new("shrooms-vb-core/core"))
|
.include(Path::new("shrooms-vb-core/core"))
|
||||||
.opt_level(2)
|
.opt_level(opt_level)
|
||||||
.flag_if_supported("-fno-strict-aliasing")
|
.flag_if_supported("-fno-strict-aliasing")
|
||||||
.define("VB_LITTLE_ENDIAN", None)
|
.define("VB_LITTLE_ENDIAN", None)
|
||||||
.define("VB_SIGNED_PROPAGATE", None)
|
.define("VB_SIGNED_PROPAGATE", None)
|
||||||
.define("VB_DIV_GENERIC", None)
|
.define("VB_DIV_GENERIC", None)
|
||||||
|
.define("VB_DIRECT_EXECUTE", "on_execute")
|
||||||
|
.define("VB_DIRECT_FRAME", "on_frame")
|
||||||
|
.define("VB_DIRECT_READ", "on_read")
|
||||||
|
.define("VB_DIRECT_WRITE", "on_write")
|
||||||
.file(Path::new("shrooms-vb-core/core/vb.c"))
|
.file(Path::new("shrooms-vb-core/core/vb.c"))
|
||||||
.compile("vb");
|
.compile("vb");
|
||||||
|
|
||||||
|
|||||||
+9
-2
@@ -1,3 +1,4 @@
|
|||||||
|
set -e
|
||||||
version=$(cat Cargo.toml | sed -n -e '/version/ {s/.* = *//p;q}' | tr -d '"')
|
version=$(cat Cargo.toml | sed -n -e '/version/ {s/.* = *//p;q}' | tr -d '"')
|
||||||
|
|
||||||
read -p "You wanted to release $version, right? [Y/n] " -n 1 -r
|
read -p "You wanted to release $version, right? [Y/n] " -n 1 -r
|
||||||
@@ -18,11 +19,15 @@ if ! command -v jq 2>&1 >/dev/null; then
|
|||||||
echo "Please install jq."
|
echo "Please install jq."
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
if ! command -v docker 2>&1 >/dev/null; then
|
||||||
|
echo "Please install docker."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
docker build -f build.Dockerfile -t lemur-build .
|
docker build -f build.Dockerfile -t lemur-build .
|
||||||
MSYS_NO_PATHCONV=1 docker run -it --rm -v .:/app -w /app --entrypoint bash lemur-build /app/scripts/do-bundle.sh
|
MSYS_NO_PATHCONV=1 docker run -it --rm -v .:/app -w /app --entrypoint bash lemur-build /app/scripts/do-bundle.sh
|
||||||
|
|
||||||
read -r -d EOF 'body' <<EOF
|
body=$(cat <<EOF
|
||||||
## How to install
|
## How to install
|
||||||
|
|
||||||
The emulator can be found in the "Downloads" section of this release.
|
The emulator can be found in the "Downloads" section of this release.
|
||||||
@@ -43,8 +48,9 @@ If you're not sure which to choose, use [this guide](https://support.apple.com/e
|
|||||||
|
|
||||||
You can either download and run \`lemur-linux\`, or download and install the attached .deb file.
|
You can either download and run \`lemur-linux\`, or download and install the attached .deb file.
|
||||||
EOF
|
EOF
|
||||||
|
)
|
||||||
|
|
||||||
read -r -d EOF 'payload' <<EOF
|
payload=$(cat <<EOF
|
||||||
{
|
{
|
||||||
"body": $(echo "$body" | jq -Rsa .),
|
"body": $(echo "$body" | jq -Rsa .),
|
||||||
"draft": false,
|
"draft": false,
|
||||||
@@ -53,6 +59,7 @@ read -r -d EOF 'payload' <<EOF
|
|||||||
"tag_name": "v${version}"
|
"tag_name": "v${version}"
|
||||||
}
|
}
|
||||||
EOF
|
EOF
|
||||||
|
)
|
||||||
|
|
||||||
echo "Creating release..."
|
echo "Creating release..."
|
||||||
response=$(curl -s --json "$payload" "https://git.virtual-boy.com/api/v1/repos/PVB/lemur/releases?token=$RELEASE_TOKEN")
|
response=$(curl -s --json "$payload" "https://git.virtual-boy.com/api/v1/repos/PVB/lemur/releases?token=$RELEASE_TOKEN")
|
||||||
|
|||||||
+1
-1
Submodule shrooms-vb-core updated: 27e926bd58...155a3aa678
+114
-51
@@ -6,6 +6,7 @@ use egui::{
|
|||||||
ViewportCommand, ViewportId, ViewportInfo,
|
ViewportCommand, ViewportId, ViewportInfo,
|
||||||
};
|
};
|
||||||
use gilrs::{EventType, Gilrs};
|
use gilrs::{EventType, Gilrs};
|
||||||
|
use tracing::{error, warn};
|
||||||
use winit::{
|
use winit::{
|
||||||
application::ApplicationHandler,
|
application::ApplicationHandler,
|
||||||
event::WindowEvent,
|
event::WindowEvent,
|
||||||
@@ -17,8 +18,13 @@ use crate::{
|
|||||||
controller::ControllerManager,
|
controller::ControllerManager,
|
||||||
emulator::{EmulatorClient, EmulatorCommand, SimId},
|
emulator::{EmulatorClient, EmulatorCommand, SimId},
|
||||||
input::MappingProvider,
|
input::MappingProvider,
|
||||||
|
memory::MemoryMonitor,
|
||||||
persistence::Persistence,
|
persistence::Persistence,
|
||||||
window::{AboutWindow, AppWindow, GameWindow, InputWindow},
|
vram::VramProcessor,
|
||||||
|
window::{
|
||||||
|
AboutWindow, AppWindow, BgMapWindow, CharacterDataWindow, GameWindow, GdbServerWindow,
|
||||||
|
InputWindow,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn load_icon() -> anyhow::Result<IconData> {
|
fn load_icon() -> anyhow::Result<IconData> {
|
||||||
@@ -38,17 +44,26 @@ pub struct Application {
|
|||||||
proxy: EventLoopProxy<UserEvent>,
|
proxy: EventLoopProxy<UserEvent>,
|
||||||
mappings: MappingProvider,
|
mappings: MappingProvider,
|
||||||
controllers: ControllerManager,
|
controllers: ControllerManager,
|
||||||
|
memory: MemoryMonitor,
|
||||||
|
vram: VramProcessor,
|
||||||
persistence: Persistence,
|
persistence: Persistence,
|
||||||
viewports: HashMap<ViewportId, Viewport>,
|
viewports: HashMap<ViewportId, Viewport>,
|
||||||
focused: Option<ViewportId>,
|
focused: Option<ViewportId>,
|
||||||
|
init_debug_port: Option<u16>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Application {
|
impl Application {
|
||||||
pub fn new(client: EmulatorClient, proxy: EventLoopProxy<UserEvent>) -> Self {
|
pub fn new(
|
||||||
|
client: EmulatorClient,
|
||||||
|
proxy: EventLoopProxy<UserEvent>,
|
||||||
|
debug_port: Option<u16>,
|
||||||
|
) -> Self {
|
||||||
let icon = load_icon().ok().map(Arc::new);
|
let icon = load_icon().ok().map(Arc::new);
|
||||||
let persistence = Persistence::new();
|
let persistence = Persistence::new();
|
||||||
let mappings = MappingProvider::new(persistence.clone());
|
let mappings = MappingProvider::new(persistence.clone());
|
||||||
let controllers = ControllerManager::new(client.clone(), &mappings);
|
let controllers = ControllerManager::new(client.clone(), &mappings);
|
||||||
|
let memory = MemoryMonitor::new(client.clone());
|
||||||
|
let vram = VramProcessor::new();
|
||||||
{
|
{
|
||||||
let mappings = mappings.clone();
|
let mappings = mappings.clone();
|
||||||
let proxy = proxy.clone();
|
let proxy = proxy.clone();
|
||||||
@@ -59,10 +74,13 @@ impl Application {
|
|||||||
client,
|
client,
|
||||||
proxy,
|
proxy,
|
||||||
mappings,
|
mappings,
|
||||||
|
memory,
|
||||||
|
vram,
|
||||||
controllers,
|
controllers,
|
||||||
persistence,
|
persistence,
|
||||||
viewports: HashMap::new(),
|
viewports: HashMap::new(),
|
||||||
focused: None,
|
focused: None,
|
||||||
|
init_debug_port: debug_port,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,15 +98,19 @@ impl Application {
|
|||||||
|
|
||||||
impl ApplicationHandler<UserEvent> for Application {
|
impl ApplicationHandler<UserEvent> for Application {
|
||||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||||
|
if let Some(port) = self.init_debug_port {
|
||||||
|
let mut server =
|
||||||
|
GdbServerWindow::new(SimId::Player1, self.client.clone(), self.proxy.clone());
|
||||||
|
server.launch(port);
|
||||||
|
self.open(event_loop, Box::new(server));
|
||||||
|
}
|
||||||
let app = GameWindow::new(
|
let app = GameWindow::new(
|
||||||
self.client.clone(),
|
self.client.clone(),
|
||||||
self.proxy.clone(),
|
self.proxy.clone(),
|
||||||
self.persistence.clone(),
|
self.persistence.clone(),
|
||||||
SimId::Player1,
|
SimId::Player1,
|
||||||
);
|
);
|
||||||
let wrapper = Viewport::new(event_loop, self.icon.clone(), Box::new(app));
|
self.open(event_loop, Box::new(app));
|
||||||
self.focused = Some(wrapper.id());
|
|
||||||
self.viewports.insert(wrapper.id(), wrapper);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn window_event(
|
fn window_event(
|
||||||
@@ -105,19 +127,23 @@ impl ApplicationHandler<UserEvent> for Application {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let viewport_id = viewport.id();
|
let viewport_id = viewport.id();
|
||||||
match &event {
|
|
||||||
WindowEvent::KeyboardInput { event, .. } => {
|
|
||||||
self.controllers.handle_key_event(event);
|
|
||||||
viewport.app.handle_key_event(event);
|
|
||||||
}
|
|
||||||
WindowEvent::Focused(new_focused) => {
|
|
||||||
self.focused = new_focused.then_some(viewport_id);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
let mut queue_redraw = false;
|
let mut queue_redraw = false;
|
||||||
let mut inactive_viewports = HashSet::new();
|
let mut inactive_viewports = HashSet::new();
|
||||||
match viewport.on_window_event(event) {
|
let (consumed, action) = viewport.on_window_event(&event);
|
||||||
|
if !consumed {
|
||||||
|
match event {
|
||||||
|
WindowEvent::KeyboardInput { event, .. } => {
|
||||||
|
if !viewport.app.handle_key_event(&event) {
|
||||||
|
self.controllers.handle_key_event(&event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::Focused(new_focused) => {
|
||||||
|
self.focused = new_focused.then_some(viewport_id);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match action {
|
||||||
Some(Action::Redraw) => {
|
Some(Action::Redraw) => {
|
||||||
for viewport in self.viewports.values_mut() {
|
for viewport in self.viewports.values_mut() {
|
||||||
match viewport.redraw(event_loop) {
|
match viewport.redraw(event_loop) {
|
||||||
@@ -169,20 +195,34 @@ impl ApplicationHandler<UserEvent> for Application {
|
|||||||
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
|
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
|
||||||
match event {
|
match event {
|
||||||
UserEvent::GamepadEvent(event) => {
|
UserEvent::GamepadEvent(event) => {
|
||||||
self.controllers.handle_gamepad_event(&event);
|
if let Some(viewport) = self
|
||||||
let Some(viewport) = self
|
|
||||||
.focused
|
.focused
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|id| self.viewports.get_mut(id))
|
.and_then(|id| self.viewports.get_mut(id))
|
||||||
else {
|
{
|
||||||
return;
|
if viewport.app.handle_gamepad_event(&event) {
|
||||||
};
|
return;
|
||||||
viewport.app.handle_gamepad_event(&event);
|
}
|
||||||
|
}
|
||||||
|
self.controllers.handle_gamepad_event(&event);
|
||||||
}
|
}
|
||||||
UserEvent::OpenAbout => {
|
UserEvent::OpenAbout => {
|
||||||
let about = AboutWindow;
|
let about = AboutWindow;
|
||||||
self.open(event_loop, Box::new(about));
|
self.open(event_loop, Box::new(about));
|
||||||
}
|
}
|
||||||
|
UserEvent::OpenCharacterData(sim_id) => {
|
||||||
|
let vram = CharacterDataWindow::new(sim_id, &mut self.memory, &mut self.vram);
|
||||||
|
self.open(event_loop, Box::new(vram));
|
||||||
|
}
|
||||||
|
UserEvent::OpenBgMap(sim_id) => {
|
||||||
|
let bgmap = BgMapWindow::new(sim_id, &mut self.memory, &mut self.vram);
|
||||||
|
self.open(event_loop, Box::new(bgmap));
|
||||||
|
}
|
||||||
|
UserEvent::OpenDebugger(sim_id) => {
|
||||||
|
let debugger =
|
||||||
|
GdbServerWindow::new(sim_id, self.client.clone(), self.proxy.clone());
|
||||||
|
self.open(event_loop, Box::new(debugger));
|
||||||
|
}
|
||||||
UserEvent::OpenInput => {
|
UserEvent::OpenInput => {
|
||||||
let input = InputWindow::new(self.mappings.clone());
|
let input = InputWindow::new(self.mappings.clone());
|
||||||
self.open(event_loop, Box::new(input));
|
self.open(event_loop, Box::new(input));
|
||||||
@@ -196,6 +236,13 @@ impl ApplicationHandler<UserEvent> for Application {
|
|||||||
);
|
);
|
||||||
self.open(event_loop, Box::new(p2));
|
self.open(event_loop, Box::new(p2));
|
||||||
}
|
}
|
||||||
|
UserEvent::Quit(sim_id) => {
|
||||||
|
self.viewports
|
||||||
|
.retain(|_, viewport| viewport.app.sim_id() != sim_id);
|
||||||
|
if !self.viewports.contains_key(&ViewportId::ROOT) {
|
||||||
|
event_loop.exit();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,8 +255,8 @@ impl ApplicationHandler<UserEvent> for Application {
|
|||||||
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
|
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
|
||||||
let (sender, receiver) = oneshot::channel();
|
let (sender, receiver) = oneshot::channel();
|
||||||
if self.client.send_command(EmulatorCommand::Exit(sender)) {
|
if self.client.send_command(EmulatorCommand::Exit(sender)) {
|
||||||
if let Err(err) = receiver.recv_timeout(Duration::from_secs(5)) {
|
if let Err(error) = receiver.recv_timeout(Duration::from_secs(5)) {
|
||||||
eprintln!("could not gracefully exit: {}", err);
|
error!(%error, "could not gracefully exit.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -231,22 +278,13 @@ impl Viewport {
|
|||||||
icon: Option<Arc<IconData>>,
|
icon: Option<Arc<IconData>>,
|
||||||
mut app: Box<dyn AppWindow>,
|
mut app: Box<dyn AppWindow>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let mut painter = egui_wgpu::winit::Painter::new(
|
|
||||||
egui_wgpu::WgpuConfiguration {
|
|
||||||
present_mode: wgpu::PresentMode::AutoNoVsync,
|
|
||||||
..egui_wgpu::WgpuConfiguration::default()
|
|
||||||
},
|
|
||||||
1,
|
|
||||||
None,
|
|
||||||
false,
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
|
|
||||||
let ctx = Context::default();
|
let ctx = Context::default();
|
||||||
let mut fonts = FontDefinitions::default();
|
let mut fonts = FontDefinitions::default();
|
||||||
fonts.font_data.insert(
|
fonts.font_data.insert(
|
||||||
"Selawik".into(),
|
"Selawik".into(),
|
||||||
FontData::from_static(include_bytes!("../assets/selawik.ttf")),
|
Arc::new(FontData::from_static(include_bytes!(
|
||||||
|
"../assets/selawik.ttf"
|
||||||
|
))),
|
||||||
);
|
);
|
||||||
fonts
|
fonts
|
||||||
.families
|
.families
|
||||||
@@ -260,6 +298,24 @@ impl Viewport {
|
|||||||
});
|
});
|
||||||
egui_extras::install_image_loaders(&ctx);
|
egui_extras::install_image_loaders(&ctx);
|
||||||
|
|
||||||
|
#[allow(unused_mut)]
|
||||||
|
let mut wgpu_config = egui_wgpu::WgpuConfiguration {
|
||||||
|
present_mode: wgpu::PresentMode::AutoNoVsync,
|
||||||
|
..egui_wgpu::WgpuConfiguration::default()
|
||||||
|
};
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
if let egui_wgpu::WgpuSetup::CreateNew {
|
||||||
|
supported_backends, ..
|
||||||
|
} = &mut wgpu_config.wgpu_setup
|
||||||
|
{
|
||||||
|
*supported_backends -= wgpu::Backends::VULKAN;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut painter =
|
||||||
|
egui_wgpu::winit::Painter::new(ctx.clone(), wgpu_config, 1, None, false, true);
|
||||||
|
|
||||||
let mut info = ViewportInfo::default();
|
let mut info = ViewportInfo::default();
|
||||||
let mut builder = app.initial_viewport();
|
let mut builder = app.initial_viewport();
|
||||||
if let Some(icon) = icon {
|
if let Some(icon) = icon {
|
||||||
@@ -268,7 +324,7 @@ impl Viewport {
|
|||||||
let (window, state) = create_window_and_state(&ctx, event_loop, &builder, &mut painter);
|
let (window, state) = create_window_and_state(&ctx, event_loop, &builder, &mut painter);
|
||||||
egui_winit::update_viewport_info(&mut info, &ctx, &window, true);
|
egui_winit::update_viewport_info(&mut info, &ctx, &window, true);
|
||||||
|
|
||||||
app.on_init(painter.render_state().as_ref().unwrap());
|
app.on_init(&ctx, painter.render_state().as_ref().unwrap());
|
||||||
Self {
|
Self {
|
||||||
painter,
|
painter,
|
||||||
ctx,
|
ctx,
|
||||||
@@ -285,8 +341,8 @@ impl Viewport {
|
|||||||
self.app.viewport_id()
|
self.app.viewport_id()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_window_event(&mut self, event: WindowEvent) -> Option<Action> {
|
pub fn on_window_event(&mut self, event: &WindowEvent) -> (bool, Option<Action>) {
|
||||||
let response = self.state.on_window_event(&self.window, &event);
|
let response = self.state.on_window_event(&self.window, event);
|
||||||
egui_winit::update_viewport_info(
|
egui_winit::update_viewport_info(
|
||||||
&mut self.info,
|
&mut self.info,
|
||||||
self.state.egui_ctx(),
|
self.state.egui_ctx(),
|
||||||
@@ -294,22 +350,22 @@ impl Viewport {
|
|||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
|
|
||||||
match event {
|
let action = match event {
|
||||||
WindowEvent::RedrawRequested => Some(Action::Redraw),
|
WindowEvent::RedrawRequested => Some(Action::Redraw),
|
||||||
WindowEvent::CloseRequested => Some(Action::Close),
|
WindowEvent::CloseRequested => Some(Action::Close),
|
||||||
WindowEvent::Resized(size) => {
|
WindowEvent::Resized(size) => {
|
||||||
let (Some(width), Some(height)) =
|
if let (Some(width), Some(height)) =
|
||||||
(NonZero::new(size.width), NonZero::new(size.height))
|
(NonZero::new(size.width), NonZero::new(size.height))
|
||||||
else {
|
{
|
||||||
return None;
|
self.painter
|
||||||
};
|
.on_window_resized(ViewportId::ROOT, width, height);
|
||||||
self.painter
|
}
|
||||||
.on_window_resized(ViewportId::ROOT, width, height);
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
_ if response.repaint => Some(Action::Redraw),
|
_ if response.repaint => Some(Action::Redraw),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
};
|
||||||
|
(response.consumed, action)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn redraw(&mut self, event_loop: &ActiveEventLoop) -> Option<Action> {
|
fn redraw(&mut self, event_loop: &ActiveEventLoop) -> Option<Action> {
|
||||||
@@ -325,7 +381,7 @@ impl Viewport {
|
|||||||
[0.0, 0.0, 0.0, 0.0],
|
[0.0, 0.0, 0.0, 0.0],
|
||||||
&clipped_primitives,
|
&clipped_primitives,
|
||||||
&output.textures_delta,
|
&output.textures_delta,
|
||||||
false,
|
vec![],
|
||||||
);
|
);
|
||||||
|
|
||||||
self.state
|
self.state
|
||||||
@@ -371,8 +427,12 @@ impl Drop for Viewport {
|
|||||||
pub enum UserEvent {
|
pub enum UserEvent {
|
||||||
GamepadEvent(gilrs::Event),
|
GamepadEvent(gilrs::Event),
|
||||||
OpenAbout,
|
OpenAbout,
|
||||||
|
OpenCharacterData(SimId),
|
||||||
|
OpenBgMap(SimId),
|
||||||
|
OpenDebugger(SimId),
|
||||||
OpenInput,
|
OpenInput,
|
||||||
OpenPlayer2,
|
OpenPlayer2,
|
||||||
|
Quit(SimId),
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum Action {
|
pub enum Action {
|
||||||
@@ -401,9 +461,12 @@ fn create_window_and_state(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn process_gamepad_input(mappings: MappingProvider, proxy: EventLoopProxy<UserEvent>) {
|
fn process_gamepad_input(mappings: MappingProvider, proxy: EventLoopProxy<UserEvent>) {
|
||||||
let Ok(mut gilrs) = Gilrs::new() else {
|
let mut gilrs = match Gilrs::new() {
|
||||||
eprintln!("could not connect gamepad listener");
|
Ok(gilrs) => gilrs,
|
||||||
return;
|
Err(error) => {
|
||||||
|
warn!(%error, "could not connect gamepad listener");
|
||||||
|
return;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
while let Some(event) = gilrs.next_event_blocking(None) {
|
while let Some(event) = gilrs.next_event_blocking(None) {
|
||||||
if event.event == EventType::Connected {
|
if event.event == EventType::Connected {
|
||||||
|
|||||||
+2
-1
@@ -4,6 +4,7 @@ use anyhow::{bail, Result};
|
|||||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use rubato::{FftFixedInOut, Resampler};
|
use rubato::{FftFixedInOut, Resampler};
|
||||||
|
use tracing::error;
|
||||||
|
|
||||||
pub struct Audio {
|
pub struct Audio {
|
||||||
#[allow(unused)]
|
#[allow(unused)]
|
||||||
@@ -54,7 +55,7 @@ impl Audio {
|
|||||||
}
|
}
|
||||||
chunk.commit_all();
|
chunk.commit_all();
|
||||||
},
|
},
|
||||||
move |err| eprintln!("stream error: {err}"),
|
move |error| error!(%error, "stream error"),
|
||||||
None,
|
None,
|
||||||
)?;
|
)?;
|
||||||
stream.play()?;
|
stream.play()?;
|
||||||
|
|||||||
+401
-117
@@ -1,34 +1,33 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
|
fmt::Display,
|
||||||
fs::{self, File},
|
fs::{self, File},
|
||||||
io::{Read, Seek, SeekFrom, Write},
|
io::{Read, Seek, SeekFrom, Write},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
sync::{
|
sync::{
|
||||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
atomic::{AtomicBool, Ordering},
|
||||||
mpsc::{self, RecvError, TryRecvError},
|
mpsc::{self, RecvError, TryRecvError},
|
||||||
Arc,
|
Arc, Weak,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
use atomic::Atomic;
|
||||||
|
use bytemuck::NoUninit;
|
||||||
use egui_toast::{Toast, ToastKind, ToastOptions};
|
use egui_toast::{Toast, ToastKind, ToastOptions};
|
||||||
|
use tracing::{error, warn};
|
||||||
|
|
||||||
use crate::{audio::Audio, graphics::TextureSink};
|
use crate::{
|
||||||
pub use shrooms_vb_core::VBKey;
|
audio::Audio,
|
||||||
use shrooms_vb_core::{Sim, EXPECTED_FRAME_SIZE};
|
graphics::TextureSink,
|
||||||
|
memory::{MemoryRange, MemoryRegion},
|
||||||
|
};
|
||||||
|
use shrooms_vb_core::{Sim, StopReason, EXPECTED_FRAME_SIZE};
|
||||||
|
pub use shrooms_vb_core::{VBKey, VBRegister, VBWatchpointType};
|
||||||
|
|
||||||
|
mod address_set;
|
||||||
mod shrooms_vb_core;
|
mod shrooms_vb_core;
|
||||||
|
|
||||||
pub struct EmulatorBuilder {
|
|
||||||
rom: Option<PathBuf>,
|
|
||||||
commands: mpsc::Receiver<EmulatorCommand>,
|
|
||||||
sim_count: Arc<AtomicUsize>,
|
|
||||||
running: Arc<[AtomicBool; 2]>,
|
|
||||||
has_game: Arc<[AtomicBool; 2]>,
|
|
||||||
audio_on: Arc<[AtomicBool; 2]>,
|
|
||||||
linked: Arc<AtomicBool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
|
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
|
||||||
pub enum SimId {
|
pub enum SimId {
|
||||||
Player1,
|
Player1,
|
||||||
@@ -45,6 +44,14 @@ impl SimId {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
impl Display for SimId {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str(match self {
|
||||||
|
Self::Player1 => "Player 1",
|
||||||
|
Self::Player2 => "Player 2",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct Cart {
|
struct Cart {
|
||||||
rom_path: PathBuf,
|
rom_path: PathBuf,
|
||||||
@@ -83,23 +90,35 @@ fn sram_path(rom_path: &Path, sim_id: SimId) -> PathBuf {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct EmulatorBuilder {
|
||||||
|
rom: Option<PathBuf>,
|
||||||
|
commands: mpsc::Receiver<EmulatorCommand>,
|
||||||
|
sim_state: Arc<[Atomic<SimState>; 2]>,
|
||||||
|
state: Arc<Atomic<EmulatorState>>,
|
||||||
|
audio_on: Arc<[AtomicBool; 2]>,
|
||||||
|
linked: Arc<AtomicBool>,
|
||||||
|
start_paused: bool,
|
||||||
|
}
|
||||||
|
|
||||||
impl EmulatorBuilder {
|
impl EmulatorBuilder {
|
||||||
pub fn new() -> (Self, EmulatorClient) {
|
pub fn new() -> (Self, EmulatorClient) {
|
||||||
let (queue, commands) = mpsc::channel();
|
let (queue, commands) = mpsc::channel();
|
||||||
let builder = Self {
|
let builder = Self {
|
||||||
rom: None,
|
rom: None,
|
||||||
commands,
|
commands,
|
||||||
sim_count: Arc::new(AtomicUsize::new(0)),
|
sim_state: Arc::new([
|
||||||
running: Arc::new([AtomicBool::new(false), AtomicBool::new(false)]),
|
Atomic::new(SimState::Uninitialized),
|
||||||
has_game: Arc::new([AtomicBool::new(false), AtomicBool::new(false)]),
|
Atomic::new(SimState::Uninitialized),
|
||||||
|
]),
|
||||||
|
state: Arc::new(Atomic::new(EmulatorState::Paused)),
|
||||||
audio_on: Arc::new([AtomicBool::new(true), AtomicBool::new(true)]),
|
audio_on: Arc::new([AtomicBool::new(true), AtomicBool::new(true)]),
|
||||||
linked: Arc::new(AtomicBool::new(false)),
|
linked: Arc::new(AtomicBool::new(false)),
|
||||||
|
start_paused: false,
|
||||||
};
|
};
|
||||||
let client = EmulatorClient {
|
let client = EmulatorClient {
|
||||||
queue,
|
queue,
|
||||||
sim_count: builder.sim_count.clone(),
|
sim_state: builder.sim_state.clone(),
|
||||||
running: builder.running.clone(),
|
state: builder.state.clone(),
|
||||||
has_game: builder.has_game.clone(),
|
|
||||||
audio_on: builder.audio_on.clone(),
|
audio_on: builder.audio_on.clone(),
|
||||||
linked: builder.linked.clone(),
|
linked: builder.linked.clone(),
|
||||||
};
|
};
|
||||||
@@ -113,18 +132,27 @@ impl EmulatorBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn start_paused(self, paused: bool) -> Self {
|
||||||
|
Self {
|
||||||
|
start_paused: paused,
|
||||||
|
..self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn build(self) -> Result<Emulator> {
|
pub fn build(self) -> Result<Emulator> {
|
||||||
let mut emulator = Emulator::new(
|
let mut emulator = Emulator::new(
|
||||||
self.commands,
|
self.commands,
|
||||||
self.sim_count,
|
self.sim_state,
|
||||||
self.running,
|
self.state,
|
||||||
self.has_game,
|
|
||||||
self.audio_on,
|
self.audio_on,
|
||||||
self.linked,
|
self.linked,
|
||||||
)?;
|
)?;
|
||||||
if let Some(path) = self.rom {
|
if let Some(path) = self.rom {
|
||||||
emulator.load_cart(SimId::Player1, &path)?;
|
emulator.load_cart(SimId::Player1, &path)?;
|
||||||
}
|
}
|
||||||
|
if self.start_paused {
|
||||||
|
emulator.pause_sims()?;
|
||||||
|
}
|
||||||
Ok(emulator)
|
Ok(emulator)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -134,21 +162,24 @@ pub struct Emulator {
|
|||||||
carts: [Option<Cart>; 2],
|
carts: [Option<Cart>; 2],
|
||||||
audio: Audio,
|
audio: Audio,
|
||||||
commands: mpsc::Receiver<EmulatorCommand>,
|
commands: mpsc::Receiver<EmulatorCommand>,
|
||||||
sim_count: Arc<AtomicUsize>,
|
sim_state: Arc<[Atomic<SimState>; 2]>,
|
||||||
running: Arc<[AtomicBool; 2]>,
|
state: Arc<Atomic<EmulatorState>>,
|
||||||
has_game: Arc<[AtomicBool; 2]>,
|
|
||||||
audio_on: Arc<[AtomicBool; 2]>,
|
audio_on: Arc<[AtomicBool; 2]>,
|
||||||
linked: Arc<AtomicBool>,
|
linked: Arc<AtomicBool>,
|
||||||
renderers: HashMap<SimId, TextureSink>,
|
renderers: HashMap<SimId, TextureSink>,
|
||||||
messages: HashMap<SimId, mpsc::Sender<Toast>>,
|
messages: HashMap<SimId, mpsc::Sender<Toast>>,
|
||||||
|
debuggers: HashMap<SimId, DebugInfo>,
|
||||||
|
watched_regions: HashMap<MemoryRange, Weak<MemoryRegion>>,
|
||||||
|
eye_contents: Vec<u8>,
|
||||||
|
audio_samples: Vec<f32>,
|
||||||
|
buffer: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Emulator {
|
impl Emulator {
|
||||||
fn new(
|
fn new(
|
||||||
commands: mpsc::Receiver<EmulatorCommand>,
|
commands: mpsc::Receiver<EmulatorCommand>,
|
||||||
sim_count: Arc<AtomicUsize>,
|
sim_state: Arc<[Atomic<SimState>; 2]>,
|
||||||
running: Arc<[AtomicBool; 2]>,
|
state: Arc<Atomic<EmulatorState>>,
|
||||||
has_game: Arc<[AtomicBool; 2]>,
|
|
||||||
audio_on: Arc<[AtomicBool; 2]>,
|
audio_on: Arc<[AtomicBool; 2]>,
|
||||||
linked: Arc<AtomicBool>,
|
linked: Arc<AtomicBool>,
|
||||||
) -> Result<Self> {
|
) -> Result<Self> {
|
||||||
@@ -157,13 +188,17 @@ impl Emulator {
|
|||||||
carts: [None, None],
|
carts: [None, None],
|
||||||
audio: Audio::init()?,
|
audio: Audio::init()?,
|
||||||
commands,
|
commands,
|
||||||
sim_count,
|
sim_state,
|
||||||
running,
|
state,
|
||||||
has_game,
|
|
||||||
audio_on,
|
audio_on,
|
||||||
linked,
|
linked,
|
||||||
renderers: HashMap::new(),
|
renderers: HashMap::new(),
|
||||||
messages: HashMap::new(),
|
messages: HashMap::new(),
|
||||||
|
debuggers: HashMap::new(),
|
||||||
|
watched_regions: HashMap::new(),
|
||||||
|
eye_contents: vec![0u8; 384 * 224 * 2],
|
||||||
|
audio_samples: Vec::with_capacity(EXPECTED_FRAME_SIZE),
|
||||||
|
buffer: vec![],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -194,17 +229,17 @@ impl Emulator {
|
|||||||
let index = sim_id.to_index();
|
let index = sim_id.to_index();
|
||||||
while self.sims.len() <= index {
|
while self.sims.len() <= index {
|
||||||
self.sims.push(Sim::new());
|
self.sims.push(Sim::new());
|
||||||
|
self.sim_state[index].store(SimState::NoGame, Ordering::Release);
|
||||||
}
|
}
|
||||||
self.sim_count.store(self.sims.len(), Ordering::Relaxed);
|
|
||||||
let sim = &mut self.sims[index];
|
let sim = &mut self.sims[index];
|
||||||
sim.reset();
|
sim.reset();
|
||||||
if let Some(cart) = new_cart {
|
if let Some(cart) = new_cart {
|
||||||
sim.load_cart(cart.rom.clone(), cart.sram.clone())?;
|
sim.load_cart(cart.rom.clone(), cart.sram.clone())?;
|
||||||
self.carts[index] = Some(cart);
|
self.carts[index] = Some(cart);
|
||||||
self.has_game[index].store(true, Ordering::Release);
|
self.sim_state[index].store(SimState::Ready, Ordering::Release);
|
||||||
}
|
}
|
||||||
if self.has_game[index].load(Ordering::Acquire) {
|
if self.sim_state[index].load(Ordering::Acquire) == SimState::Ready {
|
||||||
self.running[index].store(true, Ordering::Release);
|
self.resume_sims();
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -229,9 +264,31 @@ impl Emulator {
|
|||||||
self.linked.store(false, Ordering::Release);
|
self.linked.store(false, Ordering::Release);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn pause_sim(&mut self, sim_id: SimId) -> Result<()> {
|
fn pause_sims(&mut self) -> Result<()> {
|
||||||
self.running[sim_id.to_index()].store(false, Ordering::Release);
|
if self
|
||||||
self.save_sram(sim_id)
|
.state
|
||||||
|
.compare_exchange(
|
||||||
|
EmulatorState::Running,
|
||||||
|
EmulatorState::Paused,
|
||||||
|
Ordering::AcqRel,
|
||||||
|
Ordering::Relaxed,
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
for sim_id in SimId::values() {
|
||||||
|
self.save_sram(sim_id)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resume_sims(&mut self) {
|
||||||
|
let _ = self.state.compare_exchange(
|
||||||
|
EmulatorState::Paused,
|
||||||
|
EmulatorState::Running,
|
||||||
|
Ordering::AcqRel,
|
||||||
|
Ordering::Relaxed,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save_sram(&mut self, sim_id: SimId) -> Result<()> {
|
fn save_sram(&mut self, sim_id: SimId) -> Result<()> {
|
||||||
@@ -249,64 +306,82 @@ impl Emulator {
|
|||||||
self.save_sram(SimId::Player2)?;
|
self.save_sram(SimId::Player2)?;
|
||||||
self.renderers.remove(&SimId::Player2);
|
self.renderers.remove(&SimId::Player2);
|
||||||
self.sims.truncate(1);
|
self.sims.truncate(1);
|
||||||
self.sim_count.store(self.sims.len(), Ordering::Relaxed);
|
self.sim_state[SimId::Player2.to_index()].store(SimState::Uninitialized, Ordering::Release);
|
||||||
self.running[SimId::Player2.to_index()].store(false, Ordering::Release);
|
self.stop_debugging(SimId::Player2);
|
||||||
self.has_game[SimId::Player2.to_index()].store(false, Ordering::Release);
|
|
||||||
self.linked.store(false, Ordering::Release);
|
self.linked.store(false, Ordering::Release);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run(&mut self) {
|
fn start_debugging(&mut self, sim_id: SimId, sender: DebugSender) {
|
||||||
let mut eye_contents = vec![0u8; 384 * 224 * 2];
|
if self.sim_state[sim_id.to_index()].load(Ordering::Acquire) != SimState::Ready {
|
||||||
let mut audio_samples = vec![];
|
// Can't debug unless a game is connected
|
||||||
loop {
|
return;
|
||||||
let p1_running = self.running[SimId::Player1.to_index()].load(Ordering::Acquire);
|
}
|
||||||
let p2_running = self.running[SimId::Player2.to_index()].load(Ordering::Acquire);
|
let debug = DebugInfo {
|
||||||
let mut idle = p1_running || p2_running;
|
sender,
|
||||||
if p1_running && p2_running {
|
stop_reason: Some(DebugStopReason::Paused),
|
||||||
Sim::emulate_many(&mut self.sims);
|
};
|
||||||
} else if p1_running {
|
self.debuggers.insert(sim_id, debug);
|
||||||
self.sims[SimId::Player1.to_index()].emulate();
|
self.state
|
||||||
} else if p2_running {
|
.store(EmulatorState::Debugging, Ordering::Release);
|
||||||
self.sims[SimId::Player2.to_index()].emulate();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
for sim_id in SimId::values() {
|
fn stop_debugging(&mut self, sim_id: SimId) {
|
||||||
let Some(renderer) = self.renderers.get_mut(&sim_id) else {
|
if let Some(sim) = self.sims.get_mut(sim_id.to_index()) {
|
||||||
continue;
|
sim.clear_debug_state();
|
||||||
};
|
}
|
||||||
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
self.debuggers.remove(&sim_id);
|
||||||
continue;
|
if self.debuggers.is_empty() {
|
||||||
};
|
let _ = self.state.compare_exchange(
|
||||||
if sim.read_pixels(&mut eye_contents) {
|
EmulatorState::Debugging,
|
||||||
idle = false;
|
EmulatorState::Running,
|
||||||
if renderer.queue_render(&eye_contents).is_err() {
|
Ordering::AcqRel,
|
||||||
self.renderers.remove(&sim_id);
|
Ordering::Relaxed,
|
||||||
}
|
);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn debug_interrupt(&mut self, sim_id: SimId) {
|
||||||
|
self.debug_stop(sim_id, DebugStopReason::Paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn debug_stop(&mut self, sim_id: SimId, reason: DebugStopReason) {
|
||||||
|
let Some(debugger) = self.debuggers.get_mut(&sim_id) else {
|
||||||
|
self.stop_debugging(sim_id);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if debugger.stop_reason != Some(reason) {
|
||||||
|
debugger.stop_reason = Some(reason);
|
||||||
|
if debugger.sender.send(DebugEvent::Stopped(reason)).is_err() {
|
||||||
|
self.stop_debugging(sim_id);
|
||||||
}
|
}
|
||||||
let p1_audio =
|
}
|
||||||
p1_running && self.audio_on[SimId::Player1.to_index()].load(Ordering::Acquire);
|
}
|
||||||
let p2_audio =
|
|
||||||
p2_running && self.audio_on[SimId::Player2.to_index()].load(Ordering::Acquire);
|
fn debug_continue(&mut self, sim_id: SimId) -> bool {
|
||||||
let weight = if p1_audio && p2_audio { 0.5 } else { 1.0 };
|
let Some(debugger) = self.debuggers.get_mut(&sim_id) else {
|
||||||
if p1_audio {
|
self.stop_debugging(sim_id);
|
||||||
if let Some(sim) = self.sims.get_mut(SimId::Player1.to_index()) {
|
return false;
|
||||||
sim.read_samples(&mut audio_samples, weight);
|
};
|
||||||
}
|
debugger.stop_reason = None;
|
||||||
}
|
true
|
||||||
if p2_audio {
|
}
|
||||||
if let Some(sim) = self.sims.get_mut(SimId::Player2.to_index()) {
|
fn debug_step(&mut self, sim_id: SimId) {
|
||||||
sim.read_samples(&mut audio_samples, weight);
|
if self.debug_continue(sim_id) {
|
||||||
}
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
}
|
return;
|
||||||
if audio_samples.is_empty() {
|
};
|
||||||
audio_samples.resize(EXPECTED_FRAME_SIZE, 0.0);
|
sim.step();
|
||||||
} else {
|
}
|
||||||
idle = false;
|
}
|
||||||
}
|
|
||||||
self.audio.update(&audio_samples);
|
fn watch_memory(&mut self, range: MemoryRange, region: Weak<MemoryRegion>) {
|
||||||
audio_samples.clear();
|
self.watched_regions.insert(range, region);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(&mut self) {
|
||||||
|
loop {
|
||||||
|
let idle = self.tick();
|
||||||
if idle {
|
if idle {
|
||||||
// The game is paused, and we have output all the video/audio we have.
|
// The game is paused, and we have output all the video/audio we have.
|
||||||
// Block the thread until a new command comes in.
|
// Block the thread until a new command comes in.
|
||||||
@@ -328,9 +403,107 @@ impl Emulator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
self.watched_regions.retain(|range, region| {
|
||||||
|
let Some(region) = region.upgrade() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(sim) = self.sims.get_mut(range.sim.to_index()) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
self.buffer.clear();
|
||||||
|
sim.read_memory(range.start, range.length, &mut self.buffer);
|
||||||
|
region.update(&self.buffer);
|
||||||
|
true
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// returns true if the emulator is "idle" (i.e. this didn't output anything)
|
||||||
|
pub fn tick(&mut self) -> bool {
|
||||||
|
let p1_state = self.sim_state[SimId::Player1.to_index()].load(Ordering::Acquire);
|
||||||
|
let p2_state = self.sim_state[SimId::Player2.to_index()].load(Ordering::Acquire);
|
||||||
|
let state = self.state.load(Ordering::Acquire);
|
||||||
|
|
||||||
|
// Emulation
|
||||||
|
// Don't emulate if the state is "paused", or if any sim is paused in the debugger
|
||||||
|
let running = match state {
|
||||||
|
EmulatorState::Paused => false,
|
||||||
|
EmulatorState::Running => true,
|
||||||
|
EmulatorState::Debugging => self.debuggers.values().all(|d| d.stop_reason.is_none()),
|
||||||
|
};
|
||||||
|
let p1_running = running && p1_state == SimState::Ready;
|
||||||
|
let p2_running = running && p2_state == SimState::Ready;
|
||||||
|
let mut idle = !p1_running && !p2_running;
|
||||||
|
if p1_running && p2_running {
|
||||||
|
Sim::emulate_many(&mut self.sims);
|
||||||
|
} else if p1_running {
|
||||||
|
self.sims[SimId::Player1.to_index()].emulate();
|
||||||
|
} else if p2_running {
|
||||||
|
self.sims[SimId::Player2.to_index()].emulate();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debug state
|
||||||
|
if state == EmulatorState::Debugging {
|
||||||
|
for sim_id in SimId::values() {
|
||||||
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if let Some(reason) = sim.stop_reason() {
|
||||||
|
let stop_reason = match reason {
|
||||||
|
StopReason::Stepped => DebugStopReason::Trace,
|
||||||
|
StopReason::Watchpoint(watch, address) => {
|
||||||
|
DebugStopReason::Watchpoint(watch, address)
|
||||||
|
}
|
||||||
|
StopReason::Breakpoint => DebugStopReason::Breakpoint,
|
||||||
|
};
|
||||||
|
self.debug_stop(sim_id, stop_reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Video
|
||||||
|
for sim_id in SimId::values() {
|
||||||
|
let Some(renderer) = self.renderers.get_mut(&sim_id) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if sim.read_pixels(&mut self.eye_contents) {
|
||||||
|
idle = false;
|
||||||
|
if renderer.queue_render(&self.eye_contents).is_err() {
|
||||||
|
self.renderers.remove(&sim_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Audio
|
||||||
|
// Audio playback speed is how we keep the emulator running in real time.
|
||||||
|
// Even if we're muted, call `read_samples` to know how many frames of silence to play.
|
||||||
|
let p1_audio =
|
||||||
|
p1_running && self.audio_on[SimId::Player1.to_index()].load(Ordering::Acquire);
|
||||||
|
let p2_audio =
|
||||||
|
p2_running && self.audio_on[SimId::Player2.to_index()].load(Ordering::Acquire);
|
||||||
|
let (p1_weight, p2_weight) = match (p1_audio, p2_audio) {
|
||||||
|
(true, true) => (0.5, 0.5),
|
||||||
|
(true, false) => (1.0, 0.0),
|
||||||
|
(false, true) => (0.0, 1.0),
|
||||||
|
(false, false) => (0.0, 0.0),
|
||||||
|
};
|
||||||
|
if let Some(sim) = self.sims.get_mut(SimId::Player1.to_index()) {
|
||||||
|
sim.read_samples(&mut self.audio_samples, p1_weight);
|
||||||
|
}
|
||||||
|
if let Some(sim) = self.sims.get_mut(SimId::Player2.to_index()) {
|
||||||
|
sim.read_samples(&mut self.audio_samples, p2_weight);
|
||||||
|
}
|
||||||
|
if !self.audio_samples.is_empty() {
|
||||||
|
idle = false;
|
||||||
|
}
|
||||||
|
self.audio.update(&self.audio_samples);
|
||||||
|
self.audio_samples.clear();
|
||||||
|
idle
|
||||||
|
}
|
||||||
|
|
||||||
fn handle_command(&mut self, command: EmulatorCommand) {
|
fn handle_command(&mut self, command: EmulatorCommand) {
|
||||||
match command {
|
match command {
|
||||||
EmulatorCommand::ConnectToSim(sim_id, renderer, messages) => {
|
EmulatorCommand::ConnectToSim(sim_id, renderer, messages) => {
|
||||||
@@ -359,19 +532,81 @@ impl Emulator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
EmulatorCommand::Pause => {
|
EmulatorCommand::Pause => {
|
||||||
for sim_id in SimId::values() {
|
if let Err(error) = self.pause_sims() {
|
||||||
if let Err(error) = self.pause_sim(sim_id) {
|
self.report_error(SimId::Player1, format!("Error pausing: {error}"));
|
||||||
self.report_error(sim_id, format!("Error pausing: {error}"));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EmulatorCommand::Resume => {
|
EmulatorCommand::Resume => {
|
||||||
for sim_id in SimId::values() {
|
self.resume_sims();
|
||||||
let index = sim_id.to_index();
|
}
|
||||||
if self.has_game[index].load(Ordering::Acquire) {
|
EmulatorCommand::StartDebugging(sim_id, debugger) => {
|
||||||
self.running[index].store(true, Ordering::Relaxed);
|
self.start_debugging(sim_id, debugger);
|
||||||
}
|
}
|
||||||
}
|
EmulatorCommand::StopDebugging(sim_id) => {
|
||||||
|
self.stop_debugging(sim_id);
|
||||||
|
}
|
||||||
|
EmulatorCommand::DebugInterrupt(sim_id) => {
|
||||||
|
self.debug_interrupt(sim_id);
|
||||||
|
}
|
||||||
|
EmulatorCommand::DebugContinue(sim_id) => {
|
||||||
|
self.debug_continue(sim_id);
|
||||||
|
}
|
||||||
|
EmulatorCommand::DebugStep(sim_id) => {
|
||||||
|
self.debug_step(sim_id);
|
||||||
|
}
|
||||||
|
EmulatorCommand::ReadRegister(sim_id, register, done) => {
|
||||||
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let value = sim.read_register(register);
|
||||||
|
let _ = done.send(value);
|
||||||
|
}
|
||||||
|
EmulatorCommand::WriteRegister(sim_id, register, value) => {
|
||||||
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
sim.write_register(register, value);
|
||||||
|
}
|
||||||
|
EmulatorCommand::ReadMemory(sim_id, start, length, mut buffer, done) => {
|
||||||
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
sim.read_memory(start, length, &mut buffer);
|
||||||
|
let _ = done.send(buffer);
|
||||||
|
}
|
||||||
|
EmulatorCommand::WriteMemory(sim_id, start, buffer, done) => {
|
||||||
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
sim.write_memory(start, &buffer);
|
||||||
|
let _ = done.send(buffer);
|
||||||
|
}
|
||||||
|
EmulatorCommand::WatchMemory(range, region) => {
|
||||||
|
self.watch_memory(range, region);
|
||||||
|
}
|
||||||
|
EmulatorCommand::AddBreakpoint(sim_id, address) => {
|
||||||
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
sim.add_breakpoint(address);
|
||||||
|
}
|
||||||
|
EmulatorCommand::RemoveBreakpoint(sim_id, address) => {
|
||||||
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
sim.remove_breakpoint(address);
|
||||||
|
}
|
||||||
|
EmulatorCommand::AddWatchpoint(sim_id, address, length, watch) => {
|
||||||
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
sim.add_watchpoint(address, length, watch);
|
||||||
|
}
|
||||||
|
EmulatorCommand::RemoveWatchpoint(sim_id, address, length, watch) => {
|
||||||
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
sim.remove_watchpoint(address, length, watch);
|
||||||
}
|
}
|
||||||
EmulatorCommand::SetAudioEnabled(p1, p2) => {
|
EmulatorCommand::SetAudioEnabled(p1, p2) => {
|
||||||
self.audio_on[SimId::Player1.to_index()].store(p1, Ordering::Release);
|
self.audio_on[SimId::Player1.to_index()].store(p1, Ordering::Release);
|
||||||
@@ -418,7 +653,7 @@ impl Emulator {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
eprintln!("{}", message);
|
error!("{}", message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -430,6 +665,20 @@ pub enum EmulatorCommand {
|
|||||||
StopSecondSim,
|
StopSecondSim,
|
||||||
Pause,
|
Pause,
|
||||||
Resume,
|
Resume,
|
||||||
|
StartDebugging(SimId, DebugSender),
|
||||||
|
StopDebugging(SimId),
|
||||||
|
DebugInterrupt(SimId),
|
||||||
|
DebugContinue(SimId),
|
||||||
|
DebugStep(SimId),
|
||||||
|
ReadRegister(SimId, VBRegister, oneshot::Sender<u32>),
|
||||||
|
WriteRegister(SimId, VBRegister, u32),
|
||||||
|
ReadMemory(SimId, u32, usize, Vec<u8>, oneshot::Sender<Vec<u8>>),
|
||||||
|
WriteMemory(SimId, u32, Vec<u8>, oneshot::Sender<Vec<u8>>),
|
||||||
|
WatchMemory(MemoryRange, Weak<MemoryRegion>),
|
||||||
|
AddBreakpoint(SimId, u32),
|
||||||
|
RemoveBreakpoint(SimId, u32),
|
||||||
|
AddWatchpoint(SimId, u32, usize, VBWatchpointType),
|
||||||
|
RemoveWatchpoint(SimId, u32, usize, VBWatchpointType),
|
||||||
SetAudioEnabled(bool, bool),
|
SetAudioEnabled(bool, bool),
|
||||||
Link,
|
Link,
|
||||||
Unlink,
|
Unlink,
|
||||||
@@ -438,37 +687,72 @@ pub enum EmulatorCommand {
|
|||||||
Exit(oneshot::Sender<()>),
|
Exit(oneshot::Sender<()>),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, NoUninit)]
|
||||||
|
#[repr(usize)]
|
||||||
|
pub enum SimState {
|
||||||
|
Uninitialized,
|
||||||
|
NoGame,
|
||||||
|
Ready,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, NoUninit)]
|
||||||
|
#[repr(usize)]
|
||||||
|
pub enum EmulatorState {
|
||||||
|
Paused,
|
||||||
|
Running,
|
||||||
|
Debugging,
|
||||||
|
}
|
||||||
|
|
||||||
|
type DebugSender = tokio::sync::mpsc::UnboundedSender<DebugEvent>;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum DebugStopReason {
|
||||||
|
// We are stepping
|
||||||
|
Trace,
|
||||||
|
// We hit a breakpoint
|
||||||
|
Breakpoint,
|
||||||
|
// We hit a watchpoint
|
||||||
|
Watchpoint(VBWatchpointType, u32),
|
||||||
|
// The debugger told us to pause
|
||||||
|
Paused,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct DebugInfo {
|
||||||
|
sender: DebugSender,
|
||||||
|
stop_reason: Option<DebugStopReason>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum DebugEvent {
|
||||||
|
Stopped(DebugStopReason),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct EmulatorClient {
|
pub struct EmulatorClient {
|
||||||
queue: mpsc::Sender<EmulatorCommand>,
|
queue: mpsc::Sender<EmulatorCommand>,
|
||||||
sim_count: Arc<AtomicUsize>,
|
sim_state: Arc<[Atomic<SimState>; 2]>,
|
||||||
running: Arc<[AtomicBool; 2]>,
|
state: Arc<Atomic<EmulatorState>>,
|
||||||
has_game: Arc<[AtomicBool; 2]>,
|
|
||||||
audio_on: Arc<[AtomicBool; 2]>,
|
audio_on: Arc<[AtomicBool; 2]>,
|
||||||
linked: Arc<AtomicBool>,
|
linked: Arc<AtomicBool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EmulatorClient {
|
impl EmulatorClient {
|
||||||
pub fn has_player_2(&self) -> bool {
|
pub fn sim_state(&self, sim_id: SimId) -> SimState {
|
||||||
self.sim_count.load(Ordering::Acquire) == 2
|
self.sim_state[sim_id.to_index()].load(Ordering::Acquire)
|
||||||
}
|
}
|
||||||
pub fn is_running(&self, sim_id: SimId) -> bool {
|
pub fn emulator_state(&self) -> EmulatorState {
|
||||||
self.running[sim_id.to_index()].load(Ordering::Acquire)
|
self.state.load(Ordering::Acquire)
|
||||||
}
|
|
||||||
pub fn has_game(&self, sim_id: SimId) -> bool {
|
|
||||||
self.has_game[sim_id.to_index()].load(Ordering::Acquire)
|
|
||||||
}
|
|
||||||
pub fn are_sims_linked(&self) -> bool {
|
|
||||||
self.linked.load(Ordering::Acquire)
|
|
||||||
}
|
}
|
||||||
pub fn is_audio_enabled(&self, sim_id: SimId) -> bool {
|
pub fn is_audio_enabled(&self, sim_id: SimId) -> bool {
|
||||||
self.audio_on[sim_id.to_index()].load(Ordering::Acquire)
|
self.audio_on[sim_id.to_index()].load(Ordering::Acquire)
|
||||||
}
|
}
|
||||||
|
pub fn are_sims_linked(&self) -> bool {
|
||||||
|
self.linked.load(Ordering::Acquire)
|
||||||
|
}
|
||||||
pub fn send_command(&self, command: EmulatorCommand) -> bool {
|
pub fn send_command(&self, command: EmulatorCommand) -> bool {
|
||||||
match self.queue.send(command) {
|
match self.queue.send(command) {
|
||||||
Ok(()) => true,
|
Ok(()) => true,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
eprintln!(
|
warn!(
|
||||||
"could not send command {:?} as emulator is shut down",
|
"could not send command {:?} as emulator is shut down",
|
||||||
err.0
|
err.0
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,270 @@
|
|||||||
|
use std::{
|
||||||
|
collections::{BTreeMap, BTreeSet},
|
||||||
|
ops::Bound,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct AddressSet {
|
||||||
|
ranges: BTreeSet<(u32, usize)>,
|
||||||
|
bounds: BTreeMap<u32, usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AddressSet {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add(&mut self, address: u32, length: usize) {
|
||||||
|
if length == 0 || !self.ranges.insert((address, length)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let end = (address as usize)
|
||||||
|
.checked_add(length)
|
||||||
|
.and_then(|e| u32::try_from(e).ok());
|
||||||
|
|
||||||
|
if let Some(end) = end {
|
||||||
|
let val_before = self.bounds.range(..=end).next_back().map_or(0, |(_, &v)| v);
|
||||||
|
self.bounds.insert(end, val_before);
|
||||||
|
}
|
||||||
|
|
||||||
|
let val_before = self
|
||||||
|
.bounds
|
||||||
|
.range(..address)
|
||||||
|
.next_back()
|
||||||
|
.map_or(0, |(_, &v)| v);
|
||||||
|
if let Some(&val_at) = self.bounds.get(&address) {
|
||||||
|
if val_before == val_at + 1 {
|
||||||
|
self.bounds.remove(&address);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.bounds.insert(address, val_before);
|
||||||
|
}
|
||||||
|
|
||||||
|
let start_bound = Bound::Included(address);
|
||||||
|
let end_bound = match end {
|
||||||
|
Some(e) => Bound::Excluded(e),
|
||||||
|
None => Bound::Unbounded,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (_, val) in self.bounds.range_mut((start_bound, end_bound)) {
|
||||||
|
*val += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(&mut self, address: u32, length: usize) {
|
||||||
|
if !self.ranges.remove(&(address, length)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let end = (address as usize)
|
||||||
|
.checked_add(length)
|
||||||
|
.and_then(|e| u32::try_from(e).ok());
|
||||||
|
|
||||||
|
if let Some(end) = end {
|
||||||
|
let val_before = self.bounds.range(..end).next_back().map_or(0, |(_, &v)| v);
|
||||||
|
if let Some(&val_at) = self.bounds.get(&end) {
|
||||||
|
if val_at + 1 == val_before {
|
||||||
|
self.bounds.remove(&end);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.bounds.insert(end, val_before);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let val_before = self
|
||||||
|
.bounds
|
||||||
|
.range(..address)
|
||||||
|
.next_back()
|
||||||
|
.map_or(0, |(_, &v)| v);
|
||||||
|
if let Some(&val_at) = self.bounds.get(&address) {
|
||||||
|
if val_before + 1 == val_at {
|
||||||
|
self.bounds.remove(&address);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.bounds.insert(address, val_before);
|
||||||
|
}
|
||||||
|
|
||||||
|
let start_bound = Bound::Included(address);
|
||||||
|
let end_bound = match end {
|
||||||
|
Some(e) => Bound::Excluded(e),
|
||||||
|
None => Bound::Unbounded,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (_, val) in self.bounds.range_mut((start_bound, end_bound)) {
|
||||||
|
*val -= 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear(&mut self) {
|
||||||
|
self.ranges.clear();
|
||||||
|
self.bounds.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.bounds.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, address: u32) -> bool {
|
||||||
|
self.bounds
|
||||||
|
.range(..=address)
|
||||||
|
.next_back()
|
||||||
|
.is_some_and(|(_, &val)| val > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start_of_range_containing(&self, address: u32) -> Option<u32> {
|
||||||
|
if !self.contains(address) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.ranges
|
||||||
|
.range(..=(address, usize::MAX))
|
||||||
|
.rev()
|
||||||
|
.find_map(|&(start, length)| {
|
||||||
|
let contains = start <= address
|
||||||
|
&& (start as usize)
|
||||||
|
.checked_add(length)
|
||||||
|
.is_none_or(|end| end > address as usize);
|
||||||
|
contains.then_some(start)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::AddressSet;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_not_include_addresses_when_empty() {
|
||||||
|
let set = AddressSet::new();
|
||||||
|
assert!(set.is_empty());
|
||||||
|
assert!(!set.contains(0x13374200));
|
||||||
|
assert_eq!(set.start_of_range_containing(0x13374200), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_include_addresses_when_full() {
|
||||||
|
let mut set = AddressSet::new();
|
||||||
|
set.add(0x00000000, 0x100000000);
|
||||||
|
assert!(set.contains(0x13374200));
|
||||||
|
assert_eq!(set.start_of_range_containing(0x13374200), Some(0x00000000));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_ignore_empty_address_ranges() {
|
||||||
|
let mut set = AddressSet::new();
|
||||||
|
set.add(0x13374200, 0);
|
||||||
|
assert!(set.is_empty());
|
||||||
|
assert!(!set.contains(0x13374200));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_add_addresses_idempotently() {
|
||||||
|
let mut set = AddressSet::new();
|
||||||
|
set.add(0x13374200, 1);
|
||||||
|
set.add(0x13374200, 1);
|
||||||
|
set.remove(0x13374200, 1);
|
||||||
|
assert!(set.is_empty());
|
||||||
|
assert!(!set.contains(0x13374200));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_remove_addresses_idempotently() {
|
||||||
|
let mut set = AddressSet::new();
|
||||||
|
set.add(0x13374200, 1);
|
||||||
|
set.remove(0x13374200, 1);
|
||||||
|
set.remove(0x13374200, 1);
|
||||||
|
assert!(set.is_empty());
|
||||||
|
assert!(!set.contains(0x13374200));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_report_address_in_range() {
|
||||||
|
let mut set = AddressSet::new();
|
||||||
|
set.add(0x13374200, 4);
|
||||||
|
assert!(!set.contains(0x133741ff));
|
||||||
|
for address in 0x13374200..0x13374204 {
|
||||||
|
assert!(set.contains(address));
|
||||||
|
}
|
||||||
|
assert!(!set.contains(0x13374204));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_allow_overlapping_addresses() {
|
||||||
|
let mut set = AddressSet::new();
|
||||||
|
set.add(0x13374200, 4);
|
||||||
|
set.add(0x13374201, 1);
|
||||||
|
set.add(0x13374202, 2);
|
||||||
|
|
||||||
|
assert!(!set.contains(0x133741ff));
|
||||||
|
for address in 0x13374200..0x13374204 {
|
||||||
|
assert!(set.contains(address));
|
||||||
|
}
|
||||||
|
assert!(!set.contains(0x13374204));
|
||||||
|
|
||||||
|
set.remove(0x13374200, 4);
|
||||||
|
assert!(!set.contains(0x13374200));
|
||||||
|
for address in 0x13374201..0x13374204 {
|
||||||
|
assert!(set.contains(address));
|
||||||
|
}
|
||||||
|
assert!(!set.contains(0x13374204));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_allow_removing_overlapped_address_ranges() {
|
||||||
|
let mut set = AddressSet::new();
|
||||||
|
set.add(0x13374200, 8);
|
||||||
|
set.add(0x13374204, 8);
|
||||||
|
set.remove(0x13374204, 8);
|
||||||
|
|
||||||
|
for address in 0x13374200..0x13374208 {
|
||||||
|
assert!(set.contains(address));
|
||||||
|
}
|
||||||
|
for address in 0x13374208..0x1337420c {
|
||||||
|
assert!(!set.contains(address));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_merge_adjacent_ranges() {
|
||||||
|
let mut set = AddressSet::new();
|
||||||
|
set.add(0x13374200, 4);
|
||||||
|
set.add(0x13374204, 4);
|
||||||
|
set.add(0x13374208, 4);
|
||||||
|
set.add(0x1337420c, 4);
|
||||||
|
|
||||||
|
assert!(!set.contains(0x133741ff));
|
||||||
|
for address in 0x13374200..0x13374210 {
|
||||||
|
assert!(set.contains(address));
|
||||||
|
}
|
||||||
|
assert!(!set.contains(0x13374210));
|
||||||
|
|
||||||
|
set.remove(0x13374200, 4);
|
||||||
|
set.remove(0x13374204, 4);
|
||||||
|
set.remove(0x13374208, 4);
|
||||||
|
set.remove(0x1337420c, 4);
|
||||||
|
|
||||||
|
assert!(set.is_empty());
|
||||||
|
for address in 0x133741ff..=0x13374210 {
|
||||||
|
assert!(!set.contains(address));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_find_start_of_range() {
|
||||||
|
let mut set = AddressSet::new();
|
||||||
|
set.add(0x13374200, 4);
|
||||||
|
assert_eq!(set.start_of_range_containing(0x133741ff), None);
|
||||||
|
for address in 0x13374200..0x13374204 {
|
||||||
|
assert_eq!(set.start_of_range_containing(address), Some(0x13374200));
|
||||||
|
}
|
||||||
|
assert_eq!(set.start_of_range_containing(0x13374204), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_ignore_ranges_not_containing_address() {
|
||||||
|
let mut set = AddressSet::new();
|
||||||
|
set.add(0x10000000, 1024);
|
||||||
|
set.add(0x30000000, 1024);
|
||||||
|
|
||||||
|
assert!(!set.contains(0x20000000));
|
||||||
|
assert_eq!(set.start_of_range_containing(0x20000000), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
+329
-11
@@ -5,6 +5,8 @@ use bitflags::bitflags;
|
|||||||
use num_derive::{FromPrimitive, ToPrimitive};
|
use num_derive::{FromPrimitive, ToPrimitive};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use super::address_set::AddressSet;
|
||||||
|
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
struct VB {
|
struct VB {
|
||||||
_data: [u8; 0],
|
_data: [u8; 0],
|
||||||
@@ -55,7 +57,38 @@ bitflags! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub enum VBRegister {
|
||||||
|
Program(u32),
|
||||||
|
System(u32),
|
||||||
|
PC,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum VBWatchpointType {
|
||||||
|
Read,
|
||||||
|
Write,
|
||||||
|
Access,
|
||||||
|
}
|
||||||
|
|
||||||
|
type OnExecute =
|
||||||
|
extern "C" fn(sim: *mut VB, address: u32, code: *const u16, length: c_int) -> c_int;
|
||||||
type OnFrame = extern "C" fn(sim: *mut VB) -> c_int;
|
type OnFrame = extern "C" fn(sim: *mut VB) -> c_int;
|
||||||
|
type OnRead = extern "C" fn(
|
||||||
|
sim: *mut VB,
|
||||||
|
address: u32,
|
||||||
|
type_: VBDataType,
|
||||||
|
value: *mut i32,
|
||||||
|
cycles: *mut u32,
|
||||||
|
) -> c_int;
|
||||||
|
type OnWrite = extern "C" fn(
|
||||||
|
sim: *mut VB,
|
||||||
|
address: u32,
|
||||||
|
type_: VBDataType,
|
||||||
|
value: *mut i32,
|
||||||
|
cycles: *mut u32,
|
||||||
|
cancel: *mut c_int,
|
||||||
|
) -> c_int;
|
||||||
|
|
||||||
#[link(name = "vb")]
|
#[link(name = "vb")]
|
||||||
extern "C" {
|
extern "C" {
|
||||||
@@ -77,6 +110,10 @@ extern "C" {
|
|||||||
right_stride_x: c_int,
|
right_stride_x: c_int,
|
||||||
right_stride_y: c_int,
|
right_stride_y: c_int,
|
||||||
);
|
);
|
||||||
|
#[link_name = "vbGetProgramCounter"]
|
||||||
|
fn vb_get_program_counter(sim: *mut VB) -> u32;
|
||||||
|
#[link_name = "vbGetProgramRegister"]
|
||||||
|
fn vb_get_program_register(sim: *mut VB, index: c_uint) -> i32;
|
||||||
#[link_name = "vbGetSamples"]
|
#[link_name = "vbGetSamples"]
|
||||||
fn vb_get_samples(
|
fn vb_get_samples(
|
||||||
sim: *mut VB,
|
sim: *mut VB,
|
||||||
@@ -84,24 +121,36 @@ extern "C" {
|
|||||||
capacity: *mut c_uint,
|
capacity: *mut c_uint,
|
||||||
position: *mut c_uint,
|
position: *mut c_uint,
|
||||||
) -> *mut c_void;
|
) -> *mut c_void;
|
||||||
|
#[link_name = "vbGetSystemRegister"]
|
||||||
|
fn vb_get_system_register(sim: *mut VB, index: c_uint) -> i32;
|
||||||
#[link_name = "vbGetUserData"]
|
#[link_name = "vbGetUserData"]
|
||||||
fn vb_get_user_data(sim: *mut VB) -> *mut c_void;
|
fn vb_get_user_data(sim: *mut VB) -> *mut c_void;
|
||||||
#[link_name = "vbInit"]
|
#[link_name = "vbInit"]
|
||||||
fn vb_init(sim: *mut VB) -> *mut VB;
|
fn vb_init(sim: *mut VB) -> *mut VB;
|
||||||
|
#[link_name = "vbRead"]
|
||||||
|
fn vb_read(sim: *mut VB, address: u32, typ_: VBDataType) -> i32;
|
||||||
#[link_name = "vbReset"]
|
#[link_name = "vbReset"]
|
||||||
fn vb_reset(sim: *mut VB);
|
fn vb_reset(sim: *mut VB);
|
||||||
#[link_name = "vbSetCartRAM"]
|
#[link_name = "vbSetCartRAM"]
|
||||||
fn vb_set_cart_ram(sim: *mut VB, sram: *mut c_void, size: u32) -> c_int;
|
fn vb_set_cart_ram(sim: *mut VB, sram: *mut c_void, size: u32) -> c_int;
|
||||||
#[link_name = "vbSetCartROM"]
|
#[link_name = "vbSetCartROM"]
|
||||||
fn vb_set_cart_rom(sim: *mut VB, rom: *mut c_void, size: u32) -> c_int;
|
fn vb_set_cart_rom(sim: *mut VB, rom: *mut c_void, size: u32) -> c_int;
|
||||||
|
#[link_name = "vbSetExecuteCallback"]
|
||||||
|
fn vb_set_execute_callback(sim: *mut VB, callback: Option<OnExecute>) -> Option<OnExecute>;
|
||||||
#[link_name = "vbSetFrameCallback"]
|
#[link_name = "vbSetFrameCallback"]
|
||||||
fn vb_set_frame_callback(sim: *mut VB, on_frame: OnFrame);
|
fn vb_set_frame_callback(sim: *mut VB, callback: Option<OnFrame>) -> Option<OnFrame>;
|
||||||
#[link_name = "vbSetKeys"]
|
#[link_name = "vbSetKeys"]
|
||||||
fn vb_set_keys(sim: *mut VB, keys: u16) -> u16;
|
fn vb_set_keys(sim: *mut VB, keys: u16) -> u16;
|
||||||
#[link_name = "vbSetOption"]
|
#[link_name = "vbSetOption"]
|
||||||
fn vb_set_option(sim: *mut VB, key: VBOption, value: c_int);
|
fn vb_set_option(sim: *mut VB, key: VBOption, value: c_int);
|
||||||
#[link_name = "vbSetPeer"]
|
#[link_name = "vbSetPeer"]
|
||||||
fn vb_set_peer(sim: *mut VB, peer: *mut VB);
|
fn vb_set_peer(sim: *mut VB, peer: *mut VB);
|
||||||
|
#[link_name = "vbSetProgramCounter"]
|
||||||
|
fn vb_set_program_counter(sim: *mut VB, value: u32) -> u32;
|
||||||
|
#[link_name = "vbSetProgramRegister"]
|
||||||
|
fn vb_set_program_register(sim: *mut VB, index: c_uint, value: i32) -> i32;
|
||||||
|
#[link_name = "vbSetReadCallback"]
|
||||||
|
fn vb_set_read_callback(sim: *mut VB, callback: Option<OnRead>) -> Option<OnRead>;
|
||||||
#[link_name = "vbSetSamples"]
|
#[link_name = "vbSetSamples"]
|
||||||
fn vb_set_samples(
|
fn vb_set_samples(
|
||||||
sim: *mut VB,
|
sim: *mut VB,
|
||||||
@@ -109,13 +158,20 @@ extern "C" {
|
|||||||
typ_: VBDataType,
|
typ_: VBDataType,
|
||||||
capacity: c_uint,
|
capacity: c_uint,
|
||||||
) -> c_int;
|
) -> c_int;
|
||||||
|
#[link_name = "vbSetSystemRegister"]
|
||||||
|
fn vb_set_system_register(sim: *mut VB, index: c_uint, value: u32) -> u32;
|
||||||
#[link_name = "vbSetUserData"]
|
#[link_name = "vbSetUserData"]
|
||||||
fn vb_set_user_data(sim: *mut VB, tag: *mut c_void);
|
fn vb_set_user_data(sim: *mut VB, tag: *mut c_void);
|
||||||
|
#[link_name = "vbSetWriteCallback"]
|
||||||
|
fn vb_set_write_callback(sim: *mut VB, callback: Option<OnWrite>) -> Option<OnWrite>;
|
||||||
#[link_name = "vbSizeOf"]
|
#[link_name = "vbSizeOf"]
|
||||||
fn vb_size_of() -> usize;
|
fn vb_size_of() -> usize;
|
||||||
|
#[link_name = "vbWrite"]
|
||||||
|
fn vb_write(sim: *mut VB, address: u32, _type: VBDataType, value: i32) -> i32;
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "C" fn on_frame(sim: *mut VB) -> i32 {
|
#[no_mangle]
|
||||||
|
extern "C" fn on_frame(sim: *mut VB) -> c_int {
|
||||||
// SAFETY: the *mut VB owns its userdata.
|
// SAFETY: the *mut VB owns its userdata.
|
||||||
// There is no way for the userdata to be null or otherwise invalid.
|
// There is no way for the userdata to be null or otherwise invalid.
|
||||||
let data: &mut VBState = unsafe { &mut *vb_get_user_data(sim).cast() };
|
let data: &mut VBState = unsafe { &mut *vb_get_user_data(sim).cast() };
|
||||||
@@ -123,12 +179,109 @@ extern "C" fn on_frame(sim: *mut VB) -> i32 {
|
|||||||
1
|
1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[no_mangle]
|
||||||
|
extern "C" fn on_execute(sim: *mut VB, address: u32, _code: *const u16, _length: c_int) -> c_int {
|
||||||
|
// SAFETY: the *mut VB owns its userdata.
|
||||||
|
// There is no way for the userdata to be null or otherwise invalid.
|
||||||
|
let data: &mut VBState = unsafe { &mut *vb_get_user_data(sim).cast() };
|
||||||
|
|
||||||
|
let mut stopped = data.stop_reason.is_some();
|
||||||
|
if data.step_from.is_some_and(|s| s != address) {
|
||||||
|
data.step_from = None;
|
||||||
|
data.stop_reason = Some(StopReason::Stepped);
|
||||||
|
stopped = true;
|
||||||
|
}
|
||||||
|
if data.breakpoints.binary_search(&address).is_ok() {
|
||||||
|
data.stop_reason = Some(StopReason::Breakpoint);
|
||||||
|
stopped = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if stopped {
|
||||||
|
1
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[no_mangle]
|
||||||
|
extern "C" fn on_read(
|
||||||
|
sim: *mut VB,
|
||||||
|
address: u32,
|
||||||
|
_type: VBDataType,
|
||||||
|
_value: *mut i32,
|
||||||
|
_cycles: *mut u32,
|
||||||
|
) -> c_int {
|
||||||
|
// SAFETY: the *mut VB owns its userdata.
|
||||||
|
// There is no way for the userdata to be null or otherwise invalid.
|
||||||
|
let data: &mut VBState = unsafe { &mut *vb_get_user_data(sim).cast() };
|
||||||
|
|
||||||
|
if let Some(start) = data.read_watchpoints.start_of_range_containing(address) {
|
||||||
|
let watch = if data.write_watchpoints.contains(address) {
|
||||||
|
VBWatchpointType::Access
|
||||||
|
} else {
|
||||||
|
VBWatchpointType::Read
|
||||||
|
};
|
||||||
|
data.stop_reason = Some(StopReason::Watchpoint(watch, start));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Don't stop here, the debugger expects us to break after the memory access.
|
||||||
|
// We'll stop in on_execute instead.
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
|
#[no_mangle]
|
||||||
|
extern "C" fn on_write(
|
||||||
|
sim: *mut VB,
|
||||||
|
address: u32,
|
||||||
|
_type: VBDataType,
|
||||||
|
_value: *mut i32,
|
||||||
|
_cycles: *mut u32,
|
||||||
|
_cancel: *mut c_int,
|
||||||
|
) -> c_int {
|
||||||
|
// SAFETY: the *mut VB owns its userdata.
|
||||||
|
// There is no way for the userdata to be null or otherwise invalid.
|
||||||
|
let data: &mut VBState = unsafe { &mut *vb_get_user_data(sim).cast() };
|
||||||
|
|
||||||
|
if let Some(start) = data.write_watchpoints.start_of_range_containing(address) {
|
||||||
|
let watch = if data.read_watchpoints.contains(address) {
|
||||||
|
VBWatchpointType::Access
|
||||||
|
} else {
|
||||||
|
VBWatchpointType::Write
|
||||||
|
};
|
||||||
|
data.stop_reason = Some(StopReason::Watchpoint(watch, start));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Don't stop here, the debugger expects us to break after the memory access.
|
||||||
|
// We'll stop in on_execute instead.
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
const AUDIO_CAPACITY_SAMPLES: usize = 834 * 4;
|
const AUDIO_CAPACITY_SAMPLES: usize = 834 * 4;
|
||||||
const AUDIO_CAPACITY_FLOATS: usize = AUDIO_CAPACITY_SAMPLES * 2;
|
const AUDIO_CAPACITY_FLOATS: usize = AUDIO_CAPACITY_SAMPLES * 2;
|
||||||
pub const EXPECTED_FRAME_SIZE: usize = 834 * 2;
|
pub const EXPECTED_FRAME_SIZE: usize = 834 * 2;
|
||||||
|
|
||||||
struct VBState {
|
struct VBState {
|
||||||
frame_seen: bool,
|
frame_seen: bool,
|
||||||
|
stop_reason: Option<StopReason>,
|
||||||
|
step_from: Option<u32>,
|
||||||
|
breakpoints: Vec<u32>,
|
||||||
|
read_watchpoints: AddressSet,
|
||||||
|
write_watchpoints: AddressSet,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VBState {
|
||||||
|
fn needs_execute_callback(&self) -> bool {
|
||||||
|
self.step_from.is_some()
|
||||||
|
|| !self.breakpoints.is_empty()
|
||||||
|
|| !self.read_watchpoints.is_empty()
|
||||||
|
|| !self.write_watchpoints.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum StopReason {
|
||||||
|
Breakpoint,
|
||||||
|
Watchpoint(VBWatchpointType, u32),
|
||||||
|
Stepped,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[repr(transparent)]
|
#[repr(transparent)]
|
||||||
@@ -136,9 +289,6 @@ pub struct Sim {
|
|||||||
sim: *mut VB,
|
sim: *mut VB,
|
||||||
}
|
}
|
||||||
|
|
||||||
// SAFETY: the memory pointed to by sim is valid
|
|
||||||
unsafe impl Send for Sim {}
|
|
||||||
|
|
||||||
impl Sim {
|
impl Sim {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
// init the VB instance itself
|
// init the VB instance itself
|
||||||
@@ -147,13 +297,22 @@ impl Sim {
|
|||||||
let memory = vec![0u64; size.div_ceil(4)];
|
let memory = vec![0u64; size.div_ceil(4)];
|
||||||
let sim: *mut VB = Box::into_raw(memory.into_boxed_slice()).cast();
|
let sim: *mut VB = Box::into_raw(memory.into_boxed_slice()).cast();
|
||||||
unsafe { vb_init(sim) };
|
unsafe { vb_init(sim) };
|
||||||
unsafe { vb_set_option(sim, VBOption::PseudoHalt, 1) };
|
// pseudohalt is disabled due to breaking red alarm
|
||||||
|
unsafe { vb_set_option(sim, VBOption::PseudoHalt, 0) };
|
||||||
|
unsafe { vb_set_keys(sim, VBKey::SGN.bits()) };
|
||||||
unsafe { vb_reset(sim) };
|
unsafe { vb_reset(sim) };
|
||||||
|
|
||||||
// set up userdata
|
// set up userdata
|
||||||
let state = VBState { frame_seen: false };
|
let state = VBState {
|
||||||
|
frame_seen: false,
|
||||||
|
stop_reason: None,
|
||||||
|
step_from: None,
|
||||||
|
breakpoints: vec![],
|
||||||
|
read_watchpoints: AddressSet::new(),
|
||||||
|
write_watchpoints: AddressSet::new(),
|
||||||
|
};
|
||||||
unsafe { vb_set_user_data(sim, Box::into_raw(Box::new(state)).cast()) };
|
unsafe { vb_set_user_data(sim, Box::into_raw(Box::new(state)).cast()) };
|
||||||
unsafe { vb_set_frame_callback(sim, on_frame) };
|
unsafe { vb_set_frame_callback(sim, Some(on_frame)) };
|
||||||
|
|
||||||
// set up audio buffer
|
// set up audio buffer
|
||||||
let audio_buffer = vec![0.0f32; AUDIO_CAPACITY_FLOATS];
|
let audio_buffer = vec![0.0f32; AUDIO_CAPACITY_FLOATS];
|
||||||
@@ -242,9 +401,7 @@ impl Sim {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn read_pixels(&mut self, buffers: &mut [u8]) -> bool {
|
pub fn read_pixels(&mut self, buffers: &mut [u8]) -> bool {
|
||||||
// SAFETY: the *mut VB owns its userdata.
|
let data = self.get_state();
|
||||||
// There is no way for the userdata to be null or otherwise invalid.
|
|
||||||
let data: &mut VBState = unsafe { &mut *vb_get_user_data(self.sim).cast() };
|
|
||||||
if !data.frame_seen {
|
if !data.frame_seen {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -291,6 +448,167 @@ impl Sim {
|
|||||||
pub fn set_keys(&mut self, keys: VBKey) {
|
pub fn set_keys(&mut self, keys: VBKey) {
|
||||||
unsafe { vb_set_keys(self.sim, keys.bits()) };
|
unsafe { vb_set_keys(self.sim, keys.bits()) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn read_register(&mut self, register: VBRegister) -> u32 {
|
||||||
|
match register {
|
||||||
|
VBRegister::Program(index) => unsafe {
|
||||||
|
vb_get_program_register(self.sim, index) as u32
|
||||||
|
},
|
||||||
|
VBRegister::System(index) => unsafe { vb_get_system_register(self.sim, index) as u32 },
|
||||||
|
VBRegister::PC => unsafe { vb_get_program_counter(self.sim) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_register(&mut self, register: VBRegister, value: u32) {
|
||||||
|
match register {
|
||||||
|
VBRegister::Program(index) => unsafe {
|
||||||
|
vb_set_program_register(self.sim, index, value as i32);
|
||||||
|
},
|
||||||
|
VBRegister::System(index) => unsafe {
|
||||||
|
vb_set_system_register(self.sim, index, value);
|
||||||
|
},
|
||||||
|
VBRegister::PC => unsafe {
|
||||||
|
vb_set_program_counter(self.sim, value);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_memory(&mut self, start: u32, length: usize, into: &mut Vec<u8>) {
|
||||||
|
let mut address = start;
|
||||||
|
for _ in 0..length {
|
||||||
|
let byte = unsafe { vb_read(self.sim, address, VBDataType::U8) };
|
||||||
|
into.push(byte as u8);
|
||||||
|
address = address.wrapping_add(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_memory(&mut self, start: u32, buffer: &[u8]) {
|
||||||
|
let mut address = start;
|
||||||
|
for byte in buffer {
|
||||||
|
unsafe { vb_write(self.sim, address, VBDataType::U8, *byte as i32) };
|
||||||
|
address = address.wrapping_add(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_breakpoint(&mut self, address: u32) {
|
||||||
|
let data = self.get_state();
|
||||||
|
if let Err(index) = data.breakpoints.binary_search(&address) {
|
||||||
|
data.breakpoints.insert(index, address);
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
vb_set_execute_callback(self.sim, Some(on_execute));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_breakpoint(&mut self, address: u32) {
|
||||||
|
let data = self.get_state();
|
||||||
|
if let Ok(index) = data.breakpoints.binary_search(&address) {
|
||||||
|
data.breakpoints.remove(index);
|
||||||
|
if !data.needs_execute_callback() {
|
||||||
|
unsafe { vb_set_execute_callback(self.sim, None) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_watchpoint(&mut self, address: u32, length: usize, watch: VBWatchpointType) {
|
||||||
|
match watch {
|
||||||
|
VBWatchpointType::Read => self.add_read_watchpoint(address, length),
|
||||||
|
VBWatchpointType::Write => self.add_write_watchpoint(address, length),
|
||||||
|
VBWatchpointType::Access => {
|
||||||
|
self.add_read_watchpoint(address, length);
|
||||||
|
self.add_write_watchpoint(address, length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_read_watchpoint(&mut self, address: u32, length: usize) {
|
||||||
|
let state = self.get_state();
|
||||||
|
state.read_watchpoints.add(address, length);
|
||||||
|
if !state.read_watchpoints.is_empty() {
|
||||||
|
unsafe { vb_set_read_callback(self.sim, Some(on_read)) };
|
||||||
|
unsafe { vb_set_execute_callback(self.sim, Some(on_execute)) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_write_watchpoint(&mut self, address: u32, length: usize) {
|
||||||
|
let state = self.get_state();
|
||||||
|
state.write_watchpoints.add(address, length);
|
||||||
|
if !state.write_watchpoints.is_empty() {
|
||||||
|
unsafe { vb_set_write_callback(self.sim, Some(on_write)) };
|
||||||
|
unsafe { vb_set_execute_callback(self.sim, Some(on_execute)) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_watchpoint(&mut self, address: u32, length: usize, watch: VBWatchpointType) {
|
||||||
|
match watch {
|
||||||
|
VBWatchpointType::Read => self.remove_read_watchpoint(address, length),
|
||||||
|
VBWatchpointType::Write => self.remove_write_watchpoint(address, length),
|
||||||
|
VBWatchpointType::Access => {
|
||||||
|
self.remove_read_watchpoint(address, length);
|
||||||
|
self.remove_write_watchpoint(address, length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_read_watchpoint(&mut self, address: u32, length: usize) {
|
||||||
|
let state = self.get_state();
|
||||||
|
state.read_watchpoints.remove(address, length);
|
||||||
|
let needs_execute = state.needs_execute_callback();
|
||||||
|
if state.read_watchpoints.is_empty() {
|
||||||
|
unsafe { vb_set_read_callback(self.sim, None) };
|
||||||
|
if !needs_execute {
|
||||||
|
unsafe { vb_set_execute_callback(self.sim, None) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_write_watchpoint(&mut self, address: u32, length: usize) {
|
||||||
|
let state = self.get_state();
|
||||||
|
state.write_watchpoints.remove(address, length);
|
||||||
|
let needs_execute = state.needs_execute_callback();
|
||||||
|
if state.write_watchpoints.is_empty() {
|
||||||
|
unsafe { vb_set_write_callback(self.sim, None) };
|
||||||
|
if !needs_execute {
|
||||||
|
unsafe { vb_set_execute_callback(self.sim, None) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn step(&mut self) {
|
||||||
|
let current_pc = unsafe { vb_get_program_counter(self.sim) };
|
||||||
|
let data = self.get_state();
|
||||||
|
data.step_from = Some(current_pc);
|
||||||
|
unsafe {
|
||||||
|
vb_set_execute_callback(self.sim, Some(on_execute));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_debug_state(&mut self) {
|
||||||
|
let data = self.get_state();
|
||||||
|
data.step_from = None;
|
||||||
|
data.breakpoints.clear();
|
||||||
|
data.read_watchpoints.clear();
|
||||||
|
data.write_watchpoints.clear();
|
||||||
|
unsafe { vb_set_read_callback(self.sim, None) };
|
||||||
|
unsafe { vb_set_write_callback(self.sim, None) };
|
||||||
|
unsafe { vb_set_execute_callback(self.sim, None) };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop_reason(&mut self) -> Option<StopReason> {
|
||||||
|
let data = self.get_state();
|
||||||
|
let reason = data.stop_reason.take();
|
||||||
|
if !data.needs_execute_callback() {
|
||||||
|
unsafe { vb_set_execute_callback(self.sim, None) };
|
||||||
|
}
|
||||||
|
reason
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_state(&mut self) -> &mut VBState {
|
||||||
|
// SAFETY: the *mut VB owns its userdata.
|
||||||
|
// There is no way for the userdata to be null or otherwise invalid.
|
||||||
|
unsafe { &mut *vb_get_user_data(self.sim).cast() }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Sim {
|
impl Drop for Sim {
|
||||||
|
|||||||
@@ -0,0 +1,560 @@
|
|||||||
|
use anyhow::{bail, Result};
|
||||||
|
use registers::REGISTERS;
|
||||||
|
use request::{Request, RequestKind, RequestSource};
|
||||||
|
use response::Response;
|
||||||
|
use std::{
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
thread,
|
||||||
|
};
|
||||||
|
use tokio::{
|
||||||
|
io::{AsyncWriteExt as _, BufReader},
|
||||||
|
net::{TcpListener, TcpStream},
|
||||||
|
pin, select,
|
||||||
|
sync::{mpsc, oneshot},
|
||||||
|
};
|
||||||
|
use tracing::{debug, enabled, error, info, Level};
|
||||||
|
|
||||||
|
use crate::emulator::{
|
||||||
|
DebugEvent, DebugStopReason, EmulatorClient, EmulatorCommand, SimId, VBWatchpointType,
|
||||||
|
};
|
||||||
|
|
||||||
|
mod registers;
|
||||||
|
mod request;
|
||||||
|
mod response;
|
||||||
|
|
||||||
|
pub struct GdbServer {
|
||||||
|
sim_id: SimId,
|
||||||
|
client: EmulatorClient,
|
||||||
|
status: Arc<Mutex<GdbServerStatus>>,
|
||||||
|
killer: Option<oneshot::Sender<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GdbServer {
|
||||||
|
pub fn new(sim_id: SimId, client: EmulatorClient) -> Self {
|
||||||
|
Self {
|
||||||
|
sim_id,
|
||||||
|
client,
|
||||||
|
status: Arc::new(Mutex::new(GdbServerStatus::Stopped)),
|
||||||
|
killer: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn status(&self) -> GdbServerStatus {
|
||||||
|
self.status.lock().unwrap().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start(&mut self, port: u16) {
|
||||||
|
*self.status.lock().unwrap() = GdbServerStatus::Connecting;
|
||||||
|
let sim_id = self.sim_id;
|
||||||
|
let client = self.client.clone();
|
||||||
|
let status = self.status.clone();
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
self.killer = Some(tx);
|
||||||
|
thread::spawn(move || {
|
||||||
|
tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap()
|
||||||
|
.block_on(async move {
|
||||||
|
select! {
|
||||||
|
_ = run_server(sim_id, client.clone(), port, &status) => {}
|
||||||
|
_ = rx => {
|
||||||
|
client.send_command(EmulatorCommand::StopDebugging(sim_id));
|
||||||
|
*status.lock().unwrap() = GdbServerStatus::Stopped;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop(&mut self) {
|
||||||
|
if let Some(killer) = self.killer.take() {
|
||||||
|
let _ = killer.send(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for GdbServer {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_server(
|
||||||
|
sim_id: SimId,
|
||||||
|
client: EmulatorClient,
|
||||||
|
port: u16,
|
||||||
|
status: &Mutex<GdbServerStatus>,
|
||||||
|
) {
|
||||||
|
let (debug_sink, mut debug_source) = mpsc::unbounded_channel();
|
||||||
|
client.send_command(EmulatorCommand::StartDebugging(sim_id, debug_sink));
|
||||||
|
|
||||||
|
info!("Connecting to debugger on port {port}...");
|
||||||
|
let connect_future = try_connect(port, status);
|
||||||
|
pin!(connect_future);
|
||||||
|
|
||||||
|
let stream = loop {
|
||||||
|
select! {
|
||||||
|
stream = &mut connect_future => {
|
||||||
|
if let Some(stream) = stream {
|
||||||
|
break stream;
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
event = debug_source.recv() => {
|
||||||
|
if event.is_none() {
|
||||||
|
// The sim has stopped (or was never started)
|
||||||
|
*status.lock().unwrap() = GdbServerStatus::Stopped;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
info!("Connected!");
|
||||||
|
let mut connection = GdbConnection::new(sim_id, client);
|
||||||
|
match connection.run(stream, debug_source).await {
|
||||||
|
Ok(()) => {
|
||||||
|
info!("Finished debugging.");
|
||||||
|
*status.lock().unwrap() = GdbServerStatus::Stopped;
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
error!(%error, "Error from debugger.");
|
||||||
|
*status.lock().unwrap() = GdbServerStatus::Error(error.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn try_connect(port: u16, status: &Mutex<GdbServerStatus>) -> Option<TcpStream> {
|
||||||
|
*status.lock().unwrap() = GdbServerStatus::Connecting;
|
||||||
|
let listener = match TcpListener::bind(("127.0.0.1", port)).await {
|
||||||
|
Ok(l) => l,
|
||||||
|
Err(err) => {
|
||||||
|
error!(%err, "Could not open port.");
|
||||||
|
*status.lock().unwrap() = GdbServerStatus::Error(err.to_string());
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match listener.accept().await {
|
||||||
|
Ok((stream, _)) => {
|
||||||
|
*status.lock().unwrap() = GdbServerStatus::Running;
|
||||||
|
Some(stream)
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
error!(%err, "Could not connect to debugger.");
|
||||||
|
*status.lock().unwrap() = GdbServerStatus::Error(err.to_string());
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum GdbServerStatus {
|
||||||
|
Stopped,
|
||||||
|
Connecting,
|
||||||
|
Running,
|
||||||
|
Error(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GdbServerStatus {
|
||||||
|
pub fn running(&self) -> bool {
|
||||||
|
matches!(self, Self::Connecting | Self::Running)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct GdbConnection {
|
||||||
|
sim_id: SimId,
|
||||||
|
client: EmulatorClient,
|
||||||
|
ack_messages: bool,
|
||||||
|
stop_reason: Option<DebugStopReason>,
|
||||||
|
response_buf: Option<Vec<u8>>,
|
||||||
|
memory_buf: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GdbConnection {
|
||||||
|
fn new(sim_id: SimId, client: EmulatorClient) -> Self {
|
||||||
|
Self {
|
||||||
|
sim_id,
|
||||||
|
client,
|
||||||
|
ack_messages: true,
|
||||||
|
stop_reason: None,
|
||||||
|
response_buf: None,
|
||||||
|
memory_buf: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fn run(
|
||||||
|
&mut self,
|
||||||
|
stream: TcpStream,
|
||||||
|
mut debug_source: mpsc::UnboundedReceiver<DebugEvent>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let (rx, mut tx) = stream.into_split();
|
||||||
|
let mut request_source = RequestSource::new(BufReader::new(rx));
|
||||||
|
loop {
|
||||||
|
let response = select! {
|
||||||
|
maybe_event = debug_source.recv() => {
|
||||||
|
let Some(event) = maybe_event else {
|
||||||
|
// debugger has stopped running
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
self.handle_event(event)
|
||||||
|
}
|
||||||
|
maybe_request = request_source.recv() => {
|
||||||
|
let req = maybe_request?;
|
||||||
|
self.handle_request(req)?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(res) = response {
|
||||||
|
let buffer = res.finish();
|
||||||
|
if enabled!(Level::DEBUG) {
|
||||||
|
match std::str::from_utf8(&buffer) {
|
||||||
|
Ok(text) => debug!("response: {text}"),
|
||||||
|
Err(_) => debug!("response: {buffer:02x?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tx.write_all(&buffer).await?;
|
||||||
|
self.response_buf = Some(buffer);
|
||||||
|
tx.flush().await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_event(&mut self, event: DebugEvent) -> Option<Response> {
|
||||||
|
let res = match event {
|
||||||
|
DebugEvent::Stopped(reason) => {
|
||||||
|
if self.stop_reason.is_some_and(|r| r == reason) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.stop_reason = Some(reason);
|
||||||
|
self.response()
|
||||||
|
.write_str(&debug_stop_reason_string(self.stop_reason))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Some(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_request(&mut self, mut req: Request<'_>) -> Result<Option<Response>> {
|
||||||
|
debug!("received {:02x?}", req);
|
||||||
|
|
||||||
|
if req.kind == RequestKind::Signal {
|
||||||
|
self.client
|
||||||
|
.send_command(EmulatorCommand::DebugInterrupt(self.sim_id));
|
||||||
|
return Ok(None); // we'll send a message when the emulator reports it has stopped
|
||||||
|
}
|
||||||
|
|
||||||
|
let res = if req.match_str("QStartNoAckMode") {
|
||||||
|
let res = self.response().write_str("OK");
|
||||||
|
self.ack_messages = false;
|
||||||
|
res
|
||||||
|
} else if req.match_str("qSupported:") {
|
||||||
|
self.response()
|
||||||
|
.write_str("multiprocess+;swbreak+;vContSupported+;PacketSize=10000;SupportedWatchpointTypes=x86_64,aarch64-bas,aarch64-mask")
|
||||||
|
} else if req
|
||||||
|
.match_some_str([
|
||||||
|
"QThreadSuffixSupported",
|
||||||
|
"QListThreadsInStopReply",
|
||||||
|
"QEnableErrorStrings",
|
||||||
|
])
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
|
self.response().write_str("OK")
|
||||||
|
} else if req.match_str("qHostInfo") {
|
||||||
|
self.response().write_str(&format!(
|
||||||
|
"triple:{};endian:little;ptrsize:4;",
|
||||||
|
hex::encode("v810-unknown-vb")
|
||||||
|
))
|
||||||
|
} else if req.match_str("qProcessInfo") {
|
||||||
|
self.response().write_str(&format!(
|
||||||
|
"pid:1;triple:{};endian:little;ptrsize:4;",
|
||||||
|
hex::encode("v810-unknown-vb")
|
||||||
|
))
|
||||||
|
} else if req.match_str("qRegisterInfo") {
|
||||||
|
let mut get_reg_info = || {
|
||||||
|
let register = req.match_hex::<usize>()?;
|
||||||
|
REGISTERS.get(register)
|
||||||
|
};
|
||||||
|
if let Some(reg_info) = get_reg_info() {
|
||||||
|
self.response().write_str(®_info.to_description())
|
||||||
|
} else {
|
||||||
|
self.response()
|
||||||
|
}
|
||||||
|
} else if req.match_str("vCont?") {
|
||||||
|
self.response().write_str("vCont;c;s;")
|
||||||
|
} else if req.match_str("qC") {
|
||||||
|
// The v810 has no threads, so report that the "current thread" is 1.
|
||||||
|
self.response().write_str("QCp1.t1")
|
||||||
|
} else if req.match_str("qfThreadInfo") {
|
||||||
|
self.response().write_str("mp1.t1")
|
||||||
|
} else if req.match_str("qsThreadInfo") {
|
||||||
|
self.response().write_str("l")
|
||||||
|
} else if req.match_str("k") {
|
||||||
|
bail!("debug process was killed");
|
||||||
|
} else if req.match_str("?") {
|
||||||
|
self.response()
|
||||||
|
.write_str(&debug_stop_reason_string(self.stop_reason))
|
||||||
|
} else if req.match_some_str(["c", "vCont;c:"]).is_some() {
|
||||||
|
self.client
|
||||||
|
.send_command(EmulatorCommand::DebugContinue(self.sim_id));
|
||||||
|
self.stop_reason = None;
|
||||||
|
// Don't send a response until we hit a breakpoint or get interrupted
|
||||||
|
return Ok(None);
|
||||||
|
} else if req.match_some_str(["s", "vCont;s:"]).is_some() {
|
||||||
|
self.client
|
||||||
|
.send_command(EmulatorCommand::DebugStep(self.sim_id));
|
||||||
|
self.stop_reason = None;
|
||||||
|
// Don't send a response until we hit a breakpoint or get interrupted
|
||||||
|
return Ok(None);
|
||||||
|
} else if req.match_str("p") {
|
||||||
|
let mut read_register = || {
|
||||||
|
let register_index = req.match_hex::<usize>()?;
|
||||||
|
let register = REGISTERS.get(register_index)?.to_vb_register();
|
||||||
|
let (tx, rx) = ::oneshot::channel();
|
||||||
|
self.client
|
||||||
|
.send_command(EmulatorCommand::ReadRegister(self.sim_id, register, tx));
|
||||||
|
rx.recv().ok()
|
||||||
|
};
|
||||||
|
if let Some(value) = read_register() {
|
||||||
|
self.response().write_hex(value)
|
||||||
|
} else {
|
||||||
|
self.response()
|
||||||
|
}
|
||||||
|
} else if req.match_str("P") {
|
||||||
|
let mut write_register = || {
|
||||||
|
let register_index = req.match_hex::<usize>()?;
|
||||||
|
let register = REGISTERS.get(register_index)?.to_vb_register();
|
||||||
|
if !req.match_str("=") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let value = {
|
||||||
|
let mut buffer = [0; 4];
|
||||||
|
if !req.match_hex_bytes(&mut buffer) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
u32::from_le_bytes(buffer)
|
||||||
|
};
|
||||||
|
self.client.send_command(EmulatorCommand::WriteRegister(
|
||||||
|
self.sim_id,
|
||||||
|
register,
|
||||||
|
value,
|
||||||
|
));
|
||||||
|
Some(())
|
||||||
|
};
|
||||||
|
if let Some(()) = write_register() {
|
||||||
|
self.response().write_str("OK")
|
||||||
|
} else {
|
||||||
|
self.response()
|
||||||
|
}
|
||||||
|
} else if let Some(op) = req.match_some_str(["m", "x"]) {
|
||||||
|
let mut read_memory = || {
|
||||||
|
let (start, length) = parse_memory_range(&mut req)?;
|
||||||
|
let mut buf = self.memory_buf.take().unwrap_or_default();
|
||||||
|
buf.clear();
|
||||||
|
if length == 0 {
|
||||||
|
return Some(buf);
|
||||||
|
}
|
||||||
|
let (tx, rx) = ::oneshot::channel();
|
||||||
|
self.client.send_command(EmulatorCommand::ReadMemory(
|
||||||
|
self.sim_id,
|
||||||
|
start,
|
||||||
|
length,
|
||||||
|
buf,
|
||||||
|
tx,
|
||||||
|
));
|
||||||
|
rx.recv().ok()
|
||||||
|
};
|
||||||
|
if let Some(memory) = read_memory() {
|
||||||
|
let mut res = self.response();
|
||||||
|
if memory.is_empty() {
|
||||||
|
res = res.write_str("OK");
|
||||||
|
} else if op == "m" {
|
||||||
|
// send the hex-encoded byte stream
|
||||||
|
for byte in &memory {
|
||||||
|
res = res.write_hex(*byte);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// send the raw byte stream
|
||||||
|
for byte in &memory {
|
||||||
|
res = res.write_byte(*byte);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.memory_buf = Some(memory);
|
||||||
|
res
|
||||||
|
} else {
|
||||||
|
self.response()
|
||||||
|
}
|
||||||
|
} else if let Some(op) = req.match_some_str(["M", "X"]) {
|
||||||
|
let mut write_memory = || {
|
||||||
|
let (start, length) = parse_memory_range(&mut req)?;
|
||||||
|
if length == 0 {
|
||||||
|
return Some(());
|
||||||
|
}
|
||||||
|
if !req.match_str(":") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut buf = self.memory_buf.take().unwrap_or_default();
|
||||||
|
buf.resize(length, 0);
|
||||||
|
let successful_read = if op == "M" {
|
||||||
|
req.match_hex_bytes(&mut buf)
|
||||||
|
} else {
|
||||||
|
req.match_bytes(&mut buf)
|
||||||
|
};
|
||||||
|
if !successful_read {
|
||||||
|
self.memory_buf = Some(buf);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let (tx, rx) = ::oneshot::channel();
|
||||||
|
self.client
|
||||||
|
.send_command(EmulatorCommand::WriteMemory(self.sim_id, start, buf, tx));
|
||||||
|
let buf = rx.recv().ok()?;
|
||||||
|
self.memory_buf = Some(buf);
|
||||||
|
Some(())
|
||||||
|
};
|
||||||
|
if write_memory().is_some() {
|
||||||
|
self.response().write_str("OK")
|
||||||
|
} else {
|
||||||
|
self.response()
|
||||||
|
}
|
||||||
|
} else if req.match_str("Z") {
|
||||||
|
let mut parse_request = || {
|
||||||
|
let type_ = req.match_hex::<u8>()?;
|
||||||
|
if !req.match_str(",") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let address = req.match_hex()?;
|
||||||
|
if type_ == 0 || type_ == 1 {
|
||||||
|
return Some(EmulatorCommand::AddBreakpoint(self.sim_id, address));
|
||||||
|
}
|
||||||
|
if !req.match_str(",") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let length = req.match_hex()?;
|
||||||
|
let watch = match type_ {
|
||||||
|
2 => VBWatchpointType::Write,
|
||||||
|
3 => VBWatchpointType::Read,
|
||||||
|
4 => VBWatchpointType::Access,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
Some(EmulatorCommand::AddWatchpoint(
|
||||||
|
self.sim_id,
|
||||||
|
address,
|
||||||
|
length,
|
||||||
|
watch,
|
||||||
|
))
|
||||||
|
};
|
||||||
|
if let Some(command) = parse_request() {
|
||||||
|
self.client.send_command(command);
|
||||||
|
self.response().write_str("OK")
|
||||||
|
} else {
|
||||||
|
self.response()
|
||||||
|
}
|
||||||
|
} else if req.match_str("z") {
|
||||||
|
let mut parse_request = || {
|
||||||
|
let type_ = req.match_hex::<u8>()?;
|
||||||
|
if !req.match_str(",") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let address = req.match_hex()?;
|
||||||
|
if type_ == 0 || type_ == 1 {
|
||||||
|
return Some(EmulatorCommand::RemoveBreakpoint(self.sim_id, address));
|
||||||
|
}
|
||||||
|
if !req.match_str(",") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let length = req.match_hex()?;
|
||||||
|
let watch = match type_ {
|
||||||
|
2 => VBWatchpointType::Write,
|
||||||
|
3 => VBWatchpointType::Read,
|
||||||
|
4 => VBWatchpointType::Access,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
Some(EmulatorCommand::RemoveWatchpoint(
|
||||||
|
self.sim_id,
|
||||||
|
address,
|
||||||
|
length,
|
||||||
|
watch,
|
||||||
|
))
|
||||||
|
};
|
||||||
|
if let Some(command) = parse_request() {
|
||||||
|
self.client.send_command(command);
|
||||||
|
self.response().write_str("OK")
|
||||||
|
} else {
|
||||||
|
self.response()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// unrecognized command
|
||||||
|
self.response()
|
||||||
|
};
|
||||||
|
Ok(Some(res))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response(&mut self) -> Response {
|
||||||
|
Response::new(
|
||||||
|
self.response_buf.take().unwrap_or_default(),
|
||||||
|
self.ack_messages,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for GdbConnection {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.client
|
||||||
|
.send_command(EmulatorCommand::StopDebugging(self.sim_id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse a memory range into a start and a length.
|
||||||
|
fn parse_memory_range(req: &mut Request<'_>) -> Option<(u32, usize)> {
|
||||||
|
let start = req.match_hex::<u64>()?;
|
||||||
|
if !req.match_str(",") {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let length = req.match_hex::<usize>()?;
|
||||||
|
let Ok(start) = u32::try_from(start) else {
|
||||||
|
// The v810 has a 32-bit address space.
|
||||||
|
// Addresses wrap within that space, but we don't need to implement that for 64-bit addresses.
|
||||||
|
// Just refuse to return any info for addresses above 0xffffffff.
|
||||||
|
return Some((0, 0));
|
||||||
|
};
|
||||||
|
let length = length.min((u32::MAX - start) as usize + 1);
|
||||||
|
Some((start, length))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn debug_stop_reason_string(reason: Option<DebugStopReason>) -> String {
|
||||||
|
let mut result = String::new();
|
||||||
|
result += if reason.is_some_and(|r| r != DebugStopReason::Paused) {
|
||||||
|
"T05;"
|
||||||
|
} else {
|
||||||
|
"T00;"
|
||||||
|
};
|
||||||
|
if let Some(DebugStopReason::Breakpoint) = reason {
|
||||||
|
result += "swbreak;";
|
||||||
|
}
|
||||||
|
if let Some(DebugStopReason::Watchpoint(watch, address)) = reason {
|
||||||
|
result += match watch {
|
||||||
|
VBWatchpointType::Write => "watch:",
|
||||||
|
VBWatchpointType::Read => "rwatch:",
|
||||||
|
VBWatchpointType::Access => "awatch:",
|
||||||
|
};
|
||||||
|
result += &format!("{address:08x};");
|
||||||
|
}
|
||||||
|
|
||||||
|
result += "thread:p1.t1;threads:p1.t1;";
|
||||||
|
|
||||||
|
if let Some(reason) = reason {
|
||||||
|
result += "reason:";
|
||||||
|
result += match reason {
|
||||||
|
DebugStopReason::Trace => "trace;",
|
||||||
|
DebugStopReason::Breakpoint => "breakpoint;",
|
||||||
|
DebugStopReason::Watchpoint(_, _) => "watchpoint;",
|
||||||
|
DebugStopReason::Paused => "trap;",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(DebugStopReason::Watchpoint(_, address)) = reason {
|
||||||
|
result += "description:";
|
||||||
|
result += &hex::encode(address.to_string());
|
||||||
|
result += ";";
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
use crate::emulator::VBRegister;
|
||||||
|
|
||||||
|
pub struct RegisterInfo {
|
||||||
|
dwarf: u32,
|
||||||
|
name: &'static str,
|
||||||
|
set: &'static str,
|
||||||
|
alt_name: Option<&'static str>,
|
||||||
|
generic: Option<&'static str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RegisterInfo {
|
||||||
|
pub fn to_description(&self) -> String {
|
||||||
|
let mut string = format!("name:{}", self.name);
|
||||||
|
if let Some(alt) = self.alt_name {
|
||||||
|
string.push_str(&format!(";alt-name:{}", alt));
|
||||||
|
}
|
||||||
|
string.push_str(&format!(
|
||||||
|
";bitsize:32;offset:{};encoding:uint;format:hex;set:{};dwarf:{}",
|
||||||
|
self.dwarf * 4,
|
||||||
|
self.set,
|
||||||
|
self.dwarf
|
||||||
|
));
|
||||||
|
if let Some(generic) = self.generic {
|
||||||
|
string.push_str(&format!(";generic:{}", generic));
|
||||||
|
}
|
||||||
|
string
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_vb_register(&self) -> VBRegister {
|
||||||
|
match self.dwarf {
|
||||||
|
0..32 => VBRegister::Program(self.dwarf),
|
||||||
|
32..40 => VBRegister::System(self.dwarf - 32),
|
||||||
|
40..42 => VBRegister::System(self.dwarf - 16),
|
||||||
|
42..45 => VBRegister::System(self.dwarf - 13),
|
||||||
|
45 => VBRegister::PC,
|
||||||
|
other => panic!("unexpected DWARF register {other}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! register {
|
||||||
|
($set:expr, $dwarf:expr, $name:expr) => {
|
||||||
|
RegisterInfo {
|
||||||
|
dwarf: $dwarf,
|
||||||
|
name: $name,
|
||||||
|
set: $set,
|
||||||
|
alt_name: None,
|
||||||
|
generic: None,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
($set:expr, $dwarf:expr, $name:expr, alt: $alt:expr) => {
|
||||||
|
RegisterInfo {
|
||||||
|
dwarf: $dwarf,
|
||||||
|
name: $name,
|
||||||
|
set: $set,
|
||||||
|
alt_name: Some($alt),
|
||||||
|
generic: None,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
($set:expr, $dwarf:expr, $name:expr, generic: $generic:expr) => {
|
||||||
|
RegisterInfo {
|
||||||
|
dwarf: $dwarf,
|
||||||
|
name: $name,
|
||||||
|
set: $set,
|
||||||
|
alt_name: None,
|
||||||
|
generic: Some($generic),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
($set:expr, $dwarf:expr, $name:expr, alt: $alt:expr, generic: $generic:expr) => {
|
||||||
|
RegisterInfo {
|
||||||
|
dwarf: $dwarf,
|
||||||
|
name: $name,
|
||||||
|
set: $set,
|
||||||
|
alt_name: Some($alt),
|
||||||
|
generic: Some($generic),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const GENERAL: &str = "General Purpose Registers";
|
||||||
|
const SPECIAL: &str = "Special Registers";
|
||||||
|
|
||||||
|
pub const REGISTERS: [RegisterInfo; 46] = [
|
||||||
|
register!(GENERAL, 0, "r0"),
|
||||||
|
register!(GENERAL, 1, "r1"),
|
||||||
|
register!(GENERAL, 2, "fp", alt: "r2", generic: "fp"),
|
||||||
|
register!(GENERAL, 3, "sp", alt: "r3", generic: "sp"),
|
||||||
|
register!(GENERAL, 4, "gp", alt: "r4"),
|
||||||
|
register!(GENERAL, 5, "tp", alt: "r5"),
|
||||||
|
register!(GENERAL, 6, "r6", generic: "arg1"),
|
||||||
|
register!(GENERAL, 7, "r7", generic: "arg2"),
|
||||||
|
register!(GENERAL, 8, "r8", generic: "arg3"),
|
||||||
|
register!(GENERAL, 9, "r9", generic: "arg4"),
|
||||||
|
register!(GENERAL, 10, "r10"),
|
||||||
|
register!(GENERAL, 11, "r11"),
|
||||||
|
register!(GENERAL, 12, "r12"),
|
||||||
|
register!(GENERAL, 13, "r13"),
|
||||||
|
register!(GENERAL, 14, "r14"),
|
||||||
|
register!(GENERAL, 15, "r15"),
|
||||||
|
register!(GENERAL, 16, "r16"),
|
||||||
|
register!(GENERAL, 17, "r17"),
|
||||||
|
register!(GENERAL, 18, "r18"),
|
||||||
|
register!(GENERAL, 19, "r19"),
|
||||||
|
register!(GENERAL, 20, "r20"),
|
||||||
|
register!(GENERAL, 21, "r21"),
|
||||||
|
register!(GENERAL, 22, "r22"),
|
||||||
|
register!(GENERAL, 23, "r23"),
|
||||||
|
register!(GENERAL, 24, "r24"),
|
||||||
|
register!(GENERAL, 25, "r25"),
|
||||||
|
register!(GENERAL, 26, "r26"),
|
||||||
|
register!(GENERAL, 27, "r27"),
|
||||||
|
register!(GENERAL, 28, "r28"),
|
||||||
|
register!(GENERAL, 29, "r29"),
|
||||||
|
register!(GENERAL, 30, "r30"),
|
||||||
|
register!(GENERAL, 31, "lp", alt: "r31", generic: "ra"),
|
||||||
|
register!(SPECIAL, 32, "eipc", alt: "sr0"),
|
||||||
|
register!(SPECIAL, 33, "eipsw", alt: "sr1"),
|
||||||
|
register!(SPECIAL, 34, "fepc", alt: "sr2"),
|
||||||
|
register!(SPECIAL, 35, "fepsw", alt: "sr3"),
|
||||||
|
register!(SPECIAL, 36, "ecr", alt: "sr4"),
|
||||||
|
register!(SPECIAL, 37, "psw", alt: "sr5", generic: "flags"),
|
||||||
|
register!(SPECIAL, 38, "pir", alt: "sr6"),
|
||||||
|
register!(SPECIAL, 39, "tkcw", alt: "sr7"),
|
||||||
|
register!(SPECIAL, 40, "chcw", alt: "sr24"),
|
||||||
|
register!(SPECIAL, 41, "adtre", alt: "sr25"),
|
||||||
|
register!(SPECIAL, 42, "sr29"),
|
||||||
|
register!(SPECIAL, 43, "sr30"),
|
||||||
|
register!(SPECIAL, 44, "sr31"),
|
||||||
|
register!(SPECIAL, 45, "pc", generic: "pc"),
|
||||||
|
];
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
use anyhow::{bail, Result};
|
||||||
|
use atoi::FromRadix16;
|
||||||
|
use tokio::io::{AsyncRead, AsyncReadExt as _};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum RequestKind {
|
||||||
|
Signal,
|
||||||
|
Command,
|
||||||
|
}
|
||||||
|
impl RequestKind {
|
||||||
|
fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Signal => "Signal",
|
||||||
|
Self::Command => "Command",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Request<'a> {
|
||||||
|
pub kind: RequestKind,
|
||||||
|
buffer: &'a [u8],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Request<'_> {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
let mut ds = f.debug_tuple(self.kind.name());
|
||||||
|
match self.kind {
|
||||||
|
RequestKind::Signal => ds.field(&self.buffer),
|
||||||
|
RequestKind::Command => match std::str::from_utf8(self.buffer) {
|
||||||
|
Ok(str) => ds.field(&str),
|
||||||
|
Err(_) => ds.field(&self.buffer),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
ds.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Request<'_> {
|
||||||
|
pub fn match_str(&mut self, prefix: &str) -> bool {
|
||||||
|
if let Some(new_buffer) = self.buffer.strip_prefix(prefix.as_bytes()) {
|
||||||
|
self.buffer = new_buffer;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn match_some_str<'a, I: IntoIterator<Item = &'a str>>(
|
||||||
|
&mut self,
|
||||||
|
prefixes: I,
|
||||||
|
) -> Option<&'a str> {
|
||||||
|
prefixes.into_iter().find(|&prefix| self.match_str(prefix))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn match_hex<I: FromRadix16>(&mut self) -> Option<I> {
|
||||||
|
match I::from_radix_16(self.buffer) {
|
||||||
|
(_, 0) => None,
|
||||||
|
(val, used) => {
|
||||||
|
self.buffer = self.buffer.split_at(used).1;
|
||||||
|
Some(val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn match_hex_bytes(&mut self, buffer: &mut [u8]) -> bool {
|
||||||
|
if self.buffer.len() < buffer.len() * 2 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (i, item) in buffer.iter_mut().enumerate() {
|
||||||
|
match u8::from_radix_16(&self.buffer[(i * 2)..(i * 2) + 2]) {
|
||||||
|
(byte, 2) => *item = byte,
|
||||||
|
_ => return false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
self.buffer = self.buffer.split_at(buffer.len()).1;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn match_bytes(&mut self, buffer: &mut [u8]) -> bool {
|
||||||
|
if self.buffer.len() < buffer.len() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
buffer.copy_from_slice(&self.buffer[0..buffer.len()]);
|
||||||
|
self.buffer = self.buffer.split_at(buffer.len()).1;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RequestSource<R> {
|
||||||
|
reader: R,
|
||||||
|
buffer: Vec<u8>,
|
||||||
|
state: RequestReadState,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<R: AsyncRead + Unpin> RequestSource<R> {
|
||||||
|
pub fn new(reader: R) -> Self {
|
||||||
|
Self {
|
||||||
|
reader,
|
||||||
|
buffer: vec![],
|
||||||
|
state: RequestReadState::Header,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn recv(&mut self) -> Result<Request<'_>> {
|
||||||
|
let mut char = self.reader.read_u8().await?;
|
||||||
|
if matches!(self.state, RequestReadState::Start) {
|
||||||
|
self.buffer.clear();
|
||||||
|
self.state = RequestReadState::Header;
|
||||||
|
}
|
||||||
|
if matches!(self.state, RequestReadState::Header) {
|
||||||
|
// Just ignore positive acks
|
||||||
|
while char == b'+' {
|
||||||
|
char = self.reader.read_u8().await?;
|
||||||
|
}
|
||||||
|
if char == b'-' {
|
||||||
|
bail!("no support for negative acks");
|
||||||
|
}
|
||||||
|
if char == 0x03 {
|
||||||
|
// This is how the client "cancels an in-flight request"
|
||||||
|
self.buffer.push(char);
|
||||||
|
self.state = RequestReadState::Start;
|
||||||
|
return Ok(Request {
|
||||||
|
kind: RequestKind::Signal,
|
||||||
|
buffer: &self.buffer,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if char != b'$' {
|
||||||
|
// Messages are supposed to start with a dollar sign
|
||||||
|
bail!("malformed message");
|
||||||
|
}
|
||||||
|
self.state = RequestReadState::Body {
|
||||||
|
checksum: 0,
|
||||||
|
escaping: false,
|
||||||
|
};
|
||||||
|
char = self.reader.read_u8().await?;
|
||||||
|
}
|
||||||
|
while let RequestReadState::Body { checksum, escaping } = &mut self.state {
|
||||||
|
if char == b'#' && !*escaping {
|
||||||
|
self.state = RequestReadState::Checksum {
|
||||||
|
expected: *checksum,
|
||||||
|
actual: 0,
|
||||||
|
digits: 0,
|
||||||
|
};
|
||||||
|
char = self.reader.read_u8().await?;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
*checksum = checksum.wrapping_add(char);
|
||||||
|
|
||||||
|
if *escaping {
|
||||||
|
// escaped character
|
||||||
|
self.buffer.push(char ^ 0x20);
|
||||||
|
*escaping = false;
|
||||||
|
} else if char == b'}' {
|
||||||
|
// next character will be escaped
|
||||||
|
*escaping = true;
|
||||||
|
} else {
|
||||||
|
self.buffer.push(char);
|
||||||
|
}
|
||||||
|
char = self.reader.read_u8().await?;
|
||||||
|
}
|
||||||
|
while let RequestReadState::Checksum {
|
||||||
|
expected,
|
||||||
|
actual,
|
||||||
|
digits,
|
||||||
|
} = &mut self.state
|
||||||
|
{
|
||||||
|
let digit = match char {
|
||||||
|
b'0'..=b'9' => char - b'0',
|
||||||
|
b'a'..=b'f' => char - b'a' + 10,
|
||||||
|
b'A'..=b'F' => char - b'A' + 10,
|
||||||
|
_ => bail!("invalid checksum"),
|
||||||
|
};
|
||||||
|
*actual = (*actual << 4) + digit;
|
||||||
|
*digits += 1;
|
||||||
|
if *digits == 2 {
|
||||||
|
if *expected != *actual {
|
||||||
|
bail!("mismatched checksum");
|
||||||
|
}
|
||||||
|
self.state = RequestReadState::Start;
|
||||||
|
return Ok(Request {
|
||||||
|
kind: RequestKind::Command,
|
||||||
|
buffer: &self.buffer,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
char = self.reader.read_u8().await?;
|
||||||
|
}
|
||||||
|
unreachable!();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum RequestReadState {
|
||||||
|
Start,
|
||||||
|
Header,
|
||||||
|
Body {
|
||||||
|
checksum: u8,
|
||||||
|
escaping: bool,
|
||||||
|
},
|
||||||
|
Checksum {
|
||||||
|
expected: u8,
|
||||||
|
actual: u8,
|
||||||
|
digits: u8,
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
use num_traits::ToBytes;
|
||||||
|
|
||||||
|
pub struct Response {
|
||||||
|
buffer: Vec<u8>,
|
||||||
|
checksum: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Response {
|
||||||
|
pub fn new(mut buffer: Vec<u8>, ack: bool) -> Self {
|
||||||
|
buffer.clear();
|
||||||
|
if ack {
|
||||||
|
buffer.push(b'+');
|
||||||
|
}
|
||||||
|
buffer.push(b'$');
|
||||||
|
Self {
|
||||||
|
buffer,
|
||||||
|
checksum: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_str(self, str: &str) -> Self {
|
||||||
|
let mut me = self;
|
||||||
|
for byte in str.as_bytes() {
|
||||||
|
me = me.write_byte(*byte);
|
||||||
|
}
|
||||||
|
me
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_byte(mut self, byte: u8) -> Self {
|
||||||
|
if byte == b'}' || byte == b'#' || byte == b'$' || byte == b'*' {
|
||||||
|
self.buffer.push(b'}');
|
||||||
|
self.checksum = self.checksum.wrapping_add(b'}');
|
||||||
|
let escaped = byte ^ 0x20;
|
||||||
|
self.buffer.push(escaped);
|
||||||
|
self.checksum = self.checksum.wrapping_add(escaped);
|
||||||
|
} else {
|
||||||
|
self.buffer.push(byte);
|
||||||
|
self.checksum = self.checksum.wrapping_add(byte);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_hex<T: ToBytes>(mut self, value: T) -> Self {
|
||||||
|
for byte in value.to_le_bytes().as_ref() {
|
||||||
|
for digit in [(byte >> 4), (byte & 0xf)] {
|
||||||
|
let char = if digit > 9 {
|
||||||
|
b'a' + digit - 10
|
||||||
|
} else {
|
||||||
|
b'0' + digit
|
||||||
|
};
|
||||||
|
self.buffer.push(char);
|
||||||
|
self.checksum = self.checksum.wrapping_add(char);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn finish(mut self) -> Vec<u8> {
|
||||||
|
let checksum = self.checksum;
|
||||||
|
self.buffer.push(b'#');
|
||||||
|
self.write_hex(checksum).buffer
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
-6
@@ -3,25 +3,41 @@
|
|||||||
|
|
||||||
use std::{path::PathBuf, process, time::SystemTime};
|
use std::{path::PathBuf, process, time::SystemTime};
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::{bail, Result};
|
||||||
use app::Application;
|
use app::Application;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use emulator::EmulatorBuilder;
|
use emulator::EmulatorBuilder;
|
||||||
use thread_priority::{ThreadBuilder, ThreadPriority};
|
use thread_priority::{ThreadBuilder, ThreadPriority};
|
||||||
|
use tracing::error;
|
||||||
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};
|
||||||
use winit::event_loop::{ControlFlow, EventLoop};
|
use winit::event_loop::{ControlFlow, EventLoop};
|
||||||
|
|
||||||
mod app;
|
mod app;
|
||||||
mod audio;
|
mod audio;
|
||||||
mod controller;
|
mod controller;
|
||||||
mod emulator;
|
mod emulator;
|
||||||
|
mod gdbserver;
|
||||||
mod graphics;
|
mod graphics;
|
||||||
mod input;
|
mod input;
|
||||||
|
mod memory;
|
||||||
mod persistence;
|
mod persistence;
|
||||||
|
mod vram;
|
||||||
mod window;
|
mod window;
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
struct Args {
|
struct Args {
|
||||||
|
/// The path to a virtual boy ROM to run.
|
||||||
rom: Option<PathBuf>,
|
rom: Option<PathBuf>,
|
||||||
|
/// Start a GDB/LLDB debug server on this port.
|
||||||
|
#[arg(short, long)]
|
||||||
|
debug_port: Option<u16>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn init_logger() {
|
||||||
|
let directives = std::env::var("RUST_LOG").unwrap_or("error,lemur=info".into());
|
||||||
|
let filter = EnvFilter::builder().parse_lossy(directives);
|
||||||
|
let layer = tracing_subscriber::fmt::layer().with_filter(filter);
|
||||||
|
tracing_subscriber::registry().with(layer).init();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_panic_handler() {
|
fn set_panic_handler() {
|
||||||
@@ -71,6 +87,8 @@ fn set_process_priority_to_high() -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
|
init_logger();
|
||||||
|
|
||||||
set_panic_handler();
|
set_panic_handler();
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
@@ -79,8 +97,14 @@ fn main() -> Result<()> {
|
|||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
|
|
||||||
let (mut builder, client) = EmulatorBuilder::new();
|
let (mut builder, client) = EmulatorBuilder::new();
|
||||||
if let Some(path) = args.rom {
|
if let Some(path) = &args.rom {
|
||||||
builder = builder.with_rom(&path);
|
builder = builder.with_rom(path);
|
||||||
|
}
|
||||||
|
if args.debug_port.is_some() {
|
||||||
|
if args.rom.is_none() {
|
||||||
|
bail!("to start debugging, please select a game.");
|
||||||
|
}
|
||||||
|
builder = builder.start_paused(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
ThreadBuilder::default()
|
ThreadBuilder::default()
|
||||||
@@ -89,8 +113,8 @@ fn main() -> Result<()> {
|
|||||||
.spawn_careless(move || {
|
.spawn_careless(move || {
|
||||||
let mut emulator = match builder.build() {
|
let mut emulator = match builder.build() {
|
||||||
Ok(e) => e,
|
Ok(e) => e,
|
||||||
Err(err) => {
|
Err(error) => {
|
||||||
eprintln!("Error initializing emulator: {err}");
|
error!(%error, "Error initializing emulator");
|
||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -100,6 +124,6 @@ fn main() -> Result<()> {
|
|||||||
let event_loop = EventLoop::with_user_event().build().unwrap();
|
let event_loop = EventLoop::with_user_event().build().unwrap();
|
||||||
event_loop.set_control_flow(ControlFlow::Poll);
|
event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
let proxy = event_loop.create_proxy();
|
let proxy = event_loop.create_proxy();
|
||||||
event_loop.run_app(&mut Application::new(client, proxy))?;
|
event_loop.run_app(&mut Application::new(client, proxy, args.debug_port))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+182
@@ -0,0 +1,182 @@
|
|||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
fmt::Debug,
|
||||||
|
sync::{atomic::AtomicU64, Arc, RwLock, RwLockReadGuard, TryLockError, Weak},
|
||||||
|
};
|
||||||
|
|
||||||
|
use bytemuck::BoxBytes;
|
||||||
|
use itertools::Itertools;
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
|
use crate::emulator::{EmulatorClient, EmulatorCommand, SimId};
|
||||||
|
|
||||||
|
pub struct MemoryMonitor {
|
||||||
|
client: EmulatorClient,
|
||||||
|
regions: HashMap<MemoryRange, Weak<MemoryRegion>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemoryMonitor {
|
||||||
|
pub fn new(client: EmulatorClient) -> Self {
|
||||||
|
Self {
|
||||||
|
client,
|
||||||
|
regions: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn view(&mut self, sim: SimId, start: u32, length: usize) -> MemoryView {
|
||||||
|
let range = MemoryRange { sim, start, length };
|
||||||
|
let region = self
|
||||||
|
.regions
|
||||||
|
.get(&range)
|
||||||
|
.and_then(|r| r.upgrade())
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
let region = Arc::new(MemoryRegion::new(start, length));
|
||||||
|
self.regions.insert(range, Arc::downgrade(®ion));
|
||||||
|
self.client
|
||||||
|
.send_command(EmulatorCommand::WatchMemory(range, Arc::downgrade(®ion)));
|
||||||
|
region
|
||||||
|
});
|
||||||
|
MemoryView { region }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn aligned_memory(start: u32, length: usize) -> BoxBytes {
|
||||||
|
if start % 4 == 0 && length % 4 == 0 {
|
||||||
|
let memory = vec![0u32; length / 4].into_boxed_slice();
|
||||||
|
return bytemuck::box_bytes_of(memory);
|
||||||
|
}
|
||||||
|
if start % 2 == 0 && length % 2 == 0 {
|
||||||
|
let memory = vec![0u16; length / 2].into_boxed_slice();
|
||||||
|
return bytemuck::box_bytes_of(memory);
|
||||||
|
}
|
||||||
|
let memory = vec![0u8; length].into_boxed_slice();
|
||||||
|
bytemuck::box_bytes_of(memory)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MemoryView {
|
||||||
|
region: Arc<MemoryRegion>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemoryView {
|
||||||
|
pub fn borrow(&self) -> MemoryRef<'_> {
|
||||||
|
self.region.borrow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MemoryRef<'a> {
|
||||||
|
inner: RwLockReadGuard<'a, BoxBytes>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemoryRef<'_> {
|
||||||
|
pub fn read<T: bytemuck::AnyBitPattern>(&self, index: usize) -> T {
|
||||||
|
let from = index * size_of::<T>();
|
||||||
|
let to = from + size_of::<T>();
|
||||||
|
*bytemuck::from_bytes(&self.inner[from..to])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn range<T: bytemuck::AnyBitPattern>(&self, start: usize, count: usize) -> &[T] {
|
||||||
|
let from = start * size_of::<T>();
|
||||||
|
let to = from + (count * size_of::<T>());
|
||||||
|
bytemuck::cast_slice(&self.inner[from..to])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct MemoryRange {
|
||||||
|
pub sim: SimId,
|
||||||
|
pub start: u32,
|
||||||
|
pub length: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
const BUFFERS: usize = 4;
|
||||||
|
pub struct MemoryRegion {
|
||||||
|
gens: [AtomicU64; BUFFERS],
|
||||||
|
bufs: [RwLock<BoxBytes>; BUFFERS],
|
||||||
|
}
|
||||||
|
impl Debug for MemoryRegion {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("MemoryRegion")
|
||||||
|
.field("gens", &self.gens)
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// SAFETY: BoxBytes is meant to be Send+Sync, will be in a future version
|
||||||
|
unsafe impl Send for MemoryRegion {}
|
||||||
|
// SAFETY: BoxBytes is meant to be Send+Sync, will be in a future version
|
||||||
|
unsafe impl Sync for MemoryRegion {}
|
||||||
|
|
||||||
|
impl MemoryRegion {
|
||||||
|
fn new(start: u32, length: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
gens: std::array::from_fn(|i| AtomicU64::new(i as u64)),
|
||||||
|
bufs: std::array::from_fn(|_| RwLock::new(aligned_memory(start, length))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn borrow(&self) -> MemoryRef<'_> {
|
||||||
|
/*
|
||||||
|
* When reading memory, a thread will grab the newest buffer (with the highest gen)
|
||||||
|
* It will only fail to grab the lock if the writer already has it,
|
||||||
|
* but the writer prioritizes older buffers (with lower gens).
|
||||||
|
* So this method will only block if the writer produces three full buffers
|
||||||
|
* in the time it takes the reader to do four atomic reads and grab a lock.
|
||||||
|
* In the unlikely event this happens... just try again.
|
||||||
|
*/
|
||||||
|
loop {
|
||||||
|
let newest_index = self
|
||||||
|
.gens
|
||||||
|
.iter()
|
||||||
|
.map(|i| i.load(std::sync::atomic::Ordering::Acquire))
|
||||||
|
.enumerate()
|
||||||
|
.max_by_key(|(_, gen)| *gen)
|
||||||
|
.map(|(i, _)| i)
|
||||||
|
.unwrap();
|
||||||
|
let inner = match self.bufs[newest_index].try_read() {
|
||||||
|
Ok(inner) => inner,
|
||||||
|
Err(TryLockError::Poisoned(e)) => e.into_inner(),
|
||||||
|
Err(TryLockError::WouldBlock) => {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
break MemoryRef { inner };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&self, data: &[u8]) {
|
||||||
|
let gens: Vec<u64> = self
|
||||||
|
.gens
|
||||||
|
.iter()
|
||||||
|
.map(|i| i.load(std::sync::atomic::Ordering::Acquire))
|
||||||
|
.collect();
|
||||||
|
let next_gen = gens.iter().max().unwrap() + 1;
|
||||||
|
let indices = gens
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.sorted_by_key(|(_, val)| *val)
|
||||||
|
.map(|(i, _)| i);
|
||||||
|
for index in indices {
|
||||||
|
let mut lock = match self.bufs[index].try_write() {
|
||||||
|
Ok(inner) => inner,
|
||||||
|
Err(TryLockError::Poisoned(e)) => e.into_inner(),
|
||||||
|
Err(TryLockError::WouldBlock) => {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
lock.copy_from_slice(data);
|
||||||
|
self.gens[index].store(next_gen, std::sync::atomic::Ordering::Release);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
* We have four buffers, and (at time of writing) only three threads interacting with memory:
|
||||||
|
* - The UI thread, reading small regions of memory
|
||||||
|
* - The "vram renderer" thread, reading large regions of memory
|
||||||
|
* - The emulation thread, writing memory every so often
|
||||||
|
* So it should be impossible for all four buffers to have a read lock at the same time,
|
||||||
|
* and (because readers always read the newest buffer) at least one of the oldest three
|
||||||
|
* buffers will be free the entire time we're in this method.
|
||||||
|
* TL;DR this should never happen.
|
||||||
|
* But if it does, do nothing. This isn't medical software, better to show stale data than crash.
|
||||||
|
*/
|
||||||
|
warn!("all buffers were locked by a reader at the same time")
|
||||||
|
}
|
||||||
|
}
|
||||||
+293
@@ -0,0 +1,293 @@
|
|||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
ops::Deref,
|
||||||
|
sync::{Arc, Mutex, Weak},
|
||||||
|
thread,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use egui::{
|
||||||
|
epaint::ImageDelta,
|
||||||
|
load::{LoadError, SizedTexture, TextureLoader, TexturePoll},
|
||||||
|
Color32, ColorImage, TextureHandle, TextureOptions,
|
||||||
|
};
|
||||||
|
use tokio::{sync::mpsc, time::timeout};
|
||||||
|
|
||||||
|
pub struct VramProcessor {
|
||||||
|
sender: mpsc::UnboundedSender<Box<dyn VramRendererImpl>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramProcessor {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
let (sender, receiver) = mpsc::unbounded_channel();
|
||||||
|
thread::spawn(move || {
|
||||||
|
tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap()
|
||||||
|
.block_on(async move {
|
||||||
|
let mut worker = VramProcessorWorker {
|
||||||
|
receiver,
|
||||||
|
renderers: vec![],
|
||||||
|
};
|
||||||
|
worker.run().await
|
||||||
|
})
|
||||||
|
});
|
||||||
|
Self { sender }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add<const N: usize, R: VramRenderer<N> + 'static>(
|
||||||
|
&self,
|
||||||
|
renderer: R,
|
||||||
|
) -> ([VramImageHandle; N], VramParams<R::Params>) {
|
||||||
|
let handles = renderer.sizes().map(|[width, height]| {
|
||||||
|
let data = Arc::new(Mutex::new(None));
|
||||||
|
VramImageHandle {
|
||||||
|
size: [width as f32, height as f32],
|
||||||
|
data,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let images = renderer
|
||||||
|
.sizes()
|
||||||
|
.map(|[width, height]| VramImage::new(width, height));
|
||||||
|
let sink = Arc::new(Mutex::new(R::Params::default()));
|
||||||
|
let _ = self.sender.send(Box::new(VramRendererWrapper {
|
||||||
|
renderer,
|
||||||
|
params: Arc::downgrade(&sink),
|
||||||
|
images,
|
||||||
|
sinks: handles.clone().map(|i| i.data),
|
||||||
|
}));
|
||||||
|
let params = VramParams {
|
||||||
|
value: R::Params::default(),
|
||||||
|
sink,
|
||||||
|
};
|
||||||
|
(handles, params)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct VramProcessorWorker {
|
||||||
|
receiver: mpsc::UnboundedReceiver<Box<dyn VramRendererImpl>>,
|
||||||
|
renderers: Vec<Box<dyn VramRendererImpl>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramProcessorWorker {
|
||||||
|
async fn run(&mut self) {
|
||||||
|
loop {
|
||||||
|
if self.renderers.is_empty() {
|
||||||
|
// if we have nothing to do, block until we have something to do
|
||||||
|
if self.receiver.recv_many(&mut self.renderers, 64).await == 0 {
|
||||||
|
// shutdown
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
while let Ok(renderer) = self.receiver.try_recv() {
|
||||||
|
self.renderers.push(renderer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.renderers
|
||||||
|
.retain_mut(|renderer| renderer.try_update().is_ok());
|
||||||
|
// wait up to 10 ms for more renderers
|
||||||
|
if timeout(
|
||||||
|
Duration::from_millis(10),
|
||||||
|
self.receiver.recv_many(&mut self.renderers, 64),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
while let Ok(renderer) = self.receiver.try_recv() {
|
||||||
|
self.renderers.push(renderer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum VramImage {
|
||||||
|
Unchanged(Option<Arc<ColorImage>>),
|
||||||
|
Changed(ColorImage),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramImage {
|
||||||
|
pub fn new(width: usize, height: usize) -> Self {
|
||||||
|
Self::Changed(ColorImage::new([width, height], Color32::BLACK))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write(&mut self, coords: (usize, usize), shade: u8) {
|
||||||
|
match self {
|
||||||
|
Self::Unchanged(image) => {
|
||||||
|
if image.as_ref().is_none_or(|i| i[coords].r() == shade) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(mut new_image) = image.take().map(Arc::unwrap_or_clone) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
new_image[coords] = Color32::from_gray(shade);
|
||||||
|
*self = Self::Changed(new_image);
|
||||||
|
}
|
||||||
|
Self::Changed(image) => {
|
||||||
|
image[coords] = Color32::from_gray(shade);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn take(&mut self) -> Option<Arc<ColorImage>> {
|
||||||
|
match self {
|
||||||
|
Self::Unchanged(_) => None,
|
||||||
|
Self::Changed(image) => {
|
||||||
|
let arced = Arc::new(std::mem::take(image));
|
||||||
|
*self = Self::Unchanged(Some(arced.clone()));
|
||||||
|
Some(arced)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct VramImageHandle {
|
||||||
|
size: [f32; 2],
|
||||||
|
data: Arc<Mutex<Option<Arc<ColorImage>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramImageHandle {
|
||||||
|
fn pull(&mut self) -> Option<Arc<ColorImage>> {
|
||||||
|
self.data.lock().unwrap().take()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct VramParams<T> {
|
||||||
|
value: T,
|
||||||
|
sink: Arc<Mutex<T>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Deref for VramParams<T> {
|
||||||
|
type Target = T;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Clone + Eq> VramParams<T> {
|
||||||
|
pub fn write(&mut self, value: T) {
|
||||||
|
if self.value != value {
|
||||||
|
self.value = value.clone();
|
||||||
|
*self.sink.lock().unwrap() = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait VramRenderer<const N: usize>: Send {
|
||||||
|
type Params: Clone + Default + Send;
|
||||||
|
fn sizes(&self) -> [[usize; 2]; N];
|
||||||
|
fn render(&mut self, params: &Self::Params, images: &mut [VramImage; N]);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct VramRendererWrapper<const N: usize, R: VramRenderer<N>> {
|
||||||
|
renderer: R,
|
||||||
|
params: Weak<Mutex<R::Params>>,
|
||||||
|
images: [VramImage; N],
|
||||||
|
sinks: [Arc<Mutex<Option<Arc<ColorImage>>>>; N],
|
||||||
|
}
|
||||||
|
|
||||||
|
trait VramRendererImpl: Send {
|
||||||
|
fn try_update(&mut self) -> Result<(), ()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize, R: VramRenderer<N> + Send> VramRendererImpl for VramRendererWrapper<N, R> {
|
||||||
|
fn try_update(&mut self) -> Result<(), ()> {
|
||||||
|
let params = match self.params.upgrade() {
|
||||||
|
Some(params) => params.lock().unwrap().clone(),
|
||||||
|
None => {
|
||||||
|
// the UI isn't using this anymore
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.renderer.render(¶ms, &mut self.images);
|
||||||
|
|
||||||
|
for (image, sink) in self.images.iter_mut().zip(&self.sinks) {
|
||||||
|
if let Some(update) = image.take() {
|
||||||
|
sink.lock().unwrap().replace(update);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct VramTextureLoader {
|
||||||
|
cache: Mutex<HashMap<String, (VramImageHandle, Option<TextureHandle>)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramTextureLoader {
|
||||||
|
pub fn new(renderers: impl IntoIterator<Item = (String, VramImageHandle)>) -> Self {
|
||||||
|
let mut cache = HashMap::new();
|
||||||
|
for (key, image) in renderers {
|
||||||
|
cache.insert(key, (image, None));
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
cache: Mutex::new(cache),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TextureLoader for VramTextureLoader {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
concat!(module_path!(), "VramTextureLoader")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load(
|
||||||
|
&self,
|
||||||
|
ctx: &egui::Context,
|
||||||
|
uri: &str,
|
||||||
|
texture_options: TextureOptions,
|
||||||
|
_size_hint: egui::SizeHint,
|
||||||
|
) -> Result<TexturePoll, LoadError> {
|
||||||
|
let mut cache = self.cache.lock().unwrap();
|
||||||
|
let Some((image, maybe_handle)) = cache.get_mut(uri) else {
|
||||||
|
return Err(LoadError::NotSupported);
|
||||||
|
};
|
||||||
|
if texture_options != TextureOptions::NEAREST {
|
||||||
|
return Err(LoadError::Loading(
|
||||||
|
"Only TextureOptions::NEAREST are supported".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
match (image.pull(), maybe_handle.as_ref()) {
|
||||||
|
(Some(update), Some(handle)) => {
|
||||||
|
let delta = ImageDelta::full(update, texture_options);
|
||||||
|
ctx.tex_manager().write().set(handle.id(), delta);
|
||||||
|
let texture = SizedTexture::new(handle, image.size);
|
||||||
|
Ok(TexturePoll::Ready { texture })
|
||||||
|
}
|
||||||
|
(Some(update), None) => {
|
||||||
|
let handle = ctx.load_texture(uri, update, texture_options);
|
||||||
|
let texture = SizedTexture::new(&handle, image.size);
|
||||||
|
maybe_handle.replace(handle);
|
||||||
|
Ok(TexturePoll::Ready { texture })
|
||||||
|
}
|
||||||
|
(None, Some(handle)) => {
|
||||||
|
let texture = SizedTexture::new(handle, image.size);
|
||||||
|
Ok(TexturePoll::Ready { texture })
|
||||||
|
}
|
||||||
|
(None, None) => {
|
||||||
|
let size = image.size.into();
|
||||||
|
Ok(TexturePoll::Pending { size: Some(size) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn forget(&self, uri: &str) {
|
||||||
|
let _ = uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn forget_all(&self) {}
|
||||||
|
|
||||||
|
fn byte_size(&self) -> usize {
|
||||||
|
self.cache
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.values()
|
||||||
|
.map(|(image, _)| {
|
||||||
|
let [width, height] = image.size;
|
||||||
|
width as usize * height as usize * 4
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
-3
@@ -1,26 +1,39 @@
|
|||||||
pub use about::AboutWindow;
|
pub use about::AboutWindow;
|
||||||
use egui::{Context, ViewportBuilder, ViewportId};
|
use egui::{Context, ViewportBuilder, ViewportId};
|
||||||
pub use game::GameWindow;
|
pub use game::GameWindow;
|
||||||
|
pub use gdb::GdbServerWindow;
|
||||||
pub use input::InputWindow;
|
pub use input::InputWindow;
|
||||||
|
pub use vram::{BgMapWindow, CharacterDataWindow};
|
||||||
use winit::event::KeyEvent;
|
use winit::event::KeyEvent;
|
||||||
|
|
||||||
|
use crate::emulator::SimId;
|
||||||
|
|
||||||
mod about;
|
mod about;
|
||||||
mod game;
|
mod game;
|
||||||
mod game_screen;
|
mod game_screen;
|
||||||
|
mod gdb;
|
||||||
mod input;
|
mod input;
|
||||||
|
mod utils;
|
||||||
|
mod vram;
|
||||||
|
|
||||||
pub trait AppWindow {
|
pub trait AppWindow {
|
||||||
fn viewport_id(&self) -> ViewportId;
|
fn viewport_id(&self) -> ViewportId;
|
||||||
|
fn sim_id(&self) -> SimId {
|
||||||
|
SimId::Player1
|
||||||
|
}
|
||||||
fn initial_viewport(&self) -> ViewportBuilder;
|
fn initial_viewport(&self) -> ViewportBuilder;
|
||||||
fn show(&mut self, ctx: &Context);
|
fn show(&mut self, ctx: &Context);
|
||||||
fn on_init(&mut self, render_state: &egui_wgpu::RenderState) {
|
fn on_init(&mut self, ctx: &Context, render_state: &egui_wgpu::RenderState) {
|
||||||
|
let _ = ctx;
|
||||||
let _ = render_state;
|
let _ = render_state;
|
||||||
}
|
}
|
||||||
fn on_destroy(&mut self) {}
|
fn on_destroy(&mut self) {}
|
||||||
fn handle_key_event(&mut self, event: &KeyEvent) {
|
fn handle_key_event(&mut self, event: &KeyEvent) -> bool {
|
||||||
let _ = event;
|
let _ = event;
|
||||||
|
false
|
||||||
}
|
}
|
||||||
fn handle_gamepad_event(&mut self, event: &gilrs::Event) {
|
fn handle_gamepad_event(&mut self, event: &gilrs::Event) -> bool {
|
||||||
let _ = event;
|
let _ = event;
|
||||||
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+49
-81
@@ -2,13 +2,12 @@ use std::sync::mpsc;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
app::UserEvent,
|
app::UserEvent,
|
||||||
emulator::{EmulatorClient, EmulatorCommand, SimId},
|
emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId, SimState},
|
||||||
persistence::Persistence,
|
persistence::Persistence,
|
||||||
};
|
};
|
||||||
use egui::{
|
use egui::{
|
||||||
ecolor::HexColor, menu, Align2, Button, CentralPanel, Color32, Context, Direction, Frame,
|
menu, Align2, Button, CentralPanel, Color32, Context, Direction, Frame, TopBottomPanel, Ui,
|
||||||
Layout, Response, Sense, TopBottomPanel, Ui, Vec2, ViewportBuilder, ViewportCommand,
|
Vec2, ViewportBuilder, ViewportCommand, ViewportId, Window,
|
||||||
ViewportId, WidgetText, Window,
|
|
||||||
};
|
};
|
||||||
use egui_toast::{Toast, Toasts};
|
use egui_toast::{Toast, Toasts};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -16,6 +15,7 @@ use winit::event_loop::EventLoopProxy;
|
|||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
game_screen::{DisplayMode, GameScreen},
|
game_screen::{DisplayMode, GameScreen},
|
||||||
|
utils::UiExt as _,
|
||||||
AppWindow,
|
AppWindow,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -73,26 +73,29 @@ impl GameWindow {
|
|||||||
.pick_file();
|
.pick_file();
|
||||||
if let Some(path) = rom {
|
if let Some(path) = rom {
|
||||||
self.client
|
self.client
|
||||||
.send_command(EmulatorCommand::LoadGame(SimId::Player1, path));
|
.send_command(EmulatorCommand::LoadGame(self.sim_id, path));
|
||||||
}
|
}
|
||||||
ui.close_menu();
|
ui.close_menu();
|
||||||
}
|
}
|
||||||
if ui.button("Quit").clicked() {
|
if ui.button("Quit").clicked() {
|
||||||
ctx.send_viewport_cmd(ViewportCommand::Close);
|
let _ = self.proxy.send_event(UserEvent::Quit(self.sim_id));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
ui.menu_button("Emulation", |ui| {
|
ui.menu_button("Emulation", |ui| {
|
||||||
let has_game = self.client.has_game(self.sim_id);
|
let state = self.client.emulator_state();
|
||||||
if self.client.is_running(self.sim_id) {
|
let is_ready = self.client.sim_state(self.sim_id) == SimState::Ready;
|
||||||
if ui.add_enabled(has_game, Button::new("Pause")).clicked() {
|
let can_pause = is_ready && state == EmulatorState::Running;
|
||||||
|
let can_resume = is_ready && state == EmulatorState::Paused;
|
||||||
|
if state == EmulatorState::Running {
|
||||||
|
if ui.add_enabled(can_pause, Button::new("Pause")).clicked() {
|
||||||
self.client.send_command(EmulatorCommand::Pause);
|
self.client.send_command(EmulatorCommand::Pause);
|
||||||
ui.close_menu();
|
ui.close_menu();
|
||||||
}
|
}
|
||||||
} else if ui.add_enabled(has_game, Button::new("Resume")).clicked() {
|
} else if ui.add_enabled(can_resume, Button::new("Resume")).clicked() {
|
||||||
self.client.send_command(EmulatorCommand::Resume);
|
self.client.send_command(EmulatorCommand::Resume);
|
||||||
ui.close_menu();
|
ui.close_menu();
|
||||||
}
|
}
|
||||||
if ui.add_enabled(has_game, Button::new("Reset")).clicked() {
|
if ui.add_enabled(is_ready, Button::new("Reset")).clicked() {
|
||||||
self.client
|
self.client
|
||||||
.send_command(EmulatorCommand::Reset(self.sim_id));
|
.send_command(EmulatorCommand::Reset(self.sim_id));
|
||||||
ui.close_menu();
|
ui.close_menu();
|
||||||
@@ -100,8 +103,9 @@ impl GameWindow {
|
|||||||
});
|
});
|
||||||
ui.menu_button("Options", |ui| self.show_options_menu(ctx, ui));
|
ui.menu_button("Options", |ui| self.show_options_menu(ctx, ui));
|
||||||
ui.menu_button("Multiplayer", |ui| {
|
ui.menu_button("Multiplayer", |ui| {
|
||||||
|
let has_player_2 = self.client.sim_state(SimId::Player2) != SimState::Uninitialized;
|
||||||
if self.sim_id == SimId::Player1
|
if self.sim_id == SimId::Player1
|
||||||
&& !self.client.has_player_2()
|
&& !has_player_2
|
||||||
&& ui.button("Open Player 2").clicked()
|
&& ui.button("Open Player 2").clicked()
|
||||||
{
|
{
|
||||||
self.client
|
self.client
|
||||||
@@ -109,7 +113,7 @@ impl GameWindow {
|
|||||||
self.proxy.send_event(UserEvent::OpenPlayer2).unwrap();
|
self.proxy.send_event(UserEvent::OpenPlayer2).unwrap();
|
||||||
ui.close_menu();
|
ui.close_menu();
|
||||||
}
|
}
|
||||||
if self.client.has_player_2() {
|
if has_player_2 {
|
||||||
let linked = self.client.are_sims_linked();
|
let linked = self.client.are_sims_linked();
|
||||||
if linked && ui.button("Unlink").clicked() {
|
if linked && ui.button("Unlink").clicked() {
|
||||||
self.client.send_command(EmulatorCommand::Unlink);
|
self.client.send_command(EmulatorCommand::Unlink);
|
||||||
@@ -121,9 +125,31 @@ impl GameWindow {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
ui.menu_button("About", |ui| {
|
ui.menu_button("Tools", |ui| {
|
||||||
self.proxy.send_event(UserEvent::OpenAbout).unwrap();
|
if ui.button("GDB Server").clicked() {
|
||||||
ui.close_menu();
|
self.proxy
|
||||||
|
.send_event(UserEvent::OpenDebugger(self.sim_id))
|
||||||
|
.unwrap();
|
||||||
|
ui.close_menu();
|
||||||
|
}
|
||||||
|
if ui.button("Character Data").clicked() {
|
||||||
|
self.proxy
|
||||||
|
.send_event(UserEvent::OpenCharacterData(self.sim_id))
|
||||||
|
.unwrap();
|
||||||
|
ui.close_menu();
|
||||||
|
}
|
||||||
|
if ui.button("Background Maps").clicked() {
|
||||||
|
self.proxy
|
||||||
|
.send_event(UserEvent::OpenBgMap(self.sim_id))
|
||||||
|
.unwrap();
|
||||||
|
ui.close_menu();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.menu_button("Help", |ui| {
|
||||||
|
if ui.button("About").clicked() {
|
||||||
|
self.proxy.send_event(UserEvent::OpenAbout).unwrap();
|
||||||
|
ui.close_menu();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,7 +225,7 @@ impl GameWindow {
|
|||||||
let color_str = |color: Color32| {
|
let color_str = |color: Color32| {
|
||||||
format!("{:02x}{:02x}{:02x}", color.r(), color.g(), color.b())
|
format!("{:02x}{:02x}{:02x}", color.r(), color.g(), color.b())
|
||||||
};
|
};
|
||||||
let is_running = self.client.is_running(self.sim_id);
|
let is_running = self.client.emulator_state() == EmulatorState::Running;
|
||||||
if is_running {
|
if is_running {
|
||||||
self.client.send_command(EmulatorCommand::Pause);
|
self.client.send_command(EmulatorCommand::Pause);
|
||||||
}
|
}
|
||||||
@@ -306,6 +332,10 @@ impl AppWindow for GameWindow {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn sim_id(&self) -> SimId {
|
||||||
|
self.sim_id
|
||||||
|
}
|
||||||
|
|
||||||
fn initial_viewport(&self) -> ViewportBuilder {
|
fn initial_viewport(&self) -> ViewportBuilder {
|
||||||
ViewportBuilder::default()
|
ViewportBuilder::default()
|
||||||
.with_title("Lemur")
|
.with_title("Lemur")
|
||||||
@@ -353,7 +383,7 @@ impl AppWindow for GameWindow {
|
|||||||
toasts.show(ctx);
|
toasts.show(ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_init(&mut self, render_state: &egui_wgpu::RenderState) {
|
fn on_init(&mut self, _ctx: &Context, render_state: &egui_wgpu::RenderState) {
|
||||||
let (screen, sink) = GameScreen::init(render_state);
|
let (screen, sink) = GameScreen::init(render_state);
|
||||||
let (message_sink, message_source) = mpsc::channel();
|
let (message_sink, message_source) = mpsc::channel();
|
||||||
self.client.send_command(EmulatorCommand::ConnectToSim(
|
self.client.send_command(EmulatorCommand::ConnectToSim(
|
||||||
@@ -369,69 +399,7 @@ impl AppWindow for GameWindow {
|
|||||||
if self.sim_id == SimId::Player2 {
|
if self.sim_id == SimId::Player2 {
|
||||||
self.client.send_command(EmulatorCommand::StopSecondSim);
|
self.client.send_command(EmulatorCommand::StopSecondSim);
|
||||||
}
|
}
|
||||||
}
|
let _ = self.proxy.send_event(UserEvent::Quit(self.sim_id));
|
||||||
}
|
|
||||||
|
|
||||||
trait UiExt {
|
|
||||||
fn selectable_button(&mut self, selected: bool, text: impl Into<WidgetText>) -> Response;
|
|
||||||
fn selectable_option<T: Eq>(
|
|
||||||
&mut self,
|
|
||||||
current_value: &mut T,
|
|
||||||
selected_value: T,
|
|
||||||
text: impl Into<WidgetText>,
|
|
||||||
) -> Response {
|
|
||||||
let response = self.selectable_button(*current_value == selected_value, text);
|
|
||||||
if response.clicked() {
|
|
||||||
*current_value = selected_value;
|
|
||||||
}
|
|
||||||
response
|
|
||||||
}
|
|
||||||
|
|
||||||
fn color_pair_button(&mut self, left: Color32, right: Color32) -> Response;
|
|
||||||
|
|
||||||
fn color_picker(&mut self, color: &mut Color32, hex: &mut String) -> Response;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl UiExt for Ui {
|
|
||||||
fn selectable_button(&mut self, selected: bool, text: impl Into<WidgetText>) -> Response {
|
|
||||||
self.style_mut().visuals.widgets.inactive.bg_fill = Color32::TRANSPARENT;
|
|
||||||
self.style_mut().visuals.widgets.hovered.bg_fill = Color32::TRANSPARENT;
|
|
||||||
self.style_mut().visuals.widgets.active.bg_fill = Color32::TRANSPARENT;
|
|
||||||
let mut selected = selected;
|
|
||||||
self.checkbox(&mut selected, text)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn color_pair_button(&mut self, left: Color32, right: Color32) -> Response {
|
|
||||||
let button_size = Vec2::new(60.0, 20.0);
|
|
||||||
let (rect, response) = self.allocate_at_least(button_size, Sense::click());
|
|
||||||
let center_x = rect.center().x;
|
|
||||||
let left_rect = rect.with_max_x(center_x);
|
|
||||||
self.painter().rect_filled(left_rect, 0.0, left);
|
|
||||||
let right_rect = rect.with_min_x(center_x);
|
|
||||||
self.painter().rect_filled(right_rect, 0.0, right);
|
|
||||||
|
|
||||||
let style = self.style().interact(&response);
|
|
||||||
self.painter().rect_stroke(rect, 0.0, style.fg_stroke);
|
|
||||||
response
|
|
||||||
}
|
|
||||||
|
|
||||||
fn color_picker(&mut self, color: &mut Color32, hex: &mut String) -> Response {
|
|
||||||
self.allocate_ui_with_layout(
|
|
||||||
Vec2::new(100.0, 130.0),
|
|
||||||
Layout::top_down_justified(egui::Align::Center),
|
|
||||||
|ui| {
|
|
||||||
let (rect, _) = ui.allocate_at_least(Vec2::new(100.0, 100.0), Sense::hover());
|
|
||||||
ui.painter().rect_filled(rect, 0.0, *color);
|
|
||||||
let resp = ui.text_edit_singleline(hex);
|
|
||||||
if resp.changed() {
|
|
||||||
if let Ok(new_color) = HexColor::from_str_without_hash(hex) {
|
|
||||||
*color = new_color.color();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
resp
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.inner
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -63,13 +63,13 @@ impl GameScreen {
|
|||||||
layout: Some(&render_pipeline_layout),
|
layout: Some(&render_pipeline_layout),
|
||||||
vertex: wgpu::VertexState {
|
vertex: wgpu::VertexState {
|
||||||
module: &shader,
|
module: &shader,
|
||||||
entry_point: "vs_main",
|
entry_point: Some("vs_main"),
|
||||||
buffers: &[],
|
buffers: &[],
|
||||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||||
},
|
},
|
||||||
fragment: Some(wgpu::FragmentState {
|
fragment: Some(wgpu::FragmentState {
|
||||||
module: &shader,
|
module: &shader,
|
||||||
entry_point,
|
entry_point: Some(entry_point),
|
||||||
targets: &[Some(wgpu::ColorTargetState {
|
targets: &[Some(wgpu::ColorTargetState {
|
||||||
format: wgpu::TextureFormat::Bgra8Unorm,
|
format: wgpu::TextureFormat::Bgra8Unorm,
|
||||||
blend: Some(wgpu::BlendState::REPLACE),
|
blend: Some(wgpu::BlendState::REPLACE),
|
||||||
@@ -235,7 +235,7 @@ impl egui_wgpu::CallbackTrait for GameScreenCallback {
|
|||||||
.get(&self.display_mode)
|
.get(&self.display_mode)
|
||||||
.unwrap_or_else(|| panic!("Unrecognized display mode {:?}", self.display_mode));
|
.unwrap_or_else(|| panic!("Unrecognized display mode {:?}", self.display_mode));
|
||||||
render_pass.set_pipeline(pipeline);
|
render_pass.set_pipeline(pipeline);
|
||||||
render_pass.set_bind_group(0, &self.bind_group, &[]);
|
render_pass.set_bind_group(0, Some(self.bind_group.as_ref()), &[]);
|
||||||
render_pass.set_viewport(x, y, w, h, 0.0, 1.0);
|
render_pass.set_viewport(x, y, w, h, 0.0, 1.0);
|
||||||
render_pass.draw(0..6, 0..1);
|
render_pass.draw(0..6, 0..1);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
use egui::{Button, CentralPanel, TextEdit, ViewportBuilder, ViewportId};
|
||||||
|
use winit::event_loop::EventLoopProxy;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
app::UserEvent,
|
||||||
|
emulator::{EmulatorClient, SimId, SimState},
|
||||||
|
gdbserver::{GdbServer, GdbServerStatus},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::AppWindow;
|
||||||
|
|
||||||
|
pub struct GdbServerWindow {
|
||||||
|
sim_id: SimId,
|
||||||
|
client: EmulatorClient,
|
||||||
|
port_str: String,
|
||||||
|
connected: bool,
|
||||||
|
quit_on_disconnect: bool,
|
||||||
|
server: GdbServer,
|
||||||
|
proxy: EventLoopProxy<UserEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GdbServerWindow {
|
||||||
|
pub fn new(sim_id: SimId, client: EmulatorClient, proxy: EventLoopProxy<UserEvent>) -> Self {
|
||||||
|
Self {
|
||||||
|
sim_id,
|
||||||
|
client: client.clone(),
|
||||||
|
port_str: (8080 + sim_id.to_index()).to_string(),
|
||||||
|
connected: false,
|
||||||
|
quit_on_disconnect: false,
|
||||||
|
server: GdbServer::new(sim_id, client),
|
||||||
|
proxy,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn launch(&mut self, port: u16) {
|
||||||
|
self.server.stop();
|
||||||
|
self.port_str = port.to_string();
|
||||||
|
self.quit_on_disconnect = true;
|
||||||
|
self.server.start(port);
|
||||||
|
self.connected = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppWindow for GdbServerWindow {
|
||||||
|
fn viewport_id(&self) -> ViewportId {
|
||||||
|
ViewportId::from_hash_of(format!("Debugger-{}", self.sim_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sim_id(&self) -> SimId {
|
||||||
|
self.sim_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn initial_viewport(&self) -> ViewportBuilder {
|
||||||
|
ViewportBuilder::default()
|
||||||
|
.with_title(format!("GDB Server ({})", self.sim_id))
|
||||||
|
.with_inner_size((300.0, 200.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show(&mut self, ctx: &egui::Context) {
|
||||||
|
let port_num: Option<u16> = self.port_str.parse().ok();
|
||||||
|
let status = self.server.status();
|
||||||
|
CentralPanel::default().show(ctx, |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
if port_num.is_none() {
|
||||||
|
let style = ui.style_mut();
|
||||||
|
let error = style.visuals.error_fg_color;
|
||||||
|
style.visuals.widgets.active.bg_stroke.color = error;
|
||||||
|
style.visuals.widgets.hovered.bg_stroke.color = error;
|
||||||
|
}
|
||||||
|
ui.label("Port");
|
||||||
|
let port_editor = TextEdit::singleline(&mut self.port_str).desired_width(100.0);
|
||||||
|
ui.add_enabled(!status.running(), port_editor);
|
||||||
|
ui.checkbox(&mut self.quit_on_disconnect, "Quit on disconnect");
|
||||||
|
});
|
||||||
|
|
||||||
|
if !status.running() {
|
||||||
|
if self.connected && self.quit_on_disconnect {
|
||||||
|
self.proxy.send_event(UserEvent::Quit(self.sim_id)).unwrap();
|
||||||
|
} else {
|
||||||
|
self.connected = false;
|
||||||
|
}
|
||||||
|
let start_button = Button::new("Start");
|
||||||
|
let can_start =
|
||||||
|
port_num.is_some() && self.client.sim_state(self.sim_id) == SimState::Ready;
|
||||||
|
if ui.add_enabled(can_start, start_button).clicked() {
|
||||||
|
let port = port_num.unwrap();
|
||||||
|
self.server.start(port);
|
||||||
|
self.connected = true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let stop_button = Button::new("Stop");
|
||||||
|
if ui.add(stop_button).clicked() {
|
||||||
|
self.server.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match &status {
|
||||||
|
GdbServerStatus::Stopped => {}
|
||||||
|
GdbServerStatus::Connecting => {
|
||||||
|
ui.label("Connecting...");
|
||||||
|
}
|
||||||
|
GdbServerStatus::Running => {
|
||||||
|
ui.label("Running");
|
||||||
|
}
|
||||||
|
GdbServerStatus::Error(message) => {
|
||||||
|
ui.label(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
-12
@@ -198,58 +198,63 @@ impl AppWindow for InputWindow {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_key_event(&mut self, event: &winit::event::KeyEvent) {
|
fn handle_key_event(&mut self, event: &winit::event::KeyEvent) -> bool {
|
||||||
if !event.state.is_pressed() {
|
if !event.state.is_pressed() {
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
let sim_id = match self.active_tab {
|
let sim_id = match self.active_tab {
|
||||||
InputTab::Player1 => SimId::Player1,
|
InputTab::Player1 => SimId::Player1,
|
||||||
InputTab::Player2 => SimId::Player2,
|
InputTab::Player2 => SimId::Player2,
|
||||||
_ => {
|
_ => {
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some(vb) = self.now_binding.take() else {
|
let Some(vb) = self.now_binding.take() else {
|
||||||
return;
|
return false;
|
||||||
};
|
};
|
||||||
let mut mappings = self.mappings.for_sim(sim_id).write().unwrap();
|
let mut mappings = self.mappings.for_sim(sim_id).write().unwrap();
|
||||||
mappings.add_keyboard_mapping(vb, event.physical_key);
|
mappings.add_keyboard_mapping(vb, event.physical_key);
|
||||||
drop(mappings);
|
drop(mappings);
|
||||||
self.mappings.save();
|
self.mappings.save();
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_gamepad_event(&mut self, event: &gilrs::Event) {
|
fn handle_gamepad_event(&mut self, event: &gilrs::Event) -> bool {
|
||||||
let InputTab::RebindGamepad(gamepad_id) = self.active_tab else {
|
let InputTab::RebindGamepad(gamepad_id) = self.active_tab else {
|
||||||
return;
|
return false;
|
||||||
};
|
};
|
||||||
if gamepad_id != event.id {
|
if gamepad_id != event.id {
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
let Some(mappings) = self.mappings.for_gamepad(gamepad_id) else {
|
let Some(mappings) = self.mappings.for_gamepad(gamepad_id) else {
|
||||||
return;
|
return false;
|
||||||
};
|
};
|
||||||
let Some(vb) = self.now_binding else {
|
let Some(vb) = self.now_binding else {
|
||||||
return;
|
return false;
|
||||||
};
|
};
|
||||||
match event.event {
|
match event.event {
|
||||||
EventType::ButtonPressed(_, code) => {
|
EventType::ButtonPressed(_, code) => {
|
||||||
let mut mapping = mappings.write().unwrap();
|
let mut mapping = mappings.write().unwrap();
|
||||||
mapping.add_button_mapping(vb, code);
|
mapping.add_button_mapping(vb, code);
|
||||||
self.now_binding.take();
|
self.now_binding.take();
|
||||||
|
true
|
||||||
}
|
}
|
||||||
EventType::AxisChanged(_, value, code) => {
|
EventType::AxisChanged(_, value, code) => {
|
||||||
if value < -0.75 {
|
if value < -0.75 {
|
||||||
let mut mapping = mappings.write().unwrap();
|
let mut mapping = mappings.write().unwrap();
|
||||||
mapping.add_axis_neg_mapping(vb, code);
|
mapping.add_axis_neg_mapping(vb, code);
|
||||||
self.now_binding.take();
|
self.now_binding.take();
|
||||||
}
|
true
|
||||||
if value > 0.75 {
|
} else if value > 0.75 {
|
||||||
let mut mapping = mappings.write().unwrap();
|
let mut mapping = mappings.write().unwrap();
|
||||||
mapping.add_axis_pos_mapping(vb, code);
|
mapping.add_axis_pos_mapping(vb, code);
|
||||||
self.now_binding.take();
|
self.now_binding.take();
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,256 @@
|
|||||||
|
use std::ops::{Bound, RangeBounds};
|
||||||
|
|
||||||
|
use egui::{
|
||||||
|
ecolor::HexColor, Align, Color32, CursorIcon, Frame, Layout, Margin, Rect, Response, RichText,
|
||||||
|
Rounding, Sense, Shape, Stroke, TextEdit, Ui, UiBuilder, Vec2, Widget, WidgetText,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub trait UiExt {
|
||||||
|
fn section(&mut self, title: impl Into<String>, add_contents: impl FnOnce(&mut Ui));
|
||||||
|
fn selectable_button(&mut self, selected: bool, text: impl Into<WidgetText>) -> Response;
|
||||||
|
fn selectable_option<T: Eq>(
|
||||||
|
&mut self,
|
||||||
|
current_value: &mut T,
|
||||||
|
selected_value: T,
|
||||||
|
text: impl Into<WidgetText>,
|
||||||
|
) -> Response {
|
||||||
|
let response = self.selectable_button(*current_value == selected_value, text);
|
||||||
|
if response.clicked() {
|
||||||
|
*current_value = selected_value;
|
||||||
|
}
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color_pair_button(&mut self, left: Color32, right: Color32) -> Response;
|
||||||
|
|
||||||
|
fn color_picker(&mut self, color: &mut Color32, hex: &mut String) -> Response;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UiExt for Ui {
|
||||||
|
fn section(&mut self, title: impl Into<String>, add_contents: impl FnOnce(&mut Ui)) {
|
||||||
|
let mut frame = Frame::group(self.style());
|
||||||
|
frame.outer_margin.top += 10.0;
|
||||||
|
frame.inner_margin.top += 2.0;
|
||||||
|
let res = frame.show(self, add_contents);
|
||||||
|
let text = RichText::new(title).background_color(self.style().visuals.panel_fill);
|
||||||
|
let old_rect = res.response.rect;
|
||||||
|
let mut text_rect = old_rect;
|
||||||
|
text_rect.min.x += 6.0;
|
||||||
|
let new_rect = self
|
||||||
|
.allocate_new_ui(UiBuilder::new().max_rect(text_rect), |ui| ui.label(text))
|
||||||
|
.response
|
||||||
|
.rect;
|
||||||
|
self.allocate_space((old_rect.max - new_rect.max) - (old_rect.min - new_rect.min));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selectable_button(&mut self, selected: bool, text: impl Into<WidgetText>) -> Response {
|
||||||
|
self.style_mut().visuals.widgets.inactive.bg_fill = Color32::TRANSPARENT;
|
||||||
|
self.style_mut().visuals.widgets.hovered.bg_fill = Color32::TRANSPARENT;
|
||||||
|
self.style_mut().visuals.widgets.active.bg_fill = Color32::TRANSPARENT;
|
||||||
|
let mut selected = selected;
|
||||||
|
self.checkbox(&mut selected, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color_pair_button(&mut self, left: Color32, right: Color32) -> Response {
|
||||||
|
let button_size = Vec2::new(60.0, 20.0);
|
||||||
|
let (rect, response) = self.allocate_at_least(button_size, Sense::click());
|
||||||
|
let center_x = rect.center().x;
|
||||||
|
let left_rect = rect.with_max_x(center_x);
|
||||||
|
self.painter().rect_filled(left_rect, 0.0, left);
|
||||||
|
let right_rect = rect.with_min_x(center_x);
|
||||||
|
self.painter().rect_filled(right_rect, 0.0, right);
|
||||||
|
|
||||||
|
let style = self.style().interact(&response);
|
||||||
|
self.painter().rect_stroke(rect, 0.0, style.fg_stroke);
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color_picker(&mut self, color: &mut Color32, hex: &mut String) -> Response {
|
||||||
|
self.allocate_ui_with_layout(
|
||||||
|
Vec2::new(100.0, 130.0),
|
||||||
|
Layout::top_down_justified(egui::Align::Center),
|
||||||
|
|ui| {
|
||||||
|
let (rect, _) = ui.allocate_at_least(Vec2::new(100.0, 100.0), Sense::hover());
|
||||||
|
ui.painter().rect_filled(rect, 0.0, *color);
|
||||||
|
let resp = ui.text_edit_singleline(hex);
|
||||||
|
if resp.changed() {
|
||||||
|
if let Ok(new_color) = HexColor::from_str_without_hash(hex) {
|
||||||
|
*color = new_color.color();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resp
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.inner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct NumberEdit<'a> {
|
||||||
|
value: &'a mut usize,
|
||||||
|
min: Option<usize>,
|
||||||
|
max: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> NumberEdit<'a> {
|
||||||
|
pub fn new(value: &'a mut usize) -> Self {
|
||||||
|
Self {
|
||||||
|
value,
|
||||||
|
min: None,
|
||||||
|
max: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn range(self, range: impl RangeBounds<usize>) -> Self {
|
||||||
|
let min = match range.start_bound() {
|
||||||
|
Bound::Unbounded => None,
|
||||||
|
Bound::Included(t) => Some(*t),
|
||||||
|
Bound::Excluded(t) => t.checked_add(1),
|
||||||
|
};
|
||||||
|
let max = match range.end_bound() {
|
||||||
|
Bound::Unbounded => None,
|
||||||
|
Bound::Included(t) => Some(*t),
|
||||||
|
Bound::Excluded(t) => t.checked_sub(1),
|
||||||
|
};
|
||||||
|
Self { min, max, ..self }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Widget for NumberEdit<'_> {
|
||||||
|
fn ui(self, ui: &mut Ui) -> Response {
|
||||||
|
let (last_value, mut str) = ui.memory(|m| {
|
||||||
|
m.data
|
||||||
|
.get_temp(ui.id())
|
||||||
|
.unwrap_or((*self.value, self.value.to_string()))
|
||||||
|
});
|
||||||
|
let mut stale = false;
|
||||||
|
if *self.value != last_value {
|
||||||
|
str = self.value.to_string();
|
||||||
|
stale = true;
|
||||||
|
}
|
||||||
|
let valid = str.parse().is_ok_and(|v: usize| v == *self.value);
|
||||||
|
let text = TextEdit::singleline(&mut str)
|
||||||
|
.horizontal_align(Align::Max)
|
||||||
|
.margin(Margin {
|
||||||
|
left: 4.0,
|
||||||
|
right: 20.0,
|
||||||
|
top: 2.0,
|
||||||
|
bottom: 2.0,
|
||||||
|
});
|
||||||
|
let res = if valid {
|
||||||
|
ui.add(text)
|
||||||
|
} else {
|
||||||
|
let message = match (self.min, self.max) {
|
||||||
|
(Some(min), Some(max)) => format!("Please enter a number between {min} and {max}."),
|
||||||
|
(Some(min), None) => format!("Please enter a number greater than {min}."),
|
||||||
|
(None, Some(max)) => format!("Please enter a number less than {max}."),
|
||||||
|
(None, None) => "Please enter a number.".to_string(),
|
||||||
|
};
|
||||||
|
ui.scope(|ui| {
|
||||||
|
let style = ui.style_mut();
|
||||||
|
style.visuals.selection.stroke.color = style.visuals.error_fg_color;
|
||||||
|
style.visuals.widgets.hovered.bg_stroke.color =
|
||||||
|
style.visuals.error_fg_color.gamma_multiply(0.60);
|
||||||
|
ui.add(text)
|
||||||
|
})
|
||||||
|
.inner
|
||||||
|
.on_hover_text(message)
|
||||||
|
};
|
||||||
|
|
||||||
|
let arrow_left = res.rect.max.x + 4.0;
|
||||||
|
let arrow_right = res.rect.max.x + 20.0;
|
||||||
|
let arrow_top = res.rect.min.y - 2.0;
|
||||||
|
let arrow_middle = (res.rect.min.y + res.rect.max.y) / 2.0;
|
||||||
|
let arrow_bottom = res.rect.max.y + 2.0;
|
||||||
|
|
||||||
|
let mut delta = 0;
|
||||||
|
let top_arrow_rect = Rect {
|
||||||
|
min: (arrow_left, arrow_top).into(),
|
||||||
|
max: (arrow_right, arrow_middle).into(),
|
||||||
|
};
|
||||||
|
if draw_arrow(ui, top_arrow_rect, true).clicked_or_dragged() {
|
||||||
|
delta = 1;
|
||||||
|
}
|
||||||
|
let bottom_arrow_rect = Rect {
|
||||||
|
min: (arrow_left, arrow_middle).into(),
|
||||||
|
max: (arrow_right, arrow_bottom).into(),
|
||||||
|
};
|
||||||
|
if draw_arrow(ui, bottom_arrow_rect, false).clicked_or_dragged() {
|
||||||
|
delta = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let in_range =
|
||||||
|
|&val: &usize| self.min.is_none_or(|m| m <= val) && self.max.is_none_or(|m| m >= val);
|
||||||
|
if delta != 0 {
|
||||||
|
if let Some(new_value) = self.value.checked_add_signed(delta).filter(in_range) {
|
||||||
|
*self.value = new_value;
|
||||||
|
}
|
||||||
|
str = self.value.to_string();
|
||||||
|
stale = true;
|
||||||
|
} else if res.changed {
|
||||||
|
if let Some(new_value) = str.parse().ok().filter(in_range) {
|
||||||
|
*self.value = new_value;
|
||||||
|
}
|
||||||
|
stale = true;
|
||||||
|
}
|
||||||
|
if stale {
|
||||||
|
ui.memory_mut(|m| m.data.insert_temp(ui.id(), (*self.value, str)));
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_arrow(ui: &mut Ui, rect: Rect, up: bool) -> Response {
|
||||||
|
let arrow_res = ui
|
||||||
|
.allocate_rect(rect, Sense::click_and_drag())
|
||||||
|
.on_hover_cursor(CursorIcon::Default);
|
||||||
|
let visuals = ui.style().visuals.widgets.style(&arrow_res);
|
||||||
|
let painter = ui.painter_at(arrow_res.rect);
|
||||||
|
|
||||||
|
let rounding = if up {
|
||||||
|
Rounding {
|
||||||
|
ne: 2.0,
|
||||||
|
..Rounding::ZERO
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Rounding {
|
||||||
|
se: 2.0,
|
||||||
|
..Rounding::ZERO
|
||||||
|
}
|
||||||
|
};
|
||||||
|
painter.rect_filled(arrow_res.rect, rounding, visuals.bg_fill);
|
||||||
|
|
||||||
|
let left = rect.left() + 4.0;
|
||||||
|
let center = (rect.left() + rect.right()) / 2.0;
|
||||||
|
let right = rect.right() - 4.0;
|
||||||
|
let top = rect.top() + 3.0;
|
||||||
|
let bottom = rect.bottom() - 3.0;
|
||||||
|
let points = if up {
|
||||||
|
vec![
|
||||||
|
(left, bottom).into(),
|
||||||
|
(center, top).into(),
|
||||||
|
(right, bottom).into(),
|
||||||
|
]
|
||||||
|
} else {
|
||||||
|
vec![
|
||||||
|
(right, top).into(),
|
||||||
|
(center, bottom).into(),
|
||||||
|
(left, top).into(),
|
||||||
|
]
|
||||||
|
};
|
||||||
|
painter.add(Shape::convex_polygon(
|
||||||
|
points,
|
||||||
|
visuals.fg_stroke.color,
|
||||||
|
Stroke::NONE,
|
||||||
|
));
|
||||||
|
arrow_res
|
||||||
|
}
|
||||||
|
|
||||||
|
trait ResponseExt {
|
||||||
|
fn clicked_or_dragged(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResponseExt for Response {
|
||||||
|
fn clicked_or_dragged(&self) -> bool {
|
||||||
|
self.clicked() || self.dragged()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
mod bgmap;
|
||||||
|
mod chardata;
|
||||||
|
mod utils;
|
||||||
|
|
||||||
|
pub use bgmap::*;
|
||||||
|
pub use chardata::*;
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use egui::{
|
||||||
|
Align, CentralPanel, Checkbox, Color32, Context, Image, ScrollArea, Slider, TextEdit,
|
||||||
|
TextureOptions, Ui, ViewportBuilder, ViewportId,
|
||||||
|
};
|
||||||
|
use egui_extras::{Column, Size, StripBuilder, TableBuilder};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
emulator::SimId,
|
||||||
|
memory::{MemoryMonitor, MemoryView},
|
||||||
|
vram::{VramImage, VramParams, VramProcessor, VramRenderer, VramTextureLoader},
|
||||||
|
window::{
|
||||||
|
utils::{NumberEdit, UiExt},
|
||||||
|
AppWindow,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::utils::{parse_palette, CharacterGrid, GENERIC_PALETTE};
|
||||||
|
|
||||||
|
pub struct BgMapWindow {
|
||||||
|
sim_id: SimId,
|
||||||
|
loader: Arc<VramTextureLoader>,
|
||||||
|
bgmaps: MemoryView,
|
||||||
|
cell_index: usize,
|
||||||
|
generic_palette: bool,
|
||||||
|
params: VramParams<BgMapParams>,
|
||||||
|
scale: f32,
|
||||||
|
show_grid: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BgMapWindow {
|
||||||
|
pub fn new(sim_id: SimId, memory: &mut MemoryMonitor, vram: &mut VramProcessor) -> Self {
|
||||||
|
let renderer = BgMapRenderer::new(sim_id, memory);
|
||||||
|
let ([cell, bgmap], params) = vram.add(renderer);
|
||||||
|
let loader =
|
||||||
|
VramTextureLoader::new([("vram://cell".into(), cell), ("vram://bgmap".into(), bgmap)]);
|
||||||
|
Self {
|
||||||
|
sim_id,
|
||||||
|
loader: Arc::new(loader),
|
||||||
|
bgmaps: memory.view(sim_id, 0x00020000, 0x1d800),
|
||||||
|
cell_index: 0,
|
||||||
|
generic_palette: false,
|
||||||
|
params,
|
||||||
|
scale: 1.0,
|
||||||
|
show_grid: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_form(&mut self, ui: &mut Ui) {
|
||||||
|
let row_height = ui.spacing().interact_size.y;
|
||||||
|
ui.vertical(|ui| {
|
||||||
|
TableBuilder::new(ui)
|
||||||
|
.column(Column::auto())
|
||||||
|
.column(Column::remainder())
|
||||||
|
.body(|mut body| {
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Map");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let mut bgmap_index = self.cell_index / 4096;
|
||||||
|
ui.add(NumberEdit::new(&mut bgmap_index).range(0..14));
|
||||||
|
if bgmap_index != self.cell_index / 4096 {
|
||||||
|
self.cell_index = (bgmap_index * 4096) + (self.cell_index % 4096);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Cell");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(NumberEdit::new(&mut self.cell_index).range(0..16 * 4096));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Address");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let address = 0x00020000 + (self.cell_index * 2);
|
||||||
|
let mut address_str = format!("{address:08x}");
|
||||||
|
ui.add_enabled(
|
||||||
|
false,
|
||||||
|
TextEdit::singleline(&mut address_str).horizontal_align(Align::Max),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
let image = Image::new("vram://cell")
|
||||||
|
.maintain_aspect_ratio(true)
|
||||||
|
.tint(Color32::RED)
|
||||||
|
.texture_options(TextureOptions::NEAREST);
|
||||||
|
ui.add(image);
|
||||||
|
ui.section("Cell", |ui| {
|
||||||
|
let cell = self.bgmaps.borrow().read::<u16>(self.cell_index);
|
||||||
|
let (char_index, mut vflip, mut hflip, palette_index) = parse_cell(cell);
|
||||||
|
TableBuilder::new(ui)
|
||||||
|
.column(Column::remainder())
|
||||||
|
.column(Column::remainder())
|
||||||
|
.body(|mut body| {
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Character");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let mut character_str = char_index.to_string();
|
||||||
|
ui.add_enabled(
|
||||||
|
false,
|
||||||
|
TextEdit::singleline(&mut character_str)
|
||||||
|
.horizontal_align(Align::Max),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Palette");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let mut palette = format!("BG {}", palette_index);
|
||||||
|
ui.add_enabled(
|
||||||
|
false,
|
||||||
|
TextEdit::singleline(&mut palette).horizontal_align(Align::Max),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
let checkbox = Checkbox::new(&mut hflip, "H-flip");
|
||||||
|
ui.add_enabled(false, checkbox);
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let checkbox = Checkbox::new(&mut vflip, "V-flip");
|
||||||
|
ui.add_enabled(false, checkbox);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
ui.section("Display", |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label("Scale");
|
||||||
|
ui.spacing_mut().slider_width = ui.available_width();
|
||||||
|
let slider = Slider::new(&mut self.scale, 1.0..=10.0)
|
||||||
|
.step_by(1.0)
|
||||||
|
.show_value(false);
|
||||||
|
ui.add(slider);
|
||||||
|
});
|
||||||
|
ui.checkbox(&mut self.show_grid, "Show grid");
|
||||||
|
ui.checkbox(&mut self.generic_palette, "Generic palette");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
self.params.write(BgMapParams {
|
||||||
|
cell_index: self.cell_index,
|
||||||
|
generic_palette: self.generic_palette,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_bgmap(&mut self, ui: &mut Ui) {
|
||||||
|
let grid = CharacterGrid::new("vram://bgmap")
|
||||||
|
.with_scale(self.scale)
|
||||||
|
.with_grid(self.show_grid)
|
||||||
|
.with_selected(self.cell_index % 4096);
|
||||||
|
if let Some(selected) = grid.show(ui) {
|
||||||
|
self.cell_index = (self.cell_index / 4096 * 4096) + selected;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppWindow for BgMapWindow {
|
||||||
|
fn viewport_id(&self) -> ViewportId {
|
||||||
|
ViewportId::from_hash_of(format!("bgmap-{}", self.sim_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sim_id(&self) -> SimId {
|
||||||
|
self.sim_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn initial_viewport(&self) -> ViewportBuilder {
|
||||||
|
ViewportBuilder::default()
|
||||||
|
.with_title(format!("BG Map Data ({})", self.sim_id))
|
||||||
|
.with_inner_size((640.0, 480.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_init(&mut self, ctx: &Context, _render_state: &egui_wgpu::RenderState) {
|
||||||
|
ctx.add_texture_loader(self.loader.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show(&mut self, ctx: &Context) {
|
||||||
|
CentralPanel::default().show(ctx, |ui| {
|
||||||
|
ui.horizontal_top(|ui| {
|
||||||
|
StripBuilder::new(ui)
|
||||||
|
.size(Size::relative(0.3))
|
||||||
|
.size(Size::remainder())
|
||||||
|
.horizontal(|mut strip| {
|
||||||
|
strip.cell(|ui| {
|
||||||
|
ScrollArea::vertical().show(ui, |ui| self.show_form(ui));
|
||||||
|
});
|
||||||
|
strip.cell(|ui| {
|
||||||
|
ScrollArea::both().show(ui, |ui| self.show_bgmap(ui));
|
||||||
|
});
|
||||||
|
})
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_cell(cell: u16) -> (usize, bool, bool, usize) {
|
||||||
|
let char_index = (cell & 0x7ff) as usize;
|
||||||
|
let vflip = cell & 0x1000 != 0;
|
||||||
|
let hflip = cell & 0x2000 != 0;
|
||||||
|
let palette_index = (cell >> 14) as usize;
|
||||||
|
(char_index, vflip, hflip, palette_index)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Clone, PartialEq, Eq)]
|
||||||
|
struct BgMapParams {
|
||||||
|
cell_index: usize,
|
||||||
|
generic_palette: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct BgMapRenderer {
|
||||||
|
chardata: MemoryView,
|
||||||
|
bgmaps: MemoryView,
|
||||||
|
brightness: MemoryView,
|
||||||
|
palettes: MemoryView,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BgMapRenderer {
|
||||||
|
pub fn new(sim_id: SimId, memory: &mut MemoryMonitor) -> Self {
|
||||||
|
Self {
|
||||||
|
chardata: memory.view(sim_id, 0x00078000, 0x8000),
|
||||||
|
bgmaps: memory.view(sim_id, 0x00020000, 0x1d800),
|
||||||
|
brightness: memory.view(sim_id, 0x0005f824, 8),
|
||||||
|
palettes: memory.view(sim_id, 0x0005f860, 16),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_bgmap(&self, image: &mut VramImage, bgmap_index: usize, generic_palette: bool) {
|
||||||
|
let chardata = self.chardata.borrow();
|
||||||
|
let bgmaps = self.bgmaps.borrow();
|
||||||
|
let brightness = self.brightness.borrow();
|
||||||
|
let palettes = self.palettes.borrow();
|
||||||
|
|
||||||
|
let brts = brightness.range::<u8>(0, 8);
|
||||||
|
let colors = if generic_palette {
|
||||||
|
[
|
||||||
|
GENERIC_PALETTE,
|
||||||
|
GENERIC_PALETTE,
|
||||||
|
GENERIC_PALETTE,
|
||||||
|
GENERIC_PALETTE,
|
||||||
|
]
|
||||||
|
} else {
|
||||||
|
[
|
||||||
|
parse_palette(palettes.read(0), brts),
|
||||||
|
parse_palette(palettes.read(2), brts),
|
||||||
|
parse_palette(palettes.read(4), brts),
|
||||||
|
parse_palette(palettes.read(6), brts),
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
for (i, cell) in bgmaps
|
||||||
|
.range::<u16>(bgmap_index * 4096, 4096)
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
{
|
||||||
|
let (char_index, vflip, hflip, palette_index) = parse_cell(*cell);
|
||||||
|
let char = chardata.range::<u16>(char_index * 8, 8);
|
||||||
|
let palette = &colors[palette_index];
|
||||||
|
|
||||||
|
for row in 0..8 {
|
||||||
|
let y = row + (i / 64) * 8;
|
||||||
|
for (col, pixel) in self.read_char_row(char, hflip, vflip, row).enumerate() {
|
||||||
|
let x = col + (i % 64) * 8;
|
||||||
|
image.write((x, y), palette[pixel as usize]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_bgmap_cell(&self, image: &mut VramImage, index: usize, generic_palette: bool) {
|
||||||
|
let chardata = self.chardata.borrow();
|
||||||
|
let bgmaps = self.bgmaps.borrow();
|
||||||
|
let brightness = self.brightness.borrow();
|
||||||
|
let palettes = self.palettes.borrow();
|
||||||
|
|
||||||
|
let brts = brightness.range::<u8>(0, 8);
|
||||||
|
|
||||||
|
let cell = bgmaps.read::<u16>(index);
|
||||||
|
|
||||||
|
let (char_index, vflip, hflip, palette_index) = parse_cell(cell);
|
||||||
|
let char = chardata.range::<u16>(char_index * 8, 8);
|
||||||
|
let palette = if generic_palette {
|
||||||
|
GENERIC_PALETTE
|
||||||
|
} else {
|
||||||
|
parse_palette(palettes.read(palette_index * 2), brts)
|
||||||
|
};
|
||||||
|
|
||||||
|
for row in 0..8 {
|
||||||
|
for (col, pixel) in self.read_char_row(char, hflip, vflip, row).enumerate() {
|
||||||
|
image.write((col, row), palette[pixel as usize]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_char_row(
|
||||||
|
&self,
|
||||||
|
char: &[u16],
|
||||||
|
hflip: bool,
|
||||||
|
vflip: bool,
|
||||||
|
row: usize,
|
||||||
|
) -> impl Iterator<Item = u8> {
|
||||||
|
let pixels = if vflip { char[7 - row] } else { char[row] };
|
||||||
|
(0..16).step_by(2).map(move |i| {
|
||||||
|
let pixel = if hflip { 14 - i } else { i };
|
||||||
|
((pixels >> pixel) & 0x3) as u8
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramRenderer<2> for BgMapRenderer {
|
||||||
|
type Params = BgMapParams;
|
||||||
|
|
||||||
|
fn sizes(&self) -> [[usize; 2]; 2] {
|
||||||
|
[[8, 8], [8 * 64, 8 * 64]]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render(&mut self, params: &Self::Params, images: &mut [VramImage; 2]) {
|
||||||
|
self.render_bgmap_cell(&mut images[0], params.cell_index, params.generic_palette);
|
||||||
|
self.render_bgmap(
|
||||||
|
&mut images[1],
|
||||||
|
params.cell_index / 4096,
|
||||||
|
params.generic_palette,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,361 @@
|
|||||||
|
use std::{fmt::Display, sync::Arc};
|
||||||
|
|
||||||
|
use egui::{
|
||||||
|
Align, CentralPanel, Color32, ComboBox, Context, Image, ScrollArea, Slider, TextEdit,
|
||||||
|
TextureOptions, Ui, Vec2, ViewportBuilder, ViewportId,
|
||||||
|
};
|
||||||
|
use egui_extras::{Column, Size, StripBuilder, TableBuilder};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
emulator::SimId,
|
||||||
|
memory::{MemoryMonitor, MemoryView},
|
||||||
|
vram::{VramImage, VramParams, VramProcessor, VramRenderer, VramTextureLoader},
|
||||||
|
window::{
|
||||||
|
utils::{NumberEdit, UiExt as _},
|
||||||
|
AppWindow,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::utils::{self, CharacterGrid};
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
|
pub enum VramPalette {
|
||||||
|
#[default]
|
||||||
|
Generic,
|
||||||
|
Bg0,
|
||||||
|
Bg1,
|
||||||
|
Bg2,
|
||||||
|
Bg3,
|
||||||
|
Obj0,
|
||||||
|
Obj1,
|
||||||
|
Obj2,
|
||||||
|
Obj3,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramPalette {
|
||||||
|
pub const fn values() -> [VramPalette; 9] {
|
||||||
|
[
|
||||||
|
Self::Generic,
|
||||||
|
Self::Bg0,
|
||||||
|
Self::Bg1,
|
||||||
|
Self::Bg2,
|
||||||
|
Self::Bg3,
|
||||||
|
Self::Obj0,
|
||||||
|
Self::Obj1,
|
||||||
|
Self::Obj2,
|
||||||
|
Self::Obj3,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn offset(self) -> Option<usize> {
|
||||||
|
match self {
|
||||||
|
Self::Generic => None,
|
||||||
|
Self::Bg0 => Some(0),
|
||||||
|
Self::Bg1 => Some(2),
|
||||||
|
Self::Bg2 => Some(4),
|
||||||
|
Self::Bg3 => Some(6),
|
||||||
|
Self::Obj0 => Some(8),
|
||||||
|
Self::Obj1 => Some(10),
|
||||||
|
Self::Obj2 => Some(12),
|
||||||
|
Self::Obj3 => Some(14),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for VramPalette {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Generic => f.write_str("Generic"),
|
||||||
|
Self::Bg0 => f.write_str("BG 0"),
|
||||||
|
Self::Bg1 => f.write_str("BG 1"),
|
||||||
|
Self::Bg2 => f.write_str("BG 2"),
|
||||||
|
Self::Bg3 => f.write_str("BG 3"),
|
||||||
|
Self::Obj0 => f.write_str("OBJ 0"),
|
||||||
|
Self::Obj1 => f.write_str("OBJ 1"),
|
||||||
|
Self::Obj2 => f.write_str("OBJ 2"),
|
||||||
|
Self::Obj3 => f.write_str("OBJ 3"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CharacterDataWindow {
|
||||||
|
sim_id: SimId,
|
||||||
|
loader: Arc<VramTextureLoader>,
|
||||||
|
brightness: MemoryView,
|
||||||
|
palettes: MemoryView,
|
||||||
|
palette: VramPalette,
|
||||||
|
index: usize,
|
||||||
|
params: VramParams<CharDataParams>,
|
||||||
|
scale: f32,
|
||||||
|
show_grid: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CharacterDataWindow {
|
||||||
|
pub fn new(sim_id: SimId, memory: &mut MemoryMonitor, vram: &mut VramProcessor) -> Self {
|
||||||
|
let renderer = CharDataRenderer::new(sim_id, memory);
|
||||||
|
let ([char, chardata], params) = vram.add(renderer);
|
||||||
|
let loader = VramTextureLoader::new([
|
||||||
|
("vram://char".into(), char),
|
||||||
|
("vram://chardata".into(), chardata),
|
||||||
|
]);
|
||||||
|
Self {
|
||||||
|
sim_id,
|
||||||
|
loader: Arc::new(loader),
|
||||||
|
brightness: memory.view(sim_id, 0x0005f824, 8),
|
||||||
|
palettes: memory.view(sim_id, 0x0005f860, 16),
|
||||||
|
palette: params.palette,
|
||||||
|
index: params.index,
|
||||||
|
params,
|
||||||
|
scale: 4.0,
|
||||||
|
show_grid: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_form(&mut self, ui: &mut Ui) {
|
||||||
|
let row_height = ui.spacing().interact_size.y;
|
||||||
|
ui.vertical(|ui| {
|
||||||
|
TableBuilder::new(ui)
|
||||||
|
.column(Column::auto())
|
||||||
|
.column(Column::remainder())
|
||||||
|
.body(|mut body| {
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Index");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(NumberEdit::new(&mut self.index).range(0..2048));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Address");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let address = match self.index {
|
||||||
|
0x000..0x200 => 0x00060000 + self.index * 16,
|
||||||
|
0x200..0x400 => 0x000e0000 + (self.index - 0x200) * 16,
|
||||||
|
0x400..0x600 => 0x00160000 + (self.index - 0x400) * 16,
|
||||||
|
0x600..0x800 => 0x001e0000 + (self.index - 0x600) * 16,
|
||||||
|
_ => unreachable!("can't happen"),
|
||||||
|
};
|
||||||
|
let mut address_str = format!("{address:08x}");
|
||||||
|
ui.add_enabled(
|
||||||
|
false,
|
||||||
|
TextEdit::singleline(&mut address_str).horizontal_align(Align::Max),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Mirror");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let mirror = 0x00078000 + (self.index * 16);
|
||||||
|
let mut mirror_str = format!("{mirror:08x}");
|
||||||
|
ui.add_enabled(
|
||||||
|
false,
|
||||||
|
TextEdit::singleline(&mut mirror_str).horizontal_align(Align::Max),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
let image = Image::new("vram://char")
|
||||||
|
.maintain_aspect_ratio(true)
|
||||||
|
.tint(Color32::RED)
|
||||||
|
.texture_options(TextureOptions::NEAREST);
|
||||||
|
ui.add(image);
|
||||||
|
ui.section("Colors", |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label("Palette");
|
||||||
|
ComboBox::from_id_salt("palette")
|
||||||
|
.selected_text(self.palette.to_string())
|
||||||
|
.width(ui.available_width())
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
for palette in VramPalette::values() {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.palette,
|
||||||
|
palette,
|
||||||
|
palette.to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
TableBuilder::new(ui)
|
||||||
|
.columns(Column::remainder(), 4)
|
||||||
|
.body(|mut body| {
|
||||||
|
let palette = self.load_palette_colors();
|
||||||
|
body.row(30.0, |mut row| {
|
||||||
|
for color in palette {
|
||||||
|
row.col(|ui| {
|
||||||
|
let rect = ui.available_rect_before_wrap();
|
||||||
|
let scale = rect.height() / rect.width();
|
||||||
|
let rect = rect.scale_from_center2(Vec2::new(scale, 1.0));
|
||||||
|
ui.painter().rect_filled(
|
||||||
|
rect,
|
||||||
|
0.0,
|
||||||
|
Color32::RED * Color32::from_gray(color),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
ui.section("Display", |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label("Scale");
|
||||||
|
ui.spacing_mut().slider_width = ui.available_width();
|
||||||
|
let slider = Slider::new(&mut self.scale, 1.0..=10.0)
|
||||||
|
.step_by(1.0)
|
||||||
|
.show_value(false);
|
||||||
|
ui.add(slider);
|
||||||
|
});
|
||||||
|
ui.checkbox(&mut self.show_grid, "Show grid");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
self.params.write(CharDataParams {
|
||||||
|
palette: self.palette,
|
||||||
|
index: self.index,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_palette_colors(&self) -> [u8; 4] {
|
||||||
|
let Some(offset) = self.palette.offset() else {
|
||||||
|
return utils::GENERIC_PALETTE;
|
||||||
|
};
|
||||||
|
let palette = self.palettes.borrow().read(offset);
|
||||||
|
let brightnesses = self.brightness.borrow();
|
||||||
|
let brts = brightnesses.range(0, 8);
|
||||||
|
utils::parse_palette(palette, brts)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_chardata(&mut self, ui: &mut Ui) {
|
||||||
|
let grid = CharacterGrid::new("vram://chardata")
|
||||||
|
.with_scale(self.scale)
|
||||||
|
.with_grid(self.show_grid)
|
||||||
|
.with_selected(self.index);
|
||||||
|
if let Some(selected) = grid.show(ui) {
|
||||||
|
self.index = selected;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppWindow for CharacterDataWindow {
|
||||||
|
fn viewport_id(&self) -> ViewportId {
|
||||||
|
ViewportId::from_hash_of(format!("chardata-{}", self.sim_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sim_id(&self) -> SimId {
|
||||||
|
self.sim_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn initial_viewport(&self) -> ViewportBuilder {
|
||||||
|
ViewportBuilder::default()
|
||||||
|
.with_title(format!("Character Data ({})", self.sim_id))
|
||||||
|
.with_inner_size((640.0, 480.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_init(&mut self, ctx: &Context, _render_state: &egui_wgpu::RenderState) {
|
||||||
|
ctx.add_texture_loader(self.loader.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show(&mut self, ctx: &Context) {
|
||||||
|
CentralPanel::default().show(ctx, |ui| {
|
||||||
|
ui.horizontal_top(|ui| {
|
||||||
|
StripBuilder::new(ui)
|
||||||
|
.size(Size::relative(0.3))
|
||||||
|
.size(Size::remainder())
|
||||||
|
.horizontal(|mut strip| {
|
||||||
|
strip.cell(|ui| {
|
||||||
|
ScrollArea::vertical().show(ui, |ui| self.show_form(ui));
|
||||||
|
});
|
||||||
|
strip.cell(|ui| {
|
||||||
|
ScrollArea::both().show(ui, |ui| self.show_chardata(ui));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
|
||||||
|
enum CharDataResource {
|
||||||
|
Character { palette: VramPalette, index: usize },
|
||||||
|
CharacterData { palette: VramPalette },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default, PartialEq, Eq)]
|
||||||
|
struct CharDataParams {
|
||||||
|
palette: VramPalette,
|
||||||
|
index: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CharDataRenderer {
|
||||||
|
chardata: MemoryView,
|
||||||
|
brightness: MemoryView,
|
||||||
|
palettes: MemoryView,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramRenderer<2> for CharDataRenderer {
|
||||||
|
type Params = CharDataParams;
|
||||||
|
|
||||||
|
fn sizes(&self) -> [[usize; 2]; 2] {
|
||||||
|
[[8, 8], [16 * 8, 128 * 8]]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render(&mut self, params: &Self::Params, image: &mut [VramImage; 2]) {
|
||||||
|
self.render_character(&mut image[0], params.palette, params.index);
|
||||||
|
self.render_character_data(&mut image[1], params.palette);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CharDataRenderer {
|
||||||
|
pub fn new(sim_id: SimId, memory: &mut MemoryMonitor) -> Self {
|
||||||
|
Self {
|
||||||
|
chardata: memory.view(sim_id, 0x00078000, 0x8000),
|
||||||
|
brightness: memory.view(sim_id, 0x0005f824, 8),
|
||||||
|
palettes: memory.view(sim_id, 0x0005f860, 16),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_character(&self, image: &mut VramImage, palette: VramPalette, index: usize) {
|
||||||
|
if index >= 2048 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let palette = self.load_palette(palette);
|
||||||
|
let chardata = self.chardata.borrow();
|
||||||
|
let character = chardata.range::<u16>(index * 8, 8);
|
||||||
|
for (row, pixels) in character.iter().enumerate() {
|
||||||
|
for col in 0..8 {
|
||||||
|
let char = (pixels >> (col * 2)) & 0x03;
|
||||||
|
image.write((col, row), palette[char as usize]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_character_data(&self, image: &mut VramImage, palette: VramPalette) {
|
||||||
|
let palette = self.load_palette(palette);
|
||||||
|
let chardata = self.chardata.borrow();
|
||||||
|
for (row, pixels) in chardata.range::<u16>(0, 8 * 2048).iter().enumerate() {
|
||||||
|
let char_index = row / 8;
|
||||||
|
let row_index = row % 8;
|
||||||
|
let x = (char_index % 16) * 8;
|
||||||
|
let y = (char_index / 16) * 8 + row_index;
|
||||||
|
for col in 0..8 {
|
||||||
|
let char = (pixels >> (col * 2)) & 0x03;
|
||||||
|
image.write((x + col, y), palette[char as usize]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_palette(&self, palette: VramPalette) -> [u8; 4] {
|
||||||
|
let Some(offset) = palette.offset() else {
|
||||||
|
return utils::GENERIC_PALETTE;
|
||||||
|
};
|
||||||
|
let palette = self.palettes.borrow().read(offset);
|
||||||
|
let brightnesses = self.brightness.borrow();
|
||||||
|
let brts = brightnesses.range(0, 8);
|
||||||
|
utils::parse_palette(palette, brts)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
use egui::{Color32, Image, ImageSource, Response, Sense, TextureOptions, Ui, Widget};
|
||||||
|
|
||||||
|
pub const GENERIC_PALETTE: [u8; 4] = [0, 64, 128, 255];
|
||||||
|
|
||||||
|
pub fn parse_palette(palette: u8, brts: &[u8]) -> [u8; 4] {
|
||||||
|
let shades = [
|
||||||
|
0,
|
||||||
|
brts[0],
|
||||||
|
brts[2],
|
||||||
|
brts[0].saturating_add(brts[2]).saturating_add(brts[4]),
|
||||||
|
];
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
shades[(palette >> 2) as usize & 0x03],
|
||||||
|
shades[(palette >> 4) as usize & 0x03],
|
||||||
|
shades[(palette >> 6) as usize & 0x03],
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CharacterGrid<'a> {
|
||||||
|
source: ImageSource<'a>,
|
||||||
|
scale: f32,
|
||||||
|
show_grid: bool,
|
||||||
|
selected: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> CharacterGrid<'a> {
|
||||||
|
pub fn new(source: impl Into<ImageSource<'a>>) -> Self {
|
||||||
|
Self {
|
||||||
|
source: source.into(),
|
||||||
|
scale: 1.0,
|
||||||
|
show_grid: false,
|
||||||
|
selected: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_scale(self, scale: f32) -> Self {
|
||||||
|
Self { scale, ..self }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_grid(self, show_grid: bool) -> Self {
|
||||||
|
Self { show_grid, ..self }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_selected(self, selected: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
selected: Some(selected),
|
||||||
|
..self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn show(self, ui: &mut Ui) -> Option<usize> {
|
||||||
|
let start_pos = ui.cursor().min;
|
||||||
|
let cell_size = 8.0 * self.scale;
|
||||||
|
|
||||||
|
let res = self.ui(ui);
|
||||||
|
|
||||||
|
let grid_width_cells = ((res.rect.max.x - res.rect.min.x) / cell_size).round() as usize;
|
||||||
|
|
||||||
|
if res.clicked() {
|
||||||
|
let click_pos = res.interact_pointer_pos()?;
|
||||||
|
let grid_pos = (click_pos - start_pos) / cell_size;
|
||||||
|
Some((grid_pos.y as usize * grid_width_cells) + grid_pos.x as usize)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Widget for CharacterGrid<'_> {
|
||||||
|
fn ui(self, ui: &mut Ui) -> Response {
|
||||||
|
let image = Image::new(self.source)
|
||||||
|
.fit_to_original_size(self.scale)
|
||||||
|
.tint(Color32::RED)
|
||||||
|
.texture_options(TextureOptions::NEAREST)
|
||||||
|
.sense(Sense::click());
|
||||||
|
let res = ui.add(image);
|
||||||
|
|
||||||
|
let cell_size = 8.0 * self.scale;
|
||||||
|
let grid_width_cells = ((res.rect.max.x - res.rect.min.x) / cell_size).round() as usize;
|
||||||
|
let grid_height_cells = ((res.rect.max.y - res.rect.min.y) / cell_size).round() as usize;
|
||||||
|
|
||||||
|
let painter = ui.painter_at(res.rect);
|
||||||
|
if self.show_grid {
|
||||||
|
let stroke = ui.style().visuals.widgets.noninteractive.fg_stroke;
|
||||||
|
for x in (1..grid_width_cells).map(|i| (i as f32) * cell_size) {
|
||||||
|
let p1 = (res.rect.min.x + x, res.rect.min.y).into();
|
||||||
|
let p2 = (res.rect.min.x + x, res.rect.max.y).into();
|
||||||
|
painter.line(vec![p1, p2], stroke);
|
||||||
|
}
|
||||||
|
for y in (1..grid_height_cells).map(|i| (i as f32) * cell_size) {
|
||||||
|
let p1 = (res.rect.min.x, res.rect.min.y + y).into();
|
||||||
|
let p2 = (res.rect.max.x, res.rect.min.y + y).into();
|
||||||
|
painter.line(vec![p1, p2], stroke);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(selected) = self.selected {
|
||||||
|
let x1 = (selected % grid_width_cells) as f32 * cell_size;
|
||||||
|
let x2 = x1 + cell_size;
|
||||||
|
let y1 = (selected / grid_width_cells) as f32 * cell_size;
|
||||||
|
let y2 = y1 + cell_size;
|
||||||
|
painter.line(
|
||||||
|
vec![
|
||||||
|
(res.rect.min + (x1, y1).into()),
|
||||||
|
(res.rect.min + (x2, y1).into()),
|
||||||
|
(res.rect.min + (x2, y2).into()),
|
||||||
|
(res.rect.min + (x1, y2).into()),
|
||||||
|
(res.rect.min + (x1, y1).into()),
|
||||||
|
],
|
||||||
|
ui.style().visuals.widgets.active.fg_stroke,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user