Make action type generic for ExplorationPlugin.

This commit is contained in:
Nolan Darilek 2021-05-26 17:30:16 -05:00
parent 4982838815
commit d5c580f165

View File

@ -1,4 +1,4 @@
use std::error::Error; use std::{error::Error, hash::Hash, marker::PhantomData};
use bevy::prelude::*; use bevy::prelude::*;
use bevy_input_actionmap::InputMap; use bevy_input_actionmap::InputMap;
@ -69,83 +69,83 @@ pub struct FocusedExplorationType(pub Option<ExplorationType>);
#[reflect(Component)] #[reflect(Component)]
pub struct Mappable; pub struct Mappable;
pub const ACTION_EXPLORE_FORWARD: &str = "explore_forward"; fn exploration_type_change<A: 'static>(
pub const ACTION_EXPLORE_BACKWARD: &str = "explore_backward"; config: Res<ExplorationConfig<A>>,
pub const ACTION_EXPLORE_LEFT: &str = "explore_left";
pub const ACTION_EXPLORE_RIGHT: &str = "explore_right";
pub const ACTION_EXPLORE_FOCUS_NEXT: &str = "explore_focus_next";
pub const ACTION_EXPLORE_FOCUS_PREV: &str = "explore_focus_prev";
pub const ACTION_EXPLORE_SELECT_NEXT_TYPE: &str = "explore_select_next_type";
pub const ACTION_EXPLORE_SELECT_PREV_TYPE: &str = "explore_select_prev_type";
pub const ACTION_NAVIGATE_TO_EXPLORED: &str = "navigate_to";
fn exploration_type_change(
mut tts: ResMut<Tts>, mut tts: ResMut<Tts>,
input: Res<InputMap<String>>, input: Res<InputMap<A>>,
mut explorers: Query<(&Player, &Viewshed, &mut FocusedExplorationType)>, mut explorers: Query<(&Player, &Viewshed, &mut FocusedExplorationType)>,
features: Query<(&Coordinates, &ExplorationType)>, features: Query<(&Coordinates, &ExplorationType)>,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>>
let changed = input.just_active(ACTION_EXPLORE_SELECT_NEXT_TYPE) where
|| input.just_active(ACTION_EXPLORE_SELECT_PREV_TYPE); A: Hash + Eq + Clone + Send + Sync,
if !changed { {
return Ok(()); if let (Some(select_next_type), Some(select_prev_type)) = (
} config.action_explore_select_next_type.clone(),
for (_, viewshed, mut focused) in explorers.iter_mut() { config.action_explore_select_prev_type.clone(),
let mut types: Vec<ExplorationType> = vec![]; ) {
for (coordinates, t) in features.iter() { let changed = input.just_active(select_next_type.clone())
let (x, y) = **coordinates; || input.just_active(select_prev_type.clone());
let x = x as i32; if !changed {
let y = y as i32; return Ok(());
if viewshed.visible.contains(&(x, y)) {
types.push(*t);
}
} }
types.sort(); for (_, viewshed, mut focused) in explorers.iter_mut() {
types.dedup(); let mut types: Vec<ExplorationType> = vec![];
if types.is_empty() { for (coordinates, t) in features.iter() {
tts.speak("Nothing visible.", true)?; let (x, y) = **coordinates;
} else if input.just_active(ACTION_EXPLORE_SELECT_PREV_TYPE) { let x = x as i32;
if let Some(t) = &focused.0 { let y = y as i32;
if let Some(i) = types.iter().position(|v| *v == *t) { if viewshed.visible.contains(&(x, y)) {
if i == 0 { types.push(*t);
focused.0 = None; }
}
types.sort();
types.dedup();
if types.is_empty() {
tts.speak("Nothing visible.", true)?;
} else if input.just_active(select_prev_type.clone()) {
if let Some(t) = &focused.0 {
if let Some(i) = types.iter().position(|v| *v == *t) {
if i == 0 {
focused.0 = None;
} else {
let t = &types[i - 1];
focused.0 = Some(*t);
}
} else { } else {
let t = &types[i - 1]; let t = types.last().unwrap();
focused.0 = Some(*t); focused.0 = Some(*t);
} }
} else { } else {
let t = types.last().unwrap(); let t = types.last().unwrap();
focused.0 = Some(*t); focused.0 = Some(*t);
} }
} else { } else if input.just_active(select_next_type.clone()) {
let t = types.last().unwrap(); if let Some(t) = &focused.0 {
focused.0 = Some(*t); if let Some(i) = types.iter().position(|v| *v == *t) {
} if i == types.len() - 1 {
} else if input.just_active(ACTION_EXPLORE_SELECT_NEXT_TYPE) { focused.0 = None;
if let Some(t) = &focused.0 { } else {
if let Some(i) = types.iter().position(|v| *v == *t) { let t = &types[i + 1];
if i == types.len() - 1 { focused.0 = Some(*t);
focused.0 = None; }
} else { } else {
let t = &types[i + 1]; let t = types.first().unwrap();
focused.0 = Some(*t); focused.0 = Some(*t);
} }
} else { } else {
let t = types.first().unwrap(); let t = types.first().unwrap();
focused.0 = Some(*t); focused.0 = Some(*t)
} }
} else {
let t = types.first().unwrap();
focused.0 = Some(*t)
} }
} }
} }
Ok(()) Ok(())
} }
fn exploration_type_focus( fn exploration_type_focus<A: 'static>(
mut commands: Commands, mut commands: Commands,
input: Res<InputMap<String>>, config: Res<ExplorationConfig<A>>,
input: Res<InputMap<A>>,
mut tts: ResMut<Tts>, mut tts: ResMut<Tts>,
explorers: Query<( explorers: Query<(
Entity, Entity,
@ -155,52 +155,60 @@ fn exploration_type_focus(
Option<&Exploring>, Option<&Exploring>,
)>, )>,
features: Query<(&Coordinates, &ExplorationType)>, features: Query<(&Coordinates, &ExplorationType)>,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>>
let changed = input.just_active(ACTION_EXPLORE_FOCUS_NEXT) where
|| input.just_active(ACTION_EXPLORE_FOCUS_PREV); A: Hash + Eq + Clone + Send + Sync,
if !changed { {
return Ok(()); if let (Some(explore_focus_next), Some(explore_focus_prev)) = (
} config.action_explore_focus_next.clone(),
for (entity, _, viewshed, focused, exploring) in explorers.iter() { config.action_explore_focus_prev.clone(),
let mut features = features ) {
.iter() let changed = input.just_active(explore_focus_next.clone())
.filter(|(coordinates, _)| { || input.just_active(explore_focus_prev.clone());
let (x, y) = ***coordinates; if !changed {
let x = x as i32; return Ok(());
let y = y as i32;
viewshed.visible.contains(&(x, y))
})
.collect::<Vec<(&Coordinates, &ExplorationType)>>();
features.sort_by(|(c1, _), (c2, _)| c1.partial_cmp(c2).unwrap());
if let Some(focused) = &focused.0 {
features.retain(|(_, t)| **t == *focused);
} }
if features.is_empty() { for (entity, _, viewshed, focused, exploring) in explorers.iter() {
tts.speak("Nothing visible.", true)?; let mut features = features
} else { .iter()
let mut target: Option<&(&Coordinates, &ExplorationType)> = None; .filter(|(coordinates, _)| {
if input.just_active(ACTION_EXPLORE_FOCUS_NEXT) { let (x, y) = ***coordinates;
if let Some(exploring) = exploring { let x = x as i32;
target = features.iter().find(|(c, _)| ***c > **exploring); let y = y as i32;
if target.is_none() { viewshed.visible.contains(&(x, y))
target = features.first(); })
} .collect::<Vec<(&Coordinates, &ExplorationType)>>();
} else { features.sort_by(|(c1, _), (c2, _)| c1.partial_cmp(c2).unwrap());
target = features.first(); if let Some(focused) = &focused.0 {
} features.retain(|(_, t)| **t == *focused);
} else if input.just_active(ACTION_EXPLORE_FOCUS_PREV) {
if let Some(exploring) = exploring {
features.reverse();
target = features.iter().find(|(c, _)| ***c < **exploring);
if target.is_none() {
target = features.first();
}
} else {
target = features.last();
}
} }
if let Some((coordinates, _)) = target { if features.is_empty() {
commands.entity(entity).insert(Exploring(***coordinates)); tts.speak("Nothing visible.", true)?;
} else {
let mut target: Option<&(&Coordinates, &ExplorationType)> = None;
if input.just_active(explore_focus_next.clone()) {
if let Some(exploring) = exploring {
target = features.iter().find(|(c, _)| ***c > **exploring);
if target.is_none() {
target = features.first();
}
} else {
target = features.first();
}
} else if input.just_active(explore_focus_prev.clone()) {
if let Some(exploring) = exploring {
features.reverse();
target = features.iter().find(|(c, _)| ***c < **exploring);
if target.is_none() {
target = features.first();
}
} else {
target = features.last();
}
}
if let Some((coordinates, _)) = target {
commands.entity(entity).insert(Exploring(***coordinates));
}
} }
} }
} }
@ -234,58 +242,78 @@ fn exploration_type_changed_announcement(
Ok(()) Ok(())
} }
fn exploration_focus( fn exploration_focus<A: 'static>(
mut commands: Commands, mut commands: Commands,
input: Res<InputMap<String>>, config: Res<ExplorationConfig<A>>,
input: Res<InputMap<A>>,
map: Query<&Map>, map: Query<&Map>,
explorers: Query<(Entity, &Player, &Coordinates, Option<&Exploring>)>, explorers: Query<(Entity, &Player, &Coordinates, Option<&Exploring>)>,
) { ) where
for map in map.iter() { A: Hash + Eq + Clone + Send + Sync,
for (entity, _, coordinates, exploring) in explorers.iter() { {
let coordinates = **coordinates; if let (
let coordinates = (coordinates.0.floor(), coordinates.1.floor()); Some(explore_forward),
let mut exploring = if let Some(exploring) = exploring { Some(explore_backward),
**exploring Some(explore_left),
} else { Some(explore_right),
coordinates ) = (
}; config.action_explore_forward.clone(),
let orig = exploring; config.action_explore_backward.clone(),
if input.just_active(ACTION_EXPLORE_FORWARD) { config.action_explore_left.clone(),
exploring.1 += 1.; config.action_explore_right.clone(),
} else if input.just_active(ACTION_EXPLORE_BACKWARD) { ) {
exploring.1 -= 1.; for map in map.iter() {
} else if input.just_active(ACTION_EXPLORE_LEFT) { for (entity, _, coordinates, exploring) in explorers.iter() {
exploring.0 -= 1.; let coordinates = **coordinates;
} else if input.just_active(ACTION_EXPLORE_RIGHT) { let coordinates = (coordinates.0.floor(), coordinates.1.floor());
exploring.0 += 1.; let mut exploring = if let Some(exploring) = exploring {
} **exploring
if orig != exploring } else {
&& exploring.0 >= 0. coordinates
&& exploring.0 < map.width() as f32 };
&& exploring.1 >= 0. let orig = exploring;
&& exploring.1 < map.height() as f32 if input.just_active(explore_forward.clone()) {
{ exploring.1 += 1.;
commands.entity(entity).insert(Exploring(exploring)); } else if input.just_active(explore_backward.clone()) {
exploring.1 -= 1.;
} else if input.just_active(explore_left.clone()) {
exploring.0 -= 1.;
} else if input.just_active(explore_right.clone()) {
exploring.0 += 1.;
}
if orig != exploring
&& exploring.0 >= 0.
&& exploring.0 < map.width() as f32
&& exploring.1 >= 0.
&& exploring.1 < map.height() as f32
{
commands.entity(entity).insert(Exploring(exploring));
}
} }
} }
} }
} }
fn navigate_to_explored( fn navigate_to_explored<A: 'static>(
mut commands: Commands, mut commands: Commands,
input: Res<InputMap<String>>, config: Res<ExplorationConfig<A>>,
input: Res<InputMap<A>>,
map: Query<(&Map, &RevealedTiles)>, map: Query<(&Map, &RevealedTiles)>,
explorers: Query<(Entity, &Exploring)>, explorers: Query<(Entity, &Exploring)>,
) { ) where
for (entity, exploring) in explorers.iter() { A: Hash + Eq + Clone + Send + Sync,
for (map, revealed_tiles) in map.iter() { {
let point = **exploring; if let Some(navigate_to_explored) = config.action_navigate_to_explored.clone() {
let idx = point.to_index(map.width()); for (entity, exploring) in explorers.iter() {
let known = revealed_tiles[idx]; for (map, revealed_tiles) in map.iter() {
if input.just_active(ACTION_NAVIGATE_TO_EXPLORED) && known { let point = **exploring;
commands let idx = point.to_index(map.width());
.entity(entity) let known = revealed_tiles[idx];
.insert(Destination((point.x_i32(), point.y_i32()))); if input.just_active(navigate_to_explored.clone()) && known {
commands
.entity(entity)
.insert(Destination((point.x_i32(), point.y_i32())));
}
} }
} }
} }
@ -351,25 +379,67 @@ fn exploration_changed_announcement(
Ok(()) Ok(())
} }
pub struct ExplorationPlugin; #[derive(Clone, Debug)]
pub struct ExplorationConfig<A> {
pub action_explore_forward: Option<A>,
pub action_explore_backward: Option<A>,
pub action_explore_left: Option<A>,
pub action_explore_right: Option<A>,
pub action_explore_focus_next: Option<A>,
pub action_explore_focus_prev: Option<A>,
pub action_explore_select_next_type: Option<A>,
pub action_explore_select_prev_type: Option<A>,
pub action_navigate_to_explored: Option<A>,
}
impl Plugin for ExplorationPlugin { impl<A> Default for ExplorationConfig<A> {
fn default() -> Self {
Self {
action_explore_forward: None,
action_explore_backward: None,
action_explore_left: None,
action_explore_right: None,
action_explore_focus_next: None,
action_explore_focus_prev: None,
action_explore_select_next_type: None,
action_explore_select_prev_type: None,
action_navigate_to_explored: None,
}
}
}
pub struct ExplorationPlugin<'a, A>(PhantomData<&'a A>);
impl<'a, A> Default for ExplorationPlugin<'a, A> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<'a, A> Plugin for ExplorationPlugin<'a, A>
where
A: Hash + Eq + Clone + Send + Sync,
'a: 'static,
{
fn build(&self, app: &mut AppBuilder) { fn build(&self, app: &mut AppBuilder) {
if !app.world().contains_resource::<ExplorationConfig<A>>() {
app.insert_resource(ExplorationConfig::<A>::default());
}
app.register_type::<ExplorationFocused>() app.register_type::<ExplorationFocused>()
.register_type::<ExplorationType>() .register_type::<ExplorationType>()
.register_type::<Mappable>() .register_type::<Mappable>()
.add_system(exploration_focus.system()) .add_system(exploration_focus::<A>.system())
.add_system( .add_system(
exploration_type_focus exploration_type_focus::<A>
.system() .system()
.chain(error_handler.system()), .chain(error_handler.system()),
) )
.add_system( .add_system(
exploration_type_change exploration_type_change::<A>
.system() .system()
.chain(error_handler.system()), .chain(error_handler.system()),
) )
.add_system(navigate_to_explored.system()) .add_system(navigate_to_explored::<A>.system())
.add_system_to_stage( .add_system_to_stage(
CoreStage::PostUpdate, CoreStage::PostUpdate,
exploration_type_changed_announcement exploration_type_changed_announcement