Refactor visibility to triggers and fix lots of bugs.

This commit is contained in:
Nolan Darilek 2024-09-22 14:45:36 -05:00
parent 3ccb3a1d80
commit 015e98d419

View File

@ -6,10 +6,7 @@ use std::{
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::{ use bevy_rapier2d::{na::Isometry2, parry::bounding_volume::BoundingVolume};
na::{Isometry2, Vector2},
parry::bounding_volume::BoundingVolume,
};
use coord_2d::{Coord, Size}; use coord_2d::{Coord, Size};
use shadowcast::{vision_distance, Context, InputGrid}; use shadowcast::{vision_distance, Context, InputGrid};
@ -50,28 +47,21 @@ impl Viewshed {
fn update( fn update(
&mut self, &mut self,
commands: &mut Commands,
viewer_entity: &Entity, viewer_entity: &Entity,
visible_entities: &mut VisibleEntities, visible_entities: &mut VisibleEntities,
start: &Vec2, start: &Vec2,
rapier_context: &RapierContext, rapier_context: &RapierContext,
visible_query: &Query<(&Visible, &Collider, &GlobalTransform)>, visible_query: &Query<(&Visible, &Collider, &GlobalTransform)>,
events: &mut EventWriter<VisibilityChanged>, cache: &mut RefCell<HashMap<(i32, i32), (u8, HashSet<Entity>)>>,
cache: &mut HashMap<(i32, i32), (u8, HashSet<Entity>)>,
) { ) {
// println!("Start"); // println!("Start");
let mut boxes = vec![]; let mut boxes = vec![];
let shape = Collider::cuboid(self.range as f32, self.range as f32); let shape = Collider::cuboid(self.range as f32, self.range as f32);
rapier_context.intersections_with_shape( rapier_context.intersections_with_shape(*start, 0., &shape, default(), |entity| {
*start,
0.,
&shape,
QueryFilter::new().predicate(&|e| visible_query.contains(e)),
|entity| {
if let Ok((_, collider, transform)) = visible_query.get(entity) { if let Ok((_, collider, transform)) = visible_query.get(entity) {
let position = Isometry2::new( let position =
Vector2::new(transform.translation().x, transform.translation().y), Isometry2::translation(transform.translation().x, transform.translation().y);
0.,
);
// println!( // println!(
// "Hit {:?}, pushing {:?}", // "Hit {:?}, pushing {:?}",
// entity, // entity,
@ -80,12 +70,10 @@ impl Viewshed {
boxes.push(collider.raw.compute_aabb(&position)); boxes.push(collider.raw.compute_aabb(&position));
} }
true true
}, });
);
let mut context: Context<u8> = Context::default(); let mut context: Context<u8> = Context::default();
let vision_distance = vision_distance::Circle::new(self.range); let vision_distance = vision_distance::Circle::new(self.range);
let shape = Collider::cuboid(0.5, 0.5); let shape = Collider::cuboid(0.49, 0.49);
let mut new_visible_entities = HashSet::new();
let size = ( let size = (
(start.x.abs() + self.range as f32 * 2.) as u32, (start.x.abs() + self.range as f32 * 2.) as u32,
(start.y.abs() + self.range as f32 * 2.) as u32, (start.y.abs() + self.range as f32 * 2.) as u32,
@ -93,96 +81,72 @@ impl Viewshed {
let visibility_grid = VisibilityGrid( let visibility_grid = VisibilityGrid(
size, size,
RefCell::new(Box::new(|coord: Coord| { RefCell::new(Box::new(|coord: Coord| {
// println!("Checking {coord:?}");
let shape_pos = Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5); let shape_pos = Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5);
// println!("Checking {:?}", shape_pos); // println!("Checking {coord:?}: {shape_pos:?}");
if start.distance(&shape_pos) > self.range as f32 { if start.distance(&shape_pos) > self.range as f32 {
// println!("Out of range"); // println!("Out of range");
return u8::MAX; return u8::MAX;
} }
let result = if let Some((opacity, coord_entities)) = cache.get(&(coord.x, coord.y))
{
Some((*opacity, coord_entities.clone()))
} else {
let position = Isometry2::new(Vector2::new(shape_pos.x, shape_pos.y), 0.);
let aabb = shape.raw.compute_aabb(&position).tightened(0.01);
let mut hit = false;
for b in &boxes {
if b.intersects(&aabb) {
// println!("Hit at {:?}", b);
hit = true;
break;
}
}
if hit {
// println!("Hit test");
let mut opacity = 0;
let mut coord_entities = HashSet::new(); let mut coord_entities = HashSet::new();
let mut to_insert = None;
let opacity = if let Some((opacity, entities)) =
cache.borrow().get(&(coord.x, coord.y))
{
// println!("Cache hit: {opacity:?}: {entities:?}");
coord_entities = entities.clone();
*opacity
} else {
let position = Isometry2::translation(shape_pos.x, shape_pos.y);
let aabb = shape.raw.compute_aabb(&position);
if boxes.iter().any(|b| b.intersects(&aabb)) {
// println!("Hit");
let mut opacity = 0;
rapier_context.intersections_with_shape( rapier_context.intersections_with_shape(
shape_pos, shape_pos,
0., 0.,
&shape, &shape,
QueryFilter::new().predicate(&|v| visible_query.contains(v)), default(),
|entity| { |entity| {
// println!("{:?}", entity);
if let Ok((visible, _, _)) = visible_query.get(entity) { if let Ok((visible, _, _)) = visible_query.get(entity) {
// println!(
// "{entity:?}: {visible:?}: {:?}",
// transform.translation().truncate()
// );
coord_entities.insert(entity); coord_entities.insert(entity);
opacity = opacity.max(**visible); opacity = opacity.max(**visible);
} }
true true
}, },
); );
cache.insert((coord.x, coord.y), (opacity, coord_entities.clone())); to_insert = Some(((coord.x, coord.y), (opacity, coord_entities.clone())));
Some((opacity, coord_entities))
} else {
// println!("No hits, 0");
let coord_entities = HashSet::new();
cache.insert((coord.x, coord.y), (0, coord_entities.clone()));
Some((0, coord_entities))
}
};
if let Some((mut opacity, coord_entities)) = result {
// println!("Opacity: {opacity}, coord_entities: {coord_entities:?}");
for e in &coord_entities {
let mut should_insert = true;
if e == viewer_entity {
opacity = 0;
} else {
let dest = Vec2::new(coord.x as f32, coord.y as f32);
let dir = dest - *start;
// println!(
// "Checking visibility of {e} by casting from {start} to {dest}, {dir}"
// );
rapier_context.intersections_with_ray(
*start,
dir,
1.,
true,
QueryFilter::new()
.exclude_sensors()
.exclude_collider(*e)
.predicate(&|e| visible_query.contains(e)),
|entity, hit| {
if entity != *viewer_entity {
// println!("Hit {entity} at {hit:?}");
should_insert = false;
}
true
},
);
}
if should_insert {
new_visible_entities.insert(*e);
}
}
// println!("New opacity: {opacity}"); // println!("New opacity: {opacity}");
opacity opacity
} else { } else {
// println!("No hits, 0");
to_insert = Some(((coord.x, coord.y), default()));
0 0
} }
};
if let Some((k, v)) = to_insert {
cache.borrow_mut().insert(k, v);
}
if coord_entities.contains(&viewer_entity) {
let mut coord_entities = coord_entities.clone();
coord_entities.retain(|e| e != viewer_entity);
let opacity = coord_entities
.iter()
.map(|v| visible_query.get(*v).unwrap().0 .0)
.max()
.unwrap_or(0);
// println!("Viewer hit, removing viewer opacity: {opacity}");
opacity
} else {
opacity
}
})), })),
); );
let mut new_visible = HashSet::new(); let mut new_visible = HashSet::new();
let mut new_visible_entities = HashSet::new();
// println!("Start: {viewer_entity}"); // println!("Start: {viewer_entity}");
context.for_each_visible( context.for_each_visible(
Coord::new(start.x_i32(), start.y_i32()), Coord::new(start.x_i32(), start.y_i32()),
@ -192,6 +156,11 @@ impl Viewshed {
u8::MAX, u8::MAX,
|coord, _directions, _visibility| { |coord, _directions, _visibility| {
new_visible.insert((coord.x, coord.y)); new_visible.insert((coord.x, coord.y));
if let Some((_, entities)) = cache.borrow().get(&(coord.x, coord.y)) {
for e in entities {
new_visible_entities.insert(*e);
}
}
}, },
); );
if self.visible_points != new_visible { if self.visible_points != new_visible {
@ -199,17 +168,12 @@ impl Viewshed {
} }
if new_visible_entities != **visible_entities { if new_visible_entities != **visible_entities {
for lost in visible_entities.difference(&new_visible_entities) { for lost in visible_entities.difference(&new_visible_entities) {
events.send(VisibilityChanged::Lost { commands.trigger_targets(VisibilityChanged::Lost(*lost), *viewer_entity);
viewer: *viewer_entity,
viewed: *lost,
});
} }
for gained in new_visible_entities.difference(visible_entities) { for gained in new_visible_entities.difference(visible_entities) {
// println!("transition: {:?} gains {:?}", viewer_entity, gained); // println!("transition: {:?} gains {:?}", viewer_entity,
events.send(VisibilityChanged::Gained { // gained);
viewer: *viewer_entity, commands.trigger_targets(VisibilityChanged::Gained(*gained), *viewer_entity);
viewed: *gained,
});
} }
**visible_entities = new_visible_entities; **visible_entities = new_visible_entities;
} }
@ -256,8 +220,8 @@ impl ViewshedBundle {
#[derive(Event)] #[derive(Event)]
pub enum VisibilityChanged { pub enum VisibilityChanged {
Gained { viewer: Entity, viewed: Entity }, Gained(Entity),
Lost { viewer: Entity, viewed: Entity }, Lost(Entity),
} }
impl PointLike for Coord { impl PointLike for Coord {
@ -284,17 +248,14 @@ fn add_visibility_indices<MapData: 'static + Clone + Default + Send + Sync>(
} }
fn viewshed_removed( fn viewshed_removed(
mut commands: Commands,
mut query: RemovedComponents<Viewshed>, mut query: RemovedComponents<Viewshed>,
visible_entities: Query<&VisibleEntities>, visible_entities: Query<&VisibleEntities>,
mut events: EventWriter<VisibilityChanged>,
) { ) {
for entity in query.read() { for entity in query.read() {
if let Ok(visible) = visible_entities.get(entity) { if let Ok(visible) = visible_entities.get(entity) {
for e in visible.iter() { for e in visible.iter() {
events.send(VisibilityChanged::Lost { commands.trigger_targets(VisibilityChanged::Lost(*e), entity);
viewer: entity,
viewed: *e,
});
} }
} }
} }
@ -320,6 +281,7 @@ where
} }
fn update_viewshed( fn update_viewshed(
mut commands: Commands,
config: Res<RapierConfiguration>, config: Res<RapierConfiguration>,
visible: Query<(&Visible, &Collider, &GlobalTransform)>, visible: Query<(&Visible, &Collider, &GlobalTransform)>,
mut viewers: Query<( mut viewers: Query<(
@ -329,26 +291,26 @@ fn update_viewshed(
&GlobalTransform, &GlobalTransform,
)>, )>,
rapier_context: Res<RapierContext>, rapier_context: Res<RapierContext>,
mut changed: EventWriter<VisibilityChanged>,
) { ) {
if !config.query_pipeline_active { if !config.query_pipeline_active {
return; return;
} }
let mut cache = HashMap::new(); let mut cache = default();
for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers { for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers {
viewshed.update( viewshed.update(
&mut commands,
&viewer_entity, &viewer_entity,
&mut visible_entities, &mut visible_entities,
&viewer_transform.translation().truncate(), &viewer_transform.translation().truncate(),
&rapier_context, &rapier_context,
&visible, &visible,
&mut changed,
&mut cache, &mut cache,
); );
} }
} }
fn remove_visible( fn remove_visible(
mut commands: Commands,
mut removed: RemovedComponents<Visible>, mut removed: RemovedComponents<Visible>,
mut viewers: Query<( mut viewers: Query<(
Entity, Entity,
@ -358,23 +320,21 @@ fn remove_visible(
)>, )>,
rapier_context: Res<RapierContext>, rapier_context: Res<RapierContext>,
visible: Query<(&Visible, &Collider, &GlobalTransform)>, visible: Query<(&Visible, &Collider, &GlobalTransform)>,
mut changed: EventWriter<VisibilityChanged>,
) { ) {
if !removed.is_empty() { if !removed.is_empty() {
let mut cache = HashMap::new(); let mut cache = default();
for removed in removed.read() { for removed in removed.read() {
for (viewer_entity, mut viewshed, mut visible_entities, start) in &mut viewers { for (viewer_entity, mut viewshed, mut visible_entities, start) in &mut viewers {
if !visible_entities.contains(&removed) { if !visible_entities.contains(&removed) {
continue; continue;
} }
visible_entities.remove(&removed);
viewshed.update( viewshed.update(
&mut commands,
&viewer_entity, &viewer_entity,
&mut visible_entities, &mut visible_entities,
&start.translation().truncate(), &start.translation().truncate(),
&rapier_context, &rapier_context,
&visible, &visible,
&mut changed,
&mut cache, &mut cache,
); );
} }
@ -400,28 +360,18 @@ fn update_revealed_tiles<D: 'static + Clone + Default + Send + Sync>(
} }
fn log_visible( fn log_visible(
time: Res<Time>, trigger: Trigger<VisibilityChanged>,
mut recently_lost: Local<HashMap<Entity, Timer>>, viewers: Query<(&GlobalTransform, Option<&Collider>), (With<Player>, With<Viewshed>)>,
mut events: EventReader<VisibilityChanged>,
mut log: Query<&mut Log>,
viewers: Query<(Entity, &GlobalTransform, Option<&Collider>), (With<Player>, With<Viewshed>)>,
visible: Query<(&Name, &GlobalTransform, Option<&Collider>), Without<DontLogWhenVisible>>, visible: Query<(&Name, &GlobalTransform, Option<&Collider>), Without<DontLogWhenVisible>>,
mut log: Query<&mut Log>,
) { ) {
for timer in recently_lost.values_mut() { if let VisibilityChanged::Gained(entity) = trigger.event() {
timer.tick(time.delta()); if *entity == trigger.entity() {
return;
} }
recently_lost.retain(|_entity, timer| !timer.finished()); if let Ok((viewer_transform, viewer_collider)) = viewers.get(trigger.entity()) {
for event in events.read() { if let Ok((name, viewed_transform, viewed_collider)) = visible.get(*entity) {
let viewer = match event { // println!("Gain {name}: {entity}");
VisibilityChanged::Gained { viewer, .. } => viewer,
VisibilityChanged::Lost { viewer, .. } => viewer,
};
if let Ok((viewer_entity, viewer_transform, viewer_collider)) = viewers.get(*viewer) {
if let VisibilityChanged::Gained { viewed, .. } = event {
if *viewed == viewer_entity || recently_lost.contains_key(viewed) {
continue;
}
if let Ok((name, viewed_transform, viewed_collider)) = visible.get(*viewed) {
let location = if let (Some(viewer_collider), Some(viewed_collider)) = let location = if let (Some(viewer_collider), Some(viewed_collider)) =
(viewer_collider, viewed_collider) (viewer_collider, viewed_collider)
{ {
@ -438,15 +388,10 @@ fn log_visible(
log.push(format!("{}: {location}", name)); log.push(format!("{}: {location}", name));
} }
} }
} else if let VisibilityChanged::Lost { viewed, .. } = event {
recently_lost.insert(*viewed, Timer::from_seconds(2., TimerMode::Once));
}
} }
} }
} }
pub const LOG_VISIBLE_LABEL: &str = "LOG_VISIBLE";
pub struct VisibilityPlugin<MapData: 'static + Clone + Default + Send + Sync>(PhantomData<MapData>); pub struct VisibilityPlugin<MapData: 'static + Clone + Default + Send + Sync>(PhantomData<MapData>);
impl<MapData: 'static + Clone + Default + Send + Sync> Default for VisibilityPlugin<MapData> { impl<MapData: 'static + Clone + Default + Send + Sync> Default for VisibilityPlugin<MapData> {
@ -457,8 +402,7 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Default for VisibilityPlu
impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlugin<MapData> { impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlugin<MapData> {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_event::<VisibilityChanged>() app.add_systems(
.add_systems(
FixedPreUpdate, FixedPreUpdate,
( (
add_visibility_indices::<MapData>, add_visibility_indices::<MapData>,
@ -466,9 +410,7 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlug
update_revealed_tiles::<MapData>, update_revealed_tiles::<MapData>,
), ),
) )
.add_systems( .add_systems(FixedPostUpdate, (viewshed_removed, remove_visible))
FixedPostUpdate, .observe(log_visible);
(log_visible, viewshed_removed, remove_visible),
);
} }
} }