//! Project selection and the installed parts of the selected Unit DAT. use crate::{ designer_categories::contains, factory_projects::PROJECT_SLOTS, game_font::{load_game_font, BitmapFont}, mission_pager::{copy_sprite, scale, UiFrame}, object_descriptions::ObjectDescriptions, ui_sprite::{atlas_region, load_ui_page}, RgbaImage, }; use encoding_rs::WINDOWS_1251; use fparkan_prototype::UnitComponentRecord; use fparkan_vfs::Vfs; pub use crate::designer_categories::{DesignerCategory, DesignerPartsPane}; pub use crate::designer_sockets::{designer_sockets, DesignerSocket}; const SEND: [u32; 4] = [194, 437, 229, 480]; const EXIT: [u32; 4] = [405, 437, 446, 480]; const SAVE: [u32; 4] = [269, 437, 304, 480]; const LOAD: [u32; 4] = [304, 437, 339, 480]; const NAME_BOX: [u32; 4] = [270, 410, 370, 430]; /// Extent of the designer's original font profile. pub const EXTENT: [u32; 2] = [800, 600]; /// Native inset used to frame the assembled robot, in 640×480 coordinates. pub const MODEL_VIEWPORT: [f32; 4] = [195.0, 10.0, 445.0, 300.0]; /// Number of part rows in the project viewport. pub const PART_ROWS: usize = crate::designer_categories::DESIGNER_PARTS_ROWS; /// Number of visible projects in the original file picker. pub const FILE_ROWS: usize = 4; /// Controls in logical 640×480 coordinates. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DesignerAction { /// Restore a recent project in the designer. Project(usize), /// Show the selected installed-part category. Category(DesignerCategory), /// Choose the installed mount to inspect. Part(usize), /// Choose a named mount, including a socket without an installed part. Socket(usize), /// Install a researched variant at the inspected mount. Variant(usize), /// Move a list by one row. Scroll(DesignerPartsPane, bool), /// Assign the currently open project to the factory. Send, /// Open the save name field. Save, /// Open the list of saved projects. Load, /// Return to the factory panel. Exit, } /// Original strings that label the currently supported designer actions. pub struct DesignerLabels { /// Constructor title. pub title: String, /// Recent project list. pub recent: String, /// Transfer to the connected factory. pub send: String, /// Save project command. pub save: String, /// Load project command. pub load: String, /// Prompt next to the save name field. pub filename: String, /// Close the designer. pub exit: String, /// Original category titles in screen order. pub categories: [String; 6], /// Caption for the parts catalogue. pub parts_panel: String, /// Caption for the assembled model. pub model_panel: String, } struct EquipmentSprites { tab: [RgbaImage; 2], icons: [RgbaImage; 6], row: RgbaImage, row_marker: [RgbaImage; 2], scroll_bar: RgbaImage, scroll_button: [RgbaImage; 2], scroll_icon: [RgbaImage; 2], } /// Original UI resources required by the project view of the designer. pub struct DesignerScreen { font: BitmapFont, frame: UiFrame, descriptions: ObjectDescriptions, recent: RgbaImage, send: RgbaImage, send_frame: RgbaImage, save: RgbaImage, load: RgbaImage, load_frame: RgbaImage, exit: RgbaImage, exit_frame: RgbaImage, equipment: EquipmentSprites, labels: DesignerLabels, } /// Selection and scroll state to compose on the screen. pub struct DesignerPicture<'a> { /// Number of populated history slots. pub count: usize, /// Previewed project name and parts, when a slot has been opened. pub project: Option<(usize, &'a str, &'a [UnitComponentRecord])>, /// First component row in the pane. pub first_part: usize, /// First available replacement shown in the opposite pane. pub first_variant: usize, /// Installed part category displayed in the model pane. pub category: DesignerCategory, /// Selected record and the available equipment for it. pub variants: Option<(DesignerAction, &'a [String])>, /// External model mounts, including empty ones. pub sockets: &'a [DesignerSocket], /// Action whose original tooltip is shown. pub hover: Option, /// Active project file control. pub file_dialog: Option>, /// Result of the last file operation. pub file_status: Option<&'a str>, /// Whether the displayed model is connected to a production scheme. pub buildable: bool, } /// View of the name editor or the current page of saved projects. pub enum DesignerFileView<'a> { /// Project name typed by the player. Save(&'a str), /// Project names in the four visible rows. Load(&'a [&'a str]), } impl DesignerScreen { /// Reads the original sheets, display font and prototype descriptions. pub fn load(vfs: &dyn Vfs, labels: DesignerLabels) -> Result { let icons = load_ui_page(vfs, "icons")?; let frames = load_ui_page(vfs, "page4")?; let controls = load_ui_page(vfs, "page1")?; let sprite = |page: &RgbaImage, [x, y, width, height]: [u32; 4]| { atlas_region(page, [x, y, width, height]) .ok_or_else(|| format!("designer sprite outside its page at {x},{y}")) }; let category_icons = DesignerCategory::ALL .iter() .map(|category| sprite(&icons, category.tab().2)) .collect::, _>>()? .try_into() .map_err(|_| "designer category icon count mismatch")?; Ok(Self { font: load_game_font(vfs)?, frame: UiFrame::load(vfs)?, descriptions: ObjectDescriptions::load(vfs)?, recent: sprite(&icons, [216, 96, 24, 24])?, send: sprite(&icons, [176, 231, 24, 24])?, send_frame: sprite(&frames, [84, 169, 35, 43])?, save: sprite(&icons, [152, 231, 24, 24])?, load: sprite(&icons, [128, 231, 24, 24])?, load_frame: sprite(&frames, [119, 169, 35, 43])?, exit: sprite(&icons, [192, 72, 24, 24])?, exit_frame: sprite(&frames, [141, 213, 41, 43])?, equipment: EquipmentSprites { tab: [ sprite(&frames, [0, 106, 26, 37])?, sprite(&frames, [27, 106, 26, 37])?, ], icons: category_icons, row: sprite(&frames, [0, 22, 180, 21])?, row_marker: [ sprite(&controls, [178, 141, 17, 21])?, sprite(&controls, [195, 141, 17, 21])?, ], scroll_bar: sprite(&frames, [0, 0, 130, 21])?, scroll_button: [ sprite(&controls, [216, 78, 15, 21])?, sprite(&controls, [231, 78, 18, 21])?, ], scroll_icon: [ sprite(&icons, [154, 0, 11, 11])?, sprite(&icons, [154, 11, 11, 11])?, ], }, labels, }) } /// Paints the opaque panes that sit behind the rotating model. pub fn paint_background(&self) -> RgbaImage { let [width, height] = EXTENT; let mut image = RgbaImage { width, height, rgba8: vec![0; (width * height * 4) as usize], }; for pixel in image.rgba8.chunks_exact_mut(4) { pixel[3] = 255; } self.frame .paint(&mut image, [185, 2, 455, 480], [0, 48, 0, 255]); self.frame .paint(&mut image, [462, 2, 637, 265], [0, 48, 0, 255]); image } /// Paints project actions over the model and part descriptions in Unit DAT order. pub fn paint(&self, view: DesignerPicture<'_>) -> Result { let [width, height] = EXTENT; let mut image = RgbaImage { width, height, rgba8: vec![0; (width * height * 4) as usize], }; self.text( &mut image, &self.labels.title, [194, 319, 446, 335], [255; 3], )?; self.text( &mut image, &self.labels.recent, [199, 250, 350, 268], [100, 255, 100], )?; let selected = view.project.map(|(index, _, _)| index); for index in 0..view.count.min(PROJECT_SLOTS) { let tint = if selected == Some(index) { [255; 3] } else { [160; 3] }; sprite(&mut image, &self.recent, recent_slot(index), tint); } self.paint_equipment(&mut image, &view)?; if let Some((_, name, _)) = view.project { self.text(&mut image, name, [194, 300, 446, 316], [255, 255, 100])?; if view.buildable { sprite(&mut image, &self.send_frame, SEND, [255; 3]); sprite(&mut image, &self.send, [201, 450, 225, 474], [255; 3]); sprite(&mut image, &self.send_frame, SAVE, [255; 3]); sprite(&mut image, &self.save, [278, 450, 302, 474], [255; 3]); } } sprite(&mut image, &self.load_frame, LOAD, [255; 3]); sprite(&mut image, &self.load, [308, 450, 332, 474], [255; 3]); sprite(&mut image, &self.exit_frame, EXIT, [255; 3]); sprite(&mut image, &self.exit, [413, 450, 437, 474], [255; 3]); if let Some(message) = view.file_status { self.text(&mut image, message, [194, 365, 446, 386], [255, 255, 100])?; } if let Some(dialog) = view.file_dialog { match dialog { DesignerFileView::Save(name) => { self.text( &mut image, &self.labels.filename, [194, 389, 446, 407], [255; 3], )?; self.frame.paint(&mut image, NAME_BOX, [0, 24, 0, 255]); self.text(&mut image, &format!("{name}_"), NAME_BOX, [255; 3])?; } DesignerFileView::Load(files) => { self.frame .paint(&mut image, [262, 352, 378, 432], [0, 24, 0, 255]); for (row, filename) in files.iter().take(FILE_ROWS).enumerate() { self.text(&mut image, filename, file_row(row), [255; 3])?; } } } return Ok(image); } let hint = match view.hover { Some(DesignerAction::Send) => &self.labels.send, Some(DesignerAction::Save) => &self.labels.save, Some(DesignerAction::Load) => &self.labels.load, Some(DesignerAction::Exit) => &self.labels.exit, Some(DesignerAction::Category(category)) => self.category_title(category), _ => return Ok(image), }; self.text(&mut image, hint, [194, 418, 446, 436], [255; 3])?; Ok(image) } fn category_title(&self, category: DesignerCategory) -> &str { &self.labels.categories[category as usize] } fn paint_equipment( &self, image: &mut RgbaImage, view: &DesignerPicture<'_>, ) -> Result<(), String> { use DesignerPartsPane::{Model, Parts}; let records = view.project.map_or(&[][..], |(_, _, records)| records); let variants = view.variants.map_or(&[][..], |(_, names)| names); for pane in [Parts, Model] { let x = pane.left(); let title = match pane { Parts => &self.labels.parts_panel, Model => &self.labels.model_panel, }; self.text(image, title, [x + 10, 2, x + 180, 15], [255, 255, 0])?; for (index, category) in DesignerCategory::ALL.into_iter().enumerate() { let enabled = match pane { Parts => category == view.category && !variants.is_empty(), Model => model_rows(category, records, view.sockets).next().is_some(), }; let selected = enabled && category == view.category; let (frame, icon, _) = category.tab(); let frame = x + frame; let icon = x + icon; sprite( image, &self.equipment.tab[usize::from(selected)], [frame, 16, frame + 26, 53], [255; 3], ); let top = if pane == Model && category == DesignerCategory::Armour { 26 } else { 25 }; sprite( image, &self.equipment.icons[index], [icon, top, icon + 24, top + 24], category.tint(enabled, selected), ); } } let mounts = model_rows(view.category, records, view.sockets).collect::>(); for (row, &mount) in mounts .iter() .skip(view.first_part) .take(PART_ROWS) .enumerate() { let label = mounted_record(mount, view.sockets) .and_then(|index| records.get(index)) .map_or(b"".as_slice(), |record| { self.part_label(field(&record.resource_raw), field(&record.description_raw)) }); self.paint_row( image, label, Model, row, view.variants.is_some_and(|(selected, _)| selected == mount), )?; } let installed = view .variants .and_then(|(mount, _)| records.get(mounted_record(mount, view.sockets)?)) .map(|part| field(&part.resource_raw)); for (row, name) in variants .iter() .skip(view.first_variant) .take(PART_ROWS) .enumerate() { let resource = name.as_bytes(); self.paint_row( image, self.part_label(resource, resource), Parts, row, installed.is_some_and(|part| part.eq_ignore_ascii_case(resource)), )?; } for (pane, count) in [(Model, mounts.len()), (Parts, variants.len())] { if count <= PART_ROWS { continue; } let x = pane.left(); sprite( image, &self.equipment.scroll_bar, [x + 5, 203, x + 147, 224], [255; 3], ); for (index, forward) in [false, true].into_iter().enumerate() { let bounds = pane.arrow(forward); sprite( image, &self.equipment.scroll_button[index], bounds, [255; 3], ); let left = bounds[0] + u32::from(!forward); let top = if forward { 206 } else { 207 }; sprite( image, &self.equipment.scroll_icon[index], [left, top, left + 13, top + 13], [255; 3], ); } } Ok(()) } fn part_label<'a>(&'a self, key: &'a [u8], description: &'a [u8]) -> &'a [u8] { self.descriptions .short_name(key) .filter(|name| !name.is_empty()) .unwrap_or(if description.is_empty() { key } else { description }) } fn paint_row( &self, image: &mut RgbaImage, text: &[u8], pane: DesignerPartsPane, row: usize, selected: bool, ) -> Result<(), String> { let [left, top, right, bottom] = pane.row(row); sprite( image, &self.equipment.row, [left, top, right, bottom], [255; 3], ); sprite( image, &self.equipment.row_marker[usize::from(selected)], [left, top, left + 17, bottom], [255; 3], ); let [width, glyph_height] = self.font.line_metrics_bytes(text)?; let left = scale(left + 10); let top = scale(top + 7); let width = width.min((scale(right) - left) as u16); if width != 0 { let glyphs = self.font.centered_line_bytes(text, width, glyph_height)?; copy_sprite( image, &glyphs, [ left, top, left + u32::from(width), top + u32::from(glyph_height), ], [false; 2], if selected { [255, 255, 100] } else { [255; 3] }, ); } Ok(()) } fn text( &self, image: &mut RgbaImage, text: &str, bounds: [u32; 4], tint: [u8; 3], ) -> Result<(), String> { let [l, t, r, b] = bounds.map(scale); let (bytes, _, _) = WINDOWS_1251.encode(text); let labels = self .font .centered_line_bytes(&bytes, (r - l) as u16, (b - t) as u16)?; copy_sprite(image, &labels, [l, t, r, b], [false; 2], tint); Ok(()) } } /// Maps pointer input to a populated history slot or available command. pub fn hit_test([x, y]: [f32; 2], count: usize, has_project: bool) -> Option { let hit = |[l, t, r, b]: [u32; 4]| x >= l as f32 && x < r as f32 && y >= t as f32 && y < b as f32; if hit(EXIT) { return Some(DesignerAction::Exit); } if has_project && hit(SEND) { return Some(DesignerAction::Send); } if has_project && hit(SAVE) { return Some(DesignerAction::Save); } if hit(LOAD) { return Some(DesignerAction::Load); } (0..count.min(PROJECT_SLOTS)) .find(|&index| hit(recent_slot(index))) .map(DesignerAction::Project) } fn file_row(row: usize) -> [u32; 4] { let top = 354 + 18 * row as u32; [270, top, 370, top + 18] } /// Converts a pointer position to a populated file row. pub fn project_file_hit([x, y]: [f32; 2], visible: usize) -> Option { (0..visible.min(FILE_ROWS)).find(|&row| { let [l, t, r, b] = file_row(row).map(|coordinate| coordinate as f32); (l..r).contains(&x) && (t..b).contains(&y) }) } /// Hits a populated mount or variant row using the coordinates used to paint it. pub fn equipment_hit( cursor: [f32; 2], category: DesignerCategory, first_part: usize, records: &[UnitComponentRecord], first_variant: usize, variants: usize, sockets: &[DesignerSocket], ) -> Option { use DesignerPartsPane::{Model, Parts}; if let Some(category) = category_hit(cursor, records, sockets) { return Some(DesignerAction::Category(category)); } let pane = DesignerPartsPane::at(cursor)?; let count = match pane { Parts => variants, Model => model_rows(category, records, sockets).count(), }; if count > PART_ROWS { for forward in [false, true] { if contains(pane.arrow(forward), cursor) { return Some(DesignerAction::Scroll(pane, forward)); } } } let row = (0..PART_ROWS).find(|&row| contains(pane.row(row), cursor))?; match pane { Parts => { (first_variant + row < variants).then_some(DesignerAction::Variant(first_variant + row)) } Model => model_rows(category, records, sockets).nth(first_part + row), } } /// Finds an enabled category tab in the model panel. pub fn category_hit( cursor: [f32; 2], records: &[UnitComponentRecord], sockets: &[DesignerSocket], ) -> Option { DesignerCategory::ALL.into_iter().find(|&category| { let (left, _, _) = category.tab(); let left = left + DesignerPartsPane::Model.left(); let hit_width = 26 + u32::from(matches!( category, DesignerCategory::Chassis | DesignerCategory::Armour )); contains([left, 16, left + hit_width, 53], cursor) && model_rows(category, records, sockets).next().is_some() }) } /// Rows of one equipment category in native mount order. pub fn model_rows<'a>( category: DesignerCategory, records: &'a [UnitComponentRecord], sockets: &'a [DesignerSocket], ) -> impl Iterator + 'a { sockets .iter() .enumerate() .filter_map(move |(index, socket)| { (socket.category == category).then_some(DesignerAction::Socket(index)) }) .chain(category.mounts(records).filter_map(|part| { (!sockets.iter().any(|socket| socket.part == Some(part))) .then_some(DesignerAction::Part(part)) })) } fn mounted_record(mount: DesignerAction, sockets: &[DesignerSocket]) -> Option { match mount { DesignerAction::Part(part) => Some(part), DesignerAction::Socket(socket) => sockets.get(socket)?.part, _ => None, } } fn recent_slot(index: usize) -> [u32; 4] { let left = 200 + 30 * index as u32; [left, 270, left + 24, 294] } fn field(raw: &[u8; 32]) -> &[u8] { raw.split(|&byte| byte == 0).next().unwrap_or_default() } fn sprite(image: &mut RgbaImage, source: &RgbaImage, rect: [u32; 4], tint: [u8; 3]) { copy_sprite(image, source, rect.map(scale), [false; 2], tint); } #[cfg(test)] mod tests { use super::*; #[test] fn project_picker_uses_populated_slots_and_needs_a_project_to_send() { assert_eq!( hit_test([240.0, 278.0], 2, false), Some(DesignerAction::Project(1)) ); assert_eq!(hit_test([240.0, 278.0], 1, false), None); assert_eq!(hit_test([201.0, 455.0], 2, false), None); assert_eq!( hit_test([201.0, 455.0], 2, true), Some(DesignerAction::Send) ); assert_eq!( hit_test([420.0, 455.0], 0, false), Some(DesignerAction::Exit) ); } #[test] fn equipment_click_addresses_the_scrolled_mount_or_a_populated_variant() { let make_part = |role| UnitComponentRecord { archive_raw: [0; 32], resource_raw: [0; 32], kind: 1, parent_or_link: -1, description_raw: [0; 32], tail0: role, immediate_child_count: 0, }; let records = [0, 3, 4, 3, 4, 3, 3, 3, 3, 3].map(make_part); let action = |cursor| equipment_hit(cursor, DesignerCategory::Systems, 1, &records, 2, 8, &[]); assert_eq!( action([491.0, 24.0]), Some(DesignerAction::Category(DesignerCategory::Chassis)) ); assert_eq!(action([494.0, 24.0]), None, "the turret category is empty"); assert_eq!(action([500.0, 65.0]), Some(DesignerAction::Part(3))); assert_eq!(action([500.0, 88.0]), Some(DesignerAction::Part(5))); assert_eq!(action([500.0, 86.0]), None, "gap between original rows"); assert_eq!(action([30.0, 65.0]), Some(DesignerAction::Variant(2))); assert_eq!( action([629.0, 210.0]), Some(DesignerAction::Scroll(DesignerPartsPane::Model, true)) ); assert_eq!( DesignerCategory::Weapon .mounts(&records) .collect::>(), [2, 4] ); } #[test] fn an_empty_socket_enables_its_category_and_has_its_own_row() { let sockets = [ DesignerSocket { category: DesignerCategory::Weapon, parent: 1, node: 6, family: "universal_lr".into(), part: None, }, DesignerSocket { category: DesignerCategory::Weapon, parent: 1, node: 7, family: "universal_lr".into(), part: None, }, ]; let action = |cursor| equipment_hit(cursor, DesignerCategory::Weapon, 0, &[], 0, 0, &sockets); assert_eq!( action([526.0, 28.0]), Some(DesignerAction::Category(DesignerCategory::Weapon)) ); assert_eq!(action([521.0, 73.0]), Some(DesignerAction::Socket(0))); assert_eq!(action([521.0, 96.0]), Some(DesignerAction::Socket(1))); } }