blackout/src/visibility.rs

414 lines
13 KiB
Rust
Raw Normal View History

2021-05-13 17:25:45 +00:00
use std::collections::{HashMap, HashSet};
use bevy::prelude::*;
use coord_2d::{Coord, Size};
use derive_more::{Deref, DerefMut};
use shadowcast::{vision_distance, Context, InputGrid};
use crate::{
2021-05-16 22:24:26 +00:00
core::{Angle, Coordinates, Player, PointLike},
2021-05-13 17:25:45 +00:00
log::Log,
map::{ITileType, Map, MapConfig},
};
#[derive(Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct BlocksVisibility;
#[derive(Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct DontLogWhenVisible;
2021-05-13 17:25:45 +00:00
#[derive(Clone, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct RevealedTiles(pub Vec<bool>);
#[derive(Clone, Debug, Eq, PartialEq)]
2021-05-13 17:25:45 +00:00
pub struct Viewshed {
pub visible: HashSet<(i32, i32)>,
pub range: u32,
}
impl Default for Viewshed {
fn default() -> Self {
Self {
range: 15,
visible: HashSet::new(),
}
}
}
impl Viewshed {
pub fn is_visible(&self, point: &dyn PointLike) -> bool {
self.visible.contains(&point.into())
}
}
#[derive(Clone, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct VisibilityBlocked(pub Vec<bool>);
#[derive(Clone, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct VisibleTiles(pub Vec<bool>);
fn add_visibility_indices(
mut commands: Commands,
query: Query<
(Entity, &Map),
(
Added<Map>,
Without<VisibilityBlocked>,
Without<VisibleTiles>,
Without<RevealedTiles>,
),
>,
map_config: Res<MapConfig>,
) {
for (entity, map) in query.iter() {
let mut v = vec![];
for tile in &map.base.tiles {
v.push(tile.blocks_visibility());
}
commands.entity(entity).insert(VisibilityBlocked(v));
let count = map.count();
commands
.entity(entity)
.insert(VisibleTiles(vec![false; count]));
commands
.entity(entity)
.insert(RevealedTiles(vec![map_config.start_revealed; count]));
}
}
pub(crate) fn set_visibility_blocked(
map: &Map,
index: usize,
visibility_blockers: &Query<&BlocksVisibility>,
visibility_blocked: &mut VisibilityBlocked,
) {
let mut new_visibility_blocked = map.base.tiles[index].blocks_visibility();
if !new_visibility_blocked {
for e in &map.entities[index] {
if visibility_blockers.get(*e).is_ok() {
new_visibility_blocked = true;
break;
}
}
}
visibility_blocked[index] = new_visibility_blocked;
}
2021-05-13 17:25:45 +00:00
#[derive(Default, Deref, DerefMut)]
struct PrevIndex(HashMap<Entity, usize>);
2021-05-13 17:25:45 +00:00
fn map_visibility_indexing(
mut map: Query<(&Map, &mut VisibilityBlocked)>,
mut prev_index: ResMut<PrevIndex>,
2021-05-13 17:25:45 +00:00
query: Query<
2021-05-21 17:04:10 +00:00
(Entity, &Coordinates),
(
With<BlocksVisibility>,
Or<(Changed<Coordinates>, Changed<BlocksVisibility>)>,
),
2021-05-13 17:25:45 +00:00
>,
visibility_blockers: Query<&BlocksVisibility>,
) {
2021-05-21 17:04:10 +00:00
for (entity, coordinates) in query.iter() {
2021-05-13 17:25:45 +00:00
for (map, mut visibility_blocked) in map.iter_mut() {
let idx = coordinates.to_index(map.width());
if let Some(prev_idx) = prev_index.get(&entity) {
if *prev_idx == idx {
continue;
}
set_visibility_blocked(
&map,
*prev_idx,
&visibility_blockers,
&mut visibility_blocked,
);
2021-05-13 17:25:45 +00:00
}
visibility_blocked[idx] = true;
prev_index.insert(entity, idx);
}
}
}
fn remove_blocks_visibility(
mut prev_index: ResMut<PrevIndex>,
2021-05-13 17:25:45 +00:00
mut map: Query<(&Map, &mut VisibilityBlocked)>,
removed: RemovedComponents<BlocksVisibility>,
coordinates: Query<&Coordinates>,
blocks_visibility: Query<&BlocksVisibility>,
) {
for entity in removed.iter() {
for (map, mut visibility_blocked) in map.iter_mut() {
if let Ok(coordinates) = coordinates.get_component::<Coordinates>(entity) {
if let Some(prev) = prev_index.get(&entity) {
set_visibility_blocked(
&map,
*prev,
&blocks_visibility,
&mut visibility_blocked,
);
2021-05-13 17:25:45 +00:00
}
prev_index.remove(&entity);
let idx = coordinates.to_index(map.width());
set_visibility_blocked(&map, idx, &blocks_visibility, &mut visibility_blocked);
prev_index.insert(entity, idx);
2021-05-13 17:25:45 +00:00
}
}
}
}
struct VisibilityGrid(Map, VisibilityBlocked);
impl InputGrid for VisibilityGrid {
type Grid = VisibilityGrid;
type Opacity = u8;
fn size(&self, grid: &Self::Grid) -> Size {
Size::new(grid.0.width() as u32, grid.0.height() as u32)
}
fn get_opacity(&self, grid: &Self::Grid, coord: Coord) -> Self::Opacity {
let point = (coord.x, coord.y);
let index = point.to_index(grid.0.width());
if grid.1 .0[index] {
255
} else {
0
}
}
}
fn update_viewshed(
viewshed: &mut Viewshed,
start: &Coordinates,
map: &Map,
visibility_blocked: &VisibilityBlocked,
) {
let mut context: Context<u8> = Context::default();
let vision_distance = vision_distance::Circle::new(viewshed.range);
let coord = Coord::new(start.x_i32(), start.y_i32());
viewshed.visible.clear();
let visibility_grid = VisibilityGrid(map.clone(), visibility_blocked.clone());
context.for_each_visible(
coord,
&visibility_grid,
&visibility_grid,
vision_distance,
255,
|coord, _directions, _visibility| {
viewshed.visible.insert((coord.x, coord.y));
},
);
}
fn update_viewshed_for_coordinates(
mut viewers: Query<(&mut Viewshed, &Coordinates), Changed<Coordinates>>,
2021-05-13 17:25:45 +00:00
map: Query<(&Map, &VisibilityBlocked)>,
) {
for (mut viewshed, start) in viewers.iter_mut() {
for (map, visibility_blocked) in map.iter() {
update_viewshed(&mut viewshed, start, &map, &visibility_blocked);
2021-05-13 17:25:45 +00:00
}
}
}
#[derive(Clone, Debug, Default, Deref, DerefMut)]
struct PrevVisibilityBlocked(Vec<bool>);
fn visibility_blocked_added(mut prev_visibility_blocked: ResMut<PrevVisibilityBlocked>, added: Query<&VisibilityBlocked, Added<VisibilityBlocked>>) {
for visibility_blocked in added.iter() {
**prev_visibility_blocked = visibility_blocked.to_vec();
}
}
fn visibility_blocked_removed(mut prev_visibility_blocked: ResMut<PrevVisibilityBlocked>, removed: RemovedComponents<VisibilityBlocked>) {
for _ in removed.iter() {
prev_visibility_blocked.clear();
}
}
fn update_viewshed_for_visibility_blocked(
mut prev_visibility_blocked: ResMut<PrevVisibilityBlocked>,
map: Query<(&Map, &VisibilityBlocked), Changed<VisibilityBlocked>>,
mut queryset: QuerySet<(
Query<(Entity, &Viewshed)>,
Query<(&mut Viewshed, &Coordinates)>,
)>,
) {
for (map, visibility_blocked) in map.iter() {
let mut to_check = vec![];
for (index, new) in visibility_blocked.iter().enumerate() {
let changed = if let Some(prev) = prev_visibility_blocked.get(index) {
prev != new
} else {
true
};
if changed {
let coords = (index % map.width(), index / map.width());
for (entity, viewshed) in queryset.q0().iter() {
if viewshed.is_visible(&coords) {
to_check.push(entity);
}
}
}
}
to_check.dedup();
for entity in to_check {
if let Ok((mut viewshed, coordinates)) = queryset.q1_mut().get_mut(entity) {
update_viewshed(&mut viewshed, coordinates, &map, &visibility_blocked);
}
}
**prev_visibility_blocked = visibility_blocked.to_vec();
}
}
2021-05-21 17:04:10 +00:00
fn update_visible_and_revealed_tiles(
2021-05-13 17:25:45 +00:00
mut map: Query<
2021-05-21 17:04:10 +00:00
(&Map, &mut RevealedTiles, &mut VisibleTiles),
2021-05-13 17:25:45 +00:00
(
2021-05-21 17:04:10 +00:00
With<VisibilityBlocked>,
Or<(Changed<Map>, Changed<VisibilityBlocked>)>,
2021-05-13 17:25:45 +00:00
),
>,
2021-05-21 17:04:10 +00:00
viewers: Query<&Viewshed, With<Player>>,
2021-05-13 17:25:45 +00:00
) {
2021-05-21 17:04:10 +00:00
for (map, mut revealed_tiles, mut visible_tiles) in map.iter_mut() {
for viewshed in viewers.iter() {
2021-05-13 17:25:45 +00:00
for t in visible_tiles.iter_mut() {
*t = false
}
for v in viewshed.visible.iter() {
2021-05-21 17:04:10 +00:00
let idx = v.to_index(map.width());
2021-05-13 17:25:45 +00:00
revealed_tiles[idx] = true;
visible_tiles[idx] = true;
}
}
}
}
fn log_visible(
time: Res<Time>,
mut seen: Local<HashSet<Entity>>,
mut recently_lost: Local<HashMap<Entity, Timer>>,
mut log: Query<&mut Log>,
2021-05-16 22:24:26 +00:00
viewers: Query<(&Viewshed, &Coordinates, &Transform), With<Player>>,
2021-05-13 17:25:45 +00:00
map: Query<&Map>,
names: Query<&Name>,
players: Query<&Player>,
dont_log_when_visible: Query<&DontLogWhenVisible>,
2021-05-13 17:25:45 +00:00
) {
for timer in recently_lost.values_mut() {
timer.tick(time.delta());
}
let recently_lost_clone = recently_lost.clone();
for (entity, timer) in recently_lost_clone.iter() {
if timer.finished() {
recently_lost.remove(&entity);
}
}
let mut new_seen = HashSet::new();
if let Ok(mut log) = log.single_mut() {
2021-05-16 22:24:26 +00:00
for (viewshed, coordinates, transform) in viewers.iter() {
2021-05-13 17:25:45 +00:00
for viewed_coordinates in &viewshed.visible {
for map in map.iter() {
let index = viewed_coordinates.to_index(map.width());
for entity in &map.entities[index] {
if recently_lost.contains_key(&entity) {
continue;
}
if let Ok(name) = names.get(*entity) {
if players.get(*entity).is_err() {
if !seen.contains(&*entity)
&& dont_log_when_visible.get(*entity).is_err()
{
2021-05-13 17:25:45 +00:00
let name = name.to_string();
2021-05-16 22:24:26 +00:00
let forward = transform.local_x();
let yaw = Angle::Radians(forward.y.atan2(forward.x));
let location = coordinates
.direction_and_distance(viewed_coordinates, Some(yaw));
2021-05-13 17:25:45 +00:00
log.push(format!("{}: {}", name, location));
}
new_seen.insert(*entity);
}
}
}
}
}
}
}
let recently_lost_entities = seen.difference(&new_seen);
for entity in recently_lost_entities {
recently_lost.insert(*entity, Timer::from_seconds(2., false));
}
*seen = new_seen;
}
pub const LOG_VISIBLE_LABEL: &str = "LOG_VISIBLE";
pub struct VisibilityPlugin;
impl Plugin for VisibilityPlugin {
fn build(&self, app: &mut AppBuilder) {
const UPDATE_VISIBILITY_INDEX: &str = "UPDATE_VISIBILITY_INDEX";
const UPDATE_VIEWSHED: &str = "UPDATE_VIEWSHED";
const MAP_VISIBILITY: &str = "MAP_VISIBILITY";
app.init_resource::<PrevVisibilityBlocked>()
.init_resource::<PrevIndex>()
.add_system(visibility_blocked_added.system())
.add_system_to_stage(CoreStage::PostUpdate, visibility_blocked_removed.system())
2021-05-13 17:25:45 +00:00
.add_system(add_visibility_indices.system())
.add_system_to_stage(
CoreStage::PostUpdate,
add_visibility_indices
.system()
.before(UPDATE_VISIBILITY_INDEX),
)
.add_system_to_stage(
CoreStage::PostUpdate,
remove_blocks_visibility
.system()
.before(UPDATE_VISIBILITY_INDEX),
)
.add_system_to_stage(
CoreStage::PostUpdate,
map_visibility_indexing
.system()
.label(UPDATE_VISIBILITY_INDEX)
.after(crate::map::UPDATE_ENTITY_INDEX_LABEL),
)
.add_system_to_stage(
CoreStage::PostUpdate,
update_viewshed_for_coordinates
.system()
.label(UPDATE_VIEWSHED)
.after(UPDATE_VISIBILITY_INDEX),
)
.add_system_to_stage(
CoreStage::PostUpdate,
update_viewshed_for_visibility_blocked
2021-05-13 17:25:45 +00:00
.system()
.label(UPDATE_VIEWSHED)
.after(UPDATE_VISIBILITY_INDEX),
)
.add_system_to_stage(
CoreStage::PostUpdate,
2021-05-21 17:04:10 +00:00
update_visible_and_revealed_tiles
2021-05-13 17:25:45 +00:00
.system()
.label(MAP_VISIBILITY)
.after(UPDATE_VIEWSHED),
)
.add_system_to_stage(
CoreStage::PostUpdate,
log_visible
.system()
.label(LOG_VISIBLE_LABEL)
.after(MAP_VISIBILITY),
);
}
}