blackout/src/exploration.rs

474 lines
16 KiB
Rust
Raw Normal View History

use std::{error::Error, hash::Hash, marker::PhantomData};
2021-05-13 17:25:45 +00:00
use bevy::prelude::*;
use bevy_input_actionmap::InputMap;
use bevy_rapier2d::prelude::*;
2021-05-13 17:25:45 +00:00
use bevy_tts::Tts;
use derive_more::{Deref, DerefMut};
2021-07-13 17:22:50 +00:00
use mapgen::Tile;
2021-05-13 17:25:45 +00:00
use crate::{
core::{Coordinates, Player, PointLike},
error::error_handler,
map::Map,
pathfinding::Destination,
visibility::{RevealedTiles, Viewshed, VisibleTiles},
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Reflect)]
#[reflect(Component)]
pub struct ExplorationFocused;
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Reflect)]
pub enum ExplorationType {
2021-05-20 19:54:13 +00:00
Portal = 0,
2021-05-13 17:25:45 +00:00
Item = 1,
Character = 2,
Ally = 3,
Enemy = 4,
}
// Doesn't make sense to create from a `String`.
#[allow(clippy::from_over_into)]
impl Into<String> for ExplorationType {
fn into(self) -> String {
match self {
2021-05-20 19:54:13 +00:00
ExplorationType::Portal => "Portal".into(),
2021-05-13 17:25:45 +00:00
ExplorationType::Item => "Item".into(),
ExplorationType::Character => "Character".into(),
ExplorationType::Ally => "Ally".into(),
ExplorationType::Enemy => "Enemy".into(),
}
}
}
// Likewise.
#[allow(clippy::from_over_into)]
impl Into<&str> for ExplorationType {
fn into(self) -> &'static str {
match self {
2021-05-20 19:54:13 +00:00
ExplorationType::Portal => "exit",
2021-05-13 17:25:45 +00:00
ExplorationType::Item => "item",
ExplorationType::Character => "character",
ExplorationType::Ally => "ally",
ExplorationType::Enemy => "enemy",
}
}
}
#[derive(Clone, Copy, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct Exploring(pub (f32, f32));
impl_pointlike_for_tuple_component!(Exploring);
#[derive(Clone, Debug, Default, Deref, DerefMut)]
pub struct FocusedExplorationType(pub Option<ExplorationType>);
#[derive(Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct Mappable;
fn exploration_type_change<A: 'static>(
config: Res<ExplorationConfig<A>>,
2021-05-13 17:25:45 +00:00
mut tts: ResMut<Tts>,
input: Res<InputMap<A>>,
2021-05-13 17:25:45 +00:00
mut explorers: Query<(&Player, &Viewshed, &mut FocusedExplorationType)>,
features: Query<(&Coordinates, &ExplorationType)>,
) -> Result<(), Box<dyn Error>>
where
A: Hash + Eq + Clone + Send + Sync,
{
if let (Some(select_next_type), Some(select_prev_type)) = (
config.action_explore_select_next_type.clone(),
config.action_explore_select_prev_type.clone(),
) {
let changed = input.just_active(select_next_type.clone())
|| input.just_active(select_prev_type.clone());
if !changed {
return Ok(());
2021-05-13 17:25:45 +00:00
}
for (_, viewshed, mut focused) in explorers.iter_mut() {
let mut types: Vec<ExplorationType> = vec![];
for (coordinates, t) in features.iter() {
let (x, y) = **coordinates;
let x = x as i32;
let y = y as i32;
if viewshed.visible.contains(&(x, y)) {
types.push(*t);
}
}
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);
}
2021-05-13 17:25:45 +00:00
} else {
let t = types.last().unwrap();
2021-05-13 17:25:45 +00:00
focused.0 = Some(*t);
}
} else {
let t = types.last().unwrap();
focused.0 = Some(*t);
}
} else if input.just_active(select_next_type.clone()) {
if let Some(t) = &focused.0 {
if let Some(i) = types.iter().position(|v| *v == *t) {
if i == types.len() - 1 {
focused.0 = None;
} else {
let t = &types[i + 1];
focused.0 = Some(*t);
}
2021-05-13 17:25:45 +00:00
} else {
let t = types.first().unwrap();
2021-05-13 17:25:45 +00:00
focused.0 = Some(*t);
}
} else {
let t = types.first().unwrap();
focused.0 = Some(*t)
2021-05-13 17:25:45 +00:00
}
}
}
}
Ok(())
}
fn exploration_type_focus<A: 'static>(
2021-05-13 17:25:45 +00:00
mut commands: Commands,
config: Res<ExplorationConfig<A>>,
input: Res<InputMap<A>>,
2021-05-13 17:25:45 +00:00
mut tts: ResMut<Tts>,
explorers: Query<(
Entity,
&Player,
&Viewshed,
&FocusedExplorationType,
Option<&Exploring>,
)>,
features: Query<(&Coordinates, &ExplorationType)>,
) -> Result<(), Box<dyn Error>>
where
A: Hash + Eq + Clone + Send + Sync,
{
if let (Some(explore_focus_next), Some(explore_focus_prev)) = (
config.action_explore_focus_next.clone(),
config.action_explore_focus_prev.clone(),
) {
let changed = input.just_active(explore_focus_next.clone())
|| input.just_active(explore_focus_prev.clone());
if !changed {
return Ok(());
2021-05-13 17:25:45 +00:00
}
for (entity, _, viewshed, focused, exploring) in explorers.iter() {
let mut features = features
.iter()
.filter(|(coordinates, _)| {
let (x, y) = ***coordinates;
let x = x as i32;
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() {
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 {
2021-05-13 17:25:45 +00:00
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();
2021-05-13 17:25:45 +00:00
}
}
if let Some((coordinates, _)) = target {
commands.entity(entity).insert(Exploring(***coordinates));
}
2021-05-13 17:25:45 +00:00
}
}
}
Ok(())
}
fn exploration_type_changed_announcement(
mut tts: ResMut<Tts>,
focused: Query<
(
&FocusedExplorationType,
ChangeTrackers<FocusedExplorationType>,
),
Changed<FocusedExplorationType>,
>,
) -> Result<(), Box<dyn Error>> {
for (focused, changed) in focused.iter() {
if changed.is_added() {
return Ok(());
}
match &focused.0 {
Some(v) => {
let v: String = (*v).into();
tts.speak(v, true)?;
}
None => {
tts.speak("Everything", true)?;
}
};
}
Ok(())
}
fn exploration_focus<A: 'static>(
2021-05-13 17:25:45 +00:00
mut commands: Commands,
config: Res<ExplorationConfig<A>>,
input: Res<InputMap<A>>,
2021-05-13 17:25:45 +00:00
map: Query<&Map>,
explorers: Query<(Entity, &Player, &Coordinates, Option<&Exploring>)>,
) where
A: Hash + Eq + Clone + Send + Sync,
{
if let (
Some(explore_forward),
Some(explore_backward),
Some(explore_left),
Some(explore_right),
) = (
config.action_explore_forward.clone(),
config.action_explore_backward.clone(),
config.action_explore_left.clone(),
config.action_explore_right.clone(),
) {
for map in map.iter() {
for (entity, _, coordinates, exploring) in explorers.iter() {
let coordinates = **coordinates;
let coordinates = (coordinates.0.floor(), coordinates.1.floor());
let mut exploring = if let Some(exploring) = exploring {
**exploring
} else {
coordinates
};
let orig = exploring;
if input.just_active(explore_forward.clone()) {
exploring.1 += 1.;
} 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.
2021-06-09 19:53:48 +00:00
&& exploring.0 < map.width as f32
&& exploring.1 >= 0.
2021-06-09 19:53:48 +00:00
&& exploring.1 < map.height as f32
{
commands.entity(entity).insert(Exploring(exploring));
}
2021-05-13 17:25:45 +00:00
}
}
}
}
fn navigate_to_explored<A: 'static>(
2021-05-13 17:25:45 +00:00
mut commands: Commands,
config: Res<ExplorationConfig<A>>,
input: Res<InputMap<A>>,
2021-05-13 17:25:45 +00:00
map: Query<(&Map, &RevealedTiles)>,
explorers: Query<(Entity, &Exploring)>,
) where
A: Hash + Eq + Clone + Send + Sync,
{
if let Some(navigate_to_explored) = config.action_navigate_to_explored.clone() {
for (entity, exploring) in explorers.iter() {
for (map, revealed_tiles) in map.iter() {
let point = **exploring;
2021-06-09 19:53:48 +00:00
let idx = point.to_index(map.width);
let known = revealed_tiles[idx];
if input.just_active(navigate_to_explored.clone()) && known {
commands
.entity(entity)
.insert(Destination((point.x_i32(), point.y_i32())));
}
2021-05-13 17:25:45 +00:00
}
}
}
}
fn exploration_changed_announcement(
mut commands: Commands,
mut tts: ResMut<Tts>,
map: Query<(&Map, &RevealedTiles, &VisibleTiles)>,
explorers: Query<(&Coordinates, &Exploring), Changed<Exploring>>,
focused: Query<(Entity, &ExplorationFocused)>,
names: Query<&Name>,
types: Query<&ExplorationType>,
mappables: Query<&Mappable>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
2021-05-13 17:25:45 +00:00
) -> Result<(), Box<dyn Error>> {
for (coordinates, exploring) in explorers.iter() {
let collider_set = QueryPipelineColliderComponentsSet(&collider_query);
2021-05-13 17:25:45 +00:00
let coordinates = **coordinates;
let coordinates = (coordinates.0.floor(), coordinates.1.floor());
for (map, revealed_tiles, visible_tiles) in map.iter() {
let point = **exploring;
2021-06-09 19:53:48 +00:00
let idx = point.to_index(map.width);
let shape = Cuboid::new(Vec2::new(0.5, 0.5).into());
2021-05-13 17:25:45 +00:00
let known = revealed_tiles[idx];
let visible = visible_tiles[idx];
let fog_of_war = known && !visible;
let description = if known {
let mut tokens: Vec<&str> = vec![];
for (entity, _) in focused.iter() {
commands.entity(entity).remove::<ExplorationFocused>();
}
let shape_pos = (Vec2::new(exploring.x(), exploring.y()), 0.);
query_pipeline.intersections_with_shape(
&collider_set,
&shape_pos.into(),
&shape,
InteractionGroups::all(),
None,
|handle| {
let entity = handle.entity();
commands
.entity(entity)
.insert(ExplorationFocused::default());
if visible || mappables.get(entity).is_ok() {
if let Ok(name) = names.get(entity) {
tokens.push(name.as_str());
}
if tokens.is_empty() {
if let Ok(t) = types.get(entity) {
tokens.push((*t).into());
}
2021-05-13 17:25:45 +00:00
}
}
true
},
);
2021-05-13 17:25:45 +00:00
if tokens.is_empty() {
2021-07-13 17:22:50 +00:00
let tile = map.tiles[idx];
if tile.is_blocked() {
"wall".to_string()
} else {
"floor".to_string()
2021-05-13 17:25:45 +00:00
}
} else {
tokens.join(": ")
}
} else {
"Unknown".to_string()
};
2021-05-16 22:24:26 +00:00
let mut tokens: Vec<String> = vec![coordinates.direction_and_distance(exploring, None)];
2021-05-13 17:25:45 +00:00
if fog_of_war {
tokens.push("in the fog of war".into());
}
tts.speak(format!("{}: {}", description, tokens.join(", ")), true)?;
}
}
Ok(())
}
#[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>,
}
2021-05-13 17:25:45 +00:00
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,
{
2021-05-13 17:25:45 +00:00
fn build(&self, app: &mut AppBuilder) {
if !app.world().contains_resource::<ExplorationConfig<A>>() {
app.insert_resource(ExplorationConfig::<A>::default());
}
2021-05-13 17:25:45 +00:00
app.register_type::<ExplorationFocused>()
.register_type::<ExplorationType>()
.register_type::<Mappable>()
.add_system(exploration_focus::<A>.system())
2021-05-13 17:25:45 +00:00
.add_system(
exploration_type_focus::<A>
2021-05-13 17:25:45 +00:00
.system()
.chain(error_handler.system()),
)
.add_system(
exploration_type_change::<A>
2021-05-13 17:25:45 +00:00
.system()
.chain(error_handler.system()),
)
.add_system(navigate_to_explored::<A>.system())
2021-05-13 17:25:45 +00:00
.add_system_to_stage(
CoreStage::PostUpdate,
exploration_type_changed_announcement
.system()
.chain(error_handler.system()),
)
.add_system_to_stage(
CoreStage::PostUpdate,
exploration_changed_announcement
.system()
.chain(error_handler.system()),
);
}
}