diff options
| author | Valentin Popov <valentin@popov.link> | 2026-12-01 19:24:41 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-12-01 19:24:41 +0300 |
| commit | fb2b693f1d5cc9dd4989847b066e9411c264774f (patch) | |
| tree | 9f3697535776f836cffd0fa0855e4a1ec99cb96e | |
| parent | 87c082f87844f47dd6b057fc2458cee80002dc55 (diff) | |
| download | fparkan-fb2b693f1d5cc9dd4989847b066e9411c264774f.tar.xz fparkan-fb2b693f1d5cc9dd4989847b066e9411c264774f.zip | |
feat(startup): show mission loading progress in a window
| -rw-r--r-- | README.md | 2 | ||||
| -rw-r--r-- | adapters/fparkan-platform-winit/src/lib.rs | 4 | ||||
| -rw-r--r-- | adapters/fparkan-platform-winit/src/startup_window.rs | 267 | ||||
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 32 | ||||
| -rw-r--r-- | apps/fparkan-game/src/mission_loading.rs | 71 | ||||
| -rw-r--r-- | docs/tomes/04-world.md | 6 |
6 files changed, 381 insertions, 1 deletions
@@ -44,6 +44,8 @@ cargo run --release -p fparkan-game -- ` корневые объекты миссии. `--viewer` открывает графический просмотр карты без исполнения `Init` и тиков мира. `--preview-roots N`, захват камеры и параметры фиксированной позы или фазы материала тоже включают этот режим. +При оконном запуске в Windows загрузчик показывает стадию подготовки миссии +и закрывается после первого кадра игры. Если в одиночной миссии найден один герой с точкой `CameraCenter`, окно открывается с видом из его кабины. Стрелки двигают героя вперёд, назад и вбок. Мышь поворачивает корпус по горизонтали и наклоняет взгляд по diff --git a/adapters/fparkan-platform-winit/src/lib.rs b/adapters/fparkan-platform-winit/src/lib.rs index f5272673..5307ee68 100644 --- a/adapters/fparkan-platform-winit/src/lib.rs +++ b/adapters/fparkan-platform-winit/src/lib.rs @@ -5,6 +5,10 @@ #[allow(unsafe_code)] pub mod text; +#[cfg(windows)] +#[allow(unsafe_code)] +pub mod startup_window; + use fparkan_platform::{ EventSource, MonotonicClock, MonotonicInstant, NativeWindowHandles, PhysicalSize, PlatformError, PlatformEvent, RenderRequest, WindowHandle, WindowPort, diff --git a/adapters/fparkan-platform-winit/src/startup_window.rs b/adapters/fparkan-platform-winit/src/startup_window.rs new file mode 100644 index 00000000..9e486f36 --- /dev/null +++ b/adapters/fparkan-platform-winit/src/startup_window.rs @@ -0,0 +1,267 @@ +//! A responsive Windows startup window that does not depend on the game renderer. + +use std::{cell::Cell, io, mem, ptr, sync::mpsc, thread}; +use windows_sys::Win32::{ + Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM}, + Graphics::Gdi::*, + System::LibraryLoader::GetModuleHandleW, + UI::WindowsAndMessaging::*, +}; + +const SET_STAGE: u32 = WM_APP + 1; +const WIDTH: i32 = 510; +const HEIGHT: i32 = 182; + +/// Keeps a startup window on its own message loop until the game can present. +pub struct StartupWindow { + handle: usize, + thread: Option<thread::JoinHandle<()>>, +} + +impl StartupWindow { + /// Opens the window at the first stage. Stage strings must describe real work. + pub fn open(subtitle: &str, stages: &[&str]) -> io::Result<Self> { + if stages.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "no startup stages", + )); + } + let subtitle = subtitle.encode_utf16().collect(); + let stages = stages + .iter() + .map(|stage| stage.encode_utf16().collect()) + .collect(); + let (ready, receiver) = mpsc::sync_channel(0); + let thread = thread::Builder::new() + .name("startup-window".into()) + .spawn(move || { + show( + State { + stage: Cell::new(0), + subtitle, + stages, + }, + ready, + ); + })?; + match receiver.recv() { + Ok(Ok(handle)) => Ok(Self { + handle, + thread: Some(thread), + }), + result => { + let _ = thread.join(); + Err(result + .ok() + .and_then(Result::err) + .unwrap_or_else(|| io::Error::other("startup window did not initialize"))) + } + } + } + + /// Displays the given zero-based stage. + pub fn set_stage(&self, stage: usize) { + // SAFETY: PostMessage accepts a window handle from another thread. The + // message carries an integer only and is ignored if the window closed. + unsafe { PostMessageW(self.handle as HWND, SET_STAGE, stage, 0) }; + } +} + +impl Drop for StartupWindow { + fn drop(&mut self) { + // SAFETY: WM_CLOSE destroys the window on its owning thread. No buffer + // crosses the thread boundary. + unsafe { PostMessageW(self.handle as HWND, WM_CLOSE, 0, 0) }; + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +struct State { + stage: Cell<usize>, + subtitle: Vec<u16>, + stages: Vec<Vec<u16>>, +} + +fn show(state: State, ready: mpsc::SyncSender<io::Result<usize>>) { + let class_name: Vec<_> = "FParkanStartup\0".encode_utf16().collect(); + let title: Vec<_> = "FParkan — загрузка миссии\0".encode_utf16().collect(); + // SAFETY: The class and window belong to this thread. The creation strings + // stay alive through their calls, and `state` outlives all window messages. + unsafe { + let instance = GetModuleHandleW(ptr::null()); + let class = WNDCLASSW { + lpfnWndProc: Some(window_proc), + hInstance: instance, + hCursor: LoadCursorW(ptr::null_mut(), IDC_ARROW), + lpszClassName: class_name.as_ptr(), + ..mem::zeroed() + }; + if RegisterClassW(&class) == 0 { + let _ = ready.send(Err(io::Error::last_os_error())); + return; + } + let window = CreateWindowExW( + WS_EX_APPWINDOW, + class_name.as_ptr(), + title.as_ptr(), + WS_POPUP | WS_BORDER, + (GetSystemMetrics(SM_CXSCREEN) - WIDTH) / 2, + (GetSystemMetrics(SM_CYSCREEN) - HEIGHT) / 2, + WIDTH, + HEIGHT, + ptr::null_mut(), + ptr::null_mut(), + instance, + (&state as *const State).cast(), + ); + if window.is_null() { + let _ = ready.send(Err(io::Error::last_os_error())); + } else { + ShowWindow(window, SW_SHOW); + UpdateWindow(window); + if ready.send(Ok(window as usize)).is_ok() { + let mut message: MSG = mem::zeroed(); + while GetMessageW(&mut message, ptr::null_mut(), 0, 0) > 0 { + TranslateMessage(&message); + DispatchMessageW(&message); + } + } + if IsWindow(window) != 0 { + DestroyWindow(window); + } + } + UnregisterClassW(class_name.as_ptr(), instance); + } +} + +unsafe extern "system" fn window_proc( + window: HWND, + message: u32, + stage: WPARAM, + data: LPARAM, +) -> LRESULT { + // SAFETY: Win32 supplies CREATESTRUCTW for WM_NCCREATE. The userdata points + // to the thread-local State from `show` until destruction. + unsafe { + match message { + WM_NCCREATE => { + let create = &*(data as *const CREATESTRUCTW); + SetWindowLongPtrW(window, GWLP_USERDATA, create.lpCreateParams as isize); + } + WM_PAINT | SET_STAGE => { + let state = GetWindowLongPtrW(window, GWLP_USERDATA) as *const State; + if let Some(state) = state.as_ref() { + if message == SET_STAGE { + if stage < state.stages.len() && stage > state.stage.get() { + state.stage.set(stage); + InvalidateRect(window, ptr::null(), 0); + } + } else { + draw(window, state); + } + return 0; + } + } + WM_DESTROY => { + PostQuitMessage(0); + return 0; + } + _ => {} + } + DefWindowProcW(window, message, stage, data) + } +} + +fn draw(window: HWND, state: &State) { + // SAFETY: Called on WM_PAINT for this thread's window. Every brush and font + // is deleted after drawing, and BeginPaint/EndPaint delimit the borrowed DC. + unsafe { + let mut paint: PAINTSTRUCT = mem::zeroed(); + let dc = BeginPaint(window, &mut paint); + if !dc.is_null() { + let area = RECT { + left: 0, + top: 0, + right: WIDTH, + bottom: HEIGHT, + }; + let fill = |rect: &RECT, color| { + let brush = CreateSolidBrush(color); + if !brush.is_null() { + FillRect(dc, rect, brush); + DeleteObject(brush); + } + }; + fill(&area, 0x211a13); + SetBkMode(dc, TRANSPARENT as i32); + let font_face: Vec<_> = "Segoe UI\0".encode_utf16().collect(); + let line = |text: &[u16], y, size: i32, weight, color| { + let font = CreateFontW( + -size, + 0, + 0, + 0, + weight, + 0, + 0, + 0, + 1, + 0, + 0, + 5, + 0, + font_face.as_ptr(), + ); + let previous = if font.is_null() { + ptr::null_mut() + } else { + SelectObject(dc, font) + }; + SetTextColor(dc, color); + let mut rect = RECT { + left: 30, + top: y, + right: WIDTH - 30, + bottom: y + size + 12, + }; + DrawTextW( + dc, + text.as_ptr(), + text.len() as i32, + &mut rect, + DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX, + ); + if !font.is_null() { + if !previous.is_null() { + SelectObject(dc, previous); + } + DeleteObject(font); + } + }; + let title: Vec<_> = "Загрузка миссии".encode_utf16().collect(); + line(&title, 26, 27, 600, 0xf1ede5); + line(&state.subtitle, 64, 14, 400, 0xbeb3a6); + line(&state.stages[state.stage.get()], 109, 17, 400, 0xf1ede5); + let count = state.stages.len() as i32; + let span = WIDTH - 60; + for index in 0..count { + let color = match (index as usize).cmp(&state.stage.get()) { + std::cmp::Ordering::Less => 0x8e9684, + std::cmp::Ordering::Equal => 0x59bce3, + std::cmp::Ordering::Greater => 0x493c30, + }; + let rect = RECT { + left: 30 + span * index / count, + top: 145, + right: 30 + span * (index + 1) / count - 4, + bottom: 149, + }; + fill(&rect, color); + } + } + EndPaint(window, &paint); + } +} diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index 787ba07c..e299add3 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -15,6 +15,7 @@ mod damage_visibility; mod debris; mod destruction_effects; mod mission_hints; +mod mission_loading; mod mission_notices; mod mission_pause; mod motion_effects; @@ -32,6 +33,7 @@ mod projectile_sound; mod projectile_trail; mod shield_effects; mod shot_sound; +use mission_loading::{MissionLoading, Stage as LoadingStage}; use projectile_render::{prepare_projectile_draw, ProjectileDraw}; mod live_basements; mod script_coverage; @@ -179,6 +181,17 @@ fn run(args: &[String]) -> Result<String, String> { .collect::<Vec<_>>() .join("\n")); } + let event_loop = args + .sim_report_ms + .is_none() + .then(EventLoop::new) + .transpose() + .map_err(|error| format!("winit event loop: {error}"))?; + let loading = if event_loop.is_some() { + MissionLoading::start(&args.mission) + } else { + MissionLoading::default() + }; if args.mission.bytes().all(|byte| byte.is_ascii_digit()) { let missions = list_missions(vfs.as_ref())?; args.mission = args @@ -301,6 +314,7 @@ fn run(args: &[String]) -> Result<String, String> { .and_then(|c| c.celestial_births.clone()); let hold_schedule_phase = camera.is_some() && atmosphere_seconds.is_some(); let terrain_materials_duration_started = Instant::now(); + loading.stage(LoadingStage::Map); let mut preview = static_preview_mesh_and_materials( mission_assets, terrain, @@ -319,6 +333,7 @@ fn run(args: &[String]) -> Result<String, String> { chassis_animation::connect_treads(&engine, &mut preview); } let terrain_materials_duration = terrain_materials_duration_started.elapsed(); + loading.stage(LoadingStage::Scene); // Atmosphere files are mission-local assets. Resolving them from the // entire install tree would silently attach the first unrelated mission's // sky to the selected map (there are many `sky.ske` files in the campaign @@ -345,6 +360,7 @@ fn run(args: &[String]) -> Result<String, String> { Err(error) => return Err(format!("load mission audio: {error}")), }; run_static_vulkan_mode( + event_loop.expect("windowed launch created an event loop"), preview, environment, audio, @@ -364,6 +380,7 @@ fn run(args: &[String]) -> Result<String, String> { sky: sky_duration, gpu_initialization: Duration::ZERO, }, + loading, ) } @@ -9411,6 +9428,7 @@ fn load_standalone_phase_set( } fn run_static_vulkan_mode( + event_loop: EventLoop<()>, preview: StaticPreviewScene, environment: Option<DynamicEnvironment>, audio: Option<audio::GameAudio>, @@ -9425,8 +9443,8 @@ fn run_static_vulkan_mode( enable_validation: bool, control_clock_target_ms: Option<u32>, startup_timings: StartupTimings, + loading: MissionLoading, ) -> Result<String, String> { - let event_loop = EventLoop::new().map_err(|err| format!("winit event loop: {err}"))?; event_loop.set_control_flow(ControlFlow::Poll); let mut preview = preview; let mut environment = environment; @@ -9598,6 +9616,7 @@ fn run_static_vulkan_mode( control_clock_target_ms, startup_timings, ); + app.loading = loading; app.mission_engine = mission_engine; if let Some(engine) = app.mission_engine.as_mut() { fparkan_runtime::collect_unit_destruction_effects(engine); @@ -9857,6 +9876,7 @@ struct StaticVulkanApp { readback_sequence_out: Option<PathBuf>, enable_validation: bool, startup_timings: StartupTimings, + loading: MissionLoading, window_id: Option<WindowId>, window: Option<Window>, renderer: Option<VulkanSmokeRenderer>, @@ -10026,6 +10046,7 @@ impl StaticVulkanApp { readback_sequence_out, enable_validation, startup_timings, + loading: MissionLoading::default(), window_id: None, window: None, renderer: None, @@ -12168,6 +12189,8 @@ impl ApplicationHandler for StaticVulkanApp { if self.window.is_some() { return; } + self.loading.stage(LoadingStage::Renderer); + let startup_window_visible = self.loading.window_visible(); let plan = match WinitWindowPlan::smoke().validate() { Ok(plan) => plan, Err(err) => { @@ -12182,6 +12205,7 @@ impl ApplicationHandler for StaticVulkanApp { .unwrap_or((plan.width, plan.height)); let attributes = Window::default_attributes() .with_title("FParkan mission") + .with_visible(!startup_window_visible) .with_inner_size(WinitPhysicalSize::new(width, height)) // The captured clip matrix is exact for the recorded viewport // aspect. Keep that drawable fixed; compare it with the same @@ -12282,6 +12306,9 @@ impl ApplicationHandler for StaticVulkanApp { renderer.set_readback_enabled( self.readback_out.is_some() || self.readback_sequence_out.is_some(), ); + if startup_window_visible { + window.set_visible(true); + } self.window_id = Some(window.id()); self.window = Some(window); if self.cockpit.is_some() && self.demo_camera.is_none() && self.window_focused { @@ -12553,6 +12580,9 @@ impl ApplicationHandler for StaticVulkanApp { match outcome { Ok(VulkanSmokeFrameOutcome::Presented) => { let frame_index = self.record_presented_scene_frame(); + if frame_index == 0 { + self.loading.finish(); + } if let Some(directory) = self.readback_sequence_out.as_deref() { let artifact = match self .renderer diff --git a/apps/fparkan-game/src/mission_loading.rs b/apps/fparkan-game/src/mission_loading.rs new file mode 100644 index 00000000..37c056dd --- /dev/null +++ b/apps/fparkan-game/src/mission_loading.rs @@ -0,0 +1,71 @@ +//! Lifecycle of the loader for a windowed mission launch. + +#[derive(Clone, Copy)] +pub(super) enum Stage { + Map = 1, + Scene, + Renderer, +} + +#[derive(Default)] +pub(super) struct MissionLoading { + #[cfg(windows)] + window: Option<fparkan_platform_winit::startup_window::StartupWindow>, + #[cfg(not(windows))] + active: bool, +} + +const STAGES: &[&str] = &[ + "Чтение ресурсов миссии", + "Подготовка карты и материалов", + "Подготовка сцены и звука", + "Запуск Vulkan", +]; + +impl MissionLoading { + pub(super) fn start(mission: &str) -> Self { + #[cfg(windows)] + { + use fparkan_platform_winit::startup_window::StartupWindow; + let title = mission.parse::<usize>().map_or_else( + |_| mission.to_owned(), + |number| format!("FParkan · Миссия {number}"), + ); + let window = StartupWindow::open(&title, STAGES) + .map_err(|error| eprintln!("startup window: {error}")) + .ok(); + Self { window } + } + #[cfg(not(windows))] + { + eprintln!("{mission} — {}", STAGES[0]); + Self { active: true } + } + } + + pub(super) fn stage(&self, stage: Stage) { + #[cfg(windows)] + if let Some(window) = &self.window { + window.set_stage(stage as usize); + } + #[cfg(not(windows))] + if self.active { + eprintln!("{}", STAGES[stage as usize]); + } + } + + pub(super) fn window_visible(&self) -> bool { + #[cfg(windows)] + { + self.window.is_some() + } + #[cfg(not(windows))] + { + false + } + } + + pub(super) fn finish(&mut self) { + *self = Self::default(); + } +} diff --git a/docs/tomes/04-world.md b/docs/tomes/04-world.md index 1123bc7b..f80d3bb7 100644 --- a/docs/tomes/04-world.md +++ b/docs/tomes/04-world.md @@ -312,6 +312,12 @@ TMA object ### Фазы loader-а +В Windows оконный запуск показывает текущую стадию подготовки. Отдельная +очередь сообщений держит загрузчик отзывчивым, пока игра читает ресурсы, +строит сцену и запускает Vulkan. Стадия меняется при переходе к следующему +виду работы. Первый показанный кадр закрывает загрузчик. Консольные прогоны +с `--sim-report` используют ту же загрузку ресурсов в консоли. + 1. **Mission context.** Выбрать каталог миссии, прочитать конфигурацию и определить карту. 2. **World foundation.** Загрузить `Land.msh`, `Land.map`, `BuildDat.lst` и |
