blackout/src/exploration.rs

442 lines
15 KiB
Rust
Raw Normal View History

2021-09-21 20:57:47 +00:00
use std::{error::Error, fmt::Debug, hash::Hash, marker::PhantomData};
2021-05-13 17:25:45 +00:00
use bevy::prelude::*;
use bevy_rapier2d::prelude::*;
2021-05-13 17:25:45 +00:00
use bevy_tts::Tts;
2022-08-02 22:15:22 +00:00
use leafwing_input_manager::prelude::*;
2021-05-13 17:25:45 +00:00
use crate::{
2022-05-10 18:56:49 +00:00
core::{Player, PointLike},
2021-05-13 17:25:45 +00:00
error::error_handler,
map::Map,
pathfinding::Destination,
visibility::{RevealedTiles, Viewshed, Visible, VisibleEntities},
2021-05-13 17:25:45 +00:00
};
2022-08-02 22:15:22 +00:00
#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Hash, Debug)]
pub enum ExplorationAction {
Forward,
Backward,
Left,
Right,
FocusNext,
FocusPrev,
SelectNextType,
SelectPrevType,
NavigateTo,
}
2022-01-10 19:50:52 +00:00
#[derive(Component, Clone, Copy, Debug, Default, PartialEq, Reflect)]
#[reflect(Component)]
pub struct Explorable;
2022-01-10 19:50:52 +00:00
#[derive(Component, Clone, Copy, Debug, Default, PartialEq, Reflect)]
2021-05-13 17:25:45 +00:00
#[reflect(Component)]
pub struct ExplorationFocused;
2022-01-10 19:50:52 +00:00
#[derive(Component, Clone, Copy, Debug, Default, Deref, DerefMut, Reflect)]
2021-05-13 17:25:45 +00:00
#[reflect(Component)]
pub struct Exploring(pub (f32, f32));
impl_pointlike_for_tuple_component!(Exploring);
2022-01-10 19:50:52 +00:00
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
2022-12-19 20:08:31 +00:00
pub struct FocusedExplorationType<T>(pub Option<T>)
where
T: Component + Default;
2021-05-13 17:25:45 +00:00
2022-01-10 19:50:52 +00:00
#[derive(Component, Clone, Copy, Debug, Default, Reflect)]
2021-05-13 17:25:45 +00:00
#[reflect(Component)]
pub struct Mappable;
2022-12-20 13:56:43 +00:00
fn exploration_type_change<ExplorationType, State>(
2021-05-13 17:25:45 +00:00
mut tts: ResMut<Tts>,
2022-08-02 22:15:22 +00:00
mut explorers: Query<(
&ActionState<ExplorationAction>,
&VisibleEntities,
2022-12-20 13:56:43 +00:00
&mut FocusedExplorationType<ExplorationType>,
2022-08-02 22:15:22 +00:00
)>,
2022-12-20 13:56:43 +00:00
features: Query<&ExplorationType>,
) -> Result<(), Box<dyn Error>>
where
2022-12-20 13:56:43 +00:00
ExplorationType: Component + Default + Copy + Ord,
State: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{
2022-08-02 22:15:22 +00:00
for (actions, visible, mut focused) in explorers.iter_mut() {
2022-12-20 13:56:43 +00:00
let mut types: Vec<ExplorationType> = vec![];
2022-08-02 22:15:22 +00:00
for e in visible.iter() {
if let Ok(t) = features.get(*e) {
types.push(*t);
}
2022-08-02 22:15:22 +00:00
}
types.sort();
types.dedup();
if types.is_empty() {
tts.speak("Nothing visible.", true)?;
} else if actions.just_pressed(ExplorationAction::SelectPrevType) {
if let Some(t) = &focused.0 {
if let Some(i) = types.iter().position(|v| *v == *t) {
if i == 0 {
focused.0 = None;
2021-05-13 17:25:45 +00:00
} else {
2022-08-02 22:15:22 +00:00
let t = &types[i - 1];
2021-05-13 17:25:45 +00:00
focused.0 = Some(*t);
}
} else {
let t = types.last().unwrap();
focused.0 = Some(*t);
}
2022-08-02 22:15:22 +00:00
} else {
let t = types.last().unwrap();
focused.0 = Some(*t);
}
} else if actions.just_pressed(ExplorationAction::SelectNextType) {
if let Some(t) = &focused.0 {
if let Some(i) = types.iter().position(|v| *v == *t) {
if i == types.len() - 1 {
focused.0 = None;
2021-05-13 17:25:45 +00:00
} else {
2022-08-02 22:15:22 +00:00
let t = &types[i + 1];
2021-05-13 17:25:45 +00:00
focused.0 = Some(*t);
}
} else {
let t = types.first().unwrap();
2022-08-02 22:15:22 +00:00
focused.0 = Some(*t);
2021-05-13 17:25:45 +00:00
}
2022-08-02 22:15:22 +00:00
} else {
let t = types.first().unwrap();
focused.0 = Some(*t)
2021-05-13 17:25:45 +00:00
}
}
}
Ok(())
}
2022-12-20 13:56:43 +00:00
fn exploration_type_focus<ExplorationType, State>(
2021-05-13 17:25:45 +00:00
mut commands: Commands,
mut tts: ResMut<Tts>,
explorers: Query<(
Entity,
2022-08-02 22:15:22 +00:00
&ActionState<ExplorationAction>,
2021-09-23 18:36:39 +00:00
&VisibleEntities,
2022-12-20 13:56:43 +00:00
&FocusedExplorationType<ExplorationType>,
2021-05-13 17:25:45 +00:00
Option<&Exploring>,
)>,
2022-12-20 13:56:43 +00:00
features: Query<(Entity, &Transform, &ExplorationType)>,
) -> Result<(), Box<dyn Error>>
where
2022-12-20 13:56:43 +00:00
ExplorationType: Component + Default + PartialEq,
State: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{
2022-08-02 22:15:22 +00:00
for (entity, actions, visible_entities, focused_type, exploring) in explorers.iter() {
let mut features = features
.iter()
.filter(|v| visible_entities.contains(&v.0))
.map(|v| (v.1.floor(), v.2))
2022-12-20 13:56:43 +00:00
.collect::<Vec<((f32, f32), &ExplorationType)>>();
2022-08-02 22:15:22 +00:00
if features.is_empty() {
tts.speak("Nothing visible.", true)?;
return Ok(());
2021-05-13 17:25:45 +00:00
}
2022-08-02 22:15:22 +00:00
features.sort_by(|(c1, _), (c2, _)| c1.partial_cmp(c2).unwrap());
if let Some(focused) = &focused_type.0 {
features.retain(|(_, t)| **t == *focused);
}
2022-12-20 13:56:43 +00:00
let mut target: Option<&((f32, f32), &ExplorationType)> = None;
2022-08-02 22:15:22 +00:00
if actions.just_pressed(ExplorationAction::FocusNext) {
if let Some(exploring) = exploring {
target = features.iter().find(|(c, _)| *c > **exploring);
if target.is_none() {
target = features.first();
2021-05-13 17:25:45 +00:00
}
2022-08-02 22:15:22 +00:00
} else {
target = features.first();
2021-05-13 17:25:45 +00:00
}
2022-08-02 22:15:22 +00:00
} else if actions.just_pressed(ExplorationAction::FocusPrev) {
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
}
2022-08-02 22:15:22 +00:00
if let Some((coordinates, _)) = target {
commands
.entity(entity)
.insert(Exploring(coordinates.floor()));
}
2021-05-13 17:25:45 +00:00
}
Ok(())
}
2022-12-20 13:56:43 +00:00
fn exploration_type_changed_announcement<ExplorationType>(
2021-05-13 17:25:45 +00:00
mut tts: ResMut<Tts>,
focused: Query<
(
2022-12-20 13:56:43 +00:00
&FocusedExplorationType<ExplorationType>,
ChangeTrackers<FocusedExplorationType<ExplorationType>>,
2021-05-13 17:25:45 +00:00
),
2022-12-20 13:56:43 +00:00
Changed<FocusedExplorationType<ExplorationType>>,
2021-05-13 17:25:45 +00:00
>,
2022-07-12 20:22:44 +00:00
) -> Result<(), Box<dyn Error>>
where
2022-12-20 13:56:43 +00:00
ExplorationType: Component + Default + Copy + Into<String>,
2022-07-12 20:22:44 +00:00
{
2021-05-13 17:25:45 +00:00
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(())
}
2022-12-20 13:56:43 +00:00
fn exploration_focus<State, MapData>(
2021-05-13 17:25:45 +00:00
mut commands: Commands,
2022-12-20 13:56:43 +00:00
map: Query<&Map<MapData>>,
2022-08-02 22:15:22 +00:00
explorers: Query<
(
Entity,
&ActionState<ExplorationAction>,
&Transform,
Option<&Exploring>,
),
With<Player>,
>,
) where
2022-12-20 13:56:43 +00:00
State: 'static + Clone + Debug + Eq + Hash + Send + Sync,
MapData: 'static + Clone + Default + Send + Sync,
{
2022-08-02 22:15:22 +00:00
for (entity, actions, transform, exploring) in explorers.iter() {
let coordinates = transform.translation;
let mut exploring = if let Some(exploring) = exploring {
**exploring
} else {
let floor = coordinates.floor();
(floor.x, floor.y)
};
let orig = exploring;
if actions.just_pressed(ExplorationAction::Forward) {
exploring.1 += 1.;
} else if actions.just_pressed(ExplorationAction::Backward) {
exploring.1 -= 1.;
} else if actions.just_pressed(ExplorationAction::Left) {
exploring.0 -= 1.;
} else if actions.just_pressed(ExplorationAction::Right) {
exploring.0 += 1.;
}
let dimensions = if let Ok(map) = map.get_single() {
Some((map.width as f32, map.height as f32))
} else {
None
};
if let Some((width, height)) = dimensions {
if exploring.0 >= width || exploring.1 >= height {
return;
2022-07-12 22:28:36 +00:00
}
2021-05-13 17:25:45 +00:00
}
2022-08-02 22:15:22 +00:00
if orig != exploring && exploring.0 >= 0. && exploring.1 >= 0. {
commands.entity(entity).insert(Exploring(exploring));
}
2021-05-13 17:25:45 +00:00
}
}
2022-12-20 13:56:43 +00:00
fn navigate_to_explored<State, MapData>(
2021-05-13 17:25:45 +00:00
mut commands: Commands,
2022-12-20 13:56:43 +00:00
map: Query<(&Map<MapData>, &RevealedTiles)>,
2022-08-02 22:15:22 +00:00
explorers: Query<(Entity, &ActionState<ExplorationAction>, &Exploring)>,
) where
2022-12-20 13:56:43 +00:00
State: 'static + Clone + Debug + Eq + Hash + Send + Sync,
MapData: 'static + Clone + Default + Send + Sync,
{
2022-08-02 22:15:22 +00:00
for (entity, actions, exploring) in explorers.iter() {
for (map, revealed_tiles) in map.iter() {
let point = **exploring;
let idx = point.to_index(map.width);
let known = revealed_tiles[idx];
if actions.just_pressed(ExplorationAction::NavigateTo) && known {
commands
.entity(entity)
.insert(Destination((point.x_i32(), point.y_i32())));
2021-05-13 17:25:45 +00:00
}
}
}
}
2022-12-20 13:56:43 +00:00
fn exploration_changed_announcement<ExplorationType, MapData>(
2021-05-13 17:25:45 +00:00
mut commands: Commands,
mut tts: ResMut<Tts>,
2022-12-20 13:56:43 +00:00
map: Query<(&Map<MapData>, &RevealedTiles)>,
2022-05-10 18:56:49 +00:00
explorer: Query<(&Transform, &Exploring, &Viewshed), Changed<Exploring>>,
2021-09-21 20:57:47 +00:00
focused: Query<Entity, With<ExplorationFocused>>,
explorable: Query<Entity, Or<(With<Visible>, With<Explorable>)>>,
2021-05-13 17:25:45 +00:00
names: Query<&Name>,
2022-12-20 13:56:43 +00:00
types: Query<&ExplorationType>,
2021-05-13 17:25:45 +00:00
mappables: Query<&Mappable>,
2022-05-06 16:07:59 +00:00
rapier_context: Res<RapierContext>,
2022-07-12 20:22:44 +00:00
) -> Result<(), Box<dyn Error>>
where
2022-12-20 13:56:43 +00:00
ExplorationType: Component + Copy + Into<String>,
MapData: 'static + Clone + Default + Send + Sync,
2022-07-12 20:22:44 +00:00
{
2022-01-13 20:43:02 +00:00
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
let coordinates = coordinates.floor();
2022-07-12 22:28:36 +00:00
let point = **exploring;
let shape = Collider::cuboid(0.5 - f32::EPSILON, 0.5 - f32::EPSILON);
let (known, idx) = if let Ok((map, revealed_tiles)) = map.get_single() {
2022-01-13 20:43:02 +00:00
let idx = point.to_index(map.width);
2022-07-12 22:28:36 +00:00
(revealed_tiles[idx], Some(idx))
} else {
(false, None)
};
let visible = viewshed.is_point_visible(exploring);
let fog_of_war = !visible && known;
let description: String = if known || visible {
let mut tokens: Vec<String> = vec![];
for entity in focused.iter() {
commands.entity(entity).remove::<ExplorationFocused>();
}
let exploring = Vec2::new(exploring.x(), exploring.y());
rapier_context.intersections_with_shape(
exploring,
0.,
&shape,
QueryFilter::new().predicate(&|v| explorable.get(v).is_ok()),
|entity| {
commands.entity(entity).insert(ExplorationFocused);
if visible || mappables.get(entity).is_ok() {
if let Ok(name) = names.get(entity) {
tokens.push(name.to_string());
}
if tokens.is_empty() {
if let Ok(t) = types.get(entity) {
tokens.push((*t).into());
2021-05-13 17:25:45 +00:00
}
}
}
2022-07-12 22:28:36 +00:00
true
},
);
if tokens.is_empty() {
if let Some(idx) = idx {
if let Ok((map, _)) = map.get_single() {
let tile = map.tiles[idx];
if tile.is_blocked() {
tokens.push("wall".to_string());
} else {
tokens.push("floor".to_string());
}
}
2021-05-13 17:25:45 +00:00
}
2022-07-12 22:28:36 +00:00
tokens.first().cloned().unwrap_or_default()
2021-05-13 17:25:45 +00:00
} else {
2022-07-12 22:28:36 +00:00
tokens.join(": ")
2021-05-13 17:25:45 +00:00
}
2022-07-12 22:28:36 +00:00
} else {
"Unknown".to_string()
};
let mut tokens = vec![
description,
coordinates.direction_and_distance(exploring, None),
];
if fog_of_war {
tokens.push("in the fog of war".to_string());
2021-05-13 17:25:45 +00:00
}
2022-07-12 22:28:36 +00:00
tts.speak(tokens.join(", "), true)?;
2021-05-13 17:25:45 +00:00
}
Ok(())
}
2021-09-21 20:57:47 +00:00
fn cleanup(
mut commands: Commands,
explorers: Query<Entity, With<Exploring>>,
focus: Query<Entity, With<ExplorationFocused>>,
) {
for entity in explorers.iter() {
commands.entity(entity).remove::<Exploring>();
}
for entity in focus.iter() {
2021-09-22 15:21:31 +00:00
commands.entity(entity).remove::<ExplorationFocused>();
2021-09-21 20:57:47 +00:00
}
}
2022-12-19 20:08:31 +00:00
#[derive(Resource, Clone, Debug)]
2022-12-20 16:55:19 +00:00
struct ExplorationConfig<State> {
states: Vec<State>,
}
2021-05-13 17:25:45 +00:00
2022-12-20 13:56:43 +00:00
impl<State> Default for ExplorationConfig<State> {
fn default() -> Self {
2022-12-20 13:56:43 +00:00
Self { states: vec![] }
}
}
#[derive(Resource, Clone, Default)]
pub struct ExplorationPlugin<ExplorationType, State, MapData> {
2022-12-20 22:34:23 +00:00
pub states: Vec<State>,
pub exploration_type: PhantomData<ExplorationType>,
pub map_data: PhantomData<MapData>,
}
2022-12-20 13:56:43 +00:00
impl<ExplorationType, State, MapData> Plugin for ExplorationPlugin<ExplorationType, State, MapData>
where
2022-12-20 13:56:43 +00:00
ExplorationType: 'static + Component + Default + Copy + Ord + PartialEq + Into<String>,
State: 'static + Clone + Debug + Eq + Hash + Send + Sync,
MapData: 'static + Clone + Default + Send + Sync,
{
2022-01-10 19:50:52 +00:00
fn build(&self, app: &mut App) {
let config = ExplorationConfig {
states: self.states.clone(),
};
app.insert_resource(config.clone())
.register_type::<ExplorationFocused>()
2021-05-13 17:25:45 +00:00
.register_type::<Mappable>()
2022-12-19 20:08:31 +00:00
.register_type::<Explorable>()
2022-08-02 22:15:22 +00:00
.add_plugin(InputManagerPlugin::<ExplorationAction>::default())
2022-12-20 13:56:43 +00:00
.add_system(
exploration_changed_announcement::<ExplorationType, MapData>.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>)
2021-09-21 20:57:47 +00:00
.add_system_to_stage(
CoreStage::PostUpdate,
2022-12-20 13:56:43 +00:00
exploration_type_changed_announcement::<ExplorationType>.pipe(error_handler),
2021-09-21 20:57:47 +00:00
);
} else {
2022-12-20 13:56:43 +00:00
let states = config.states;
2021-09-21 20:57:47 +00:00
for state in states {
app.add_system_set(
SystemSet::on_update(state.clone())
2022-12-20 13:56:43 +00:00
.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>)
2022-07-12 20:22:44 +00:00
.with_system(
2022-12-20 13:56:43 +00:00
exploration_type_changed_announcement::<ExplorationType>
.pipe(error_handler),
2022-07-12 20:22:44 +00:00
),
2021-09-21 20:57:47 +00:00
)
2022-01-10 19:50:52 +00:00
.add_system_set(SystemSet::on_exit(state).with_system(cleanup));
2021-09-21 20:57:47 +00:00
}
}
2021-05-13 17:25:45 +00:00
}
}