diff options
| author | Valentin Popov <valentin@popov.link> | 2026-12-02 01:04:17 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-12-02 01:04:17 +0300 |
| commit | eab46d9be33596b6c689a7a34b90837a89400a89 (patch) | |
| tree | 2afc2ca857882830247349c5db1708137d9772f4 | |
| parent | 6c9fe794cda795b101825091aee4644efd9422f8 (diff) | |
| download | fparkan-eab46d9be33596b6c689a7a34b90837a89400a89.tar.xz fparkan-eab46d9be33596b6c689a7a34b90837a89400a89.zip | |
feat(ui): show the original mission loading screen
| -rw-r--r-- | adapters/fparkan-platform-winit/src/startup_window.rs | 224 | ||||
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 47 | ||||
| -rw-r--r-- | apps/fparkan-game/src/mission_loading.rs | 115 | ||||
| -rw-r--r-- | crates/fparkan-assets/src/game_font.rs | 23 | ||||
| -rw-r--r-- | crates/fparkan-assets/src/lib.rs | 1 | ||||
| -rw-r--r-- | crates/fparkan-assets/src/mission_loader.rs | 174 | ||||
| -rw-r--r-- | crates/fparkan-font/src/bitmap.rs | 12 | ||||
| -rw-r--r-- | docs/tomes/03-resources.md | 23 |
8 files changed, 421 insertions, 198 deletions
diff --git a/adapters/fparkan-platform-winit/src/startup_window.rs b/adapters/fparkan-platform-winit/src/startup_window.rs index 9e486f36..87feb984 100644 --- a/adapters/fparkan-platform-winit/src/startup_window.rs +++ b/adapters/fparkan-platform-winit/src/startup_window.rs @@ -1,6 +1,10 @@ //! A responsive Windows startup window that does not depend on the game renderer. -use std::{cell::Cell, io, mem, ptr, sync::mpsc, thread}; +use std::{ + io, mem, ptr, + sync::{mpsc, Arc, Mutex}, + thread, +}; use windows_sys::Win32::{ Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM}, Graphics::Gdi::*, @@ -8,47 +12,44 @@ use windows_sys::Win32::{ UI::WindowsAndMessaging::*, }; -const SET_STAGE: u32 = WM_APP + 1; -const WIDTH: i32 = 510; -const HEIGHT: i32 = 182; +const SET_FRAME: u32 = WM_APP + 1; -/// Keeps a startup window on its own message loop until the game can present. +/// Keeps a startup bitmap visible until the game renderer can present. pub struct StartupWindow { handle: usize, thread: Option<thread::JoinHandle<()>>, + state: Arc<State>, } 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() { + /// Opens a window with the supplied top-down 0x00RRGGBB bitmap. + pub fn open(extent: [u32; 2], pixels: Vec<u32>) -> io::Result<Self> { + let [width, height] = extent; + if width == 0 + || height == 0 + || width > i32::MAX as u32 + || height > i32::MAX as u32 + || (width as usize).checked_mul(height as usize) != Some(pixels.len()) + { return Err(io::Error::new( io::ErrorKind::InvalidInput, - "no startup stages", + "invalid startup bitmap dimensions", )); } - let subtitle = subtitle.encode_utf16().collect(); - let stages = stages - .iter() - .map(|stage| stage.encode_utf16().collect()) - .collect(); + let state = Arc::new(State { + extent: [width as i32, height as i32], + pixels: Mutex::new(pixels), + }); + let window_state = Arc::clone(&state); 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, - ); - })?; + .spawn(move || show(&window_state, ready))?; match receiver.recv() { Ok(Ok(handle)) => Ok(Self { handle, thread: Some(thread), + state, }), result => { let _ = thread.join(); @@ -60,18 +61,22 @@ impl StartupWindow { } } - /// 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) }; + /// Replaces the current bitmap and schedules a repaint. + pub fn set_frame(&self, pixels: Vec<u32>) { + if let Ok(mut frame) = self.state.pixels.lock() { + if frame.len() != pixels.len() { + return; + } + *frame = pixels; + } + // SAFETY: The message carries no references and is ignored if the window closed. + unsafe { PostMessageW(self.handle as HWND, SET_FRAME, 0, 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. + // SAFETY: WM_CLOSE destroys the window on its owning thread. unsafe { PostMessageW(self.handle as HWND, WM_CLOSE, 0, 0) }; if let Some(thread) = self.thread.take() { let _ = thread.join(); @@ -80,16 +85,15 @@ impl Drop for StartupWindow { } struct State { - stage: Cell<usize>, - subtitle: Vec<u16>, - stages: Vec<Vec<u16>>, + extent: [i32; 2], + pixels: Mutex<Vec<u32>>, } -fn show(state: State, ready: mpsc::SyncSender<io::Result<usize>>) { +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(); + let title: Vec<_> = "FParkan mission\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. + // stay alive through their calls, and state outlives all window messages. unsafe { let instance = GetModuleHandleW(ptr::null()); let class = WNDCLASSW { @@ -103,19 +107,30 @@ fn show(state: State, ready: mpsc::SyncSender<io::Result<usize>>) { let _ = ready.send(Err(io::Error::last_os_error())); return; } + let style = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; + let [width, height] = state.extent; + let mut outer = RECT { + left: 0, + top: 0, + right: width, + bottom: height, + }; + AdjustWindowRectEx(&mut outer, style, 0, WS_EX_APPWINDOW); + let width = outer.right - outer.left; + let height = outer.bottom - outer.top; 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, + style, + (GetSystemMetrics(SM_CXSCREEN) - width) / 2, + (GetSystemMetrics(SM_CYSCREEN) - height) / 2, + width, + height, ptr::null_mut(), ptr::null_mut(), instance, - (&state as *const State).cast(), + (state as *const State).cast(), ); if window.is_null() { let _ = ready.send(Err(io::Error::last_os_error())); @@ -140,28 +155,26 @@ fn show(state: State, ready: mpsc::SyncSender<io::Result<usize>>) { unsafe extern "system" fn window_proc( window: HWND, message: u32, - stage: WPARAM, + wparam: WPARAM, data: LPARAM, ) -> LRESULT { // SAFETY: Win32 supplies CREATESTRUCTW for WM_NCCREATE. The userdata points - // to the thread-local State from `show` until destruction. + // to the State kept alive by 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 => { + SET_FRAME => { + InvalidateRect(window, ptr::null(), 0); + UpdateWindow(window); + return 0; + } + WM_PAINT => { 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); - } + draw(window, state); return 0; } } @@ -171,95 +184,46 @@ unsafe extern "system" fn window_proc( } _ => {} } - DefWindowProcW(window, message, stage, data) + DefWindowProcW(window, message, wparam, 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. + // SAFETY: The paint context is borrowed until EndPaint. The bitmap is + // locked while GDI reads its validated width × height 32-bit pixels. 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, + if let Ok(frame) = state.pixels.lock() { + let [width, height] = state.extent; + let mut info: BITMAPINFO = mem::zeroed(); + info.bmiHeader = BITMAPINFOHEADER { + biSize: mem::size_of::<BITMAPINFOHEADER>() as u32, + biWidth: width, + biHeight: -height, + biPlanes: 1, + biBitCount: 32, + biCompression: BI_RGB, + ..mem::zeroed() + }; + let mut area: RECT = mem::zeroed(); + GetClientRect(window, &mut area); + StretchDIBits( + dc, 0, - 1, 0, + area.right, + area.bottom, 0, - 5, 0, - font_face.as_ptr(), + width, + height, + frame.as_ptr().cast(), + &info, + DIB_RGB_COLORS, + SRCCOPY, ); - 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 023f84b0..507a45b0 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -194,11 +194,6 @@ fn run(args: &[String]) -> Result<String, String> { .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 @@ -217,8 +212,14 @@ fn run(args: &[String]) -> Result<String, String> { } let services = EngineServices::new(vfs); let mut engine = create(services).map_err(|err| err.to_string())?; + let mut loading = if event_loop.is_some() { + MissionLoading::start(&args.root) + } else { + MissionLoading::default() + }; let mission_assets_started = Instant::now(); let loaded = load_requested_mission(&mut engine, &args).map_err(|error| error.to_string())?; + loading.stage(LoadingStage::World); let guard_clans = fparkan_runtime::mission_guard_fallback_count(&engine); if guard_clans != 0 { eprintln!("sim_coverage mission_guard_fallback={guard_clans}"); @@ -320,8 +321,21 @@ fn run(args: &[String]) -> Result<String, String> { .and_then(|c| c.sky_uv_clock.as_ref()) .and_then(|c| c.celestial_births.clone()); let hold_schedule_phase = camera.is_some() && atmosphere_seconds.is_some(); + // Resolve the mission-local atmosphere before baking the visible objects. + let sky_started = Instant::now(); + let mut environment = load_environment( + &args.root, + &args.mission, + atmosphere_seconds, + hold_schedule_phase, + )?; + if let Some(environment) = &mut environment { + environment.fixed_sky_uv_ms = captured_sky_uv_ms; + environment.captured_celestial_births = captured_celestial_births; + } + let sky_duration = sky_started.elapsed(); + loading.stage(LoadingStage::Atmosphere); let terrain_materials_duration_started = Instant::now(); - loading.stage(LoadingStage::Map); let mut preview = static_preview_mesh_and_materials( mission_assets, terrain, @@ -340,23 +354,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 - // tree). - let sky_started = Instant::now(); - let mut environment = load_environment( - &args.root, - &args.mission, - atmosphere_seconds, - hold_schedule_phase, - )?; - if let Some(environment) = &mut environment { - environment.fixed_sky_uv_ms = captured_sky_uv_ms; - environment.captured_celestial_births = captured_celestial_births; - } - let sky_duration = sky_started.elapsed(); + loading.stage(LoadingStage::Objects); let audio = match audio::GameAudio::new(Arc::new(DirectoryVfs::new(&args.root)), &args.mission) { Ok(audio) => Some(audio), @@ -12197,7 +12195,7 @@ impl ApplicationHandler for StaticVulkanApp { if self.window.is_some() { return; } - self.loading.stage(LoadingStage::Renderer); + self.loading.stage(LoadingStage::Camera); let startup_window_visible = self.loading.window_visible(); let plan = match WinitWindowPlan::smoke().validate() { Ok(plan) => plan, @@ -12314,6 +12312,7 @@ impl ApplicationHandler for StaticVulkanApp { renderer.set_readback_enabled( self.readback_out.is_some() || self.readback_sequence_out.is_some(), ); + self.loading.stage(LoadingStage::Ready); if startup_window_visible { window.set_visible(true); } diff --git a/apps/fparkan-game/src/mission_loading.rs b/apps/fparkan-game/src/mission_loading.rs index 37c056dd..41f75c87 100644 --- a/apps/fparkan-game/src/mission_loading.rs +++ b/apps/fparkan-game/src/mission_loading.rs @@ -1,71 +1,116 @@ //! Lifecycle of the loader for a windowed mission launch. +use std::path::Path; + +#[cfg(windows)] +use { + fparkan_assets::mission_loader::MissionLoader, + fparkan_platform_winit::{ + startup_window::StartupWindow, text::StringResources, WinitWindowPlan, + }, + fparkan_vfs::DirectoryVfs, +}; + #[derive(Clone, Copy)] pub(super) enum Stage { - Map = 1, - Scene, - Renderer, + World, + Atmosphere, + Objects, + Camera, + Ready, } #[derive(Default)] pub(super) struct MissionLoading { #[cfg(windows)] - window: Option<fparkan_platform_winit::startup_window::StartupWindow>, - #[cfg(not(windows))] - active: bool, + presentation: Option<Presentation>, } -const STAGES: &[&str] = &[ - "Чтение ресурсов миссии", - "Подготовка карты и материалов", - "Подготовка сцены и звука", - "Запуск Vulkan", -]; +#[cfg(windows)] +struct Presentation { + window: StartupWindow, + screen: MissionLoader, + strings: StringResources, +} impl MissionLoading { - pub(super) fn start(mission: &str) -> Self { + pub(super) fn start(_root: &Path) -> 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) + let presentation = Presentation::open(_root) .map_err(|error| eprintln!("startup window: {error}")) .ok(); - Self { window } + Self { presentation } } #[cfg(not(windows))] - { - eprintln!("{mission} — {}", STAGES[0]); - Self { active: true } - } + Self::default() } - pub(super) fn stage(&self, stage: Stage) { + pub(super) fn stage(&mut 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]); + if let Some(presentation) = &mut self.presentation { + if let Err(error) = presentation.update(_stage) { + eprintln!("startup window: {error}"); + } } } pub(super) fn window_visible(&self) -> bool { #[cfg(windows)] { - self.window.is_some() + self.presentation.is_some() } #[cfg(not(windows))] - { - false - } + false } pub(super) fn finish(&mut self) { *self = Self::default(); } } + +#[cfg(windows)] +impl Presentation { + fn open(root: &Path) -> Result<Self, String> { + let strings = StringResources::open(&root.join("iron3d.dll"))?; + let plan = WinitWindowPlan::smoke(); + let extent = [plan.width, plan.height]; + let mut screen = MissionLoader::new( + &DirectoryVfs::new(root), + extent, + &original_text(&strings, 0x13e3)?, + )?; + screen.append(&original_text(&strings, 0x1194)?)?; + let window = + StartupWindow::open(extent, screen.frame(10)).map_err(|error| error.to_string())?; + Ok(Self { + window, + screen, + strings, + }) + } + + fn update(&mut self, stage: Stage) -> Result<(), String> { + // The Rust loader prepares several original stages in one operation. + // Publish their messages together when that operation has completed. + let (ids, percent): (&[u32], u8) = match stage { + Stage::World => (&[0x1198, 0x1199, 0x119a], 45), + Stage::Atmosphere => (&[0x119b], 48), + Stage::Objects => (&[0x119c, 0x119d, 0x119e, 0x119f, 0x11a0, 0x11a2], 90), + Stage::Camera => (&[0x11a3], 95), + Stage::Ready => (&[0x11a4], 100), + }; + for &id in ids { + self.screen.append(&original_text(&self.strings, id)?)?; + } + self.window.set_frame(self.screen.frame(percent)); + Ok(()) + } +} + +#[cfg(windows)] +fn original_text(strings: &StringResources, id: u32) -> Result<String, String> { + strings + .get(id) + .ok_or_else(|| format!("missing iron3d.dll string {id:#06x}")) +} diff --git a/crates/fparkan-assets/src/game_font.rs b/crates/fparkan-assets/src/game_font.rs index 3b88c47e..12625e90 100644 --- a/crates/fparkan-assets/src/game_font.rs +++ b/crates/fparkan-assets/src/game_font.rs @@ -9,19 +9,20 @@ use std::sync::Arc; /// Load the `GAME_FONT` for the 800×600 pager profile witnessed in the original. pub fn load_game_font(vfs: &dyn Vfs) -> Result<BitmapFont, String> { - load_game_font_profile(vfs, 2, [800, 600]) + load_profile(vfs, 2, [800, 600], &["GAME_FONT"]).map(|[font]| font) } /// Load the font for composing controls in the original 640×480 layout space. pub fn load_layout_font(vfs: &dyn Vfs) -> Result<BitmapFont, String> { - load_game_font_profile(vfs, 1, [640, 480]) + load_profile(vfs, 1, [640, 480], &["GAME_FONT"]).map(|[font]| font) } -fn load_game_font_profile( +pub(crate) fn load_profile<const N: usize>( vfs: &dyn Vfs, profile: u8, dimensions: [u32; 2], -) -> Result<BitmapFont, String> { + names: &[&str; N], +) -> Result<[BitmapFont; N], String> { let bytes = read(vfs, "ui/game_resources.cfg")?; let cfg = String::from_utf8_lossy(&bytes); let aliases = @@ -33,14 +34,18 @@ fn load_game_font_profile( { return Err("unexpected dimensions for the game font profile".into()); } - let key = field(&aliases, "GAME_FONT")?.to_ascii_uppercase(); let fonts = object(&cfg, "fonts").ok_or("missing font catalog")?; - let id = EntryId(number(&fonts, &key)?); let archive = decode(read(vfs, field(&fonts, "LIBRARY")?)?, ReadProfile::Strict) .map_err(|error| error.to_string())?; - let payload = archive.payload(id).map_err(|error| error.to_string())?; - let font = decode_tfnt(Arc::from(payload)).map_err(|error| error.to_string())?; - BitmapFont::prepare(&font) + let load = |name: &&str| { + let key = field(&aliases, name)?.to_ascii_uppercase(); + let id = EntryId(number(&fonts, &key)?); + let payload = archive.payload(id).map_err(|error| error.to_string())?; + let font = decode_tfnt(Arc::from(payload)).map_err(|error| error.to_string())?; + BitmapFont::prepare(&font) + }; + let fonts = names.iter().map(load).collect::<Result<Vec<_>, _>>()?; + fonts.try_into().map_err(|_| "invalid font count".into()) } #[cfg(test)] diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs index f2601b44..d55c9f83 100644 --- a/crates/fparkan-assets/src/lib.rs +++ b/crates/fparkan-assets/src/lib.rs @@ -36,6 +36,7 @@ mod control_drive; mod control_weapon_sound; mod explosion_profile; pub mod game_font; +pub mod mission_loader; pub mod object_descriptions; pub mod satellite_map; mod turret_elevation; diff --git a/crates/fparkan-assets/src/mission_loader.rs b/crates/fparkan-assets/src/mission_loader.rs new file mode 100644 index 00000000..842c416d --- /dev/null +++ b/crates/fparkan-assets/src/mission_loader.rs @@ -0,0 +1,174 @@ +//! Composition of the original mission loading screen. + +use crate::{game_font, RgbaImage}; +use fparkan_vfs::Vfs; + +/// Screen content assembled from the installed game's fonts and strings. +pub struct MissionLoader { + extent: [u32; 2], + title: RgbaImage, + log_font: game_font::BitmapFont, + lines: Vec<RgbaImage>, +} + +impl MissionLoader { + /// Picks a font profile that fits the drawable and renders the title. + pub fn new(vfs: &dyn Vfs, extent: [u32; 2], title: &str) -> Result<Self, String> { + let [width, height] = extent; + let (profile, dimensions) = if width >= 1024 && height >= 768 { + (3, [1024, 768]) + } else if width >= 800 && height >= 600 { + (2, [800, 600]) + } else { + (1, [640, 480]) + }; + let [title_font, log_font] = + game_font::load_profile(vfs, profile, dimensions, &["MENU_FONT", "GAME_FONT"])?; + Ok(Self { + extent, + title: line(&title_font, title)?, + log_font, + lines: Vec::new(), + }) + } + + /// Adds a completed loading operation to the rolling log. + pub fn append(&mut self, text: &str) -> Result<(), String> { + self.lines.push(line(&self.log_font, text)?); + Ok(()) + } + + /// Composes top-down RGB pixels (0x00RRGGBB) for the current native percentage. + pub fn frame(&self, percent: u8) -> Vec<u32> { + let [width, height] = self.extent; + let mut pixels = vec![0; width as usize * height as usize]; + let scale = |pixels: u32, design: u32, drawable: u32| { + (f64::from(pixels) * f64::from(design) / f64::from(drawable)).round_ties_even() as u32 + }; + let project = |value: u32, design: u32, drawable: u32| { + (f64::from(value) * f64::from(drawable) / f64::from(design)).round_ties_even() as u32 + }; + let mut text = |image: &RgbaImage, x, y, color| { + let origin = [project(x, 640, width), project(y, 480, height)]; + draw_line(&mut pixels, self.extent, image, origin, color); + }; + text( + &self.title, + 320_u32.saturating_sub(scale(self.title.width, 640, width) / 2), + 240_u32.saturating_sub(scale(self.title.height + 7, 480, height)), + [100, 255, 100], + ); + let lines = &self.lines[self.lines.len().saturating_sub(17)..]; + if let Some(first) = lines.first() { + let step = scale(first.height + 2, 480, height); + for (index, image) in lines.iter().enumerate() { + let fade = index as u8 * 2; + let y = 460_u32.saturating_sub((lines.len() - index) as u32 * step); + text(image, 5, y, [100 - fade, 255 - fade, 100 - fade]); + } + } + let bar = ProgressBar::new(self.extent, self.title.width); + let [_, top, _, bottom] = bar.inner; + for x in bar.cells(percent) { + fill( + &mut pixels, + self.extent, + [x, top, x + bar.step - 2, bottom], + 0x32_e1_32, + ); + } + let [left, top, right, bottom] = bar.outline(); + for rect in [ + [left, top, right, top + 1], + [left, bottom, right, bottom + 1], + [left, top, left + 1, bottom + 1], + [right, top, right + 1, bottom + 1], + ] { + fill(&mut pixels, self.extent, rect, 0x32_ff_32); + } + pixels + } +} + +fn line(font: &game_font::BitmapFont, text: &str) -> Result<RgbaImage, String> { + let [width, height] = font.line_metrics(text)?; + font.centered_line(text, width, height) +} + +fn draw_line( + pixels: &mut [u32], + [width, height]: [u32; 2], + image: &RgbaImage, + [x, y]: [u32; 2], + color: [u8; 3], +) { + for row in 0..image.height.min(height.saturating_sub(y)) { + for col in 0..image.width.min(width.saturating_sub(x)) { + let i = ((row * image.width + col) * 4) as usize; + let [r, g, b] = + std::array::from_fn(|c| u32::from(image.rgba8[i + c]) * u32::from(color[c]) / 255); + pixels[((y + row) * width + x + col) as usize] = (r << 16) | (g << 8) | b; + } + } +} + +struct ProgressBar { + inner: [i32; 4], + step: i32, +} + +impl ProgressBar { + fn new([width, height]: [u32; 2], title_width: u32) -> Self { + let (width, height) = (width as i32, height as i32); + let span = (title_width as i32 + 8) / 8 * 8 + 8; + Self { + inner: [ + (width - span) / 2, + height / 2, + (width + span) / 2, + height / 2 + height / 30, + ], + step: span / 8, + } + } + + fn cells(&self, percent: u8) -> impl Iterator<Item = i32> { + let [left, _, right, _] = self.inner; + let end = (f64::from(right - left) * f64::from(0.01_f32) * f64::from(percent) + + f64::from(left)) + .round_ties_even() as i32; + (left..end).step_by(self.step as usize) + } + + fn outline(&self) -> [i32; 4] { + let [left, top, right, bottom] = self.inner; + [left - 3, top - 3, right, bottom + 2] + } +} + +fn fill(pixels: &mut [u32], [width, height]: [u32; 2], rect: [i32; 4], color: u32) { + let [left, top, right, bottom] = rect.map(|edge| edge.max(0) as u32); + for y in top..bottom.min(height) { + let base = y as usize * width as usize; + pixels[base + left.min(width) as usize..base + right.min(width) as usize].fill(color); + } +} + +#[cfg(test)] +mod tests { + use super::ProgressBar; + + #[test] + fn native_progress_rounds_the_title_span_and_draws_eight_segments() { + let bar = ProgressBar::new([800, 600], 73); + assert_eq!(bar.inner, [356, 300, 444, 320]); + assert_eq!(bar.outline(), [353, 297, 444, 322]); + assert_eq!(bar.cells(0).count(), 0); + assert_eq!(bar.cells(10).collect::<Vec<_>>(), [356]); + assert_eq!(bar.cells(45).collect::<Vec<_>>(), [356, 367, 378, 389]); + assert_eq!( + bar.cells(100).collect::<Vec<_>>(), + [356, 367, 378, 389, 400, 411, 422, 433] + ); + } +} diff --git a/crates/fparkan-font/src/bitmap.rs b/crates/fparkan-font/src/bitmap.rs index 039e3b9f..6360b367 100644 --- a/crates/fparkan-font/src/bitmap.rs +++ b/crates/fparkan-font/src/bitmap.rs @@ -131,6 +131,18 @@ impl BitmapFont { self.centered_line_bytes(&bytes, width, height) } + /// Text extent in native atlas pixels, including character spacing. + pub fn line_metrics(&self, text: &str) -> Result<[u16; 2], String> { + let (bytes, _, unmappable) = WINDOWS_1251.encode(text); + if unmappable { + return Err("game text contains characters outside CP1251".into()); + } + let width = bytes.iter().map(|&byte| self.advance(byte)).sum::<usize>(); + let width = u16::try_from(width).map_err(|_| "game text is too wide")?; + let height = u16::try_from(self.glyph_height).map_err(|_| "game font is too tall")?; + Ok([width, height]) + } + /// Composes a single line from a game resource's original CP1251 bytes. pub fn centered_line_bytes( &self, diff --git a/docs/tomes/03-resources.md b/docs/tomes/03-resources.md index f092ece5..8f494d27 100644 --- a/docs/tomes/03-resources.md +++ b/docs/tomes/03-resources.md @@ -594,6 +594,29 @@ Resolver не должен интерпретировать bytes BASE как me polygon record и неизвестные поля 1:1, пока полный gameplay-контракт BASE не подтверждён. +## Экран загрузки миссии + +Загрузчик показывает сделанную работу. По завершении очередной операции +движок добавляет строку в журнал и передаёт шкале новое значение. Например, +после добавления ландшафта оригинал передаёт 45, а после добавления атмосферы +48. Шкала в обоих случаях показывает четыре ячейки из восьми. Ширина шкалы +зависит от ширины заголовка, поэтому она подстраивается под язык игры. + +Заголовок «Загрузка...» и строки журнала читаются из таблицы ресурсов +`iron3d.dll`. Алиасы `MENU_FONT` и `GAME_FONT` берутся из +`ui/game_resources.cfg` и указывают на два растровых шрифта в `ui/font.lib`. +Заголовок центрируется над шкалой, а последние 17 строк располагаются +слева внизу. Координаты текста переводятся из области 640×480 в размер +окна, тогда как рамка и ячейки шкалы рассчитываются в пикселях экрана. + +В сборке GOG с SHA-256 +`D1DC4EA8535E2069B0A05C9E8BE2724DD438BA44CCA7A83007D8B2E50F9E35FA` +экран рисует `iron3d.dll+0x6a020`, шкалу — `+0x6a310`, журнал — +`+0x6a4a0`. FParkan публикует несколько строк за одно обновление, когда +одна операция подготавливает сразу несколько частей мира. Окно загрузки +может обновляться во время подготовки геометрии и закрывается после первого +успешного вывода кадра Vulkan. + ## Правило сохранения Lossless editor сохраняет неизвестные поля, хвосты фиксированных строк, |
