upgrade to bevy 0.20

This commit is contained in:
2026-10-20 23:59:48 -05:00
parent 4607f12756
commit 25557d85ce
7 changed files with 1626 additions and 1591 deletions
+241 -313
View File
@@ -7,9 +7,11 @@ use bevy::input_focus::{
AutoFocus, FocusCause, InputFocus, InputFocusVisible,
tab_navigation::{TabGroup, TabIndex},
};
use bevy::picking::hover::Hovered;
use bevy::text::{EditableText, EditableTextFilter, TextCursorStyle};
use bevy::ui::Pressed;
use bevy::ui::auto_directional_navigation::AutoDirectionalNavigation;
use bevy::ui_widgets::Button;
use bevy::ui_widgets::{Button, TextInput};
use bevy::{prelude::*, ui_widgets::Activate};
use derive_more::{Deref, DerefMut};
@@ -19,7 +21,6 @@ impl Plugin for MainMenuPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::Menu), setup_menu)
.add_systems(OnExit(AppState::Menu), cleanup_menu)
// .add_systems(Startup, enable_ui_debug)
.add_systems(Update, (menu_redraw).run_if(in_state(AppState::Menu)))
.add_observer(button_activate_observer)
.add_systems(Update, (scale_ui, style_ui_elements))
@@ -45,15 +46,15 @@ struct Selected;
/// Defines colors that a UI object should turn when interactions occur.
#[derive(Component, Clone, PartialEq, Default, Debug)]
pub(crate) struct InteractionColors {
default: Color,
hovered: Color,
pressed: Color,
selected: Color,
selected_hovered: Color,
selected_pressed: Color,
pub(crate) default_outline: Color,
pub(crate) focused_outline: Color,
pub struct InteractionColors {
pub default: Color,
pub hovered: Color,
pub pressed: Color,
pub selected: Color,
pub selected_hovered: Color,
pub selected_pressed: Color,
pub default_outline: Color,
pub focused_outline: Color,
}
impl InteractionColors {
pub const DEFAULT: InteractionColors = InteractionColors {
@@ -122,25 +123,27 @@ impl MenuLayer {
fn render(&self, layer: usize, menu_root: Entity) -> Box<dyn Scene> {
match self {
MenuLayer::Root => Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Play", Some(MenuLayer::Play)),
menu_button("Settings", Some(MenuLayer::Settings)),
(
menu_button("Quit", None)
@menu_button("Play", Some(MenuLayer::Play))
--
@menu_button("Settings", Some(MenuLayer::Settings))
--
@menu_button("Quit", None)
on(|_event: On<Activate>, mut exit: MessageWriter<AppExit>| { exit.write(AppExit::Success); } )
InteractionColors::DANGER
),
]
}),
MenuLayer::Play => Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Load Save", Some(MenuLayer::LoadSave)),
menu_button("Browse Games", Some(MenuLayer::Browse)),
menu_button("Direct Connect", Some(MenuLayer::DirectConnect)),
@menu_button("Load Save", Some(MenuLayer::LoadSave))
--
@menu_button("Browse Games", Some(MenuLayer::Browse))
--
@menu_button("Direct Connect", Some(MenuLayer::DirectConnect))
]
}),
MenuLayer::LoadSave => {
@@ -155,40 +158,39 @@ impl MenuLayer {
// TODO: get rid of row gap when many saves are present.
Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
{entries},
(
menu_button("New Game", Some(MenuLayer::NewGame))
InteractionColors::GOOD
),
{entries}
--
@menu_button("New Game", Some(MenuLayer::NewGame))
InteractionColors::GOOD
]
})
}
MenuLayer::NewGame => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
{new_game_menu()}
]
}),
MenuLayer::GameInfo(game) => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
{game_info_menu(game)}
]
}),
MenuLayer::Browse => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Game 1", None)
@menu_button("Game 1", None)
]
}),
MenuLayer::DirectConnect => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
// TODO: have IP addr text box here
@@ -196,22 +198,23 @@ impl MenuLayer {
]
}),
MenuLayer::Settings => Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Controls", Some(MenuLayer::Controls)),
menu_button("Graphics", Some(MenuLayer::Graphics)),
@menu_button("Controls", Some(MenuLayer::Controls))
--
@menu_button("Graphics", Some(MenuLayer::Graphics))
]
}),
MenuLayer::Controls => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
Text("Controls..")
]
}),
MenuLayer::Graphics => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
Text("Graphics..")
@@ -228,13 +231,6 @@ struct LastMenu(Vec<MenuLayer>);
#[derive(Resource, Debug, Clone, PartialEq, Eq, Hash, Deref, DerefMut)]
struct CurrentMenu(Vec<MenuLayer>);
// fn enable_ui_debug(mut debug_options: ResMut<GlobalUiDebugOptions>) {
// debug_options.enabled = true;
// debug_options.outline_border_box = true;
// debug_options.outline_padding_box = true;
// debug_options.outline_content_box = true;
// }
fn setup_menu(mut commands: Commands) {
commands.insert_resource(CurrentMenu(vec![MenuLayer::Root]));
commands.insert_resource(LastMenu(vec![]));
@@ -297,172 +293,163 @@ fn menu_redraw(
}
fn new_game_menu() -> impl SceneList {
bsn_list![
(
Text("New Game")
bsn_list! {
Text("New Game")
Node {
align_self: AlignSelf::Center,
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(100.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
--
Text("Save Name")
Node {
margin: UiRect::axes(px(12), px(0)),
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(66.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
--
#NewGameTextField
GameNameTextField
Node {
border: Val::all(px(6)),
padding: Val::all(px(12)),
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
}
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric())
TextLayout::no_wrap()
TextFont {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
--
Node {
margin: UiRect::top(px(48)),
}
Children [
@menu_button("Create", None)
InteractionColors::GOOD
Node {
align_self: AlignSelf::Center,
margin: UiRect::left(Val::Auto),
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(100.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
Text("Save Name")
Node {
margin: UiRect::axes(px(12), px(0)),
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(66.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
#NewGameTextField
GameNameTextField
Node {
border: Val::all(px(6)),
padding: Val::all(px(12)),
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
}
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric())
TextLayout::no_wrap()
TextFont {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
),
(
Node {
margin: UiRect::top(px(48)),
}
Children [
menu_button("Create", None)
InteractionColors::GOOD
Node {
margin: UiRect::left(Val::Auto),
}
on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>| {
let value = text_field.value();
info!("Create triggered for: {}", value);
create_game_save(value.to_string()).unwrap();
// TODO: refresh listing
})
]
),
]
on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>| {
let value = text_field.value();
info!("Create triggered for: {}", value);
create_game_save(value.to_string()).unwrap();
// TODO: refresh listing
})
]
}
}
fn game_info_menu(name: impl Into<String>) -> impl SceneList {
let name = name.into();
bsn_list![
(
#GameInfoTitle
Text("Load Save")
bsn_list! {
#GameInfoTitle
Text("Load Save")
Node {
align_self: AlignSelf::Center,
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(100.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
--
Text("Save Name")
Node {
margin: UiRect::axes(px(12), px(0)),
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(66.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
--
#SaveNameTextField
GameNameTextField
Node {
border: Val::all(px(6)),
padding: Val::all(px(12)),
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText::new(name)
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
}
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric())
TextLayout::no_wrap()
TextFont {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
--
Node {
margin: UiRect::top(px(48)),
}
Children [
@menu_button("Delete", None)
InteractionColors::DANGER
Node {
align_self: AlignSelf::Center,
margin: UiRect::right(Val::Auto),
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(100.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
Text("Save Name")
on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>| {
let value = text_field.value();
info!("Delete triggered for: {}", value);
delete_game_save(value.to_string()).unwrap();
// TODO: refresh listing
})
--
// TODO: when the user changed the name of the game, change this to a "rename" button
@menu_button("Play", None)
InteractionColors::GOOD
Node {
margin: UiRect::axes(px(12), px(0)),
margin: UiRect::left(Val::Auto),
}
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
font_size: px(66.0),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
#SaveNameTextField
GameNameTextField
Node {
border: Val::all(px(6)),
padding: Val::all(px(12)),
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
EditableText::new(name)
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
}
EditableTextFilter::new(|c| c == ' ' || c.is_ascii_alphanumeric())
TextLayout::no_wrap()
TextFont {
font_size: FontSize::Px(66.),
}
TextCursorStyle {
color: Color::BLACK,
}
AutoDirectionalNavigation::default()
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
),
(
Node {
margin: UiRect::top(px(48)),
}
Children [
(
menu_button("Delete", None)
InteractionColors::DANGER
Node {
margin: UiRect::right(Val::Auto),
}
on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>| {
let value = text_field.value();
info!("Delete triggered for: {}", value);
delete_game_save(value.to_string()).unwrap();
// TODO: refresh listing
})
),
(
// TODO: when the user changed the name of the game, change this to a "rename" button
menu_button("Play", None)
InteractionColors::GOOD
Node {
margin: UiRect::left(Val::Auto),
}
on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>, mut commands: Commands, mut app_state: ResMut<NextState<AppState>>| {
// TODO: we should definately get this value from an added
// resource. Call it something like `SelectedGameSave`
let value = text_field.value().to_string();
info!("Play triggered for: {}", value);
commands.insert_resource(ActiveGameSave::new(value));
app_state.set(AppState::Lobby);
on(|_event: On<Activate>, text_field: Single<&EditableText, With<GameNameTextField>>, mut commands: Commands, mut app_state: ResMut<NextState<AppState>>| {
// TODO: we should definately get this value from an added
// resource. Call it something like `SelectedGameSave`
let value = text_field.value().to_string();
info!("Play triggered for: {}", value);
commands.insert_resource(ActiveGameSave::new(value));
app_state.set(AppState::Lobby);
// TODO: refresh listing
})
),
]
),
]
// TODO: refresh listing
})
]
}
}
fn menu_layer(layer: usize) -> impl Scene {
@@ -500,6 +487,14 @@ fn full_menu_layer(layer: usize) -> impl Scene {
fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<dyn Scene> {
let label = label.into();
let next_layer: Box<dyn Scene> = if let Some(next_layer) = next_layer {
Box::new(bsn! {
NextLayer(next_layer)
})
} else {
Box::new(bsn! {})
};
Box::new(bsn! {
Button
AutoDirectionalNavigation::default()
@@ -513,11 +508,12 @@ fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<d
align_items: AlignItems::Center,
margin: UiRect::all(px(4)),
}
{next_layer.map(|l| template_value(NextLayer(l)))}
@next_layer
BorderColor::from(Color::BLACK)
InteractionColors::DEFAULT
Interaction
Children [(
// TODO: add interaction component here if neccesary
Hovered
Children [
Text(label)
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
@@ -525,7 +521,7 @@ fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<d
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
)]
]
})
}
@@ -555,7 +551,7 @@ fn button_activate_observer(
// push next layer
menu.push(next_layer.0.clone());
for (entity, selected) in q_selected.iter_many(layer_entries) {
for (entity, selected) in q_selected.iter_many(layer_entries).matched() {
if entity == event.entity {
if !selected {
commands.entity(entity).insert(Selected);
@@ -570,28 +566,50 @@ fn button_activate_observer(
/// Styles the UI elements according to their [`InteractionColors`].
fn style_ui_elements(
input_focus: Res<InputFocus>,
mut elements: Query<(
Entity,
&Interaction,
&mut BackgroundColor,
&InteractionColors,
Has<Selected>,
)>,
mut q_elements: Query<
(
Entity,
Option<&Hovered>,
Has<Pressed>,
Option<&mut BackgroundColor>,
Option<&mut BorderColor>,
&InteractionColors,
Has<Selected>,
),
Or<(With<BackgroundColor>, With<BorderColor>)>,
>,
) {
let focused_entity = input_focus.get();
for (entity, interaction, mut bg, colors, selected) in &mut elements {
let new_color = match (selected, *interaction) {
(true, Interaction::Pressed) => colors.selected_pressed,
(true, Interaction::Hovered) => colors.selected_hovered,
(true, Interaction::None) => colors.selected,
(false, Interaction::Pressed) => colors.pressed,
(false, Interaction::Hovered) => colors.hovered,
(false, Interaction::None) if focused_entity == Some(entity) => colors.hovered,
(false, Interaction::None) => colors.default,
for (entity, hovered, pressed, bg, border, colors, selected) in &mut q_elements {
let is_focused = focused_entity == Some(entity);
// if the entity is focused, its similar to it being hovered.
let hovered = hovered.is_some_and(|h| h.get()) || is_focused;
let new_color = match (selected, pressed, hovered) {
(true, true, _) => colors.selected_pressed,
(true, false, true) => colors.selected_hovered,
(true, false, false) => colors.selected,
(false, true, _) => colors.pressed,
(false, false, true) => colors.hovered,
(false, false, false) => colors.default,
};
if bg.0 != new_color {
bg.0 = new_color;
if let Some(mut border) = border {
if is_focused {
if border.top != colors.focused_outline {
border.set_all(colors.focused_outline);
}
} else {
if border.top != colors.default_outline {
border.set_all(colors.default_outline);
}
}
}
if let Some(mut bg) = bg {
if bg.0 != new_color {
bg.0 = new_color;
}
}
}
}
@@ -602,6 +620,7 @@ fn scale_ui(mut ui_scale: ResMut<UiScale>, window: Single<&Window>) {
ui_scale.0 = scale_factor;
}
// TODO: generify the inputing of the nav inputs that are in here
fn focus_rightmost_layer_on_navigation(
keyboard: Res<ButtonInput<KeyCode>>,
gamepads: Query<&Gamepad>,
@@ -671,94 +690,3 @@ fn first_focusable_in_layer(
.iter()
.find_map(|child| first_focusable_in_layer(child, children, focusable_entities))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::focus_navigation::navigate_directionally;
use bevy::{
input_focus::directional_navigation::{
DirectionalNavigationMap, DirectionalNavigationPlugin,
},
math::CompassOctant,
};
#[test]
fn focus_uses_hover_color_while_selected_keeps_selected_color() {
let mut app = App::new();
let colors = InteractionColors::DEFAULT;
let focused = app
.world_mut()
.spawn((
Interaction::None,
BackgroundColor(colors.default),
colors.clone(),
))
.id();
let selected = app
.world_mut()
.spawn((
Interaction::None,
BackgroundColor(colors.default),
colors.clone(),
Selected,
))
.id();
app.world_mut()
.insert_resource(InputFocus::from_entity(focused));
app.add_systems(Update, style_ui_elements);
app.update();
assert_eq!(
app.world().get::<BackgroundColor>(focused).unwrap().0,
colors.hovered
);
assert_eq!(
app.world().get::<BackgroundColor>(selected).unwrap().0,
colors.selected
);
}
#[test]
fn first_directional_input_only_focuses_first_item_in_rightmost_layer() {
let mut app = App::new();
app.add_plugins(DirectionalNavigationPlugin);
let left_layer = app.world_mut().spawn(Layer(0)).id();
app.world_mut()
.spawn((AutoDirectionalNavigation::default(), ChildOf(left_layer)));
let right_layer = app.world_mut().spawn(Layer(1)).id();
let first_right_item = app
.world_mut()
.spawn((AutoDirectionalNavigation::default(), ChildOf(right_layer)))
.id();
let next_right_item = app
.world_mut()
.spawn((AutoDirectionalNavigation::default(), ChildOf(right_layer)))
.id();
app.world_mut().insert_resource(InputFocus::default());
app.world_mut().insert_resource(InputFocusVisible(false));
app.world_mut().init_resource::<NavigationInputState>();
app.world_mut().init_resource::<ButtonInput<KeyCode>>();
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.press(KeyCode::ArrowRight);
app.world_mut()
.resource_mut::<DirectionalNavigationMap>()
.add_edge(first_right_item, next_right_item, CompassOctant::East);
app.add_systems(
PreUpdate,
(focus_rightmost_layer_on_navigation, navigate_directionally).chain(),
);
app.update();
assert_eq!(
app.world().resource::<InputFocus>().get(),
Some(first_right_item)
);
assert!(app.world().resource::<InputFocusVisible>().0);
}
}