diff options
| author | Valentin Popov <valentin@popov.link> | 2026-12-02 15:20:23 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-12-02 15:20:23 +0300 |
| commit | cc6bbdfa4aebf844ec7be2e8eb01b7fd1c69d24b (patch) | |
| tree | 4b69fecd2c3172724ad62cd2e75d1bb456ca0c65 | |
| parent | 04e58559f76c89a284dfab820efed25a97db2461 (diff) | |
| download | fparkan-cc6bbdfa4aebf844ec7be2e8eb01b7fd1c69d24b.tar.xz fparkan-cc6bbdfa4aebf844ec7be2e8eb01b7fd1c69d24b.zip | |
feat(ui): show strategic factories and order a warbot
19 files changed, 913 insertions, 19 deletions
diff --git a/apps/fparkan-game/src/designer_model.rs b/apps/fparkan-game/src/designer_model.rs index 3070a688..c5929439 100644 --- a/apps/fparkan-game/src/designer_model.rs +++ b/apps/fparkan-game/src/designer_model.rs @@ -47,11 +47,19 @@ impl DesignerModels { active: Option<(usize, u32)>, viewport: [f32; 2], ) -> Result<(), String> { + self.draw_in(renderer, active, viewport, MODEL_VIEWPORT) + } + + pub(super) fn draw_in( + &self, + renderer: &mut VulkanSmokeRenderer, + active: Option<(usize, u32)>, + viewport: [f32; 2], + rect: [f32; 4], + ) -> Result<(), String> { let preview = active.and_then(|(scheme, elapsed_ms)| { - self.0 - .get(scheme)? - .as_ref() - .map(|model| model.view(elapsed_ms, viewport)) + let model = self.0.get(scheme)?.as_ref()?; + Some(model.view_in(elapsed_ms, viewport, rect)) }); for (scheme, model) in self.0.iter().enumerate() { let Some(model) = model else { continue }; @@ -162,6 +170,10 @@ impl DesignerModel { } pub(super) fn view(&self, elapsed_ms: u32, drawable: [f32; 2]) -> VulkanModelPreview { + self.view_in(elapsed_ms, drawable, MODEL_VIEWPORT) + } + + fn view_in(&self, elapsed_ms: u32, drawable: [f32; 2], rect: [f32; 4]) -> VulkanModelPreview { let yaw = elapsed_ms as f64 * f64::from(SPIN_RADIANS_PER_MS); let (sin_yaw, cos_yaw) = yaw.sin_cos(); let (sin_elevation, cos_elevation) = ELEVATION.sin_cos(); @@ -179,7 +191,7 @@ impl DesignerModel { let right = normalize3(cross3(forward, [0.0, 0.0, 1.0])) .expect("designer elevation avoids the pole"); let up = cross3(right, forward); - let [l, t, r, b] = MODEL_VIEWPORT; + let [l, t, r, b] = rect; let viewport = [l / 640.0, t / 480.0, r / 640.0, b / 480.0]; let aspect = super::preview_aspect( ((r - l) / 640.0 * drawable[0]) / ((b - t) / 480.0 * drawable[1]), diff --git a/apps/fparkan-game/src/factory_menu.rs b/apps/fparkan-game/src/factory_menu.rs index 788d2fbe..1ce2f683 100644 --- a/apps/fparkan-game/src/factory_menu.rs +++ b/apps/fparkan-game/src/factory_menu.rs @@ -632,6 +632,18 @@ struct ProjectPicture { } impl FactoryProjectPanel { + #[cfg(windows)] + pub(super) fn draw_strategic_model( + &self, + renderer: &mut VulkanSmokeRenderer, + active: (usize, u32), + viewport: [f32; 2], + ) -> Result<(), String> { + if let Some(designer) = &self.designer { + designer.draw_factory_model(renderer, active, viewport)?; + } + Ok(()) + } pub(super) fn load( root: &Path, preview: &mut StaticPreviewScene, diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index 33a1885a..2db15fe3 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -39,6 +39,8 @@ mod satellite_map_chrome; #[cfg(windows)] mod strategic_balance_hud; #[cfg(windows)] +mod strategic_factory_hud; +#[cfg(windows)] mod strategic_roster_hud; mod strategic_toolbar_hud; #[cfg(windows)] diff --git a/apps/fparkan-game/src/mission_overlay.rs b/apps/fparkan-game/src/mission_overlay.rs index 4dd955b8..c193e76f 100644 --- a/apps/fparkan-game/src/mission_overlay.rs +++ b/apps/fparkan-game/src/mission_overlay.rs @@ -14,8 +14,9 @@ use super::{ #[cfg(windows)] use super::{ mission_help::MissionHelp, mission_hints::MissionHints, - strategic_balance_hud::StrategicBalanceHud, strategic_roster_hud::StrategicRosterHud, - strategic_tooltip_hud::StrategicTooltipHud, weapon_hud::WeaponHud, + strategic_balance_hud::StrategicBalanceHud, strategic_factory_hud::StrategicFactoryHud, + strategic_roster_hud::StrategicRosterHud, strategic_tooltip_hud::StrategicTooltipHud, + weapon_hud::WeaponHud, }; use fparkan_assets::RgbaImage; use fparkan_runtime::{ @@ -37,6 +38,8 @@ pub(super) struct MissionOverlay { #[cfg(windows)] strategic_roster: Option<StrategicRosterHud>, #[cfg(windows)] + pub(super) strategic_factory: Option<StrategicFactoryHud>, + #[cfg(windows)] strategic_tooltip: Option<StrategicTooltipHud>, dial: Option<CockpitDial>, pub(super) factory_projects: Option<FactoryProjectPanel>, @@ -119,6 +122,14 @@ impl MissionOverlay { .ok() }); #[cfg(windows)] + let strategic_factory = cockpit.and_then(|_| { + StrategicFactoryHud::load(root, preview) + .inspect_err(|error| { + eprintln!("strategic_factory_panel_unavailable reason={error}") + }) + .ok() + }); + #[cfg(windows)] let weapons = cockpit.and_then(|cockpit| { WeaponHud::load(root, cockpit.handle, preview) .map(Some) @@ -173,6 +184,8 @@ impl MissionOverlay { #[cfg(windows)] strategic_roster, #[cfg(windows)] + strategic_factory, + #[cfg(windows)] strategic_tooltip, dial, factory_projects, @@ -219,6 +232,10 @@ impl MissionOverlay { remove(roster.range_index(), ranges, counts); } #[cfg(windows)] + if let Some(factory) = &self.strategic_factory { + remove(factory.range_index(), ranges, counts); + } + #[cfg(windows)] if let Some(tooltip) = &self.strategic_tooltip { remove(tooltip.range_index(), ranges, counts); } @@ -258,6 +275,12 @@ impl StaticVulkanApp { self.advance_strategy_toolbar(frame.clock.time_ms); } #[cfg(windows)] + let factory_frame = self + .pending_scene_update + .as_ref() + .map(|frame| frame.clock.time_ms) + .and_then(|now_ms| self.strategic_factory_frame(now_ms)); + #[cfg(windows)] let warbot_rows = self.strategic_warbot_rows(); #[cfg(windows)] let row_count = warbot_rows.len(); @@ -282,6 +305,7 @@ impl StaticVulkanApp { layout: view.toolbar_layout(), sections: fparkan_runtime::strategic_toolbar::available_sections(engine, cockpit), warbots_open: view.warbots_open, + factories_open: view.factories_open(), map_open: self .overlay .satellite_map @@ -372,6 +396,17 @@ impl StaticVulkanApp { self.command_view.as_ref(), )?; } + #[cfg(windows)] + let factory_model = if let Some(hud) = &mut self.overlay.strategic_factory { + hud.draw( + renderer, + factory_frame, + self.mission_engine.as_ref(), + frame.clock.time_ms, + )? + } else { + None + }; let cockpit = self.cockpit.filter(|_| self.command_view.is_none()); let occupant = self.mission_engine.as_ref().zip(cockpit); if let Some(dial) = &mut self.overlay.dial { @@ -450,6 +485,10 @@ impl StaticVulkanApp { frame.viewport, frame.clock.time_ms, )?; + #[cfg(windows)] + if let Some(active) = factory_model { + panel.draw_strategic_model(renderer, active, frame.viewport)?; + } } if let Some(hud) = &mut self.overlay.strategy_cursor { if let Some(window) = &self.window { diff --git a/apps/fparkan-game/src/robot_designer.rs b/apps/fparkan-game/src/robot_designer.rs index 2c97ef35..8fe71df7 100644 --- a/apps/fparkan-game/src/robot_designer.rs +++ b/apps/fparkan-game/src/robot_designer.rs @@ -26,6 +26,19 @@ pub(super) struct RobotDesignerPanel { } impl RobotDesignerPanel { + pub(super) fn draw_factory_model( + &self, + renderer: &mut VulkanSmokeRenderer, + active: (usize, u32), + viewport: [f32; 2], + ) -> Result<(), String> { + self.models.draw_in( + renderer, + Some(active), + viewport, + fparkan_assets::strategic_factory::MODEL_RECT, + ) + } pub(super) fn load( root: &Path, preview: &mut StaticPreviewScene, diff --git a/apps/fparkan-game/src/strategic_factory_hud.rs b/apps/fparkan-game/src/strategic_factory_hud.rs new file mode 100644 index 00000000..4f65df88 --- /dev/null +++ b/apps/fparkan-game/src/strategic_factory_hud.rs @@ -0,0 +1,161 @@ +use super::{ + mission_overlay::{add_overlay_sprite, overlay_texture}, + DirectoryVfs, EnvironmentGpuRange, StaticPreviewScene, VulkanSmokeRenderer, +}; +use fparkan_assets::{ + strategic_factory::{FactoryImages, FactoryPicture, FactoryRow, EXTENT, ORIGIN}, + warbot_card::{CardLabels, RatingScale}, +}; +use fparkan_platform_winit::text::StringResources; +use fparkan_runtime::{factory_panel_project, Engine, FactoryPanelPlant}; +use std::path::Path; + +#[derive(PartialEq, Eq)] +pub(super) struct FactoryFrame { + pub plants: Vec<FactoryPanelPlant>, + pub active_plant: usize, + pub selected: Option<usize>, + pub model_started_ms: u32, +} + +impl FactoryFrame { + pub(super) fn scheme(&self) -> Option<usize> { + self.selected + .and_then(|slot| self.plants[self.active_plant].projects.get(slot).copied()) + } +} + +pub(super) struct StrategicFactoryHud { + range: EnvironmentGpuRange, + strings: StringResources, + images: FactoryImages, + labels: CardLabels, + scale: RatingScale, + displayed: Option<FactoryFrame>, +} + +impl StrategicFactoryHud { + pub(super) fn load(root: &Path, preview: &mut StaticPreviewScene) -> Result<Self, String> { + let strings = StringResources::open(&root.join("iron3d.dll"))?; + let read = |id| { + strings + .get(id) + .ok_or_else(|| format!("missing factory card string {id:#x}")) + }; + let images = FactoryImages::load(&DirectoryVfs::new(root), &read(0x647)?)?; + let labels = CardLabels { + labels: [ + read(0x13cd)?, + read(0x13ce)?, + read(0x13cf)?, + read(0x13d0)?, + read(0x13d1)?, + ], + tonnes: read(0x183e)?, + speed: read(0x1820)?, + metres: read(0x1822)?, + }; + let scale = match std::fs::read(root.join("iron_3d.ini")) { + Ok(bytes) => RatingScale::from_ini(&String::from_utf8_lossy(&bytes)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => RatingScale::default(), + Err(error) => return Err(error.to_string()), + }; + let [width, height] = EXTENT; + let [x, y] = ORIGIN.map(|axis| axis as f32); + let range = add_overlay_sprite( + preview, + fparkan_assets::RgbaImage { + width, + height, + rgba8: vec![0; (width * height * 4) as usize], + }, + [x, y, x + width as f32, y + height as f32], + [1.0; 3], + 1.0, + )?; + Ok(Self { + range, + strings, + images, + labels, + scale, + displayed: None, + }) + } + + pub(super) fn range_index(&self) -> usize { + self.range.range_index + } + + pub(super) fn draw( + &mut self, + renderer: &mut VulkanSmokeRenderer, + frame: Option<FactoryFrame>, + engine: Option<&Engine>, + now_ms: u32, + ) -> Result<Option<(usize, u32)>, String> { + renderer + .set_draw_range_index_count(self.range_index(), if frame.is_some() { 6 } else { 0 }) + .map_err(|error| error.to_string())?; + let Some(frame) = frame else { return Ok(None) }; + let active_model = frame + .scheme() + .map(|scheme| (scheme, now_ms.wrapping_sub(frame.model_started_ms))); + if self.displayed.as_ref() == Some(&frame) { + return Ok(active_model); + } + let names = frame + .plants + .iter() + .map(|plant| { + self.strings + .get(plant.label_id) + .ok_or_else(|| format!("missing factory class {:#x}", plant.label_id)) + }) + .collect::<Result<Vec<_>, _>>()?; + let rows = names + .iter() + .enumerate() + .map(|(index, name)| FactoryRow { + name, + selected: index == frame.active_plant, + }) + .collect::<Vec<_>>(); + let project = engine + .zip(frame.scheme()) + .and_then(|(engine, scheme)| factory_panel_project(engine, scheme)); + let name = project.as_ref().and_then(|project| { + let prefix = project.prefix.iter().collect::<String>(); + Some(format!( + "{prefix}-X {}", + self.strings.get(project.label_id)? + )) + }); + let stats = project.as_ref().map_or_else( + || [None, None, None, None, None], + |project| { + let stats = project.stats; + self.labels.lines( + stats.weight, + [stats.speed, stats.defence, stats.offence, stats.radar], + &self.scale, + ) + }, + ); + let plant = &frame.plants[frame.active_plant]; + let image = self.images.paint(FactoryPicture { + rows: &rows, + project_name: name.as_deref(), + stats: &stats, + projects: plant.projects.len(), + selected_project: frame.selected, + progress: plant.progress, + free_minds: plant.free_minds, + })?; + renderer + .update_material_texture(self.range.material_index, 0, &overlay_texture(image)) + .map_err(|error| error.to_string())?; + self.displayed = Some(frame); + Ok(active_model) + } +} diff --git a/apps/fparkan-game/src/strategic_toolbar_hud.rs b/apps/fparkan-game/src/strategic_toolbar_hud.rs index f6ab4c23..7bd71cfe 100644 --- a/apps/fparkan-game/src/strategic_toolbar_hud.rs +++ b/apps/fparkan-game/src/strategic_toolbar_hud.rs @@ -66,6 +66,9 @@ impl StrategicToolbarHud { if frame.warbots_open && frame.sections[0] { visuals[1] = ButtonVisual::Lit; } + if frame.factories_open && frame.sections[4] { + visuals[5] = ButtonVisual::Lit; + } // The chat button is disabled in a local mission. visuals[9] = ButtonVisual::Disabled; if frame.map_open { @@ -94,6 +97,7 @@ pub(super) struct ToolbarFrame { pub layout: ToolbarLayout, pub sections: [bool; 8], pub warbots_open: bool, + pub factories_open: bool, pub map_open: bool, pub pointer: Option<[f32; 2]>, pub now_ms: u32, diff --git a/apps/fparkan-game/src/strategic_view.rs b/apps/fparkan-game/src/strategic_view.rs index 74dc7f63..94c1006d 100644 --- a/apps/fparkan-game/src/strategic_view.rs +++ b/apps/fparkan-game/src/strategic_view.rs @@ -2,6 +2,8 @@ use super::{ add3, player_movement_key, scale3, screen_ray_from_pixels, LegacyD3d7Projection, PreviewCameraFrame, StaticVulkanApp, }; +#[cfg(windows)] +use fparkan_assets::strategic_factory::{self, FactoryAction}; use fparkan_assets::strategic_roster::{ covers_pointer, hit_test, order_at, CockpitControl, ListHit, RosterOrder, }; @@ -30,6 +32,8 @@ pub(super) struct ActiveCommandView { pointer: Option<[f32; 2]>, toolbar: ToolbarFold, pub(super) warbots_open: bool, + #[cfg(windows)] + factory: Option<FactorySelection>, pub(super) selected_warbot: Option<ObjectHandle>, order_input: Option<OrderInput>, } @@ -39,7 +43,57 @@ enum OrderInput { Patrol, } +#[cfg(windows)] +#[derive(Default)] +struct FactorySelection { + plant: Option<ObjectHandle>, + scheme: Option<usize>, + model_started_ms: u32, +} + +#[cfg(windows)] +impl FactorySelection { + fn frame( + &mut self, + plants: Vec<fparkan_runtime::FactoryPanelPlant>, + now_ms: u32, + ) -> Option<super::strategic_factory_hud::FactoryFrame> { + let active_plant = plants + .iter() + .position(|plant| Some(plant.handle) == self.plant) + .unwrap_or(0); + let plant = plants.get(active_plant)?; + let selected = plant + .projects + .iter() + .position(|&scheme| Some(scheme) == self.scheme) + .or_else(|| (!plant.projects.is_empty()).then_some(0)); + let scheme = selected.map(|slot| plant.projects[slot]); + if scheme != self.scheme || Some(plant.handle) != self.plant { + self.model_started_ms = now_ms; + } + self.plant = Some(plant.handle); + self.scheme = scheme; + Some(super::strategic_factory_hud::FactoryFrame { + plants, + active_plant, + selected, + model_started_ms: self.model_started_ms, + }) + } +} + impl ActiveCommandView { + pub(super) fn factories_open(&self) -> bool { + #[cfg(windows)] + { + self.factory.is_some() + } + #[cfg(not(windows))] + { + false + } + } fn refresh_warbots(&mut self, rows: &[WarbotRow]) -> Option<WarbotRow> { self.warbots_open = !rows.is_empty(); if rows @@ -143,6 +197,8 @@ impl StaticVulkanApp { pointer: None, toolbar: ToolbarFold::default(), warbots_open: false, + #[cfg(windows)] + factory: None, selected_warbot: None, order_input: None, }); @@ -257,6 +313,8 @@ impl StaticVulkanApp { self.command_view.as_mut().filter(|view| view.warbots_open) { view.warbots_open = false; + } else if self.close_strategic_factory_panel() { + return true; } else { self.close_strategy(); } @@ -402,11 +460,85 @@ impl StaticVulkanApp { } Some(ToolbarAction::Warbots) if view.warbots_open => view.warbots_open = false, Some(ToolbarAction::Warbots) => { + #[cfg(windows)] + { + view.factory = None; + } if let Some(row) = view.refresh_warbots(&warbot_rows(engine, cockpit)) { self.play_warbot_selection(row); } } + Some(ToolbarAction::Factories) => { + #[cfg(windows)] + if view.factory.take().is_none() && self.overlay.strategic_factory.is_some() { + let mut factory = FactorySelection::default(); + if factory + .frame( + fparkan_runtime::factory_panel_plants( + engine, + cockpit, + self.simulation_time_ms, + ), + self.simulation_time_ms, + ) + .is_some() + { + view.factory = Some(factory); + view.warbots_open = false; + view.selected_warbot = None; + view.order_input = None; + } + } + } None => { + #[cfg(windows)] + if let Some(factory) = view + .factory + .as_mut() + .filter(|_| view.toolbar.layout().sections_visible()) + { + let now = self.simulation_time_ms; + if let Some(frame) = factory.frame( + fparkan_runtime::factory_panel_plants(engine, cockpit, now), + now, + ) { + let plant = &frame.plants[frame.active_plant]; + match strategic_factory::hit_test( + xy, + frame.plants.len(), + plant.projects.len(), + plant.progress.is_none() && plant.free_minds > 0, + ) { + Some(FactoryAction::Close) => view.factory = None, + Some(FactoryAction::Plant(index)) => { + factory.plant = Some(frame.plants[index].handle); + factory.scheme = frame.plants[index].projects.first().copied(); + factory.model_started_ms = now; + } + Some(FactoryAction::Project(index)) => { + factory.scheme = Some(plant.projects[index]); + factory.model_started_ms = now; + } + Some(FactoryAction::Build) => { + if let Some(scheme) = frame.scheme() { + if let Err(error) = fparkan_runtime::order_clan_factory_scheme( + engine, + cockpit, + plant.handle, + scheme, + now, + ) { + eprintln!( + "strategic_factory_order_rejected reason={error}" + ); + } + } + } + None => {} + } + } + return; + } if view.warbots_open && view.toolbar_layout().sections_visible() { match hit_test(xy, rows.len()) { Some(ListHit::Close) => { @@ -595,6 +727,37 @@ impl StaticVulkanApp { } } + fn close_strategic_factory_panel(&mut self) -> bool { + #[cfg(windows)] + { + self.command_view + .as_mut() + .and_then(|view| view.factory.take()) + .is_some() + } + #[cfg(not(windows))] + { + false + } + } + + #[cfg(windows)] + pub(super) fn strategic_factory_frame( + &mut self, + now_ms: u32, + ) -> Option<super::strategic_factory_hud::FactoryFrame> { + let view = self.command_view.as_mut()?; + let visible = view.toolbar.layout().sections_visible(); + let selection = view.factory.as_mut()?; + let engine = self.mission_engine.as_ref()?; + let plants = fparkan_runtime::factory_panel_plants(engine, self.cockpit?, now_ms); + let frame = selection.frame(plants, now_ms); + if frame.is_none() { + view.factory = None; + } + frame.filter(|_| visible) + } + fn play_toolbar_latch(&mut self) { if let Some(audio) = &mut self.audio { if let Err(error) = audio.play_interface_sound("BAR_OPEN") { diff --git a/crates/fparkan-assets/src/lib.rs b/crates/fparkan-assets/src/lib.rs index 800a8e64..f07e2af4 100644 --- a/crates/fparkan-assets/src/lib.rs +++ b/crates/fparkan-assets/src/lib.rs @@ -48,6 +48,7 @@ pub mod object_descriptions; pub mod satellite_map; pub mod satellite_map_chrome; pub mod strategic_balance; +pub mod strategic_factory; pub mod strategic_roster; pub mod strategy_cursor; pub mod strategy_toolbar; diff --git a/crates/fparkan-assets/src/strategic_factory.rs b/crates/fparkan-assets/src/strategic_factory.rs new file mode 100644 index 00000000..e9d1a387 --- /dev/null +++ b/crates/fparkan-assets/src/strategic_factory.rs @@ -0,0 +1,276 @@ +//! The strategic factory panel, composed from the installed compound controls. + +use crate::{ + game_font::{load_layout_font, BitmapFont}, + mission_pager::copy_sprite, + ui_sprite::{atlas_region, load_ui_page, load_ui_sprites}, + warbot_card::{self, CardLine}, + RgbaImage, +}; +use fparkan_vfs::Vfs; + +pub const ORIGIN: [u32; 2] = [51, 0]; +pub const EXTENT: [u32; 2] = [319, 480]; +/// iron3d+0x98240 places the rotating preview at card origin + (185, 2). +pub const MODEL_RECT: [f32; 4] = [236.0, 23.0, 351.0, 138.0]; +const ROW_TOP: u32 = 171; +const ROW_PITCH: u32 = 20; +const ROW_HEIGHT: u32 = 19; +pub const VISIBLE_PLANTS: usize = ((EXTENT[1] - ROW_TOP) / ROW_PITCH) as usize; +const BUILD: [u32; 4] = [263, 150, 313, 169]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FactoryAction { + Close, + Project(usize), + Build, + Plant(usize), +} + +fn project_rect(index: usize) -> [u32; 4] { + let left = 10 + index as u32 * 23; + [left, 125, left + 19, 142] +} + +pub fn hit_test( + [x, y]: [f32; 2], + plants: usize, + projects: usize, + idle: bool, +) -> Option<FactoryAction> { + let [x, y] = [x.round_ties_even() - ORIGIN[0] as f32, y.round_ties_even()]; + let hit = |[left, top, right, bottom]: [u32; 4]| { + (left as f32..right as f32).contains(&x) && (top as f32..bottom as f32).contains(&y) + }; + if hit([283, 0, 318, 19]) { + return Some(FactoryAction::Close); + } + if idle && projects != 0 && hit(BUILD) { + return Some(FactoryAction::Build); + } + if let Some(index) = (0..projects).find(|&index| hit(project_rect(index))) { + return Some(FactoryAction::Project(index)); + } + (0..plants.min(VISIBLE_PLANTS)) + .find(|&index| { + let top = ROW_TOP + index as u32 * ROW_PITCH; + hit([0, top, 318, top + ROW_HEIGHT]) + }) + .map(FactoryAction::Plant) +} + +pub struct FactoryRow<'a> { + pub name: &'a str, + pub selected: bool, +} + +pub struct FactoryPicture<'a> { + pub rows: &'a [FactoryRow<'a>], + pub project_name: Option<&'a str>, + pub stats: &'a [Option<CardLine<'a>>], + pub projects: usize, + pub selected_project: Option<usize>, + pub progress: Option<u8>, + pub free_minds: u32, +} + +pub struct FactoryImages { + font: BitmapFont, + base: RgbaImage, + row_cap: [RgbaImage; 2], + row_body: RgbaImage, + ray: RgbaImage, + icons: [RgbaImage; 5], +} + +impl FactoryImages { + pub fn load(vfs: &dyn Vfs, title: &str) -> Result<Self, String> { + let [title_cap, body, close, row_off, row_on, ray, tl, tr, br, bl, h, v] = load_ui_sprites( + vfs, + "ui/compaund.cfg", + [ + "ccres_ending_text", + "ccres_body_text", + "ccres_exit_button_pressed", + "ccres_lamp_text_ending_off", + "ccres_lamp_text_ending_normal", + "ccres_ray_body", + "ccres_frame_corner_1", + "ccres_frame_corner_2", + "ccres_frame_corner_3", + "ccres_frame_corner_4", + "ccres_frame_edge_h", + "ccres_frame_edge_v", + ], + )?; + let [exit, project, project_frame, build, free] = load_ui_sprites( + vfs, + "ui/hq.cfg", + [ + "exit_icon", + "project_icon", + "short_button_frame_off", + "build_icon", + "brain_icon", + ], + )?; + let atlas = load_ui_page(vfs, "ui_menu")?; + let plant = + atlas_region(&atlas, [129, 94, 15, 15]).ok_or("factory glyph outside ui_menu")?; + let font = load_layout_font(vfs)?; + let mut base = RgbaImage { + width: EXTENT[0], + height: EXTENT[1], + rgba8: vec![0; (EXTENT[0] * EXTENT[1] * 4) as usize], + }; + let green = RgbaImage { + width: 1, + height: 1, + rgba8: vec![0, 128, 0, 128], + }; + for (sprite, rect) in [ + (&title_cap, [0, 0, 6, 19]), + (&body, [5, 0, 284, 19]), + (&close, [283, 0, 318, 19]), + (&exit, [298, 3, 311, 16]), + (&green, [5, 26, 313, 142]), + (&h, [8, 21, 310, 26]), + (&h, [8, 142, 310, 147]), + (&v, [0, 29, 5, 139]), + (&v, [313, 29, 318, 139]), + (&tl, [0, 21, 8, 29]), + (&tr, [310, 21, 318, 29]), + (&br, [310, 139, 318, 147]), + (&bl, [0, 139, 8, 147]), + ] { + stamp(&mut base, sprite, rect, [255; 3]); + } + text(&font, &mut base, title, [5, 0, 283, 19], [255; 3])?; + Ok(Self { + font, + base, + row_cap: [row_off, row_on], + row_body: body, + ray, + icons: [project, project_frame, plant, build, free], + }) + } + + pub fn paint(&self, picture: FactoryPicture<'_>) -> Result<RgbaImage, String> { + let mut image = self.base.clone(); + let [project, frame, plant, build, free] = &self.icons; + if let Some(name) = picture.project_name { + let width = u32::from(self.font.line_metrics(name)?[0]).min(170); + text( + &self.font, + &mut image, + name, + [10, 27, 10 + width, 43], + [255, 255, 0], + )?; + warbot_card::paint_at(&self.font, &mut image, picture.stats, [10, 144, 147], 43)?; + } + for index in 0..picture.projects { + let rect = project_rect(index); + stamp( + &mut image, + frame, + [rect[0] - 2, rect[1] - 2, rect[2] + 2, rect[3] + 2], + [255; 3], + ); + let tint = if picture.selected_project == Some(index) { + [255; 3] + } else { + [128, 255, 128] + }; + stamp(&mut image, project, rect, tint); + } + stamp(&mut image, free, [274, 127, 289, 142], [128, 255, 128]); + text( + &self.font, + &mut image, + &picture.free_minds.to_string(), + [289, 125, 306, 144], + [128, 255, 128], + )?; + stamp(&mut image, &self.row_body, [5, 150, 263, 169], [255; 3]); + if let Some(progress) = picture.progress { + text( + &self.font, + &mut image, + &format!("{progress}%"), + [5, 150, 263, 169], + [255; 3], + )?; + } else if picture.selected_project.is_some() && picture.free_minds > 0 { + stamp(&mut image, &self.row_body, BUILD, [255; 3]); + stamp( + &mut image, + build, + [BUILD[0] + 10, BUILD[1] + 2, BUILD[0] + 40, BUILD[1] + 17], + [255; 3], + ); + } + for (index, row) in picture.rows.iter().take(VISIBLE_PLANTS).enumerate() { + let y = ROW_TOP + index as u32 * ROW_PITCH; + let bottom = y + ROW_HEIGHT; + stamp( + &mut image, + &self.row_cap[usize::from(row.selected)], + [0, y, 11, bottom], + [255; 3], + ); + stamp(&mut image, &self.row_body, [10, y, 38, bottom], [255; 3]); + stamp(&mut image, plant, [13, y + 2, 28, y + 17], [255, 0, 0]); + stamp(&mut image, &self.ray, [38, y, 318, bottom], [255; 3]); + text( + &self.font, + &mut image, + row.name, + [38, y, 318, bottom], + if row.selected { [255; 3] } else { [128; 3] }, + )?; + } + Ok(image) + } +} + +fn stamp(image: &mut RgbaImage, sprite: &RgbaImage, rect: [u32; 4], tint: [u8; 3]) { + copy_sprite(image, sprite, rect, [false; 2], tint); +} + +fn text( + font: &BitmapFont, + image: &mut RgbaImage, + label: &str, + rect: [u32; 4], + tint: [u8; 3], +) -> Result<(), String> { + let [left, top, right, bottom] = rect; + let glyphs = font.centered_line(label, (right - left) as u16, (bottom - top) as u16)?; + stamp(image, &glyphs, rect, tint); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn factory_actions_follow_project_and_row_extents() { + assert_eq!( + hit_test([95.0, 132.0], 1, 2, true), + Some(FactoryAction::Project(1)) + ); + assert_eq!(hit_test([95.0, 132.0], 1, 1, true), None); + assert_eq!( + hit_test([340.0, 160.0], 1, 2, true), + Some(FactoryAction::Build) + ); + assert_eq!(hit_test([340.0, 160.0], 1, 2, false), None); + assert_eq!( + hit_test([200.0, 172.0], 1, 2, true), + Some(FactoryAction::Plant(0)) + ); + } +} diff --git a/crates/fparkan-assets/src/strategy_toolbar.rs b/crates/fparkan-assets/src/strategy_toolbar.rs index 11a3fcab..a50520c2 100644 --- a/crates/fparkan-assets/src/strategy_toolbar.rs +++ b/crates/fparkan-assets/src/strategy_toolbar.rs @@ -29,6 +29,8 @@ pub enum ToolbarAction { Hero, /// Toggle the clan's warbot list. Warbots, + /// Toggle the clan's factory panel. + Factories, /// Toggle the satellite map. Map, } @@ -39,6 +41,7 @@ pub fn command_button_at([x, y]: [f32; 2]) -> Option<ToolbarAction> { match button_index_at([x, y])? { 0 => Some(ToolbarAction::Hero), 1 => Some(ToolbarAction::Warbots), + 5 => Some(ToolbarAction::Factories), 10 => Some(ToolbarAction::Map), _ => None, } diff --git a/crates/fparkan-assets/src/warbot_card.rs b/crates/fparkan-assets/src/warbot_card.rs index 015bddce..c9608622 100644 --- a/crates/fparkan-assets/src/warbot_card.rs +++ b/crates/fparkan-assets/src/warbot_card.rs @@ -126,10 +126,20 @@ pub(super) fn paint( panel: &mut RgbaImage, lines: &[Option<CardLine<'_>>], ) -> Result<(), String> { + paint_at(font, panel, lines, [71, 203, 206], 40) +} + +pub(super) fn paint_at( + font: &BitmapFont, + panel: &mut RgbaImage, + lines: &[Option<CardLine<'_>>], + [label, number, unit]: [u32; 3], + top: u32, +) -> Result<(), String> { let height = u32::from(font.line_metrics("A")?[1]); for (index, line) in lines.iter().enumerate() { let Some(line) = line else { continue }; - let y = 40 + index as u32 * (height + 2); + let y = top + index as u32 * (height + 2); let green = [0, 255, 0]; let value = if line.warn { [255, 0, 0] @@ -137,9 +147,9 @@ pub(super) fn paint( [180, 180, 255] }; for (text, x, align_right, tint) in [ - (line.label, 71_u32, false, green), - (line.number.as_str(), 203, true, value), - (line.unit, 206, false, green), + (line.label, label, false, green), + (line.number.as_str(), number, true, value), + (line.unit, unit, false, green), ] { if text.is_empty() { continue; diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 84f1050b..206c41cb 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -212,9 +212,10 @@ pub use player_weapon::{ WeaponIndicator, WeaponLamp, }; pub use production::{ - clan_factory_schemes, factory_part_variants, factory_project_components, factory_project_root, - factory_project_schemes, factory_saved_schemes, factory_schemes, order_clan_factory_scheme, - order_factory_design, order_factory_robot, order_factory_scheme, + clan_factory_schemes, factory_panel_plants, factory_panel_project, factory_part_variants, + factory_project_components, factory_project_root, factory_project_schemes, + factory_saved_schemes, factory_schemes, order_clan_factory_scheme, order_factory_design, + order_factory_robot, order_factory_scheme, FactoryPanelPlant, FactoryPanelProject, }; pub use projectile::{ apply_projectile_contact, apply_projectile_hit, apply_projectile_impact, diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index f29cea25..d314aa88 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -24,6 +24,11 @@ use fparkan_world::{ use std::collections::VecDeque; use std::sync::Arc; +mod strategic; +pub use strategic::{ + factory_panel_plants, factory_panel_project, FactoryPanelPlant, FactoryPanelProject, +}; + // shortcut: GPU geometry is prepared for a bounded number of live builds per scheme. // Lift the cap when the renderer can instantiate new roots during a mission. pub(super) const RESERVE_SLOTS: usize = 8; diff --git a/crates/fparkan-runtime/src/production/strategic.rs b/crates/fparkan-runtime/src/production/strategic.rs new file mode 100644 index 00000000..a6dc21d3 --- /dev/null +++ b/crates/fparkan-runtime/src/production/strategic.rs @@ -0,0 +1,174 @@ +use super::{loaded_production, owned_factories, player_owner, recent_schemes_for_plant}; +use crate::{ + factory_project_root, + warbot_stats::{stats_from_table, WarbotStats}, + Engine, StartingCockpit, +}; +use fparkan_world::{registration_sequence, ObjectHandle}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FactoryPanelPlant { + pub handle: ObjectHandle, + pub label_id: u32, + pub free_minds: u32, + pub progress: Option<u8>, + pub projects: Vec<usize>, +} + +pub fn factory_panel_plants( + engine: &Engine, + cockpit: StartingCockpit, + now_ms: u32, +) -> Vec<FactoryPanelPlant> { + let Ok((mission, production)) = loaded_production(engine) else { + return Vec::new(); + }; + let Ok(owner) = player_owner(&engine.world, cockpit) else { + return Vec::new(); + }; + let capacity = mission + .ai_startup_states + .iter() + .find(|state| state.clan_index == usize::from(owner.0)) + .map_or(0, |state| state.record_slots.len()); + let free_minds = crate::clan_minds::free_slots( + capacity, + mission.mission_events.clan_classes(&engine.world, owner), + production.reserved_minds(&engine.world, owner), + ); + let mut plants: Vec<_> = owned_factories(&engine.world, mission, production, owner) + .filter_map(|(index, handle, _)| { + if mission + .control_device_tables + .iter() + .any(|table| table.handle == handle && table.node_provider_depletion_marked) + { + return None; + } + let sequence = registration_sequence(&engine.world, handle).ok()??; + let root = &mission.object_drafts[index] + .unit_components + .first()? + .resource_raw; + let size = crate::unit_size_class::classify(3, root); + let label = crate::strategic_map_readout::building_label(super::PLANT_CLASS, size); + let order = production + .pending + .iter() + .find(|order| order.plant == handle && order.owner == owner); + let progress = order.map(|order| { + let time = ratio( + now_ms.wrapping_sub(order.start_ms) as f32, + order.duration_ms as f32, + ); + let collected = order.paid.as_ref().map_or(1.0, |paid| { + ratio(paid.collected.ore, paid.cost.ore) + .min(ratio(paid.collected.power, paid.cost.power)) + }); + (time.min(collected) * 100.0).round_ties_even() as u8 + }); + let projects = recent_schemes_for_plant(mission, production, index) + .into_iter() + .map(|(id, _)| id) + .collect(); + Some(( + sequence, + FactoryPanelPlant { + handle, + label_id: label, + free_minds, + progress, + projects, + }, + )) + }) + .collect(); + plants.sort_unstable_by_key(|(sequence, _)| *sequence); + plants.into_iter().map(|(_, plant)| plant).collect() +} + +fn ratio(amount: f32, target: f32) -> f32 { + if target <= 0.0 { + 1.0 + } else { + (amount / target).clamp(0.0, 1.0) + } +} + +pub struct FactoryPanelProject { + pub prefix: [char; 3], + pub label_id: u32, + pub stats: WarbotStats, +} + +pub fn factory_panel_project(engine: &Engine, scheme: usize) -> Option<FactoryPanelProject> { + let (mission, production) = loaded_production(engine).ok()?; + let root = factory_project_root(engine, scheme)?; + let draft = &mission.object_drafts[root]; + let (role, label_id) = match draft.unit_dat_header_flags? { + 0x0100_2000 => ('T', 0x1838), + 0x0100_4000 => ('B', 0x1839), + 0x0100_8000 => ('W', 0x183a), + 0x0101_0000 => ('C', 0x183b), + _ => return None, + }; + let size = crate::unit_size_class::classify(4, &draft.unit_components.first()?.resource_raw); + let chassis = mission + .unit_chassis_flags + .get(&(root as u32)) + .and_then(|flags| flags.chassis_type) + .unwrap_or(0); + let prefix = crate::strategic_roster::unit_prefix(size, chassis, role); + let stats = stats_from_table(production.controls.get(&root)?); + Some(FactoryPanelProject { + prefix, + label_id, + stats, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[ignore = "requires licensed mission resources"] + fn stock_factory_panel_tracks_player_order_and_reserved_mind() { + use crate::{ + create, load_gameplay_mission, order_clan_factory_scheme, starting_cockpit, + EngineServices, MissionMode, MissionRequest, MissionStartupInput, + }; + use fparkan_vfs::DirectoryVfs; + use std::sync::Arc; + + let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap(); + let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap(); + load_gameplay_mission( + &mut engine, + MissionRequest { + key: "MISSIONS/Single.01/data.tma".into(), + mode: MissionMode::SingleMission, + }, + MissionStartupInput { + queue_time_ms: 0, + research_creation_gate: false, + }, + None, + ) + .unwrap(); + let cockpit = starting_cockpit(&engine).unwrap(); + let plants = factory_panel_plants(&engine, cockpit, 0); + assert_eq!(plants.len(), 1); + let plant = &plants[0]; + assert_eq!(plant.label_id, 0x17a3); + assert_eq!(plant.free_minds, 3); + assert!(plant.progress.is_none()); + let scheme = plant.projects[0]; + assert!(factory_panel_project(&engine, scheme).is_some()); + let duration = + order_clan_factory_scheme(&mut engine, cockpit, plant.handle, scheme, 100).unwrap(); + let pending = factory_panel_plants(&engine, cockpit, 100 + duration / 2); + assert_eq!(pending[0].free_minds, 2); + assert_eq!(pending[0].progress, Some(50)); + } +} diff --git a/crates/fparkan-runtime/src/strategic_map_readout.rs b/crates/fparkan-runtime/src/strategic_map_readout.rs index 33d24b0f..027dd83f 100644 --- a/crates/fparkan-runtime/src/strategic_map_readout.rs +++ b/crates/fparkan-runtime/src/strategic_map_readout.rs @@ -106,7 +106,7 @@ fn emblem_tint(own: bool, relation: Option<i32>, building: bool) -> [u8; 3] { } } -fn building_label(class: u32, size: u32) -> u32 { +pub(super) fn building_label(class: u32, size: u32) -> u32 { // iron3d+0x33a90 uses the type and Behavior's size selector. match (class, size) { (0x8000_0002, _) => 0x1799, diff --git a/crates/fparkan-runtime/src/warbot_stats.rs b/crates/fparkan-runtime/src/warbot_stats.rs index c7eab4b7..b37f5201 100644 --- a/crates/fparkan-runtime/src/warbot_stats.rs +++ b/crates/fparkan-runtime/src/warbot_stats.rs @@ -31,6 +31,10 @@ pub fn warbot_stats(engine: &Engine, handle: ObjectHandle) -> Option<WarbotStats .control_device_tables .iter() .find(|table| table.handle == handle)?; + Some(stats_from_table(table)) +} + +pub(super) fn stats_from_table(table: &MissionControlDeviceTableState) -> WarbotStats { let profile = table.owner_profile.as_ref(); let weight = profile.and_then(|profile| { let load = profile.load_projection.as_ref().ok()?; @@ -42,11 +46,11 @@ pub fn warbot_stats(engine: &Engine, handle: ObjectHandle) -> Option<WarbotStats }); let speed = profile.and_then(|profile| finite(profile.current_words[7])); let MissionControlDeviceTableStatus::Available(devices) = &table.status else { - return Some(WarbotStats { + return WarbotStats { weight, speed, ..WarbotStats::default() - }); + }; }; let weapons = devices .iter() @@ -60,13 +64,13 @@ pub fn warbot_stats(engine: &Engine, handle: ObjectHandle) -> Option<WarbotStats }); let radar = crate::radar::radar_device(table) .map_or(Some(0.0), |device| finite(device.coefficient_bits?[3])); - Some(WarbotStats { + WarbotStats { weight, speed, defence: defence(table, devices), offence: offence(weapons), radar, - }) + } } pub(super) fn durability_percent(table: &MissionControlDeviceTableState) -> Option<i32> { diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 2e125d86..1b65e662 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -323,6 +323,9 @@ seed и общий порядок Control RNG открыты. `control_resource_ Открыты подсказки в других разделах и отступ рамки при аппаратном указателе. Доступность разделов вычисляется по живым объектам клана. Отдельное состояние строения с задачей Behavior `0x12` остаётся открытым. +Раздел заводов показывает действующий одиночный заказ. Процент платной сборки +берётся из таймера и собранных ресурсов FParkan, без сверки с запросом Behavior `0x204`. +Открыты пакетный выпуск, отмена, вход в конструктор с этой панели и подсказки её кнопок. Аппаратный режим ANI, указатели остальных действий и подсветка приказа после щелчка остаются открытыми. Приказ поиска берёт кандидатов из текущего реестра Control. Отбор по diff --git a/docs/appendices/ui-shell.md b/docs/appendices/ui-shell.md index 310daa69..9592eb8a 100644 --- a/docs/appendices/ui-shell.md +++ b/docs/appendices/ui-shell.md @@ -483,6 +483,17 @@ FParkan использует для этого штатный эффект раÐ Например, в карточке LTW-3 над строкой списка появляется «Уничтожить!». [Хеши GOG-сборок](../reference/original-binaries.md) +### Заводы в стратегическом режиме + +Щелчок «Заводы» выбирает раздел 5 (RVA `0x84580`, `0x85160`). +Список в RVA `0x85720` строится по принадлежащим игроку заводам, а +RVA `0x97430` рисует выбранный проект и процент его сборки. Например, +в «Двух крепостях» можно заказать варбота на малом заводе из рубки бункера. +Выбор проекта меняет показания Control и вращающуюся модель. Размер окна +модели `115×115` и его отступ от карточки берутся из RVA `0x98240`. +Свободные ячейки клана учитывают место, зарезервированное заказом. +[Хеши GOG-сборок](../reference/original-binaries.md) + ### Приказы варботу Панель начинается на X = 100 сразу под списком. `iron3d.dll` по RVA |
