mod finitefloat; pub use finitefloat::{FiniteF32, FiniteF64}; use crate::input::Player; use bincode::{Decode, Encode}; use jgenesis_proc_macros::{EnumAll, EnumDisplay, EnumFromStr}; use std::borrow::Cow; use std::error::Error; use std::fmt::{Debug, Display, Formatter}; use std::hash::Hash; use std::num::NonZeroU8; #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable, Encode, Decode)] pub struct Color { pub r: u8, pub g: u8, pub b: u8, pub a: u8, } impl Color { pub const BLACK: Self = Self::rgb(0, 0, 0); pub const TRANSPARENT: Self = Self::rgba(0, 0, 0, 0); #[must_use] #[inline] pub const fn rgb(r: u8, g: u8, b: u8) -> Self { Self { r, g, b, a: 255 } } #[must_use] #[inline] pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self { Self { r, g, b, a } } } impl Default for Color { #[inline] fn default() -> Self { Self::BLACK } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct FrameSize { pub width: u32, pub height: u32, } impl FrameSize { #[allow(clippy::len_without_is_empty)] #[must_use] pub fn len(self) -> u32 { self.width * self.height } } #[derive(Debug, Clone, Copy)] pub struct DisplayArea { pub width: u32, pub height: u32, pub x: u32, pub y: u32, pub pixel_density: f32, } #[derive(Debug, Clone, Copy)] pub enum Rotation { None, Clockwise, OneEighty, Counterclockwise, } #[derive(Debug, Clone, Copy)] pub struct DisplayInfo { pub frame_size: FrameSize, pub display_area: DisplayArea, pub pixel_aspect_ratio: Option, pub target_fps: f64, pub rotation: Rotation, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Encode, Decode)] pub enum ColorCorrection { #[default] None, GbcLcd { screen_gamma: FiniteF32, }, GbaLcd { screen_gamma: FiniteF32, }, } impl Display for ColorCorrection { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::None => write!(f, "None"), &Self::GbcLcd { screen_gamma } => { write!(f, "Game Boy Color LCD (gamma {:.1})", f32::from(screen_gamma)) } &Self::GbaLcd { screen_gamma } => { write!(f, "Game Boy Advance LCD (gamma {:.1})", f32::from(screen_gamma)) } } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum SamplesPerColorCycle { Twelve, // ~42.95 MHz sample rate (NES, SNES) Fifteen, // ~53.69 MHz sample rate (SMS, Genesis) } impl From for u32 { fn from(value: SamplesPerColorCycle) -> Self { match value { SamplesPerColorCycle::Twelve => 12, SamplesPerColorCycle::Fifteen => 15, } } } impl From for u64 { fn from(value: SamplesPerColorCycle) -> Self { u32::from(value).into() } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct CompositeParams { // How many times to repeat each frame buffer pixel pub upscale_factor: u32, pub samples_per_color_cycle: SamplesPerColorCycle, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct NtscPerFrameParams { pub frame_phase_offset: u64, pub per_line_phase_offset: u64, } /// Rendering options that are not required to be explicitly specified, unlike frame size #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct RenderFrameOptions { pub pixel_aspect_ratio: Option, pub color_correction: ColorCorrection, pub frame_blending: bool, pub composite_params: Option, pub emulate_nes_ntsc_output: bool, pub ntsc_per_frame_params: Option, } /// [`RenderFrameOptions`] excluding per-frame parameters #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] pub struct RenderFrameOptionsHashable { pub pixel_aspect_ratio: Option, pub color_correction: ColorCorrection, pub frame_blending: bool, pub composite_params: Option, pub emulate_nes_ntsc_output: bool, } impl RenderFrameOptions { #[must_use] pub fn pixel_aspect_ratio(pixel_aspect_ratio: Option) -> Self { Self { pixel_aspect_ratio, ..Self::default() } } #[must_use] pub fn to_hashable(self) -> RenderFrameOptionsHashable { RenderFrameOptionsHashable { pixel_aspect_ratio: self.pixel_aspect_ratio, color_correction: self.color_correction, frame_blending: self.frame_blending, composite_params: self.composite_params, emulate_nes_ntsc_output: self.emulate_nes_ntsc_output, } } } pub trait Renderer { type Err: Debug + Display + Send + Sync + 'static; /// Render a frame. /// /// The frame buffer may be larger than the specified frame size, but the len must be at least /// (`frame_width` * `frame_height`). Colors past the first (`frame_width` * `frame_height`) /// will be ignored. /// /// `target_fps` must be a finite positive value. /// /// If pixel aspect ratio is None, the frame will be stretched to fill the window. If it is /// Some, the frame will be rendered in the largest possible area that maintains the specified /// pixel aspect ratio. /// /// # Errors /// /// This method will return an error if it is unable to render the frame. fn render_frame( &mut self, frame_buffer: &[Color], frame_size: FrameSize, target_fps: f64, options: RenderFrameOptions, ) -> Result<(), Self::Err>; } pub trait AudioOutput { type Err: Debug + Display + Send + Sync + 'static; /// Push a stereo audio sample. /// /// # Errors /// /// This method will return an error if it is unable to push the sample to the audio device. fn push_sample(&mut self, sample_l: f64, sample_r: f64) -> Result<(), Self::Err>; } pub trait SaveWriter { type Err: Debug + Display + Send + Sync + 'static; /// Read an array of bytes using the given extension. /// /// # Errors /// /// Will propagate any errors encountered while reading the file. fn load_bytes(&mut self, extension: &str) -> Result, Self::Err>; /// Write a slice of bytes using the given extension. /// /// # Errors /// /// Will propagate any errors encountered while writing the file. fn persist_bytes(&mut self, extension: &str, bytes: &[u8]) -> Result<(), Self::Err>; /// Load a serialized value using the given extension. /// /// For loading raw bytes, use `load_bytes` instead which does not assume that the length is serialized. /// /// # Errors /// /// Will propagate any errors encountered while reading the file or deserializing the data. fn load_serialized>(&mut self, extension: &str) -> Result; /// Write a serialized value using the given extension. /// /// For writing raw bytes, use `persist_bytes` instead which does not serialize the slice length. /// /// # Errors /// /// Will propagate any errors encountered while writing the file or serializing the data. fn persist_serialized(&mut self, extension: &str, data: E) -> Result<(), Self::Err>; } pub trait PartialClone { /// Create a partial clone of `self`, which clones all emulation state but may not clone /// read-only fields such as ROMs and frame buffers. #[must_use] fn partial_clone(&self) -> Self; } impl PartialClone for Option { fn partial_clone(&self) -> Self { self.as_ref().map(T::partial_clone) } } pub use jgenesis_proc_macros::PartialClone; #[derive( Debug, Clone, Copy, PartialEq, Eq, Default, Encode, Decode, EnumDisplay, EnumFromStr, EnumAll, )] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "clap", derive(jgenesis_proc_macros::CustomValueEnum))] pub enum TimingMode { #[default] Ntsc, Pal, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TickEffect { None, FrameRendered, } pub type TickResult = Result; #[derive(Debug, Clone)] pub struct Modal { pub id: Option>, pub text: String, } pub trait MappableInputs