bevy_codex/main_menu/
systems.rs1use bevy::{color::palettes::css::BLACK, prelude::*, window::PrimaryWindow};
2
3use bevy_lunex::{
4 prelude::{MainUi, Pickable, Rl, UiNodeTreeInitTrait, UiTree},
5 Base, MovableByCamera, PackageLayout, UiClickEvent, UiImage2dBundle, UiLayout, UiLink,
6 UiTreeBundle,
7};
8
9use crate::{
10 loading::components::Loading,
11 main_menu::components::MainMenuButton,
12 resources::CodexSettings,
13 settings::components::SettingsPg,
14 widgets::{
15 button::components::{CustomButton, CustomButtonRef},
16 panel::components::Panel,
17 },
18};
19
20use super::components::MainMenu;
21
22pub fn build_main_menu(
23 mut commands: Commands,
24 asset_server: Res<AssetServer>,
25 query: Query<Entity, Added<MainMenu>>,
26 window: Query<&Window, With<PrimaryWindow>>,
27 codex_settings: Res<CodexSettings>,
28) {
29 for route_entity in &query {
30 if let Ok(resolution) = window.get_single() {
31 let r_size = (resolution.width(), resolution.height());
32 commands
33 .entity(route_entity)
34 .insert(SpatialBundle::default())
35 .with_children(|route| {
36 route
37 .spawn((
38 UiTreeBundle::<MainUi>::from(UiTree::new2d("MainMenu")),
39 MovableByCamera,
40 ))
41 .with_children(|ui| {
42 let root = UiLink::<MainUi>::path("Root");
43 ui.spawn((
44 root.clone(),
45 UiLayout::window().size(r_size).pack::<Base>(),
46 ));
47 let background = UiLink::<MainUi>::path("Background");
48
49 ui.spawn((
50 background.clone(),
51 UiLayout::window_full().pack::<Base>(),
52 Pickable::IGNORE,
53 UiImage2dBundle::from(asset_server.load("Level_base_diffuse.png")),
54 ));
55 let content = vec![
56 CustomButtonRef {
57 link: MainMenuButton::NewGame.str(),
58 },
59 CustomButtonRef {
60 link: MainMenuButton::Settings.str(),
61 },
62 CustomButtonRef {
63 link: MainMenuButton::QuitGame.str(),
64 },
65 ];
66 ui.spawn((
67 background.add("Panel"),
68 UiLayout::window()
69 .size(Rl((40.0, 80.0)))
70 .pos(Rl((10.0, 10.0)))
71 .pack::<Base>(),
72 Panel {
73 text: Some(codex_settings.title.to_string()),
74 color: BLACK.into(),
75 content,
76 ..default()
77 },
78 Pickable::IGNORE,
79 ));
80 });
81 });
82 }
83 }
84}
85
86pub fn main_menu_button_clicked_system(
87 mut commands: Commands,
88 mut events: EventReader<UiClickEvent>,
89 query: Query<&CustomButton>,
90 menu_q: Query<Entity, With<MainMenu>>,
91 mut exit: EventWriter<bevy::app::AppExit>,
92) {
93 for event in events.read() {
94 if let Ok(ent) = menu_q.get_single() {
95 if let Ok(button) = query.get(event.target) {
96 if button.text == MainMenuButton::NewGame.str() {
97 commands.entity(ent).despawn_recursive();
98 commands.spawn(Loading(Some("Loading...".to_string())));
99 } else if button.text == MainMenuButton::Settings.str() {
100 commands.entity(ent).despawn_recursive();
101 commands.spawn(SettingsPg);
102 } else if button.text == MainMenuButton::QuitGame.str() {
103 commands.entity(event.target).despawn_recursive();
104 exit.send(bevy::app::AppExit::Success);
105 }
106 }
107 }
108 }
109}