aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-03 12:27:37 +0300
committerValentin Popov <valentin@popov.link>2026-12-03 12:27:37 +0300
commite59c55289c494a5bd0126b6c40bc4e07a52b8a28 (patch)
tree9b968144498a0339b98f1d583f23bb574b8e3e03
parente9ba4a3e0a039715fdf1c169edd7f56faa8570b1 (diff)
downloadfparkan-e59c55289c494a5bd0126b6c40bc4e07a52b8a28.tar.xz
fparkan-e59c55289c494a5bd0126b6c40bc4e07a52b8a28.zip
feat(ui): use the installed display mode at game startup
-rw-r--r--README.md2
-rw-r--r--apps/fparkan-game/src/mission_loading.rs37
-rw-r--r--crates/fparkan-assets/src/game_settings.rs83
-rw-r--r--crates/fparkan-assets/src/lib.rs1
-rw-r--r--crates/fparkan-runtime/src/hero_look.rs29
-rw-r--r--docs/appendices/ui-shell.md16
6 files changed, 141 insertions, 27 deletions
diff --git a/README.md b/README.md
index a570f936..a9cd3853 100644
--- a/README.md
+++ b/README.md
@@ -37,6 +37,8 @@ cargo run --release -p fparkan-game -- `
или щелчком левой кнопки мыши.
Оно показывает кампании, одиночные миссии и демо из установленной игры.
При запуске из каталога игры `--root` можно опустить.
+Размер окна и полноэкранный режим читаются из `[CS]` в `Iron_3D.ini`
+установленной игры. Параметры захваченной камеры задают свой размер кадра.
`--list-missions` выводит пути к миссиям и их номера. Для `--mission`
можно указать номер из этого списка. `--sim-report <секунды>`
выполняет миссию без окна с воспроизводимым шагом 60 Гц и выводит число
diff --git a/apps/fparkan-game/src/mission_loading.rs b/apps/fparkan-game/src/mission_loading.rs
index 823c6b35..bff5790b 100644
--- a/apps/fparkan-game/src/mission_loading.rs
+++ b/apps/fparkan-game/src/mission_loading.rs
@@ -5,7 +5,9 @@ use super::{
mission_startup::{self, PreparedMission},
Args, Engine, LegacyCameraCapture, StaticVulkanApp,
};
+use fparkan_assets::game_settings::{DisplaySettings, GameSettings};
use fparkan_platform_winit::{new_game_event_loop, WinitWindowPlan};
+use fparkan_vfs::DirectoryVfs;
use std::{
panic::{catch_unwind, AssertUnwindSafe},
path::Path,
@@ -17,7 +19,7 @@ use winit::{
dpi::PhysicalSize,
event::{DeviceEvent, DeviceId, WindowEvent},
event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy},
- window::{Window, WindowId},
+ window::{Fullscreen, Window, WindowId},
};
#[cfg(windows)]
@@ -25,7 +27,6 @@ use {
super::startup_intro::StartupIntro,
fparkan_assets::mission_loader::MissionLoader,
fparkan_platform_winit::{startup_window, text::StringResources},
- fparkan_vfs::DirectoryVfs,
std::time::{Duration, Instant},
winit::event::{ElementState, MouseButton},
};
@@ -57,7 +58,17 @@ pub(super) fn run(
.as_ref()
.map(LegacyCameraCapture::captured_viewport)
.transpose()?;
- let extent = capture.map_or([plan.width, plan.height], |viewport| viewport.extent);
+ let display = if capture.is_none() && !args.viewer {
+ GameSettings::load(&DirectoryVfs::new(&args.root))
+ .map_err(|error| format!("read Iron_3D.ini: {error}"))?
+ .display()
+ } else {
+ None
+ };
+ let extent = capture.map_or_else(
+ || display.map_or([plan.width, plan.height], |display| display.extent),
+ |viewport| viewport.extent,
+ );
let event_loop = new_game_event_loop().map_err(|error| format!("winit event loop: {error}"))?;
event_loop.set_control_flow(ControlFlow::Wait);
let mut startup = WindowedMission {
@@ -65,6 +76,7 @@ pub(super) fn run(
intro: menu.as_ref().and_then(|_| StartupIntro::open(&args.root)),
args,
extent,
+ exclusive_display: display.filter(|display| cfg!(windows) && !display.windowed),
resizable: capture.is_none(),
menu,
loading: MissionLoading::default(),
@@ -110,6 +122,7 @@ struct LoadRequest {
struct WindowedMission {
args: Args,
extent: [u32; 2],
+ exclusive_display: Option<DisplaySettings>,
resizable: bool,
menu: Option<LaunchMenu>,
// The DirectShow child and its graph must release before the window.
@@ -188,9 +201,27 @@ impl ApplicationHandler for WindowedMission {
return;
}
let [width, height] = self.extent;
+ let fullscreen = match self.exclusive_display {
+ Some(display) => {
+ let mode = event_loop.primary_monitor().and_then(|monitor| {
+ monitor.video_modes().min_by_key(|mode| {
+ let size = mode.size();
+ display.mode_distance([size.width, size.height], mode.bit_depth().into())
+ })
+ });
+ let Some(mode) = mode else {
+ self.error = Some("Iron_3D.ini requests fullscreen with no video modes".into());
+ event_loop.exit();
+ return;
+ };
+ Some(Fullscreen::Exclusive(mode))
+ }
+ None => None,
+ };
let attributes = Window::default_attributes()
.with_title("FParkan")
.with_inner_size(PhysicalSize::new(width, height))
+ .with_fullscreen(fullscreen)
// Preserve the recorded crop when playing from a captured camera.
.with_resizable(self.resizable);
match event_loop.create_window(attributes) {
diff --git a/crates/fparkan-assets/src/game_settings.rs b/crates/fparkan-assets/src/game_settings.rs
new file mode 100644
index 00000000..a57d3f62
--- /dev/null
+++ b/crates/fparkan-assets/src/game_settings.rs
@@ -0,0 +1,83 @@
+//! 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<Self, VfsError> {
+ 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<i32> {
+ 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<DisplaySettings> {
+ 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,
+ })
+ }
+}
+
+/// 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))
+ }
+}
+
+#[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());
+}
diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs
index a0b207d9..df9bbce5 100644
--- a/crates/fparkan-assets/src/lib.rs
+++ b/crates/fparkan-assets/src/lib.rs
@@ -42,6 +42,7 @@ mod effect_material_phases;
mod explosion_profile;
pub mod factory_projects;
pub mod game_font;
+pub mod game_settings;
pub mod help_resources;
pub mod help_screen;
pub mod mission_catalog;
diff --git a/crates/fparkan-runtime/src/hero_look.rs b/crates/fparkan-runtime/src/hero_look.rs
index 2e923d20..a31512d1 100644
--- a/crates/fparkan-runtime/src/hero_look.rs
+++ b/crates/fparkan-runtime/src/hero_look.rs
@@ -1,3 +1,4 @@
+use fparkan_assets::game_settings::GameSettings;
use fparkan_path::{normalize_relative, PathPolicy};
use fparkan_vfs::Vfs;
use std::f32::consts::{PI, TAU};
@@ -29,9 +30,8 @@ impl HeroLook {
vfs.read(&path).ok()
};
let table_bytes = read(table_name);
- let settings_bytes = read(b"Iron_3D.ini");
let table = String::from_utf8_lossy(table_bytes.as_deref().unwrap_or_default());
- let settings = String::from_utf8_lossy(settings_bytes.as_deref().unwrap_or_default());
+ let settings = GameSettings::load(vfs).unwrap_or_default();
Self {
yaw_turns: mouse_binding(
&table,
@@ -71,8 +71,9 @@ impl HeroLook {
)
.unwrap_or(0.15),
],
- reverse_y: control_setting(&settings, "MOUSE_REV_Y").unwrap_or(0) != 0,
- sensitivity: control_setting(&settings, "MOUSE_SENS")
+ reverse_y: settings.integer("MOUSE_REV_Y").unwrap_or(0) != 0,
+ sensitivity: settings
+ .integer("MOUSE_SENS")
.map_or(1.0, |value| value as f32 * 0.01),
filtered: [0.0; 2],
phase: 0.5,
@@ -198,23 +199,6 @@ fn mouse_binding(
})
}
-fn control_setting(settings: &str, key: &str) -> Option<i32> {
- let mut controls = false;
- for line in settings.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");
- }
- if controls {
- if let Some((name, value)) = line.split_once('=') {
- if name.trim().eq_ignore_ascii_case(key) {
- return value.trim().parse().ok();
- }
- }
- }
- }
- None
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -262,9 +246,6 @@ MOUSE SCAN_NULL SCAN_MOUSE_Y 1 CICLS_TURRET MCMD_ANGLE_Y 0.30 1 MAN_NOTWRAP 0.0
),
Some(0.30)
);
- let settings = "[VIDEO]\nMOUSE_SENS=100\n[cs]\n mouse_sens = 50\n mouse_rev_y=1";
- assert_eq!(control_setting(settings, "MOUSE_SENS"), Some(50));
- assert_eq!(control_setting(settings, "MOUSE_REV_Y"), Some(1));
}
#[test]
diff --git a/docs/appendices/ui-shell.md b/docs/appendices/ui-shell.md
index 1cbab73e..e1b72ac1 100644
--- a/docs/appendices/ui-shell.md
+++ b/docs/appendices/ui-shell.md
@@ -19,6 +19,22 @@ Win32 messages
требует API capture. Разделение world и UI pass доказано, но не следует
выдавать его за восстановленный layout классов виджетов.
+## Размер экрана
+
+Оболочка читает `DISPLAY_WIDTH`, `DISPLAY_HEIGHT` и `WINDOW_MODE` в секции
+`[CS]` файла `Iron_3D.ini`. В GOG-сборке это делает `iron3d.dll`, RVA
+`0xa07d0`. Размер задаёт клиентскую область, а ненулевой `WINDOW_MODE`
+добавляет оконную рамку. FParkan задаёт этот размер одному окну для заставки,
+меню, загрузчика и миссии.
+
+При `WINDOW_MODE=0` `services.dll` передаёт ширину, высоту и `BITDEPTH`
+из RVA `0x1340` в выбор режима в RVA `0x2120`. Расстояние до режима равно
+`100 * (|Δwidth| + |Δheight|) + |Δbit_depth|`. Если запрошены 800×600 и 16 бит,
+режим 800×600 и 32 бита получает 16, а 799×601 и 16 бит получает 200.
+FParkan использует это правило для режимов, доступных на основном мониторе.
+Глубина цвета входит в выбор видеорежима. Формат кадра Vulkan определяется
+поверхностью. Хеши GOG-модулей приведены в [паспорте сборки](../reference/original-binaries.md).
+
## Ресурсы и идентичность
В demo найдены `ui/shell_ctrls.cfg`, `ui/menu_resources.cfg`, `ui/cursor.cfg`,