Compare commits

..
34 Commits
Author SHA1 Message Date
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
27 changed files with 1389 additions and 1260 deletions
Generated
+558 -1004
View File
File diff suppressed because it is too large Load Diff
+10 -10
View File
@@ -4,18 +4,18 @@ 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.12.2" version = "0.15.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
anyhow = "1" anyhow = "1"
atoi = "2" atoi = "3"
audioadapter-buffers = "3" audioadapter-buffers = "4"
atomic = "0.6" 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 = "0.18"
directories = "6" directories = "6"
egui = { version = "0.34", features = ["persistence", "serde"] } egui = { version = "0.34", features = ["persistence", "serde"] }
egui_extras = { version = "0.34", features = ["image"] } egui_extras = { version = "0.34", features = ["image"] }
@@ -25,28 +25,28 @@ egui-wgpu = { version = "0.34", features = ["winit"] }
fxprof-processed-profile = "0.8" fxprof-processed-profile = "0.8"
fixed = { version = "1.28", features = ["num-traits"] } fixed = { version = "1.28", features = ["num-traits"] }
gilrs = { version = "0.11", features = ["serde-serialize"] } gilrs = { version = "0.11", features = ["serde-serialize"] }
gimli = "0.33" gimli = "0.34"
hex = "0.4" hex = "0.4"
image = { version = "0.25", default-features = false, features = ["png"] } image = { version = "0.25", default-features = false, features = ["png"] }
itertools = "0.14" itertools = "0.15"
normpath = "1" normpath = "1"
notify = "8" notify = "8"
num-derive = "0.4" num-derive = "0.4"
num-traits = "0.2" num-traits = "0.2"
object = "0.39" object = "0.39"
oneshot = { version = "0.2", features = ["async", "std"] } oneshot = { version = "0.2", features = ["async", "std"] }
pollster = "0.4" pollster = "1"
rand = "0.10" rand = "0.10"
rfd = "0.17" rfd = "0.17"
rtrb = "0.3" rtrb = "0.3"
rubato = "2" rubato = "4"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
thread-priority = "3" thread-priority = "3"
tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "sync", "time"] } 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"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] }
wgpu = "29" wgpu = { version = "29", features = ["serde"] }
wholesym = "0.8" wholesym = "0.8"
winit = { version = "0.30", features = ["serde"] } winit = { version = "0.30", features = ["serde"] }
+14 -18
View File
@@ -1,7 +1,7 @@
# This Dockerfile produces a base image for builds. # This Dockerfile produces a base image for builds.
# It includes all dependencies necessary to cross-compile for Windows/MacOS/Linux. # 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 ADD --chmod=644 "https://apt.llvm.org/llvm-snapshot.gpg.key" /etc/apt/trusted.gpg.d/apt.llvm.org.asc
WORKDIR /build/osxcross WORKDIR /build/osxcross
ADD "https://github.com/tpoechtrager/osxcross.git#47936a512273bb3b414b5a2e83043c92eabc7ae7" . 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 && \ RUN apt-get update && \
apt-get install -y ca-certificates apt-get install -y ca-certificates
COPY llvm.sources /etc/apt/sources.list.d/llvm.sources COPY llvm.sources /etc/apt/sources.list.d/llvm.sources
COPY install-llvm.sh .
RUN apt-get update && \ RUN apt-get update && \
./install-llvm.sh && \ apt-get install -y bash bzip2 clang-22 git lld-22 llvm-22 make patch xz-utils && \
apt-get install -y bash bzip2 git make patch xz-utils && \ ln -s $(which clang-22) /usr/bin/clang && \
ln -s $(which clang-21) /usr/bin/clang && \ ln -s $(which clang++-22) /usr/bin/clang++ && \
ln -s $(which clang++-21) /usr/bin/clang++ && \ ln -s $(which ld64.lld-22) /usr/bin/ld64.lld && \
ln -s $(which ld64.lld-21) /usr/bin/ld64.lld && \
SDK_VERSION=14.5 UNATTENDED=1 ENABLE_COMPILER_RT_INSTALL=1 TARGET_DIR=/osxcross ./build.sh SDK_VERSION=14.5 UNATTENDED=1 ENABLE_COMPILER_RT_INSTALL=1 TARGET_DIR=/osxcross ./build.sh
FROM rust:1.94-bookworm FROM rust:1.97-trixie
ADD --chmod=644 "https://apt.llvm.org/llvm-snapshot.gpg.key" /etc/apt/trusted.gpg.d/apt.llvm.org.asc 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 llvm.sources /etc/apt/sources.list.d/llvm.sources
COPY install-llvm.sh .
RUN rustup target add x86_64-pc-windows-msvc && \ RUN rustup target add x86_64-pc-windows-msvc && \
rustup target add x86_64-apple-darwin && \ rustup target add x86_64-apple-darwin && \
rustup target add aarch64-apple-darwin && \ rustup target add aarch64-apple-darwin && \
apt-get update && \ apt-get update && \
./install-llvm.sh && \ apt-get install -y clang-22 lld-22 libc6-dev libasound2-dev libudev-dev genisoimage mingw-w64 && \
apt-get install -y libc6-dev libasound2-dev libudev-dev genisoimage mingw-w64 && \
cargo install cargo-bundle xwin && \ cargo install cargo-bundle xwin && \
xwin --accept-license splat --output xwin && \ xwin --accept-license splat --output xwin && \
rm -rf .xwin-cache && \ rm -rf .xwin-cache && \
ln -s $(which clang-21) /usr/bin/clang && \ ln -s $(which clang-22) /usr/bin/clang && \
ln -s $(which clang++-21) /usr/bin/clang++ ln -s $(which clang++-22) /usr/bin/clang++
COPY --from=osxcross /osxcross /osxcross COPY --from=osxcross /osxcross /osxcross
ENV PATH="/osxcross/bin:$PATH" \ ENV PATH="/osxcross/bin:$PATH" \
LD_LIBRARY_PATH="/osxcross/lib" \ 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" \ CC_x86_64-apple-darwin="o64-clang" \
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" \
@@ -47,11 +43,11 @@ ENV PATH="/osxcross/bin:$PATH" \
SHROOMS_CFLAGS_x86_64-pc-windows-msvc="-flto" \ 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" \ 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_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_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_LINKER="oa64-clang" \
CARGO_TARGET_AARCH64_APPLE_DARWIN_AR="llvm-ar-21" \ CARGO_TARGET_AARCH64_APPLE_DARWIN_AR="llvm-ar-22" \
RC_PATH="llvm-rc-21" \ RC_PATH="llvm-rc-22" \
MACOSX_DEPLOYMENT_TARGET="14.5" MACOSX_DEPLOYMENT_TARGET="14.5"
ENTRYPOINT ["bash"] 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 Types: deb deb-src
URIs: http://apt.llvm.org/bookworm/ URIs: http://apt.llvm.org/trixie/
Suites: llvm-toolchain-bookworm-21 Suites: llvm-toolchain-trixie-22
Components: main Components: main
+106 -56
View File
@@ -14,16 +14,16 @@ use egui::{
use egui_wgpu::winit::Painter; use egui_wgpu::winit::Painter;
use egui_winit::EventResponse; use egui_winit::EventResponse;
use gilrs::{EventType, Gilrs}; use gilrs::{EventType, Gilrs};
use tracing::{error, warn}; use tracing::{debug, error, warn};
use winit::{ use winit::{
application::ApplicationHandler, application::ApplicationHandler,
event::WindowEvent, event::WindowEvent,
event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy}, event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy, OwnedDisplayHandle},
window::{Window, WindowId}, window::{Window, WindowId},
}; };
use crate::{ use crate::{
config::CliArgs, config::{AppConfig, CliArgs},
controller::ControllerManager, controller::ControllerManager,
emulator::{EmulatorClient, EmulatorCommand, SimId}, emulator::{EmulatorClient, EmulatorCommand, SimId},
images::ImageTextureLoader, images::ImageTextureLoader,
@@ -48,9 +48,30 @@ fn load_icon() -> anyhow::Result<IconData> {
struct SharedViewportState { struct SharedViewportState {
viewport_info: ViewportIdMap<ViewportInfo>, viewport_info: ViewportIdMap<ViewportInfo>,
painter: Painter, wgpu: WgpuState,
painter: Option<Painter>,
resized_viewport: Option<ViewportId>, 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 {
present_mode: wgpu::PresentMode::AutoVsync,
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 { pub struct Application {
client: EmulatorClient, client: EmulatorClient,
@@ -70,10 +91,12 @@ impl Application {
pub fn new( pub fn new(
client: EmulatorClient, client: EmulatorClient,
proxy: EventLoopProxy<UserEvent>, proxy: EventLoopProxy<UserEvent>,
handle: OwnedDisplayHandle,
persistence: Persistence, persistence: Persistence,
args: CliArgs, args: CliArgs,
config: AppConfig,
) -> Self { ) -> Self {
let wgpu = WgpuState::new(); let wgpu = WgpuState::new(handle, config);
let icon = load_icon().ok().map(Arc::new); let icon = load_icon().ok().map(Arc::new);
let mappings = MappingProvider::new(persistence.clone(), args.player2_controller); let mappings = MappingProvider::new(persistence.clone(), args.player2_controller);
let shortcuts = ShortcutProvider::new(persistence.clone()); 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![]; let mut initial_windows = vec![];
if let Some(port) = args.debug_port { if let Some(port) = args.debug_port {
initial_windows.push(ChildWindow::Debugger { port: Some(port) }); initial_windows.push(ChildWindow::Debugger { port: Some(port) });
@@ -184,7 +193,8 @@ impl Application {
ctx, ctx,
shared: SharedViewportState { shared: SharedViewportState {
viewport_info: ViewportIdMap::default(), viewport_info: ViewportIdMap::default(),
painter, wgpu,
painter: None,
resized_viewport: None, resized_viewport: None,
}, },
icon, icon,
@@ -288,7 +298,8 @@ impl Application {
} }
} }
let clipped_primitives = self.ctx.tessellate(output.shapes, output.pixels_per_point); 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, viewport.id,
output.pixels_per_point, output.pixels_per_point,
[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0],
@@ -296,7 +307,6 @@ impl Application {
&output.textures_delta, &output.textures_delta,
vec![], vec![],
); );
viewport.window.pre_present_notify();
} }
let mut active_viewports = ViewportIdSet::default(); let mut active_viewports = ViewportIdSet::default();
for (id, update) in updates { for (id, update) in updates {
@@ -325,7 +335,11 @@ impl Application {
id, id,
InitArgs { InitArgs {
window: &manager.window, window: &manager.window,
render_state: &self.shared.painter.render_state().unwrap(), render_state: &self
.shared
.get_painter()
.render_state()
.unwrap(),
}, },
); );
manager manager
@@ -341,7 +355,9 @@ impl Application {
if !active_viewports.contains(&ViewportId::ROOT) { if !active_viewports.contains(&ViewportId::ROOT) {
event_loop.exit(); 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 +375,7 @@ impl ApplicationHandler<UserEvent> for Application {
viewport_builder, viewport_builder,
&mut self.shared, &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); GameScreen::init_pipeline(&render_state);
self.app.handle_init( self.app.handle_init(
ViewportId::ROOT, ViewportId::ROOT,
@@ -398,12 +414,18 @@ impl ApplicationHandler<UserEvent> for Application {
if close_requested && viewport_id == ViewportId::ROOT { if close_requested && viewport_id == ViewportId::ROOT {
event_loop.exit(); event_loop.exit();
} }
if response.repaint {
viewport.window.request_redraw();
}
if !response.consumed { if !response.consumed {
match event { match event {
WindowEvent::KeyboardInput { event, .. } => { WindowEvent::KeyboardInput { event, .. }
if !self.app.handle_key_event(viewport_id, &event) { if !self.app.handle_key_event(viewport_id, &event) =>
{
self.controllers.handle_key_event(&event); self.controllers.handle_key_event(&event);
} }
WindowEvent::DroppedFile(path) => {
self.app.handle_dropped_file(viewport_id, path);
} }
WindowEvent::Focused(new_focused) => { WindowEvent::Focused(new_focused) => {
self.focused = new_focused.then_some(viewport_id); self.focused = new_focused.then_some(viewport_id);
@@ -445,6 +467,9 @@ impl ApplicationHandler<UserEvent> for Application {
self.controllers.handle_gamepad_event(&event); 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 { UserEvent::Quit(sim_id) => match sim_id {
SimId::Player1 => event_loop.exit(), SimId::Player1 => event_loop.exit(),
SimId::Player2 => self.app.close(ChildWindow::Player2), SimId::Player2 => self.app.close(ChildWindow::Player2),
@@ -477,47 +502,66 @@ impl ApplicationHandler<UserEvent> for Application {
struct WgpuState { struct WgpuState {
instance: wgpu::Instance, instance: wgpu::Instance,
adapter: wgpu::Adapter, device_descriptor: Arc<dyn Fn(&wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> + Send + Sync>,
device: wgpu::Device, config: AppConfig,
queue: wgpu::Queue,
} }
impl WgpuState { impl WgpuState {
fn new() -> Self { fn new(handle: OwnedDisplayHandle, config: AppConfig) -> Self {
#[allow(unused_variables)] #[allow(unused_variables)]
let egui_wgpu::WgpuConfiguration { let egui_wgpu::WgpuSetupCreateNew {
wgpu_setup:
egui_wgpu::WgpuSetup::CreateNew(egui_wgpu::WgpuSetupCreateNew {
instance_descriptor: wgpu::InstanceDescriptor { backends, .. }, instance_descriptor: wgpu::InstanceDescriptor { backends, .. },
device_descriptor, device_descriptor,
.. ..
}), } = egui_wgpu::WgpuSetupCreateNew::without_display_handle();
..
} = egui_wgpu::WgpuConfiguration::default()
else {
panic!("required fields not found")
};
#[cfg(windows)] #[cfg(windows)]
let backends = wgpu::Backends::from_env() let backends = wgpu::Backends::from_env()
.unwrap_or((wgpu::Backends::PRIMARY | wgpu::Backends::GL) - wgpu::Backends::VULKAN); .unwrap_or((wgpu::Backends::PRIMARY | wgpu::Backends::GL) - wgpu::Backends::VULKAN);
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends, 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 { Self {
instance, 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,
}))
.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, adapter,
device, device,
queue, queue,
@@ -541,14 +585,15 @@ impl ViewportManager {
shared: &mut SharedViewportState, shared: &mut SharedViewportState,
) -> Self { ) -> Self {
let window = Arc::new(egui_winit::create_window(ctx, event_loop, &builder).unwrap()); 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( let state = egui_winit::State::new(
ctx.clone(), ctx.clone(),
viewport_id, viewport_id,
event_loop, event_loop,
Some(window.scale_factor() as f32), Some(window.scale_factor() as f32),
event_loop.system_theme(), event_loop.system_theme(),
shared.painter.max_texture_side(), painter.max_texture_side(),
); );
let mut info = ViewportInfo { let mut info = ViewportInfo {
@@ -585,9 +630,13 @@ impl ViewportManager {
{ {
if shared.resized_viewport != Some(self.id) { if shared.resized_viewport != Some(self.id) {
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 response = self.state.on_window_event(&self.window, event);
let info = shared.viewport_info.get_mut(&self.id).unwrap(); let info = shared.viewport_info.get_mut(&self.id).unwrap();
@@ -627,6 +676,7 @@ impl ViewportManager {
pub enum UserEvent { pub enum UserEvent {
GamepadEvent(gilrs::Event), GamepadEvent(gilrs::Event),
Quit(SimId), Quit(SimId),
LowBattery(SimId, bool),
RequestRedraw(ViewportId, Instant), RequestRedraw(ViewportId, Instant),
} }
+162 -21
View File
@@ -1,12 +1,16 @@
use std::time::Duration; use std::time::Duration;
use anyhow::{Result, bail}; use anyhow::{Context, Result, bail};
use audioadapter_buffers::direct::InterleavedSlice; use audioadapter_buffers::direct::InterleavedSlice;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::{
use rubato::Resampler; Device, FromSample, Sample, SampleFormat, SizedSample, StreamConfig,
use tracing::error; traits::{DeviceTrait, HostTrait, StreamTrait},
};
use itertools::Itertools;
use rubato::{Adjustable as _, Resampler};
use tracing::warn;
pub struct Audio { struct CpalAudio {
#[allow(unused)] #[allow(unused)]
stream: cpal::Stream, stream: cpal::Stream,
sampler: rubato::Async<f32>, sampler: rubato::Async<f32>,
@@ -17,20 +21,32 @@ pub struct Audio {
const VB_FREQUENCY: usize = 41700; const VB_FREQUENCY: usize = 41700;
impl Audio { impl CpalAudio {
pub fn init() -> Result<Self> { fn init() -> Result<Self> {
let host = cpal::default_host(); let host = cpal::default_host();
let Some(device) = host.default_output_device() else { let device = host
bail!("No output device available"); .default_output_device()
}; .context("no output device available")?;
let Some(config) = device let default_rate = device.default_output_config()?.sample_rate();
let supported_config = device
.supported_output_configs()? .supported_output_configs()?
.find(|c| c.channels() == 2 && c.sample_format().is_float()) .filter(|c| {
else { c.contains_rate(default_rate)
bail!("No suitable output config available"); && matches!(
}; c.sample_format(),
let mut config = config.with_max_sample_rate().config(); SampleFormat::F32
let resample_ratio = config.sample_rate.0 as f64 / VB_FREQUENCY as f64; | 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 chunk_size = (834.0 * resample_ratio) as usize;
let sampler = rubato::Async::new_poly( let sampler = rubato::Async::new_poly(
resample_ratio, resample_ratio,
@@ -42,13 +58,30 @@ impl Audio {
)?; )?;
config.buffer_size = cpal::BufferSize::Fixed(sampler.output_frames_max() as u32); 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 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 output_buffer = vec![0.0; sampler.nbr_channels() * sampler.output_frames_max()];
let (sample_sink, mut sample_source) = let (sample_sink, mut sample_source) =
rtrb::RingBuffer::new(sampler.output_frames_max() * 4); rtrb::RingBuffer::new(sampler.output_frames_max() * 4);
let stream = device.build_output_stream( let stream = device.build_output_stream(
&config, config,
move |data: &mut [f32], _| { move |data: &mut [f32], _| {
let requested = data.len(); let requested = data.len();
let chunk = match sample_source.read_chunk(data.len()) { let chunk = match sample_source.read_chunk(data.len()) {
@@ -66,7 +99,7 @@ impl Audio {
} }
chunk.commit_all(); chunk.commit_all();
}, },
move |error| error!(%error, "stream error"), move |error| warn!(%error, "stream error"),
None, None,
)?; )?;
stream.play()?; 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 { while self.input_buffer.len() + samples.len() >= self.sampler.input_frames_next() * 2 {
let samples_needed = let samples_needed =
(self.sampler.input_frames_next() * 2).saturating_sub(self.input_buffer.len()); (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 self.sampler
.set_resample_ratio_relative(1.0 / speed, false)?; .set_resample_ratio_relative(1.0 / speed, false)?;
Ok(()) 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),
}
}
}
+75 -4
View File
@@ -1,5 +1,5 @@
use anyhow::Result; use anyhow::Result;
use clap::Parser; use clap::{Parser, ValueEnum};
use egui::{Color32, Pos2, Vec2}; use egui::{Color32, Pos2, Vec2};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -47,6 +47,28 @@ pub struct CliArgs {
/// Map the first connected controller to Player 2 /// Map the first connected controller to Player 2
#[arg(long)] #[arg(long)]
pub player2_controller: bool, 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>,
}
#[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] = [ pub const COLOR_PRESETS: [[Color32; 2]; 3] = [
@@ -64,6 +86,49 @@ pub const COLOR_PRESETS: [[Color32; 2]; 3] = [
], ],
]; ];
const fn default_power_preference() -> wgpu::PowerPreference {
wgpu::PowerPreference::LowPower
}
#[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,
}
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,
}
}
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;
}
updated
}
}
const APP_CONFIG_FILENAME: &str = "config";
const fn default_audio_enabled() -> bool { const fn default_audio_enabled() -> bool {
true true
} }
@@ -76,12 +141,16 @@ pub struct SimConfig {
#[serde(default = "default_audio_enabled")] #[serde(default = "default_audio_enabled")]
pub audio_enabled: bool, pub audio_enabled: bool,
#[serde(default)] #[serde(default)]
pub low_battery: bool,
#[serde(default)]
pub watch_rom: bool,
#[serde(default)]
pub position: Option<Pos2>, pub position: Option<Pos2>,
} }
impl SimConfig { impl SimConfig {
pub fn load(persistence: &Persistence, sim_id: SimId) -> Self { 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; return config;
} }
Self { Self {
@@ -89,16 +158,18 @@ impl SimConfig {
colors: COLOR_PRESETS[0], colors: COLOR_PRESETS[0],
dimensions: DisplayMode::Anaglyph.proportions() + Vec2::new(0.0, 22.0), dimensions: DisplayMode::Anaglyph.proportions() + Vec2::new(0.0, 22.0),
audio_enabled: true, audio_enabled: true,
low_battery: false,
watch_rom: false,
position: None, position: None,
} }
} }
pub fn save(&self, persistence: &Persistence, sim_id: SimId) -> Result<()> { 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 { match sim_id {
SimId::Player1 => "config_p1", SimId::Player1 => "config_p1",
SimId::Player2 => "config_p2", 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 gilrs::{Event as GamepadEvent, EventType, GamepadId, ev::Code};
use winit::{ use winit::{
@@ -8,12 +11,13 @@ use winit::{
use crate::{ use crate::{
emulator::{EmulatorClient, EmulatorCommand, SimId, VBKey}, emulator::{EmulatorClient, EmulatorCommand, SimId, VBKey},
input::{InputMapping, MappingProvider}, input::{AxisMapping, InputMapping, MappingProvider},
}; };
pub struct Controller { pub struct Controller {
pub sim_id: SimId, pub sim_id: SimId,
state: VBKey, state: VBKey,
axis_values: HashMap<(GamepadId, Code), f32>,
mapping: Arc<RwLock<InputMapping>>, mapping: Arc<RwLock<InputMapping>>,
} }
@@ -22,6 +26,7 @@ impl Controller {
Self { Self {
sim_id, sim_id,
state: VBKey::SGN, state: VBKey::SGN,
axis_values: HashMap::new(),
mapping: mappings.for_sim(sim_id).clone(), mapping: mappings.for_sim(sim_id).clone(),
} }
} }
@@ -45,20 +50,23 @@ impl Controller {
(VBKey::empty(), mappings) (VBKey::empty(), mappings)
} }
EventType::AxisChanged(_, value, code) => { EventType::AxisChanged(_, value, code) => {
let (neg, pos) = self.map_axis(&event.id, &code)?; let mapping = self.map_axis(&event.id, &code)?;
let mut pressed = VBKey::empty(); self.axis_values.insert((event.id, code), value);
let mut released = VBKey::empty();
if value < -0.75 { let pair_value = mapping
pressed = pressed.union(neg); .pair
} .and_then(|p| self.axis_values.get(&(event.id, p)))
if value > 0.75 { .copied()
pressed = pressed.union(pos); .unwrap_or_default();
} let neg = mapping.neg;
if value > -0.65 { let pos = mapping.pos;
released = released.union(neg);
} let (mut pressed, mut released) = axis_presses(value, pair_value, neg, pos);
if value < 0.65 { if let Some(other) = mapping.pair.and_then(|p| self.map_axis(&event.id, &p)) {
released = released.union(pos); 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) (pressed, released)
} }
@@ -69,6 +77,15 @@ impl Controller {
self.update_state(pressed, released) 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> { fn update_state(&mut self, pressed: VBKey, released: VBKey) -> Option<VBKey> {
let old_state = self.state; let old_state = self.state;
self.state = self.state.union(pressed).difference(released); self.state = self.state.union(pressed).difference(released);
@@ -87,7 +104,7 @@ impl Controller {
self.mapping.read().unwrap().map_button(id, code) 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) 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);
}
} }
+10 -6
View File
@@ -138,7 +138,7 @@ impl EmulatorBuilder {
self.audio_on, self.audio_on,
self.watch_rom, self.watch_rom,
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)?;
} }
@@ -178,11 +178,11 @@ impl Emulator {
audio_on: Arc<[AtomicBool; 2]>, audio_on: Arc<[AtomicBool; 2]>,
watch_rom: Arc<[AtomicBool; 2]>, watch_rom: Arc<[AtomicBool; 2]>,
linked: Arc<AtomicBool>, linked: Arc<AtomicBool>,
) -> Result<Self> { ) -> Self {
Ok(Self { Self {
sims: vec![], sims: vec![],
carts: [None, None], carts: [None, None],
audio: Audio::init()?, audio: Audio::init(),
commands, commands,
sim_state, sim_state,
state, state,
@@ -198,7 +198,7 @@ impl Emulator {
eye_contents: [vec![0u8; 384 * 224 * 2], vec![0u8; 384 * 224 * 2]], eye_contents: [vec![0u8; 384 * 224 * 2], vec![0u8; 384 * 224 * 2]],
audio_samples: Vec::with_capacity(EXPECTED_FRAME_SIZE), audio_samples: Vec::with_capacity(EXPECTED_FRAME_SIZE),
buffer: vec![], buffer: vec![],
}) }
} }
pub fn reload_cart(&mut self, sim_id: SimId) -> Result<()> { pub fn reload_cart(&mut self, sim_id: SimId) -> Result<()> {
@@ -265,7 +265,8 @@ impl Emulator {
} else if let Some(cart) = self.carts[index].as_mut() } else if let Some(cart) = self.carts[index].as_mut()
&& cart.is_watching() && cart.is_watching()
{ {
cart.restart_watching(); cart.reload()?;
sim.load_cart(cart.rom.clone(), cart.sram.clone())?;
} }
let mut profiling = false; let mut profiling = false;
if let Some(profiler) = self.profilers[sim_id.to_index()].as_ref() if let Some(profiler) = self.profilers[sim_id.to_index()].as_ref()
@@ -946,6 +947,9 @@ pub struct EmulatorClient {
} }
impl EmulatorClient { 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 { pub fn sim_state(&self, sim_id: SimId) -> SimState {
self.sim_state[sim_id.to_index()].load(Ordering::Acquire) self.sim_state[sim_id.to_index()].load(Ordering::Acquire)
} }
+19 -4
View File
@@ -22,10 +22,7 @@ pub struct Cart {
impl Cart { impl Cart {
pub fn load(file_path: &Path, sim_id: SimId, watch: bool) -> Result<Self> { pub fn load(file_path: &Path, sim_id: SimId, watch: bool) -> Result<Self> {
let rom = fs::read(file_path)?; let (rom, info) = Self::read_rom(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)));
let mut sram_file = File::options() let mut sram_file = File::options()
.read(true) .read(true)
@@ -66,6 +63,16 @@ 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 save_sram(&mut self) -> Result<()> { pub fn save_sram(&mut self) -> Result<()> {
self.sram_file.seek(SeekFrom::Start(0))?; self.sram_file.seek(SeekFrom::Start(0))?;
self.sram_file.write_all(&self.sram)?; self.sram_file.write_all(&self.sram)?;
@@ -92,6 +99,14 @@ impl Cart {
self.changed = Arc::new(AtomicBool::new(false)); self.changed = Arc::new(AtomicBool::new(false));
self.watcher = None; 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> { fn build_watcher(file_path: &Path, changed: Arc<AtomicBool>) -> Option<notify::RecommendedWatcher> {
+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,
}
+34 -23
View File
@@ -52,12 +52,28 @@ pub trait Mappings {
fn use_default_mappings(&mut self); 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)] #[derive(Serialize, Deserialize)]
pub struct GamepadMapping { pub struct GamepadMapping {
buttons: HashMap<Code, VBKey>, buttons: HashMap<Code, VBKey>,
axes: HashMap<Code, (VBKey, VBKey)>, axes: HashMap<Code, AxisMapping>,
default_buttons: HashMap<Code, VBKey>, default_buttons: HashMap<Code, VBKey>,
default_axes: HashMap<Code, (VBKey, VBKey)>, default_axes: HashMap<Code, AxisMapping>,
} }
impl GamepadMapping { impl GamepadMapping {
@@ -78,7 +94,8 @@ impl GamepadMapping {
let mut default_axes = HashMap::new(); let mut default_axes = HashMap::new();
let mut default_axis = |axis: Axis, neg: VBKey, pos: VBKey| { let mut default_axis = |axis: Axis, neg: VBKey, pos: VBKey| {
if let Some(code) = gamepad.axis_code(axis) { 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); 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) { pub fn add_axis_neg_mapping(&mut self, key: VBKey, code: Code) {
let entry = self let entry = self.axes.entry(code).or_default();
.axes entry.neg = entry.neg.union(key);
.entry(code)
.or_insert((VBKey::empty(), VBKey::empty()));
entry.0 = entry.0.union(key);
} }
pub fn add_axis_pos_mapping(&mut self, key: VBKey, code: Code) { pub fn add_axis_pos_mapping(&mut self, key: VBKey, code: Code) {
let entry = self let entry = self.axes.entry(code).or_default();
.axes entry.pos = entry.pos.union(key);
.entry(code)
.or_insert((VBKey::empty(), VBKey::empty()));
entry.1 = entry.1.union(key);
} }
fn save_mappings(&self) -> PersistedGamepadMapping { fn save_mappings(&self) -> PersistedGamepadMapping {
@@ -145,11 +156,11 @@ impl GamepadMapping {
impl Mappings for GamepadMapping { impl Mappings for GamepadMapping {
fn mapping_names(&self) -> HashMap<VBKey, Vec<String>> { fn mapping_names(&self) -> HashMap<VBKey, Vec<String>> {
let mut results: HashMap<VBKey, Vec<String>> = HashMap::new(); let mut results: HashMap<VBKey, Vec<String>> = HashMap::new();
for (axis, (left_keys, right_keys)) in &self.axes { for (axis, mapping) in &self.axes {
for key in left_keys.iter() { for key in mapping.neg.iter() {
results.entry(key).or_default().push(format!("-{axis}")); 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}")); results.entry(key).or_default().push(format!("+{axis}"));
} }
} }
@@ -162,10 +173,10 @@ impl Mappings for GamepadMapping {
} }
fn clear_mappings(&mut self, key: VBKey) { fn clear_mappings(&mut self, key: VBKey) {
self.axes.retain(|_, (left, right)| { self.axes.retain(|_, mapping| {
*left = left.difference(key); mapping.neg = mapping.neg.difference(key);
*right = right.difference(key); mapping.pos = mapping.pos.difference(key);
!(left.is_empty() && right.is_empty()) !(mapping.neg.is_empty() && mapping.pos.is_empty())
}); });
self.buttons.retain(|_, keys| { self.buttons.retain(|_, keys| {
*keys = keys.difference(key); *keys = keys.difference(key);
@@ -200,7 +211,7 @@ impl InputMapping {
mappings.buttons.get(code).copied() 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(); let mappings = self.gamepads.get(id)?.read().unwrap();
mappings.axes.get(code).copied() mappings.axes.get(code).copied()
} }
@@ -459,9 +470,9 @@ struct PersistedKeyboardMapping {
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct PersistedGamepadMapping { struct PersistedGamepadMapping {
buttons: Vec<(Code, VBKey)>, buttons: Vec<(Code, VBKey)>,
axes: Vec<(Code, (VBKey, VBKey))>, axes: Vec<(Code, AxisMapping)>,
default_buttons: Vec<(Code, VBKey)>, default_buttons: Vec<(Code, VBKey)>,
default_axes: Vec<(Code, (VBKey, VBKey))>, default_axes: Vec<(Code, AxisMapping)>,
} }
#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] #[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
+15 -2
View File
@@ -13,7 +13,7 @@ use tracing_subscriber::{EnvFilter, Layer, layer::SubscriberExt, util::Subscribe
use winit::event_loop::{ControlFlow, EventLoop}; use winit::event_loop::{ControlFlow, EventLoop};
use crate::{ use crate::{
config::{CliArgs, SimConfig}, config::{AppConfig, CliArgs, SimConfig},
emulator::SimId, emulator::SimId,
persistence::Persistence, persistence::Persistence,
}; };
@@ -23,6 +23,7 @@ mod audio;
mod config; mod config;
mod controller; mod controller;
mod emulator; mod emulator;
mod filepicker;
mod gdbserver; mod gdbserver;
mod graphics; mod graphics;
mod images; mod images;
@@ -110,6 +111,10 @@ fn main() -> Result<()> {
if args.profile { if args.profile {
builder = builder.start_paused(true) builder = builder.start_paused(true)
} }
let mut config = AppConfig::load(&persistence);
if config.update(&args) {
let _ = config.save(&persistence);
}
let p1 = SimConfig::load(&persistence, SimId::Player1); let p1 = SimConfig::load(&persistence, SimId::Player1);
let p2 = SimConfig::load(&persistence, SimId::Player2); let p2 = SimConfig::load(&persistence, SimId::Player2);
@@ -136,6 +141,14 @@ 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, persistence, args))?; let handle = event_loop.owned_display_handle();
event_loop.run_app(&mut Application::new(
client,
proxy,
handle,
persistence,
args,
config,
))?;
Ok(()) Ok(())
} }
+8 -4
View File
@@ -1,4 +1,4 @@
use std::sync::Arc; use std::{path::PathBuf, sync::Arc};
pub use about::AboutWindow; pub use about::AboutWindow;
use egui::{Ui, ViewportBuilder}; use egui::{Ui, ViewportBuilder};
@@ -28,11 +28,11 @@ mod utils;
mod vip; mod vip;
pub trait AppWindow { pub trait AppWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
SimId::Player1 None
} }
fn image_url(&self, name: &str) -> String { 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 initial_viewport(&self) -> ViewportBuilder;
fn show(&mut self, ui: &mut Ui); fn show(&mut self, ui: &mut Ui);
@@ -47,6 +47,10 @@ pub trait AppWindow {
let _ = event; let _ = event;
false false
} }
fn handle_dropped_file(&mut self, path: PathBuf) -> bool {
let _ = path;
false
}
} }
pub struct InitArgs<'a> { pub struct InitArgs<'a> {
+85 -19
View File
@@ -1,5 +1,6 @@
use std::{ use std::{
ops::{Deref, DerefMut}, ops::{Deref, DerefMut},
path::PathBuf,
sync::{Arc, Mutex, atomic::AtomicBool, mpsc}, sync::{Arc, Mutex, atomic::AtomicBool, mpsc},
time::Duration, time::Duration,
}; };
@@ -8,6 +9,7 @@ use crate::{
app::UserEvent, app::UserEvent,
config::{COLOR_PRESETS, SimConfig}, config::{COLOR_PRESETS, SimConfig},
emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId, SimState}, emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId, SimState},
filepicker::FilePicker,
images::ImageTextureLoader, images::ImageTextureLoader,
input::{Command, MappingProvider, ShortcutProvider}, input::{Command, MappingProvider, ShortcutProvider},
memory::MemoryClient, memory::MemoryClient,
@@ -46,13 +48,14 @@ pub struct GameWindow {
messages: mpsc::Receiver<Toast>, messages: mpsc::Receiver<Toast>,
message_sink: mpsc::Sender<Toast>, message_sink: mpsc::Sender<Toast>,
color_picker: Option<ColorPickerState>, color_picker: Option<ColorPickerState>,
window: Option<Arc<winit::window::Window>>, file_picker: FilePicker,
memory: Arc<MemoryClient>, memory: Arc<MemoryClient>,
images: Arc<ImageTextureLoader>, images: Arc<ImageTextureLoader>,
mappings: MappingProvider, mappings: MappingProvider,
children: ViewportIdMap<ChildWindowWrapper>, children: ViewportIdMap<ChildWindowWrapper>,
child_states: UiData<ViewportIdMap<ChildState>>, child_states: UiData<ViewportIdMap<ChildState>>,
queued_children: Vec<ChildWindow>, queued_children: Vec<ChildWindow>,
show_player_name: bool,
} }
impl GameWindow { impl GameWindow {
@@ -69,6 +72,8 @@ impl GameWindow {
sim_id: SimId, sim_id: SimId,
) -> Self { ) -> Self {
let config = SimConfig::load(&persistence, sim_id); 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() let toasts = Toasts::new()
.with_anchor(Anchor::BottomLeft) .with_anchor(Anchor::BottomLeft)
.with_margin((10.0, 10.0).into()) .with_margin((10.0, 10.0).into())
@@ -87,13 +92,14 @@ impl GameWindow {
messages, messages,
message_sink, message_sink,
color_picker: None, color_picker: None,
window: None, file_picker: FilePicker::new(),
memory: memory.clone(), memory: memory.clone(),
images: images.clone(), images: images.clone(),
mappings: mappings.clone(), mappings: mappings.clone(),
children: ViewportIdMap::default(), children: ViewportIdMap::default(),
child_states: UiData::new(), child_states: UiData::new(),
queued_children: vec![], queued_children: vec![],
show_player_name: false,
} }
} }
@@ -176,6 +182,13 @@ impl GameWindow {
}; };
let mut viewport = child.initial_viewport(); 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) { if let Some(state) = self.child_states.get(&viewport_id) {
viewport.position = Some(state.position); viewport.position = Some(state.position);
viewport.inner_size = Some(state.size); viewport.inner_size = Some(state.size);
@@ -184,6 +197,8 @@ impl GameWindow {
viewport_id, viewport_id,
ChildWindowWrapper { ChildWindowWrapper {
app: Arc::new(Mutex::new(child)), app: Arc::new(Mutex::new(child)),
title,
sim_id,
updates: Some(viewport), updates: Some(viewport),
close_requested: Arc::new(AtomicBool::new(false)), close_requested: Arc::new(AtomicBool::new(false)),
}, },
@@ -202,6 +217,10 @@ impl GameWindow {
self.handle_event(viewport_id, |window| window.handle_gamepad_event(event)) 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 fn handle_event<F, R>(&mut self, viewport_id: ViewportId, cb: F) -> R
where where
F: FnOnce(&mut dyn AppWindow) -> R, F: FnOnce(&mut dyn AppWindow) -> R,
@@ -238,9 +257,11 @@ impl GameWindow {
for command in ui.input_mut(|input| self.shortcuts.consume_all(input)) { for command in ui.input_mut(|input| self.shortcuts.consume_all(input)) {
match command { match command {
Command::OpenRom => { Command::OpenRom => {
let rom = rfd::FileDialog::new() let rom = self
.file_picker
.pick_file_dialog()
.add_filter("Virtual Boy ROMs", &["vb", "vbrom", "elf", "isx"]) .add_filter("Virtual Boy ROMs", &["vb", "vbrom", "elf", "isx"])
.pick_file(); .open();
if let Some(path) = rom { if let Some(path) = rom {
self.client self.client
.send_command(EmulatorCommand::LoadGame(self.sim_id, path)); .send_command(EmulatorCommand::LoadGame(self.sim_id, path));
@@ -294,9 +315,11 @@ impl GameWindow {
.add(self.button_for(ui.ctx(), "Open ROM", Command::OpenRom)) .add(self.button_for(ui.ctx(), "Open ROM", Command::OpenRom))
.clicked() .clicked()
{ {
let rom = rfd::FileDialog::new() let rom = self
.file_picker
.pick_file_dialog()
.add_filter("Virtual Boy ROMs", &["vb", "vbrom", "elf", "isx"]) .add_filter("Virtual Boy ROMs", &["vb", "vbrom", "elf", "isx"])
.pick_file(); .open();
if let Some(path) = rom { if let Some(path) = rom {
self.client self.client
.send_command(EmulatorCommand::LoadGame(self.sim_id, path)); .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); let watch_rom = self.client.is_rom_watched(self.sim_id);
if ui.selectable_button(watch_rom, "Watch ROM").clicked() { if ui.selectable_button(watch_rom, "Watch ROM").clicked() {
self.update_config(|c| c.watch_rom = !watch_rom);
self.client self.client
.send_command(EmulatorCommand::WatchRom(self.sim_id, !watch_rom)); .send_command(EmulatorCommand::WatchRom(self.sim_id, !watch_rom));
} }
@@ -368,10 +392,18 @@ impl GameWindow {
{ {
pollster::block_on(self.take_screenshot()); 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("Options", |ui| self.show_options_menu(ui));
ui.menu_button("Multiplayer", |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 if self.sim_id == SimId::Player1
&& !has_player_2 && !has_player_2
&& ui.button("Open Player 2").clicked() && ui.button("Open Player 2").clicked()
@@ -448,13 +480,12 @@ impl GameWindow {
self.client self.client
.send_command(EmulatorCommand::Screenshot(self.sim_id, tx)); .send_command(EmulatorCommand::Screenshot(self.sim_id, tx));
let bytes = rx.await.context("Could not take screenshot")?; 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"]) .add_filter("PNG images", &["png"])
.set_file_name("screenshot.png"); .set_file_name("screenshot.png")
if let Some(window) = self.window.as_ref() { .open();
file_dialog = file_dialog.set_parent(window);
}
let file = file_dialog.save_file();
let Some(path) = file else { let Some(path) = file else {
return Ok(None); return Ok(None);
}; };
@@ -623,8 +654,8 @@ impl GameWindow {
} }
impl AppWindow for GameWindow { impl AppWindow for GameWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
self.sim_id Some(self.sim_id)
} }
fn initial_viewport(&self) -> ViewportBuilder { fn initial_viewport(&self) -> ViewportBuilder {
@@ -639,6 +670,30 @@ impl AppWindow for GameWindow {
} }
fn show(&mut self, ui: &mut Ui) { 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); self.child_states.load(ui);
let dimensions = { let dimensions = {
let bounds = ui.content_rect(); let bounds = ui.content_rect();
@@ -690,12 +745,15 @@ impl AppWindow for GameWindow {
let app = child.app.clone(); let app = child.app.clone();
let viewport_builder = child.updates.take().unwrap_or_default(); let viewport_builder = child.updates.take().unwrap_or_default();
let close_requested = child.close_requested.clone(); 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( self.child_states.insert(
*id, *id,
ChildState { ChildState {
position: rect.min, position: outer.min,
size: rect.size(), size: inner.size(),
}, },
); );
} }
@@ -721,7 +779,13 @@ impl AppWindow for GameWindow {
)); ));
self.screen = Some(screen); 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 +806,8 @@ struct ColorPickerState {
struct ChildWindowWrapper { struct ChildWindowWrapper {
app: Arc<Mutex<AppWrapper>>, app: Arc<Mutex<AppWrapper>>,
title: String,
sim_id: Option<SimId>,
updates: Option<ViewportBuilder>, updates: Option<ViewportBuilder>,
close_requested: Arc<AtomicBool>, close_requested: Arc<AtomicBool>,
} }
+3 -3
View File
@@ -42,13 +42,13 @@ impl GdbServerWindow {
} }
impl AppWindow for GdbServerWindow { impl AppWindow for GdbServerWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
self.sim_id Some(self.sim_id)
} }
fn initial_viewport(&self) -> ViewportBuilder { fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default() ViewportBuilder::default()
.with_title(format!("GDB Server ({})", self.sim_id)) .with_title("GDB Server")
.with_inner_size((300.0, 200.0)) .with_inner_size((300.0, 200.0))
} }
+13 -14
View File
@@ -1,12 +1,12 @@
use std::{fs, sync::Arc, time::Duration}; use std::{fs, time::Duration};
use anyhow::Result; use anyhow::Result;
use egui::{Button, CentralPanel, Checkbox, Label, ViewportBuilder}; use egui::{Button, CentralPanel, Checkbox, Label, ViewportBuilder};
use egui_notify::{Anchor, Toast, Toasts}; use egui_notify::{Anchor, Toast, Toasts};
use winit::window::Window;
use crate::{ use crate::{
emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId}, emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId},
filepicker::FilePicker,
profiler::{Profiler, ProfilerStatus}, profiler::{Profiler, ProfilerStatus},
window::{AppWindow, InitArgs}, window::{AppWindow, InitArgs},
}; };
@@ -16,7 +16,7 @@ pub struct ProfileWindow {
client: EmulatorClient, client: EmulatorClient,
profiler: Profiler, profiler: Profiler,
toasts: Toasts, toasts: Toasts,
window: Option<Arc<Window>>, file_picker: FilePicker,
} }
impl ProfileWindow { impl ProfileWindow {
@@ -29,7 +29,7 @@ impl ProfileWindow {
.with_anchor(Anchor::BottomLeft) .with_anchor(Anchor::BottomLeft)
.with_margin((10.0, 10.0).into()) .with_margin((10.0, 10.0).into())
.reverse(true), .reverse(true),
window: None, file_picker: FilePicker::new(),
} }
} }
@@ -62,13 +62,12 @@ impl ProfileWindow {
fn try_finish_recording(&mut self) -> Result<Option<String>> { fn try_finish_recording(&mut self) -> Result<Option<String>> {
let bytes_receiver = self.profiler.finish_recording(); 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"]) .add_filter("Profiler files", &["json"])
.set_file_name("profile.json"); .set_file_name("profile.json")
if let Some(window) = self.window.as_ref() { .open();
file_dialog = file_dialog.set_parent(window);
}
let file = file_dialog.save_file();
if let Some(path) = file { if let Some(path) = file {
let bytes = pollster::block_on(bytes_receiver)?; let bytes = pollster::block_on(bytes_receiver)?;
let _ = fs::remove_file(&path); let _ = fs::remove_file(&path);
@@ -82,13 +81,13 @@ impl ProfileWindow {
} }
impl AppWindow for ProfileWindow { impl AppWindow for ProfileWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
self.sim_id Some(self.sim_id)
} }
fn initial_viewport(&self) -> ViewportBuilder { fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default() ViewportBuilder::default()
.with_title(format!("Profiler ({})", self.sim_id)) .with_title("Profiler")
.with_inner_size((300.0, 200.0)) .with_inner_size((300.0, 200.0))
} }
@@ -164,6 +163,6 @@ impl AppWindow for ProfileWindow {
} }
fn on_init(&mut self, args: InitArgs) { fn on_init(&mut self, args: InitArgs) {
self.window = Some(args.window.clone()); self.file_picker.set_window(args.window);
} }
} }
+3 -3
View File
@@ -29,13 +29,13 @@ impl TerminalWindow {
} }
impl AppWindow for TerminalWindow { impl AppWindow for TerminalWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
self.sim_id Some(self.sim_id)
} }
fn initial_viewport(&self) -> ViewportBuilder { fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default() ViewportBuilder::default()
.with_title(format!("Terminal ({})", self.sim_id)) .with_title("Terminal")
.with_inner_size((640.0, 480.0)) .with_inner_size((640.0, 480.0))
} }
+10 -6
View File
@@ -1,6 +1,6 @@
use std::{ use std::{
fmt::{Display, UpperHex}, fmt::{Display, UpperHex},
ops::{Bound, Deref, DerefMut, RangeBounds}, ops::{AddAssign, Bound, Deref, DerefMut, MulAssign, RangeBounds},
str::FromStr, str::FromStr,
}; };
@@ -10,7 +10,7 @@ use egui::{
RichText, Sense, Shape, Stroke, StrokeKind, TextEdit, Ui, UiBuilder, Vec2, Widget, WidgetText, RichText, Sense, Shape, Stroke, StrokeKind, TextEdit, Ui, UiBuilder, Vec2, Widget, WidgetText,
ecolor::HexColor, util::id_type_map::SerializableAny, ecolor::HexColor, util::id_type_map::SerializableAny,
}; };
use num_traits::{CheckedAdd, CheckedSub, One}; use num_traits::{CheckedAdd, CheckedSub, One, Zero};
pub trait UiExt { pub trait UiExt {
fn section(&mut self, title: impl Into<String>, add_contents: impl FnOnce(&mut Ui)); fn section(&mut self, title: impl Into<String>, add_contents: impl FnOnce(&mut Ui));
@@ -105,14 +105,16 @@ enum Direction {
pub trait Number: pub trait Number:
Copy Copy
+ Zero
+ One + One
+ AddAssign
+ MulAssign
+ CheckedAdd + CheckedAdd
+ CheckedSub + CheckedSub
+ Eq + Eq
+ Ord + Ord
+ Display + Display
+ FromStr + FromStr
+ FromRadix16
+ UpperHex + UpperHex
+ Send + Send
+ Sync + Sync
@@ -121,14 +123,16 @@ pub trait Number:
} }
impl< impl<
T: Copy T: Copy
+ Zero
+ One + One
+ AddAssign
+ MulAssign
+ CheckedAdd + CheckedAdd
+ CheckedSub + CheckedSub
+ Eq + Eq
+ Ord + Ord
+ Display + Display
+ FromStr + FromStr
+ FromRadix16
+ UpperHex + UpperHex
+ Send + Send
+ Sync + Sync
@@ -209,8 +213,8 @@ impl<T: Number> Widget for NumberEdit<'_, T> {
let from_string = |val: &str| { let from_string = |val: &str| {
if self.hex { if self.hex {
let bytes = val.as_bytes(); let bytes = val.as_bytes();
let (result, consumed) = T::from_radix_16(bytes); let (result, consumed) = atoi::Integer::<T>::from_radix_16(bytes);
(consumed == bytes.len()).then_some(result) (consumed == bytes.len()).then_some(result.0)
} else { } else {
val.parse::<T>().ok() val.parse::<T>().ok()
} }
+3 -3
View File
@@ -191,13 +191,13 @@ impl BgMapWindow {
} }
impl AppWindow for BgMapWindow { impl AppWindow for BgMapWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
self.sim_id Some(self.sim_id)
} }
fn initial_viewport(&self) -> ViewportBuilder { fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default() ViewportBuilder::default()
.with_title(format!("BG Map Data ({})", self.sim_id)) .with_title("BG Map Data")
.with_inner_size((640.0, 480.0)) .with_inner_size((640.0, 480.0))
} }
+3 -3
View File
@@ -251,13 +251,13 @@ impl CharacterDataWindow {
} }
impl AppWindow for CharacterDataWindow { impl AppWindow for CharacterDataWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
self.sim_id Some(self.sim_id)
} }
fn initial_viewport(&self) -> ViewportBuilder { fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default() ViewportBuilder::default()
.with_title(format!("Character Data ({})", self.sim_id)) .with_title("Character Data")
.with_inner_size((640.0, 480.0)) .with_inner_size((640.0, 480.0))
} }
+3 -3
View File
@@ -151,13 +151,13 @@ impl FrameBufferWindow {
} }
impl AppWindow for FrameBufferWindow { impl AppWindow for FrameBufferWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
self.sim_id Some(self.sim_id)
} }
fn initial_viewport(&self) -> ViewportBuilder { fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default() ViewportBuilder::default()
.with_title(format!("Frame Buffers ({})", self.sim_id)) .with_title("Frame Buffers")
.with_inner_size((640.0, 480.0)) .with_inner_size((640.0, 480.0))
} }
+3 -3
View File
@@ -207,13 +207,13 @@ impl ObjectWindow {
} }
impl AppWindow for ObjectWindow { impl AppWindow for ObjectWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
self.sim_id Some(self.sim_id)
} }
fn initial_viewport(&self) -> ViewportBuilder { fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default() ViewportBuilder::default()
.with_title(format!("Object Data ({})", self.sim_id)) .with_title("Object Data")
.with_inner_size((640.0, 500.0)) .with_inner_size((640.0, 500.0))
} }
+3 -3
View File
@@ -630,13 +630,13 @@ fn read_address<T: MemoryValue>(registers: &MemoryRef, address: usize) -> T {
} }
impl AppWindow for RegisterWindow { impl AppWindow for RegisterWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
self.sim_id Some(self.sim_id)
} }
fn initial_viewport(&self) -> ViewportBuilder { fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default() ViewportBuilder::default()
.with_title(format!("Registers ({})", self.sim_id)) .with_title("Registers")
.with_inner_size((800.0, 480.0)) .with_inner_size((800.0, 480.0))
} }
+5 -5
View File
@@ -527,13 +527,13 @@ impl WorldWindow {
} }
impl AppWindow for WorldWindow { impl AppWindow for WorldWindow {
fn sim_id(&self) -> SimId { fn sim_id(&self) -> Option<SimId> {
self.sim_id Some(self.sim_id)
} }
fn initial_viewport(&self) -> ViewportBuilder { fn initial_viewport(&self) -> ViewportBuilder {
ViewportBuilder::default() ViewportBuilder::default()
.with_title(format!("Worlds ({})", self.sim_id)) .with_title("Worlds")
.with_inner_size((640.0, 520.0)) .with_inner_size((640.0, 520.0))
} }
@@ -1081,8 +1081,8 @@ impl<'a> SourceCoordCalculator<'a> {
(sx, sy) (sx, sy)
} }
SourceParam::Affine(affine) => { SourceParam::Affine(affine) => {
let sx = affine_coord(affine.src_x, x, affine.dx, 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)); let sy = affine_coord(affine.src_y, x, affine.dy, -(affine.src_parallax.min(0)));
(sx, sy) (sx, sy)
} }
} }