//! Settings shared with the installed game's `Iron_3D.ini` profile. use fparkan_path::{normalize_relative, PathPolicy}; use fparkan_vfs::{Vfs, VfsError}; use std::sync::Arc; /// The original game's profile. A missing INI supplies no overrides. #[derive(Default)] pub struct GameSettings(Arc<[u8]>); impl GameSettings { /// Reads the installed profile through the same VFS as the game data. pub fn load(vfs: &dyn Vfs) -> Result { let path = normalize_relative(b"Iron_3D.ini", PathPolicy::StrictLegacy) .map_err(|_| VfsError::Path)?; match vfs.read(&path) { Ok(bytes) => Ok(Self(bytes)), Err(VfsError::NotFound(_)) => Ok(Self::default()), Err(error) => Err(error), } } /// Reads an integer from the case-insensitive `[CS]` section. pub fn integer(&self, key: &str) -> Option { let text = String::from_utf8_lossy(&self.0); let mut controls = false; for line in text.lines().map(str::trim) { if let Some(section) = line.strip_prefix('[').and_then(|line| line.split_once(']')) { controls = section.0.eq_ignore_ascii_case("CS"); continue; } if controls { if let Some((name, value)) = line.split_once('=') { if name.trim().eq_ignore_ascii_case(key) { return value.trim().parse().ok(); } } } } None } /// Returns the requested display when both client dimensions are present. pub fn display(&self) -> Option { let positive = |key| u32::try_from(self.integer(key)?).ok().filter(|&n| n != 0); Some(DisplaySettings { extent: [positive("DISPLAY_WIDTH")?, positive("DISPLAY_HEIGHT")?], bit_depth: positive("BITDEPTH").unwrap_or(32), windowed: self.integer("WINDOW_MODE").unwrap_or(1) != 0, }) } /// An explicit zero disables the separate water reflection pass. pub fn water_reflections(&self) -> bool { self.integer("REFLECTIONS").unwrap_or(1) != 0 } /// The lowest native render quality omits the cloud dome pass. pub fn sky_clouds(&self) -> bool { self.integer("RENDER_QUALITY") != Some(0) } /// The lowest native render quality omits the two terrain microtexture stages. pub fn terrain_microtexturing(&self) -> bool { self.integer("RENDER_QUALITY") != Some(0) } /// The lowest native render quality omits software point lighting on surfaces. pub fn emulate_point_lights(&self) -> bool { self.integer("RENDER_QUALITY") != Some(0) } /// Reads separate wave and CD volume settings from the original profile. pub fn audio(&self) -> AudioSettings { let gain = |key| { self.integer(key) .map(|value| value.clamp(0, 100) as f32 * 0.01) }; AudioSettings { effects_gain: gain("SFX_VOLUME"), cd_gain: gain("CD_VOLUME"), play_cd: self.integer("PLAY_CD_MUSIC").unwrap_or_default() != 0, } } /// Replaces selected `[CS]` integers, preserving the other profile bytes. pub fn with_cs_integers(&self, updates: &[(&str, i32)]) -> Vec { let mut bytes = self.0.to_vec(); let newline = if bytes.windows(2).any(|pair| pair == b"\r\n") { "\r\n" } else { "\n" }; for &(key, value) in updates { write_cs_integer(&mut bytes, key, value, newline); } bytes } } fn write_cs_integer(bytes: &mut Vec, key: &str, value: i32, newline: &str) { let mut offset = 0; let mut in_cs = false; let mut insert_at = None; for line in bytes.split_inclusive(|&byte| byte == b'\n') { let trimmed = line.trim_ascii(); if let Some(section) = trimmed.strip_prefix(b"[") { in_cs = section .iter() .position(|&byte| byte == b']') .is_some_and(|end| section[..end].eq_ignore_ascii_case(b"CS")); } else if in_cs { if let Some(equals) = line.iter().position(|&byte| byte == b'=') { if line[..equals] .trim_ascii() .eq_ignore_ascii_case(key.as_bytes()) { let field = &line[equals + 1..]; let content = field.trim_ascii_end(); let start = offset + equals + 1 + content.len() - content.trim_ascii_start().len(); let end = offset + equals + 1 + content.len(); bytes.splice(start..end, value.to_string().bytes()); return; } } } offset += line.len(); if in_cs { insert_at = Some(offset); } } let at = insert_at.unwrap_or(bytes.len()); let separator = if at > 0 && bytes[at - 1] != b'\n' { newline } else { "" }; let entry = match insert_at { Some(_) => format!("{separator}{key}={value}{newline}"), None => format!("{separator}[CS]{newline}{key}={value}{newline}"), }; bytes.splice(at..at, entry.bytes()); } /// The size, color depth and display mode requested by the legacy profile. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct DisplaySettings { pub extent: [u32; 2], pub bit_depth: u32, pub windowed: bool, } impl DisplaySettings { /// The original mode selector gives each pixel of difference a weight of 100. pub fn mode_distance(self, extent: [u32; 2], bit_depth: u32) -> u64 { let [width, height] = self.extent; (u64::from(width.abs_diff(extent[0])) + u64::from(height.abs_diff(extent[1]))) * 100 + u64::from(self.bit_depth.abs_diff(bit_depth)) } } /// Initial gains by sound source. Omitted controls leave the mixer defaults. #[derive(Clone, Copy, Debug, PartialEq)] pub struct AudioSettings { pub effects_gain: Option, pub cd_gain: Option, pub play_cd: bool, } #[cfg(test)] #[test] fn reads_the_original_display_profile_and_scores_video_modes() { let settings = GameSettings(Arc::from( &b"[OTHER]\nDISPLAY_WIDTH=1\n[cs]\n display_width=800\n DISPLAY_HEIGHT = 600\nBITDEPTH=16\nWINDOW_MODE=0"[..], )); let display = settings.display().unwrap(); assert_eq!(display.extent, [800, 600]); assert!(!display.windowed); assert_eq!(display.mode_distance([800, 600], 32), 16); assert_eq!(display.mode_distance([799, 601], 16), 200); assert!(GameSettings::default().display().is_none()); } #[cfg(test)] #[test] fn reads_water_reflections_independently_of_embm() { let settings = GameSettings(Arc::from(&b"[CS]\nREFLECTIONS=0\nEMBM=1"[..])); assert!(!settings.water_reflections()); let settings = GameSettings(Arc::from(&b"[CS]\nREFLECTIONS=1\nEMBM=0"[..])); assert!(settings.water_reflections()); assert!(GameSettings::default().water_reflections()); } #[cfg(test)] #[test] fn only_low_render_quality_omits_clouds_microtextures_and_software_point_lights() { for (profile, expected) in [ (&b"[CS]\nRENDER_QUALITY=0"[..], false), (&b"[CS]\nRENDER_QUALITY=1"[..], true), (&b"[CS]\nRENDER_QUALITY=2"[..], true), (&b"[CS]"[..], true), ] { let settings = GameSettings(Arc::from(profile)); assert_eq!(settings.sky_clouds(), expected); assert_eq!(settings.terrain_microtexturing(), expected); assert_eq!(settings.emulate_point_lights(), expected); } } #[cfg(test)] #[test] fn reads_separate_effects_and_cd_controls() { let settings = GameSettings(Arc::from( &b"[CS]\nSFX_VOLUME=20\nCD_VOLUME=120\nPLAY_CD_MUSIC=0\n[OTHER]\nSFX_VOLUME=60"[..], )); let audio = settings.audio(); assert!((audio.effects_gain.unwrap() - 0.2).abs() < f32::EPSILON); assert_eq!(audio.cd_gain, Some(1.0)); assert!(!audio.play_cd); assert_eq!(GameSettings::default().audio().effects_gain, None); let music = GameSettings(Arc::from(&b"[CS]\nCD_VOLUME=0\nPLAY_CD_MUSIC=1"[..])); assert_eq!(music.audio().cd_gain, Some(0.0)); assert!(music.audio().play_cd); } #[cfg(test)] #[test] fn updates_only_the_chosen_cs_entries() { let settings = GameSettings(Arc::from( &b";\xef\xf0\xe8\xec\xe5\xf0\r\n[cs]\r\n sfx_volume = 20 \r\n[NETWORK]\r\nSFX_VOLUME=5"[..], )); assert_eq!( settings.with_cs_integers(&[("SFX_VOLUME", 48), ("PLAY_CD_MUSIC", 1)]), b";\xef\xf0\xe8\xec\xe5\xf0\r\n[cs]\r\n sfx_volume = 48 \r\nPLAY_CD_MUSIC=1\r\n[NETWORK]\r\nSFX_VOLUME=5" ); assert_eq!( GameSettings::default().with_cs_integers(&[("CD_VOLUME", 33)]), b"[CS]\nCD_VOLUME=33\n" ); }