Mostly updated to bevy 0.13

main
Elijah C. Voigt 2 years ago
parent d3c2289d41
commit 877f7001b1

@ -2,9 +2,6 @@
/// TODO: Custom Asset: FmodEventMapper /// TODO: Custom Asset: FmodEventMapper
/// ///
use crate::prelude::*; use crate::prelude::*;
use bevy::prelude::*;
use bevy_fmod::prelude::AudioSource;
use bevy_fmod::prelude::*;
pub(crate) struct AudioPlugin; pub(crate) struct AudioPlugin;
@ -28,8 +25,8 @@ impl Plugin for AudioPlugin {
( (
play_audio.run_if(any_component_added::<AudioSource>()), play_audio.run_if(any_component_added::<AudioSource>()),
audio_trigger.run_if(on_event::<AudioEvent>()), audio_trigger.run_if(on_event::<AudioEvent>()),
control_volume.run_if(resource_changed::<AudioVolume>()), control_volume.run_if(resource_changed::<AudioVolume>),
toggle_volume.run_if(just_pressed(KeyCode::M)), toggle_volume.run_if(just_pressed(KeyCode::KeyM)),
), ),
); );
} }

@ -56,7 +56,7 @@ fn init_credits_ui(
Credits, Credits,
TextBundle { TextBundle {
text: Text { text: Text {
alignment: TextAlignment::Center, justify: JustifyText::Center,
sections: vec![], sections: vec![],
..default() ..default()
}, },

@ -1,12 +1,3 @@
use bevy::{
diagnostic::{
DiagnosticsStore, EntityCountDiagnosticsPlugin, FrameTimeDiagnosticsPlugin,
SystemInformationDiagnosticsPlugin,
},
input::{keyboard::KeyboardInput, ButtonState},
utils::{hashbrown::hash_map::Iter, HashMap},
};
use crate::prelude::*; use crate::prelude::*;
pub(crate) struct DebugPlugin; pub(crate) struct DebugPlugin;
@ -28,19 +19,19 @@ impl Plugin for DebugPlugin {
.add_systems( .add_systems(
Update, Update,
( (
selected_gizmo.run_if(any_with_component::<game::Selected>()), selected_gizmo.run_if(any_with_component::<game::Selected>),
selected_position.run_if(any_with_component::<game::Selected>()), selected_position.run_if(any_with_component::<game::Selected>),
) )
.run_if(resource_exists::<DebugEnabled>()), .run_if(resource_exists::<DebugEnabled>),
) )
.add_systems(Startup, init_debug_ui) .add_systems(Startup, init_debug_ui)
.add_systems( .add_systems(
Update, Update,
( (
toggle_debug_mode.run_if(on_event::<KeyboardInput>()), toggle_debug_mode.run_if(on_event::<KeyboardInput>()),
display_diagnostics.run_if(resource_exists::<DebugEnabled>()), display_diagnostics.run_if(resource_exists::<DebugEnabled>),
toggle_debug_ui.run_if(resource_changed_or_removed::<DebugEnabled>()), toggle_debug_ui.run_if(resource_changed_or_removed::<DebugEnabled>()),
camera_info.run_if(resource_exists::<DebugEnabled>()), camera_info.run_if(resource_exists::<DebugEnabled>),
), ),
); );
} }
@ -84,7 +75,7 @@ fn toggle_debug_mode(
.filter( .filter(
|KeyboardInput { |KeyboardInput {
state, key_code, .. state, key_code, ..
}| *state == ButtonState::Pressed && *key_code == Some(KeyCode::F3), }| *state == ButtonState::Pressed && *key_code == KeyCode::F3,
) )
.for_each(|_| match enabled { .for_each(|_| match enabled {
Some(_) => commands.remove_resource::<DebugEnabled>(), Some(_) => commands.remove_resource::<DebugEnabled>(),
@ -137,7 +128,7 @@ fn display_diagnostics(
root.iter_mut().for_each(|mut text| { root.iter_mut().for_each(|mut text| {
text.sections = diagnostics text.sections = diagnostics
.iter() .iter()
.map(|d| format!("{}: {:.0}\n", d.name, d.smoothed().unwrap_or(0.0),)) .map(|d| format!("{}: {:.0}\n", d.suffix, d.smoothed().unwrap_or(0.0),))
.chain(debug_infos.iter().map(|(k, v)| format!("{}: {}\n", k, v))) .chain(debug_infos.iter().map(|(k, v)| format!("{}: {}\n", k, v)))
.map(|s| TextSection::new(s, TextStyle { ..default() })) .map(|s| TextSection::new(s, TextStyle { ..default() }))
.collect(); .collect();
@ -166,21 +157,21 @@ fn aabb_gizmo(
mut commands: Commands, mut commands: Commands,
) { ) {
added.iter().for_each(|e| { added.iter().for_each(|e| {
commands.entity(e).insert(AabbGizmo { commands.entity(e).insert(ShowAabbGizmo {
color: Some(Color::RED), color: Some(Color::RED),
}); });
}); });
removed.read().for_each(|e| { removed.read().for_each(|e| {
commands.entity(e).remove::<AabbGizmo>(); commands.entity(e).remove::<ShowAabbGizmo>();
}); });
match active { match active {
Some(_) => selected.iter().for_each(|e| { Some(_) => selected.iter().for_each(|e| {
commands.entity(e).insert(AabbGizmo { commands.entity(e).insert(ShowAabbGizmo {
color: Some(Color::RED), color: Some(Color::RED),
}); });
}), }),
None => selected.iter().for_each(|e| { None => selected.iter().for_each(|e| {
commands.entity(e).remove::<AabbGizmo>(); commands.entity(e).remove::<ShowAabbGizmo>();
}), }),
} }
} }

@ -1,33 +1,4 @@
use crate::{ use crate::prelude::*;
game::{Board, BoardIndex, Piece, Side},
prelude::*,
tweak::Tweaks,
};
use bevy::{
animation::RepeatAnimation,
core_pipeline::{
bloom::BloomSettings,
experimental::taa::{TemporalAntiAliasPlugin, TemporalAntiAliasSettings},
prepass::MotionVectorPrepass,
tonemapping::{DebandDither, Tonemapping},
Skybox,
},
input::{
mouse::{MouseButtonInput, MouseMotion, MouseScrollUnit, MouseWheel},
ButtonState,
},
pbr::{
ExtendedMaterial, MaterialExtension, ScreenSpaceAmbientOcclusionBundle,
ScreenSpaceAmbientOcclusionSettings,
},
render::{
render_resource::{AsBindGroup, ShaderRef, TextureViewDescriptor, TextureViewDimension},
view::ColorGrading,
},
utils::HashMap,
window::PrimaryWindow,
};
use tweaks::*;
pub(crate) struct Display3dPlugin; pub(crate) struct Display3dPlugin;
@ -43,7 +14,7 @@ impl Plugin for Display3dPlugin {
( (
initialize, initialize,
fix_skybox.before(initialize), fix_skybox.before(initialize),
update_tweaks.run_if(resource_exists::<tweak::GameTweaks>()), update_tweaks.run_if(resource_exists::<tweak::GameTweaks>),
), ),
) )
.add_systems( .add_systems(
@ -62,7 +33,7 @@ impl Plugin for Display3dPlugin {
set_piece_position.run_if(any_component_changed::<BoardIndex>()), set_piece_position.run_if(any_component_changed::<BoardIndex>()),
set_piece_texture set_piece_texture
.run_if(any_component_changed::<Side>()) .run_if(any_component_changed::<Side>())
.run_if(resource_exists::<tweak::GameTweaks>()), .run_if(resource_exists::<tweak::GameTweaks>),
select select
.run_if(in_state(GameState::Play)) .run_if(in_state(GameState::Play))
.run_if(in_state(DisplayState::Display3d)) .run_if(in_state(DisplayState::Display3d))
@ -71,10 +42,10 @@ impl Plugin for Display3dPlugin {
put_down.run_if(any_component_removed::<game::Selected>()), put_down.run_if(any_component_removed::<game::Selected>()),
switch_sides switch_sides
.run_if(in_state(GameState::Play)) .run_if(in_state(GameState::Play))
.run_if(state_changed::<game::TurnState>()), .run_if(state_changed::<game::TurnState>),
update_tweaks update_tweaks
.run_if(on_event::<AssetEvent<Tweaks>>()) .run_if(on_event::<AssetEvent<Tweaks>>())
.run_if(resource_exists::<tweak::GameTweaks>()), .run_if(resource_exists::<tweak::GameTweaks>),
scale_lighting.run_if( scale_lighting.run_if(
any_component_added::<DirectionalLight>() any_component_added::<DirectionalLight>()
.or_else(any_component_added::<SpotLight>()) .or_else(any_component_added::<SpotLight>())
@ -82,9 +53,9 @@ impl Plugin for Display3dPlugin {
.or_else(on_event::<AssetEvent<Tweaks>>()), .or_else(on_event::<AssetEvent<Tweaks>>()),
), ),
setup_capture_piece.run_if(any_component_changed::<Handle<StandardMaterial>>()), setup_capture_piece.run_if(any_component_changed::<Handle<StandardMaterial>>()),
capture_piece.run_if(any_with_component::<game::Captured>()), capture_piece.run_if(any_with_component::<game::Captured>),
skip_animation skip_animation
.run_if(just_pressed(KeyCode::Return).or_else(just_pressed(MouseButton::Left))) .run_if(just_pressed(KeyCode::Enter).or_else(just_pressed(MouseButton::Left)))
.run_if(in_state(GameState::Play)), .run_if(in_state(GameState::Play)),
), ),
) )
@ -96,9 +67,9 @@ impl Plugin for Display3dPlugin {
gizmo_system, gizmo_system,
selected_gizmo, selected_gizmo,
moves_gizmo, moves_gizmo,
debug_selected.run_if(any_with_component::<game::Selected>()), debug_selected.run_if(any_with_component::<game::Selected>),
) )
.run_if(resource_exists::<debug::DebugEnabled>()) .run_if(resource_exists::<debug::DebugEnabled>)
.run_if(in_state(GameState::Play)) .run_if(in_state(GameState::Play))
.run_if(in_state(DisplayState::Display3d)), .run_if(in_state(DisplayState::Display3d)),
) )
@ -112,8 +83,8 @@ impl Plugin for Display3dPlugin {
.add_systems( .add_systems(
OnEnter(GameState::Play), OnEnter(GameState::Play),
( (
set_piece_texture.run_if(resource_exists::<tweak::GameTweaks>()), set_piece_texture.run_if(resource_exists::<tweak::GameTweaks>),
update_tweaks.run_if(resource_exists::<tweak::GameTweaks>()), update_tweaks.run_if(resource_exists::<tweak::GameTweaks>),
opening_animation opening_animation
.run_if(run_once()) .run_if(run_once())
.run_if(in_state(DisplayState::Display3d)), .run_if(in_state(DisplayState::Display3d)),
@ -142,7 +113,7 @@ fn load_assets(
mut meshes: ResMut<Assets<Mesh>>, mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>, mut materials: ResMut<Assets<StandardMaterial>>,
) { ) {
let hitbox_shape = meshes.add(shape::Box::new(1.0, 0.1, 1.0).into()); let hitbox_shape = meshes.add(Cuboid::new(1.0, 0.1, 1.0));
let hitbox_material = materials.add(StandardMaterial { let hitbox_material = materials.add(StandardMaterial {
base_color: Color::NONE, base_color: Color::NONE,
perceptual_roughness: 0.0, perceptual_roughness: 0.0,
@ -278,12 +249,15 @@ fn hydrate_camera(
..default() ..default()
}, },
BloomSettings { ..default() }, BloomSettings { ..default() },
Skybox(skybox_handle.clone()), Skybox {
image: skybox_handle.clone(),
brightness: 1.0,
},
EnvironmentMapLight { EnvironmentMapLight {
diffuse_map: skybox_handle.clone(), diffuse_map: skybox_handle.clone(),
specular_map: skybox_handle.clone(), specular_map: skybox_handle.clone(),
intensity: 1.0,
}, },
UiCameraConfig { show_ui: true },
FogSettings { ..default() }, FogSettings { ..default() },
ScreenSpaceAmbientOcclusionBundle { ..default() }, ScreenSpaceAmbientOcclusionBundle { ..default() },
TemporalAntiAliasSettings { ..default() }, TemporalAntiAliasSettings { ..default() },
@ -341,25 +315,26 @@ fn update_tweaks(
camera_settings.iter_mut().for_each( camera_settings.iter_mut().for_each(
|(entity, mut fog, mut color_grading, mut tonemapping, mut bloom)| { |(entity, mut fog, mut color_grading, mut tonemapping, mut bloom)| {
*fog = tweak *fog = tweak
.get::<TweakFogSettings>("display3d_fog") .get::<tweaks::TweakFogSettings>("display3d_fog")
.unwrap() .unwrap()
.into(); .into();
*color_grading = tweak *color_grading = tweak
.get::<TweakColorGrading>("display3d_color_grading") .get::<tweaks::TweakColorGrading>("display3d_color_grading")
.unwrap() .unwrap()
.into(); .into();
*tonemapping = tweak *tonemapping = tweak
.get::<TweakTonemapping>("display3d_color_tonemapping") .get::<tweaks::TweakTonemapping>("display3d_color_tonemapping")
.unwrap() .unwrap()
.into(); .into();
*bloom = tweak *bloom = tweak
.get::<TweakBloomSettings>("display3d_bloom") .get::<tweaks::TweakBloomSettings>("display3d_bloom")
.unwrap() .unwrap()
.into(); .into();
let quality_level = tweak.get::<TweakScreenSpaceAmbientOcclusionQualityLevel>( let quality_level = tweak
"display3d_ssao_quality_level", .get::<tweaks::TweakScreenSpaceAmbientOcclusionQualityLevel>(
); "display3d_ssao_quality_level",
);
match quality_level { match quality_level {
Some(quality_level) => { Some(quality_level) => {
commands commands
@ -373,7 +348,10 @@ fn update_tweaks(
commands commands
.entity(entity) .entity(entity)
.remove::<ScreenSpaceAmbientOcclusionSettings>(); .remove::<ScreenSpaceAmbientOcclusionSettings>();
let msaa: Msaa = tweak.get::<TweakMsaa>("display3d_msaa").unwrap().into(); let msaa: Msaa = tweak
.get::<tweaks::TweakMsaa>("display3d_msaa")
.unwrap()
.into();
commands.insert_resource(msaa); commands.insert_resource(msaa);
} }
} }
@ -542,7 +520,7 @@ fn gizmo_system(mut gizmos: Gizmos) {
/// TODO: This has bad feel, needs to be tuned /// TODO: This has bad feel, needs to be tuned
fn move_camera( fn move_camera(
buttons: Res<Input<MouseButton>>, buttons: Res<ButtonInput<MouseButton>>,
mut events: EventReader<MouseMotion>, mut events: EventReader<MouseMotion>,
mut camera: Query<&mut Transform, (With<Display3d>, With<Camera>)>, mut camera: Query<&mut Transform, (With<Display3d>, With<Camera>)>,
) { ) {
@ -1132,17 +1110,7 @@ fn scale_lighting(
} }
pub(super) mod tweaks { pub(super) mod tweaks {
use bevy::{ use super::*;
core_pipeline::{bloom::BloomSettings, tonemapping::Tonemapping},
math::Vec3,
pbr::{FogFalloff, FogSettings, ScreenSpaceAmbientOcclusionQualityLevel},
prelude::*,
render::{
color::Color,
view::{ColorGrading, Msaa},
},
};
use serde::Deserialize;
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub enum TweakTonemapping { pub enum TweakTonemapping {

@ -1,7 +1,3 @@
use bevy::app::AppExit;
use bevy::utils::HashSet;
use crate::audio::AudioEvent;
use crate::prelude::*; use crate::prelude::*;
pub(crate) struct GamePlugin; pub(crate) struct GamePlugin;
@ -10,13 +6,13 @@ impl Plugin for GamePlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_event::<Move>() app.add_event::<Move>()
.add_event::<Selection>() .add_event::<Selection>()
.add_state::<TurnState>() .init_state::<TurnState>()
.insert_resource(Score { ..default() }) .insert_resource(Score { ..default() })
.add_systems(Startup, setup_board) .add_systems(Startup, setup_board)
.add_systems(OnEnter(GameState::Play), hide_valid_moves) .add_systems(OnEnter(GameState::Play), hide_valid_moves)
.add_systems( .add_systems(
Update, Update,
manage_state_entities::<GameState>().run_if(state_changed::<GameState>()), manage_state_entities::<GameState>().run_if(state_changed::<GameState>),
) )
.add_systems( .add_systems(
Update, Update,
@ -30,8 +26,8 @@ impl Plugin for GamePlugin {
show_valid_moves.run_if(any_component_added::<Selected>()), show_valid_moves.run_if(any_component_added::<Selected>()),
hide_valid_moves.run_if(any_component_removed::<Selected>()), hide_valid_moves.run_if(any_component_removed::<Selected>()),
manage_score.run_if(any_component_added::<Captured>()), manage_score.run_if(any_component_added::<Captured>()),
check_endgame.run_if(resource_changed::<Board>()), check_endgame.run_if(resource_changed::<Board>),
reset_game.run_if(just_pressed(KeyCode::R)), reset_game.run_if(just_pressed(KeyCode::KeyR)),
), ),
) )
.add_systems(OnEnter(GameState::Endgame), set_endgame.after(manage_score)) .add_systems(OnEnter(GameState::Endgame), set_endgame.after(manage_score))
@ -44,7 +40,7 @@ impl Plugin for GamePlugin {
) )
.add_systems( .add_systems(
PostUpdate, PostUpdate,
(debug_board.run_if(resource_exists::<debug::DebugEnabled>()),), (debug_board.run_if(resource_exists::<debug::DebugEnabled>),),
) )
.add_systems(OnEnter(GameState::Restart), handle_restart) .add_systems(OnEnter(GameState::Restart), handle_restart)
.add_systems(OnEnter(GameState::Quit), handle_quit); .add_systems(OnEnter(GameState::Quit), handle_quit);
@ -829,7 +825,9 @@ fn handle_selection(
// De-select the piece // De-select the piece
info!("Applying moves {:?}", moves); info!("Applying moves {:?}", moves);
if !(*done) { if !(*done) {
moves.iter().for_each(|m| move_events.send(m.clone())); moves.iter().for_each(|m| {
move_events.send(m.clone());
});
*done = true; *done = true;
} }
} }

@ -1,8 +1,3 @@
use bevy::render::{
mesh::{MeshVertexAttribute, VertexAttributeValues},
render_resource::VertexFormat,
};
use crate::prelude::*; use crate::prelude::*;
/// Hit data for 2d sprites /// Hit data for 2d sprites
@ -32,6 +27,12 @@ impl Triangle {
(self.edge_a()).cross(self.edge_b()) (self.edge_a()).cross(self.edge_b())
} }
fn normal_plane(&self) -> Plane3d {
Plane3d {
normal: Direction3d::new(self.normal()).expect("Valid normal direction"),
}
}
fn edge_a(&self) -> Vec3 { fn edge_a(&self) -> Vec3 {
self.v1 - self.v0 self.v1 - self.v0
} }
@ -56,7 +57,7 @@ impl Triangle {
/// Heavily synthesized from these two resources: /// Heavily synthesized from these two resources:
/// * Textbook: https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/ray-triangle-intersection-geometric-solution.html /// * Textbook: https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/ray-triangle-intersection-geometric-solution.html
/// * Example: https://github.com/aevyrie/bevy_mod_raycast/blob/435d8ef100738797161ac3a9b910ea346a4ed6e6/src/raycast.rs#L43 /// * Example: https://github.com/aevyrie/bevy_mod_raycast/blob/435d8ef100738797161ac3a9b910ea346a4ed6e6/src/raycast.rs#L43
pub(crate) fn intersects3d(ray: &Ray, mesh: &Mesh, gt: &GlobalTransform) -> Option<Hit3d> { pub(crate) fn intersects3d(ray: &Ray3d, mesh: &Mesh, gt: &GlobalTransform) -> Option<Hit3d> {
let attr = MeshVertexAttribute::new("Vertex_Position", 0, VertexFormat::Float32x3); let attr = MeshVertexAttribute::new("Vertex_Position", 0, VertexFormat::Float32x3);
if let Some(verts) = mesh.attribute(attr) { if let Some(verts) = mesh.attribute(attr) {
if let Some(idxs) = mesh.indices() { if let Some(idxs) = mesh.indices() {
@ -84,7 +85,9 @@ pub(crate) fn intersects3d(ray: &Ray, mesh: &Mesh, gt: &GlobalTransform) -> Opti
.map(|[v0, v1, v2]| Triangle { v0, v1, v2 }) .map(|[v0, v1, v2]| Triangle { v0, v1, v2 })
.filter_map(|triangle| { .filter_map(|triangle| {
// Calculate the distance this ray hits the plane normal to the tri // Calculate the distance this ray hits the plane normal to the tri
if let Some(d) = ray.intersect_plane(triangle.v0, triangle.normal()) { if let Some(d) =
ray.intersect_plane(triangle.v0, triangle.normal_plane())
{
// Calculate the point on that plane which intersects // Calculate the point on that plane which intersects
let p = ray.get_point(d); let p = ray.get_point(d);
// Inside out test // Inside out test

@ -1,5 +1,3 @@
use bevy::core::FrameCount;
use crate::prelude::*; use crate::prelude::*;
pub(crate) struct IntroPlugin; pub(crate) struct IntroPlugin;
@ -10,7 +8,7 @@ impl Plugin for IntroPlugin {
.add_systems( .add_systems(
OnExit(GameState::Loading), OnExit(GameState::Loading),
init_intro_text init_intro_text
.run_if(resource_exists::<tweak::GameTweaks>()) .run_if(resource_exists::<tweak::GameTweaks>)
.run_if(run_once()), .run_if(run_once()),
) )
.add_systems(OnEnter(GameState::Intro), manage_intro) .add_systems(OnEnter(GameState::Intro), manage_intro)
@ -24,12 +22,12 @@ impl Plugin for IntroPlugin {
// Updated for as long as there is scrolling text // Updated for as long as there is scrolling text
manage_scroll_text_animation.run_if( manage_scroll_text_animation.run_if(
any_component_added::<ui::TextScrollAnimation>() any_component_added::<ui::TextScrollAnimation>()
.or_else(just_pressed(KeyCode::Return)) .or_else(just_pressed(KeyCode::Enter))
.or_else(just_pressed(MouseButton::Left)), .or_else(just_pressed(MouseButton::Left)),
), ),
// Play intro manages playing the intro of each individual paragraph // Play intro manages playing the intro of each individual paragraph
// Runs every time the TextScroll component (managed by manage_scroll_text_animation) is updated // Runs every time the TextScroll component (managed by manage_scroll_text_animation) is updated
scroll_text.run_if(any_with_component::<ui::TextScroll>()), scroll_text.run_if(any_with_component::<ui::TextScroll>),
) )
.run_if(in_state(GameState::Intro)), .run_if(in_state(GameState::Intro)),
); );
@ -108,7 +106,7 @@ fn init_intro_text(
}, },
}) })
.collect(), .collect(),
alignment: TextAlignment::Center, justify: JustifyText::Center,
..default() ..default()
}, },
..default() ..default()
@ -239,8 +237,8 @@ fn scroll_text(
tweaks_file: Res<tweak::GameTweaks>, tweaks_file: Res<tweak::GameTweaks>,
tweaks: Res<Assets<tweak::Tweaks>>, tweaks: Res<Assets<tweak::Tweaks>>,
time: Res<Time>, time: Res<Time>,
keys: Res<Input<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
mouse: Res<Input<MouseButton>>, mouse: Res<ButtonInput<MouseButton>>,
parents: Query<&Parent>, parents: Query<&Parent>,
mut commands: Commands, mut commands: Commands,
) { ) {
@ -261,7 +259,7 @@ fn scroll_text(
// If user pressed enter, skip to end of paragraph // If user pressed enter, skip to end of paragraph
text_scroll.progress = text_scroll.progress =
if keys.just_pressed(KeyCode::Return) || mouse.just_pressed(MouseButton::Left) { if keys.just_pressed(KeyCode::Enter) || mouse.just_pressed(MouseButton::Left) {
usize::MAX usize::MAX
} }
// Otherwise, progress by some fixed increment // Otherwise, progress by some fixed increment

@ -16,12 +16,7 @@ struct Loading;
// TODO: Why is this image not showing?? // TODO: Why is this image not showing??
fn initialize(mut commands: Commands, server: Res<AssetServer>) { fn initialize(mut commands: Commands, server: Res<AssetServer>) {
commands.spawn(( commands.spawn((Loading, GameState::Loading, Camera2dBundle { ..default() }));
Loading,
GameState::Loading,
Camera2dBundle { ..default() },
UiCameraConfig { show_ui: true },
));
commands.spawn(( commands.spawn((
Loading, Loading,
GameState::Loading, GameState::Loading,

@ -16,10 +16,6 @@ mod tutorial;
mod tweak; mod tweak;
mod ui; mod ui;
use bevy::winit::WinitWindows;
use std::{hash::Hash, time::Duration};
use winit::window::Icon;
use crate::prelude::*; use crate::prelude::*;
fn main() { fn main() {
@ -28,15 +24,15 @@ fn main() {
} }
let mut app = App::new(); let mut app = App::new();
app.add_state::<GameState>(); app.init_state::<GameState>();
app.add_state::<DisplayState>(); app.init_state::<DisplayState>();
app.add_systems( app.add_systems(
Update, Update,
( (
debug_state::<DisplayState>.run_if(resource_changed::<State<DisplayState>>()), debug_state::<DisplayState>.run_if(resource_changed::<State<DisplayState>>),
debug_state::<GameState>.run_if(resource_changed::<State<GameState>>()), debug_state::<GameState>.run_if(resource_changed::<State<GameState>>),
debug_state::<tutorial::TutorialState> debug_state::<tutorial::TutorialState>
.run_if(resource_changed::<State<tutorial::TutorialState>>()), .run_if(resource_changed::<State<tutorial::TutorialState>>),
), ),
); );
app.add_systems(Startup, set_window_icon); app.add_systems(Startup, set_window_icon);
@ -167,9 +163,9 @@ fn set_window_icon(
} }
} }
pub(crate) fn just_pressed<T>(button: T) -> impl FnMut(Res<Input<T>>) -> bool + Clone pub(crate) fn just_pressed<T>(button: T) -> impl FnMut(Res<ButtonInput<T>>) -> bool + Clone
where where
T: Copy + Eq + Hash + Send + Sync + 'static, T: Copy + Eq + Hash + Send + Sync + 'static,
{ {
Box::new(move |buttons: Res<Input<T>>| -> bool { buttons.just_pressed(button) }) Box::new(move |buttons: Res<ButtonInput<T>>| -> bool { buttons.just_pressed(button) })
} }

@ -1,12 +1,10 @@
use crate::prelude::*; use crate::prelude::*;
use self::tutorial::TutorialState;
pub(crate) struct MenuPlugin; pub(crate) struct MenuPlugin;
impl Plugin for MenuPlugin { impl Plugin for MenuPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_state::<MenuState>() app.init_state::<MenuState>()
// Initialize menus // Initialize menus
.add_systems( .add_systems(
// TODO: move this to game.rs or display3d.rs // TODO: move this to game.rs or display3d.rs
@ -16,7 +14,7 @@ impl Plugin for MenuPlugin {
// Manage visible/hidden states // Manage visible/hidden states
.add_systems( .add_systems(
Update, Update,
manage_state_entities::<MenuState>().run_if(state_changed::<MenuState>()), manage_state_entities::<MenuState>().run_if(state_changed::<MenuState>),
) )
.add_systems( .add_systems(
Update, Update,
@ -123,7 +121,7 @@ fn init_play_menu(
// Tutorial button // Tutorial button
parent parent
.spawn(( .spawn((
ButtonAction(tutorial::TutorialState::Intro), ButtonAction(TutorialState::Intro),
ButtonAction(MenuState::Off), ButtonAction(MenuState::Off),
ButtonBundle { ButtonBundle {
style: Style { style: Style {

@ -1,3 +1,47 @@
pub use crate::*; pub(crate) use crate::{audio::AudioEvent, game::*, tutorial::*, tweak::*, *};
pub use bevy::gltf::Gltf; pub(crate) use bevy::{
pub use bevy::prelude::*; animation::RepeatAnimation,
app::AppExit,
asset::{io::Reader, AssetLoader, LoadContext},
core::FrameCount,
core_pipeline::{
bloom::BloomSettings,
experimental::taa::{TemporalAntiAliasPlugin, TemporalAntiAliasSettings},
prepass::MotionVectorPrepass,
tonemapping::{DebandDither, Tonemapping},
Skybox,
},
diagnostic::{
DiagnosticsStore, EntityCountDiagnosticsPlugin, FrameTimeDiagnosticsPlugin,
SystemInformationDiagnosticsPlugin,
},
gltf::Gltf,
input::{
keyboard::KeyboardInput,
mouse::{MouseButtonInput, MouseMotion, MouseScrollUnit, MouseWheel},
ButtonState,
},
pbr::ScreenSpaceAmbientOcclusionQualityLevel,
pbr::{
ExtendedMaterial, MaterialExtension, ScreenSpaceAmbientOcclusionBundle,
ScreenSpaceAmbientOcclusionSettings,
},
prelude::*,
reflect::TypePath,
render::{
mesh::{MeshVertexAttribute, VertexAttributeValues},
render_resource::{
AsBindGroup, ShaderRef, TextureViewDescriptor, TextureViewDimension, VertexFormat,
},
view::ColorGrading,
},
utils::BoxedFuture,
utils::{hashbrown::hash_map::Iter, HashMap, HashSet},
window::PrimaryWindow,
winit::WinitWindows,
};
pub(crate) use bevy_fmod::prelude::{AudioSource, *};
pub(crate) use serde::Deserialize;
pub(crate) use std::{hash::Hash, str::Utf8Error, time::Duration};
pub(crate) use thiserror::Error;
pub(crate) use winit::window::Icon;

@ -1,17 +1,15 @@
use bevy::utils::HashSet;
use crate::prelude::*; use crate::prelude::*;
pub(crate) struct TutorialPlugin; pub(crate) struct TutorialPlugin;
impl Plugin for TutorialPlugin { impl Plugin for TutorialPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_state::<TutorialState>() app.init_state::<TutorialState>()
.init_resource::<SeenStates>() .init_resource::<SeenStates>()
.add_systems( .add_systems(
OnExit(GameState::Loading), OnExit(GameState::Loading),
initialize_tutorial initialize_tutorial
.run_if(resource_exists::<tweak::GameTweaks>()) .run_if(resource_exists::<tweak::GameTweaks>)
.run_if(run_once()), .run_if(run_once()),
) )
.add_systems( .add_systems(
@ -19,7 +17,7 @@ impl Plugin for TutorialPlugin {
( (
// Evaluate if a piece is selected // Evaluate if a piece is selected
step.run_if( step.run_if(
state_exists::<TutorialState>().and_then( state_exists::<TutorialState>.and_then(
// A piece changes sides // A piece changes sides
any_component_changed::<game::Side>() any_component_changed::<game::Side>()
// When a piece is selected, we // When a piece is selected, we
@ -28,7 +26,7 @@ impl Plugin for TutorialPlugin {
.or_else(any_component_removed::<game::Selected>()) .or_else(any_component_removed::<game::Selected>())
// TEMP: The user hits 'enter' // TEMP: The user hits 'enter'
.or_else( .or_else(
just_pressed(KeyCode::Return) just_pressed(KeyCode::Enter)
.or_else(just_pressed(MouseButton::Left)), .or_else(just_pressed(MouseButton::Left)),
), ),
), ),
@ -38,13 +36,12 @@ impl Plugin for TutorialPlugin {
// Manage visible/hidden states // Manage visible/hidden states
.add_systems( .add_systems(
Update, Update,
manage_state_entities::<TutorialState>().run_if(state_changed::<TutorialState>()), manage_state_entities::<TutorialState>().run_if(state_changed::<TutorialState>),
) )
.add_systems( .add_systems(
Update, Update,
activate_tutorial_step.run_if( activate_tutorial_step
state_exists::<TutorialState>().and_then(state_changed::<TutorialState>()), .run_if(state_exists::<TutorialState>.and_then(state_changed::<TutorialState>)),
),
); );
} }
} }
@ -210,7 +207,7 @@ fn initialize_tutorial(
}, },
}) })
.collect(), .collect(),
alignment: TextAlignment::Left, justify: JustifyText::Left,
..default() ..default()
}, },
..default() ..default()

@ -1,14 +1,4 @@
use crate::prelude::*; use crate::prelude::*;
use bevy::asset::AsyncReadExt;
use bevy::utils::HashMap;
use bevy::{
asset::{io::Reader, AssetLoader, LoadContext},
reflect::TypePath,
utils::BoxedFuture,
};
use serde::Deserialize;
use std::str::Utf8Error;
use thiserror::Error;
/// A Tweaks is resource used to specify game customization like asset names, /// A Tweaks is resource used to specify game customization like asset names,
/// and non-user customizations made to the game during development. /// and non-user customizations made to the game during development.
@ -145,6 +135,8 @@ impl AssetLoader for TweaksLoader {
_settings: &'a Self::Settings, _settings: &'a Self::Settings,
load_context: &'a mut LoadContext, load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, Result<Self::Asset, Self::Error>> { ) -> BoxedFuture<'a, Result<Self::Asset, Self::Error>> {
use bevy::asset::AsyncReadExt;
Box::pin(async move { Box::pin(async move {
let mut bytes = Vec::new(); let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?; reader.read_to_end(&mut bytes).await?;

@ -1,5 +1,3 @@
use bevy::window::PrimaryWindow;
use crate::prelude::*; use crate::prelude::*;
pub(crate) struct UiPlugin; pub(crate) struct UiPlugin;
@ -10,13 +8,13 @@ impl Plugin for UiPlugin {
Update, Update,
( (
manage_cursor.run_if( manage_cursor.run_if(
any_component_changed::<Interaction>().or_else(state_changed::<GameState>()), any_component_changed::<Interaction>().or_else(state_changed::<GameState>),
), ),
interactive_button.run_if(any_component_changed::<Interaction>()), interactive_button.run_if(any_component_changed::<Interaction>()),
scale_ui.run_if( scale_ui.run_if(
on_event::<AssetEvent<tweak::Tweaks>>() on_event::<AssetEvent<tweak::Tweaks>>()
.or_else(any_component_changed::<Window>()) .or_else(any_component_changed::<Window>())
.and_then(resource_exists::<tweak::GameTweaks>()), .and_then(resource_exists::<tweak::GameTweaks>),
), ),
), ),
); );
@ -60,7 +58,7 @@ fn manage_cursor(
CursorIcon::Grabbing CursorIcon::Grabbing
// If a button is clicked, icon is grab // If a button is clicked, icon is grab
} else if buttons.iter().any(|i| *i == Interaction::Hovered) { } else if buttons.iter().any(|i| *i == Interaction::Hovered) {
CursorIcon::Hand CursorIcon::Grab
// Default icon is Crosshair // Default icon is Crosshair
} else { } else {
CursorIcon::Crosshair CursorIcon::Crosshair
@ -146,7 +144,7 @@ fn scale_ui(
// Setting UI Scale based on ratio of expected to current ratio // Setting UI Scale based on ratio of expected to current ratio
let width_ratio = w.resolution.width() / width; let width_ratio = w.resolution.width() / width;
let height_ratio = w.resolution.height() / height; let height_ratio = w.resolution.height() / height;
let new_scale = (width_ratio).min(height_ratio) as f64; let new_scale = (width_ratio).min(height_ratio);
if ui_scale.0 != new_scale { if ui_scale.0 != new_scale {
ui_scale.0 = new_scale; ui_scale.0 = new_scale;
} }

Loading…
Cancel
Save