Compare commits

..
41 Commits
Author SHA1 Message Date
SonicSwordcane fe766efcdc chore: Release lemur version 0.15.1 2026-09-06 21:52:36 -04:00
SonicSwordcane acb8856dd0 Different color for transparent pixels 2026-09-06 21:48:19 -04:00
SonicSwordcane e2c25cbae5 Choose save data location 2026-09-06 21:30:46 -04:00
SonicSwordcane 7d517e932e Update dependencies 2026-09-06 17:24:59 -04:00
SonicSwordcane ec7a89d9da chore: Release lemur version 0.15.0 2026-08-15 01:00:33 -04:00
SonicSwordcane a6c12a986c Persist watch rom setting 2026-08-15 00:59:35 -04:00
SonicSwordcane 762f43fd42 Support emulating low battery 2026-08-15 00:52:40 -04:00
SonicSwordcane 3a00497942 Fix warning on not-linux 2026-08-15 00:27:03 -04:00
SonicSwordcane 1d4c6c9e88 Support playing roms by dragging into window 2026-08-15 00:18:39 -04:00
SonicSwordcane 4f3dc85bb4 Make extensions case insensitive on linux 2026-08-15 00:11:44 -04:00
SonicSwordcane 644e99c295 Make audio much more defensive 2026-08-14 23:42:02 -04:00
SonicSwordcane 1ff4fda55b chore: Release lemur version 0.14.0 2026-08-12 20:05:12 -04:00
SonicSwordcane 76b7e9d6ec Never attach dialog to window on Windows 2026-08-12 19:59:26 -04:00
SonicSwordcane e15659f6d2 Use sync API on macos 2026-08-12 19:45:59 -04:00
SonicSwordcane a926f19f79 Try only setting the window on macos 2026-08-11 23:23:22 -04:00
SonicSwordcane 8ed1019b44 Use async file picker API 2026-08-11 22:53:31 -04:00
SonicSwordcane ff8353cacc Use recommended hardware sample rate 2026-08-09 17:30:24 -04:00
SonicSwordcane 0a8663a010 Remember power preerence and force fallback 2026-08-08 22:44:00 -04:00
SonicSwordcane 05d00eee5a Improve graphics driver support and debugging
- Support WGPU_FORCE_FALLBACK to run on CPU
 - Pass display when creating wgpu instance
 - Pass compatible surface when constructing adapter
 - Log some settings (at debug level)
2026-08-08 18:38:47 -04:00
SonicSwordcane cfec6e51bf chore: Release lemur version 0.13.1 2026-07-30 19:38:35 -04:00
SonicSwordcane 88721236e7 Show (Player 1) or (Player 2) on new windows too 2026-07-30 19:38:14 -04:00
SonicSwordcane 9824e8f475 Fix "watch rom" feature not actually reloading 2026-07-30 19:33:05 -04:00
SonicSwordcane 5d86ceddd7 chore: Release lemur version 0.13.0 2026-07-16 23:57:36 -04:00
SonicSwordcane d934c843eb Display (Player 1) or (Player 2) consistently 2026-07-16 23:56:20 -04:00
SonicSwordcane b283b69f74 Fix windows growing over time 2026-07-16 23:11:14 -04:00
SonicSwordcane 828acebb89 Fix cpal initialization on windows 2026-07-14 00:13:20 -04:00
SonicSwordcane 466cf29eb7 Update cpal 2026-07-13 23:16:27 -04:00
SonicSwordcane c7628c42d8 Update several dependencies 2026-07-13 23:03:35 -04:00
SonicSwordcane 2ce0edee76 chore: Release lemur version 0.12.4 2026-05-22 00:02:15 -04:00
SonicSwordcane d21cb4e5d0 Fix controller code 2026-05-21 23:45:00 -04:00
SonicSwordcane 6e36254203 Detect diagonals better on controllers 2026-05-21 23:03:15 -04:00
SonicSwordcane 5fd1957d74 Update world inspector too 2026-05-21 21:46:16 -04:00
SonicSwordcane 19c595dd7d Update shrooms-vb-core to address affine bug 2026-05-21 17:27:58 -04:00
SonicSwordcane bb43c9aad8 chore: Release lemur version 0.12.3 2026-04-27 22:03:08 -04:00
SonicSwordcane 9256c513da Update LLVM version 2026-04-27 22:02:33 -04:00
SonicSwordcane 218a1764bc Update deps 2026-04-27 21:21:57 -04:00
SonicSwordcane ea9ca614e9 Explicitly request redraw when needed 2026-04-27 21:17:13 -04:00
SonicSwordcane dd9e04f636 Update to rust 1.95 2026-04-18 11:23:01 -04:00
SonicSwordcane f37ee878e1 chore: Release lemur version 0.12.2 2026-04-12 14:08:44 -04:00
SonicSwordcane bd0a4294e8 Update deps 2026-04-12 14:05:49 -04:00
SonicSwordcane 9934566414 Avoid unnecessary frequent rerenders 2026-04-12 14:01:34 -04:00
33 changed files with 1952 additions and 1638 deletions
Generated
+858 -1239
View File
File diff suppressed because it is too large Load Diff
+18 -18
View File
@@ -4,49 +4,49 @@ description = "An emulator for the Virtual Boy."
repository = "https://git.virtual-boy.com/PVB/lemur"
publish = false
license = "MIT"
version = "0.12.1"
version = "0.15.1"
edition = "2024"
[dependencies]
anyhow = "1"
atoi = "2"
audioadapter-buffers = "3"
atoi = "3"
audioadapter-buffers = "5"
atomic = "0.6"
bitflags = { version = "2", features = ["serde"] }
bytemuck = { version = "1", features = ["derive"] }
clap = { version = "4", features = ["derive"] }
cpal = { git = "https://github.com/sidit77/cpal.git", rev = "66ed6be" }
cpal = "0.18"
directories = "6"
egui = { version = "0.34", features = ["persistence", "serde"] }
egui_extras = { version = "0.34", features = ["image"] }
egui-notify = "0.22"
egui-winit = "0.34"
egui-wgpu = { version = "0.34", features = ["winit"] }
egui = { version = "0.36", features = ["persistence", "serde"] }
egui_extras = { version = "0.36", features = ["image"] }
egui-notify = "0.23"
egui-winit = "0.36"
egui-wgpu = { version = "0.36", features = ["winit"] }
fxprof-processed-profile = "0.8"
fixed = { version = "1.28", features = ["num-traits"] }
gilrs = { version = "0.11", features = ["serde-serialize"] }
gimli = "0.33"
gimli = "0.34"
hex = "0.4"
image = { version = "0.25", default-features = false, features = ["png"] }
itertools = "0.14"
itertools = "0.15"
normpath = "1"
notify = "8"
num-derive = "0.4"
num-derive = "0.5"
num-traits = "0.2"
object = "0.39"
object = "0.40"
oneshot = { version = "0.2", features = ["async", "std"] }
pollster = "0.4"
pollster = "1"
rand = "0.10"
rfd = "0.17"
rtrb = "0.3"
rubato = "2"
rtrb = "0.4"
rubato = "5"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thread-priority = "3"
tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "sync", "time"] }
tracing = { version = "0.1", features = ["release_max_level_info"] }
tracing = { version = "0.1", features = ["release_max_level_debug"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
wgpu = "29"
wgpu = { version = "30", features = ["serde"] }
wholesym = "0.8"
winit = { version = "0.30", features = ["serde"] }
+14 -18
View File
@@ -1,7 +1,7 @@
# This Dockerfile produces a base image for builds.
# It includes all dependencies necessary to cross-compile for Windows/MacOS/Linux.
FROM debian:bookworm AS osxcross
FROM debian:trixie AS osxcross
ADD --chmod=644 "https://apt.llvm.org/llvm-snapshot.gpg.key" /etc/apt/trusted.gpg.d/apt.llvm.org.asc
WORKDIR /build/osxcross
ADD "https://github.com/tpoechtrager/osxcross.git#47936a512273bb3b414b5a2e83043c92eabc7ae7" .
@@ -9,35 +9,31 @@ ADD "https://github.com/joseluisq/macosx-sdks/releases/download/14.5/MacOSX14.5.
RUN apt-get update && \
apt-get install -y ca-certificates
COPY llvm.sources /etc/apt/sources.list.d/llvm.sources
COPY install-llvm.sh .
RUN apt-get update && \
./install-llvm.sh && \
apt-get install -y bash bzip2 git make patch xz-utils && \
ln -s $(which clang-21) /usr/bin/clang && \
ln -s $(which clang++-21) /usr/bin/clang++ && \
ln -s $(which ld64.lld-21) /usr/bin/ld64.lld && \
apt-get install -y bash bzip2 clang-22 git lld-22 llvm-22 make patch xz-utils && \
ln -s $(which clang-22) /usr/bin/clang && \
ln -s $(which clang++-22) /usr/bin/clang++ && \
ln -s $(which ld64.lld-22) /usr/bin/ld64.lld && \
SDK_VERSION=14.5 UNATTENDED=1 ENABLE_COMPILER_RT_INSTALL=1 TARGET_DIR=/osxcross ./build.sh
FROM rust:1.94-bookworm
FROM rust:1.98-trixie
ADD --chmod=644 "https://apt.llvm.org/llvm-snapshot.gpg.key" /etc/apt/trusted.gpg.d/apt.llvm.org.asc
COPY llvm.sources /etc/apt/sources.list.d/llvm.sources
COPY install-llvm.sh .
RUN rustup target add x86_64-pc-windows-msvc && \
rustup target add x86_64-apple-darwin && \
rustup target add aarch64-apple-darwin && \
apt-get update && \
./install-llvm.sh && \
apt-get install -y libc6-dev libasound2-dev libudev-dev genisoimage mingw-w64 && \
apt-get install -y clang-22 lld-22 libc6-dev libasound2-dev libudev-dev genisoimage mingw-w64 && \
cargo install cargo-bundle xwin && \
xwin --accept-license splat --output xwin && \
rm -rf .xwin-cache && \
ln -s $(which clang-21) /usr/bin/clang && \
ln -s $(which clang++-21) /usr/bin/clang++
ln -s $(which clang-22) /usr/bin/clang && \
ln -s $(which clang++-22) /usr/bin/clang++
COPY --from=osxcross /osxcross /osxcross
ENV PATH="/osxcross/bin:$PATH" \
LD_LIBRARY_PATH="/osxcross/lib" \
CC="clang-21" CXX="clang++-21" AR="llvm-ar-21" \
CC="clang-22" CXX="clang++-22" AR="llvm-ar-22" \
CC_x86_64-apple-darwin="o64-clang" \
CXX_x86_64-apple-darwin="o64-clang++" \
CC_aarch64-apple-darwin="oa64-clang" \
@@ -47,11 +43,11 @@ ENV PATH="/osxcross/bin:$PATH" \
SHROOMS_CFLAGS_x86_64-pc-windows-msvc="-flto" \
CFLAGS_x86_64-pc-windows-msvc="-I/xwin/crt/include -I/xwin/sdk/include/ucrt -I/xwin/sdk/include/um -I/xwin/sdk/include/shared" \
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-21" \
CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER="lld-link-22" \
CARGO_TARGET_X86_64_APPLE_DARWIN_LINKER="o64-clang" \
CARGO_TARGET_X86_64_APPLE_DARWIN_AR="llvm-ar-21" \
CARGO_TARGET_X86_64_APPLE_DARWIN_AR="llvm-ar-22" \
CARGO_TARGET_AARCH64_APPLE_DARWIN_LINKER="oa64-clang" \
CARGO_TARGET_AARCH64_APPLE_DARWIN_AR="llvm-ar-21" \
RC_PATH="llvm-rc-21" \
CARGO_TARGET_AARCH64_APPLE_DARWIN_AR="llvm-ar-22" \
RC_PATH="llvm-rc-22" \
MACOSX_DEPLOYMENT_TARGET="14.5"
ENTRYPOINT ["bash"]
-19
View File
@@ -1,19 +0,0 @@
#!/usr/bin/env bash
# Hopefully temporary script to manually install working llvm packages.
# The apt index for these is broken in bookworm, and upgrading to trixie
# would make them depend on too new of a libc version.
# https://apt.llvm.org/bookworm/pool/main/l/llvm-toolchain-21/clang-21_21.1.5~%2B%2B20251023083151%2B45afac62e373-1~exp1~20251023083333.51_amd64.deb
PACKAGES=('clang-21' 'clang-tools-21' 'libclang-common-21-dev' 'libclang-cpp21' 'libclang-rt-21-dev' 'libclang1-21' 'libllvm21' 'lld-21' 'llvm-21' 'llvm-21-dev' 'llvm-21-linker-tools' 'llvm-21-runtime' 'llvm-21-tools')
FILES=()
URL='https://apt.llvm.org/bookworm/pool/main/l/llvm-toolchain-21'
VERSION='21.1.5~%2B%2B20251023083151%2B45afac62e373-1~exp1~20251023083333.51_amd64.deb'
apt-get install -y curl python3
for package in "${PACKAGES[@]}"; do
curl -O -L "$URL/${package}_$VERSION"
FILES+=("./${package}_$VERSION")
done
apt-get install -y "${FILES[@]}"
+2 -2
View File
@@ -1,4 +1,4 @@
Types: deb deb-src
URIs: http://apt.llvm.org/bookworm/
Suites: llvm-toolchain-bookworm-21
URIs: http://apt.llvm.org/trixie/
Suites: llvm-toolchain-trixie-22
Components: main
+118 -66
View File
@@ -14,22 +14,22 @@ use egui::{
use egui_wgpu::winit::Painter;
use egui_winit::EventResponse;
use gilrs::{EventType, Gilrs};
use tracing::{error, warn};
use tracing::{debug, error, warn};
use winit::{
application::ApplicationHandler,
event::WindowEvent,
event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy},
event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy, OwnedDisplayHandle},
window::{Window, WindowId},
};
use crate::{
config::CliArgs,
config::{AppConfig, CliArgs},
controller::ControllerManager,
emulator::{EmulatorClient, EmulatorCommand, SimId},
filesystem::Persistence,
images::ImageTextureLoader,
input::{MappingProvider, ShortcutProvider},
memory::MemoryClient,
persistence::Persistence,
window::{AppWindow, ChildWindow, GameScreen, GameWindow, InitArgs},
};
@@ -48,9 +48,30 @@ fn load_icon() -> anyhow::Result<IconData> {
struct SharedViewportState {
viewport_info: ViewportIdMap<ViewportInfo>,
painter: Painter,
wgpu: WgpuState,
painter: Option<Painter>,
resized_viewport: Option<ViewportId>,
}
impl SharedViewportState {
fn init_painter(&mut self, ctx: &Context, window: &Window) -> &mut Painter {
if self.painter.is_none() {
let wgpu_config = egui_wgpu::WgpuConfiguration {
surface: egui_wgpu::SurfaceConfig::HIGH_THROUGHPUT,
wgpu_setup: egui_wgpu::WgpuSetup::Existing(self.wgpu.init(window)),
..egui_wgpu::WgpuConfiguration::default()
};
let options = egui_wgpu::RendererOptions::default();
let painter =
pollster::block_on(Painter::new(ctx.clone(), wgpu_config, false, options));
self.painter = Some(painter);
}
self.painter.as_mut().unwrap()
}
fn get_painter(&mut self) -> &mut Painter {
self.painter.as_mut().unwrap()
}
}
pub struct Application {
client: EmulatorClient,
@@ -70,10 +91,12 @@ impl Application {
pub fn new(
client: EmulatorClient,
proxy: EventLoopProxy<UserEvent>,
handle: OwnedDisplayHandle,
persistence: Persistence,
args: CliArgs,
config: AppConfig,
) -> Self {
let wgpu = WgpuState::new();
let wgpu = WgpuState::new(handle, config);
let icon = load_icon().ok().map(Arc::new);
let mappings = MappingProvider::new(persistence.clone(), args.player2_controller);
let shortcuts = ShortcutProvider::new(persistence.clone());
@@ -131,20 +154,6 @@ impl Application {
});
}
let wgpu_config = egui_wgpu::WgpuConfiguration {
present_mode: wgpu::PresentMode::AutoVsync,
wgpu_setup: egui_wgpu::WgpuSetup::Existing(egui_wgpu::WgpuSetupExisting {
instance: wgpu.instance.clone(),
adapter: wgpu.adapter.clone(),
device: wgpu.device.clone(),
queue: wgpu.queue.clone(),
}),
..egui_wgpu::WgpuConfiguration::default()
};
let options = egui_wgpu::RendererOptions::default();
let painter = pollster::block_on(Painter::new(ctx.clone(), wgpu_config, false, options));
let mut initial_windows = vec![];
if let Some(port) = args.debug_port {
initial_windows.push(ChildWindow::Debugger { port: Some(port) });
@@ -184,7 +193,8 @@ impl Application {
ctx,
shared: SharedViewportState {
viewport_info: ViewportIdMap::default(),
painter,
wgpu,
painter: None,
resized_viewport: None,
},
icon,
@@ -247,7 +257,7 @@ impl Application {
continue;
}
input.viewports = self.shared.viewport_info.clone();
let output = self.ctx.run_ui(input, |ui| {
let mut output = self.ctx.run_ui(input, |ui| {
if viewport.id == ViewportId::ROOT {
self.app.show(ui);
} else if let Some(cb) = ui.viewport(|v| v.viewport_ui_cb.clone()) {
@@ -288,15 +298,16 @@ impl Application {
}
}
let clipped_primitives = self.ctx.tessellate(output.shapes, output.pixels_per_point);
self.shared.painter.paint_and_update_textures(
viewport.window.pre_present_notify();
self.shared.get_painter().paint_and_update_textures(
viewport.id,
output.pixels_per_point,
[0.0, 0.0, 0.0, 0.0],
&clipped_primitives,
&output.textures_delta,
&mut output.textures_delta,
vec![],
&viewport.window,
);
viewport.window.pre_present_notify();
}
let mut active_viewports = ViewportIdSet::default();
for (id, update) in updates {
@@ -325,7 +336,11 @@ impl Application {
id,
InitArgs {
window: &manager.window,
render_state: &self.shared.painter.render_state().unwrap(),
render_state: &self
.shared
.get_painter()
.render_state()
.unwrap(),
},
);
manager
@@ -341,7 +356,9 @@ impl Application {
if !active_viewports.contains(&ViewportId::ROOT) {
event_loop.exit();
}
self.shared.painter.gc_viewports(&active_viewports);
if let Some(painter) = self.shared.painter.as_mut() {
painter.gc_viewports(&active_viewports);
}
}
}
@@ -359,7 +376,7 @@ impl ApplicationHandler<UserEvent> for Application {
viewport_builder,
&mut self.shared,
);
let render_state = self.shared.painter.render_state().unwrap();
let render_state = self.shared.get_painter().render_state().unwrap();
GameScreen::init_pipeline(&render_state);
self.app.handle_init(
ViewportId::ROOT,
@@ -398,22 +415,28 @@ impl ApplicationHandler<UserEvent> for Application {
if close_requested && viewport_id == ViewportId::ROOT {
event_loop.exit();
}
if response.repaint {
viewport.window.request_redraw();
}
if !response.consumed {
match event {
WindowEvent::KeyboardInput { event, .. } => {
if !self.app.handle_key_event(viewport_id, &event) {
self.controllers.handle_key_event(&event);
}
WindowEvent::KeyboardInput { event, .. }
if !self.app.handle_key_event(viewport_id, &event) =>
{
self.controllers.handle_key_event(&event);
}
WindowEvent::DroppedFile(path) => {
self.app.handle_dropped_file(viewport_id, path);
}
WindowEvent::Focused(new_focused) => {
self.focused = new_focused.then_some(viewport_id);
}
WindowEvent::RedrawRequested => {
self.repaint_all(event_loop);
}
_ => {}
}
}
if response.repaint {
self.repaint_all(event_loop);
}
self.check_repaint(event_loop);
}
@@ -445,6 +468,9 @@ impl ApplicationHandler<UserEvent> for Application {
self.controllers.handle_gamepad_event(&event);
}
}
UserEvent::LowBattery(sim_id, pwr) => {
self.controllers.handle_low_battery(sim_id, pwr);
}
UserEvent::Quit(sim_id) => match sim_id {
SimId::Player1 => event_loop.exit(),
SimId::Player2 => self.app.close(ChildWindow::Player2),
@@ -477,47 +503,67 @@ impl ApplicationHandler<UserEvent> for Application {
struct WgpuState {
instance: wgpu::Instance,
adapter: wgpu::Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
device_descriptor: Arc<dyn Fn(&wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> + Send + Sync>,
config: AppConfig,
}
impl WgpuState {
fn new() -> Self {
fn new(handle: OwnedDisplayHandle, config: AppConfig) -> Self {
#[allow(unused_variables)]
let egui_wgpu::WgpuConfiguration {
wgpu_setup:
egui_wgpu::WgpuSetup::CreateNew(egui_wgpu::WgpuSetupCreateNew {
instance_descriptor: wgpu::InstanceDescriptor { backends, .. },
device_descriptor,
..
}),
let egui_wgpu::WgpuSetupCreateNew {
instance_descriptor: wgpu::InstanceDescriptor { backends, .. },
device_descriptor,
..
} = egui_wgpu::WgpuConfiguration::default()
else {
panic!("required fields not found")
};
} = egui_wgpu::WgpuSetupCreateNew::without_display_handle();
#[cfg(windows)]
let backends = wgpu::Backends::from_env()
.unwrap_or((wgpu::Backends::PRIMARY | wgpu::Backends::GL) - wgpu::Backends::VULKAN);
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends,
..wgpu::InstanceDescriptor::new_without_display_handle_from_env()
..wgpu::InstanceDescriptor::new_with_display_handle_from_env(Box::new(handle))
});
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference:
wgpu::PowerPreference::from_env().unwrap_or(wgpu::PowerPreference::LowPower),
compatible_surface: None,
force_fallback_adapter: false,
}))
.expect("could not create adapter");
let (device, queue) =
pollster::block_on(adapter.request_device(&(*device_descriptor)(&adapter)))
.expect("could not request device");
Self {
instance,
device_descriptor,
config,
}
}
fn init(&mut self, window: &Window) -> egui_wgpu::WgpuSetupExisting {
let power_preference =
wgpu::PowerPreference::from_env().unwrap_or(self.config.power_preference);
debug!("power preference: {power_preference:?}");
let force_fallback_adapter = std::env::var("WGPU_FORCE_FALLBACK")
.map_or(self.config.force_fallback, |f| {
f.eq_ignore_ascii_case("true") || f.eq_ignore_ascii_case("1")
});
debug!("force fallback: {force_fallback_adapter}");
let surface = self
.instance
.create_surface(window)
.expect("could not create surface");
let adapter =
pollster::block_on(self.instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference,
compatible_surface: Some(&surface),
force_fallback_adapter,
apply_limit_buckets: false,
}))
.expect("could not create adapter");
debug!("selected adapter: {:?}", adapter.get_info());
drop(surface);
let (device, queue) =
pollster::block_on(adapter.request_device(&(*self.device_descriptor)(&adapter)))
.expect("could not request device");
egui_wgpu::WgpuSetupExisting {
instance: self.instance.clone(),
adapter,
device,
queue,
@@ -541,14 +587,15 @@ impl ViewportManager {
shared: &mut SharedViewportState,
) -> Self {
let window = Arc::new(egui_winit::create_window(ctx, event_loop, &builder).unwrap());
pollster::block_on(shared.painter.set_window(viewport_id, Some(window.clone()))).unwrap();
let painter = shared.init_painter(ctx, &window);
pollster::block_on(painter.set_window(viewport_id, Some(window.clone()))).unwrap();
let state = egui_winit::State::new(
ctx.clone(),
viewport_id,
event_loop,
Some(window.scale_factor() as f32),
event_loop.system_theme(),
shared.painter.max_texture_side(),
painter.max_texture_side(),
);
let mut info = ViewportInfo {
@@ -585,9 +632,13 @@ impl ViewportManager {
{
if shared.resized_viewport != Some(self.id) {
shared.resized_viewport = Some(self.id);
shared.painter.on_window_resize_state_change(self.id, true);
shared
.get_painter()
.on_window_resize_state_change(self.id, true);
}
shared.painter.on_window_resized(self.id, width, height);
shared
.get_painter()
.on_window_resized(self.id, width, height);
}
let response = self.state.on_window_event(&self.window, event);
let info = shared.viewport_info.get_mut(&self.id).unwrap();
@@ -627,6 +678,7 @@ impl ViewportManager {
pub enum UserEvent {
GamepadEvent(gilrs::Event),
Quit(SimId),
LowBattery(SimId, bool),
RequestRedraw(ViewportId, Instant),
}
+162 -21
View File
@@ -1,12 +1,16 @@
use std::time::Duration;
use anyhow::{Result, bail};
use anyhow::{Context, Result, bail};
use audioadapter_buffers::direct::InterleavedSlice;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use rubato::Resampler;
use tracing::error;
use cpal::{
Device, FromSample, Sample, SampleFormat, SizedSample, StreamConfig,
traits::{DeviceTrait, HostTrait, StreamTrait},
};
use itertools::Itertools;
use rubato::{Adjustable as _, Resampler};
use tracing::warn;
pub struct Audio {
struct CpalAudio {
#[allow(unused)]
stream: cpal::Stream,
sampler: rubato::Async<f32>,
@@ -17,20 +21,32 @@ pub struct Audio {
const VB_FREQUENCY: usize = 41700;
impl Audio {
pub fn init() -> Result<Self> {
impl CpalAudio {
fn init() -> Result<Self> {
let host = cpal::default_host();
let Some(device) = host.default_output_device() else {
bail!("No output device available");
};
let Some(config) = device
let device = host
.default_output_device()
.context("no output device available")?;
let default_rate = device.default_output_config()?.sample_rate();
let supported_config = device
.supported_output_configs()?
.find(|c| c.channels() == 2 && c.sample_format().is_float())
else {
bail!("No suitable output config available");
};
let mut config = config.with_max_sample_rate().config();
let resample_ratio = config.sample_rate.0 as f64 / VB_FREQUENCY as f64;
.filter(|c| {
c.contains_rate(default_rate)
&& matches!(
c.sample_format(),
SampleFormat::F32
| SampleFormat::F64
| SampleFormat::I32
| SampleFormat::I16
)
})
.max_by(|a, b| a.cmp_default_heuristics(b))
.context("no suitable output config available")?
.with_sample_rate(default_rate);
let mut config = supported_config.config();
let resample_ratio = config.sample_rate as f64 / VB_FREQUENCY as f64;
let chunk_size = (834.0 * resample_ratio) as usize;
let sampler = rubato::Async::new_poly(
resample_ratio,
@@ -42,13 +58,30 @@ impl Audio {
)?;
config.buffer_size = cpal::BufferSize::Fixed(sampler.output_frames_max() as u32);
match supported_config.sample_format() {
SampleFormat::F32 if config.channels == 2 => {
Self::new_f32_stereo(device, config, sampler)
}
SampleFormat::F32 => Self::new::<f32>(device, config, sampler),
SampleFormat::F64 => Self::new::<f64>(device, config, sampler),
SampleFormat::I32 => Self::new::<i32>(device, config, sampler),
SampleFormat::I16 => Self::new::<i16>(device, config, sampler),
_ => bail!("unsupported sample format"),
}
}
fn new_f32_stereo(
device: Device,
config: StreamConfig,
sampler: rubato::Async<f32>,
) -> Result<Self> {
let input_buffer = Vec::with_capacity(sampler.nbr_channels() * sampler.input_frames_max());
let output_buffer = vec![0.0; sampler.nbr_channels() * sampler.output_frames_max()];
let (sample_sink, mut sample_source) =
rtrb::RingBuffer::new(sampler.output_frames_max() * 4);
let stream = device.build_output_stream(
&config,
config,
move |data: &mut [f32], _| {
let requested = data.len();
let chunk = match sample_source.read_chunk(data.len()) {
@@ -66,7 +99,7 @@ impl Audio {
}
chunk.commit_all();
},
move |error| error!(%error, "stream error"),
move |error| warn!(%error, "stream error"),
None,
)?;
stream.play()?;
@@ -79,7 +112,60 @@ impl Audio {
})
}
pub fn update(&mut self, mut samples: &[f32]) {
fn new<S: SizedSample + FromSample<f32>>(
device: Device,
config: StreamConfig,
sampler: rubato::Async<f32>,
) -> Result<Self> {
let input_buffer = Vec::with_capacity(sampler.nbr_channels() * sampler.input_frames_max());
let output_buffer = vec![0.0; sampler.nbr_channels() * sampler.output_frames_max()];
let (sample_sink, mut sample_source) =
rtrb::RingBuffer::new(sampler.output_frames_max() * 4);
let channels = config.channels as usize;
let stream = device.build_output_stream(
config,
move |data: &mut [S], _| {
let requested = data.len() * 2 / channels;
let chunk = match sample_source.read_chunk(requested) {
Ok(c) => c,
Err(rtrb::chunks::ChunkError::TooFewSlots(n)) => {
sample_source.read_chunk(n).unwrap()
}
};
let (first, second) = chunk.as_slices();
let new_samples = first
.iter()
.chain(second)
.map(|s: &f32| (*s).to_sample())
.chunks(2);
let buffer = data.iter_mut().chunks(channels);
for (dst, samples) in buffer.into_iter().zip(&new_samples) {
// channels beyond the first two are zeroed
let src = samples.chain(std::iter::repeat(S::EQUILIBRIUM));
for (d, s) in dst.zip(src) {
*d = s;
}
}
chunk.commit_all();
},
move |error| warn!(%error, "stream error"),
None,
)?;
stream.play()?;
Ok(Self {
stream,
sampler,
input_buffer,
output_buffer,
sample_sink,
})
}
fn update(&mut self, mut samples: &[f32]) {
while self.input_buffer.len() + samples.len() >= self.sampler.input_frames_next() * 2 {
let samples_needed =
(self.sampler.input_frames_next() * 2).saturating_sub(self.input_buffer.len());
@@ -117,9 +203,64 @@ impl Audio {
}
}
pub fn set_speed(&mut self, speed: f64) -> Result<()> {
fn set_speed(&mut self, speed: f64) -> Result<()> {
self.sampler
.set_resample_ratio_relative(1.0 / speed, false)?;
Ok(())
}
}
struct NoAudio {
speed: f64,
}
impl NoAudio {
fn new() -> Self {
Self { speed: 1.0 }
}
fn update(&mut self, samples: &[f32]) {
let samples = (samples.len() / 2) as f64;
let elapsed = Duration::from_secs_f64(samples / (VB_FREQUENCY as f64 * self.speed));
std::thread::sleep(elapsed);
}
fn set_speed(&mut self, speed: f64) -> Result<()> {
self.speed = speed;
Ok(())
}
}
#[allow(clippy::large_enum_variant)]
enum AudioInner {
Cpal(CpalAudio),
None(NoAudio),
}
pub struct Audio(AudioInner);
impl Audio {
pub fn init() -> Self {
match CpalAudio::init() {
Ok(a) => Self(AudioInner::Cpal(a)),
Err(e) => {
warn!("could not play audio: {e}");
Self(AudioInner::None(NoAudio::new()))
}
}
}
pub fn update(&mut self, samples: &[f32]) {
match &mut self.0 {
AudioInner::Cpal(a) => a.update(samples),
AudioInner::None(a) => a.update(samples),
}
}
pub fn set_speed(&mut self, speed: f64) -> Result<()> {
match &mut self.0 {
AudioInner::Cpal(a) => a.set_speed(speed),
AudioInner::None(a) => a.set_speed(speed),
}
}
}
+100 -5
View File
@@ -1,9 +1,10 @@
use anyhow::Result;
use clap::Parser;
use bytemuck::NoUninit;
use clap::{Parser, ValueEnum};
use egui::{Color32, Pos2, Vec2};
use serde::{Deserialize, Serialize};
use crate::{emulator::SimId, persistence::Persistence, window::DisplayMode};
use crate::{emulator::SimId, filesystem::Persistence, window::DisplayMode};
use std::path::PathBuf;
#[derive(Parser)]
@@ -47,6 +48,31 @@ pub struct CliArgs {
/// Map the first connected controller to Player 2
#[arg(long)]
pub player2_controller: bool,
/// Force the application to render with CPU, rather than GPU.
#[arg(long)]
pub wgpu_force_fallback: Option<bool>,
/// Set a preference for whether to use a low-power or high-performance GPU adapter
#[arg(long)]
pub wgpu_power_preference: Option<PowerPreferenceWrapper>,
/// Choose whether save files are kept in the rom or the data directory
#[arg(long)]
pub save_data_location: Option<SaveDataLocation>,
}
#[derive(ValueEnum, Clone, Copy)]
pub enum PowerPreferenceWrapper {
Low,
High,
None,
}
impl From<PowerPreferenceWrapper> for wgpu::PowerPreference {
fn from(value: PowerPreferenceWrapper) -> Self {
match value {
PowerPreferenceWrapper::Low => wgpu::PowerPreference::LowPower,
PowerPreferenceWrapper::High => wgpu::PowerPreference::HighPerformance,
PowerPreferenceWrapper::None => wgpu::PowerPreference::None,
}
}
}
pub const COLOR_PRESETS: [[Color32; 2]; 3] = [
@@ -64,6 +90,69 @@ pub const COLOR_PRESETS: [[Color32; 2]; 3] = [
],
];
const fn default_power_preference() -> wgpu::PowerPreference {
wgpu::PowerPreference::LowPower
}
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, ValueEnum, Debug, NoUninit)]
#[repr(usize)]
pub enum SaveDataLocation {
/// The same directory as the ROM
RomDirectory,
/// This application's data directory
DataDirectory,
}
const fn default_save_data_location() -> SaveDataLocation {
SaveDataLocation::RomDirectory
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct AppConfig {
#[serde(default = "default_power_preference")]
pub power_preference: wgpu::PowerPreference,
#[serde(default)]
pub force_fallback: bool,
#[serde(default = "default_save_data_location")]
pub save_data_location: SaveDataLocation,
}
impl AppConfig {
pub fn load(persistence: &Persistence) -> Self {
if let Ok(config) = persistence.load_config(APP_CONFIG_FILENAME) {
return config;
}
Self {
power_preference: default_power_preference(),
force_fallback: false,
save_data_location: default_save_data_location(),
}
}
pub fn save(&self, persistence: &Persistence) -> Result<()> {
persistence.save_config(APP_CONFIG_FILENAME, &self)
}
pub fn update(&mut self, args: &CliArgs) -> bool {
let mut updated = false;
if let Some(pref) = args.wgpu_power_preference {
self.power_preference = pref.into();
updated = true;
}
if let Some(force_fallback) = args.wgpu_force_fallback {
self.force_fallback = force_fallback;
updated = true;
}
if let Some(save_data_location) = args.save_data_location {
self.save_data_location = save_data_location;
updated = true;
}
updated
}
}
const APP_CONFIG_FILENAME: &str = "config";
const fn default_audio_enabled() -> bool {
true
}
@@ -76,12 +165,16 @@ pub struct SimConfig {
#[serde(default = "default_audio_enabled")]
pub audio_enabled: bool,
#[serde(default)]
pub low_battery: bool,
#[serde(default)]
pub watch_rom: bool,
#[serde(default)]
pub position: Option<Pos2>,
}
impl SimConfig {
pub fn load(persistence: &Persistence, sim_id: SimId) -> Self {
if let Ok(config) = persistence.load_config(config_filename(sim_id)) {
if let Ok(config) = persistence.load_config(sim_config_filename(sim_id)) {
return config;
}
Self {
@@ -89,16 +182,18 @@ impl SimConfig {
colors: COLOR_PRESETS[0],
dimensions: DisplayMode::Anaglyph.proportions() + Vec2::new(0.0, 22.0),
audio_enabled: true,
low_battery: false,
watch_rom: false,
position: None,
}
}
pub fn save(&self, persistence: &Persistence, sim_id: SimId) -> Result<()> {
persistence.save_config(config_filename(sim_id), self)
persistence.save_config(sim_config_filename(sim_id), self)
}
}
fn config_filename(sim_id: SimId) -> &'static str {
fn sim_config_filename(sim_id: SimId) -> &'static str {
match sim_id {
SimId::Player1 => "config_p1",
SimId::Player2 => "config_p2",
+134 -17
View File
@@ -1,4 +1,7 @@
use std::sync::{Arc, RwLock};
use std::{
collections::HashMap,
sync::{Arc, RwLock},
};
use gilrs::{Event as GamepadEvent, EventType, GamepadId, ev::Code};
use winit::{
@@ -8,12 +11,13 @@ use winit::{
use crate::{
emulator::{EmulatorClient, EmulatorCommand, SimId, VBKey},
input::{InputMapping, MappingProvider},
input::{AxisMapping, InputMapping, MappingProvider},
};
pub struct Controller {
pub sim_id: SimId,
state: VBKey,
axis_values: HashMap<(GamepadId, Code), f32>,
mapping: Arc<RwLock<InputMapping>>,
}
@@ -22,6 +26,7 @@ impl Controller {
Self {
sim_id,
state: VBKey::SGN,
axis_values: HashMap::new(),
mapping: mappings.for_sim(sim_id).clone(),
}
}
@@ -45,20 +50,23 @@ impl Controller {
(VBKey::empty(), mappings)
}
EventType::AxisChanged(_, value, code) => {
let (neg, pos) = self.map_axis(&event.id, &code)?;
let mut pressed = VBKey::empty();
let mut released = VBKey::empty();
if value < -0.75 {
pressed = pressed.union(neg);
}
if value > 0.75 {
pressed = pressed.union(pos);
}
if value > -0.65 {
released = released.union(neg);
}
if value < 0.65 {
released = released.union(pos);
let mapping = self.map_axis(&event.id, &code)?;
self.axis_values.insert((event.id, code), value);
let pair_value = mapping
.pair
.and_then(|p| self.axis_values.get(&(event.id, p)))
.copied()
.unwrap_or_default();
let neg = mapping.neg;
let pos = mapping.pos;
let (mut pressed, mut released) = axis_presses(value, pair_value, neg, pos);
if let Some(other) = mapping.pair.and_then(|p| self.map_axis(&event.id, &p)) {
let (other_pressed, other_released) =
axis_presses(pair_value, value, other.neg, other.pos);
pressed = pressed.union(other_pressed);
released = released.union(other_released);
}
(pressed, released)
}
@@ -69,6 +77,15 @@ impl Controller {
self.update_state(pressed, released)
}
pub fn low_battery(&mut self, pwr: bool) -> Option<VBKey> {
let (pressed, released) = if pwr {
(VBKey::PWR, VBKey::empty())
} else {
(VBKey::empty(), VBKey::PWR)
};
self.update_state(pressed, released)
}
fn update_state(&mut self, pressed: VBKey, released: VBKey) -> Option<VBKey> {
let old_state = self.state;
self.state = self.state.union(pressed).difference(released);
@@ -87,7 +104,7 @@ impl Controller {
self.mapping.read().unwrap().map_button(id, code)
}
fn map_axis(&self, id: &GamepadId, code: &Code) -> Option<(VBKey, VBKey)> {
fn map_axis(&self, id: &GamepadId, code: &Code) -> Option<AxisMapping> {
self.mapping.read().unwrap().map_axis(id, code)
}
}
@@ -125,4 +142,104 @@ impl ControllerManager {
}
}
}
pub fn handle_low_battery(&mut self, sim_id: SimId, pwr: bool) {
let controller = &mut self.controllers[sim_id.to_index()];
if let Some(pressed) = controller.low_battery(pwr) {
self.client
.send_command(EmulatorCommand::SetKeys(controller.sim_id, pressed));
}
}
}
fn axis_presses(value: f32, pair_value: f32, neg: VBKey, pos: VBKey) -> (VBKey, VBKey) {
use std::f32::consts::FRAC_PI_3;
let mut pressed = VBKey::empty();
let mut released = VBKey::empty();
let magnitude = value.hypot(pair_value);
let abs_angle = pair_value.atan2(value).abs();
if magnitude < 0.65 {
released = released.union(neg).union(pos);
} else if abs_angle <= FRAC_PI_3 {
// stick tilted towards positive
released = released.union(neg);
if magnitude >= 0.75 {
pressed = pressed.union(pos);
}
} else if abs_angle >= 2.0 * FRAC_PI_3 {
// stick tilted towards negative
released = released.union(pos);
if magnitude >= 0.75 {
pressed = pressed.union(neg);
}
} else {
released = released.union(neg).union(pos);
}
(pressed, released)
}
#[cfg(test)]
mod tests {
use super::{VBKey, axis_presses};
const NEG: VBKey = VBKey::LL;
const POS: VBKey = VBKey::LR;
const NONE: VBKey = VBKey::empty();
const BOTH: VBKey = NEG.union(POS);
#[test]
fn detects_no_input() {
let (pressed, released) = axis_presses(0.0, 0.0, NEG, POS);
assert_eq!(pressed, NONE);
assert_eq!(released, BOTH);
}
#[test]
fn detects_pos_input() {
let (pressed, released) = axis_presses(1.0, 0.0, NEG, POS);
assert_eq!(pressed, POS);
assert_eq!(released, NEG);
}
#[test]
fn detects_neg_input() {
let (pressed, released) = axis_presses(-1.0, 0.0, NEG, POS);
assert_eq!(pressed, NEG);
assert_eq!(released, POS);
}
#[test]
fn respects_dead_zone() {
let (pressed, released) = axis_presses(0.70, 0.0, NEG, POS);
assert_eq!(pressed, NONE);
assert_eq!(released, NEG);
}
#[test]
fn handles_diagonals_ok() {
let (pressed, released) = axis_presses(0.6, 0.6, NEG, POS);
assert_eq!(pressed, POS);
assert_eq!(released, NEG);
}
#[test]
fn ignores_diagonal_noise() {
let (pressed, released) = axis_presses(-1.0, -0.1484245, NEG, POS);
assert_eq!(pressed, NEG);
assert_eq!(released, POS);
}
#[test]
fn ignores_small_values() {
let (pressed, released) = axis_presses(-0.1484245, -1.0, NEG, POS);
assert_eq!(pressed, NONE);
assert_eq!(released, BOTH);
}
}
+77 -45
View File
@@ -18,6 +18,7 @@ use tracing::{error, warn};
use crate::{
audio::Audio,
config::SaveDataLocation,
graphics::TextureSink,
memory::{MemoryRange, MemoryRegion},
};
@@ -74,12 +75,13 @@ pub struct EmulatorBuilder {
state: Arc<Atomic<EmulatorState>>,
audio_on: Arc<[AtomicBool; 2]>,
linked: Arc<AtomicBool>,
save_data_location: Arc<Atomic<SaveDataLocation>>,
start_paused: bool,
watch_rom: Arc<[AtomicBool; 2]>,
}
impl EmulatorBuilder {
pub fn new() -> (Self, EmulatorClient) {
pub fn new(save_data_location: SaveDataLocation) -> (Self, EmulatorClient) {
let (queue, commands) = mpsc::channel();
let builder = Self {
rom: None,
@@ -91,6 +93,7 @@ impl EmulatorBuilder {
state: Arc::new(Atomic::new(EmulatorState::Paused)),
audio_on: Arc::new([AtomicBool::new(true), AtomicBool::new(true)]),
linked: Arc::new(AtomicBool::new(false)),
save_data_location: Arc::new(Atomic::new(save_data_location)),
start_paused: false,
watch_rom: Arc::new([AtomicBool::new(false), AtomicBool::new(false)]),
};
@@ -98,8 +101,9 @@ impl EmulatorBuilder {
queue,
sim_state: builder.sim_state.clone(),
state: builder.state.clone(),
watch_rom: builder.watch_rom.clone(),
linked: builder.linked.clone(),
save_data_location: builder.save_data_location.clone(),
watch_rom: builder.watch_rom.clone(),
};
(builder, client)
}
@@ -131,18 +135,42 @@ impl EmulatorBuilder {
}
pub fn build(self) -> Result<Emulator> {
let mut emulator = Emulator::new(
self.commands,
self.sim_state,
self.state,
self.audio_on,
self.watch_rom,
self.linked,
)?;
if let Some(path) = self.rom {
let Self {
rom,
commands,
sim_state,
state,
audio_on,
watch_rom,
linked,
save_data_location,
start_paused,
} = self;
let mut emulator = Emulator {
sims: vec![],
carts: [None, None],
audio: Audio::init(),
commands,
sim_state,
state,
audio_on,
watch_rom,
linked,
save_data_location,
profilers: [None, None],
renderers: HashMap::new(),
messages: HashMap::new(),
debuggers: HashMap::new(),
stdouts: HashMap::new(),
watched_regions: HashMap::new(),
eye_contents: [vec![0u8; 384 * 224 * 2], vec![0u8; 384 * 224 * 2]],
audio_samples: Vec::with_capacity(EXPECTED_FRAME_SIZE),
buffer: vec![],
};
if let Some(path) = rom {
emulator.load_cart(SimId::Player1, &path)?;
}
if self.start_paused {
if start_paused {
emulator.pause_sims()?;
}
Ok(emulator)
@@ -159,6 +187,7 @@ pub struct Emulator {
audio_on: Arc<[AtomicBool; 2]>,
watch_rom: Arc<[AtomicBool; 2]>,
linked: Arc<AtomicBool>,
save_data_location: Arc<Atomic<SaveDataLocation>>,
profilers: [Option<ProfileSender>; 2],
renderers: HashMap<SimId, TextureSink>,
messages: HashMap<SimId, mpsc::Sender<Toast>>,
@@ -171,36 +200,6 @@ pub struct Emulator {
}
impl Emulator {
fn new(
commands: mpsc::Receiver<EmulatorCommand>,
sim_state: Arc<[Atomic<SimState>; 2]>,
state: Arc<Atomic<EmulatorState>>,
audio_on: Arc<[AtomicBool; 2]>,
watch_rom: Arc<[AtomicBool; 2]>,
linked: Arc<AtomicBool>,
) -> Result<Self> {
Ok(Self {
sims: vec![],
carts: [None, None],
audio: Audio::init()?,
commands,
sim_state,
state,
audio_on,
watch_rom,
linked,
profilers: [None, None],
renderers: HashMap::new(),
messages: HashMap::new(),
debuggers: HashMap::new(),
stdouts: HashMap::new(),
watched_regions: HashMap::new(),
eye_contents: [vec![0u8; 384 * 224 * 2], vec![0u8; 384 * 224 * 2]],
audio_samples: Vec::with_capacity(EXPECTED_FRAME_SIZE),
buffer: vec![],
})
}
pub fn reload_cart(&mut self, sim_id: SimId) -> Result<()> {
let Some(cart) = &self.carts[sim_id.to_index()] else {
return Ok(());
@@ -211,7 +210,12 @@ impl Emulator {
pub fn load_cart(&mut self, sim_id: SimId, path: &Path) -> Result<()> {
let watch = self.watch_rom[sim_id.to_index()].load(Ordering::Acquire);
let cart = Cart::load(path, sim_id, watch)?;
let cart = Cart::load(
path,
sim_id,
self.save_data_location.load(Ordering::Acquire),
watch,
)?;
self.try_reset_sim(sim_id, Some(cart))?;
Ok(())
}
@@ -224,7 +228,12 @@ impl Emulator {
};
let watch = self.watch_rom[SimId::Player2.to_index()].load(Ordering::Acquire);
let cart = match file_path {
Some(rom_path) => Some(Cart::load(&rom_path, SimId::Player2, watch)?),
Some(rom_path) => Some(Cart::load(
&rom_path,
SimId::Player2,
self.save_data_location.load(Ordering::Acquire),
watch,
)?),
None => None,
};
self.try_reset_sim(SimId::Player2, cart)?;
@@ -265,7 +274,8 @@ impl Emulator {
} else if let Some(cart) = self.carts[index].as_mut()
&& cart.is_watching()
{
cart.restart_watching();
cart.reload()?;
sim.load_cart(cart.rom.clone(), cart.sram.clone())?;
}
let mut profiling = false;
if let Some(profiler) = self.profilers[sim_id.to_index()].as_ref()
@@ -686,6 +696,20 @@ impl Emulator {
cart.stop_watching();
}
}
EmulatorCommand::SetSaveDataLocation(save_data_location) => {
self.save_data_location
.store(save_data_location, Ordering::Release);
for sim_id in SimId::values() {
if let Some(cart) = self.carts[sim_id.to_index()].as_mut()
&& let Err(error) = cart.change_save_data_location(save_data_location)
{
self.report_error(
sim_id,
format!("Error changing save data location: {error}"),
);
}
}
}
EmulatorCommand::StartSecondSim(path) => {
if let Err(error) = self.start_second_sim(path) {
self.report_error(
@@ -853,6 +877,7 @@ pub enum EmulatorCommand {
LoadGame(SimId, PathBuf),
ReloadRom(SimId),
WatchRom(SimId, bool),
SetSaveDataLocation(SaveDataLocation),
StartSecondSim(Option<PathBuf>),
StopSecondSim,
Pause,
@@ -942,10 +967,14 @@ pub struct EmulatorClient {
sim_state: Arc<[Atomic<SimState>; 2]>,
state: Arc<Atomic<EmulatorState>>,
linked: Arc<AtomicBool>,
save_data_location: Arc<Atomic<SaveDataLocation>>,
watch_rom: Arc<[AtomicBool; 2]>,
}
impl EmulatorClient {
pub fn has_player_2(&self) -> bool {
self.sim_state(SimId::Player2) != SimState::Uninitialized
}
pub fn sim_state(&self, sim_id: SimId) -> SimState {
self.sim_state[sim_id.to_index()].load(Ordering::Acquire)
}
@@ -955,6 +984,9 @@ impl EmulatorClient {
pub fn are_sims_linked(&self) -> bool {
self.linked.load(Ordering::Acquire)
}
pub fn save_data_location(&self) -> SaveDataLocation {
self.save_data_location.load(Ordering::Acquire)
}
pub fn is_rom_watched(&self, sim_id: SimId) -> bool {
self.watch_rom[sim_id.to_index()].load(Ordering::Acquire)
}
+58 -11
View File
@@ -8,10 +8,15 @@ use std::{
sync::{Arc, atomic::AtomicBool},
};
use crate::emulator::{SimId, game_info::GameInfo, shrooms_vb_util::rom_from_isx};
use crate::{
config::SaveDataLocation,
emulator::{SimId, game_info::GameInfo, shrooms_vb_util::rom_from_isx},
filesystem,
};
pub struct Cart {
pub file_path: PathBuf,
sim_id: SimId,
pub rom: Vec<u8>,
sram_file: File,
pub sram: Vec<u8>,
@@ -21,18 +26,20 @@ pub struct Cart {
}
impl Cart {
pub fn load(file_path: &Path, sim_id: SimId, watch: bool) -> Result<Self> {
let rom = fs::read(file_path)?;
let (rom, info) = try_parse_isx(file_path, &rom)
.or_else(|| try_parse_elf(file_path, &rom))
.unwrap_or_else(|| (rom, GameInfo::empty(file_path)));
pub fn load(
file_path: &Path,
sim_id: SimId,
save_data_location: SaveDataLocation,
watch: bool,
) -> Result<Self> {
let (rom, info) = Self::read_rom(file_path)?;
let mut sram_file = File::options()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(sram_path(file_path, sim_id))?;
.open(sram_path(file_path, sim_id, save_data_location))?;
let sram = if sram_file.metadata()?.len() == 0 {
// new SRAM file, randomize the contents
@@ -57,6 +64,7 @@ impl Cart {
Ok(Cart {
file_path: file_path.to_path_buf(),
sim_id,
rom,
sram_file,
sram,
@@ -66,6 +74,29 @@ impl Cart {
})
}
pub fn reload(&mut self) -> Result<()> {
let (rom, info) = Self::read_rom(&self.file_path)?;
self.rom = rom;
self.info = Arc::new(info);
if self.is_watching() {
self.restart_watching();
}
Ok(())
}
pub fn change_save_data_location(
&mut self,
save_data_location: SaveDataLocation,
) -> Result<()> {
self.sram_file = File::options()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(sram_path(&self.file_path, self.sim_id, save_data_location))?;
self.save_sram()
}
pub fn save_sram(&mut self) -> Result<()> {
self.sram_file.seek(SeekFrom::Start(0))?;
self.sram_file.write_all(&self.sram)?;
@@ -92,6 +123,14 @@ impl Cart {
self.changed = Arc::new(AtomicBool::new(false));
self.watcher = None;
}
fn read_rom(file_path: &Path) -> Result<(Vec<u8>, GameInfo)> {
let rom = fs::read(file_path)?;
let (rom, info) = try_parse_isx(file_path, &rom)
.or_else(|| try_parse_elf(file_path, &rom))
.unwrap_or_else(|| (rom, GameInfo::empty(file_path)));
Ok((rom, info))
}
}
fn build_watcher(file_path: &Path, changed: Arc<AtomicBool>) -> Option<notify::RecommendedWatcher> {
@@ -162,9 +201,17 @@ fn parse_elf_program<Elf: object::read::elf::FileHeader<Endian = object::Endiann
Some(bytes)
}
fn sram_path(file_path: &Path, sim_id: SimId) -> PathBuf {
match sim_id {
SimId::Player1 => file_path.with_extension("p1.sram"),
SimId::Player2 => file_path.with_extension("p2.sram"),
fn sram_path(file_path: &Path, sim_id: SimId, save_data_location: SaveDataLocation) -> PathBuf {
let extension = match sim_id {
SimId::Player1 => "p1.sram",
SimId::Player2 => "p2.sram",
};
if let SaveDataLocation::DataDirectory = save_data_location
&& let Some(data_dir) = filesystem::init_data_dir()
&& let Some(rom_name) = file_path.file_name()
{
data_dir.join(rom_name).with_extension(extension)
} else {
file_path.with_extension(extension)
}
}
+103
View File
@@ -0,0 +1,103 @@
#[cfg(target_os = "linux")]
use std::fmt::Write as _;
use std::{
path::PathBuf,
sync::{Arc, Weak},
};
use winit::window::Window;
pub struct FilePicker {
window: Option<Weak<Window>>,
}
impl FilePicker {
pub fn new() -> Self {
Self { window: None }
}
pub fn set_window(&mut self, window: &Arc<Window>) {
self.window = Some(Arc::downgrade(window));
}
pub fn pick_file_dialog(&self) -> FileDialogBuilder {
self.new_dialog(FileDialogAction::PickFile, false)
}
pub fn save_file_dialog(&self) -> FileDialogBuilder {
self.new_dialog(FileDialogAction::SaveFile, cfg!(not(target_os = "windows")))
}
fn new_dialog(&self, action: FileDialogAction, attach_window: bool) -> FileDialogBuilder {
#[cfg(not(target_os = "macos"))]
let mut dialog = rfd::AsyncFileDialog::new();
#[cfg(target_os = "macos")]
let mut dialog = rfd::FileDialog::new();
if attach_window && let Some(window) = self.window.as_ref().and_then(|w| w.upgrade()) {
dialog = dialog.set_parent(&window);
}
FileDialogBuilder { dialog, action }
}
}
pub struct FileDialogBuilder {
#[cfg(not(target_os = "macos"))]
dialog: rfd::AsyncFileDialog,
#[cfg(target_os = "macos")]
dialog: rfd::FileDialog,
action: FileDialogAction,
}
impl FileDialogBuilder {
pub fn add_filter(self, name: impl Into<String>, extensions: &[impl ToString]) -> Self {
#[cfg(target_os = "linux")]
let exts = extensions
.iter()
.map(|ext| {
let mut normalized = String::new();
for char in ext.to_string().chars() {
if char.is_ascii_lowercase() {
let _ = write!(&mut normalized, "[{char}{}]", char.to_ascii_uppercase());
} else {
normalized.push(char);
}
}
normalized
})
.collect::<Vec<_>>();
#[cfg(target_os = "linux")]
let extensions = &exts;
Self {
dialog: self.dialog.add_filter(name, extensions),
..self
}
}
pub fn set_file_name(self, file_name: impl Into<String>) -> Self {
Self {
dialog: self.dialog.set_file_name(file_name),
..self
}
}
pub fn open(self) -> Option<PathBuf> {
#[cfg(not(target_os = "macos"))]
fn resolve(action: impl Future<Output = Option<rfd::FileHandle>>) -> Option<PathBuf> {
pollster::block_on(action).map(Into::into)
}
#[cfg(target_os = "macos")]
fn resolve(action: Option<PathBuf>) -> Option<PathBuf> {
action
}
match self.action {
FileDialogAction::PickFile => resolve(self.dialog.pick_file()),
FileDialogAction::SaveFile => resolve(self.dialog.save_file()),
}
}
}
enum FileDialogAction {
PickFile,
SaveFile,
}
+52
View File
@@ -0,0 +1,52 @@
use std::{fs, path::PathBuf};
use anyhow::{Result, bail};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
#[derive(Clone)]
pub struct Persistence {
config_dir: Option<PathBuf>,
}
impl Persistence {
pub fn new() -> Self {
Self {
config_dir: init_config_dir(),
}
}
pub fn save_config<T: Serialize>(&self, file: &str, data: &T) -> Result<()> {
if let Some(config_dir) = self.config_dir.as_ref() {
let bytes = serde_json::to_vec_pretty(data)?;
let filename = config_dir.join(file).with_extension("json");
fs::write(&filename, bytes)?;
}
Ok(())
}
pub fn load_config<T: for<'a> Deserialize<'a>>(&self, file: &str) -> Result<T> {
let Some(config_dir) = self.config_dir.as_ref() else {
bail!("config directory not found");
};
let filename = config_dir.join(file).with_extension("json");
let bytes = fs::read(filename)?;
Ok(serde_json::from_slice(&bytes)?)
}
}
fn init_config_dir() -> Option<PathBuf> {
let config_dir = project_dirs()?.config_dir().to_path_buf();
fs::create_dir_all(&config_dir).ok()?;
Some(config_dir)
}
pub fn init_data_dir() -> Option<PathBuf> {
let data_dir = project_dirs()?.data_dir().to_path_buf();
fs::create_dir_all(&data_dir).ok()?;
Some(data_dir)
}
fn project_dirs() -> Option<ProjectDirs> {
ProjectDirs::from("com", "virtual-boy", "Lemur")
}
+35 -24
View File
@@ -14,7 +14,7 @@ use winit::keyboard::{KeyCode, PhysicalKey};
use crate::{
emulator::{SimId, VBKey},
persistence::Persistence,
filesystem::Persistence,
};
#[derive(Clone, PartialEq, Eq, Hash)]
@@ -52,12 +52,28 @@ pub trait Mappings {
fn use_default_mappings(&mut self);
}
#[derive(Clone, Copy, Serialize, Deserialize)]
pub struct AxisMapping {
pub neg: VBKey,
pub pos: VBKey,
pub pair: Option<Code>,
}
impl Default for AxisMapping {
fn default() -> Self {
Self {
neg: VBKey::empty(),
pos: VBKey::empty(),
pair: None,
}
}
}
#[derive(Serialize, Deserialize)]
pub struct GamepadMapping {
buttons: HashMap<Code, VBKey>,
axes: HashMap<Code, (VBKey, VBKey)>,
axes: HashMap<Code, AxisMapping>,
default_buttons: HashMap<Code, VBKey>,
default_axes: HashMap<Code, (VBKey, VBKey)>,
default_axes: HashMap<Code, AxisMapping>,
}
impl GamepadMapping {
@@ -78,7 +94,8 @@ impl GamepadMapping {
let mut default_axes = HashMap::new();
let mut default_axis = |axis: Axis, neg: VBKey, pos: VBKey| {
if let Some(code) = gamepad.axis_code(axis) {
default_axes.insert(code, (neg, pos));
let pair = axis.second_axis().and_then(|a| gamepad.axis_code(a));
default_axes.insert(code, AxisMapping { neg, pos, pair });
}
};
default_axis(Axis::LeftStickX, VBKey::LL, VBKey::LR);
@@ -102,19 +119,13 @@ impl GamepadMapping {
}
pub fn add_axis_neg_mapping(&mut self, key: VBKey, code: Code) {
let entry = self
.axes
.entry(code)
.or_insert((VBKey::empty(), VBKey::empty()));
entry.0 = entry.0.union(key);
let entry = self.axes.entry(code).or_default();
entry.neg = entry.neg.union(key);
}
pub fn add_axis_pos_mapping(&mut self, key: VBKey, code: Code) {
let entry = self
.axes
.entry(code)
.or_insert((VBKey::empty(), VBKey::empty()));
entry.1 = entry.1.union(key);
let entry = self.axes.entry(code).or_default();
entry.pos = entry.pos.union(key);
}
fn save_mappings(&self) -> PersistedGamepadMapping {
@@ -145,11 +156,11 @@ impl GamepadMapping {
impl Mappings for GamepadMapping {
fn mapping_names(&self) -> HashMap<VBKey, Vec<String>> {
let mut results: HashMap<VBKey, Vec<String>> = HashMap::new();
for (axis, (left_keys, right_keys)) in &self.axes {
for key in left_keys.iter() {
for (axis, mapping) in &self.axes {
for key in mapping.neg.iter() {
results.entry(key).or_default().push(format!("-{axis}"));
}
for key in right_keys.iter() {
for key in mapping.pos.iter() {
results.entry(key).or_default().push(format!("+{axis}"));
}
}
@@ -162,10 +173,10 @@ impl Mappings for GamepadMapping {
}
fn clear_mappings(&mut self, key: VBKey) {
self.axes.retain(|_, (left, right)| {
*left = left.difference(key);
*right = right.difference(key);
!(left.is_empty() && right.is_empty())
self.axes.retain(|_, mapping| {
mapping.neg = mapping.neg.difference(key);
mapping.pos = mapping.pos.difference(key);
!(mapping.neg.is_empty() && mapping.pos.is_empty())
});
self.buttons.retain(|_, keys| {
*keys = keys.difference(key);
@@ -200,7 +211,7 @@ impl InputMapping {
mappings.buttons.get(code).copied()
}
pub fn map_axis(&self, id: &GamepadId, code: &Code) -> Option<(VBKey, VBKey)> {
pub fn map_axis(&self, id: &GamepadId, code: &Code) -> Option<AxisMapping> {
let mappings = self.gamepads.get(id)?.read().unwrap();
mappings.axes.get(code).copied()
}
@@ -459,9 +470,9 @@ struct PersistedKeyboardMapping {
#[derive(Serialize, Deserialize)]
struct PersistedGamepadMapping {
buttons: Vec<(Code, VBKey)>,
axes: Vec<(Code, (VBKey, VBKey))>,
axes: Vec<(Code, AxisMapping)>,
default_buttons: Vec<(Code, VBKey)>,
default_axes: Vec<(Code, (VBKey, VBKey))>,
default_axes: Vec<(Code, AxisMapping)>,
}
#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
+22 -13
View File
@@ -13,9 +13,9 @@ use tracing_subscriber::{EnvFilter, Layer, layer::SubscriberExt, util::Subscribe
use winit::event_loop::{ControlFlow, EventLoop};
use crate::{
config::{CliArgs, SimConfig},
config::{AppConfig, CliArgs, SimConfig},
emulator::SimId,
persistence::Persistence,
filesystem::Persistence,
};
mod app;
@@ -23,12 +23,13 @@ mod audio;
mod config;
mod controller;
mod emulator;
mod filepicker;
mod filesystem;
mod gdbserver;
mod graphics;
mod images;
mod input;
mod memory;
mod persistence;
mod profiler;
mod window;
@@ -59,14 +60,9 @@ fn set_panic_handler() {
eprint!("{message}");
let Some(project_dirs) = directories::ProjectDirs::from("com", "virtual-boy", "Lemur")
else {
let Some(data_dir) = filesystem::init_data_dir() else {
return;
};
let data_dir = project_dirs.data_dir();
if std::fs::create_dir_all(data_dir).is_err() {
return;
}
let timestamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
@@ -97,7 +93,14 @@ fn main() -> Result<()> {
let persistence = Persistence::new();
let (mut builder, client) = EmulatorBuilder::new();
let mut config = AppConfig::load(&persistence);
if config.update(&args) {
let _ = config.save(&persistence);
}
let p1 = SimConfig::load(&persistence, SimId::Player1);
let p2 = SimConfig::load(&persistence, SimId::Player2);
let (mut builder, client) = EmulatorBuilder::new(config.save_data_location);
if let Some(path) = &args.rom {
builder = builder.with_rom(path);
}
@@ -110,8 +113,6 @@ fn main() -> Result<()> {
if args.profile {
builder = builder.start_paused(true)
}
let p1 = SimConfig::load(&persistence, SimId::Player1);
let p2 = SimConfig::load(&persistence, SimId::Player2);
let watch = args.watch;
@@ -136,6 +137,14 @@ fn main() -> Result<()> {
let event_loop = EventLoop::with_user_event().build().unwrap();
event_loop.set_control_flow(ControlFlow::Poll);
let proxy = event_loop.create_proxy();
event_loop.run_app(&mut Application::new(client, proxy, persistence, args))?;
let handle = event_loop.owned_display_handle();
event_loop.run_app(&mut Application::new(
client,
proxy,
handle,
persistence,
args,
config,
))?;
Ok(())
}
-46
View File
@@ -1,46 +0,0 @@
use std::{fs, path::PathBuf};
use anyhow::{Result, bail};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
#[derive(Clone)]
pub struct Persistence {
dirs: Option<Dirs>,
}
impl Persistence {
pub fn new() -> Self {
Self { dirs: init_dirs() }
}
pub fn save_config<T: Serialize>(&self, file: &str, data: &T) -> Result<()> {
if let Some(dirs) = self.dirs.as_ref() {
let bytes = serde_json::to_vec_pretty(data)?;
let filename = dirs.config_dir.join(file).with_extension("json");
fs::write(&filename, bytes)?;
}
Ok(())
}
pub fn load_config<T: for<'a> Deserialize<'a>>(&self, file: &str) -> Result<T> {
let Some(dirs) = self.dirs.as_ref() else {
bail!("config directory not found");
};
let filename = dirs.config_dir.join(file).with_extension("json");
let bytes = fs::read(filename)?;
Ok(serde_json::from_slice(&bytes)?)
}
}
#[derive(Clone)]
struct Dirs {
config_dir: PathBuf,
}
fn init_dirs() -> Option<Dirs> {
let dirs = ProjectDirs::from("com", "virtual-boy", "Lemur")?;
let config_dir = dirs.config_dir().to_path_buf();
fs::create_dir_all(&config_dir).ok()?;
Some(Dirs { config_dir })
}
+8 -4
View File
@@ -1,4 +1,4 @@
use std::sync::Arc;
use std::{path::PathBuf, sync::Arc};
pub use about::AboutWindow;
use egui::{Ui, ViewportBuilder};
@@ -28,11 +28,11 @@ mod utils;
mod vip;
pub trait AppWindow {
fn sim_id(&self) -> SimId {
SimId::Player1
fn sim_id(&self) -> Option<SimId> {
None
}
fn image_url(&self, name: &str) -> String {
format!("vip://{}/{name}", self.sim_id())
format!("vip://{}/{name}", self.sim_id().unwrap_or(SimId::Player1))
}
fn initial_viewport(&self) -> ViewportBuilder;
fn show(&mut self, ui: &mut Ui);
@@ -47,6 +47,10 @@ pub trait AppWindow {
let _ = event;
false
}
fn handle_dropped_file(&mut self, path: PathBuf) -> bool {
let _ = path;
false
}
}
pub struct InitArgs<'a> {
+1 -1
View File
@@ -12,7 +12,7 @@ impl AppWindow for AboutWindow {
}
fn show(&mut self, ui: &mut Ui) {
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ui.vertical_centered(|ui| {
ui.label("Lemur Virtual Boy Emulator");
ui.label(format!("Version {}", env!("CARGO_PKG_VERSION")));
+123 -28
View File
@@ -1,17 +1,19 @@
use std::{
ops::{Deref, DerefMut},
path::PathBuf,
sync::{Arc, Mutex, atomic::AtomicBool, mpsc},
time::Duration,
};
use crate::{
app::UserEvent,
config::{COLOR_PRESETS, SimConfig},
config::{AppConfig, COLOR_PRESETS, SaveDataLocation, SimConfig},
emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId, SimState},
filepicker::FilePicker,
filesystem::Persistence,
images::ImageTextureLoader,
input::{Command, MappingProvider, ShortcutProvider},
memory::MemoryClient,
persistence::Persistence,
window::{
AboutWindow, BgMapWindow, CharacterDataWindow, FrameBufferWindow, GdbServerWindow,
HotkeysWindow, InitArgs, InputWindow, ObjectWindow, ProfileWindow, RegisterWindow,
@@ -46,13 +48,14 @@ pub struct GameWindow {
messages: mpsc::Receiver<Toast>,
message_sink: mpsc::Sender<Toast>,
color_picker: Option<ColorPickerState>,
window: Option<Arc<winit::window::Window>>,
file_picker: FilePicker,
memory: Arc<MemoryClient>,
images: Arc<ImageTextureLoader>,
mappings: MappingProvider,
children: ViewportIdMap<ChildWindowWrapper>,
child_states: UiData<ViewportIdMap<ChildState>>,
queued_children: Vec<ChildWindow>,
show_player_name: bool,
}
impl GameWindow {
@@ -69,6 +72,8 @@ impl GameWindow {
sim_id: SimId,
) -> Self {
let config = SimConfig::load(&persistence, sim_id);
let _ = proxy.send_event(UserEvent::LowBattery(sim_id, config.low_battery));
client.send_command(EmulatorCommand::WatchRom(sim_id, config.watch_rom));
let toasts = Toasts::new()
.with_anchor(Anchor::BottomLeft)
.with_margin((10.0, 10.0).into())
@@ -87,13 +92,14 @@ impl GameWindow {
messages,
message_sink,
color_picker: None,
window: None,
file_picker: FilePicker::new(),
memory: memory.clone(),
images: images.clone(),
mappings: mappings.clone(),
children: ViewportIdMap::default(),
child_states: UiData::new(),
queued_children: vec![],
show_player_name: false,
}
}
@@ -176,6 +182,13 @@ impl GameWindow {
};
let mut viewport = child.initial_viewport();
let title = viewport.title.clone().unwrap();
let sim_id = child.sim_id();
if let Some(sim_id) = sim_id
&& self.show_player_name
{
viewport.title = Some(format!("{title} ({sim_id})"));
}
if let Some(state) = self.child_states.get(&viewport_id) {
viewport.position = Some(state.position);
viewport.inner_size = Some(state.size);
@@ -184,6 +197,8 @@ impl GameWindow {
viewport_id,
ChildWindowWrapper {
app: Arc::new(Mutex::new(child)),
title,
sim_id,
updates: Some(viewport),
close_requested: Arc::new(AtomicBool::new(false)),
},
@@ -202,6 +217,10 @@ impl GameWindow {
self.handle_event(viewport_id, |window| window.handle_gamepad_event(event))
}
pub fn handle_dropped_file(&mut self, viewport_id: ViewportId, path: PathBuf) -> bool {
self.handle_event(viewport_id, |window| window.handle_dropped_file(path))
}
fn handle_event<F, R>(&mut self, viewport_id: ViewportId, cb: F) -> R
where
F: FnOnce(&mut dyn AppWindow) -> R,
@@ -238,9 +257,11 @@ impl GameWindow {
for command in ui.input_mut(|input| self.shortcuts.consume_all(input)) {
match command {
Command::OpenRom => {
let rom = rfd::FileDialog::new()
let rom = self
.file_picker
.pick_file_dialog()
.add_filter("Virtual Boy ROMs", &["vb", "vbrom", "elf", "isx"])
.pick_file();
.open();
if let Some(path) = rom {
self.client
.send_command(EmulatorCommand::LoadGame(self.sim_id, path));
@@ -294,9 +315,11 @@ impl GameWindow {
.add(self.button_for(ui.ctx(), "Open ROM", Command::OpenRom))
.clicked()
{
let rom = rfd::FileDialog::new()
let rom = self
.file_picker
.pick_file_dialog()
.add_filter("Virtual Boy ROMs", &["vb", "vbrom", "elf", "isx"])
.pick_file();
.open();
if let Some(path) = rom {
self.client
.send_command(EmulatorCommand::LoadGame(self.sim_id, path));
@@ -311,6 +334,7 @@ impl GameWindow {
}
let watch_rom = self.client.is_rom_watched(self.sim_id);
if ui.selectable_button(watch_rom, "Watch ROM").clicked() {
self.update_config(|c| c.watch_rom = !watch_rom);
self.client
.send_command(EmulatorCommand::WatchRom(self.sim_id, !watch_rom));
}
@@ -368,10 +392,18 @@ impl GameWindow {
{
pollster::block_on(self.take_screenshot());
}
ui.separator();
let low_battery = self.config.low_battery;
if ui.selectable_button(low_battery, "Low Battery").clicked() {
self.update_config(|c| c.low_battery = !low_battery);
let _ = self
.proxy
.send_event(UserEvent::LowBattery(self.sim_id, !low_battery));
}
});
ui.menu_button("Options", |ui| self.show_options_menu(ui));
ui.menu_button("Multiplayer", |ui| {
let has_player_2 = self.client.sim_state(SimId::Player2) != SimState::Uninitialized;
let has_player_2 = self.client.has_player_2();
if self.sim_id == SimId::Player1
&& !has_player_2
&& ui.button("Open Player 2").clicked()
@@ -448,13 +480,12 @@ impl GameWindow {
self.client
.send_command(EmulatorCommand::Screenshot(self.sim_id, tx));
let bytes = rx.await.context("Could not take screenshot")?;
let mut file_dialog = rfd::FileDialog::new()
let file = self
.file_picker
.save_file_dialog()
.add_filter("PNG images", &["png"])
.set_file_name("screenshot.png");
if let Some(window) = self.window.as_ref() {
file_dialog = file_dialog.set_parent(window);
}
let file = file_dialog.save_file();
.set_file_name("screenshot.png")
.open();
let Some(path) = file else {
return Ok(None);
};
@@ -573,6 +604,37 @@ impl GameWindow {
if ui.button("Hotkeys").clicked() {
self.open(ChildWindow::Hotkeys);
}
ui.menu_button("Save Data Location", |ui| {
let save_data_location = self.client.save_data_location();
let update_save_data_location = |new_location: SaveDataLocation| {
if new_location == save_data_location {
return;
};
let mut app_config = AppConfig::load(&self.persistence);
app_config.save_data_location = new_location;
let _ = app_config.save(&self.persistence);
self.client
.send_command(EmulatorCommand::SetSaveDataLocation(new_location));
};
if ui
.selectable_button(
save_data_location == SaveDataLocation::RomDirectory,
"Same Directory as ROM",
)
.clicked()
{
update_save_data_location(SaveDataLocation::RomDirectory);
}
if ui
.selectable_button(
save_data_location == SaveDataLocation::DataDirectory,
"App Data Directory",
)
.clicked()
{
update_save_data_location(SaveDataLocation::DataDirectory);
}
});
}
fn show_color_picker(&mut self, ui: &mut Ui) {
@@ -623,8 +685,8 @@ impl GameWindow {
}
impl AppWindow for GameWindow {
fn sim_id(&self) -> SimId {
self.sim_id
fn sim_id(&self) -> Option<SimId> {
Some(self.sim_id)
}
fn initial_viewport(&self) -> ViewportBuilder {
@@ -639,6 +701,30 @@ impl AppWindow for GameWindow {
}
fn show(&mut self, ui: &mut Ui) {
let has_player_2 = self.client.has_player_2();
if !self.show_player_name && has_player_2 {
ui.send_viewport_cmd(ViewportCommand::Title(format!("Lemur ({})", self.sim_id)));
for (viewport_id, child) in &self.children {
if let Some(sim_id) = child.sim_id {
ui.send_viewport_cmd_to(
*viewport_id,
ViewportCommand::Title(format!("{} ({sim_id})", child.title)),
);
}
}
self.show_player_name = true;
} else if self.show_player_name && !has_player_2 {
ui.send_viewport_cmd(ViewportCommand::Title("Lemur".to_string()));
for (viewport_id, child) in &self.children {
if child.sim_id.is_some() {
ui.send_viewport_cmd_to(
*viewport_id,
ViewportCommand::Title(child.title.clone()),
);
}
}
self.show_player_name = false;
}
self.child_states.load(ui);
let dimensions = {
let bounds = ui.content_rect();
@@ -653,13 +739,11 @@ impl AppWindow for GameWindow {
while let Ok(toast) = self.messages.try_recv() {
self.toasts.add(toast);
}
Panel::top("menubar")
.exact_size(22.0)
.show_inside(ui, |ui| {
MenuBar::new().ui(ui, |ui| {
self.show_menu(ui);
});
Panel::top("menubar").exact_size(22.0).show(ui, |ui| {
MenuBar::new().ui(ui, |ui| {
self.show_menu(ui);
});
});
if self.color_picker.is_some() {
Window::new("Color Picker")
.title_bar(false)
@@ -670,7 +754,7 @@ impl AppWindow for GameWindow {
});
}
let frame = Frame::central_panel(ui.style()).fill(Color32::BLACK);
CentralPanel::default().frame(frame).show_inside(ui, |ui| {
CentralPanel::default().frame(frame).show(ui, |ui| {
if let Some(screen) = self.screen.as_mut() {
screen.update(self.config.display_mode, self.config.colors);
ui.add(screen);
@@ -690,12 +774,15 @@ impl AppWindow for GameWindow {
let app = child.app.clone();
let viewport_builder = child.updates.take().unwrap_or_default();
let close_requested = child.close_requested.clone();
if let Some(rect) = ui.input_for(*id, |inp| inp.viewport().outer_rect) {
if let (Some(outer), Some(inner)) = ui.input_for(*id, |inp| {
let viewport = inp.viewport();
(viewport.outer_rect, viewport.inner_rect)
}) {
self.child_states.insert(
*id,
ChildState {
position: rect.min,
size: rect.size(),
position: outer.min,
size: inner.size(),
},
);
}
@@ -721,7 +808,13 @@ impl AppWindow for GameWindow {
));
self.screen = Some(screen);
}
self.window = Some(args.window.clone());
self.file_picker.set_window(args.window);
}
fn handle_dropped_file(&mut self, path: PathBuf) -> bool {
self.client
.send_command(EmulatorCommand::LoadGame(self.sim_id, path));
true
}
}
@@ -742,6 +835,8 @@ struct ColorPickerState {
struct ChildWindowWrapper {
app: Arc<Mutex<AppWrapper>>,
title: String,
sim_id: Option<SimId>,
updates: Option<ViewportBuilder>,
close_requested: Arc<AtomicBool>,
}
+4 -4
View File
@@ -42,20 +42,20 @@ impl GdbServerWindow {
}
impl AppWindow for GdbServerWindow {
fn sim_id(&self) -> SimId {
self.sim_id
fn sim_id(&self) -> Option<SimId> {
Some(self.sim_id)
}
fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default()
.with_title(format!("GDB Server ({})", self.sim_id))
.with_title("GDB Server")
.with_inner_size((300.0, 200.0))
}
fn show(&mut self, ui: &mut egui::Ui) {
let port_num: Option<u16> = self.port_str.parse().ok();
let status = self.server.status();
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ui.horizontal(|ui| {
if port_num.is_none() {
let style = ui.style_mut();
+1 -1
View File
@@ -131,7 +131,7 @@ impl AppWindow for HotkeysWindow {
}
fn show(&mut self, ui: &mut Ui) {
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ui.horizontal(|ui| {
if ui.button("Use defaults").clicked() {
self.shortcuts.reset();
+3 -3
View File
@@ -70,7 +70,7 @@ impl InputWindow {
.column(Column::remainder())
.cell_layout(Layout::left_to_right(egui::Align::Center))
.body(|mut body| {
for keys in KEY_NAMES.chunks_exact(2) {
for keys in KEY_NAMES.as_chunks::<2>().0 {
body.row(20.0, |mut row| {
for (key, name) in keys {
let binding = names.remove(key).map(|mut s| {
@@ -167,7 +167,7 @@ impl AppWindow for InputWindow {
}
fn show(&mut self, ui: &mut Ui) {
Panel::top("options").show_inside(ui, |ui| {
Panel::top("options").show(ui, |ui| {
ui.horizontal(|ui| {
let old_active_tab = self.active_tab;
ui.selectable_value(&mut self.active_tab, InputTab::Player1, "Player 1");
@@ -182,7 +182,7 @@ impl AppWindow for InputWindow {
}
});
});
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
match self.active_tab {
InputTab::Player1 => self.show_key_bindings(ui, SimId::Player1),
InputTab::Player2 => self.show_key_bindings(ui, SimId::Player2),
+14 -15
View File
@@ -1,12 +1,12 @@
use std::{fs, sync::Arc, time::Duration};
use std::{fs, time::Duration};
use anyhow::Result;
use egui::{Button, CentralPanel, Checkbox, Label, ViewportBuilder};
use egui_notify::{Anchor, Toast, Toasts};
use winit::window::Window;
use crate::{
emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId},
filepicker::FilePicker,
profiler::{Profiler, ProfilerStatus},
window::{AppWindow, InitArgs},
};
@@ -16,7 +16,7 @@ pub struct ProfileWindow {
client: EmulatorClient,
profiler: Profiler,
toasts: Toasts,
window: Option<Arc<Window>>,
file_picker: FilePicker,
}
impl ProfileWindow {
@@ -29,7 +29,7 @@ impl ProfileWindow {
.with_anchor(Anchor::BottomLeft)
.with_margin((10.0, 10.0).into())
.reverse(true),
window: None,
file_picker: FilePicker::new(),
}
}
@@ -62,13 +62,12 @@ impl ProfileWindow {
fn try_finish_recording(&mut self) -> Result<Option<String>> {
let bytes_receiver = self.profiler.finish_recording();
let mut file_dialog = rfd::FileDialog::new()
let file = self
.file_picker
.save_file_dialog()
.add_filter("Profiler files", &["json"])
.set_file_name("profile.json");
if let Some(window) = self.window.as_ref() {
file_dialog = file_dialog.set_parent(window);
}
let file = file_dialog.save_file();
.set_file_name("profile.json")
.open();
if let Some(path) = file {
let bytes = pollster::block_on(bytes_receiver)?;
let _ = fs::remove_file(&path);
@@ -82,20 +81,20 @@ impl ProfileWindow {
}
impl AppWindow for ProfileWindow {
fn sim_id(&self) -> SimId {
self.sim_id
fn sim_id(&self) -> Option<SimId> {
Some(self.sim_id)
}
fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default()
.with_title(format!("Profiler ({})", self.sim_id))
.with_title("Profiler")
.with_inner_size((300.0, 200.0))
}
fn show(&mut self, ui: &mut egui::Ui) {
let status = self.profiler.status();
let recording = matches!(status, ProfilerStatus::Recording);
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
ui.add(
@@ -164,6 +163,6 @@ impl AppWindow for ProfileWindow {
}
fn on_init(&mut self, args: InitArgs) {
self.window = Some(args.window.clone());
self.file_picker.set_window(args.window);
}
}
+4 -4
View File
@@ -29,13 +29,13 @@ impl TerminalWindow {
}
impl AppWindow for TerminalWindow {
fn sim_id(&self) -> SimId {
self.sim_id
fn sim_id(&self) -> Option<SimId> {
Some(self.sim_id)
}
fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default()
.with_title(format!("Terminal ({})", self.sim_id))
.with_title("Terminal")
.with_inner_size((640.0, 480.0))
}
@@ -54,7 +54,7 @@ impl AppWindow for TerminalWindow {
}
self.lines.back_mut().unwrap().push_str(rest);
}
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ScrollArea::vertical()
.stick_to_bottom(true)
.auto_shrink([false, false])
+10 -6
View File
@@ -1,6 +1,6 @@
use std::{
fmt::{Display, UpperHex},
ops::{Bound, Deref, DerefMut, RangeBounds},
ops::{AddAssign, Bound, Deref, DerefMut, MulAssign, RangeBounds},
str::FromStr,
};
@@ -10,7 +10,7 @@ use egui::{
RichText, Sense, Shape, Stroke, StrokeKind, TextEdit, Ui, UiBuilder, Vec2, Widget, WidgetText,
ecolor::HexColor, util::id_type_map::SerializableAny,
};
use num_traits::{CheckedAdd, CheckedSub, One};
use num_traits::{CheckedAdd, CheckedSub, One, Zero};
pub trait UiExt {
fn section(&mut self, title: impl Into<String>, add_contents: impl FnOnce(&mut Ui));
@@ -105,14 +105,16 @@ enum Direction {
pub trait Number:
Copy
+ Zero
+ One
+ AddAssign
+ MulAssign
+ CheckedAdd
+ CheckedSub
+ Eq
+ Ord
+ Display
+ FromStr
+ FromRadix16
+ UpperHex
+ Send
+ Sync
@@ -121,14 +123,16 @@ pub trait Number:
}
impl<
T: Copy
+ Zero
+ One
+ AddAssign
+ MulAssign
+ CheckedAdd
+ CheckedSub
+ Eq
+ Ord
+ Display
+ FromStr
+ FromRadix16
+ UpperHex
+ Send
+ Sync
@@ -209,8 +213,8 @@ impl<T: Number> Widget for NumberEdit<'_, T> {
let from_string = |val: &str| {
if self.hex {
let bytes = val.as_bytes();
let (result, consumed) = T::from_radix_16(bytes);
(consumed == bytes.len()).then_some(result)
let (result, consumed) = atoi::Integer::<T>::from_radix_16(bytes);
(consumed == bytes.len()).then_some(result.0)
} else {
val.parse::<T>().ok()
}
+4 -4
View File
@@ -191,19 +191,19 @@ impl BgMapWindow {
}
impl AppWindow for BgMapWindow {
fn sim_id(&self) -> SimId {
self.sim_id
fn sim_id(&self) -> Option<SimId> {
Some(self.sim_id)
}
fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default()
.with_title(format!("BG Map Data ({})", self.sim_id))
.with_title("BG Map Data")
.with_inner_size((640.0, 480.0))
}
fn show(&mut self, ui: &mut Ui) {
self.state.load(ui);
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ui.horizontal_top(|ui| {
StripBuilder::new(ui)
.size(Size::relative(0.3).at_most(200.0))
+4 -4
View File
@@ -251,19 +251,19 @@ impl CharacterDataWindow {
}
impl AppWindow for CharacterDataWindow {
fn sim_id(&self) -> SimId {
self.sim_id
fn sim_id(&self) -> Option<SimId> {
Some(self.sim_id)
}
fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default()
.with_title(format!("Character Data ({})", self.sim_id))
.with_title("Character Data")
.with_inner_size((640.0, 480.0))
}
fn show(&mut self, ui: &mut Ui) {
self.state.load(ui);
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ui.horizontal_top(|ui| {
StripBuilder::new(ui)
.size(Size::relative(0.3).at_most(200.0))
+4 -4
View File
@@ -151,19 +151,19 @@ impl FrameBufferWindow {
}
impl AppWindow for FrameBufferWindow {
fn sim_id(&self) -> SimId {
self.sim_id
fn sim_id(&self) -> Option<SimId> {
Some(self.sim_id)
}
fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default()
.with_title(format!("Frame Buffers ({})", self.sim_id))
.with_title("Frame Buffers")
.with_inner_size((640.0, 480.0))
}
fn show(&mut self, ui: &mut Ui) {
self.state.load(ui);
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ui.horizontal_top(|ui| {
StripBuilder::new(ui)
.size(Size::relative(0.3).at_most(200.0))
+4 -4
View File
@@ -207,19 +207,19 @@ impl ObjectWindow {
}
impl AppWindow for ObjectWindow {
fn sim_id(&self) -> SimId {
self.sim_id
fn sim_id(&self) -> Option<SimId> {
Some(self.sim_id)
}
fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default()
.with_title(format!("Object Data ({})", self.sim_id))
.with_title("Object Data")
.with_inner_size((640.0, 500.0))
}
fn show(&mut self, ui: &mut Ui) {
self.state.load(ui);
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ui.horizontal_top(|ui| {
StripBuilder::new(ui)
.size(Size::relative(0.3).at_most(200.0))
+4 -4
View File
@@ -630,18 +630,18 @@ fn read_address<T: MemoryValue>(registers: &MemoryRef, address: usize) -> T {
}
impl AppWindow for RegisterWindow {
fn sim_id(&self) -> SimId {
self.sim_id
fn sim_id(&self) -> Option<SimId> {
Some(self.sim_id)
}
fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default()
.with_title(format!("Registers ({})", self.sim_id))
.with_title("Registers")
.with_inner_size((800.0, 480.0))
}
fn show(&mut self, ui: &mut Ui) {
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ScrollArea::vertical().show(ui, |ui| {
ui.horizontal_top(|ui| {
let width = ui.available_width();
+4 -1
View File
@@ -1,6 +1,7 @@
use egui::{Color32, Image, ImageSource, Response, Sense, TextureOptions, Ui, Widget};
pub const GENERIC_PALETTE: [u8; 4] = [0, 32, 64, 128];
const COLOR_TRANSPARENT: Color32 = Color32::from_rgb(0x25, 0x25, 0x25);
pub fn shade(brt: u8, color: Color32) -> Color32 {
let corrected = if brt > 132 {
@@ -44,7 +45,9 @@ pub fn parse_brts(brts: &[u16; 3], color: Color32) -> [Color32; 4] {
pub fn palette_colors(palette: u8, brts: &[u8; 8], color: Color32) -> [Color32; 4] {
let colors = parse_shades(brts).map(|s| shade(s, color));
parse_palette(palette).map(|p| colors[p as usize])
let mut palette_colors = parse_palette(palette).map(|p| colors[p as usize]);
palette_colors[0] = COLOR_TRANSPARENT;
palette_colors
}
pub struct Object {
+6 -6
View File
@@ -527,19 +527,19 @@ impl WorldWindow {
}
impl AppWindow for WorldWindow {
fn sim_id(&self) -> SimId {
self.sim_id
fn sim_id(&self) -> Option<SimId> {
Some(self.sim_id)
}
fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default()
.with_title(format!("Worlds ({})", self.sim_id))
.with_title("Worlds")
.with_inner_size((640.0, 520.0))
}
fn show(&mut self, ui: &mut Ui) {
self.state.load(ui);
CentralPanel::default().show_inside(ui, |ui| {
CentralPanel::default().show(ui, |ui| {
ui.horizontal_top(|ui| {
StripBuilder::new(ui)
.size(Size::relative(0.3).at_most(200.0))
@@ -1081,8 +1081,8 @@ impl<'a> SourceCoordCalculator<'a> {
(sx, sy)
}
SourceParam::Affine(affine) => {
let sx = affine_coord(affine.src_x, x, affine.dx, affine.src_parallax.min(0));
let sy = affine_coord(affine.src_y, x, affine.dy, affine.src_parallax.min(0));
let sx = affine_coord(affine.src_x, x, affine.dx, -(affine.src_parallax.min(0)));
let sy = affine_coord(affine.src_y, x, affine.dy, -(affine.src_parallax.min(0)));
(sx, sy)
}
}