From c3e2add9a189879b5e800344e07645af591a2cbd Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Wed, 2 Dec 2026 00:14:47 +0400 Subject: feat(ui): show live weapon readings in the hero cockpit --- crates/fparkan-assets/src/game_font.rs | 20 +++++- crates/fparkan-assets/src/lib.rs | 1 + crates/fparkan-assets/src/ui_sprite.rs | 68 +++++++++++++++++++++ crates/fparkan-font/src/bitmap.rs | 36 +++++++++++ crates/fparkan-runtime/src/lib.rs | 1 + crates/fparkan-runtime/src/player_weapon.rs | 94 +++++++++++++++++++++++++++-- 6 files changed, 212 insertions(+), 8 deletions(-) create mode 100644 crates/fparkan-assets/src/ui_sprite.rs (limited to 'crates') diff --git a/crates/fparkan-assets/src/game_font.rs b/crates/fparkan-assets/src/game_font.rs index 556aa79d..3b88c47e 100644 --- a/crates/fparkan-assets/src/game_font.rs +++ b/crates/fparkan-assets/src/game_font.rs @@ -9,15 +9,29 @@ 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 { + load_game_font_profile(vfs, 2, [800, 600]) +} + +/// Load the font for composing controls in the original 640×480 layout space. +pub fn load_layout_font(vfs: &dyn Vfs) -> Result { + load_game_font_profile(vfs, 1, [640, 480]) +} + +fn load_game_font_profile( + vfs: &dyn Vfs, + profile: u8, + dimensions: [u32; 2], +) -> Result { let bytes = read(vfs, "ui/game_resources.cfg")?; let cfg = String::from_utf8_lossy(&bytes); - let aliases = object(&cfg, "font_substitutes2").ok_or("missing 800×600 font profile")?; + let aliases = + object(&cfg, &format!("font_substitutes{profile}")).ok_or("missing game font profile")?; if [ number(&aliases, "DIMENSION_X")?, number(&aliases, "DIMENSION_Y")?, - ] != [800, 600] + ] != dimensions { - return Err("unexpected dimensions for the 800×600 font profile".into()); + 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")?; diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs index 75851628..bd66a50a 100644 --- a/crates/fparkan-assets/src/lib.rs +++ b/crates/fparkan-assets/src/lib.rs @@ -39,6 +39,7 @@ pub mod game_font; pub mod satellite_map; mod turret_elevation; mod ui_configuration; +pub mod ui_sprite; pub use behavior_profile_values::{ decode_behavior_go_speed_percent, decode_behavior_work_rates, BehaviorWorkRates, }; diff --git a/crates/fparkan-assets/src/ui_sprite.rs b/crates/fparkan-assets/src/ui_sprite.rs new file mode 100644 index 00000000..157b851c --- /dev/null +++ b/crates/fparkan-assets/src/ui_sprite.rs @@ -0,0 +1,68 @@ +//! Original UI atlas rectangles selected through the game resource table. + +use crate::ui_configuration::{field, number, object, read}; +use fparkan_nres::{decode, EntryId, ReadProfile}; +use fparkan_texm::{decode_mip_rgba8, decode_texm, RgbaImage}; +use fparkan_vfs::Vfs; +use std::{collections::HashMap, sync::Arc}; + +pub fn load_ui_sprites( + vfs: &dyn Vfs, + config: &str, + names: [&str; N], +) -> Result<[RgbaImage; N], String> { + let definitions = read(vfs, config)?; + let definitions = String::from_utf8_lossy(&definitions); + let game = read(vfs, "ui/game_resources.cfg")?; + let game = String::from_utf8_lossy(&game); + let textures = object(&game, "textures").ok_or("missing UI texture catalog")?; + let archive = decode( + read(vfs, field(&textures, "LIBRARY")?)?, + ReadProfile::Strict, + ) + .map_err(|error| error.to_string())?; + let mut pages = HashMap::new(); + let mut sprites = Vec::with_capacity(N); + for name in names { + let region = + object(&definitions, name).ok_or_else(|| format!("missing UI sprite {name}"))?; + let page = number(&textures, &field(®ion, "TEXTURE")?.to_ascii_uppercase())?; + let image = match pages.entry(page) { + std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::hash_map::Entry::Vacant(entry) => { + let payload = archive + .payload(EntryId(page)) + .map_err(|error| error.to_string())?; + let texture = decode_texm(Arc::from(payload)).map_err(|error| error.to_string())?; + entry.insert(decode_mip_rgba8(&texture, 0).map_err(|error| error.to_string())?) + } + }; + let [x, y, width, height] = + ["OFFSET_X", "OFFSET_Y", "WIDTH", "HEIGHT"].map(|key| number(®ion, key)); + let [x, y, width, height] = [x?, y?, width?, height?]; + if width == 0 + || height == 0 + || x.checked_add(width).is_none_or(|right| right > image.width) + || y.checked_add(height) + .is_none_or(|bottom| bottom > image.height) + { + return Err(format!("UI sprite {name} is outside atlas page {page}")); + } + let rgba8 = (y..y + height) + .flat_map(|row| { + let start = (row as usize * image.width as usize + x as usize) * 4; + image.rgba8[start..start + width as usize * 4] + .iter() + .copied() + }) + .collect(); + sprites.push(RgbaImage { + width, + height, + rgba8, + }); + } + Ok(sprites + .try_into() + .expect("one rectangle per UI sprite name")) +} diff --git a/crates/fparkan-font/src/bitmap.rs b/crates/fparkan-font/src/bitmap.rs index 7f628b71..c28ce7f4 100644 --- a/crates/fparkan-font/src/bitmap.rs +++ b/crates/fparkan-font/src/bitmap.rs @@ -122,6 +122,42 @@ impl BitmapFont { Ok(((occupied + PADDING) as u32, pixels)) } + /// Renders a single line centered in a transparent RGBA image. + pub fn centered_line(&self, text: &str, width: u16, height: u16) -> Result { + let (bytes, _, unmappable) = WINDOWS_1251.encode(text); + if unmappable { + return Err("game text contains characters outside CP1251".into()); + } + let (width, height) = (usize::from(width), usize::from(height)); + if height < self.glyph_height || width == 0 { + return Err("game text rectangle is too small".into()); + } + let len = width + .checked_mul(height) + .and_then(|area| area.checked_mul(4)) + .filter(|&len| len <= isize::MAX as usize) + .ok_or("game text rectangle is too large")?; + let mut pixels = vec![0; len]; + let advance = bytes.iter().map(|&byte| self.advance(byte)).sum::(); + let mut x = width.saturating_sub(advance) / 2; + let y = (height - self.glyph_height) / 2; + for &byte in bytes.iter() { + self.draw_glyph( + self.glyphs[usize::from(byte)], + &mut pixels, + width, + [x, y], + width - x, + ); + x = (x + self.advance(byte)).min(width); + } + Ok(RgbaImage { + width: width as u32, + height: height as u32, + rgba8: pixels, + }) + } + fn advance(&self, byte: u8) -> usize { self.glyphs[usize::from(byte)].width - 1 + self.spacing } diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 2b148397..a53e32f0 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -193,6 +193,7 @@ pub use player_motion::{ pub use player_status::{is_player_clan, player_status, PlayerStatus}; pub use player_weapon::{ prepared_warbot_weapons, starting_player_weapons, PlayerWeaponWarning, PlayerWeapons, + WeaponIndicator, WeaponLamp, }; pub use production::{ clan_factory_schemes, factory_schemes, order_clan_factory_scheme, order_factory_robot, diff --git a/crates/fparkan-runtime/src/player_weapon.rs b/crates/fparkan-runtime/src/player_weapon.rs index 347e0450..84408c61 100644 --- a/crates/fparkan-runtime/src/player_weapon.rs +++ b/crates/fparkan-runtime/src/player_weapon.rs @@ -21,6 +21,33 @@ enum WeaponSelection { Slot(usize), } +impl WeaponSelection { + fn includes(self, index: usize) -> bool { + match self { + Self::All => true, + Self::StandardSuit => matches!(index, 0 | 2), + Self::Slot(slot) => slot == index, + } + } +} + +/// The lamp, ammunition and capacitor reading for one cockpit weapon slot. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct WeaponIndicator { + pub rounds: Option, + pub charge_percent: u8, + pub lamp: WeaponLamp, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum WeaponLamp { + Unavailable, + Reloading, + Cycling, + Ready, + Unselected, +} + /// Cockpit announcements triggered by a weapon's current supply. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PlayerWeaponWarning { @@ -83,6 +110,47 @@ enum FirePhase { } impl PlayerWeapons { + /// Read the same slot, cycle and budget that drive manual firing. + pub fn indicators(&self) -> impl Iterator + '_ { + self.weapons.iter().enumerate().map(|(slot, weapon)| { + let ratio = weapon + .charge + .as_ref() + .filter(|charge| charge.capacity > 0.0) + .map_or(1.0, |charge| charge.amount / charge.capacity); + let charge_percent = if (0.0..=1.0).contains(&ratio) { + (f64::from(ratio) * 100.0).round_ties_even() as u8 + } else { + 0 + }; + // iron3d+0x9ccd0 selects the compound-control lamp from Control's status. + let lamp = if !self.selection.includes(slot) { + WeaponLamp::Unselected + } else if weapon.destroyed || weapon.rounds_remaining == Some(0) { + WeaponLamp::Unavailable + } else { + match weapon.phase { + FirePhase::Idle + if weapon + .charge + .as_ref() + .is_some_and(|charge| !charge.can_start()) => + { + WeaponLamp::Reloading + } + FirePhase::Idle => WeaponLamp::Ready, + FirePhase::Reload => WeaponLamp::Reloading, + FirePhase::Shot | FirePhase::Recover | FirePhase::Finish => WeaponLamp::Cycling, + } + }; + WeaponIndicator { + rounds: weapon.rounds_remaining, + charge_percent, + lamp, + } + }) + } + /// Reads the authoritative Control charge and ammunition before firing. pub fn read_control_energy(&mut self, engine: &Engine, handle: crate::ObjectHandle) { if let Some(mission) = &engine.loaded { @@ -232,11 +300,7 @@ impl PlayerWeapons { weapon.windup_started = false; return None; } - let selected = match selection { - WeaponSelection::All => true, - WeaponSelection::StandardSuit => matches!(index, 0 | 2), - WeaponSelection::Slot(slot) => slot == index, - }; + let selected = selection.includes(index); let mut start = selected && trigger(index, weapon, &weapon.barrels[weapon.barrel_index].muzzle); if let Some(deployment) = &mut weapon.deployment { @@ -917,8 +981,20 @@ mod tests { cost: 4.0, amount: 8.0, }); + assert_eq!( + weapons.indicators().next(), + Some(WeaponIndicator { + rounds: Some(1), + charge_percent: 80, + lamp: WeaponLamp::Ready, + }) + ); let mut node_times = [None]; assert!(weapons.fire(true, 0).next().is_none()); + assert_eq!( + weapons.indicators().next().unwrap().lamp, + WeaponLamp::Cycling + ); let mut interrupted = weapons.clone(); interrupted.weapons[0].destroyed = true; assert!(interrupted.fire(true, 11).next().is_none()); @@ -965,6 +1041,14 @@ mod tests { assert_eq!(node_times, [Some(4.0)]); assert_eq!(weapons.firing_effect_phases(7).next(), Some((effect, 0.0))); assert_eq!(weapons.weapons()[0].rounds_remaining(), Some(0)); + assert_eq!( + weapons.indicators().next(), + Some(WeaponIndicator { + rounds: Some(0), + charge_percent: 40, + lamp: WeaponLamp::Unavailable, + }) + ); assert_eq!(weapons.weapons[0].charge.as_ref().unwrap().amount, 4.0); assert_eq!( weapons.take_warnings().next(), -- cgit v1.2.3