cargo fmt

main
Elijah C. Voigt 2 years ago
parent 609ae8ebb9
commit fe2e023036

@ -2,9 +2,7 @@ use gltf::*;
fn main() -> gltf::Result<()> {
let g = Gltf::open("assets/models/Martian Chess.glb")?;
g.animations()
.into_iter()
.for_each(|x| {
g.animations().into_iter().for_each(|x| {
println!("{:?}", x.name());
});
Ok(())

@ -1,8 +1,8 @@
use bevy::pbr::OpaqueRendererMethod;
use bevy::prelude::*;
use bevy::pbr::ExtendedMaterial;
use bevy::pbr::MaterialExtension;
use bevy::pbr::MaterialMeshBundle;
use bevy::pbr::OpaqueRendererMethod;
use bevy::prelude::*;
use bevy::render::render_resource::*;
type MyMat = ExtendedMaterial<StandardMaterial, MatExt>;
@ -19,10 +19,7 @@ fn main() {
.run();
}
fn setup(
mut commands: Commands,
assets: Res<AssetServer>,
) {
fn setup(mut commands: Commands, assets: Res<AssetServer>) {
commands.spawn(SceneBundle {
scene: assets.load("models/Martian Chess.glb#Scene0"),
..default()
@ -65,17 +62,18 @@ fn setup_material(
// Extension we will add to existing gltf-sourced materials
let extension = MatExt { cutoff: 1.0 };
// Base material we will extend for the duration of the dissolve effect
let mut base = standard_materials.get(handle).expect("Resolve material data").clone();
let mut base = standard_materials
.get(handle)
.expect("Resolve material data")
.clone();
base.opaque_render_method = OpaqueRendererMethod::Auto;
base.alpha_mode = AlphaMode::Mask(0.5);
commands.entity(entity).insert(
materials.add(ExtendedMaterial {
base,
extension,
})
).remove::<Handle<StandardMaterial>>();
commands
.entity(entity)
.insert(materials.add(ExtendedMaterial { base, extension }))
.remove::<Handle<StandardMaterial>>();
})
}

@ -76,7 +76,9 @@ fn audio_trigger(
AudioEvent::MenuSelect => tweak.get::<String>("audio_menu_select").unwrap(),
AudioEvent::PickUp => tweak.get::<String>("audio_display3d_pick_up").unwrap(),
AudioEvent::PutDown => tweak.get::<String>("audio_display3d_put_down").unwrap(),
AudioEvent::Idle | AudioEvent::StopIdle => tweak.get::<String>("audio_display3d_idle").unwrap(),
AudioEvent::Idle | AudioEvent::StopIdle => {
tweak.get::<String>("audio_display3d_idle").unwrap()
}
AudioEvent::Invalid => tweak.get::<String>("audio_display3d_invalid").unwrap(),
};
// There is an event, play an audio

@ -19,20 +19,20 @@ impl Plugin for DebugPlugin {
SystemInformationDiagnosticsPlugin::default(),
))
.init_resource::<DebugInfo>()
.insert_resource(
GizmoConfig {
.insert_resource(GizmoConfig {
depth_bias: -0.1,
..default()
},
)
.add_systems(Update, (
aabb_gizmo,
))
})
.add_systems(Update, (aabb_gizmo,))
// Systems that run in the editor mode
.add_systems(Update, (
.add_systems(
Update,
(
selected_gizmo.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(
Update,
@ -163,14 +163,18 @@ fn aabb_gizmo(
mut commands: Commands,
) {
added.iter().for_each(|e| {
commands.entity(e).insert(AabbGizmo { color: Some(Color::RED) });
commands.entity(e).insert(AabbGizmo {
color: Some(Color::RED),
});
});
removed.read().for_each(|e| {
commands.entity(e).remove::<AabbGizmo>();
});
match active {
Some(_) => selected.iter().for_each(|e| {
commands.entity(e).insert(AabbGizmo { color: Some(Color::RED) });
commands.entity(e).insert(AabbGizmo {
color: Some(Color::RED),
});
}),
None => selected.iter().for_each(|e| {
commands.entity(e).remove::<AabbGizmo>();
@ -179,10 +183,7 @@ fn aabb_gizmo(
}
/// Draw a gizmo showing cardinal directions for a selected object
fn selected_gizmo(
selected: Query<&GlobalTransform, With<game::Selected>>,
mut gizmos: Gizmos,
) {
fn selected_gizmo(selected: Query<&GlobalTransform, With<game::Selected>>, mut gizmos: Gizmos) {
selected.iter().for_each(|g| {
let s = g.translation();
gizmos.ray(s, Vec3::X, Color::RED);
@ -195,8 +196,10 @@ fn selected_position(
selected: Query<(Entity, &GlobalTransform), With<game::Selected>>,
mut debug_info: ResMut<debug::DebugInfo>,
) {
let val = selected.iter().map(|(e, gt)| {
format!("\n{:?} {:?}", e, gt.translation())
}).collect::<Vec<String>>().join("");
let val = selected
.iter()
.map(|(e, gt)| format!("\n{:?} {:?}", e, gt.translation()))
.collect::<Vec<String>>()
.join("");
debug_info.set("Position".into(), val);
}

@ -12,9 +12,12 @@ use bevy::{
Skybox,
},
input::mouse::{MouseButtonInput, MouseMotion, MouseScrollUnit, MouseWheel},
pbr::{ScreenSpaceAmbientOcclusionBundle, ScreenSpaceAmbientOcclusionSettings, MaterialExtension, ExtendedMaterial, OpaqueRendererMethod},
pbr::{
ExtendedMaterial, MaterialExtension, OpaqueRendererMethod,
ScreenSpaceAmbientOcclusionBundle, ScreenSpaceAmbientOcclusionSettings,
},
render::{
render_resource::{TextureViewDescriptor, TextureViewDimension, ShaderRef,AsBindGroup},
render_resource::{AsBindGroup, ShaderRef, TextureViewDescriptor, TextureViewDimension},
view::ColorGrading,
},
window::PrimaryWindow,
@ -32,7 +35,11 @@ impl Plugin for Display3dPlugin {
.insert_resource(Msaa::Off)
.add_systems(
OnExit(GameState::Loading),
(initialize, fix_skybox.before(initialize), update_tweaks.run_if(resource_exists::<tweak::GameTweaks>()),),
(
initialize,
fix_skybox.before(initialize),
update_tweaks.run_if(resource_exists::<tweak::GameTweaks>()),
),
)
.add_systems(
Update,
@ -47,7 +54,9 @@ impl Plugin for Display3dPlugin {
set_valid_move_model.run_if(any_component_added::<game::ValidMove>),
set_tile_hitbox.run_if(any_component_added::<game::Tile>),
set_piece_position.run_if(any_component_changed::<BoardIndex>),
set_piece_texture.run_if(any_component_changed::<Side>).run_if(resource_exists::<tweak::GameTweaks>()),
set_piece_texture
.run_if(any_component_changed::<Side>)
.run_if(resource_exists::<tweak::GameTweaks>()),
select
.run_if(in_state(GameState::Play))
.run_if(in_state(DisplayState::Display3d))
@ -57,7 +66,9 @@ impl Plugin for Display3dPlugin {
switch_sides
.run_if(in_state(GameState::Play))
.run_if(state_changed::<game::TurnState>()),
update_tweaks.run_if(on_event::<AssetEvent<Tweaks>>()).run_if(resource_exists::<tweak::GameTweaks>()),
update_tweaks
.run_if(on_event::<AssetEvent<Tweaks>>())
.run_if(resource_exists::<tweak::GameTweaks>()),
scale_lighting.run_if(
any_component_added::<DirectionalLight>
.or_else(any_component_added::<SpotLight>)
@ -280,10 +291,9 @@ fn hydrate_camera(
.unwrap()
.as_str(),
),
}.expect("Camera Startup");
player
.play(animation.clone())
.pause();
}
.expect("Camera Startup");
player.play(animation.clone()).pause();
}
});
}
@ -738,7 +748,11 @@ fn select(
meshes: Res<Assets<Mesh>>,
cameras: Query<(&Camera, &GlobalTransform)>,
windows: Query<&Window, With<PrimaryWindow>>,
selectable: Query<(Entity, &BoardIndex, &Side, Option<&Piece>), (With<game::Selectable>, With<Display3d>)>,
selectable: Query<
(Entity, &BoardIndex, &Side),
(With<game::Selectable>, With<Display3d>),
>,
selected: Query<Entity, With<game::Selected>>,
children: Query<&Children>,
mut selections: EventWriter<game::Selection>,
state: Res<State<game::TurnState>>,
@ -760,10 +774,12 @@ fn select(
hit::intersects3d(&ray, mesh, &gt).and_then(|_hit| {
selectable
.iter()
.find_map(|(e, &board_index, &side, piece_ish)| {
// Check if this piece is on the active side
let side_check = piece_ish.is_some() && *state.get() == side;
.find_map(|(e, &board_index, &side)| {
// Check the side of the selection if no piece is selected
// Otherwise this is fine, select away
let side_check = !selected.is_empty() || *state.get() == side;
let hit_check = {
// This entity was hit (tile hitboxes)
let primary = entity == e;
@ -772,8 +788,10 @@ fn select(
.iter_descendants(e)
.any(|child| child == entity);
(side_check && (primary || secondary)).then_some(board_index)
primary || secondary
};
(side_check && hit_check).then_some(board_index)
})
.iter()
.for_each(|&board_index| {
@ -816,7 +834,10 @@ fn moves_gizmo(
}
fn set_valid_move_model(
mut events: Query<(&mut Handle<Scene>, &mut Visibility), (With<Display3d>, Added<game::ValidMove>)>,
mut events: Query<
(&mut Handle<Scene>, &mut Visibility),
(With<Display3d>, Added<game::ValidMove>),
>,
gltfs: Res<Assets<Gltf>>,
tweaks: Res<Assets<Tweaks>>,
tweaks_file: Res<tweak::GameTweaks>,
@ -874,20 +895,28 @@ fn pick_up(
info!(" Child: {:?}", child);
if let Ok((name, mut player)) = players.get_mut(child) {
info!("Picking up {:?} ({:?}) {:?}", name, entity, piece);
let pickup_animation = format!("display3d_models_animations_pick_up_{:?}", piece).to_ascii_lowercase();
let pickup_handle = gltf.named_animations.get(
let pickup_animation =
format!("display3d_models_animations_pick_up_{:?}", piece).to_ascii_lowercase();
let pickup_handle = gltf
.named_animations
.get(
tweak
.get::<String>(pickup_animation.as_str())
.unwrap()
.as_str(),
).expect("Pickup Animation");
let idle_animation = format!("display3d_models_animations_idle_{:?}", piece).to_ascii_lowercase();
let idle_handle = gltf.named_animations.get(
)
.expect("Pickup Animation");
let idle_animation =
format!("display3d_models_animations_idle_{:?}", piece).to_ascii_lowercase();
let idle_handle = gltf
.named_animations
.get(
tweak
.get::<String>(idle_animation.as_str())
.unwrap()
.as_str(),
).expect("Idle animation");
)
.expect("Idle animation");
if let Some(pickup_clip) = clips.get(pickup_handle) {
if let Some(idle_clip) = clips.get(idle_handle) {
if pickup_clip.compatible_with(name) && idle_clip.compatible_with(name) {
@ -931,13 +960,18 @@ fn put_down(
children.iter_descendants(entity).for_each(|child| {
if let Ok((name, mut player)) = players.get_mut(child) {
info!("Putting down {:?}", entity);
let putdown_animation = format!("display3d_models_animations_put_down_{:?}", piece).to_ascii_lowercase();
let putdown_handle = gltf.named_animations.get(
let putdown_animation =
format!("display3d_models_animations_put_down_{:?}", piece)
.to_ascii_lowercase();
let putdown_handle = gltf
.named_animations
.get(
tweak
.get::<String>(putdown_animation.as_str())
.unwrap()
.as_str(),
).expect("PutDown Animation");
)
.expect("PutDown Animation");
if let Some(putdown_clip) = clips.get(putdown_handle) {
if putdown_clip.compatible_with(name) {
player
@ -1006,7 +1040,11 @@ fn switch_sides(
}
fn scale_lighting(
mut directional: Query<(Entity, &mut DirectionalLight, Option<&Original<DirectionalLight>>)>,
mut directional: Query<(
Entity,
&mut DirectionalLight,
Option<&Original<DirectionalLight>>,
)>,
mut spot: Query<(Entity, &mut SpotLight, Option<&Original<SpotLight>>)>,
mut point: Query<(Entity, &mut PointLight, Option<&Original<PointLight>>)>,
mut commands: Commands,
@ -1017,8 +1055,12 @@ fn scale_lighting(
.get(tweaks_file.handle.clone())
.expect("Load tweakfile");
let directional_tweak = tweak.get::<f32>("display3d_lights_scaling_directional").expect("Directional lighting scalar");
directional.iter_mut().for_each(|(entity, mut val, original)| {
let directional_tweak = tweak
.get::<f32>("display3d_lights_scaling_directional")
.expect("Directional lighting scalar");
directional
.iter_mut()
.for_each(|(entity, mut val, original)| {
debug!("Scaling directional light {:?}", entity);
if let Some(Original(v)) = original {
val.illuminance = v.illuminance * directional_tweak;
@ -1028,7 +1070,9 @@ fn scale_lighting(
}
});
let spot_tweak = tweak.get::<f32>("display3d_lights_scaling_spot").expect("Spot lighting scalar");
let spot_tweak = tweak
.get::<f32>("display3d_lights_scaling_spot")
.expect("Spot lighting scalar");
spot.iter_mut().for_each(|(entity, mut val, original)| {
debug!("Scaling spot light {:?}", entity);
if let Some(Original(v)) = original {
@ -1039,7 +1083,9 @@ fn scale_lighting(
}
});
let point_tweak = tweak.get::<f32>("display3d_lights_scaling_point").expect("Point lighting scalar");
let point_tweak = tweak
.get::<f32>("display3d_lights_scaling_point")
.expect("Point lighting scalar");
point.iter_mut().for_each(|(entity, mut val, original)| {
debug!("Scaling point light {:?}", entity);
if let Some(Original(v)) = original {
@ -1245,7 +1291,10 @@ struct Backup<T: Component>(T);
/// The animation is like a 'beam me up scotty' sorta thing.
fn capture_piece(
events: Query<Entity, (With<Display3d>, Added<game::Captured>)>,
mut query: Query<(&mut Visibility, &mut Transform, &Side), (With<Display3d>, With<game::Captured>)>,
mut query: Query<
(&mut Visibility, &mut Transform, &Side),
(With<Display3d>, With<game::Captured>),
>,
mut state: Local<Option<game::CaptureFlow>>,
standard_materials: ResMut<Assets<StandardMaterial>>,
mut dissolve_materials: ResMut<Assets<DissolveMaterial>>,
@ -1270,9 +1319,7 @@ fn capture_piece(
// Play fade-out animation
{
object_dissolve_materials
.iter()
.for_each(|handle| {
object_dissolve_materials.iter().for_each(|handle| {
let extended_material = dissolve_materials
.get_mut(handle)
.expect("Get the dissolve material");
@ -1283,7 +1330,10 @@ fn capture_piece(
// Change the material's value to create animation
extended_material.extension.percentage -= delta; // TODO: Tweak this timing
debug!("Play fade out animation {:?} {:?}", delta, extended_material.extension.percentage);
debug!(
"Play fade out animation {:?} {:?}",
delta, extended_material.extension.percentage
);
if extended_material.extension.percentage <= 0.0 {
// Set to exactly 0 for simplicity
@ -1294,7 +1344,7 @@ fn capture_piece(
}
});
}
},
}
game::CaptureFlow::Store(entity) => {
let (mut v, mut t, side) = query
.get_mut(entity)
@ -1306,7 +1356,7 @@ fn capture_piece(
t.translation = capture_translation(side, score.get(*side));
*state = s.next();
},
}
game::CaptureFlow::FadeIn(entity) => {
let (mut v, _, _) = query
.get_mut(entity)
@ -1317,9 +1367,7 @@ fn capture_piece(
// Play fade-in animation
{
object_dissolve_materials
.iter()
.for_each(|handle| {
object_dissolve_materials.iter().for_each(|handle| {
let extended_material = dissolve_materials
.get_mut(handle)
.expect("Get the dissolve material");
@ -1330,7 +1378,10 @@ fn capture_piece(
// Change the material's value to create animation
extended_material.extension.percentage += delta; // TODO: Tweak this timing
debug!("Play fade in animation {:?} {:?}", delta, extended_material.extension.percentage);
debug!(
"Play fade in animation {:?} {:?}",
delta, extended_material.extension.percentage
);
if extended_material.extension.percentage >= 1.0 {
// Move to next state now that animation is done
@ -1345,7 +1396,9 @@ fn capture_piece(
// Re-add the original material
if let Ok(Backup(orig)) = backup_material.get(entity) {
commands.entity(entity).insert(orig.clone());
commands.entity(entity).remove::<Backup<Handle<StandardMaterial>>>();
commands
.entity(entity)
.remove::<Backup<Handle<StandardMaterial>>>();
} else {
warn!("Entity {:?} does not have original material", entity)
}
@ -1354,29 +1407,28 @@ fn capture_piece(
}
}
}
},
}
None => {
*state = events.iter().next().map(|entity| {
children
.iter_descendants(entity)
.filter_map(|e| {
object_standard_materials.get(e).ok().map(|h| (e, h))
})
.filter_map(|e| object_standard_materials.get(e).ok().map(|h| (e, h)))
.for_each(|(child, handle)| {
// Extension we will add to existing gltf-sourced materials
let extension = DissolveExtension { percentage: 1.0 };
// Base material we will extend for the duration of the dissolve effect
let mut base = standard_materials.get(handle).expect("Resolve material data").clone();
let mut base = standard_materials
.get(handle)
.expect("Resolve material data")
.clone();
base.opaque_render_method = OpaqueRendererMethod::Auto;
base.alpha_mode = AlphaMode::Mask(0.5);
commands.entity(child).insert(
dissolve_materials.add(ExtendedMaterial {
base,
extension,
})
).insert(Backup(handle.clone()))
commands
.entity(child)
.insert(dissolve_materials.add(ExtendedMaterial { base, extension }))
.insert(Backup(handle.clone()))
.remove::<Handle<StandardMaterial>>();
});

@ -32,7 +32,9 @@ impl Plugin for GamePlugin {
)
.add_systems(
PreUpdate,
asserts::<display3d::Display3d>.run_if(in_state(DisplayState::Display3d)).run_if(in_state(GameState::Play)),
asserts::<display3d::Display3d>
.run_if(in_state(DisplayState::Display3d))
.run_if(in_state(GameState::Play)),
)
.add_systems(
PostUpdate,
@ -70,7 +72,6 @@ impl PartialEq<Side> for TurnState {
}
}
#[derive(Debug, Component, Clone, PartialEq, Copy, Hash)]
pub(crate) enum Piece {
Pawn,
@ -517,7 +518,7 @@ pub(crate) fn update_board(
audio_events.send(audio::AudioEvent::StopIdle);
*played = true;
if *from != *to_idx {
let ns = !*curr_state.get() ;
let ns = !*curr_state.get();
info!("Piece moved, switching sides: {:?}", ns);
next_state.set(ns);
}
@ -700,9 +701,7 @@ fn show_valid_moves(
}
/// Hide "Valid Move" indicators when a piece is de-selected
fn hide_valid_moves(
mut indicators: Query<&mut Visibility, With<ValidMove>>,
) {
fn hide_valid_moves(mut indicators: Query<&mut Visibility, With<ValidMove>>) {
indicators.iter_mut().for_each(|mut visibility| {
*visibility = Visibility::Hidden;
});

@ -2,7 +2,6 @@
#![feature(iter_intersperse)] // used in debug.rs
#![feature(async_closure)] // Loading tweakfiles
mod audio;
mod credits;
mod debug;
@ -101,7 +100,14 @@ fn toggle_display_camera(
}
fn activate<Marker: Component>(
mut entities: Query<&mut Visibility, (With<Marker>, Without<game::Captured>, Without<game::ValidMove>)>,
mut entities: Query<
&mut Visibility,
(
With<Marker>,
Without<game::Captured>,
Without<game::ValidMove>,
),
>,
) {
entities.iter_mut().for_each(|mut visibility| {
*visibility = Visibility::Visible;

@ -50,16 +50,14 @@ fn init_menu_ui(mut commands: Commands) {
},
))
.with_children(|parent| {
parent.spawn(
TextBundle::from_section(
parent.spawn(TextBundle::from_section(
"M A R T I A N C H E S S",
TextStyle {
font_size: 48.0,
color: Color::ORANGE_RED,
..default()
},
)
);
));
parent
.spawn((
GameState::Play,

@ -54,9 +54,9 @@ impl Tweaks {
} else {
None
}
}).flatten().map(|h| {
(k.clone(), h)
}),
})
.flatten()
.map(|h| (k.clone(), h)),
_ => None,
})
.collect();
@ -78,10 +78,9 @@ impl Tweaks {
}
pub fn get<'de, T: Deserialize<'de>>(&self, key: &str) -> Option<T> {
Tweaks::locate(&self.table, key)
.map(|val| match val.try_into() {
Tweaks::locate(&self.table, key).map(|val| match val.try_into() {
Ok(val) => val,
Err(e) => panic!("{}", e.message())
Err(e) => panic!("{}", e.message()),
})
}

Loading…
Cancel
Save