Compare commits

..

No commits in common. "6eddde886e390432b6656125530bc644c8098c64" and "8e4369163a7b2c81227e50b0adb2a13b2f327e4f" have entirely different histories.

17 changed files with 354 additions and 255 deletions

View File

@ -13,25 +13,27 @@ speech_dispatcher_0_10 = ["bevy_tts/speech_dispatcher_0_10"]
speech_dispatcher_0_11 = ["bevy_tts/speech_dispatcher_0_11"] speech_dispatcher_0_11 = ["bevy_tts/speech_dispatcher_0_11"]
[dependencies.bevy] [dependencies.bevy]
version = "0.10" version = "0.9"
default-features = false default-features = false
features = [ features = [
"bevy_gilrs", "bevy_gilrs",
"bevy_winit", "bevy_winit",
"render",
"x11", "x11",
"wayland", "wayland",
"serialize", "serialize",
] ]
[dependencies] [dependencies]
bevy_rapier2d = "0.21" backtrace = "0.3"
bevy_synthizer = "0.2" bevy_rapier2d = "0.20"
bevy_tts = { version = "0.5", default-features = false, features = ["tolk"] } bevy_synthizer = "0.1"
bevy_tts = { version = "0.4", default-features = false, features = ["tolk"] }
coord_2d = "0.3" coord_2d = "0.3"
futures-lite = "1" futures-lite = "1"
gilrs = "0.10" gilrs = "0.10"
here_be_dragons = { version = "0.3", features = ["serde"] } here_be_dragons = "0.2"
leafwing-input-manager = "0.9" leafwing-input-manager = { git = "https://github.com/ndarilek/leafwing-input-manager" }
maze_generator = "2" maze_generator = "2"
once_cell = "1" once_cell = "1"
pathfinding = "4" pathfinding = "4"

View File

@ -15,6 +15,8 @@ _Blackout_ uses a few other libraries for its magic:
It provides, including but not limited to: It provides, including but not limited to:
* commands
* `RunIfExists` extension for only running a given command if its entity exists
* core * core
* `PointLike` trait for distance and other calculations between `Coordinates` and `Coordinates`-like things (I.e. `(f32, f32)`, `(i32, i32)`, ...) * `PointLike` trait for distance and other calculations between `Coordinates` and `Coordinates`-like things (I.e. `(f32, f32)`, `(i32, i32)`, ...)
* `Angle` type for handling angles in degrees/radians * `Angle` type for handling angles in degrees/radians
@ -47,4 +49,5 @@ It provides, including but not limited to:
* utils * utils
* Poorly-named `target_and_other` function for taking 2 entities, a predecate, and returning `Some((match, other))` if one matches or `None` if neither do. Good for, say, taking in a collision pair and returning a bullet entity first * Poorly-named `target_and_other` function for taking 2 entities, a predecate, and returning `Some((match, other))` if one matches or `None` if neither do. Good for, say, taking in a collision pair and returning a bullet entity first
* error * error
* Logger for logging piped errors in systems * Logger for logging panic stacktraces
* Panic handler for sending stacktraces to [Sentry](https://sentry.io) in release builds

22
src/commands.rs Normal file
View File

@ -0,0 +1,22 @@
use bevy::{
ecs::{system::Command, world::EntityMut},
prelude::*,
};
struct RunIfExistsCommand<F>(Entity, F);
impl<F: FnOnce(EntityMut) + Send + Sync + 'static> Command for RunIfExistsCommand<F> {
fn write(self, world: &mut World) {
world.get_entity_mut(self.0).map(self.1);
}
}
pub trait RunIfExistsExt {
fn run_if_exists(&mut self, entity: Entity, f: impl FnOnce(EntityMut) + Send + Sync + 'static);
}
impl RunIfExistsExt for Commands<'_, '_> {
fn run_if_exists(&mut self, entity: Entity, f: impl FnOnce(EntityMut) + Send + Sync + 'static) {
self.add(RunIfExistsCommand(entity, f));
}
}

View File

@ -2,11 +2,12 @@ use std::{
cmp::{max, min}, cmp::{max, min},
f32::consts::PI, f32::consts::PI,
fmt::Display, fmt::Display,
marker::PhantomData,
ops::Sub, ops::Sub,
sync::RwLock, sync::RwLock,
}; };
use bevy::{app::PluginGroupBuilder, prelude::*, utils::FloatOrd}; use bevy::{app::PluginGroupBuilder, ecs::query::WorldQuery, prelude::*, utils::FloatOrd};
use bevy_rapier2d::{ use bevy_rapier2d::{
parry::query::{closest_points, distance, ClosestPoints}, parry::query::{closest_points, distance, ClosestPoints},
prelude::*, prelude::*,
@ -656,21 +657,23 @@ fn sync_config(config: Res<CoreConfig>) {
} }
} }
pub struct CorePlugin { pub struct CorePlugin<RapierUserData> {
pub relative_direction_mode: RelativeDirectionMode, pub relative_direction_mode: RelativeDirectionMode,
pub pixels_per_unit: u8, pub pixels_per_unit: u8,
pub rapier_user_data: PhantomData<RapierUserData>,
} }
impl Default for CorePlugin { impl<RapierUserData> Default for CorePlugin<RapierUserData> {
fn default() -> Self { fn default() -> Self {
Self { Self {
relative_direction_mode: RelativeDirectionMode::Directional, relative_direction_mode: RelativeDirectionMode::Directional,
pixels_per_unit: 1, pixels_per_unit: 1,
rapier_user_data: default(),
} }
} }
} }
impl Plugin for CorePlugin { impl<RapierUserData: 'static + WorldQuery + Send + Sync> Plugin for CorePlugin<RapierUserData> {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
let config = CoreConfig { let config = CoreConfig {
relative_direction_mode: self.relative_direction_mode, relative_direction_mode: self.relative_direction_mode,
@ -678,7 +681,7 @@ impl Plugin for CorePlugin {
}; };
app.insert_resource(config) app.insert_resource(config)
.register_type::<CardinalDirection>() .register_type::<CardinalDirection>()
.add_plugin(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter( .add_plugin(RapierPhysicsPlugin::<RapierUserData>::pixels_per_meter(
config.pixels_per_unit as f32, config.pixels_per_unit as f32,
)) ))
.add_startup_system(setup) .add_startup_system(setup)
@ -686,13 +689,21 @@ impl Plugin for CorePlugin {
} }
} }
pub struct CorePlugins; pub struct CorePlugins<RapierUserData>(PhantomData<RapierUserData>);
impl PluginGroup for CorePlugins { impl<RapierUserData> Default for CorePlugins<RapierUserData> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<RapierUserData: 'static + WorldQuery + Send + Sync> PluginGroup
for CorePlugins<RapierUserData>
{
fn build(self) -> PluginGroupBuilder { fn build(self) -> PluginGroupBuilder {
PluginGroupBuilder::start::<Self>() PluginGroupBuilder::start::<Self>()
.add(crate::bevy_tts::TtsPlugin) .add(crate::bevy_tts::TtsPlugin)
.add(crate::bevy_synthizer::SynthizerPlugin::default()) .add(crate::bevy_synthizer::SynthizerPlugin::default())
.add(CorePlugin::default()) .add(CorePlugin::<RapierUserData>::default())
} }
} }

View File

@ -1,5 +1,7 @@
use std::error::Error; use std::error::Error;
use std::{panic, thread};
use backtrace::Backtrace;
use bevy::prelude::*; use bevy::prelude::*;
pub fn error_handler(In(result): In<Result<(), Box<dyn Error>>>) { pub fn error_handler(In(result): In<Result<(), Box<dyn Error>>>) {
@ -7,3 +9,45 @@ pub fn error_handler(In(result): In<Result<(), Box<dyn Error>>>) {
error!("{}", e); error!("{}", e);
} }
} }
fn init_panic_handler() {
panic::set_hook(Box::new(|info| {
let backtrace = Backtrace::default();
let thread = thread::current();
let thread = thread.name().unwrap_or("<unnamed>");
let msg = match info.payload().downcast_ref::<&'static str>() {
Some(s) => *s,
None => match info.payload().downcast_ref::<String>() {
Some(s) => &**s,
None => "Box<Any>",
},
};
match info.location() {
Some(location) => {
error!(
target: "panic", "thread '{}' panicked at '{}': {}:{}{:?}",
thread,
msg,
location.file(),
location.line(),
backtrace
);
}
None => error!(
target: "panic",
"thread '{}' panicked at '{}'{:?}",
thread,
msg,
backtrace
),
}
}));
}
pub struct ErrorPlugin;
impl Plugin for ErrorPlugin {
fn build(&self, _app: &mut App) {
init_panic_handler();
}
}

View File

@ -62,7 +62,7 @@ where
ExplorationType: Component + Default + Copy + Ord, ExplorationType: Component + Default + Copy + Ord,
State: 'static + Clone + Debug + Eq + Hash + Send + Sync, State: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{ {
for (actions, visible, mut focused) in &mut explorers { for (actions, visible, mut focused) in explorers.iter_mut() {
let mut types: Vec<ExplorationType> = vec![]; let mut types: Vec<ExplorationType> = vec![];
for e in visible.iter() { for e in visible.iter() {
if let Ok(t) = features.get(*e) { if let Ok(t) = features.get(*e) {
@ -128,7 +128,7 @@ where
ExplorationType: Component + Default + PartialEq, ExplorationType: Component + Default + PartialEq,
State: 'static + Clone + Debug + Eq + Hash + Send + Sync, State: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{ {
for (entity, actions, visible_entities, focused_type, exploring) in &explorers { for (entity, actions, visible_entities, focused_type, exploring) in explorers.iter() {
let mut features = features let mut features = features
.iter() .iter()
.filter(|v| visible_entities.contains(&v.0)) .filter(|v| visible_entities.contains(&v.0))
@ -177,7 +177,7 @@ fn exploration_type_changed_announcement<ExplorationType>(
focused: Query< focused: Query<
( (
&FocusedExplorationType<ExplorationType>, &FocusedExplorationType<ExplorationType>,
Ref<FocusedExplorationType<ExplorationType>>, ChangeTrackers<FocusedExplorationType<ExplorationType>>,
), ),
Changed<FocusedExplorationType<ExplorationType>>, Changed<FocusedExplorationType<ExplorationType>>,
>, >,
@ -185,7 +185,7 @@ fn exploration_type_changed_announcement<ExplorationType>(
where where
ExplorationType: Component + Default + Copy + Into<String>, ExplorationType: Component + Default + Copy + Into<String>,
{ {
for (focused, changed) in &focused { for (focused, changed) in focused.iter() {
if changed.is_added() { if changed.is_added() {
return Ok(()); return Ok(());
} }
@ -218,7 +218,7 @@ fn exploration_focus<State, MapData>(
State: 'static + Clone + Debug + Eq + Hash + Send + Sync, State: 'static + Clone + Debug + Eq + Hash + Send + Sync,
MapData: 'static + Clone + Default + Send + Sync, MapData: 'static + Clone + Default + Send + Sync,
{ {
for (entity, actions, transform, exploring) in &explorers { for (entity, actions, transform, exploring) in explorers.iter() {
let coordinates = transform.translation; let coordinates = transform.translation;
let mut exploring = if let Some(exploring) = exploring { let mut exploring = if let Some(exploring) = exploring {
**exploring **exploring
@ -260,8 +260,8 @@ fn navigate_to_explored<State, MapData>(
State: 'static + Clone + Debug + Eq + Hash + Send + Sync, State: 'static + Clone + Debug + Eq + Hash + Send + Sync,
MapData: 'static + Clone + Default + Send + Sync, MapData: 'static + Clone + Default + Send + Sync,
{ {
for (entity, actions, exploring) in &explorers { for (entity, actions, exploring) in explorers.iter() {
for (map, revealed_tiles) in &map { for (map, revealed_tiles) in map.iter() {
let point = **exploring; let point = **exploring;
let idx = point.to_index(map.width); let idx = point.to_index(map.width);
let known = revealed_tiles[idx]; let known = revealed_tiles[idx];
@ -363,19 +363,25 @@ fn cleanup(
explorers: Query<Entity, With<Exploring>>, explorers: Query<Entity, With<Exploring>>,
focus: Query<Entity, With<ExplorationFocused>>, focus: Query<Entity, With<ExplorationFocused>>,
) { ) {
for entity in &explorers { for entity in explorers.iter() {
commands.entity(entity).remove::<Exploring>(); commands.entity(entity).remove::<Exploring>();
} }
for entity in &focus { for entity in focus.iter() {
commands.entity(entity).remove::<ExplorationFocused>(); commands.entity(entity).remove::<ExplorationFocused>();
} }
} }
#[derive(Resource, Clone, Debug, Default)] #[derive(Resource, Clone, Debug)]
struct ExplorationConfig<State> { struct ExplorationConfig<State> {
states: Vec<State>, states: Vec<State>,
} }
impl<State> Default for ExplorationConfig<State> {
fn default() -> Self {
Self { states: vec![] }
}
}
#[derive(Resource, Clone, Default)] #[derive(Resource, Clone, Default)]
pub struct ExplorationPlugin<ExplorationType, State, MapData> { pub struct ExplorationPlugin<ExplorationType, State, MapData> {
pub states: Vec<State>, pub states: Vec<State>,
@ -383,13 +389,10 @@ pub struct ExplorationPlugin<ExplorationType, State, MapData> {
pub map_data: PhantomData<MapData>, pub map_data: PhantomData<MapData>,
} }
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub struct Exploration;
impl<ExplorationType, State, MapData> Plugin for ExplorationPlugin<ExplorationType, State, MapData> impl<ExplorationType, State, MapData> Plugin for ExplorationPlugin<ExplorationType, State, MapData>
where where
ExplorationType: 'static + Component + Default + Copy + Ord + PartialEq + Into<String>, ExplorationType: 'static + Component + Default + Copy + Ord + PartialEq + Into<String>,
State: States, State: 'static + Clone + Debug + Eq + Hash + Send + Sync,
MapData: 'static + Clone + Default + Send + Sync, MapData: 'static + Clone + Default + Send + Sync,
{ {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
@ -401,30 +404,37 @@ where
.register_type::<Mappable>() .register_type::<Mappable>()
.register_type::<Explorable>() .register_type::<Explorable>()
.add_plugin(InputManagerPlugin::<ExplorationAction>::default()) .add_plugin(InputManagerPlugin::<ExplorationAction>::default())
.add_systems( .add_system(
( exploration_changed_announcement::<ExplorationType, MapData>.pipe(error_handler),
exploration_type_change::<ExplorationType, State>.pipe(error_handler), );
if config.states.is_empty() {
app.add_system(exploration_focus::<State, MapData>)
.add_system(exploration_type_focus::<ExplorationType, State>.pipe(error_handler))
.add_system(exploration_type_change::<ExplorationType, State>.pipe(error_handler))
.add_system(navigate_to_explored::<State, MapData>)
.add_system_to_stage(
CoreStage::PostUpdate,
exploration_type_changed_announcement::<ExplorationType>.pipe(error_handler), exploration_type_changed_announcement::<ExplorationType>.pipe(error_handler),
) );
.chain() } else {
.in_set(Exploration),
)
.add_systems(
(
exploration_focus::<State, MapData>,
exploration_type_focus::<ExplorationType, State>.pipe(error_handler),
exploration_changed_announcement::<ExplorationType, MapData>
.pipe(error_handler),
)
.chain()
.in_set(Exploration),
)
.add_system(navigate_to_explored::<State, MapData>.in_set(Exploration));
if !config.states.is_empty() {
let states = config.states; let states = config.states;
for state in states { for state in states {
app.configure_set(Exploration.in_set(OnUpdate(state.clone()))) app.add_system_set(
.add_system(cleanup.in_schedule(OnExit(state))); SystemSet::on_update(state.clone())
.with_system(exploration_focus::<State, MapData>)
.with_system(
exploration_type_focus::<ExplorationType, State>.pipe(error_handler),
)
.with_system(
exploration_type_change::<ExplorationType, State>.pipe(error_handler),
)
.with_system(navigate_to_explored::<State, MapData>)
.with_system(
exploration_type_changed_announcement::<ExplorationType>
.pipe(error_handler),
),
)
.add_system_set(SystemSet::on_exit(state).with_system(cleanup));
} }
} }
} }

View File

@ -6,6 +6,7 @@ pub use bevy;
pub use bevy_rapier2d; pub use bevy_rapier2d;
pub use bevy_synthizer; pub use bevy_synthizer;
pub use bevy_tts; pub use bevy_tts;
pub mod commands;
pub use coord_2d; pub use coord_2d;
#[macro_use] #[macro_use]
pub mod core; pub mod core;
@ -19,6 +20,7 @@ pub mod log;
pub mod map; pub mod map;
pub mod navigation; pub mod navigation;
pub mod pathfinding; pub mod pathfinding;
pub mod pitch_shift;
pub use rand; pub use rand;
pub use shadowcast; pub use shadowcast;
pub mod sound; pub mod sound;

View File

@ -41,7 +41,7 @@ fn read_log(
mut position: Local<usize>, mut position: Local<usize>,
log: Query<&Log, Changed<Log>>, log: Query<&Log, Changed<Log>>,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
for log in &log { for log in log.iter() {
if *position >= log.len() { if *position >= log.len() {
*position = 0; *position = 0;
} }
@ -61,10 +61,6 @@ impl Plugin for LogPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.register_type::<LogEntry>() app.register_type::<LogEntry>()
.add_startup_system(setup) .add_startup_system(setup)
.add_system( .add_system_to_stage(CoreStage::PostUpdate, read_log.pipe(error_handler));
read_log
.pipe(error_handler)
.in_base_set(CoreSet::PostUpdate),
);
} }
} }

View File

@ -183,7 +183,7 @@ fn spawn_colliders<D: 'static + Clone + Default + Send + Sync>(
mut commands: Commands, mut commands: Commands,
maps: Query<(Entity, &Map<D>, &SpawnColliders), Changed<SpawnColliders>>, maps: Query<(Entity, &Map<D>, &SpawnColliders), Changed<SpawnColliders>>,
) { ) {
for (map_entity, map, spawn_colliders) in &maps { for (map_entity, map, spawn_colliders) in maps.iter() {
if **spawn_colliders { if **spawn_colliders {
commands commands
.entity(map_entity) .entity(map_entity)
@ -244,7 +244,7 @@ fn spawn_portals<D: 'static + Clone + Default + Send + Sync>(
mut commands: Commands, mut commands: Commands,
map: Query<(Entity, &Map<D>, &SpawnPortals), Changed<SpawnPortals>>, map: Query<(Entity, &Map<D>, &SpawnPortals), Changed<SpawnPortals>>,
) { ) {
for (map_entity, map, spawn_portals) in &map { for (map_entity, map, spawn_portals) in map.iter() {
if **spawn_portals { if **spawn_portals {
commands.entity(map_entity).remove::<SpawnPortals>(); commands.entity(map_entity).remove::<SpawnPortals>();
let mut portals: Vec<(f32, f32)> = vec![]; let mut portals: Vec<(f32, f32)> = vec![];
@ -297,9 +297,9 @@ fn spawn_portal_colliders<D: 'static + Clone + Default + Send + Sync>(
map: Query<(Entity, &SpawnColliders), With<Map<D>>>, map: Query<(Entity, &SpawnColliders), With<Map<D>>>,
portals: Query<Entity, (With<Portal>, Without<Collider>)>, portals: Query<Entity, (With<Portal>, Without<Collider>)>,
) { ) {
for (entity, spawn_colliders) in &map { for (entity, spawn_colliders) in map.iter() {
if **spawn_colliders { if **spawn_colliders {
for portal_entity in &portals { for portal_entity in portals.iter() {
commands commands
.entity(portal_entity) .entity(portal_entity)
.insert((Collider::cuboid(0.5, 0.5), Sensor)); .insert((Collider::cuboid(0.5, 0.5), Sensor));
@ -328,13 +328,8 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for MapPlugin<MapD
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.insert_resource(self.clone()) app.insert_resource(self.clone())
.register_type::<Portal>() .register_type::<Portal>()
.add_systems( .add_system_to_stage(CoreStage::PreUpdate, spawn_colliders::<MapData>)
( .add_system_to_stage(CoreStage::PreUpdate, spawn_portals::<MapData>)
spawn_colliders::<MapData>, .add_system_to_stage(CoreStage::PreUpdate, spawn_portal_colliders::<MapData>);
spawn_portals::<MapData>,
spawn_portal_colliders::<MapData>,
)
.in_base_set(CoreSet::PreUpdate),
);
} }
} }

View File

@ -6,6 +6,7 @@ use bevy_tts::Tts;
use leafwing_input_manager::{axislike::DualAxisData, prelude::*}; use leafwing_input_manager::{axislike::DualAxisData, prelude::*};
use crate::{ use crate::{
commands::RunIfExistsExt,
core::{Angle, Area, CardinalDirection, GlobalTransformExt, Player}, core::{Angle, Area, CardinalDirection, GlobalTransformExt, Player},
error::error_handler, error::error_handler,
exploration::{ExplorationFocused, Exploring}, exploration::{ExplorationFocused, Exploring},
@ -82,58 +83,6 @@ impl Default for Speed {
} }
} }
fn snap(
mut tts: ResMut<Tts>,
mut snap_timers: ResMut<SnapTimers>,
mut query: Query<
(
Entity,
&ActionState<NavigationAction>,
&mut Transform,
&CardinalDirection,
),
With<Player>,
>,
) -> Result<(), Box<dyn Error>> {
for (entity, actions, mut transform, direction) in &mut query {
if snap_timers.contains_key(&entity) {
continue;
} else if actions.just_pressed(NavigationAction::SnapLeft) {
snap_timers.insert(entity, SnapTimer::default());
transform.rotation = Quat::from_rotation_z(match direction {
CardinalDirection::North => PI,
CardinalDirection::East => PI / 2.,
CardinalDirection::South => 0.,
CardinalDirection::West => -PI / 2.,
});
} else if actions.just_pressed(NavigationAction::SnapRight) {
snap_timers.insert(entity, SnapTimer::default());
transform.rotation = Quat::from_rotation_z(match direction {
CardinalDirection::North => 0.,
CardinalDirection::East => -PI / 2.,
CardinalDirection::South => PI,
CardinalDirection::West => PI / 2.,
});
} else if actions.just_pressed(NavigationAction::SnapReverse) {
snap_timers.insert(entity, SnapTimer::default());
transform.rotate(Quat::from_rotation_z(PI));
} else if actions.just_pressed(NavigationAction::SnapCardinal) {
let yaw: Angle = direction.into();
let yaw = yaw.radians();
transform.rotation = Quat::from_rotation_z(yaw);
tts.speak(direction.to_string(), true)?;
}
}
Ok(())
}
fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
for timer in snap_timers.values_mut() {
timer.tick(time.delta());
}
snap_timers.retain(|_, v| !v.finished());
}
fn controls( fn controls(
mut commands: Commands, mut commands: Commands,
time: Res<Time>, time: Res<Time>,
@ -275,12 +224,63 @@ fn controls(
} }
if cleanup { if cleanup {
commands.entity(entity).remove::<Exploring>(); commands.entity(entity).remove::<Exploring>();
for entity in &exploration_focused { for entity in exploration_focused.iter() {
commands.entity(entity).remove::<ExplorationFocused>(); commands.entity(entity).remove::<ExplorationFocused>();
} }
} }
} }
} }
fn snap(
mut tts: ResMut<Tts>,
mut snap_timers: ResMut<SnapTimers>,
mut query: Query<
(
Entity,
&ActionState<NavigationAction>,
&mut Transform,
&CardinalDirection,
),
With<Player>,
>,
) -> Result<(), Box<dyn Error>> {
for (entity, actions, mut transform, direction) in &mut query {
if snap_timers.contains_key(&entity) {
continue;
} else if actions.just_pressed(NavigationAction::SnapLeft) {
snap_timers.insert(entity, SnapTimer::default());
transform.rotation = Quat::from_rotation_z(match direction {
CardinalDirection::North => PI,
CardinalDirection::East => PI / 2.,
CardinalDirection::South => 0.,
CardinalDirection::West => -PI / 2.,
});
} else if actions.just_pressed(NavigationAction::SnapRight) {
snap_timers.insert(entity, SnapTimer::default());
transform.rotation = Quat::from_rotation_z(match direction {
CardinalDirection::North => 0.,
CardinalDirection::East => -PI / 2.,
CardinalDirection::South => PI,
CardinalDirection::West => PI / 2.,
});
} else if actions.just_pressed(NavigationAction::SnapReverse) {
snap_timers.insert(entity, SnapTimer::default());
transform.rotate(Quat::from_rotation_z(PI));
} else if actions.just_pressed(NavigationAction::SnapCardinal) {
let yaw: Angle = direction.into();
let yaw = yaw.radians();
transform.rotation = Quat::from_rotation_z(yaw);
tts.speak(direction.to_string(), true)?;
}
}
Ok(())
}
fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
for timer in snap_timers.values_mut() {
timer.tick(time.delta());
}
snap_timers.retain(|_, v| !v.finished());
}
fn update_direction( fn update_direction(
mut commands: Commands, mut commands: Commands,
@ -289,7 +289,7 @@ fn update_direction(
(With<Player>, Changed<Transform>), (With<Player>, Changed<Transform>),
>, >,
) { ) {
for (entity, transform, direction) in &mut query { for (entity, transform, direction) in query.iter_mut() {
let yaw = transform.yaw(); let yaw = transform.yaw();
let new_direction: CardinalDirection = yaw.into(); let new_direction: CardinalDirection = yaw.into();
if let Some(mut direction) = direction { if let Some(mut direction) = direction {
@ -304,12 +304,14 @@ fn update_direction(
fn remove_direction( fn remove_direction(
mut commands: Commands, mut commands: Commands,
mut removed: RemovedComponents<Transform>, removed: RemovedComponents<Transform>,
directions: Query<&CardinalDirection>, directions: Query<&CardinalDirection>,
) { ) {
for entity in &mut removed { for entity in removed.iter() {
if directions.contains(entity) { if directions.contains(entity) {
commands.entity(entity).remove::<CardinalDirection>(); commands.run_if_exists(entity, |mut entity| {
entity.remove::<CardinalDirection>();
});
} }
} }
} }
@ -317,7 +319,7 @@ fn remove_direction(
fn speak_direction( fn speak_direction(
mut tts: ResMut<Tts>, mut tts: ResMut<Tts>,
player: Query< player: Query<
(&CardinalDirection, Ref<CardinalDirection>), (&CardinalDirection, ChangeTrackers<CardinalDirection>),
(With<Player>, Changed<CardinalDirection>), (With<Player>, Changed<CardinalDirection>),
>, >,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
@ -331,7 +333,7 @@ fn speak_direction(
} }
fn add_speed(mut commands: Commands, query: Query<Entity, (Added<Speed>, Without<Velocity>)>) { fn add_speed(mut commands: Commands, query: Query<Entity, (Added<Speed>, Without<Velocity>)>) {
for entity in &query { for entity in query.iter() {
commands.entity(entity).insert(Velocity { commands.entity(entity).insert(Velocity {
linvel: Vec2::ZERO, linvel: Vec2::ZERO,
..default() ..default()
@ -382,8 +384,7 @@ fn log_area_descriptions<State>(
} }
} }
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)] pub const MOVEMENT_CONTROLS: &str = "MOVEMENT_CONTROLS";
pub struct Movement;
#[derive(Resource, Clone, Debug)] #[derive(Resource, Clone, Debug)]
pub struct NavigationPlugin<State> { pub struct NavigationPlugin<State> {
@ -404,7 +405,7 @@ impl<State> Default for NavigationPlugin<State> {
impl<State> Plugin for NavigationPlugin<State> impl<State> Plugin for NavigationPlugin<State>
where where
State: States, State: 'static + Clone + Copy + Debug + Eq + Hash + Send + Sync,
{ {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.insert_resource(self.clone()); app.insert_resource(self.clone());
@ -415,19 +416,22 @@ where
.register_type::<RotationSpeed>() .register_type::<RotationSpeed>()
.register_type::<Speed>() .register_type::<Speed>()
.add_plugin(InputManagerPlugin::<NavigationAction>::default()) .add_plugin(InputManagerPlugin::<NavigationAction>::default())
.add_systems((update_direction, add_speed).in_base_set(CoreSet::PreUpdate)) .add_system_to_stage(CoreStage::PreUpdate, update_direction)
.add_systems( .add_system_to_stage(CoreStage::PostUpdate, remove_direction)
(snap.pipe(error_handler), controls) .add_system(tick_snap_timers)
.chain() .add_system(speak_direction.pipe(error_handler))
.in_set(Movement), .add_system(add_speed)
) .add_system_to_stage(CoreStage::PostUpdate, log_area_descriptions::<State>);
.add_systems((tick_snap_timers, speak_direction.pipe(error_handler))) if self.states.is_empty() {
.add_systems( app.add_system(controls.label(MOVEMENT_CONTROLS))
(remove_direction, log_area_descriptions::<State>).in_base_set(CoreSet::PostUpdate), .add_system(snap.pipe(error_handler).before(MOVEMENT_CONTROLS));
); } else {
if !self.states.is_empty() {
for state in &self.states { for state in &self.states {
app.configure_set(Movement.in_set(OnUpdate(state.clone()))); app.add_system_set(
SystemSet::on_update(*state)
.with_system(controls.label(MOVEMENT_CONTROLS))
.with_system(snap.pipe(error_handler).before(MOVEMENT_CONTROLS)),
);
} }
} }
} }

View File

@ -14,6 +14,7 @@ use leafwing_input_manager::{axislike::DualAxisData, plugin::InputManagerSystem,
use pathfinding::prelude::*; use pathfinding::prelude::*;
use crate::{ use crate::{
commands::RunIfExistsExt,
core::{PointLike, TransformExt}, core::{PointLike, TransformExt},
map::{Map, MapObstruction}, map::{Map, MapObstruction},
navigation::{NavigationAction, RotationSpeed}, navigation::{NavigationAction, RotationSpeed},
@ -234,16 +235,16 @@ fn calculate_path(
shape_clone, shape_clone,
) )
}); });
commands commands.run_if_exists(entity, |mut entity| {
.entity(entity) entity.insert(Calculating(task));
.insert(Calculating(task)) entity.remove::<Path>();
.remove::<Path>() entity.remove::<NoPath>();
.remove::<NoPath>(); });
} }
} }
fn poll_tasks(mut commands: Commands, mut query: Query<(Entity, &mut Calculating)>) { fn poll_tasks(mut commands: Commands, mut query: Query<(Entity, &mut Calculating)>) {
for (entity, mut calculating) in &mut query { for (entity, mut calculating) in query.iter_mut() {
if let Some(result) = future::block_on(future::poll_once(&mut **calculating)) { if let Some(result) = future::block_on(future::poll_once(&mut **calculating)) {
if let Some(path) = result { if let Some(path) = result {
trace!("{entity:?}: Path: {path:?}"); trace!("{entity:?}: Path: {path:?}");
@ -260,9 +261,9 @@ fn poll_tasks(mut commands: Commands, mut query: Query<(Entity, &mut Calculating
fn remove_destination( fn remove_destination(
mut commands: Commands, mut commands: Commands,
entities: &Entities, entities: &Entities,
mut removed: RemovedComponents<Destination>, removed: RemovedComponents<Destination>,
) { ) {
for entity in &mut removed { for entity in removed.iter() {
if entities.contains(entity) { if entities.contains(entity) {
commands.entity(entity).remove::<Calculating>(); commands.entity(entity).remove::<Calculating>();
} }
@ -323,7 +324,7 @@ fn negotiate_path(
start, start,
transform.yaw().radians(), transform.yaw().radians(),
direction, direction,
collider, &*collider,
rapier_context.integration_parameters.dt, rapier_context.integration_parameters.dt,
QueryFilter::new() QueryFilter::new()
.exclude_sensors() .exclude_sensors()
@ -407,13 +408,18 @@ impl Plugin for PathfindingPlugin {
.register_type::<NoPath>() .register_type::<NoPath>()
.register_type::<Path>() .register_type::<Path>()
.register_type::<CostMap>() .register_type::<CostMap>()
.add_systems((negotiate_path, poll_tasks).in_base_set(CoreSet::PreUpdate)) .add_system_to_stage(CoreStage::PreUpdate, calculate_path)
.add_systems( .add_system_to_stage(CoreStage::PostUpdate, remove_destination)
(actions, calculate_path) .add_system_to_stage(CoreStage::PreUpdate, poll_tasks)
.chain() .add_system_to_stage(
.in_base_set(CoreSet::PreUpdate) CoreStage::PreUpdate,
.after(InputManagerSystem::Tick), negotiate_path.after(InputManagerSystem::Tick),
) )
.add_system(remove_destination.in_base_set(CoreSet::PostUpdate)); .add_system_to_stage(
CoreStage::PreUpdate,
actions
.after(InputManagerSystem::Update)
.before(calculate_path),
);
} }
} }

View File

@ -4,6 +4,7 @@ use bevy::prelude::*;
use crate::{ use crate::{
bevy_synthizer::{Listener, Sound}, bevy_synthizer::{Listener, Sound},
commands::RunIfExistsExt,
sound::SoundIcon, sound::SoundIcon,
}; };
@ -21,7 +22,7 @@ fn tag_behind(
if config.downshift_behind { if config.downshift_behind {
if let Ok(listener_transform) = listener.get_single() { if let Ok(listener_transform) = listener.get_single() {
let listener_forward = listener_transform.forward(); let listener_forward = listener_transform.forward();
for (entity, transform, sound, icon) in &sounds { for (entity, transform, sound, icon) in sounds.iter() {
if icon.is_none() && sound.is_none() { if icon.is_none() && sound.is_none() {
continue; continue;
} }
@ -29,15 +30,21 @@ fn tag_behind(
let dot = v.dot(listener_forward); let dot = v.dot(listener_forward);
let is_behind = dot <= 0.; let is_behind = dot <= 0.;
if is_behind { if is_behind {
commands.entity(entity).insert(Behind); commands.run_if_exists(entity, |mut entity| {
entity.insert(Behind);
});
} else if !is_behind { } else if !is_behind {
commands.entity(entity).remove::<Behind>(); commands.run_if_exists(entity, |mut entity| {
entity.remove::<Behind>();
});
} }
} }
} }
} else { } else {
for entity in &behind { for entity in behind.iter() {
commands.entity(entity).remove::<Behind>(); commands.run_if_exists(entity, |mut entity| {
entity.remove::<Behind>();
});
} }
} }
} }
@ -54,7 +61,7 @@ fn behind_added(
mut last_sound_pitch: ResMut<LastSoundPitch>, mut last_sound_pitch: ResMut<LastSoundPitch>,
mut query: Query<(Entity, Option<&mut SoundIcon>, Option<&mut Sound>), Added<Behind>>, mut query: Query<(Entity, Option<&mut SoundIcon>, Option<&mut Sound>), Added<Behind>>,
) { ) {
for (entity, icon, sound) in &mut query { for (entity, icon, sound) in query.iter_mut() {
if let Some(mut icon) = icon { if let Some(mut icon) = icon {
icon.pitch *= config.downshift; icon.pitch *= config.downshift;
last_icon_pitch.insert(entity, icon.pitch); last_icon_pitch.insert(entity, icon.pitch);
@ -69,12 +76,12 @@ fn behind_removed(
config: Res<PitchShiftPlugin>, config: Res<PitchShiftPlugin>,
mut last_icon_pitch: ResMut<LastIconPitch>, mut last_icon_pitch: ResMut<LastIconPitch>,
mut last_sound_pitch: ResMut<LastSoundPitch>, mut last_sound_pitch: ResMut<LastSoundPitch>,
mut removed: RemovedComponents<Behind>, removed: RemovedComponents<Behind>,
mut icons: Query<&mut SoundIcon>, mut icons: Query<&mut SoundIcon>,
mut sounds: Query<&mut Sound>, mut sounds: Query<&mut Sound>,
) { ) {
let downshift = 1. / config.downshift; let downshift = 1. / config.downshift;
for entity in &mut removed { for entity in removed.iter() {
if let Ok(mut icon) = icons.get_mut(entity) { if let Ok(mut icon) = icons.get_mut(entity) {
icon.pitch *= downshift; icon.pitch *= downshift;
last_icon_pitch.remove(&entity); last_icon_pitch.remove(&entity);
@ -90,7 +97,7 @@ fn sound_icon_changed(
mut last_icon_pitch: ResMut<LastIconPitch>, mut last_icon_pitch: ResMut<LastIconPitch>,
mut icons: Query<(Entity, &mut SoundIcon), (With<Behind>, Changed<SoundIcon>)>, mut icons: Query<(Entity, &mut SoundIcon), (With<Behind>, Changed<SoundIcon>)>,
) { ) {
for (entity, mut icon) in &mut icons { for (entity, mut icon) in icons.iter_mut() {
let should_change = if let Some(pitch) = last_icon_pitch.get(&entity) { let should_change = if let Some(pitch) = last_icon_pitch.get(&entity) {
*pitch != icon.pitch *pitch != icon.pitch
} else { } else {
@ -108,7 +115,7 @@ fn sound_changed(
mut last_sound_pitch: ResMut<LastSoundPitch>, mut last_sound_pitch: ResMut<LastSoundPitch>,
mut sounds: Query<(Entity, &mut Sound), (With<Behind>, Without<SoundIcon>, Changed<Sound>)>, mut sounds: Query<(Entity, &mut Sound), (With<Behind>, Without<SoundIcon>, Changed<Sound>)>,
) { ) {
for (entity, mut sound) in &mut sounds { for (entity, mut sound) in sounds.iter_mut() {
let should_change = if let Some(pitch) = last_sound_pitch.get(&entity) { let should_change = if let Some(pitch) = last_sound_pitch.get(&entity) {
*pitch != sound.pitch *pitch != sound.pitch
} else { } else {
@ -127,7 +134,7 @@ fn sync_config(
behind: Query<Entity, With<Behind>>, behind: Query<Entity, With<Behind>>,
) { ) {
if config.is_changed() { if config.is_changed() {
for entity in &behind { for entity in behind.iter() {
commands.entity(entity).remove::<Behind>(); commands.entity(entity).remove::<Behind>();
} }
} }
@ -154,8 +161,11 @@ impl Plugin for PitchShiftPlugin {
.register_type::<Behind>() .register_type::<Behind>()
.init_resource::<LastIconPitch>() .init_resource::<LastIconPitch>()
.init_resource::<LastSoundPitch>() .init_resource::<LastSoundPitch>()
.add_system(tag_behind.in_base_set(CoreSet::PreUpdate)) .add_system_to_stage(CoreStage::PreUpdate, tag_behind)
.add_systems((behind_added, sound_icon_changed, sound_changed, sync_config)) .add_system(behind_added)
.add_system(behind_removed.in_base_set(CoreSet::PostUpdate)); .add_system_to_stage(CoreStage::PostUpdate, behind_removed)
.add_system(sound_icon_changed)
.add_system(sound_changed)
.add_system(sync_config);
} }
} }

View File

@ -4,7 +4,7 @@ use bevy::{prelude::*, transform::TransformSystem};
use bevy_synthizer::{Buffer, Sound}; use bevy_synthizer::{Buffer, Sound};
use rand::random; use rand::random;
use crate::core::PointLike; use crate::{commands::RunIfExistsExt, core::PointLike};
#[derive(Component, Clone, Debug, Reflect)] #[derive(Component, Clone, Debug, Reflect)]
#[reflect(Component)] #[reflect(Component)]
@ -29,12 +29,14 @@ impl Default for Footstep {
} }
fn added(mut commands: Commands, footsteps: Query<(Entity, &Footstep), Added<Footstep>>) { fn added(mut commands: Commands, footsteps: Query<(Entity, &Footstep), Added<Footstep>>) {
for (entity, footstep) in &footsteps { for (entity, footstep) in footsteps.iter() {
let buffer = footstep.buffer.clone(); let buffer = footstep.buffer.clone();
commands.entity(entity).insert(Sound { commands.run_if_exists(entity, move |mut entity| {
audio: buffer.into(), entity.insert(Sound {
paused: true, buffer,
..default() paused: true,
..default()
});
}); });
} }
} }
@ -44,7 +46,7 @@ fn update(
mut footsteps: Query<(Entity, &Footstep, &Parent, &mut Sound)>, mut footsteps: Query<(Entity, &Footstep, &Parent, &mut Sound)>,
transforms_storage: Query<&GlobalTransform>, transforms_storage: Query<&GlobalTransform>,
) { ) {
for (entity, footstep, parent, mut sound) in &mut footsteps { for (entity, footstep, parent, mut sound) in footsteps.iter_mut() {
if let Ok(transform) = transforms_storage.get(**parent) { if let Ok(transform) = transforms_storage.get(**parent) {
if let Some(last) = last_step_distance.get(&entity) { if let Some(last) = last_step_distance.get(&entity) {
let distance = last.0 + (last.1.distance(transform)); let distance = last.0 + (last.1.distance(transform));
@ -74,11 +76,10 @@ pub struct FootstepPlugin;
impl Plugin for FootstepPlugin { impl Plugin for FootstepPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.register_type::<Footstep>() app.register_type::<Footstep>()
.add_system(added.in_base_set(CoreSet::PreUpdate)) .add_system_to_stage(CoreStage::PreUpdate, added)
.add_system( .add_system_to_stage(
update CoreStage::PostUpdate,
.after(TransformSystem::TransformPropagate) update.after(TransformSystem::TransformPropagate),
.in_base_set(CoreSet::PostUpdate),
); );
} }
} }

View File

@ -1,11 +1,12 @@
use std::{fmt::Debug, time::Duration}; use std::{fmt::Debug, hash::Hash, time::Duration};
use bevy::prelude::*; use bevy::prelude::*;
use bevy_synthizer::{Audio, Buffer, Sound}; use bevy_synthizer::{Buffer, Sound};
use rand::random; use rand::random;
use crate::{ use crate::{
commands::RunIfExistsExt,
core::Player, core::Player,
exploration::ExplorationFocused, exploration::ExplorationFocused,
visibility::{VisibilityChanged, Visible, VisibleEntities}, visibility::{VisibilityChanged, Visible, VisibleEntities},
@ -38,18 +39,20 @@ impl Default for SoundIcon {
} }
fn added(mut commands: Commands, icons: Query<(Entity, &SoundIcon), Added<SoundIcon>>) { fn added(mut commands: Commands, icons: Query<(Entity, &SoundIcon), Added<SoundIcon>>) {
for (entity, icon) in &icons { for (entity, icon) in icons.iter() {
let buffer = icon.buffer.clone(); let buffer = icon.buffer.clone();
let gain = icon.gain; let gain = icon.gain;
let pitch = icon.pitch; let pitch = icon.pitch;
let looping = icon.interval.is_none(); let looping = icon.interval.is_none();
commands.entity(entity).insert(Sound { commands.run_if_exists(entity, move |mut entity| {
audio: buffer.into(), entity.insert(Sound {
gain, buffer,
pitch, gain,
looping, pitch,
paused: true, looping,
..default() paused: true,
..default()
});
}); });
} }
} }
@ -67,13 +70,13 @@ fn update<S>(
&mut Sound, &mut Sound,
)>, )>,
) where ) where
S: States, S: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{ {
if !config.states.is_empty() && !config.states.contains(&state.0) { if !config.states.is_empty() && !config.states.contains(state.current()) {
return; return;
} }
for visible in &viewers { for visible in viewers.iter() {
for (icon_entity, mut icon, visibility, parent, mut sound) in &mut icons { for (icon_entity, mut icon, visibility, parent, mut sound) in icons.iter_mut() {
let entity = if visibility.is_some() { let entity = if visibility.is_some() {
Some(icon_entity) Some(icon_entity)
} else if parent.is_some() { } else if parent.is_some() {
@ -94,9 +97,8 @@ fn update<S>(
} }
} }
let buffer = icon.buffer.clone(); let buffer = icon.buffer.clone();
let audio: Audio = buffer.into(); if sound.buffer != buffer {
if sound.audio != audio { sound.buffer = buffer;
sound.audio = audio;
} }
sound.gain = icon.gain; sound.gain = icon.gain;
sound.pitch = icon.pitch; sound.pitch = icon.pitch;
@ -115,7 +117,7 @@ fn exploration_focus_changed(
mut icons: Query<&mut SoundIcon>, mut icons: Query<&mut SoundIcon>,
) { ) {
const ICON_GAIN: f64 = 3.; const ICON_GAIN: f64 = 3.;
for (entity, children) in &mut focused { for (entity, children) in focused.iter_mut() {
if let Ok(mut icon) = icons.get_mut(entity) { if let Ok(mut icon) = icons.get_mut(entity) {
icon.gain *= ICON_GAIN; icon.gain *= ICON_GAIN;
} }
@ -130,12 +132,12 @@ fn exploration_focus_changed(
} }
fn exploration_focus_removed( fn exploration_focus_removed(
mut removed: RemovedComponents<ExplorationFocused>, removed: RemovedComponents<ExplorationFocused>,
mut query: Query<&mut SoundIcon>, mut query: Query<&mut SoundIcon>,
children: Query<&Children>, children: Query<&Children>,
) { ) {
const ICON_GAIN: f64 = 3.; const ICON_GAIN: f64 = 3.;
for entity in &mut removed { for entity in removed.iter() {
if let Ok(mut icon) = query.get_mut(entity) { if let Ok(mut icon) = query.get_mut(entity) {
icon.gain /= ICON_GAIN; icon.gain /= ICON_GAIN;
} }
@ -194,21 +196,21 @@ impl<S> Default for SoundIconPlugin<S> {
impl<S> Plugin for SoundIconPlugin<S> impl<S> Plugin for SoundIconPlugin<S>
where where
S: States, S: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{ {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.insert_resource(self.clone()) app.insert_resource(self.clone())
.register_type::<SoundIcon>() .register_type::<SoundIcon>()
.add_systems((added, reset_timer_on_visibility_gain).in_base_set(CoreSet::PreUpdate)) .add_system(added)
.add_systems( .add_system_to_stage(CoreStage::PostUpdate, update::<S>)
(exploration_focus_changed, update::<S>) .add_system_to_stage(
.chain() CoreStage::PostUpdate,
.in_base_set(CoreSet::PreUpdate), exploration_focus_changed.after(update::<S>),
) )
.add_system( .add_system_to_stage(
exploration_focus_removed CoreStage::PostUpdate,
.in_base_set(CoreSet::PostUpdate) exploration_focus_removed.after(exploration_focus_changed),
.after(exploration_focus_changed), )
); .add_system_to_stage(CoreStage::PostUpdate, reset_timer_on_visibility_gain);
} }
} }

View File

@ -1,18 +1,18 @@
use std::{fmt::Debug, hash::Hash};
use bevy::{app::PluginGroupBuilder, prelude::*}; use bevy::{app::PluginGroupBuilder, prelude::*};
pub mod footstep; pub mod footstep;
pub mod icon; pub mod icon;
pub mod pitch_shift;
pub mod volumetric; pub mod volumetric;
pub use footstep::Footstep; pub use footstep::Footstep;
pub use icon::{SoundIcon, SoundIconPlugin}; pub use icon::{SoundIcon, SoundIconPlugin};
pub use pitch_shift::PitchShiftPlugin;
pub use volumetric::Volumetric; pub use volumetric::Volumetric;
/*fn scale_sounds(config: Res<CoreConfig>, mut sounds: Query<&mut Sound>) { /*fn scale_sounds(config: Res<CoreConfig>, mut sounds: Query<&mut Sound>) {
let pixels_per_unit = config.pixels_per_unit as f32; let pixels_per_unit = config.pixels_per_unit as f32;
for mut sound in &mut sounds { for mut sound in sounds.iter_mut() {
sound.reference_distance *= pixels_per_unit; sound.reference_distance *= pixels_per_unit;
if sound.max_distance != f32::MAX { if sound.max_distance != f32::MAX {
sound.max_distance *= pixels_per_unit; sound.max_distance *= pixels_per_unit;
@ -30,13 +30,12 @@ impl<'a, S> Default for SoundPlugins<'a, S> {
impl<S> PluginGroup for SoundPlugins<'static, S> impl<S> PluginGroup for SoundPlugins<'static, S>
where where
S: States, S: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{ {
fn build(self) -> PluginGroupBuilder { fn build(self) -> PluginGroupBuilder {
PluginGroupBuilder::start::<Self>() PluginGroupBuilder::start::<Self>()
.add(footstep::FootstepPlugin) .add(footstep::FootstepPlugin)
.add(icon::SoundIconPlugin::<S>::default()) .add(icon::SoundIconPlugin::<S>::default())
.add(pitch_shift::PitchShiftPlugin::default())
.add(volumetric::VolumetricPlugin) .add(volumetric::VolumetricPlugin)
// .add_system(scale_sounds); // .add_system(scale_sounds);
} }

View File

@ -2,7 +2,7 @@ use bevy::{prelude::*, transform::TransformSystem};
use bevy_rapier2d::{parry::query::ClosestPoints, prelude::*}; use bevy_rapier2d::{parry::query::ClosestPoints, prelude::*};
use bevy_synthizer::{Listener, Sound}; use bevy_synthizer::{Listener, Sound};
use crate::core::GlobalTransformExt; use crate::{commands::RunIfExistsExt, core::GlobalTransformExt};
#[derive(Component, Default, Reflect, Clone, Copy, Debug)] #[derive(Component, Default, Reflect, Clone, Copy, Debug)]
#[reflect(Component)] #[reflect(Component)]
@ -39,15 +39,11 @@ fn update(
} }
} }
fn removed( fn removed(mut commands: Commands, removed: RemovedComponents<Volumetric>) {
mut commands: Commands, for entity in removed.iter() {
mut removed: RemovedComponents<Volumetric>, commands.run_if_exists(entity, |mut entity| {
transforms: Query<Entity, (With<Transform>, With<GlobalTransform>)>, entity.insert(TransformBundle::default());
) { });
for entity in &mut removed {
if transforms.get(entity).is_ok() {
commands.entity(entity).insert(TransformBundle::default());
}
} }
} }
@ -56,11 +52,10 @@ pub struct VolumetricPlugin;
impl Plugin for VolumetricPlugin { impl Plugin for VolumetricPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.register_type::<Volumetric>() app.register_type::<Volumetric>()
.add_system( .add_system_to_stage(
update CoreStage::PostUpdate,
.in_base_set(CoreSet::PostUpdate) update.before(TransformSystem::TransformPropagate),
.before(TransformSystem::TransformPropagate),
) )
.add_system(removed.in_base_set(CoreSet::PostUpdate)); .add_system_to_stage(CoreStage::PostUpdate, removed);
} }
} }

View File

@ -253,7 +253,7 @@ fn add_visibility_indices<MapData: 'static + Clone + Default + Send + Sync>(
map_config: Res<MapPlugin<MapData>>, map_config: Res<MapPlugin<MapData>>,
query: Query<(Entity, &Map<MapData>), (Added<Map<MapData>>, Without<RevealedTiles>)>, query: Query<(Entity, &Map<MapData>), (Added<Map<MapData>>, Without<RevealedTiles>)>,
) { ) {
for (entity, map) in &query { for (entity, map) in query.iter() {
let count = map.width * map.height; let count = map.width * map.height;
commands commands
.entity(entity) .entity(entity)
@ -262,11 +262,11 @@ fn add_visibility_indices<MapData: 'static + Clone + Default + Send + Sync>(
} }
fn viewshed_removed( fn viewshed_removed(
mut query: RemovedComponents<Viewshed>, query: RemovedComponents<Viewshed>,
visible_entities: Query<&VisibleEntities>, visible_entities: Query<&VisibleEntities>,
mut events: EventWriter<VisibilityChanged>, mut events: EventWriter<VisibilityChanged>,
) { ) {
for entity in &mut query { for entity in query.iter() {
if let Ok(visible) = visible_entities.get(entity) { if let Ok(visible) = visible_entities.get(entity) {
for e in visible.iter() { for e in visible.iter() {
events.send(VisibilityChanged::Lost { events.send(VisibilityChanged::Lost {
@ -314,7 +314,8 @@ fn update_viewshed(
return; return;
} }
let mut cache = HashMap::new(); let mut cache = HashMap::new();
for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers { for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in viewers.iter_mut()
{
viewshed.update( viewshed.update(
&viewer_entity, &viewer_entity,
&mut visible_entities, &mut visible_entities,
@ -329,7 +330,7 @@ fn update_viewshed(
} }
fn remove_visible( fn remove_visible(
mut removed: RemovedComponents<Visible>, removed: RemovedComponents<Visible>,
mut viewers: Query<( mut viewers: Query<(
Entity, Entity,
&mut Viewshed, &mut Viewshed,
@ -341,10 +342,10 @@ fn remove_visible(
obstructions: Query<&MapObstruction>, obstructions: Query<&MapObstruction>,
mut changed: EventWriter<VisibilityChanged>, mut changed: EventWriter<VisibilityChanged>,
) { ) {
if !removed.is_empty() { if removed.iter().len() != 0 {
let mut cache = HashMap::new(); let mut cache = HashMap::new();
for removed in &mut removed { for removed in removed.iter() {
for (viewer_entity, mut viewshed, mut visible_entities, start) in &mut viewers { for (viewer_entity, mut viewshed, mut visible_entities, start) in viewers.iter_mut() {
if !visible_entities.contains(&removed) { if !visible_entities.contains(&removed) {
continue; continue;
} }
@ -368,8 +369,8 @@ fn update_revealed_tiles<D: 'static + Clone + Default + Send + Sync>(
mut map: Query<(&Map<D>, &mut RevealedTiles)>, mut map: Query<(&Map<D>, &mut RevealedTiles)>,
viewers: Query<&Viewshed, (With<Player>, Changed<Viewshed>)>, viewers: Query<&Viewshed, (With<Player>, Changed<Viewshed>)>,
) { ) {
for viewshed in &viewers { for viewshed in viewers.iter() {
for (map, mut revealed_tiles) in &mut map { for (map, mut revealed_tiles) in map.iter_mut() {
for v in viewshed.visible_points.iter() { for v in viewshed.visible_points.iter() {
let idx = v.to_index(map.width); let idx = v.to_index(map.width);
if idx >= revealed_tiles.len() { if idx >= revealed_tiles.len() {
@ -440,15 +441,11 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Default for VisibilityPlu
impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlugin<MapData> { impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlugin<MapData> {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_event::<VisibilityChanged>() app.add_event::<VisibilityChanged>()
.add_systems( .add_system_to_stage(CoreStage::PreUpdate, add_visibility_indices::<MapData>)
( .add_system_to_stage(CoreStage::PreUpdate, update_viewshed)
add_visibility_indices::<MapData>, .add_system_to_stage(CoreStage::PostUpdate, viewshed_removed)
update_viewshed, .add_system_to_stage(CoreStage::PostUpdate, remove_visible)
update_revealed_tiles::<MapData>, .add_system_to_stage(CoreStage::PreUpdate, update_revealed_tiles::<MapData>)
log_visible, .add_system_to_stage(CoreStage::PreUpdate, log_visible);
)
.in_base_set(CoreSet::PreUpdate),
)
.add_systems((viewshed_removed, remove_visible).in_base_set(CoreSet::PostUpdate));
} }
} }