blackout/src/visibility.rs

495 lines
16 KiB
Rust
Raw Normal View History

2021-05-13 17:25:45 +00:00
use std::collections::{HashMap, HashSet};
use bevy::prelude::*;
use bevy_rapier2d::na::UnitComplex;
2021-05-13 17:25:45 +00:00
use coord_2d::{Coord, Size};
use derive_more::{Deref, DerefMut};
use shadowcast::{vision_distance, Context, InputGrid};
use crate::{
bevy_rapier2d::prelude::*,
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},
utils::target_and_other,
2021-05-13 17:25:45 +00:00
};
#[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 range: u32,
pub visible_points: HashSet<(i32, i32)>,
2021-05-13 17:25:45 +00:00
}
impl Default for Viewshed {
fn default() -> Self {
Self {
range: 15,
visible_points: HashSet::new(),
2021-05-13 17:25:45 +00:00
}
}
}
impl Viewshed {
pub fn is_point_visible(&self, point: &dyn PointLike) -> bool {
self.visible_points.contains(&point.into())
2021-05-13 17:25:45 +00:00
}
}
#[derive(Clone, Copy, Debug, Default, Reflect)]
struct VisibilityCollider;
#[derive(Clone, Copy, Debug, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct Visible(pub u8);
impl Default for Visible {
fn default() -> Self {
Self::opaque()
}
}
impl Visible {
pub fn transparent() -> Self {
Self(0)
}
pub fn opaque() -> Self {
Self(u8::MAX)
}
}
#[derive(Clone, Debug, Default, Deref, DerefMut)]
pub struct VisibleEntities(HashSet<Entity>);
2021-05-13 17:25:45 +00:00
#[derive(Clone, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct VisibleTiles(pub Vec<bool>);
#[derive(Bundle, Default)]
pub struct ViewshedBundle {
pub viewshed: Viewshed,
pub visible_entities: VisibleEntities,
}
impl ViewshedBundle {
pub fn new(range: u32) -> Self {
Self {
viewshed: Viewshed {
range,
..Default::default()
},
..Default::default()
}
}
}
pub enum VisibilityChanged {
Gained { viewer: Entity, viewed: Entity },
Lost { viewer: Entity, viewed: Entity },
}
2021-09-21 17:58:57 +00:00
#[derive(Clone, Debug, Default, Deref, DerefMut)]
struct VisibilityColliderToViewshed(HashMap<Entity, Entity>);
#[derive(Clone, Debug, Default, Deref, DerefMut)]
struct ViewshedToVisibilityCollider(HashMap<Entity, Entity>);
2021-06-09 22:42:04 +00:00
impl PointLike for Coord {
fn x(&self) -> f32 {
self.x as f32
}
fn y(&self) -> f32 {
self.y as f32
}
}
2021-05-13 17:25:45 +00:00
fn add_visibility_indices(
mut commands: Commands,
query: Query<(Entity, &Map), (Added<Map>, Without<VisibleTiles>, Without<RevealedTiles>)>,
2021-05-13 17:25:45 +00:00
map_config: Res<MapConfig>,
) {
for (entity, map) in query.iter() {
2021-06-09 19:53:48 +00:00
let count = map.width * map.height;
2021-05-13 17:25:45 +00:00
commands
.entity(entity)
.insert(VisibleTiles(vec![false; count]));
commands
.entity(entity)
.insert(RevealedTiles(vec![map_config.start_revealed; count]));
}
}
2021-09-21 17:58:57 +00:00
fn viewshed_added(
mut commands: Commands,
mut collider_to_viewshed: ResMut<VisibilityColliderToViewshed>,
mut viewshed_to_collider: ResMut<ViewshedToVisibilityCollider>,
query: Query<Entity, Added<Viewshed>>,
) {
for entity in query.iter() {
2021-09-21 17:58:57 +00:00
let id = commands
.spawn_bundle(ColliderBundle {
collider_type: ColliderType::Sensor,
flags: ColliderFlags {
active_collision_types: ActiveCollisionTypes::all(),
active_events: ActiveEvents::INTERSECTION_EVENTS,
..Default::default()
},
..Default::default()
})
.insert(VisibilityCollider)
.id();
viewshed_to_collider.insert(entity, id);
collider_to_viewshed.insert(id, entity);
}
}
fn viewshed_changed(
mut commands: Commands,
2021-09-21 17:58:57 +00:00
viewshed_to_collider: Res<ViewshedToVisibilityCollider>,
query: Query<(Entity, &Viewshed, &RigidBodyPosition), Changed<Viewshed>>,
mut collider_data: Query<
2021-09-21 17:58:57 +00:00
(Option<&mut ColliderShape>, Option<&mut ColliderPosition>),
With<VisibilityCollider>,
>,
) {
for (entity, viewshed, position) in query.iter() {
2021-09-21 17:58:57 +00:00
if let Some(collider_entity) = viewshed_to_collider.get(&entity) {
if let Ok((collider_shape, collider_position)) = collider_data.get_mut(*collider_entity)
{
if viewshed.visible_points.len() < 2 {
commands.entity(*collider_entity).remove::<ColliderShape>();
} else {
let translation = position.position.translation;
let mut points = vec![];
for p in &viewshed.visible_points {
points.push(point!(
p.x() - translation.x + 0.5,
p.y() - translation.y + 0.5
));
2021-09-21 17:58:57 +00:00
}
if let Some(shape) = ColliderShape::convex_hull(&points) {
if let (Some(mut collider_shape), Some(mut collider_position)) =
(collider_shape, collider_position)
{
*collider_shape = shape;
*collider_position = translation.into();
}
}
}
}
}
}
}
fn viewshed_removed(
2021-09-21 17:58:57 +00:00
mut collider_to_viewshed: ResMut<VisibilityColliderToViewshed>,
mut viewshed_to_collider: ResMut<ViewshedToVisibilityCollider>,
query: RemovedComponents<Viewshed>,
) {
for entity in query.iter() {
2021-09-21 17:58:57 +00:00
if let Some(collider) = viewshed_to_collider.get(&entity) {
collider_to_viewshed.remove(&collider);
}
2021-09-21 17:58:57 +00:00
viewshed_to_collider.remove(&entity);
}
}
pub struct VisibilityGrid<'a, F>(pub &'a Map, pub F);
2021-05-13 17:25:45 +00:00
impl<'a, F> InputGrid for VisibilityGrid<'a, F>
where
F: Fn(Coord) -> u8,
{
type Grid = VisibilityGrid<'a, F>;
2021-05-13 17:25:45 +00:00
type Opacity = u8;
fn size(&self, grid: &Self::Grid) -> Size {
2021-06-09 19:53:48 +00:00
Size::new(grid.0.width as u32, grid.0.height as u32)
2021-05-13 17:25:45 +00:00
}
fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity {
self.1(coord)
2021-05-13 17:25:45 +00:00
}
}
fn update_viewshed(
viewer_entity: &Entity,
viewshed: &mut Viewshed,
start: &dyn PointLike,
query_pipeline: &QueryPipeline,
collider_query: &QueryPipelineColliderComponentsQuery,
map: &Map,
visible: &Query<&Visible>,
) {
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());
let shape = Cuboid::new(Vec2::new(0.49, 0.49).into());
let range = viewshed.range as f32;
let collider_set = QueryPipelineColliderComponentsSet(&collider_query);
let visibility_grid = VisibilityGrid(map, |coord: Coord| {
if coord.distance(start) > range {
return 255;
}
let shape_pos = (Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5), 0.);
let mut opacity = 0;
query_pipeline.intersections_with_shape(
&collider_set,
&shape_pos.into(),
&shape,
InteractionGroups::all(),
Some(&|v| v.entity() != *viewer_entity && visible.get(v.entity()).is_ok()),
|handle| {
if let Ok(visible) = visible.get(handle.entity()) {
opacity = **visible;
}
2021-09-21 17:58:57 +00:00
true
},
);
opacity
});
2021-08-23 15:14:03 +00:00
let mut new_visible = HashSet::new();
context.for_each_visible(
coord,
&visibility_grid,
&visibility_grid,
vision_distance,
255,
|coord, _directions, _visibility| {
2021-08-23 15:14:03 +00:00
new_visible.insert((coord.x, coord.y));
},
);
if viewshed.visible_points != new_visible {
viewshed.visible_points = new_visible;
2021-08-23 15:14:03 +00:00
}
}
2021-07-13 17:24:33 +00:00
fn update_viewshed_for_coordinates(
config: Res<RapierConfiguration>,
visible: Query<(Entity, &Coordinates), (Changed<Coordinates>, With<Visible>)>,
mut viewers: Query<(Entity, &mut Viewshed, &Coordinates)>,
map: Query<&Map>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
visible_query: Query<&Visible>,
) {
if !config.query_pipeline_active {
return;
}
2021-08-23 15:14:03 +00:00
for (visible_entity, coordinates) in visible.iter() {
for (viewer_entity, mut viewshed, start) in viewers.iter_mut() {
2021-08-23 15:14:03 +00:00
if viewer_entity == visible_entity
|| coordinates.distance(start) > viewshed.range as f32
{
continue;
}
if let Ok(map) = map.single() {
update_viewshed(
&viewer_entity,
&mut viewshed,
start,
&*query_pipeline,
&collider_query,
map,
&visible_query,
);
}
}
}
}
2021-07-13 17:24:33 +00:00
fn update_viewshed_for_start(
config: Res<RapierConfiguration>,
2021-06-09 22:42:04 +00:00
mut viewers: Query<(Entity, &mut Viewshed, &Coordinates), Changed<Coordinates>>,
map: Query<&Map>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
visible: Query<&Visible>,
2021-05-13 17:25:45 +00:00
) {
if !config.query_pipeline_active {
return;
}
2021-06-09 22:42:04 +00:00
for (viewer_entity, mut viewshed, start) in viewers.iter_mut() {
if let Ok(map) = map.single() {
update_viewshed(
&viewer_entity,
&mut viewshed,
start,
&*query_pipeline,
&collider_query,
map,
&visible,
);
}
}
}
fn remove_visible(
removed: RemovedComponents<Visible>,
mut viewers: Query<(Entity, &mut Viewshed, &mut VisibleEntities, &Coordinates)>,
map: Query<&Map>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
visible: Query<&Visible>,
) {
for removed in removed.iter() {
for (viewer_entity, mut viewshed, mut visible_entities, start) in viewers.iter_mut() {
if !visible_entities.contains(&removed) {
continue;
}
visible_entities.remove(&removed);
if let Ok(map) = map.single() {
update_viewshed(
&viewer_entity,
&mut viewshed,
start,
&*query_pipeline,
&collider_query,
map,
&visible,
);
}
}
}
}
2021-05-21 17:04:10 +00:00
fn update_visible_and_revealed_tiles(
mut map: Query<(&Map, &mut RevealedTiles, &mut VisibleTiles)>,
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_points.iter() {
2021-06-09 19:53:48 +00:00
let idx = v.to_index(map.width);
2021-09-01 16:34:38 +00:00
if idx >= revealed_tiles.len() || idx >= visible_tiles.len() {
continue;
}
2021-05-13 17:25:45 +00:00
revealed_tiles[idx] = true;
visible_tiles[idx] = true;
}
}
}
}
fn intersection(
mut events: EventReader<IntersectionEvent>,
2021-09-21 17:58:57 +00:00
collider_to_viewshed: Res<VisibilityColliderToViewshed>,
colliders: Query<Entity, With<VisibilityCollider>>,
mut viewers: Query<&mut VisibleEntities>,
visible: Query<Entity, With<Visible>>,
mut visibility_changed: EventWriter<VisibilityChanged>,
) {
for event in events.iter() {
if let Some((visibility_collider, other)) =
target_and_other(event.collider1.entity(), event.collider2.entity(), |v| {
colliders.get(v).is_ok()
})
{
if visible.get(other).is_ok() {
if let Some(viewshed_entity) = collider_to_viewshed.get(&visibility_collider) {
if let Ok(mut visible_entities) = viewers.get_mut(*viewshed_entity) {
if event.intersecting {
visibility_changed.send(VisibilityChanged::Gained {
viewer: *viewshed_entity,
viewed: other,
});
visible_entities.insert(other);
2021-09-21 17:58:57 +00:00
} else {
visibility_changed.send(VisibilityChanged::Lost {
viewer: *viewshed_entity,
viewed: other,
});
visible_entities.remove(&other);
2021-09-21 17:58:57 +00:00
}
}
}
}
}
}
}
2021-05-13 17:25:45 +00:00
fn log_visible(
time: Res<Time>,
mut recently_lost: Local<HashMap<Entity, Timer>>,
2021-09-21 17:58:57 +00:00
mut events: EventReader<VisibilityChanged>,
2021-05-13 17:25:45 +00:00
mut log: Query<&mut Log>,
viewers: Query<(Entity, &Coordinates, &Transform), (With<Player>, With<Viewshed>)>,
visible: Query<
2021-09-21 17:58:57 +00:00
(&Name, Option<&RigidBodyPosition>, Option<&ColliderPosition>),
Without<DontLogWhenVisible>,
>,
2021-05-13 17:25:45 +00:00
) {
for timer in recently_lost.values_mut() {
2021-05-13 17:25:45 +00:00
timer.tick(time.delta());
}
recently_lost.retain(|_entity, timer| !timer.finished());
for event in events.iter() {
let viewer = match event {
VisibilityChanged::Gained { viewer, .. } => viewer,
VisibilityChanged::Lost { viewer, .. } => viewer,
};
if let Ok((viewer_entity, viewer_coordinates, viewer_transform)) = viewers.get(*viewer) {
if let VisibilityChanged::Gained { viewed, .. } = event {
if *viewed == viewer_entity || recently_lost.contains_key(viewed) {
2021-09-21 17:58:57 +00:00
continue;
}
if let Ok((name, body_position, collider_position)) = visible.get(*viewed) {
2021-09-21 17:58:57 +00:00
if let Ok(mut log) = log.single_mut() {
let viewed_coordinates = if let Some(p) = body_position {
(p.position.translation.x, p.position.translation.y)
} else if let Some(p) = collider_position {
(p.translation.x, p.translation.y)
} else {
(0., 0.)
};
let forward = viewer_transform.local_x();
let yaw = Angle::Radians(forward.y.atan2(forward.x));
let location = viewer_coordinates
.direction_and_distance(&viewed_coordinates, Some(yaw));
log.push(format!("{}: {}", **name, location));
}
}
} else if let VisibilityChanged::Lost { viewed, .. } = event {
recently_lost.insert(*viewed, Timer::from_seconds(2., false));
2021-05-13 17:25:45 +00:00
}
}
}
}
pub const LOG_VISIBLE_LABEL: &str = "LOG_VISIBLE";
pub struct VisibilityPlugin;
impl Plugin for VisibilityPlugin {
fn build(&self, app: &mut AppBuilder) {
2021-09-21 17:58:57 +00:00
app.init_resource::<VisibilityColliderToViewshed>()
.init_resource::<ViewshedToVisibilityCollider>()
.add_event::<VisibilityChanged>()
.add_system(add_visibility_indices.system())
.add_system(viewshed_added.system())
.add_system(viewshed_changed.system())
.add_system_to_stage(CoreStage::PostUpdate, viewshed_removed.system())
.add_system(update_viewshed_for_coordinates.system())
.add_system(update_viewshed_for_start.system())
.add_system_to_stage(CoreStage::PostUpdate, remove_visible.system())
2021-05-13 17:25:45 +00:00
.add_system_to_stage(
CoreStage::PostUpdate,
update_visible_and_revealed_tiles.system(),
2021-05-13 17:25:45 +00:00
)
.add_system(intersection.system())
.add_system_to_stage(CoreStage::PostUpdate, log_visible.system());
2021-05-13 17:25:45 +00:00
}
}