Compare commits
21 Commits
0debae0678
...
f7cf960b62
Author | SHA1 | Date |
---|---|---|
|
f7cf960b62 | |
|
b888d1140a | |
|
7356287030 | |
|
b5e1711a56 | |
|
92ccc482ae | |
|
c4f17bfc13 | |
|
dfcfd17bfc | |
|
d16c5363da | |
|
a5676c20d1 | |
|
ba15dc77ae | |
|
ebe444870f | |
|
a461faf89d | |
|
a82389224f | |
|
600148c781 | |
|
4601f1b52f | |
|
57eebb5874 | |
|
75779f2b24 | |
|
6c9265cb78 | |
|
5f17469dc2 | |
|
db36332307 | |
|
8df05d923d |
|
@ -1763,7 +1763,7 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lemur"
|
name = "lemur"
|
||||||
version = "0.3.1"
|
version = "0.3.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"atoi",
|
"atoi",
|
||||||
|
|
|
@ -4,7 +4,7 @@ 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.3.1"
|
version = "0.3.2"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
@ -35,7 +35,7 @@ rubato = "0.16"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
thread-priority = "1"
|
thread-priority = "1"
|
||||||
tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "sync"] }
|
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_info"] }
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
wgpu = "23"
|
wgpu = "23"
|
||||||
|
|
165
src/app.rs
165
src/app.rs
|
@ -18,8 +18,13 @@ use crate::{
|
||||||
controller::ControllerManager,
|
controller::ControllerManager,
|
||||||
emulator::{EmulatorClient, EmulatorCommand, SimId},
|
emulator::{EmulatorClient, EmulatorCommand, SimId},
|
||||||
input::MappingProvider,
|
input::MappingProvider,
|
||||||
|
memory::MemoryClient,
|
||||||
persistence::Persistence,
|
persistence::Persistence,
|
||||||
window::{AboutWindow, AppWindow, GameWindow, GdbServerWindow, InputWindow},
|
vram::VramProcessor,
|
||||||
|
window::{
|
||||||
|
AboutWindow, AppWindow, BgMapWindow, CharacterDataWindow, GameWindow, GdbServerWindow,
|
||||||
|
InputWindow, ObjectWindow,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn load_icon() -> anyhow::Result<IconData> {
|
fn load_icon() -> anyhow::Result<IconData> {
|
||||||
|
@ -35,10 +40,13 @@ fn load_icon() -> anyhow::Result<IconData> {
|
||||||
|
|
||||||
pub struct Application {
|
pub struct Application {
|
||||||
icon: Option<Arc<IconData>>,
|
icon: Option<Arc<IconData>>,
|
||||||
|
wgpu: WgpuState,
|
||||||
client: EmulatorClient,
|
client: EmulatorClient,
|
||||||
proxy: EventLoopProxy<UserEvent>,
|
proxy: EventLoopProxy<UserEvent>,
|
||||||
mappings: MappingProvider,
|
mappings: MappingProvider,
|
||||||
controllers: ControllerManager,
|
controllers: ControllerManager,
|
||||||
|
memory: Arc<MemoryClient>,
|
||||||
|
vram: VramProcessor,
|
||||||
persistence: Persistence,
|
persistence: Persistence,
|
||||||
viewports: HashMap<ViewportId, Viewport>,
|
viewports: HashMap<ViewportId, Viewport>,
|
||||||
focused: Option<ViewportId>,
|
focused: Option<ViewportId>,
|
||||||
|
@ -51,10 +59,13 @@ impl Application {
|
||||||
proxy: EventLoopProxy<UserEvent>,
|
proxy: EventLoopProxy<UserEvent>,
|
||||||
debug_port: Option<u16>,
|
debug_port: Option<u16>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
|
let wgpu = WgpuState::new();
|
||||||
let icon = load_icon().ok().map(Arc::new);
|
let icon = load_icon().ok().map(Arc::new);
|
||||||
let persistence = Persistence::new();
|
let persistence = Persistence::new();
|
||||||
let mappings = MappingProvider::new(persistence.clone());
|
let mappings = MappingProvider::new(persistence.clone());
|
||||||
let controllers = ControllerManager::new(client.clone(), &mappings);
|
let controllers = ControllerManager::new(client.clone(), &mappings);
|
||||||
|
let memory = Arc::new(MemoryClient::new(client.clone()));
|
||||||
|
let vram = VramProcessor::new();
|
||||||
{
|
{
|
||||||
let mappings = mappings.clone();
|
let mappings = mappings.clone();
|
||||||
let proxy = proxy.clone();
|
let proxy = proxy.clone();
|
||||||
|
@ -62,9 +73,12 @@ impl Application {
|
||||||
}
|
}
|
||||||
Self {
|
Self {
|
||||||
icon,
|
icon,
|
||||||
|
wgpu,
|
||||||
client,
|
client,
|
||||||
proxy,
|
proxy,
|
||||||
mappings,
|
mappings,
|
||||||
|
memory,
|
||||||
|
vram,
|
||||||
controllers,
|
controllers,
|
||||||
persistence,
|
persistence,
|
||||||
viewports: HashMap::new(),
|
viewports: HashMap::new(),
|
||||||
|
@ -80,7 +94,7 @@ impl Application {
|
||||||
}
|
}
|
||||||
self.viewports.insert(
|
self.viewports.insert(
|
||||||
viewport_id,
|
viewport_id,
|
||||||
Viewport::new(event_loop, self.icon.clone(), window),
|
Viewport::new(event_loop, &self.wgpu, self.icon.clone(), window),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -116,19 +130,23 @@ impl ApplicationHandler<UserEvent> for Application {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let viewport_id = viewport.id();
|
let viewport_id = viewport.id();
|
||||||
match &event {
|
|
||||||
WindowEvent::KeyboardInput { event, .. } => {
|
|
||||||
self.controllers.handle_key_event(event);
|
|
||||||
viewport.app.handle_key_event(event);
|
|
||||||
}
|
|
||||||
WindowEvent::Focused(new_focused) => {
|
|
||||||
self.focused = new_focused.then_some(viewport_id);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
let mut queue_redraw = false;
|
let mut queue_redraw = false;
|
||||||
let mut inactive_viewports = HashSet::new();
|
let mut inactive_viewports = HashSet::new();
|
||||||
match viewport.on_window_event(event) {
|
let (consumed, action) = viewport.on_window_event(&event);
|
||||||
|
if !consumed {
|
||||||
|
match event {
|
||||||
|
WindowEvent::KeyboardInput { event, .. } => {
|
||||||
|
if !viewport.app.handle_key_event(&event) {
|
||||||
|
self.controllers.handle_key_event(&event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WindowEvent::Focused(new_focused) => {
|
||||||
|
self.focused = new_focused.then_some(viewport_id);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match action {
|
||||||
Some(Action::Redraw) => {
|
Some(Action::Redraw) => {
|
||||||
for viewport in self.viewports.values_mut() {
|
for viewport in self.viewports.values_mut() {
|
||||||
match viewport.redraw(event_loop) {
|
match viewport.redraw(event_loop) {
|
||||||
|
@ -180,20 +198,33 @@ impl ApplicationHandler<UserEvent> for Application {
|
||||||
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
|
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) {
|
||||||
match event {
|
match event {
|
||||||
UserEvent::GamepadEvent(event) => {
|
UserEvent::GamepadEvent(event) => {
|
||||||
self.controllers.handle_gamepad_event(&event);
|
if let Some(viewport) = self
|
||||||
let Some(viewport) = self
|
|
||||||
.focused
|
.focused
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|id| self.viewports.get_mut(id))
|
.and_then(|id| self.viewports.get_mut(id))
|
||||||
else {
|
{
|
||||||
return;
|
if viewport.app.handle_gamepad_event(&event) {
|
||||||
};
|
return;
|
||||||
viewport.app.handle_gamepad_event(&event);
|
}
|
||||||
|
}
|
||||||
|
self.controllers.handle_gamepad_event(&event);
|
||||||
}
|
}
|
||||||
UserEvent::OpenAbout => {
|
UserEvent::OpenAbout => {
|
||||||
let about = AboutWindow;
|
let about = AboutWindow;
|
||||||
self.open(event_loop, Box::new(about));
|
self.open(event_loop, Box::new(about));
|
||||||
}
|
}
|
||||||
|
UserEvent::OpenCharacterData(sim_id) => {
|
||||||
|
let vram = CharacterDataWindow::new(sim_id, &self.memory, &mut self.vram);
|
||||||
|
self.open(event_loop, Box::new(vram));
|
||||||
|
}
|
||||||
|
UserEvent::OpenBgMap(sim_id) => {
|
||||||
|
let bgmap = BgMapWindow::new(sim_id, &self.memory, &mut self.vram);
|
||||||
|
self.open(event_loop, Box::new(bgmap));
|
||||||
|
}
|
||||||
|
UserEvent::OpenObjects(sim_id) => {
|
||||||
|
let objects = ObjectWindow::new(sim_id, &self.memory, &mut self.vram);
|
||||||
|
self.open(event_loop, Box::new(objects));
|
||||||
|
}
|
||||||
UserEvent::OpenDebugger(sim_id) => {
|
UserEvent::OpenDebugger(sim_id) => {
|
||||||
let debugger =
|
let debugger =
|
||||||
GdbServerWindow::new(sim_id, self.client.clone(), self.proxy.clone());
|
GdbServerWindow::new(sim_id, self.client.clone(), self.proxy.clone());
|
||||||
|
@ -238,6 +269,58 @@ impl ApplicationHandler<UserEvent> for Application {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct WgpuState {
|
||||||
|
instance: Arc<wgpu::Instance>,
|
||||||
|
adapter: Arc<wgpu::Adapter>,
|
||||||
|
device: Arc<wgpu::Device>,
|
||||||
|
queue: Arc<wgpu::Queue>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WgpuState {
|
||||||
|
fn new() -> Self {
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
let egui_wgpu::WgpuConfiguration {
|
||||||
|
wgpu_setup:
|
||||||
|
egui_wgpu::WgpuSetup::CreateNew {
|
||||||
|
supported_backends,
|
||||||
|
device_descriptor,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
..
|
||||||
|
} = egui_wgpu::WgpuConfiguration::default()
|
||||||
|
else {
|
||||||
|
panic!("required fields not found")
|
||||||
|
};
|
||||||
|
#[cfg(windows)]
|
||||||
|
let supported_backends = wgpu::util::backend_bits_from_env()
|
||||||
|
.unwrap_or((wgpu::Backends::PRIMARY | wgpu::Backends::GL) - wgpu::Backends::VULKAN);
|
||||||
|
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||||
|
backends: supported_backends,
|
||||||
|
..wgpu::InstanceDescriptor::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||||
|
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||||
|
compatible_surface: None,
|
||||||
|
force_fallback_adapter: false,
|
||||||
|
}))
|
||||||
|
.expect("could not create adapter");
|
||||||
|
|
||||||
|
let trace_path = std::env::var("WGPU_TRACE");
|
||||||
|
let (device, queue) = pollster::block_on(adapter.request_device(
|
||||||
|
&(*device_descriptor)(&adapter),
|
||||||
|
trace_path.ok().as_ref().map(std::path::Path::new),
|
||||||
|
))
|
||||||
|
.expect("could not request device");
|
||||||
|
Self {
|
||||||
|
instance: Arc::new(instance),
|
||||||
|
adapter: Arc::new(adapter),
|
||||||
|
device: Arc::new(device),
|
||||||
|
queue: Arc::new(queue),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct Viewport {
|
struct Viewport {
|
||||||
painter: egui_wgpu::winit::Painter,
|
painter: egui_wgpu::winit::Painter,
|
||||||
ctx: Context,
|
ctx: Context,
|
||||||
|
@ -251,6 +334,7 @@ struct Viewport {
|
||||||
impl Viewport {
|
impl Viewport {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
event_loop: &ActiveEventLoop,
|
event_loop: &ActiveEventLoop,
|
||||||
|
wgpu: &WgpuState,
|
||||||
icon: Option<Arc<IconData>>,
|
icon: Option<Arc<IconData>>,
|
||||||
mut app: Box<dyn AppWindow>,
|
mut app: Box<dyn AppWindow>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
|
@ -274,20 +358,16 @@ impl Viewport {
|
||||||
});
|
});
|
||||||
egui_extras::install_image_loaders(&ctx);
|
egui_extras::install_image_loaders(&ctx);
|
||||||
|
|
||||||
#[allow(unused_mut)]
|
let wgpu_config = egui_wgpu::WgpuConfiguration {
|
||||||
let mut wgpu_config = egui_wgpu::WgpuConfiguration {
|
|
||||||
present_mode: wgpu::PresentMode::AutoNoVsync,
|
present_mode: wgpu::PresentMode::AutoNoVsync,
|
||||||
|
wgpu_setup: egui_wgpu::WgpuSetup::Existing {
|
||||||
|
instance: wgpu.instance.clone(),
|
||||||
|
adapter: wgpu.adapter.clone(),
|
||||||
|
device: wgpu.device.clone(),
|
||||||
|
queue: wgpu.queue.clone(),
|
||||||
|
},
|
||||||
..egui_wgpu::WgpuConfiguration::default()
|
..egui_wgpu::WgpuConfiguration::default()
|
||||||
};
|
};
|
||||||
#[cfg(windows)]
|
|
||||||
{
|
|
||||||
if let egui_wgpu::WgpuSetup::CreateNew {
|
|
||||||
supported_backends, ..
|
|
||||||
} = &mut wgpu_config.wgpu_setup
|
|
||||||
{
|
|
||||||
*supported_backends -= wgpu::Backends::VULKAN;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut painter =
|
let mut painter =
|
||||||
egui_wgpu::winit::Painter::new(ctx.clone(), wgpu_config, 1, None, false, true);
|
egui_wgpu::winit::Painter::new(ctx.clone(), wgpu_config, 1, None, false, true);
|
||||||
|
@ -300,7 +380,7 @@ impl Viewport {
|
||||||
let (window, state) = create_window_and_state(&ctx, event_loop, &builder, &mut painter);
|
let (window, state) = create_window_and_state(&ctx, event_loop, &builder, &mut painter);
|
||||||
egui_winit::update_viewport_info(&mut info, &ctx, &window, true);
|
egui_winit::update_viewport_info(&mut info, &ctx, &window, true);
|
||||||
|
|
||||||
app.on_init(painter.render_state().as_ref().unwrap());
|
app.on_init(&ctx, painter.render_state().as_ref().unwrap());
|
||||||
Self {
|
Self {
|
||||||
painter,
|
painter,
|
||||||
ctx,
|
ctx,
|
||||||
|
@ -317,8 +397,8 @@ impl Viewport {
|
||||||
self.app.viewport_id()
|
self.app.viewport_id()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_window_event(&mut self, event: WindowEvent) -> Option<Action> {
|
pub fn on_window_event(&mut self, event: &WindowEvent) -> (bool, Option<Action>) {
|
||||||
let response = self.state.on_window_event(&self.window, &event);
|
let response = self.state.on_window_event(&self.window, event);
|
||||||
egui_winit::update_viewport_info(
|
egui_winit::update_viewport_info(
|
||||||
&mut self.info,
|
&mut self.info,
|
||||||
self.state.egui_ctx(),
|
self.state.egui_ctx(),
|
||||||
|
@ -326,22 +406,22 @@ impl Viewport {
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
|
|
||||||
match event {
|
let action = match event {
|
||||||
WindowEvent::RedrawRequested => Some(Action::Redraw),
|
WindowEvent::RedrawRequested => Some(Action::Redraw),
|
||||||
WindowEvent::CloseRequested => Some(Action::Close),
|
WindowEvent::CloseRequested => Some(Action::Close),
|
||||||
WindowEvent::Resized(size) => {
|
WindowEvent::Resized(size) => {
|
||||||
let (Some(width), Some(height)) =
|
if let (Some(width), Some(height)) =
|
||||||
(NonZero::new(size.width), NonZero::new(size.height))
|
(NonZero::new(size.width), NonZero::new(size.height))
|
||||||
else {
|
{
|
||||||
return None;
|
self.painter
|
||||||
};
|
.on_window_resized(ViewportId::ROOT, width, height);
|
||||||
self.painter
|
}
|
||||||
.on_window_resized(ViewportId::ROOT, width, height);
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
_ if response.repaint => Some(Action::Redraw),
|
_ if response.repaint => Some(Action::Redraw),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
};
|
||||||
|
(response.consumed, action)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn redraw(&mut self, event_loop: &ActiveEventLoop) -> Option<Action> {
|
fn redraw(&mut self, event_loop: &ActiveEventLoop) -> Option<Action> {
|
||||||
|
@ -403,6 +483,9 @@ impl Drop for Viewport {
|
||||||
pub enum UserEvent {
|
pub enum UserEvent {
|
||||||
GamepadEvent(gilrs::Event),
|
GamepadEvent(gilrs::Event),
|
||||||
OpenAbout,
|
OpenAbout,
|
||||||
|
OpenCharacterData(SimId),
|
||||||
|
OpenBgMap(SimId),
|
||||||
|
OpenObjects(SimId),
|
||||||
OpenDebugger(SimId),
|
OpenDebugger(SimId),
|
||||||
OpenInput,
|
OpenInput,
|
||||||
OpenPlayer2,
|
OpenPlayer2,
|
||||||
|
|
|
@ -7,7 +7,7 @@ use std::{
|
||||||
sync::{
|
sync::{
|
||||||
atomic::{AtomicBool, Ordering},
|
atomic::{AtomicBool, Ordering},
|
||||||
mpsc::{self, RecvError, TryRecvError},
|
mpsc::{self, RecvError, TryRecvError},
|
||||||
Arc,
|
Arc, Weak,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -17,7 +17,11 @@ use bytemuck::NoUninit;
|
||||||
use egui_toast::{Toast, ToastKind, ToastOptions};
|
use egui_toast::{Toast, ToastKind, ToastOptions};
|
||||||
use tracing::{error, warn};
|
use tracing::{error, warn};
|
||||||
|
|
||||||
use crate::{audio::Audio, graphics::TextureSink};
|
use crate::{
|
||||||
|
audio::Audio,
|
||||||
|
graphics::TextureSink,
|
||||||
|
memory::{MemoryRange, MemoryRegion},
|
||||||
|
};
|
||||||
use shrooms_vb_core::{Sim, StopReason, EXPECTED_FRAME_SIZE};
|
use shrooms_vb_core::{Sim, StopReason, EXPECTED_FRAME_SIZE};
|
||||||
pub use shrooms_vb_core::{VBKey, VBRegister, VBWatchpointType};
|
pub use shrooms_vb_core::{VBKey, VBRegister, VBWatchpointType};
|
||||||
|
|
||||||
|
@ -165,8 +169,10 @@ pub struct Emulator {
|
||||||
renderers: HashMap<SimId, TextureSink>,
|
renderers: HashMap<SimId, TextureSink>,
|
||||||
messages: HashMap<SimId, mpsc::Sender<Toast>>,
|
messages: HashMap<SimId, mpsc::Sender<Toast>>,
|
||||||
debuggers: HashMap<SimId, DebugInfo>,
|
debuggers: HashMap<SimId, DebugInfo>,
|
||||||
|
watched_regions: HashMap<MemoryRange, Weak<MemoryRegion>>,
|
||||||
eye_contents: Vec<u8>,
|
eye_contents: Vec<u8>,
|
||||||
audio_samples: Vec<f32>,
|
audio_samples: Vec<f32>,
|
||||||
|
buffer: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Emulator {
|
impl Emulator {
|
||||||
|
@ -189,8 +195,10 @@ impl Emulator {
|
||||||
renderers: HashMap::new(),
|
renderers: HashMap::new(),
|
||||||
messages: HashMap::new(),
|
messages: HashMap::new(),
|
||||||
debuggers: HashMap::new(),
|
debuggers: HashMap::new(),
|
||||||
|
watched_regions: HashMap::new(),
|
||||||
eye_contents: vec![0u8; 384 * 224 * 2],
|
eye_contents: vec![0u8; 384 * 224 * 2],
|
||||||
audio_samples: Vec::with_capacity(EXPECTED_FRAME_SIZE),
|
audio_samples: Vec::with_capacity(EXPECTED_FRAME_SIZE),
|
||||||
|
buffer: vec![],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -367,6 +375,10 @@ impl Emulator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn watch_memory(&mut self, range: MemoryRange, region: Weak<MemoryRegion>) {
|
||||||
|
self.watched_regions.insert(range, region);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn run(&mut self) {
|
pub fn run(&mut self) {
|
||||||
loop {
|
loop {
|
||||||
let idle = self.tick();
|
let idle = self.tick();
|
||||||
|
@ -391,6 +403,18 @@ impl Emulator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
self.watched_regions.retain(|range, region| {
|
||||||
|
let Some(region) = region.upgrade() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(sim) = self.sims.get_mut(range.sim.to_index()) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
self.buffer.clear();
|
||||||
|
sim.read_memory(range.start, range.length, &mut self.buffer);
|
||||||
|
region.update(&self.buffer);
|
||||||
|
true
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -557,6 +581,9 @@ impl Emulator {
|
||||||
sim.write_memory(start, &buffer);
|
sim.write_memory(start, &buffer);
|
||||||
let _ = done.send(buffer);
|
let _ = done.send(buffer);
|
||||||
}
|
}
|
||||||
|
EmulatorCommand::WatchMemory(range, region) => {
|
||||||
|
self.watch_memory(range, region);
|
||||||
|
}
|
||||||
EmulatorCommand::AddBreakpoint(sim_id, address) => {
|
EmulatorCommand::AddBreakpoint(sim_id, address) => {
|
||||||
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
|
||||||
return;
|
return;
|
||||||
|
@ -647,6 +674,7 @@ pub enum EmulatorCommand {
|
||||||
WriteRegister(SimId, VBRegister, u32),
|
WriteRegister(SimId, VBRegister, u32),
|
||||||
ReadMemory(SimId, u32, usize, Vec<u8>, oneshot::Sender<Vec<u8>>),
|
ReadMemory(SimId, u32, usize, Vec<u8>, oneshot::Sender<Vec<u8>>),
|
||||||
WriteMemory(SimId, u32, Vec<u8>, oneshot::Sender<Vec<u8>>),
|
WriteMemory(SimId, u32, Vec<u8>, oneshot::Sender<Vec<u8>>),
|
||||||
|
WatchMemory(MemoryRange, Weak<MemoryRegion>),
|
||||||
AddBreakpoint(SimId, u32),
|
AddBreakpoint(SimId, u32),
|
||||||
RemoveBreakpoint(SimId, u32),
|
RemoveBreakpoint(SimId, u32),
|
||||||
AddWatchpoint(SimId, u32, usize, VBWatchpointType),
|
AddWatchpoint(SimId, u32, usize, VBWatchpointType),
|
||||||
|
|
|
@ -19,7 +19,9 @@ mod emulator;
|
||||||
mod gdbserver;
|
mod gdbserver;
|
||||||
mod graphics;
|
mod graphics;
|
||||||
mod input;
|
mod input;
|
||||||
|
mod memory;
|
||||||
mod persistence;
|
mod persistence;
|
||||||
|
mod vram;
|
||||||
mod window;
|
mod window;
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
|
|
|
@ -0,0 +1,260 @@
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
fmt::Debug,
|
||||||
|
sync::{atomic::AtomicU64, Arc, Mutex, RwLock, RwLockReadGuard, TryLockError, Weak},
|
||||||
|
};
|
||||||
|
|
||||||
|
use bytemuck::BoxBytes;
|
||||||
|
use itertools::Itertools;
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
|
use crate::emulator::{EmulatorClient, EmulatorCommand, SimId};
|
||||||
|
|
||||||
|
pub struct MemoryClient {
|
||||||
|
client: EmulatorClient,
|
||||||
|
regions: Mutex<HashMap<MemoryRange, Weak<MemoryRegion>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemoryClient {
|
||||||
|
pub fn new(client: EmulatorClient) -> Self {
|
||||||
|
Self {
|
||||||
|
client,
|
||||||
|
regions: Mutex::new(HashMap::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn watch(&self, sim: SimId, start: u32, length: usize) -> MemoryView {
|
||||||
|
let range = MemoryRange { sim, start, length };
|
||||||
|
let mut regions = self.regions.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let region = regions
|
||||||
|
.get(&range)
|
||||||
|
.and_then(|r| r.upgrade())
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
let region = Arc::new(MemoryRegion::new(start, length));
|
||||||
|
regions.insert(range, Arc::downgrade(®ion));
|
||||||
|
self.client
|
||||||
|
.send_command(EmulatorCommand::WatchMemory(range, Arc::downgrade(®ion)));
|
||||||
|
region
|
||||||
|
});
|
||||||
|
MemoryView { region }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write<T: MemoryValue>(&self, sim: SimId, address: u32, data: &T) {
|
||||||
|
let mut buffer = vec![];
|
||||||
|
data.to_bytes(&mut buffer);
|
||||||
|
let (tx, _) = oneshot::channel();
|
||||||
|
self.client
|
||||||
|
.send_command(EmulatorCommand::WriteMemory(sim, address, buffer, tx));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn aligned_memory(start: u32, length: usize) -> BoxBytes {
|
||||||
|
if start % 4 == 0 && length % 4 == 0 {
|
||||||
|
let memory = vec![0u32; length / 4].into_boxed_slice();
|
||||||
|
return bytemuck::box_bytes_of(memory);
|
||||||
|
}
|
||||||
|
if start % 2 == 0 && length % 2 == 0 {
|
||||||
|
let memory = vec![0u16; length / 2].into_boxed_slice();
|
||||||
|
return bytemuck::box_bytes_of(memory);
|
||||||
|
}
|
||||||
|
let memory = vec![0u8; length].into_boxed_slice();
|
||||||
|
bytemuck::box_bytes_of(memory)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MemoryView {
|
||||||
|
region: Arc<MemoryRegion>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemoryView {
|
||||||
|
pub fn borrow(&self) -> MemoryRef<'_> {
|
||||||
|
self.region.borrow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MemoryRef<'a> {
|
||||||
|
inner: RwLockReadGuard<'a, BoxBytes>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait MemoryValue {
|
||||||
|
fn from_bytes(bytes: &[u8]) -> Self;
|
||||||
|
fn to_bytes(&self, buffer: &mut Vec<u8>);
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! primitive_memory_value_impl {
|
||||||
|
($T:ty, $L: expr) => {
|
||||||
|
impl MemoryValue for $T {
|
||||||
|
#[inline]
|
||||||
|
fn from_bytes(bytes: &[u8]) -> Self {
|
||||||
|
let bytes: [u8; std::mem::size_of::<$T>()] = std::array::from_fn(|i| bytes[i]);
|
||||||
|
<$T>::from_le_bytes(bytes)
|
||||||
|
}
|
||||||
|
#[inline]
|
||||||
|
fn to_bytes(&self, buffer: &mut Vec<u8>) {
|
||||||
|
buffer.extend_from_slice(&self.to_le_bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
primitive_memory_value_impl!(u8, 1);
|
||||||
|
primitive_memory_value_impl!(u16, 2);
|
||||||
|
primitive_memory_value_impl!(u32, 4);
|
||||||
|
|
||||||
|
impl<const N: usize, T: MemoryValue> MemoryValue for [T; N] {
|
||||||
|
#[inline]
|
||||||
|
fn from_bytes(bytes: &[u8]) -> Self {
|
||||||
|
std::array::from_fn(|i| {
|
||||||
|
T::from_bytes(&bytes[i * std::mem::size_of::<T>()..(i + 1) * std::mem::size_of::<T>()])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
#[inline]
|
||||||
|
fn to_bytes(&self, buffer: &mut Vec<u8>) {
|
||||||
|
for item in self {
|
||||||
|
item.to_bytes(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MemoryIter<'a, T> {
|
||||||
|
bytes: &'a [u8],
|
||||||
|
index: usize,
|
||||||
|
_phantom: std::marker::PhantomData<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T> MemoryIter<'a, T> {
|
||||||
|
fn new(bytes: &'a [u8]) -> Self {
|
||||||
|
Self {
|
||||||
|
bytes,
|
||||||
|
index: 0,
|
||||||
|
_phantom: std::marker::PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: MemoryValue> Iterator for MemoryIter<'_, T> {
|
||||||
|
type Item = T;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
|
if self.index >= self.bytes.len() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let bytes = &self.bytes[self.index..self.index + std::mem::size_of::<T>()];
|
||||||
|
self.index += std::mem::size_of::<T>();
|
||||||
|
Some(T::from_bytes(bytes))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemoryRef<'_> {
|
||||||
|
pub fn read<T: MemoryValue>(&self, index: usize) -> T {
|
||||||
|
let from = index * size_of::<T>();
|
||||||
|
let to = from + size_of::<T>();
|
||||||
|
T::from_bytes(&self.inner[from..to])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn range<T: MemoryValue>(&self, start: usize, count: usize) -> MemoryIter<T> {
|
||||||
|
let from = start * size_of::<T>();
|
||||||
|
let to = from + (count * size_of::<T>());
|
||||||
|
MemoryIter::new(&self.inner[from..to])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct MemoryRange {
|
||||||
|
pub sim: SimId,
|
||||||
|
pub start: u32,
|
||||||
|
pub length: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
const BUFFERS: usize = 4;
|
||||||
|
pub struct MemoryRegion {
|
||||||
|
gens: [AtomicU64; BUFFERS],
|
||||||
|
bufs: [RwLock<BoxBytes>; BUFFERS],
|
||||||
|
}
|
||||||
|
impl Debug for MemoryRegion {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("MemoryRegion")
|
||||||
|
.field("gens", &self.gens)
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// SAFETY: BoxBytes is meant to be Send+Sync, will be in a future version
|
||||||
|
unsafe impl Send for MemoryRegion {}
|
||||||
|
// SAFETY: BoxBytes is meant to be Send+Sync, will be in a future version
|
||||||
|
unsafe impl Sync for MemoryRegion {}
|
||||||
|
|
||||||
|
impl MemoryRegion {
|
||||||
|
fn new(start: u32, length: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
gens: std::array::from_fn(|i| AtomicU64::new(i as u64)),
|
||||||
|
bufs: std::array::from_fn(|_| RwLock::new(aligned_memory(start, length))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn borrow(&self) -> MemoryRef<'_> {
|
||||||
|
/*
|
||||||
|
* When reading memory, a thread will grab the newest buffer (with the highest gen)
|
||||||
|
* It will only fail to grab the lock if the writer already has it,
|
||||||
|
* but the writer prioritizes older buffers (with lower gens).
|
||||||
|
* So this method will only block if the writer produces three full buffers
|
||||||
|
* in the time it takes the reader to do four atomic reads and grab a lock.
|
||||||
|
* In the unlikely event this happens... just try again.
|
||||||
|
*/
|
||||||
|
loop {
|
||||||
|
let newest_index = self
|
||||||
|
.gens
|
||||||
|
.iter()
|
||||||
|
.map(|i| i.load(std::sync::atomic::Ordering::Acquire))
|
||||||
|
.enumerate()
|
||||||
|
.max_by_key(|(_, gen)| *gen)
|
||||||
|
.map(|(i, _)| i)
|
||||||
|
.unwrap();
|
||||||
|
let inner = match self.bufs[newest_index].try_read() {
|
||||||
|
Ok(inner) => inner,
|
||||||
|
Err(TryLockError::Poisoned(e)) => e.into_inner(),
|
||||||
|
Err(TryLockError::WouldBlock) => {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
break MemoryRef { inner };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&self, data: &[u8]) {
|
||||||
|
let gens: Vec<u64> = self
|
||||||
|
.gens
|
||||||
|
.iter()
|
||||||
|
.map(|i| i.load(std::sync::atomic::Ordering::Acquire))
|
||||||
|
.collect();
|
||||||
|
let next_gen = gens.iter().max().unwrap() + 1;
|
||||||
|
let indices = gens
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.sorted_by_key(|(_, val)| *val)
|
||||||
|
.map(|(i, _)| i);
|
||||||
|
for index in indices {
|
||||||
|
let mut lock = match self.bufs[index].try_write() {
|
||||||
|
Ok(inner) => inner,
|
||||||
|
Err(TryLockError::Poisoned(e)) => e.into_inner(),
|
||||||
|
Err(TryLockError::WouldBlock) => {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
lock.copy_from_slice(data);
|
||||||
|
self.gens[index].store(next_gen, std::sync::atomic::Ordering::Release);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
* We have four buffers, and (at time of writing) only three threads interacting with memory:
|
||||||
|
* - The UI thread, reading small regions of memory
|
||||||
|
* - The "vram renderer" thread, reading large regions of memory
|
||||||
|
* - The emulation thread, writing memory every so often
|
||||||
|
* So it should be impossible for all four buffers to have a read lock at the same time,
|
||||||
|
* and (because readers always read the newest buffer) at least one of the oldest three
|
||||||
|
* buffers will be free the entire time we're in this method.
|
||||||
|
* TL;DR this should never happen.
|
||||||
|
* But if it does, do nothing. This isn't medical software, better to show stale data than crash.
|
||||||
|
*/
|
||||||
|
warn!("all buffers were locked by a reader at the same time")
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,327 @@
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
ops::Deref,
|
||||||
|
sync::{Arc, Mutex, Weak},
|
||||||
|
thread,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use egui::{
|
||||||
|
epaint::ImageDelta,
|
||||||
|
load::{LoadError, SizedTexture, TextureLoader, TexturePoll},
|
||||||
|
Color32, ColorImage, TextureHandle, TextureOptions,
|
||||||
|
};
|
||||||
|
use tokio::{sync::mpsc, time::timeout};
|
||||||
|
|
||||||
|
pub struct VramProcessor {
|
||||||
|
sender: mpsc::UnboundedSender<Box<dyn VramRendererImpl>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramProcessor {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
let (sender, receiver) = mpsc::unbounded_channel();
|
||||||
|
thread::spawn(move || {
|
||||||
|
tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap()
|
||||||
|
.block_on(async move {
|
||||||
|
let mut worker = VramProcessorWorker {
|
||||||
|
receiver,
|
||||||
|
renderers: vec![],
|
||||||
|
};
|
||||||
|
worker.run().await
|
||||||
|
})
|
||||||
|
});
|
||||||
|
Self { sender }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add<const N: usize, R: VramRenderer<N> + 'static>(
|
||||||
|
&self,
|
||||||
|
renderer: R,
|
||||||
|
) -> ([VramImageHandle; N], VramParams<R::Params>) {
|
||||||
|
let states = renderer.sizes().map(VramRenderImageState::new);
|
||||||
|
let handles = states.clone().map(|state| VramImageHandle {
|
||||||
|
size: state.size.map(|i| i as f32),
|
||||||
|
data: state.sink,
|
||||||
|
});
|
||||||
|
let images = renderer
|
||||||
|
.sizes()
|
||||||
|
.map(|[width, height]| VramImage::new(width, height));
|
||||||
|
let sink = Arc::new(Mutex::new(R::Params::default()));
|
||||||
|
let _ = self.sender.send(Box::new(VramRendererWrapper {
|
||||||
|
renderer,
|
||||||
|
params: Arc::downgrade(&sink),
|
||||||
|
images,
|
||||||
|
states,
|
||||||
|
}));
|
||||||
|
let params = VramParams {
|
||||||
|
value: R::Params::default(),
|
||||||
|
sink,
|
||||||
|
};
|
||||||
|
(handles, params)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct VramProcessorWorker {
|
||||||
|
receiver: mpsc::UnboundedReceiver<Box<dyn VramRendererImpl>>,
|
||||||
|
renderers: Vec<Box<dyn VramRendererImpl>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramProcessorWorker {
|
||||||
|
async fn run(&mut self) {
|
||||||
|
loop {
|
||||||
|
if self.renderers.is_empty() {
|
||||||
|
// if we have nothing to do, block until we have something to do
|
||||||
|
if self.receiver.recv_many(&mut self.renderers, 64).await == 0 {
|
||||||
|
// shutdown
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
while let Ok(renderer) = self.receiver.try_recv() {
|
||||||
|
self.renderers.push(renderer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.renderers
|
||||||
|
.retain_mut(|renderer| renderer.try_update().is_ok());
|
||||||
|
// wait up to 10 ms for more renderers
|
||||||
|
if timeout(
|
||||||
|
Duration::from_millis(10),
|
||||||
|
self.receiver.recv_many(&mut self.renderers, 64),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
while let Ok(renderer) = self.receiver.try_recv() {
|
||||||
|
self.renderers.push(renderer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct VramImage {
|
||||||
|
size: [usize; 2],
|
||||||
|
shades: Vec<Color32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramImage {
|
||||||
|
pub fn new(width: usize, height: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
size: [width, height],
|
||||||
|
shades: vec![Color32::BLACK; width * height],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear(&mut self) {
|
||||||
|
for shade in self.shades.iter_mut() {
|
||||||
|
*shade = Color32::BLACK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write(&mut self, coords: (usize, usize), pixel: Color32) {
|
||||||
|
self.shades[coords.1 * self.size[0] + coords.0] = pixel;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add(&mut self, coords: (usize, usize), pixel: Color32) {
|
||||||
|
let index = coords.1 * self.size[0] + coords.0;
|
||||||
|
let old = self.shades[index];
|
||||||
|
self.shades[index] = Color32::from_rgb(
|
||||||
|
old.r() + pixel.r(),
|
||||||
|
old.g() + pixel.g(),
|
||||||
|
old.b() + pixel.b(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn changed(&self, image: &ColorImage) -> bool {
|
||||||
|
image.pixels.iter().zip(&self.shades).any(|(a, b)| a != b)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read(&self, image: &mut ColorImage) {
|
||||||
|
image.pixels.copy_from_slice(&self.shades);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct VramImageHandle {
|
||||||
|
size: [f32; 2],
|
||||||
|
data: Arc<Mutex<Option<Arc<ColorImage>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramImageHandle {
|
||||||
|
fn pull(&mut self) -> Option<Arc<ColorImage>> {
|
||||||
|
self.data.lock().unwrap().take()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct VramParams<T> {
|
||||||
|
value: T,
|
||||||
|
sink: Arc<Mutex<T>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Deref for VramParams<T> {
|
||||||
|
type Target = T;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Clone + Eq> VramParams<T> {
|
||||||
|
pub fn write(&mut self, value: T) {
|
||||||
|
if self.value != value {
|
||||||
|
self.value = value.clone();
|
||||||
|
*self.sink.lock().unwrap() = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait VramRenderer<const N: usize>: Send {
|
||||||
|
type Params: Clone + Default + Send;
|
||||||
|
fn sizes(&self) -> [[usize; 2]; N];
|
||||||
|
fn render(&mut self, params: &Self::Params, images: &mut [VramImage; N]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct VramRenderImageState {
|
||||||
|
size: [usize; 2],
|
||||||
|
buffers: [Arc<ColorImage>; 2],
|
||||||
|
last_buffer: usize,
|
||||||
|
sink: Arc<Mutex<Option<Arc<ColorImage>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramRenderImageState {
|
||||||
|
fn new(size: [usize; 2]) -> Self {
|
||||||
|
let buffers = [
|
||||||
|
Arc::new(ColorImage::new(size, Color32::BLACK)),
|
||||||
|
Arc::new(ColorImage::new(size, Color32::BLACK)),
|
||||||
|
];
|
||||||
|
let sink = buffers[0].clone();
|
||||||
|
Self {
|
||||||
|
size,
|
||||||
|
buffers,
|
||||||
|
last_buffer: 0,
|
||||||
|
sink: Arc::new(Mutex::new(Some(sink))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn try_send_update(&mut self, image: &VramImage) {
|
||||||
|
let last = &self.buffers[self.last_buffer];
|
||||||
|
if !image.changed(last) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let next_buffer = (self.last_buffer + 1) % self.buffers.len();
|
||||||
|
let next = &mut self.buffers[next_buffer];
|
||||||
|
image.read(Arc::make_mut(next));
|
||||||
|
self.last_buffer = next_buffer;
|
||||||
|
self.sink.lock().unwrap().replace(next.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct VramRendererWrapper<const N: usize, R: VramRenderer<N>> {
|
||||||
|
renderer: R,
|
||||||
|
params: Weak<Mutex<R::Params>>,
|
||||||
|
images: [VramImage; N],
|
||||||
|
states: [VramRenderImageState; N],
|
||||||
|
}
|
||||||
|
|
||||||
|
trait VramRendererImpl: Send {
|
||||||
|
fn try_update(&mut self) -> Result<(), ()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize, R: VramRenderer<N> + Send> VramRendererImpl for VramRendererWrapper<N, R> {
|
||||||
|
fn try_update(&mut self) -> Result<(), ()> {
|
||||||
|
let params = match self.params.upgrade() {
|
||||||
|
Some(params) => params.lock().unwrap().clone(),
|
||||||
|
None => {
|
||||||
|
// the UI isn't using this anymore
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.renderer.render(¶ms, &mut self.images);
|
||||||
|
|
||||||
|
for (state, image) in self.states.iter_mut().zip(&self.images) {
|
||||||
|
state.try_send_update(image);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct VramTextureLoader {
|
||||||
|
cache: Mutex<HashMap<String, (VramImageHandle, Option<TextureHandle>)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramTextureLoader {
|
||||||
|
pub fn new(renderers: impl IntoIterator<Item = (String, VramImageHandle)>) -> Self {
|
||||||
|
let mut cache = HashMap::new();
|
||||||
|
for (key, image) in renderers {
|
||||||
|
cache.insert(key, (image, None));
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
cache: Mutex::new(cache),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TextureLoader for VramTextureLoader {
|
||||||
|
fn id(&self) -> &str {
|
||||||
|
concat!(module_path!(), "VramTextureLoader")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load(
|
||||||
|
&self,
|
||||||
|
ctx: &egui::Context,
|
||||||
|
uri: &str,
|
||||||
|
texture_options: TextureOptions,
|
||||||
|
_size_hint: egui::SizeHint,
|
||||||
|
) -> Result<TexturePoll, LoadError> {
|
||||||
|
let mut cache = self.cache.lock().unwrap();
|
||||||
|
let Some((image, maybe_handle)) = cache.get_mut(uri) else {
|
||||||
|
return Err(LoadError::NotSupported);
|
||||||
|
};
|
||||||
|
if texture_options != TextureOptions::NEAREST {
|
||||||
|
return Err(LoadError::Loading(
|
||||||
|
"Only TextureOptions::NEAREST are supported".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
match (image.pull(), maybe_handle.as_ref()) {
|
||||||
|
(Some(update), Some(handle)) => {
|
||||||
|
let delta = ImageDelta::full(update, texture_options);
|
||||||
|
ctx.tex_manager().write().set(handle.id(), delta);
|
||||||
|
let texture = SizedTexture::new(handle, image.size);
|
||||||
|
Ok(TexturePoll::Ready { texture })
|
||||||
|
}
|
||||||
|
(Some(update), None) => {
|
||||||
|
let handle = ctx.load_texture(uri, update, texture_options);
|
||||||
|
let texture = SizedTexture::new(&handle, image.size);
|
||||||
|
maybe_handle.replace(handle);
|
||||||
|
Ok(TexturePoll::Ready { texture })
|
||||||
|
}
|
||||||
|
(None, Some(handle)) => {
|
||||||
|
let texture = SizedTexture::new(handle, image.size);
|
||||||
|
Ok(TexturePoll::Ready { texture })
|
||||||
|
}
|
||||||
|
(None, None) => {
|
||||||
|
let size = image.size.into();
|
||||||
|
Ok(TexturePoll::Pending { size: Some(size) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn forget(&self, uri: &str) {
|
||||||
|
let _ = uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn forget_all(&self) {}
|
||||||
|
|
||||||
|
fn byte_size(&self) -> usize {
|
||||||
|
self.cache
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.values()
|
||||||
|
.map(|(image, _)| {
|
||||||
|
let [width, height] = image.size;
|
||||||
|
width as usize * height as usize * 4
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
}
|
|
@ -3,6 +3,7 @@ use egui::{Context, ViewportBuilder, ViewportId};
|
||||||
pub use game::GameWindow;
|
pub use game::GameWindow;
|
||||||
pub use gdb::GdbServerWindow;
|
pub use gdb::GdbServerWindow;
|
||||||
pub use input::InputWindow;
|
pub use input::InputWindow;
|
||||||
|
pub use vram::{BgMapWindow, CharacterDataWindow, ObjectWindow};
|
||||||
use winit::event::KeyEvent;
|
use winit::event::KeyEvent;
|
||||||
|
|
||||||
use crate::emulator::SimId;
|
use crate::emulator::SimId;
|
||||||
|
@ -12,6 +13,8 @@ mod game;
|
||||||
mod game_screen;
|
mod game_screen;
|
||||||
mod gdb;
|
mod gdb;
|
||||||
mod input;
|
mod input;
|
||||||
|
mod utils;
|
||||||
|
mod vram;
|
||||||
|
|
||||||
pub trait AppWindow {
|
pub trait AppWindow {
|
||||||
fn viewport_id(&self) -> ViewportId;
|
fn viewport_id(&self) -> ViewportId;
|
||||||
|
@ -20,14 +23,17 @@ pub trait AppWindow {
|
||||||
}
|
}
|
||||||
fn initial_viewport(&self) -> ViewportBuilder;
|
fn initial_viewport(&self) -> ViewportBuilder;
|
||||||
fn show(&mut self, ctx: &Context);
|
fn show(&mut self, ctx: &Context);
|
||||||
fn on_init(&mut self, render_state: &egui_wgpu::RenderState) {
|
fn on_init(&mut self, ctx: &Context, render_state: &egui_wgpu::RenderState) {
|
||||||
|
let _ = ctx;
|
||||||
let _ = render_state;
|
let _ = render_state;
|
||||||
}
|
}
|
||||||
fn on_destroy(&mut self) {}
|
fn on_destroy(&mut self) {}
|
||||||
fn handle_key_event(&mut self, event: &KeyEvent) {
|
fn handle_key_event(&mut self, event: &KeyEvent) -> bool {
|
||||||
let _ = event;
|
let _ = event;
|
||||||
|
false
|
||||||
}
|
}
|
||||||
fn handle_gamepad_event(&mut self, event: &gilrs::Event) {
|
fn handle_gamepad_event(&mut self, event: &gilrs::Event) -> bool {
|
||||||
let _ = event;
|
let _ = event;
|
||||||
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,9 +6,8 @@ use crate::{
|
||||||
persistence::Persistence,
|
persistence::Persistence,
|
||||||
};
|
};
|
||||||
use egui::{
|
use egui::{
|
||||||
ecolor::HexColor, menu, Align2, Button, CentralPanel, Color32, Context, Direction, Frame,
|
menu, Align2, Button, CentralPanel, Color32, Context, Direction, Frame, TopBottomPanel, Ui,
|
||||||
Layout, Response, Sense, TopBottomPanel, Ui, Vec2, ViewportBuilder, ViewportCommand,
|
Vec2, ViewportBuilder, ViewportCommand, ViewportId, Window,
|
||||||
ViewportId, WidgetText, Window,
|
|
||||||
};
|
};
|
||||||
use egui_toast::{Toast, Toasts};
|
use egui_toast::{Toast, Toasts};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
@ -16,6 +15,7 @@ use winit::event_loop::EventLoopProxy;
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
game_screen::{DisplayMode, GameScreen},
|
game_screen::{DisplayMode, GameScreen},
|
||||||
|
utils::UiExt as _,
|
||||||
AppWindow,
|
AppWindow,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -132,10 +132,30 @@ impl GameWindow {
|
||||||
.unwrap();
|
.unwrap();
|
||||||
ui.close_menu();
|
ui.close_menu();
|
||||||
}
|
}
|
||||||
|
if ui.button("Character Data").clicked() {
|
||||||
|
self.proxy
|
||||||
|
.send_event(UserEvent::OpenCharacterData(self.sim_id))
|
||||||
|
.unwrap();
|
||||||
|
ui.close_menu();
|
||||||
|
}
|
||||||
|
if ui.button("Background Maps").clicked() {
|
||||||
|
self.proxy
|
||||||
|
.send_event(UserEvent::OpenBgMap(self.sim_id))
|
||||||
|
.unwrap();
|
||||||
|
ui.close_menu();
|
||||||
|
}
|
||||||
|
if ui.button("Objects").clicked() {
|
||||||
|
self.proxy
|
||||||
|
.send_event(UserEvent::OpenObjects(self.sim_id))
|
||||||
|
.unwrap();
|
||||||
|
ui.close_menu();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
ui.menu_button("About", |ui| {
|
ui.menu_button("Help", |ui| {
|
||||||
self.proxy.send_event(UserEvent::OpenAbout).unwrap();
|
if ui.button("About").clicked() {
|
||||||
ui.close_menu();
|
self.proxy.send_event(UserEvent::OpenAbout).unwrap();
|
||||||
|
ui.close_menu();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -365,7 +385,7 @@ impl AppWindow for GameWindow {
|
||||||
toasts.show(ctx);
|
toasts.show(ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_init(&mut self, render_state: &egui_wgpu::RenderState) {
|
fn on_init(&mut self, _ctx: &Context, render_state: &egui_wgpu::RenderState) {
|
||||||
let (screen, sink) = GameScreen::init(render_state);
|
let (screen, sink) = GameScreen::init(render_state);
|
||||||
let (message_sink, message_source) = mpsc::channel();
|
let (message_sink, message_source) = mpsc::channel();
|
||||||
self.client.send_command(EmulatorCommand::ConnectToSim(
|
self.client.send_command(EmulatorCommand::ConnectToSim(
|
||||||
|
@ -385,69 +405,6 @@ impl AppWindow for GameWindow {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
trait UiExt {
|
|
||||||
fn selectable_button(&mut self, selected: bool, text: impl Into<WidgetText>) -> Response;
|
|
||||||
fn selectable_option<T: Eq>(
|
|
||||||
&mut self,
|
|
||||||
current_value: &mut T,
|
|
||||||
selected_value: T,
|
|
||||||
text: impl Into<WidgetText>,
|
|
||||||
) -> Response {
|
|
||||||
let response = self.selectable_button(*current_value == selected_value, text);
|
|
||||||
if response.clicked() {
|
|
||||||
*current_value = selected_value;
|
|
||||||
}
|
|
||||||
response
|
|
||||||
}
|
|
||||||
|
|
||||||
fn color_pair_button(&mut self, left: Color32, right: Color32) -> Response;
|
|
||||||
|
|
||||||
fn color_picker(&mut self, color: &mut Color32, hex: &mut String) -> Response;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl UiExt for Ui {
|
|
||||||
fn selectable_button(&mut self, selected: bool, text: impl Into<WidgetText>) -> Response {
|
|
||||||
self.style_mut().visuals.widgets.inactive.bg_fill = Color32::TRANSPARENT;
|
|
||||||
self.style_mut().visuals.widgets.hovered.bg_fill = Color32::TRANSPARENT;
|
|
||||||
self.style_mut().visuals.widgets.active.bg_fill = Color32::TRANSPARENT;
|
|
||||||
let mut selected = selected;
|
|
||||||
self.checkbox(&mut selected, text)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn color_pair_button(&mut self, left: Color32, right: Color32) -> Response {
|
|
||||||
let button_size = Vec2::new(60.0, 20.0);
|
|
||||||
let (rect, response) = self.allocate_at_least(button_size, Sense::click());
|
|
||||||
let center_x = rect.center().x;
|
|
||||||
let left_rect = rect.with_max_x(center_x);
|
|
||||||
self.painter().rect_filled(left_rect, 0.0, left);
|
|
||||||
let right_rect = rect.with_min_x(center_x);
|
|
||||||
self.painter().rect_filled(right_rect, 0.0, right);
|
|
||||||
|
|
||||||
let style = self.style().interact(&response);
|
|
||||||
self.painter().rect_stroke(rect, 0.0, style.fg_stroke);
|
|
||||||
response
|
|
||||||
}
|
|
||||||
|
|
||||||
fn color_picker(&mut self, color: &mut Color32, hex: &mut String) -> Response {
|
|
||||||
self.allocate_ui_with_layout(
|
|
||||||
Vec2::new(100.0, 130.0),
|
|
||||||
Layout::top_down_justified(egui::Align::Center),
|
|
||||||
|ui| {
|
|
||||||
let (rect, _) = ui.allocate_at_least(Vec2::new(100.0, 100.0), Sense::hover());
|
|
||||||
ui.painter().rect_filled(rect, 0.0, *color);
|
|
||||||
let resp = ui.text_edit_singleline(hex);
|
|
||||||
if resp.changed() {
|
|
||||||
if let Ok(new_color) = HexColor::from_str_without_hash(hex) {
|
|
||||||
*color = new_color.color();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
resp
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.inner
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct ColorPickerState {
|
struct ColorPickerState {
|
||||||
color_codes: [String; 2],
|
color_codes: [String; 2],
|
||||||
just_opened: bool,
|
just_opened: bool,
|
||||||
|
|
|
@ -198,58 +198,63 @@ impl AppWindow for InputWindow {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_key_event(&mut self, event: &winit::event::KeyEvent) {
|
fn handle_key_event(&mut self, event: &winit::event::KeyEvent) -> bool {
|
||||||
if !event.state.is_pressed() {
|
if !event.state.is_pressed() {
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
let sim_id = match self.active_tab {
|
let sim_id = match self.active_tab {
|
||||||
InputTab::Player1 => SimId::Player1,
|
InputTab::Player1 => SimId::Player1,
|
||||||
InputTab::Player2 => SimId::Player2,
|
InputTab::Player2 => SimId::Player2,
|
||||||
_ => {
|
_ => {
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some(vb) = self.now_binding.take() else {
|
let Some(vb) = self.now_binding.take() else {
|
||||||
return;
|
return false;
|
||||||
};
|
};
|
||||||
let mut mappings = self.mappings.for_sim(sim_id).write().unwrap();
|
let mut mappings = self.mappings.for_sim(sim_id).write().unwrap();
|
||||||
mappings.add_keyboard_mapping(vb, event.physical_key);
|
mappings.add_keyboard_mapping(vb, event.physical_key);
|
||||||
drop(mappings);
|
drop(mappings);
|
||||||
self.mappings.save();
|
self.mappings.save();
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_gamepad_event(&mut self, event: &gilrs::Event) {
|
fn handle_gamepad_event(&mut self, event: &gilrs::Event) -> bool {
|
||||||
let InputTab::RebindGamepad(gamepad_id) = self.active_tab else {
|
let InputTab::RebindGamepad(gamepad_id) = self.active_tab else {
|
||||||
return;
|
return false;
|
||||||
};
|
};
|
||||||
if gamepad_id != event.id {
|
if gamepad_id != event.id {
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
let Some(mappings) = self.mappings.for_gamepad(gamepad_id) else {
|
let Some(mappings) = self.mappings.for_gamepad(gamepad_id) else {
|
||||||
return;
|
return false;
|
||||||
};
|
};
|
||||||
let Some(vb) = self.now_binding else {
|
let Some(vb) = self.now_binding else {
|
||||||
return;
|
return false;
|
||||||
};
|
};
|
||||||
match event.event {
|
match event.event {
|
||||||
EventType::ButtonPressed(_, code) => {
|
EventType::ButtonPressed(_, code) => {
|
||||||
let mut mapping = mappings.write().unwrap();
|
let mut mapping = mappings.write().unwrap();
|
||||||
mapping.add_button_mapping(vb, code);
|
mapping.add_button_mapping(vb, code);
|
||||||
self.now_binding.take();
|
self.now_binding.take();
|
||||||
|
true
|
||||||
}
|
}
|
||||||
EventType::AxisChanged(_, value, code) => {
|
EventType::AxisChanged(_, value, code) => {
|
||||||
if value < -0.75 {
|
if value < -0.75 {
|
||||||
let mut mapping = mappings.write().unwrap();
|
let mut mapping = mappings.write().unwrap();
|
||||||
mapping.add_axis_neg_mapping(vb, code);
|
mapping.add_axis_neg_mapping(vb, code);
|
||||||
self.now_binding.take();
|
self.now_binding.take();
|
||||||
}
|
true
|
||||||
if value > 0.75 {
|
} else if value > 0.75 {
|
||||||
let mut mapping = mappings.write().unwrap();
|
let mut mapping = mappings.write().unwrap();
|
||||||
mapping.add_axis_pos_mapping(vb, code);
|
mapping.add_axis_pos_mapping(vb, code);
|
||||||
self.now_binding.take();
|
self.now_binding.take();
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,312 @@
|
||||||
|
use std::{
|
||||||
|
fmt::Display,
|
||||||
|
ops::{Bound, RangeBounds},
|
||||||
|
str::FromStr,
|
||||||
|
};
|
||||||
|
|
||||||
|
use egui::{
|
||||||
|
ecolor::HexColor, Align, Color32, CursorIcon, Event, Frame, Key, Layout, Margin, Rect,
|
||||||
|
Response, RichText, Rounding, Sense, Shape, Stroke, TextEdit, Ui, UiBuilder, Vec2, Widget,
|
||||||
|
WidgetText,
|
||||||
|
};
|
||||||
|
use num_traits::PrimInt;
|
||||||
|
|
||||||
|
pub trait UiExt {
|
||||||
|
fn section(&mut self, title: impl Into<String>, add_contents: impl FnOnce(&mut Ui));
|
||||||
|
fn selectable_button(&mut self, selected: bool, text: impl Into<WidgetText>) -> Response;
|
||||||
|
fn selectable_option<T: Eq>(
|
||||||
|
&mut self,
|
||||||
|
current_value: &mut T,
|
||||||
|
selected_value: T,
|
||||||
|
text: impl Into<WidgetText>,
|
||||||
|
) -> Response {
|
||||||
|
let response = self.selectable_button(*current_value == selected_value, text);
|
||||||
|
if response.clicked() {
|
||||||
|
*current_value = selected_value;
|
||||||
|
}
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color_pair_button(&mut self, left: Color32, right: Color32) -> Response;
|
||||||
|
|
||||||
|
fn color_picker(&mut self, color: &mut Color32, hex: &mut String) -> Response;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UiExt for Ui {
|
||||||
|
fn section(&mut self, title: impl Into<String>, add_contents: impl FnOnce(&mut Ui)) {
|
||||||
|
let mut frame = Frame::group(self.style());
|
||||||
|
frame.outer_margin.top += 10.0;
|
||||||
|
frame.inner_margin.top += 2.0;
|
||||||
|
let res = frame.show(self, add_contents);
|
||||||
|
let text = RichText::new(title).background_color(self.style().visuals.panel_fill);
|
||||||
|
let old_rect = res.response.rect;
|
||||||
|
let mut text_rect = old_rect;
|
||||||
|
text_rect.min.x += 6.0;
|
||||||
|
let new_rect = self
|
||||||
|
.allocate_new_ui(UiBuilder::new().max_rect(text_rect), |ui| ui.label(text))
|
||||||
|
.response
|
||||||
|
.rect;
|
||||||
|
self.allocate_space((old_rect.max - new_rect.max) - (old_rect.min - new_rect.min));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selectable_button(&mut self, selected: bool, text: impl Into<WidgetText>) -> Response {
|
||||||
|
self.style_mut().visuals.widgets.inactive.bg_fill = Color32::TRANSPARENT;
|
||||||
|
self.style_mut().visuals.widgets.hovered.bg_fill = Color32::TRANSPARENT;
|
||||||
|
self.style_mut().visuals.widgets.active.bg_fill = Color32::TRANSPARENT;
|
||||||
|
let mut selected = selected;
|
||||||
|
self.checkbox(&mut selected, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color_pair_button(&mut self, left: Color32, right: Color32) -> Response {
|
||||||
|
let button_size = Vec2::new(60.0, 20.0);
|
||||||
|
let (rect, response) = self.allocate_at_least(button_size, Sense::click());
|
||||||
|
let center_x = rect.center().x;
|
||||||
|
let left_rect = rect.with_max_x(center_x);
|
||||||
|
self.painter().rect_filled(left_rect, 0.0, left);
|
||||||
|
let right_rect = rect.with_min_x(center_x);
|
||||||
|
self.painter().rect_filled(right_rect, 0.0, right);
|
||||||
|
|
||||||
|
let style = self.style().interact(&response);
|
||||||
|
self.painter().rect_stroke(rect, 0.0, style.fg_stroke);
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color_picker(&mut self, color: &mut Color32, hex: &mut String) -> Response {
|
||||||
|
self.allocate_ui_with_layout(
|
||||||
|
Vec2::new(100.0, 130.0),
|
||||||
|
Layout::top_down_justified(egui::Align::Center),
|
||||||
|
|ui| {
|
||||||
|
let (rect, _) = ui.allocate_at_least(Vec2::new(100.0, 100.0), Sense::hover());
|
||||||
|
ui.painter().rect_filled(rect, 0.0, *color);
|
||||||
|
let resp = ui.text_edit_singleline(hex);
|
||||||
|
if resp.changed() {
|
||||||
|
if let Ok(new_color) = HexColor::from_str_without_hash(hex) {
|
||||||
|
*color = new_color.color();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resp
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.inner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Direction {
|
||||||
|
Up,
|
||||||
|
Down,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait Number: PrimInt + Display + FromStr + Send + Sync + 'static {}
|
||||||
|
impl<T: PrimInt + Display + FromStr + Send + Sync + 'static> Number for T {}
|
||||||
|
|
||||||
|
pub struct NumberEdit<'a, T: Number> {
|
||||||
|
value: &'a mut T,
|
||||||
|
increment: T,
|
||||||
|
min: Option<T>,
|
||||||
|
max: Option<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: Number> NumberEdit<'a, T> {
|
||||||
|
pub fn new(value: &'a mut T) -> Self {
|
||||||
|
Self {
|
||||||
|
value,
|
||||||
|
increment: T::one(),
|
||||||
|
min: None,
|
||||||
|
max: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn range(self, range: impl RangeBounds<T>) -> Self {
|
||||||
|
let min = match range.start_bound() {
|
||||||
|
Bound::Unbounded => None,
|
||||||
|
Bound::Included(t) => Some(*t),
|
||||||
|
Bound::Excluded(t) => t.checked_add(&self.increment),
|
||||||
|
};
|
||||||
|
let max = match range.end_bound() {
|
||||||
|
Bound::Unbounded => None,
|
||||||
|
Bound::Included(t) => Some(*t),
|
||||||
|
Bound::Excluded(t) => t.checked_sub(&self.increment),
|
||||||
|
};
|
||||||
|
Self { min, max, ..self }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Number> Widget for NumberEdit<'_, T> {
|
||||||
|
fn ui(self, ui: &mut Ui) -> Response {
|
||||||
|
let (last_value, mut str, focus) = ui.memory(|m| {
|
||||||
|
let (lv, s) = m
|
||||||
|
.data
|
||||||
|
.get_temp(ui.id())
|
||||||
|
.unwrap_or((*self.value, self.value.to_string()));
|
||||||
|
let focus = m.has_focus(ui.id());
|
||||||
|
(lv, s, focus)
|
||||||
|
});
|
||||||
|
let mut stale = false;
|
||||||
|
if *self.value != last_value {
|
||||||
|
str = self.value.to_string();
|
||||||
|
stale = true;
|
||||||
|
}
|
||||||
|
let valid = str.parse().is_ok_and(|v: T| v == *self.value);
|
||||||
|
let mut up_pressed = false;
|
||||||
|
let mut down_pressed = false;
|
||||||
|
if focus {
|
||||||
|
ui.input_mut(|i| {
|
||||||
|
i.events.retain(|e| match e {
|
||||||
|
Event::Key {
|
||||||
|
key: Key::ArrowUp,
|
||||||
|
pressed: true,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
up_pressed = true;
|
||||||
|
false
|
||||||
|
}
|
||||||
|
Event::Key {
|
||||||
|
key: Key::ArrowDown,
|
||||||
|
pressed: true,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
down_pressed = true;
|
||||||
|
false
|
||||||
|
}
|
||||||
|
_ => true,
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let text = TextEdit::singleline(&mut str)
|
||||||
|
.horizontal_align(Align::Max)
|
||||||
|
.id(ui.id())
|
||||||
|
.margin(Margin {
|
||||||
|
left: 4.0,
|
||||||
|
right: 20.0,
|
||||||
|
top: 2.0,
|
||||||
|
bottom: 2.0,
|
||||||
|
});
|
||||||
|
let res = if valid {
|
||||||
|
ui.add(text)
|
||||||
|
} else {
|
||||||
|
let message = match (self.min, self.max) {
|
||||||
|
(Some(min), Some(max)) => format!("Please enter a number between {min} and {max}."),
|
||||||
|
(Some(min), None) => format!("Please enter a number greater than {min}."),
|
||||||
|
(None, Some(max)) => format!("Please enter a number less than {max}."),
|
||||||
|
(None, None) => "Please enter a number.".to_string(),
|
||||||
|
};
|
||||||
|
ui.scope(|ui| {
|
||||||
|
let style = ui.style_mut();
|
||||||
|
style.visuals.selection.stroke.color = style.visuals.error_fg_color;
|
||||||
|
style.visuals.widgets.hovered.bg_stroke.color =
|
||||||
|
style.visuals.error_fg_color.gamma_multiply(0.60);
|
||||||
|
ui.add(text)
|
||||||
|
})
|
||||||
|
.inner
|
||||||
|
.on_hover_text(message)
|
||||||
|
};
|
||||||
|
|
||||||
|
let arrow_left = res.rect.max.x + 4.0;
|
||||||
|
let arrow_right = res.rect.max.x + 20.0;
|
||||||
|
let arrow_top = res.rect.min.y - 2.0;
|
||||||
|
let arrow_middle = (res.rect.min.y + res.rect.max.y) / 2.0;
|
||||||
|
let arrow_bottom = res.rect.max.y + 2.0;
|
||||||
|
|
||||||
|
let mut delta = None;
|
||||||
|
let top_arrow_rect = Rect {
|
||||||
|
min: (arrow_left, arrow_top).into(),
|
||||||
|
max: (arrow_right, arrow_middle).into(),
|
||||||
|
};
|
||||||
|
if draw_arrow(ui, top_arrow_rect, true).clicked_or_dragged() || up_pressed {
|
||||||
|
delta = Some(Direction::Up);
|
||||||
|
}
|
||||||
|
let bottom_arrow_rect = Rect {
|
||||||
|
min: (arrow_left, arrow_middle).into(),
|
||||||
|
max: (arrow_right, arrow_bottom).into(),
|
||||||
|
};
|
||||||
|
if draw_arrow(ui, bottom_arrow_rect, false).clicked_or_dragged() || down_pressed {
|
||||||
|
delta = Some(Direction::Down);
|
||||||
|
}
|
||||||
|
|
||||||
|
let in_range =
|
||||||
|
|val: &T| self.min.is_none_or(|m| &m <= val) && self.max.is_none_or(|m| &m >= val);
|
||||||
|
if let Some(dir) = delta {
|
||||||
|
let value = match dir {
|
||||||
|
Direction::Up => self.value.checked_add(&self.increment),
|
||||||
|
Direction::Down => self.value.checked_sub(&self.increment),
|
||||||
|
};
|
||||||
|
if let Some(new_value) = value.filter(in_range) {
|
||||||
|
*self.value = new_value;
|
||||||
|
}
|
||||||
|
str = self.value.to_string();
|
||||||
|
stale = true;
|
||||||
|
} else if res.changed {
|
||||||
|
if let Some(new_value) = str.parse().ok().filter(in_range) {
|
||||||
|
*self.value = new_value;
|
||||||
|
}
|
||||||
|
stale = true;
|
||||||
|
}
|
||||||
|
if stale {
|
||||||
|
ui.memory_mut(|m| m.data.insert_temp(ui.id(), (*self.value, str)));
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_arrow(ui: &mut Ui, rect: Rect, up: bool) -> Response {
|
||||||
|
let arrow_res = ui
|
||||||
|
.allocate_rect(
|
||||||
|
rect,
|
||||||
|
Sense {
|
||||||
|
click: true,
|
||||||
|
drag: true,
|
||||||
|
focusable: false,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.on_hover_cursor(CursorIcon::Default);
|
||||||
|
let visuals = ui.style().visuals.widgets.style(&arrow_res);
|
||||||
|
let painter = ui.painter_at(arrow_res.rect);
|
||||||
|
|
||||||
|
let rounding = if up {
|
||||||
|
Rounding {
|
||||||
|
ne: 2.0,
|
||||||
|
..Rounding::ZERO
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Rounding {
|
||||||
|
se: 2.0,
|
||||||
|
..Rounding::ZERO
|
||||||
|
}
|
||||||
|
};
|
||||||
|
painter.rect_filled(arrow_res.rect, rounding, visuals.bg_fill);
|
||||||
|
|
||||||
|
let left = rect.left() + 4.0;
|
||||||
|
let center = (rect.left() + rect.right()) / 2.0;
|
||||||
|
let right = rect.right() - 4.0;
|
||||||
|
let top = rect.top() + 3.0;
|
||||||
|
let bottom = rect.bottom() - 3.0;
|
||||||
|
let points = if up {
|
||||||
|
vec![
|
||||||
|
(left, bottom).into(),
|
||||||
|
(center, top).into(),
|
||||||
|
(right, bottom).into(),
|
||||||
|
]
|
||||||
|
} else {
|
||||||
|
vec![
|
||||||
|
(right, top).into(),
|
||||||
|
(center, bottom).into(),
|
||||||
|
(left, top).into(),
|
||||||
|
]
|
||||||
|
};
|
||||||
|
painter.add(Shape::convex_polygon(
|
||||||
|
points,
|
||||||
|
visuals.fg_stroke.color,
|
||||||
|
Stroke::NONE,
|
||||||
|
));
|
||||||
|
arrow_res
|
||||||
|
}
|
||||||
|
|
||||||
|
trait ResponseExt {
|
||||||
|
fn clicked_or_dragged(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResponseExt for Response {
|
||||||
|
fn clicked_or_dragged(&self) -> bool {
|
||||||
|
self.clicked() || self.dragged()
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
mod bgmap;
|
||||||
|
mod chardata;
|
||||||
|
mod object;
|
||||||
|
mod utils;
|
||||||
|
|
||||||
|
pub use bgmap::*;
|
||||||
|
pub use chardata::*;
|
||||||
|
pub use object::*;
|
|
@ -0,0 +1,315 @@
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use egui::{
|
||||||
|
Align, CentralPanel, Checkbox, Color32, ComboBox, Context, Image, ScrollArea, Slider, TextEdit,
|
||||||
|
TextureOptions, Ui, ViewportBuilder, ViewportId,
|
||||||
|
};
|
||||||
|
use egui_extras::{Column, Size, StripBuilder, TableBuilder};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
emulator::SimId,
|
||||||
|
memory::{MemoryClient, MemoryView},
|
||||||
|
vram::{VramImage, VramParams, VramProcessor, VramRenderer, VramTextureLoader},
|
||||||
|
window::{
|
||||||
|
utils::{NumberEdit, UiExt},
|
||||||
|
AppWindow,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::utils::{self, CellData, CharacterGrid};
|
||||||
|
|
||||||
|
pub struct BgMapWindow {
|
||||||
|
sim_id: SimId,
|
||||||
|
loader: Arc<VramTextureLoader>,
|
||||||
|
memory: Arc<MemoryClient>,
|
||||||
|
bgmaps: MemoryView,
|
||||||
|
cell_index: usize,
|
||||||
|
generic_palette: bool,
|
||||||
|
params: VramParams<BgMapParams>,
|
||||||
|
scale: f32,
|
||||||
|
show_grid: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BgMapWindow {
|
||||||
|
pub fn new(sim_id: SimId, memory: &Arc<MemoryClient>, vram: &mut VramProcessor) -> Self {
|
||||||
|
let renderer = BgMapRenderer::new(sim_id, memory);
|
||||||
|
let ([cell, bgmap], params) = vram.add(renderer);
|
||||||
|
let loader =
|
||||||
|
VramTextureLoader::new([("vram://cell".into(), cell), ("vram://bgmap".into(), bgmap)]);
|
||||||
|
Self {
|
||||||
|
sim_id,
|
||||||
|
loader: Arc::new(loader),
|
||||||
|
memory: memory.clone(),
|
||||||
|
bgmaps: memory.watch(sim_id, 0x00020000, 0x1d800),
|
||||||
|
cell_index: 0,
|
||||||
|
generic_palette: false,
|
||||||
|
params,
|
||||||
|
scale: 1.0,
|
||||||
|
show_grid: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_form(&mut self, ui: &mut Ui) {
|
||||||
|
let row_height = ui.spacing().interact_size.y;
|
||||||
|
ui.vertical(|ui| {
|
||||||
|
TableBuilder::new(ui)
|
||||||
|
.column(Column::auto())
|
||||||
|
.column(Column::remainder())
|
||||||
|
.body(|mut body| {
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Map");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let mut bgmap_index = self.cell_index / 4096;
|
||||||
|
ui.add(NumberEdit::new(&mut bgmap_index).range(0..14));
|
||||||
|
if bgmap_index != self.cell_index / 4096 {
|
||||||
|
self.cell_index = (bgmap_index * 4096) + (self.cell_index % 4096);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Cell");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(NumberEdit::new(&mut self.cell_index).range(0..16 * 4096));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Address");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let address = 0x00020000 + (self.cell_index * 2);
|
||||||
|
let mut address_str = format!("{address:08x}");
|
||||||
|
ui.add_enabled(
|
||||||
|
false,
|
||||||
|
TextEdit::singleline(&mut address_str).horizontal_align(Align::Max),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
let image = Image::new("vram://cell")
|
||||||
|
.maintain_aspect_ratio(true)
|
||||||
|
.texture_options(TextureOptions::NEAREST);
|
||||||
|
ui.add(image);
|
||||||
|
ui.section("Cell", |ui| {
|
||||||
|
let mut data = self.bgmaps.borrow().read::<u16>(self.cell_index);
|
||||||
|
let mut cell = CellData::parse(data);
|
||||||
|
TableBuilder::new(ui)
|
||||||
|
.column(Column::remainder())
|
||||||
|
.column(Column::remainder())
|
||||||
|
.body(|mut body| {
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Character");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(NumberEdit::new(&mut cell.char_index).range(0..2048));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Palette");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ComboBox::from_id_salt("palette")
|
||||||
|
.selected_text(format!("BG {}", cell.palette_index))
|
||||||
|
.width(ui.available_width())
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
for palette in 0..4 {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut cell.palette_index,
|
||||||
|
palette,
|
||||||
|
format!("BG {palette}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(Checkbox::new(&mut cell.hflip, "H-flip"));
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(Checkbox::new(&mut cell.vflip, "V-flip"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if cell.update(&mut data) {
|
||||||
|
let address = 0x00020000 + (self.cell_index * 2);
|
||||||
|
self.memory.write(self.sim_id, address as u32, &data);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.section("Display", |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label("Scale");
|
||||||
|
ui.spacing_mut().slider_width = ui.available_width();
|
||||||
|
let slider = Slider::new(&mut self.scale, 1.0..=10.0)
|
||||||
|
.step_by(1.0)
|
||||||
|
.show_value(false);
|
||||||
|
ui.add(slider);
|
||||||
|
});
|
||||||
|
ui.checkbox(&mut self.show_grid, "Show grid");
|
||||||
|
ui.checkbox(&mut self.generic_palette, "Generic palette");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
self.params.write(BgMapParams {
|
||||||
|
cell_index: self.cell_index,
|
||||||
|
generic_palette: self.generic_palette,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_bgmap(&mut self, ui: &mut Ui) {
|
||||||
|
let grid = CharacterGrid::new("vram://bgmap")
|
||||||
|
.with_scale(self.scale)
|
||||||
|
.with_grid(self.show_grid)
|
||||||
|
.with_selected(self.cell_index % 4096);
|
||||||
|
if let Some(selected) = grid.show(ui) {
|
||||||
|
self.cell_index = (self.cell_index / 4096 * 4096) + selected;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppWindow for BgMapWindow {
|
||||||
|
fn viewport_id(&self) -> ViewportId {
|
||||||
|
ViewportId::from_hash_of(format!("bgmap-{}", self.sim_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sim_id(&self) -> SimId {
|
||||||
|
self.sim_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn initial_viewport(&self) -> ViewportBuilder {
|
||||||
|
ViewportBuilder::default()
|
||||||
|
.with_title(format!("BG Map Data ({})", self.sim_id))
|
||||||
|
.with_inner_size((640.0, 480.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_init(&mut self, ctx: &Context, _render_state: &egui_wgpu::RenderState) {
|
||||||
|
ctx.add_texture_loader(self.loader.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show(&mut self, ctx: &Context) {
|
||||||
|
CentralPanel::default().show(ctx, |ui| {
|
||||||
|
ui.horizontal_top(|ui| {
|
||||||
|
StripBuilder::new(ui)
|
||||||
|
.size(Size::relative(0.3))
|
||||||
|
.size(Size::remainder())
|
||||||
|
.horizontal(|mut strip| {
|
||||||
|
strip.cell(|ui| {
|
||||||
|
ScrollArea::vertical().show(ui, |ui| self.show_form(ui));
|
||||||
|
});
|
||||||
|
strip.cell(|ui| {
|
||||||
|
ScrollArea::both().show(ui, |ui| self.show_bgmap(ui));
|
||||||
|
});
|
||||||
|
})
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Clone, PartialEq, Eq)]
|
||||||
|
struct BgMapParams {
|
||||||
|
cell_index: usize,
|
||||||
|
generic_palette: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct BgMapRenderer {
|
||||||
|
chardata: MemoryView,
|
||||||
|
bgmaps: MemoryView,
|
||||||
|
brightness: MemoryView,
|
||||||
|
palettes: MemoryView,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BgMapRenderer {
|
||||||
|
pub fn new(sim_id: SimId, memory: &MemoryClient) -> Self {
|
||||||
|
Self {
|
||||||
|
chardata: memory.watch(sim_id, 0x00078000, 0x8000),
|
||||||
|
bgmaps: memory.watch(sim_id, 0x00020000, 0x1d800),
|
||||||
|
brightness: memory.watch(sim_id, 0x0005f824, 8),
|
||||||
|
palettes: memory.watch(sim_id, 0x0005f860, 16),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_bgmap(&self, image: &mut VramImage, bgmap_index: usize, generic_palette: bool) {
|
||||||
|
let chardata = self.chardata.borrow();
|
||||||
|
let bgmaps = self.bgmaps.borrow();
|
||||||
|
let brightness = self.brightness.borrow();
|
||||||
|
let palettes = self.palettes.borrow();
|
||||||
|
|
||||||
|
let brts = brightness.read::<[u8; 8]>(0);
|
||||||
|
let colors = if generic_palette {
|
||||||
|
[utils::generic_palette(Color32::RED); 4]
|
||||||
|
} else {
|
||||||
|
[0, 2, 4, 6].map(|i| utils::parse_palette(palettes.read(i), &brts, Color32::RED))
|
||||||
|
};
|
||||||
|
|
||||||
|
for (i, cell) in bgmaps.range::<u16>(bgmap_index * 4096, 4096).enumerate() {
|
||||||
|
let CellData {
|
||||||
|
char_index,
|
||||||
|
vflip,
|
||||||
|
hflip,
|
||||||
|
palette_index,
|
||||||
|
} = CellData::parse(cell);
|
||||||
|
let char = chardata.read::<[u16; 8]>(char_index);
|
||||||
|
let palette = &colors[palette_index];
|
||||||
|
|
||||||
|
for row in 0..8 {
|
||||||
|
let y = row + (i / 64) * 8;
|
||||||
|
for (col, pixel) in utils::read_char_row(&char, hflip, vflip, row).enumerate() {
|
||||||
|
let x = col + (i % 64) * 8;
|
||||||
|
image.write((x, y), palette[pixel as usize]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_bgmap_cell(&self, image: &mut VramImage, index: usize, generic_palette: bool) {
|
||||||
|
let chardata = self.chardata.borrow();
|
||||||
|
let bgmaps = self.bgmaps.borrow();
|
||||||
|
let brightness = self.brightness.borrow();
|
||||||
|
let palettes = self.palettes.borrow();
|
||||||
|
|
||||||
|
let brts = brightness.read::<[u8; 8]>(0);
|
||||||
|
|
||||||
|
let cell = bgmaps.read::<u16>(index);
|
||||||
|
|
||||||
|
let CellData {
|
||||||
|
char_index,
|
||||||
|
vflip,
|
||||||
|
hflip,
|
||||||
|
palette_index,
|
||||||
|
} = CellData::parse(cell);
|
||||||
|
let char = chardata.read::<[u16; 8]>(char_index);
|
||||||
|
let palette = if generic_palette {
|
||||||
|
utils::generic_palette(Color32::RED)
|
||||||
|
} else {
|
||||||
|
utils::parse_palette(palettes.read(palette_index * 2), &brts, Color32::RED)
|
||||||
|
};
|
||||||
|
|
||||||
|
for row in 0..8 {
|
||||||
|
for (col, pixel) in utils::read_char_row(&char, hflip, vflip, row).enumerate() {
|
||||||
|
image.write((col, row), palette[pixel as usize]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramRenderer<2> for BgMapRenderer {
|
||||||
|
type Params = BgMapParams;
|
||||||
|
|
||||||
|
fn sizes(&self) -> [[usize; 2]; 2] {
|
||||||
|
[[8, 8], [8 * 64, 8 * 64]]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render(&mut self, params: &Self::Params, images: &mut [VramImage; 2]) {
|
||||||
|
self.render_bgmap_cell(&mut images[0], params.cell_index, params.generic_palette);
|
||||||
|
self.render_bgmap(
|
||||||
|
&mut images[1],
|
||||||
|
params.cell_index / 4096,
|
||||||
|
params.generic_palette,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,356 @@
|
||||||
|
use std::{fmt::Display, sync::Arc};
|
||||||
|
|
||||||
|
use egui::{
|
||||||
|
Align, CentralPanel, Color32, ComboBox, Context, Image, ScrollArea, Slider, TextEdit,
|
||||||
|
TextureOptions, Ui, Vec2, ViewportBuilder, ViewportId,
|
||||||
|
};
|
||||||
|
use egui_extras::{Column, Size, StripBuilder, TableBuilder};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
emulator::SimId,
|
||||||
|
memory::{MemoryClient, MemoryView},
|
||||||
|
vram::{VramImage, VramParams, VramProcessor, VramRenderer, VramTextureLoader},
|
||||||
|
window::{
|
||||||
|
utils::{NumberEdit, UiExt as _},
|
||||||
|
AppWindow,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::utils::{self, CharacterGrid};
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
|
pub enum VramPalette {
|
||||||
|
#[default]
|
||||||
|
Generic,
|
||||||
|
Bg0,
|
||||||
|
Bg1,
|
||||||
|
Bg2,
|
||||||
|
Bg3,
|
||||||
|
Obj0,
|
||||||
|
Obj1,
|
||||||
|
Obj2,
|
||||||
|
Obj3,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramPalette {
|
||||||
|
pub const fn values() -> [VramPalette; 9] {
|
||||||
|
[
|
||||||
|
Self::Generic,
|
||||||
|
Self::Bg0,
|
||||||
|
Self::Bg1,
|
||||||
|
Self::Bg2,
|
||||||
|
Self::Bg3,
|
||||||
|
Self::Obj0,
|
||||||
|
Self::Obj1,
|
||||||
|
Self::Obj2,
|
||||||
|
Self::Obj3,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const fn offset(self) -> Option<usize> {
|
||||||
|
match self {
|
||||||
|
Self::Generic => None,
|
||||||
|
Self::Bg0 => Some(0),
|
||||||
|
Self::Bg1 => Some(2),
|
||||||
|
Self::Bg2 => Some(4),
|
||||||
|
Self::Bg3 => Some(6),
|
||||||
|
Self::Obj0 => Some(8),
|
||||||
|
Self::Obj1 => Some(10),
|
||||||
|
Self::Obj2 => Some(12),
|
||||||
|
Self::Obj3 => Some(14),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for VramPalette {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Generic => f.write_str("Generic"),
|
||||||
|
Self::Bg0 => f.write_str("BG 0"),
|
||||||
|
Self::Bg1 => f.write_str("BG 1"),
|
||||||
|
Self::Bg2 => f.write_str("BG 2"),
|
||||||
|
Self::Bg3 => f.write_str("BG 3"),
|
||||||
|
Self::Obj0 => f.write_str("OBJ 0"),
|
||||||
|
Self::Obj1 => f.write_str("OBJ 1"),
|
||||||
|
Self::Obj2 => f.write_str("OBJ 2"),
|
||||||
|
Self::Obj3 => f.write_str("OBJ 3"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CharacterDataWindow {
|
||||||
|
sim_id: SimId,
|
||||||
|
loader: Arc<VramTextureLoader>,
|
||||||
|
brightness: MemoryView,
|
||||||
|
palettes: MemoryView,
|
||||||
|
palette: VramPalette,
|
||||||
|
index: usize,
|
||||||
|
params: VramParams<CharDataParams>,
|
||||||
|
scale: f32,
|
||||||
|
show_grid: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CharacterDataWindow {
|
||||||
|
pub fn new(sim_id: SimId, memory: &MemoryClient, vram: &mut VramProcessor) -> Self {
|
||||||
|
let renderer = CharDataRenderer::new(sim_id, memory);
|
||||||
|
let ([char, chardata], params) = vram.add(renderer);
|
||||||
|
let loader = VramTextureLoader::new([
|
||||||
|
("vram://char".into(), char),
|
||||||
|
("vram://chardata".into(), chardata),
|
||||||
|
]);
|
||||||
|
Self {
|
||||||
|
sim_id,
|
||||||
|
loader: Arc::new(loader),
|
||||||
|
brightness: memory.watch(sim_id, 0x0005f824, 8),
|
||||||
|
palettes: memory.watch(sim_id, 0x0005f860, 16),
|
||||||
|
palette: params.palette,
|
||||||
|
index: params.index,
|
||||||
|
params,
|
||||||
|
scale: 4.0,
|
||||||
|
show_grid: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_form(&mut self, ui: &mut Ui) {
|
||||||
|
let row_height = ui.spacing().interact_size.y;
|
||||||
|
ui.vertical(|ui| {
|
||||||
|
TableBuilder::new(ui)
|
||||||
|
.column(Column::auto())
|
||||||
|
.column(Column::remainder())
|
||||||
|
.body(|mut body| {
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Index");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(NumberEdit::new(&mut self.index).range(0..2048));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Address");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let address = match self.index {
|
||||||
|
0x000..0x200 => 0x00060000 + self.index * 16,
|
||||||
|
0x200..0x400 => 0x000e0000 + (self.index - 0x200) * 16,
|
||||||
|
0x400..0x600 => 0x00160000 + (self.index - 0x400) * 16,
|
||||||
|
0x600..0x800 => 0x001e0000 + (self.index - 0x600) * 16,
|
||||||
|
_ => unreachable!("can't happen"),
|
||||||
|
};
|
||||||
|
let mut address_str = format!("{address:08x}");
|
||||||
|
ui.add_enabled(
|
||||||
|
false,
|
||||||
|
TextEdit::singleline(&mut address_str).horizontal_align(Align::Max),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Mirror");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let mirror = 0x00078000 + (self.index * 16);
|
||||||
|
let mut mirror_str = format!("{mirror:08x}");
|
||||||
|
ui.add_enabled(
|
||||||
|
false,
|
||||||
|
TextEdit::singleline(&mut mirror_str).horizontal_align(Align::Max),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
let image = Image::new("vram://char")
|
||||||
|
.maintain_aspect_ratio(true)
|
||||||
|
.texture_options(TextureOptions::NEAREST);
|
||||||
|
ui.add(image);
|
||||||
|
ui.section("Colors", |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label("Palette");
|
||||||
|
ComboBox::from_id_salt("palette")
|
||||||
|
.selected_text(self.palette.to_string())
|
||||||
|
.width(ui.available_width())
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
for palette in VramPalette::values() {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.palette,
|
||||||
|
palette,
|
||||||
|
palette.to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
TableBuilder::new(ui)
|
||||||
|
.columns(Column::remainder(), 4)
|
||||||
|
.body(|mut body| {
|
||||||
|
let palette = self.load_palette_colors();
|
||||||
|
body.row(30.0, |mut row| {
|
||||||
|
for color in palette {
|
||||||
|
row.col(|ui| {
|
||||||
|
let rect = ui.available_rect_before_wrap();
|
||||||
|
let scale = rect.height() / rect.width();
|
||||||
|
let rect = rect.scale_from_center2(Vec2::new(scale, 1.0));
|
||||||
|
ui.painter().rect_filled(rect, 0.0, color);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
ui.section("Display", |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label("Scale");
|
||||||
|
ui.spacing_mut().slider_width = ui.available_width();
|
||||||
|
let slider = Slider::new(&mut self.scale, 1.0..=10.0)
|
||||||
|
.step_by(1.0)
|
||||||
|
.show_value(false);
|
||||||
|
ui.add(slider);
|
||||||
|
});
|
||||||
|
ui.checkbox(&mut self.show_grid, "Show grid");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
self.params.write(CharDataParams {
|
||||||
|
palette: self.palette,
|
||||||
|
index: self.index,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_palette_colors(&self) -> [Color32; 4] {
|
||||||
|
let Some(offset) = self.palette.offset() else {
|
||||||
|
return utils::generic_palette(Color32::RED);
|
||||||
|
};
|
||||||
|
let palette = self.palettes.borrow().read(offset);
|
||||||
|
let brightnesses = self.brightness.borrow();
|
||||||
|
let brts = brightnesses.read(0);
|
||||||
|
utils::parse_palette(palette, &brts, Color32::RED)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_chardata(&mut self, ui: &mut Ui) {
|
||||||
|
let grid = CharacterGrid::new("vram://chardata")
|
||||||
|
.with_scale(self.scale)
|
||||||
|
.with_grid(self.show_grid)
|
||||||
|
.with_selected(self.index);
|
||||||
|
if let Some(selected) = grid.show(ui) {
|
||||||
|
self.index = selected;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppWindow for CharacterDataWindow {
|
||||||
|
fn viewport_id(&self) -> ViewportId {
|
||||||
|
ViewportId::from_hash_of(format!("chardata-{}", self.sim_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sim_id(&self) -> SimId {
|
||||||
|
self.sim_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn initial_viewport(&self) -> ViewportBuilder {
|
||||||
|
ViewportBuilder::default()
|
||||||
|
.with_title(format!("Character Data ({})", self.sim_id))
|
||||||
|
.with_inner_size((640.0, 480.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_init(&mut self, ctx: &Context, _render_state: &egui_wgpu::RenderState) {
|
||||||
|
ctx.add_texture_loader(self.loader.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show(&mut self, ctx: &Context) {
|
||||||
|
CentralPanel::default().show(ctx, |ui| {
|
||||||
|
ui.horizontal_top(|ui| {
|
||||||
|
StripBuilder::new(ui)
|
||||||
|
.size(Size::relative(0.3))
|
||||||
|
.size(Size::remainder())
|
||||||
|
.horizontal(|mut strip| {
|
||||||
|
strip.cell(|ui| {
|
||||||
|
ScrollArea::vertical().show(ui, |ui| self.show_form(ui));
|
||||||
|
});
|
||||||
|
strip.cell(|ui| {
|
||||||
|
ScrollArea::both().show(ui, |ui| self.show_chardata(ui));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash)]
|
||||||
|
enum CharDataResource {
|
||||||
|
Character { palette: VramPalette, index: usize },
|
||||||
|
CharacterData { palette: VramPalette },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default, PartialEq, Eq)]
|
||||||
|
struct CharDataParams {
|
||||||
|
palette: VramPalette,
|
||||||
|
index: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CharDataRenderer {
|
||||||
|
chardata: MemoryView,
|
||||||
|
brightness: MemoryView,
|
||||||
|
palettes: MemoryView,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramRenderer<2> for CharDataRenderer {
|
||||||
|
type Params = CharDataParams;
|
||||||
|
|
||||||
|
fn sizes(&self) -> [[usize; 2]; 2] {
|
||||||
|
[[8, 8], [16 * 8, 128 * 8]]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render(&mut self, params: &Self::Params, image: &mut [VramImage; 2]) {
|
||||||
|
self.render_character(&mut image[0], params.palette, params.index);
|
||||||
|
self.render_character_data(&mut image[1], params.palette);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CharDataRenderer {
|
||||||
|
pub fn new(sim_id: SimId, memory: &MemoryClient) -> Self {
|
||||||
|
Self {
|
||||||
|
chardata: memory.watch(sim_id, 0x00078000, 0x8000),
|
||||||
|
brightness: memory.watch(sim_id, 0x0005f824, 8),
|
||||||
|
palettes: memory.watch(sim_id, 0x0005f860, 16),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_character(&self, image: &mut VramImage, palette: VramPalette, index: usize) {
|
||||||
|
if index >= 2048 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let palette = self.load_palette(palette);
|
||||||
|
let chardata = self.chardata.borrow();
|
||||||
|
let character = chardata.range::<u16>(index * 8, 8);
|
||||||
|
for (row, pixels) in character.enumerate() {
|
||||||
|
for col in 0..8 {
|
||||||
|
let char = (pixels >> (col * 2)) & 0x03;
|
||||||
|
image.write((col, row), palette[char as usize]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_character_data(&self, image: &mut VramImage, palette: VramPalette) {
|
||||||
|
let palette = self.load_palette(palette);
|
||||||
|
let chardata = self.chardata.borrow();
|
||||||
|
for (row, pixels) in chardata.range::<u16>(0, 8 * 2048).enumerate() {
|
||||||
|
let char_index = row / 8;
|
||||||
|
let row_index = row % 8;
|
||||||
|
let x = (char_index % 16) * 8;
|
||||||
|
let y = (char_index / 16) * 8 + row_index;
|
||||||
|
for col in 0..8 {
|
||||||
|
let char = (pixels >> (col * 2)) & 0x03;
|
||||||
|
image.write((x + col, y), palette[char as usize]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_palette(&self, palette: VramPalette) -> [Color32; 4] {
|
||||||
|
let Some(offset) = palette.offset() else {
|
||||||
|
return utils::GENERIC_PALETTE.map(|p| utils::shade(p, Color32::RED));
|
||||||
|
};
|
||||||
|
let palette = self.palettes.borrow().read(offset);
|
||||||
|
let brightnesses = self.brightness.borrow();
|
||||||
|
let brts = brightnesses.read(0);
|
||||||
|
utils::parse_palette(palette, &brts, Color32::RED)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,341 @@
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use egui::{
|
||||||
|
Align, CentralPanel, Checkbox, Color32, ComboBox, Context, Image, ScrollArea, Slider, TextEdit,
|
||||||
|
TextureOptions, Ui, ViewportBuilder, ViewportId,
|
||||||
|
};
|
||||||
|
use egui_extras::{Column, Size, StripBuilder, TableBuilder};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
emulator::SimId,
|
||||||
|
memory::{MemoryClient, MemoryView},
|
||||||
|
vram::{VramImage, VramParams, VramProcessor, VramRenderer, VramTextureLoader},
|
||||||
|
window::{
|
||||||
|
utils::{NumberEdit, UiExt as _},
|
||||||
|
AppWindow,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::utils::{self, Object};
|
||||||
|
|
||||||
|
pub struct ObjectWindow {
|
||||||
|
sim_id: SimId,
|
||||||
|
loader: Arc<VramTextureLoader>,
|
||||||
|
memory: Arc<MemoryClient>,
|
||||||
|
objects: MemoryView,
|
||||||
|
index: usize,
|
||||||
|
generic_palette: bool,
|
||||||
|
params: VramParams<ObjectParams>,
|
||||||
|
scale: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ObjectWindow {
|
||||||
|
pub fn new(sim_id: SimId, memory: &Arc<MemoryClient>, vram: &mut VramProcessor) -> Self {
|
||||||
|
let renderer = ObjectRenderer::new(sim_id, memory);
|
||||||
|
let ([zoom, full], params) = vram.add(renderer);
|
||||||
|
let loader =
|
||||||
|
VramTextureLoader::new([("vram://zoom".into(), zoom), ("vram://full".into(), full)]);
|
||||||
|
Self {
|
||||||
|
sim_id,
|
||||||
|
loader: Arc::new(loader),
|
||||||
|
memory: memory.clone(),
|
||||||
|
objects: memory.watch(sim_id, 0x0003e000, 0x2000),
|
||||||
|
index: 0,
|
||||||
|
generic_palette: false,
|
||||||
|
params,
|
||||||
|
scale: 1.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_form(&mut self, ui: &mut Ui) {
|
||||||
|
let row_height = ui.spacing().interact_size.y;
|
||||||
|
ui.vertical(|ui| {
|
||||||
|
TableBuilder::new(ui)
|
||||||
|
.column(Column::auto())
|
||||||
|
.column(Column::remainder())
|
||||||
|
.body(|mut body| {
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Index");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(NumberEdit::new(&mut self.index).range(0..1024));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Address");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
let address = 0x3e000 + self.index * 8;
|
||||||
|
let mut address_str = format!("{address:08x}");
|
||||||
|
ui.add_enabled(
|
||||||
|
false,
|
||||||
|
TextEdit::singleline(&mut address_str).horizontal_align(Align::Max),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
let image = Image::new("vram://zoom")
|
||||||
|
.maintain_aspect_ratio(true)
|
||||||
|
.texture_options(TextureOptions::NEAREST);
|
||||||
|
ui.add(image);
|
||||||
|
ui.section("Properties", |ui| {
|
||||||
|
let mut object = self.objects.borrow().read::<[u16; 4]>(self.index);
|
||||||
|
let mut obj = Object::parse(object);
|
||||||
|
TableBuilder::new(ui)
|
||||||
|
.column(Column::remainder())
|
||||||
|
.column(Column::remainder())
|
||||||
|
.body(|mut body| {
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Character");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(NumberEdit::new(&mut obj.data.char_index).range(0..2048));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Palette");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ComboBox::from_id_salt("palette")
|
||||||
|
.selected_text(format!("OBJ {}", obj.data.palette_index))
|
||||||
|
.width(ui.available_width())
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
for palette in 0..4 {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut obj.data.palette_index,
|
||||||
|
palette,
|
||||||
|
format!("OBJ {palette}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("X");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(NumberEdit::new(&mut obj.x).range(-512..512));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Y");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(NumberEdit::new(&mut obj.y).range(-8..=224));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.label("Parallax");
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(NumberEdit::new(&mut obj.parallax).range(-512..512));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(Checkbox::new(&mut obj.data.hflip, "H-flip"));
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(Checkbox::new(&mut obj.data.vflip, "V-flip"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
body.row(row_height, |mut row| {
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(Checkbox::new(&mut obj.lon, "Left"));
|
||||||
|
});
|
||||||
|
row.col(|ui| {
|
||||||
|
ui.add(Checkbox::new(&mut obj.ron, "Right"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if obj.update(&mut object) {
|
||||||
|
let address = 0x3e000 + self.index * 8;
|
||||||
|
self.memory.write(self.sim_id, address as u32, &object);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.section("Display", |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label("Scale");
|
||||||
|
ui.spacing_mut().slider_width = ui.available_width();
|
||||||
|
let slider = Slider::new(&mut self.scale, 1.0..=10.0)
|
||||||
|
.step_by(1.0)
|
||||||
|
.show_value(false);
|
||||||
|
ui.add(slider);
|
||||||
|
});
|
||||||
|
ui.checkbox(&mut self.generic_palette, "Generic palette");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
self.params.write(ObjectParams {
|
||||||
|
index: self.index,
|
||||||
|
generic_palette: self.generic_palette,
|
||||||
|
..ObjectParams::default()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_object(&mut self, ui: &mut Ui) {
|
||||||
|
let image = Image::new("vram://full")
|
||||||
|
.fit_to_original_size(self.scale)
|
||||||
|
.texture_options(TextureOptions::NEAREST);
|
||||||
|
ui.add(image);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppWindow for ObjectWindow {
|
||||||
|
fn viewport_id(&self) -> egui::ViewportId {
|
||||||
|
ViewportId::from_hash_of(format!("object-{}", self.sim_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sim_id(&self) -> SimId {
|
||||||
|
self.sim_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn initial_viewport(&self) -> ViewportBuilder {
|
||||||
|
ViewportBuilder::default()
|
||||||
|
.with_title(format!("Object Data ({})", self.sim_id))
|
||||||
|
.with_inner_size((640.0, 500.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_init(&mut self, ctx: &Context, _render_state: &egui_wgpu::RenderState) {
|
||||||
|
ctx.add_texture_loader(self.loader.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show(&mut self, ctx: &Context) {
|
||||||
|
CentralPanel::default().show(ctx, |ui| {
|
||||||
|
ui.horizontal_top(|ui| {
|
||||||
|
StripBuilder::new(ui)
|
||||||
|
.size(Size::relative(0.3))
|
||||||
|
.size(Size::remainder())
|
||||||
|
.horizontal(|mut strip| {
|
||||||
|
strip.cell(|ui| {
|
||||||
|
ScrollArea::vertical().show(ui, |ui| self.show_form(ui));
|
||||||
|
});
|
||||||
|
strip.cell(|ui| {
|
||||||
|
ScrollArea::both().show(ui, |ui| self.show_object(ui));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
|
struct ObjectParams {
|
||||||
|
index: usize,
|
||||||
|
generic_palette: bool,
|
||||||
|
left_color: Color32,
|
||||||
|
right_color: Color32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ObjectParams {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
index: 0,
|
||||||
|
generic_palette: false,
|
||||||
|
left_color: Color32::from_rgb(0xff, 0x00, 0x00),
|
||||||
|
right_color: Color32::from_rgb(0x00, 0xc6, 0xf0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Eye {
|
||||||
|
Left,
|
||||||
|
Right,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ObjectRenderer {
|
||||||
|
chardata: MemoryView,
|
||||||
|
objects: MemoryView,
|
||||||
|
brightness: MemoryView,
|
||||||
|
palettes: MemoryView,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ObjectRenderer {
|
||||||
|
pub fn new(sim_id: SimId, memory: &MemoryClient) -> Self {
|
||||||
|
Self {
|
||||||
|
chardata: memory.watch(sim_id, 0x00078000, 0x8000),
|
||||||
|
objects: memory.watch(sim_id, 0x0003e000, 0x2000),
|
||||||
|
brightness: memory.watch(sim_id, 0x0005f824, 8),
|
||||||
|
palettes: memory.watch(sim_id, 0x0005f860, 16),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_object(&self, image: &mut VramImage, params: &ObjectParams, use_pos: bool, eye: Eye) {
|
||||||
|
let chardata = self.chardata.borrow();
|
||||||
|
let objects = self.objects.borrow();
|
||||||
|
let brightness = self.brightness.borrow();
|
||||||
|
let palettes = self.palettes.borrow();
|
||||||
|
|
||||||
|
let object: [u16; 4] = objects.read(params.index);
|
||||||
|
let obj = Object::parse(object);
|
||||||
|
|
||||||
|
if match eye {
|
||||||
|
Eye::Left => !obj.lon,
|
||||||
|
Eye::Right => !obj.ron,
|
||||||
|
} {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let brts = brightness.read::<[u8; 8]>(0);
|
||||||
|
let (x, y) = if use_pos {
|
||||||
|
let x = match eye {
|
||||||
|
Eye::Left => obj.x - obj.parallax,
|
||||||
|
Eye::Right => obj.x + obj.parallax,
|
||||||
|
};
|
||||||
|
(x, obj.y)
|
||||||
|
} else {
|
||||||
|
(0, 0)
|
||||||
|
};
|
||||||
|
|
||||||
|
let color = match eye {
|
||||||
|
Eye::Left => params.left_color,
|
||||||
|
Eye::Right => params.right_color,
|
||||||
|
};
|
||||||
|
|
||||||
|
let char = chardata.read::<[u16; 8]>(obj.data.char_index);
|
||||||
|
let palette = if params.generic_palette {
|
||||||
|
utils::generic_palette(color)
|
||||||
|
} else {
|
||||||
|
utils::parse_palette(palettes.read(8 + obj.data.palette_index * 2), &brts, color)
|
||||||
|
};
|
||||||
|
|
||||||
|
for row in 0..8 {
|
||||||
|
let real_y = y + row as i16;
|
||||||
|
if !(0..224).contains(&real_y) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (col, pixel) in
|
||||||
|
utils::read_char_row(&char, obj.data.hflip, obj.data.vflip, row).enumerate()
|
||||||
|
{
|
||||||
|
let real_x = x + col as i16;
|
||||||
|
if !(0..384).contains(&real_x) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
image.add((real_x as usize, real_y as usize), palette[pixel as usize]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VramRenderer<2> for ObjectRenderer {
|
||||||
|
type Params = ObjectParams;
|
||||||
|
|
||||||
|
fn sizes(&self) -> [[usize; 2]; 2] {
|
||||||
|
[[8, 8], [384, 224]]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render(&mut self, params: &Self::Params, images: &mut [VramImage; 2]) {
|
||||||
|
images[0].clear();
|
||||||
|
self.render_object(&mut images[0], params, false, Eye::Left);
|
||||||
|
self.render_object(&mut images[0], params, false, Eye::Right);
|
||||||
|
images[1].clear();
|
||||||
|
self.render_object(&mut images[1], params, true, Eye::Left);
|
||||||
|
self.render_object(&mut images[1], params, true, Eye::Right);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,226 @@
|
||||||
|
use egui::{Color32, Image, ImageSource, Response, Sense, TextureOptions, Ui, Widget};
|
||||||
|
|
||||||
|
pub const GENERIC_PALETTE: [u8; 4] = [0, 64, 128, 255];
|
||||||
|
|
||||||
|
pub fn shade(brt: u8, color: Color32) -> Color32 {
|
||||||
|
color.gamma_multiply(brt as f32 / 255.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generic_palette(color: Color32) -> [Color32; 4] {
|
||||||
|
GENERIC_PALETTE.map(|brt| shade(brt, color))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_palette(palette: u8, brts: &[u8; 8], color: Color32) -> [Color32; 4] {
|
||||||
|
let shades = [
|
||||||
|
Color32::BLACK,
|
||||||
|
shade(brts[0], color),
|
||||||
|
shade(brts[2], color),
|
||||||
|
shade(
|
||||||
|
brts[0].saturating_add(brts[2]).saturating_add(brts[4]),
|
||||||
|
color,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
[
|
||||||
|
Color32::BLACK,
|
||||||
|
shades[(palette >> 2) as usize & 0x03],
|
||||||
|
shades[(palette >> 4) as usize & 0x03],
|
||||||
|
shades[(palette >> 6) as usize & 0x03],
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Object {
|
||||||
|
pub x: i16,
|
||||||
|
pub lon: bool,
|
||||||
|
pub ron: bool,
|
||||||
|
pub parallax: i16,
|
||||||
|
pub y: i16,
|
||||||
|
pub data: CellData,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Object {
|
||||||
|
pub fn parse(object: [u16; 4]) -> Self {
|
||||||
|
let x = ((object[0] & 0x03ff) << 6 >> 6) as i16;
|
||||||
|
let parallax = ((object[1] & 0x03ff) << 6 >> 6) as i16;
|
||||||
|
let lon = object[1] & 0x8000 != 0;
|
||||||
|
let ron = object[1] & 0x4000 != 0;
|
||||||
|
let y = (object[2] & 0x00ff) as i16;
|
||||||
|
// Y is stored as the bottom 8 bits of an i16,
|
||||||
|
// so only sign extend if it's out of range.
|
||||||
|
let y = if y > 224 { y << 8 >> 8 } else { y };
|
||||||
|
let data = CellData::parse(object[3]);
|
||||||
|
Self {
|
||||||
|
x,
|
||||||
|
lon,
|
||||||
|
ron,
|
||||||
|
parallax,
|
||||||
|
y,
|
||||||
|
data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&self, source: &mut [u16; 4]) -> bool {
|
||||||
|
let mut changed = false;
|
||||||
|
|
||||||
|
let new_x = (self.x as u16 & 0x03ff) | (source[0] & 0xfc00);
|
||||||
|
changed |= source[0] != new_x;
|
||||||
|
source[0] = new_x;
|
||||||
|
|
||||||
|
let new_p = if self.lon { 0x8000 } else { 0x0000 }
|
||||||
|
| if self.ron { 0x4000 } else { 0x0000 }
|
||||||
|
| (self.parallax as u16 & 0x3ff)
|
||||||
|
| (source[1] & 0x3c00);
|
||||||
|
changed |= source[1] != new_p;
|
||||||
|
source[1] = new_p;
|
||||||
|
|
||||||
|
let new_y = (self.y as u16 & 0x00ff) | (source[2] & 0xff00);
|
||||||
|
changed |= source[2] != new_y;
|
||||||
|
source[2] = new_y;
|
||||||
|
|
||||||
|
if self.data.update(&mut source[3]) {
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
changed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CellData {
|
||||||
|
pub palette_index: usize,
|
||||||
|
pub hflip: bool,
|
||||||
|
pub vflip: bool,
|
||||||
|
pub char_index: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CellData {
|
||||||
|
pub fn parse(cell: u16) -> Self {
|
||||||
|
let char_index = (cell & 0x7ff) as usize;
|
||||||
|
let vflip = cell & 0x1000 != 0;
|
||||||
|
let hflip = cell & 0x2000 != 0;
|
||||||
|
let palette_index = (cell >> 14) as usize;
|
||||||
|
Self {
|
||||||
|
char_index,
|
||||||
|
vflip,
|
||||||
|
hflip,
|
||||||
|
palette_index,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&self, source: &mut u16) -> bool {
|
||||||
|
let new_value = (self.palette_index as u16) << 14
|
||||||
|
| if self.hflip { 0x2000 } else { 0x0000 }
|
||||||
|
| if self.vflip { 0x1000 } else { 0x0000 }
|
||||||
|
| (self.char_index as u16 & 0x07ff)
|
||||||
|
| (*source & 0x0800);
|
||||||
|
let changed = *source != new_value;
|
||||||
|
*source = new_value;
|
||||||
|
changed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_char_row(
|
||||||
|
char: &[u16; 8],
|
||||||
|
hflip: bool,
|
||||||
|
vflip: bool,
|
||||||
|
row: usize,
|
||||||
|
) -> impl Iterator<Item = u8> {
|
||||||
|
let pixels = if vflip { char[7 - row] } else { char[row] };
|
||||||
|
(0..16).step_by(2).map(move |i| {
|
||||||
|
let pixel = if hflip { 14 - i } else { i };
|
||||||
|
((pixels >> pixel) & 0x3) as u8
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CharacterGrid<'a> {
|
||||||
|
source: ImageSource<'a>,
|
||||||
|
scale: f32,
|
||||||
|
show_grid: bool,
|
||||||
|
selected: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> CharacterGrid<'a> {
|
||||||
|
pub fn new(source: impl Into<ImageSource<'a>>) -> Self {
|
||||||
|
Self {
|
||||||
|
source: source.into(),
|
||||||
|
scale: 1.0,
|
||||||
|
show_grid: false,
|
||||||
|
selected: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_scale(self, scale: f32) -> Self {
|
||||||
|
Self { scale, ..self }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_grid(self, show_grid: bool) -> Self {
|
||||||
|
Self { show_grid, ..self }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_selected(self, selected: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
selected: Some(selected),
|
||||||
|
..self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn show(self, ui: &mut Ui) -> Option<usize> {
|
||||||
|
let start_pos = ui.cursor().min;
|
||||||
|
let cell_size = 8.0 * self.scale;
|
||||||
|
|
||||||
|
let res = self.ui(ui);
|
||||||
|
|
||||||
|
let grid_width_cells = ((res.rect.max.x - res.rect.min.x) / cell_size).round() as usize;
|
||||||
|
|
||||||
|
if res.clicked() {
|
||||||
|
let click_pos = res.interact_pointer_pos()?;
|
||||||
|
let grid_pos = (click_pos - start_pos) / cell_size;
|
||||||
|
Some((grid_pos.y as usize * grid_width_cells) + grid_pos.x as usize)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Widget for CharacterGrid<'_> {
|
||||||
|
fn ui(self, ui: &mut Ui) -> Response {
|
||||||
|
let image = Image::new(self.source)
|
||||||
|
.fit_to_original_size(self.scale)
|
||||||
|
.texture_options(TextureOptions::NEAREST)
|
||||||
|
.sense(Sense::click());
|
||||||
|
let res = ui.add(image);
|
||||||
|
|
||||||
|
let cell_size = 8.0 * self.scale;
|
||||||
|
let grid_width_cells = ((res.rect.max.x - res.rect.min.x) / cell_size).round() as usize;
|
||||||
|
let grid_height_cells = ((res.rect.max.y - res.rect.min.y) / cell_size).round() as usize;
|
||||||
|
|
||||||
|
let painter = ui.painter_at(res.rect);
|
||||||
|
if self.show_grid {
|
||||||
|
let stroke = ui.style().visuals.widgets.noninteractive.fg_stroke;
|
||||||
|
for x in (1..grid_width_cells).map(|i| (i as f32) * cell_size) {
|
||||||
|
let p1 = (res.rect.min.x + x, res.rect.min.y).into();
|
||||||
|
let p2 = (res.rect.min.x + x, res.rect.max.y).into();
|
||||||
|
painter.line(vec![p1, p2], stroke);
|
||||||
|
}
|
||||||
|
for y in (1..grid_height_cells).map(|i| (i as f32) * cell_size) {
|
||||||
|
let p1 = (res.rect.min.x, res.rect.min.y + y).into();
|
||||||
|
let p2 = (res.rect.max.x, res.rect.min.y + y).into();
|
||||||
|
painter.line(vec![p1, p2], stroke);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(selected) = self.selected {
|
||||||
|
let x1 = (selected % grid_width_cells) as f32 * cell_size;
|
||||||
|
let x2 = x1 + cell_size;
|
||||||
|
let y1 = (selected / grid_width_cells) as f32 * cell_size;
|
||||||
|
let y2 = y1 + cell_size;
|
||||||
|
painter.line(
|
||||||
|
vec![
|
||||||
|
(res.rect.min + (x1, y1).into()),
|
||||||
|
(res.rect.min + (x2, y1).into()),
|
||||||
|
(res.rect.min + (x2, y2).into()),
|
||||||
|
(res.rect.min + (x1, y2).into()),
|
||||||
|
(res.rect.min + (x1, y1).into()),
|
||||||
|
],
|
||||||
|
ui.style().visuals.widgets.active.fg_stroke,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue