blackout/src/exploration.rs

446 lines
15 KiB
Rust

use std::{error::Error, fmt::Debug, hash::Hash, marker::PhantomData};
use bevy::prelude::*;
use bevy_rapier2d::prelude::*;
use bevy_tts::Tts;
use leafwing_input_manager::prelude::*;
use crate::{
core::{Player, PointLike},
error::error_handler,
map::Map,
pathfinding::Destination,
visibility::{RevealedTiles, Viewshed, Visible, VisibleEntities},
};
#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Hash, Debug)]
pub enum ExplorationAction {
Forward,
Backward,
Left,
Right,
FocusNext,
FocusPrev,
SelectNextType,
SelectPrevType,
NavigateTo,
}
#[derive(Component, Clone, Copy, Debug, Default, PartialEq, Reflect)]
#[reflect(Component)]
pub struct Explorable;
#[derive(Component, Clone, Copy, Debug, Default, PartialEq, Reflect)]
#[reflect(Component)]
pub struct ExplorationFocused;
#[derive(Component, Clone, Copy, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct Exploring(pub (f32, f32));
impl_pointlike_for_tuple_component!(Exploring);
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
pub struct FocusedExplorationType<T>(pub Option<T>)
where
T: Component + Default;
#[derive(Component, Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct Mappable;
fn exploration_type_change<T, S>(
mut tts: ResMut<Tts>,
mut explorers: Query<(
&ActionState<ExplorationAction>,
&VisibleEntities,
&mut FocusedExplorationType<T>,
)>,
features: Query<&T>,
) -> Result<(), Box<dyn Error>>
where
T: Component + Default + Copy + Ord,
S: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{
for (actions, visible, mut focused) in explorers.iter_mut() {
let mut types: Vec<T> = vec![];
for e in visible.iter() {
if let Ok(t) = features.get(*e) {
types.push(*t);
}
}
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;
} else {
let t = &types[i - 1];
focused.0 = Some(*t);
}
} else {
let t = types.last().unwrap();
focused.0 = Some(*t);
}
} 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;
} else {
let t = &types[i + 1];
focused.0 = Some(*t);
}
} else {
let t = types.first().unwrap();
focused.0 = Some(*t);
}
} else {
let t = types.first().unwrap();
focused.0 = Some(*t)
}
}
}
Ok(())
}
fn exploration_type_focus<T, S>(
mut commands: Commands,
mut tts: ResMut<Tts>,
explorers: Query<(
Entity,
&ActionState<ExplorationAction>,
&VisibleEntities,
&FocusedExplorationType<T>,
Option<&Exploring>,
)>,
features: Query<(Entity, &Transform, &T)>,
) -> Result<(), Box<dyn Error>>
where
T: Component + Default + PartialEq,
S: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{
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))
.collect::<Vec<((f32, f32), &T)>>();
if features.is_empty() {
tts.speak("Nothing visible.", true)?;
return Ok(());
}
features.sort_by(|(c1, _), (c2, _)| c1.partial_cmp(c2).unwrap());
if let Some(focused) = &focused_type.0 {
features.retain(|(_, t)| **t == *focused);
}
let mut target: Option<&((f32, f32), &T)> = None;
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();
}
} else {
target = features.first();
}
} 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();
}
}
if let Some((coordinates, _)) = target {
commands
.entity(entity)
.insert(Exploring(coordinates.floor()));
}
}
Ok(())
}
fn exploration_type_changed_announcement<T>(
mut tts: ResMut<Tts>,
focused: Query<
(
&FocusedExplorationType<T>,
ChangeTrackers<FocusedExplorationType<T>>,
),
Changed<FocusedExplorationType<T>>,
>,
) -> Result<(), Box<dyn Error>>
where
T: Component + Default + Copy + Into<String>,
{
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<S, D: 'static + Clone + Default + Send + Sync>(
mut commands: Commands,
map: Query<&Map<D>>,
explorers: Query<
(
Entity,
&ActionState<ExplorationAction>,
&Transform,
Option<&Exploring>,
),
With<Player>,
>,
) where
S: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{
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;
}
}
if orig != exploring && exploring.0 >= 0. && exploring.1 >= 0. {
commands.entity(entity).insert(Exploring(exploring));
}
}
}
fn navigate_to_explored<S, D: 'static + Clone + Default + Send + Sync>(
mut commands: Commands,
map: Query<(&Map<D>, &RevealedTiles)>,
explorers: Query<(Entity, &ActionState<ExplorationAction>, &Exploring)>,
) where
S: 'static + Clone + Debug + Eq + Hash + Send + Sync,
{
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())));
}
}
}
}
fn exploration_changed_announcement<T, D>(
mut commands: Commands,
mut tts: ResMut<Tts>,
map: Query<(&Map<D>, &RevealedTiles)>,
explorer: Query<(&Transform, &Exploring, &Viewshed), Changed<Exploring>>,
focused: Query<Entity, With<ExplorationFocused>>,
explorable: Query<Entity, Or<(With<Visible>, With<Explorable>)>>,
names: Query<&Name>,
types: Query<&T>,
mappables: Query<&Mappable>,
rapier_context: Res<RapierContext>,
) -> Result<(), Box<dyn Error>>
where
T: Component + Copy + Into<String>,
D: 'static + Clone + Default + Send + Sync,
{
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
let coordinates = coordinates.floor();
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() {
let idx = point.to_index(map.width);
(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());
}
}
}
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());
}
}
}
tokens.first().cloned().unwrap_or_default()
} else {
tokens.join(": ")
}
} 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());
}
tts.speak(tokens.join(", "), true)?;
}
Ok(())
}
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() {
commands.entity(entity).remove::<ExplorationFocused>();
}
}
#[derive(Resource, Clone, Debug)]
pub struct ExplorationConfig<S> {
pub exploration_control_states: Vec<S>,
}
impl<S> Default for ExplorationConfig<S> {
fn default() -> Self {
Self {
exploration_control_states: vec![],
}
}
}
pub struct ExplorationPlugin<'a, T, S: 'static, A: 'static, D>(
PhantomData<T>,
PhantomData<&'a S>,
PhantomData<&'static A>,
PhantomData<D>,
);
impl<T, S, A, D> Default for ExplorationPlugin<'static, S, A, D, T> {
fn default() -> Self {
Self(PhantomData, PhantomData, PhantomData, PhantomData)
}
}
impl<T, S, A, D> Plugin for ExplorationPlugin<'static, T, S, A, D>
where
T: 'static + Component + Default + Copy + Ord + PartialEq + Into<String>,
S: Clone + Debug + Eq + Hash + Send + Sync,
A: Hash + Eq + Clone + Send + Sync,
D: 'static + Clone + Default + Send + Sync,
{
fn build(&self, app: &mut App) {
if !app.world.contains_resource::<ExplorationConfig<S>>() {
app.insert_resource(ExplorationConfig::<S>::default());
}
let config = app
.world
.get_resource::<ExplorationConfig<S>>()
.unwrap()
.clone();
app.register_type::<ExplorationFocused>()
.register_type::<Mappable>()
.register_type::<Explorable>()
.add_plugin(InputManagerPlugin::<ExplorationAction>::default())
.add_system(exploration_changed_announcement::<T, D>.pipe(error_handler));
if config.exploration_control_states.is_empty() {
app.add_system(exploration_focus::<S, D>)
.add_system(exploration_type_focus::<T, S>.pipe(error_handler))
.add_system(exploration_type_change::<T, S>.pipe(error_handler))
.add_system(navigate_to_explored::<S, D>)
.add_system_to_stage(
CoreStage::PostUpdate,
exploration_type_changed_announcement::<T>.pipe(error_handler),
);
} else {
let states = config.exploration_control_states;
for state in states {
app.add_system_set(
SystemSet::on_update(state.clone())
.with_system(exploration_focus::<S, D>)
.with_system(exploration_type_focus::<T, S>.pipe(error_handler))
.with_system(exploration_type_change::<T, S>.pipe(error_handler))
.with_system(navigate_to_explored::<S, D>)
.with_system(
exploration_type_changed_announcement::<T>.pipe(error_handler),
),
)
.add_system_set(SystemSet::on_exit(state).with_system(cleanup));
}
}
}
}