//! Mission selection before loading a world into the game window. use fparkan_assets::{ game_font::{load_menu_font, BitmapFont}, mission_catalog::MissionCatalog, }; use fparkan_vfs::Vfs; use winit::{ dpi::{PhysicalPosition, PhysicalSize}, event::{ElementState, MouseButton, WindowEvent}, keyboard::{Key, NamedKey}, window::Window, }; const EXTENT: [u32; 2] = [960, 540]; const LEFT: usize = 56; const TOP: usize = 132; const WIDTH: usize = 848; const ROW_HEIGHT: usize = 42; const VISIBLE_ROWS: usize = 8; const GAP: usize = 6; const BACKGROUND: u32 = 0x141c24; pub(super) struct LaunchMenu { catalog: MissionCatalog, font: BitmapFont, screen: Screen, selected: usize, pointer: Option>, } #[derive(Clone, Copy)] enum Screen { Main, Start, Campaigns, Campaign(usize), Single, } struct Row<'a> { label: &'a str, action: Action<'a>, } #[derive(Clone, Copy)] enum Action<'a> { Open(Screen), Launch(&'a str), Exit, } pub(super) enum MenuEvent { None, Redraw, Launch(String), Exit, } impl LaunchMenu { pub(super) fn open(vfs: &dyn Vfs) -> Result { if !cfg!(windows) { return Err("the mission menu requires a Win32 window; specify --mission".into()); } let catalog = MissionCatalog::load(vfs)?; if catalog.campaigns.is_empty() && catalog.single.is_empty() && catalog.demo.is_none() { return Err("no missions with a descr caption found in the game directory".into()); } Ok(Self { catalog, font: load_menu_font(vfs)?, screen: Screen::Main, selected: 0, pointer: None, }) } fn rows(&self) -> Vec> { let mut rows = Vec::new(); match self.screen { Screen::Main => { if let Some(demo) = &self.catalog.demo { rows.push(Row { label: "Демо", action: Action::Launch(&demo.key), }); } if !self.catalog.campaigns.is_empty() || !self.catalog.single.is_empty() { rows.push(Row { label: "Начать игру", action: Action::Open(Screen::Start), }); } rows.push(Row { label: "Выход", action: Action::Exit, }); } Screen::Start => { if !self.catalog.campaigns.is_empty() { rows.push(Row { label: "Кампании", action: Action::Open(Screen::Campaigns), }); } if !self.catalog.single.is_empty() { rows.push(Row { label: "Одиночные миссии", action: Action::Open(Screen::Single), }); } } Screen::Campaigns => { rows.extend( self.catalog .campaigns .iter() .enumerate() .map(|(index, campaign)| Row { label: &campaign.title, action: Action::Open(Screen::Campaign(index)), }), ); } Screen::Campaign(index) => { rows.extend( self.catalog.campaigns[index] .missions .iter() .map(|mission| Row { label: &mission.title, action: Action::Launch(&mission.key), }), ); } Screen::Single => { rows.extend(self.catalog.single.iter().map(|mission| Row { label: &mission.title, action: Action::Launch(&mission.key), })); } } if let Some(parent) = self.parent() { rows.push(Row { label: "Назад", action: Action::Open(parent), }); } rows } fn parent(&self) -> Option { match self.screen { Screen::Main => None, Screen::Start => Some(Screen::Main), Screen::Campaigns | Screen::Single => Some(Screen::Start), Screen::Campaign(_) => Some(Screen::Campaigns), } } fn enter(&mut self, screen: Screen) -> MenuEvent { self.screen = screen; self.selected = 0; MenuEvent::Redraw } fn activate(&mut self, index: usize) -> MenuEvent { match self.rows().get(index).map(|row| row.action) { Some(Action::Open(screen)) => self.enter(screen), Some(Action::Launch(key)) => MenuEvent::Launch(key.to_string()), Some(Action::Exit) => MenuEvent::Exit, None => MenuEvent::None, } } pub(super) fn input(&mut self, event: &WindowEvent, size: PhysicalSize) -> MenuEvent { match event { WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => { match event.logical_key { Key::Named(NamedKey::ArrowUp | NamedKey::ArrowDown) => { let count = self.rows().len(); let step = if event.logical_key == Key::Named(NamedKey::ArrowUp) { count - 1 } else { 1 }; self.selected = (self.selected + step) % count; MenuEvent::Redraw } Key::Named(NamedKey::Enter) if !event.repeat => self.activate(self.selected), Key::Named(NamedKey::Escape) if !event.repeat => match self.parent() { Some(parent) => self.enter(parent), None => MenuEvent::Exit, }, _ => MenuEvent::None, } } WindowEvent::CursorMoved { position, .. } => { self.pointer = Some(*position); match self.hit(size) { Some(index) if index != self.selected => { self.selected = index; MenuEvent::Redraw } _ => MenuEvent::None, } } WindowEvent::CursorLeft { .. } | WindowEvent::Resized(_) => { self.pointer = None; MenuEvent::None } WindowEvent::MouseInput { state: ElementState::Pressed, button: MouseButton::Left, .. } => match self.hit(size) { Some(index) => self.activate(index), None => MenuEvent::None, }, _ => MenuEvent::None, } } fn hit(&self, size: PhysicalSize) -> Option { let cursor = self.pointer?; if size.width == 0 || size.height == 0 { return None; } let x = cursor.x * f64::from(EXTENT[0]) / f64::from(size.width); let y = cursor.y * f64::from(EXTENT[1]) / f64::from(size.height); if x < LEFT as f64 || x >= (LEFT + WIDTH) as f64 || y < TOP as f64 { return None; } let row = (y as usize - TOP) / ROW_HEIGHT; let first = self.first_row(); (row < VISIBLE_ROWS && (y as usize - TOP) % ROW_HEIGHT < ROW_HEIGHT - GAP && first + row < self.rows().len()) .then_some(first + row) } fn first_row(&self) -> usize { self.selected.saturating_sub(VISIBLE_ROWS - 1) } pub(super) fn paint(&self, _window: &Window) -> Result<(), String> { #[cfg(windows)] { let pixels = self.frame()?; fparkan_platform_winit::startup_window::paint(_window, EXTENT, &pixels) .map_err(|error| format!("draw mission menu: {error}"))?; } Ok(()) } fn frame(&self) -> Result, String> { let mut frame = vec![BACKGROUND; EXTENT[0] as usize * EXTENT[1] as usize]; let title = match self.screen { Screen::Main => "FParkan", Screen::Start => "Начать игру", Screen::Campaigns => "Кампании", Screen::Campaign(index) => &self.catalog.campaigns[index].title, Screen::Single => "Одиночные миссии", }; self.text(&mut frame, title, [LEFT, 57], 2)?; let rows = self.rows(); let first = self.first_row(); for (visible, row) in rows[first..].iter().take(VISIBLE_ROWS).enumerate() { let top = TOP + visible * ROW_HEIGHT; let selected = first + visible == self.selected; let color = if selected { 0x205960 } else { 0x26333d }; fill(&mut frame, LEFT, top, WIDTH, ROW_HEIGHT - GAP, color); if selected { fill(&mut frame, LEFT, top, 4, ROW_HEIGHT - GAP, 0x65dacc); } self.text(&mut frame, row.label, [LEFT + 20, top + 9], 1)?; } Ok(frame) } fn text( &self, frame: &mut [u32], label: &str, at: [usize; 2], scale: usize, ) -> Result<(), String> { let [width, height] = self.font.line_metrics(label)?; let source = self.font.centered_line(label, width, height)?; for y in 0..source.height as usize * scale { if at[1] + y >= EXTENT[1] as usize { break; } for x in 0..(source.width as usize * scale).min(LEFT + WIDTH - at[0]) { let src = (y / scale * source.width as usize + x / scale) * 4; let index = (at[1] + y) * EXTENT[0] as usize + at[0] + x; let alpha = u32::from(source.rgba8[src + 3]); if alpha == 0 { continue; } let background = frame[index]; let mut pixel = 0; for (channel, shift) in [16, 8, 0].into_iter().enumerate() { let foreground = u32::from(source.rgba8[src + channel]); let back = (background >> shift) & 0xff; pixel |= ((foreground * alpha + back * (255 - alpha)) / 255) << shift; } frame[index] = pixel; } } Ok(()) } } fn fill(frame: &mut [u32], x: usize, y: usize, width: usize, height: usize, color: u32) { for row in y..y + height { let start = row * EXTENT[0] as usize + x; frame[start..start + width].fill(color); } }