//! Menus: the main menu, the pause menu, Settings and How to Play. //! //! While a menu is open the simulation is paused (the clock speed is saved and //! restored), map clicks and hover are ignored (`map.rs`), and gameplay hotkeys //! are ignored (`hud.rs`, `economy.rs`). Esc is handled here. use bevy::app::AppExit; use bevy::ecs::hierarchy::ChildSpawnerCommands; use bevy::picking::hover::Hovered; use bevy::prelude::*; use bevy::ui::Display; use bevy::ui_widgets::{Activate, Button}; use crate::economy::advance_clock; use crate::front::reset_game; use crate::model::{SimClock, Tool}; use crate::settings::{self, Settings, WindowModeSetting}; const PANEL: Color = Color::srgba(0.18, 0.2, 0.14, 0.97); const OVERLAY: Color = Color::srgba(0.07, 0.08, 0.05, 0.9); const PARCH: Color = Color::srgb(0.92, 0.88, 0.76); const AMBER: Color = Color::srgb(0.95, 0.68, 0.2); const BTN: Color = Color::srgba(0.27, 0.29, 0.21, 0.95); const BTN_HOVER: Color = Color::srgba(0.35, 0.37, 0.27, 0.98); /// Values the settings rows cycle through. const RESOLUTIONS: [[u32; 2]; 4] = [[1280, 720], [1600, 900], [1920, 1080], [2560, 1440]]; const WINDOW_MODES: [WindowModeSetting; 3] = [ WindowModeSetting::Windowed, WindowModeSetting::Borderless, WindowModeSetting::Fullscreen, ]; /// 0 is unlimited. const FPS_STEPS: [u32; 5] = [30, 60, 120, 144, 0]; /// Text and UI size multipliers, on top of the window-height scale. const TEXT_SIZES: [f32; 8] = [0.8, 0.9, 1.0, 1.15, 1.3, 1.5, 1.75, 2.0]; const HOW_TO_PLAY: [&str; 10] = [ "Goal: keep the three front sectors (right) supplied with Ammo, Food and Troops.", "Home side: factories make Ammo, farms make Food, the capital and cities make Troops.", "Supplied fronts push the red line east. Lose if any sector is pushed back to its limit.", "Drag from one node to another to send its goods. Air raids can bomb track.", "Track is laid through stations on the way, and a train is bought.", "A train only carries what its stops load. Plan before you drag.", "Bombed track is orange, or red with a gap. Click it (wrench mark) to repair for $150.", "Cities go hungry without Food. Hungry cities slow war production everywhere.", "Wounded go to a city or the capital (hospital). Hospital trains carry only wounded.", "Space pauses, 1/2/3 set speed. Right-drag pans, wheel zooms. Esc opens menu. H or ? shows help.", ]; #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] pub enum MenuScreen { #[default] Main, Pause, Settings, HowToPlay, } /// Which menu screen is open. `screen` is `None` while playing. #[derive(Resource, Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Menu { pub screen: Option, /// Where Settings and How to Play go back to. pub return_to: MenuScreen, } impl Menu { pub fn is_open(&self) -> bool { self.screen.is_some() } fn is_sub_screen(&self) -> bool { matches!( self.screen, Some(MenuScreen::Settings | MenuScreen::HowToPlay) ) } fn show(&mut self, next: MenuScreen) { if matches!(next, MenuScreen::Settings | MenuScreen::HowToPlay) && !self.is_sub_screen() { self.return_to = self.screen.unwrap_or(MenuScreen::Main); } self.screen = Some(next); } /// Esc and Back: sub-screens return, the pause menu closes, the main menu stays. fn go_back(&mut self) { self.screen = match self.screen { Some(MenuScreen::Settings | MenuScreen::HowToPlay) => Some(self.return_to), Some(MenuScreen::Pause) => None, other => other, }; } } pub struct MenuPlugin; impl Plugin for MenuPlugin { fn build(&self, app: &mut App) { app.add_observer(on_menu_action) .add_systems(Startup, spawn_root) .add_systems( Update, ( menu_escape, sync_pause.before(advance_clock), render_menu, update_menu_buttons, ), ); } } /// Esc: a menu open means back. Otherwise it cancels the current tool, or opens /// the pause menu when the tool is already Inspect. fn menu_escape(keys: Res>, mut menu: ResMut, mut tool: ResMut) { if !keys.just_pressed(KeyCode::Escape) { return; } if menu.is_open() { menu.go_back(); } else if !matches!(*tool, Tool::Inspect) { *tool = Tool::Inspect; } else { menu.show(MenuScreen::Pause); } } /// Holds the clock at speed 0 while a menu is open, and restores the speed when /// it closes. A speed that was changed while paused (a restart sets 1x) is kept. fn sync_pause(menu: Res, mut clock: ResMut, mut saved: Local>) { if menu.is_open() { if saved.is_none() { *saved = Some(clock.speed); } if clock.speed != 0 { clock.speed = 0; } } else if let Some(speed) = saved.take() && clock.speed == 0 { clock.speed = speed; } } #[derive(Component)] struct MenuRoot; /// The panel inside the overlay. Its children are rebuilt for each screen. #[derive(Component)] struct MenuContent; /// What a menu button does when pressed. #[derive(Component, Clone, Copy)] enum MenuAction { NewOperation, Resume, Quit, Go(MenuScreen), Back, Step(Setting, i32), } /// Settings rows, in the order they are shown. #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Setting { Resolution, WindowMode, VSync, FpsLimit, ShowPerf, TextSize, Master, Effects, Ambient, Mute, } fn spawn_root(mut commands: Commands) { commands.spawn(( MenuRoot, Node { position_type: PositionType::Absolute, left: Val::Px(0.0), right: Val::Px(0.0), top: Val::Px(0.0), bottom: Val::Px(0.0), justify_content: JustifyContent::Center, align_items: AlignItems::Center, display: Display::None, ..default() }, BackgroundColor(OVERLAY), GlobalZIndex(200), children![( MenuContent, Node { flex_direction: FlexDirection::Column, align_items: AlignItems::Center, row_gap: Val::Px(14.0), padding: UiRect::all(Val::Px(28.0)), border: UiRect::all(Val::Px(2.0)), ..default() }, BackgroundColor(PANEL), BorderColor::all(AMBER), )], )); } fn text(value: &str, size: f32, color: Color) -> impl Bundle { ( Text::new(value), TextFont::from_font_size(size), TextColor(color), ) } fn menu_button(parent: &mut ChildSpawnerCommands, label: &str, width: f32, action: MenuAction) { parent .spawn(( Button, Node { width: Val::Px(width), height: Val::Px(36.0), align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..default() }, BackgroundColor(BTN), Hovered::default(), action, )) .with_children(|b| { b.spawn(text(label, 18.0, PARCH)); }); } /// Shows the overlay for the open screen and rebuilds its content when needed. fn render_menu( mut commands: Commands, menu: Res, settings: Res, mut roots: Query<&mut Node, With>, contents: Query>, ) { let target = if menu.is_open() { Display::Flex } else { Display::None }; for mut node in &mut roots { if node.display != target { node.display = target; } } if !(menu.is_changed() || settings.is_changed()) { return; } let Ok(content) = contents.single() else { return; }; let mut entity = commands.entity(content); entity.despawn_related::(); let Some(screen) = menu.screen else { return; }; entity.with_children(|p| match screen { MenuScreen::Main => main_screen(p), MenuScreen::Pause => pause_screen(p), MenuScreen::HowToPlay => how_to_play_screen(p), MenuScreen::Settings => settings_screen(p, &settings), }); } fn main_screen(p: &mut ChildSpawnerCommands) { p.spawn(text("IRON LIFELINE", 48.0, AMBER)); p.spawn((text("Keep the front alive.", 20.0, PARCH), Node { margin: UiRect::bottom(Val::Px(12.0)), ..default() })); menu_button(p, "New Operation", 280.0, MenuAction::NewOperation); menu_button(p, "How to Play", 280.0, MenuAction::Go(MenuScreen::HowToPlay)); menu_button(p, "Settings", 280.0, MenuAction::Go(MenuScreen::Settings)); menu_button(p, "Quit", 280.0, MenuAction::Quit); } fn pause_screen(p: &mut ChildSpawnerCommands) { p.spawn(text("PAUSED", 36.0, AMBER)); menu_button(p, "Resume", 280.0, MenuAction::Resume); menu_button(p, "How to Play", 280.0, MenuAction::Go(MenuScreen::HowToPlay)); menu_button(p, "Settings", 280.0, MenuAction::Go(MenuScreen::Settings)); menu_button(p, "Main Menu", 280.0, MenuAction::Go(MenuScreen::Main)); menu_button(p, "Quit", 280.0, MenuAction::Quit); } fn how_to_play_screen(p: &mut ChildSpawnerCommands) { p.spawn(text("HOW TO PLAY", 30.0, AMBER)); p.spawn(Node { flex_direction: FlexDirection::Column, row_gap: Val::Px(7.0), width: Val::Px(760.0), ..default() }) .with_children(|lines| { for line in HOW_TO_PLAY { lines.spawn(text(line, 15.0, PARCH)); } }); menu_button(p, "Back", 280.0, MenuAction::Back); } fn settings_screen(p: &mut ChildSpawnerCommands, settings: &Settings) { let d = &settings.display; let a = &settings.audio; p.spawn(text("SETTINGS", 30.0, AMBER)); let rows = [ ("Resolution", resolution_text(d.resolution), Setting::Resolution), ("Window mode", window_mode_text(d.window_mode), Setting::WindowMode), ("VSync", on_off(d.vsync), Setting::VSync), ("FPS limit", fps_text(d.fps_limit), Setting::FpsLimit), ("Show performance", on_off(d.show_performance), Setting::ShowPerf), ("Text size", percent(d.text_size), Setting::TextSize), ("Master volume", percent(a.master), Setting::Master), ("Effects volume", percent(a.effects), Setting::Effects), ("Ambient volume", percent(a.ambient), Setting::Ambient), ("Mute", on_off(a.muted), Setting::Mute), ]; for (name, value, which) in rows { setting_row(p, name, &value, which); } menu_button(p, "Back", 280.0, MenuAction::Back); } /// One settings line: name, [<] value [>]. fn setting_row(p: &mut ChildSpawnerCommands, name: &str, value: &str, which: Setting) { p.spawn(Node { width: Val::Px(520.0), justify_content: JustifyContent::SpaceBetween, align_items: AlignItems::Center, ..default() }) .with_children(|r| { r.spawn(( text(name, 17.0, PARCH), Node { width: Val::Px(210.0), ..default() }, )); r.spawn(Node { align_items: AlignItems::Center, column_gap: Val::Px(8.0), ..default() }) .with_children(|c| { menu_button(c, "<", 36.0, MenuAction::Step(which, -1)); c.spawn(( text(value, 17.0, AMBER), Node { width: Val::Px(180.0), justify_content: JustifyContent::Center, ..default() }, )); menu_button(c, ">", 36.0, MenuAction::Step(which, 1)); }); }); } fn on_off(on: bool) -> String { if on { "On" } else { "Off" }.to_string() } fn percent(v: f32) -> String { format!("{}%", (v * 100.0).round() as i32) } fn resolution_text(r: [u32; 2]) -> String { format!("{}x{}", r[0], r[1]) } fn window_mode_text(mode: WindowModeSetting) -> String { match mode { WindowModeSetting::Windowed => "Windowed", WindowModeSetting::Borderless => "Borderless", WindowModeSetting::Fullscreen => "Fullscreen", } .to_string() } fn fps_text(fps: u32) -> String { if fps == 0 { "Unlimited".to_string() } else { fps.to_string() } } /// Position of `value` in `list`, or 0 when the file holds an unlisted value. fn index_of(list: &[T], value: &T) -> usize { list.iter().position(|v| v == value).unwrap_or(0) } /// Moves one step through a list and stops at the ends. fn step_index(index: usize, len: usize, dir: i32) -> usize { (index as i32 + dir).clamp(0, len as i32 - 1) as usize } /// Volume moves in steps of 10%. fn step_volume(v: f32, dir: i32) -> f32 { let tenths = (v * 10.0).round() as i32; (tenths + dir).clamp(0, 10) as f32 / 10.0 } fn step(settings: &mut Settings, which: Setting, dir: i32) { let d = &mut settings.display; let a = &mut settings.audio; match which { Setting::Resolution => { let i = index_of(&RESOLUTIONS[..], &d.resolution); d.resolution = RESOLUTIONS[step_index(i, RESOLUTIONS.len(), dir)]; } Setting::WindowMode => { let i = index_of(&WINDOW_MODES[..], &d.window_mode); d.window_mode = WINDOW_MODES[step_index(i, WINDOW_MODES.len(), dir)]; } Setting::VSync => d.vsync = !d.vsync, Setting::FpsLimit => { let i = index_of(&FPS_STEPS[..], &d.fps_limit); d.fps_limit = FPS_STEPS[step_index(i, FPS_STEPS.len(), dir)]; } Setting::ShowPerf => d.show_performance = !d.show_performance, Setting::TextSize => { let i = index_of(&TEXT_SIZES[..], &d.text_size); d.text_size = TEXT_SIZES[step_index(i, TEXT_SIZES.len(), dir)]; } Setting::Master => a.master = step_volume(a.master, dir), Setting::Effects => a.effects = step_volume(a.effects, dir), Setting::Ambient => a.ambient = step_volume(a.ambient, dir), Setting::Mute => a.muted = !a.muted, } } fn on_menu_action( ev: On, actions: Query<&MenuAction>, mut menu: ResMut, mut settings: ResMut, mut exit: MessageWriter, mut commands: Commands, ) { let Ok(action) = actions.get(ev.entity) else { return; }; match *action { MenuAction::NewOperation => { menu.screen = None; commands.queue(|world: &mut World| reset_game(world)); } MenuAction::Resume => menu.screen = None, MenuAction::Quit => { exit.write(AppExit::Success); } MenuAction::Go(screen) => menu.show(screen), MenuAction::Back => menu.go_back(), MenuAction::Step(which, dir) => { // Compare on a copy so an unchanged value does not mark the resource changed. let mut next = settings.clone(); step(&mut next, which, dir); if next != *settings { *settings = next; settings::save(&settings); } } } } fn update_menu_buttons(mut buttons: Query<(&Hovered, &mut BackgroundColor), With>) { for (hovered, mut bg) in &mut buttons { let target = if hovered.get() { BTN_HOVER } else { BTN }; if bg.0 != target { bg.0 = target; } } }