Compare commits
No commits in common. "fb34f6ef122decea4bafe2a0ca3afb4b98df9152" and "8eb050d10ad0e3f732cb0b95b7f03632e420113e" have entirely different histories.
fb34f6ef12
...
8eb050d10a
|
@ -31,20 +31,18 @@ impl Default for SoundIcon {
|
|||
|
||||
fn added(mut commands: Commands, icons: Query<(Entity, &SoundIcon), Added<SoundIcon>>) {
|
||||
for (entity, icon) in &icons {
|
||||
if let Some(mut commands) = commands.get_entity(entity) {
|
||||
let buffer = icon.audio.clone();
|
||||
let gain = icon.gain;
|
||||
let pitch = icon.pitch;
|
||||
let looping = icon.interval.is_none();
|
||||
commands.insert(Sound {
|
||||
audio: buffer,
|
||||
gain,
|
||||
pitch,
|
||||
looping,
|
||||
paused: true,
|
||||
..default()
|
||||
});
|
||||
}
|
||||
let buffer = icon.audio.clone();
|
||||
let gain = icon.gain;
|
||||
let pitch = icon.pitch;
|
||||
let looping = icon.interval.is_none();
|
||||
commands.entity(entity).insert(Sound {
|
||||
audio: buffer,
|
||||
gain,
|
||||
pitch,
|
||||
looping,
|
||||
paused: true,
|
||||
..default()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -6,7 +6,10 @@ use std::{
|
|||
|
||||
use bevy::prelude::*;
|
||||
|
||||
use bevy_rapier2d::{na::Isometry2, parry::bounding_volume::BoundingVolume};
|
||||
use bevy_rapier2d::{
|
||||
na::{Isometry2, Vector2},
|
||||
parry::bounding_volume::BoundingVolume,
|
||||
};
|
||||
use coord_2d::{Coord, Size};
|
||||
use shadowcast::{vision_distance, Context, InputGrid};
|
||||
|
||||
|
@ -47,107 +50,134 @@ impl Viewshed {
|
|||
|
||||
fn update(
|
||||
&mut self,
|
||||
commands: &mut Commands,
|
||||
viewer_entity: &Entity,
|
||||
visible_entities: &mut VisibleEntities,
|
||||
start: &Vec2,
|
||||
start: &GlobalTransform,
|
||||
rapier_context: &RapierContext,
|
||||
visible_query: &Query<(&Visible, &Collider, &GlobalTransform)>,
|
||||
cache: &mut RefCell<HashMap<(i32, i32), (u8, HashSet<Entity>)>>,
|
||||
events: &mut EventWriter<VisibilityChanged>,
|
||||
cache: &mut HashMap<(i32, i32), (u8, HashSet<Entity>)>,
|
||||
) {
|
||||
// println!("Start");
|
||||
let mut boxes = vec![];
|
||||
let shape = Collider::cuboid(self.range as f32, self.range as f32);
|
||||
rapier_context.intersections_with_shape(*start, 0., &shape, default(), |entity| {
|
||||
if let Ok((_, collider, transform)) = visible_query.get(entity) {
|
||||
let position =
|
||||
Isometry2::translation(transform.translation().x, transform.translation().y);
|
||||
// println!(
|
||||
// "Hit {:?}, pushing {:?}",
|
||||
// entity,
|
||||
// collider.raw.compute_aabb(&position)
|
||||
// );
|
||||
boxes.push(collider.raw.compute_aabb(&position));
|
||||
}
|
||||
true
|
||||
});
|
||||
rapier_context.intersections_with_shape(
|
||||
start.translation().truncate(),
|
||||
0.,
|
||||
&shape,
|
||||
QueryFilter::new()
|
||||
.exclude_collider(*viewer_entity)
|
||||
.predicate(&|e| visible_query.contains(e)),
|
||||
|entity| {
|
||||
if let Ok((_, collider, transform)) = visible_query.get(entity) {
|
||||
let position = Isometry2::new(
|
||||
Vector2::new(transform.translation().x, transform.translation().y),
|
||||
0.,
|
||||
);
|
||||
// println!(
|
||||
// "Hit {:?}, pushing {:?}",
|
||||
// entity,
|
||||
// collider.raw.compute_aabb(&position)
|
||||
// );
|
||||
boxes.push(collider.raw.compute_aabb(&position));
|
||||
}
|
||||
true
|
||||
},
|
||||
);
|
||||
let mut context: Context<u8> = Context::default();
|
||||
let vision_distance = vision_distance::Circle::new(self.range);
|
||||
let shape = Collider::cuboid(0.49, 0.49);
|
||||
let mut new_visible_entities = HashSet::new();
|
||||
let size = (
|
||||
(start.x.abs() + self.range as f32 * 2.) as u32,
|
||||
(start.y.abs() + self.range as f32 * 2.) as u32,
|
||||
(start.translation().x.abs() + self.range as f32) as u32,
|
||||
(start.translation().y.abs() + self.range as f32) as u32,
|
||||
);
|
||||
let visibility_grid = VisibilityGrid(
|
||||
size,
|
||||
RefCell::new(Box::new(|coord: Coord| {
|
||||
let shape_pos = Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5);
|
||||
// println!("Checking {coord:?}: {shape_pos:?}");
|
||||
// println!("Checking {:?}", shape_pos);
|
||||
if start.distance(&shape_pos) > self.range as f32 {
|
||||
// println!("Out of range");
|
||||
return u8::MAX;
|
||||
}
|
||||
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))
|
||||
let result = if let Some((opacity, coord_entities)) = cache.get(&(coord.x, coord.y))
|
||||
{
|
||||
// println!("Cache hit: {opacity:?}: {entities:?}");
|
||||
coord_entities = entities.clone();
|
||||
*opacity
|
||||
Some((*opacity, coord_entities.clone()))
|
||||
} else {
|
||||
let position = Isometry2::translation(shape_pos.x, shape_pos.y);
|
||||
let position = Isometry2::new(Vector2::new(shape_pos.x, shape_pos.y), 0.);
|
||||
let aabb = shape.raw.compute_aabb(&position);
|
||||
if boxes.iter().any(|b| b.intersects(&aabb)) {
|
||||
// println!("Hit");
|
||||
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();
|
||||
rapier_context.intersections_with_shape(
|
||||
shape_pos,
|
||||
0.,
|
||||
&shape,
|
||||
default(),
|
||||
QueryFilter::new()
|
||||
.exclude_collider(*viewer_entity)
|
||||
.predicate(&|v| visible_query.contains(v)),
|
||||
|entity| {
|
||||
// println!("{:?}", entity);
|
||||
coord_entities.insert(entity);
|
||||
if let Ok((visible, _, _)) = visible_query.get(entity) {
|
||||
// println!(
|
||||
// "{entity:?}: {visible:?}: {:?}",
|
||||
// transform.translation().truncate()
|
||||
// );
|
||||
coord_entities.insert(entity);
|
||||
opacity = opacity.max(**visible);
|
||||
}
|
||||
true
|
||||
},
|
||||
);
|
||||
to_insert = Some(((coord.x, coord.y), (opacity, coord_entities.clone())));
|
||||
// println!("New opacity: {opacity}");
|
||||
opacity
|
||||
cache.insert((coord.x, coord.y), (opacity, coord_entities.clone()));
|
||||
Some((opacity, coord_entities))
|
||||
} else {
|
||||
// println!("No hits, 0");
|
||||
to_insert = Some(((coord.x, coord.y), default()));
|
||||
0
|
||||
let coord_entities = HashSet::new();
|
||||
cache.insert((coord.x, coord.y), (0, coord_entities.clone()));
|
||||
Some((0, coord_entities))
|
||||
}
|
||||
};
|
||||
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}");
|
||||
if let Some((opacity, coord_entities)) = result {
|
||||
for e in &coord_entities {
|
||||
let mut should_insert = true;
|
||||
if coord_entities.len() > 1 {
|
||||
let start = start.translation().truncate();
|
||||
let dest = Vec2::new(coord.x as f32, coord.y as f32);
|
||||
let dir = dest - start;
|
||||
rapier_context.intersections_with_ray(
|
||||
start,
|
||||
dir,
|
||||
1.,
|
||||
true,
|
||||
QueryFilter::new()
|
||||
.exclude_sensors()
|
||||
.exclude_collider(*viewer_entity)
|
||||
.exclude_collider(*e)
|
||||
.predicate(&|e| visible_query.contains(e)),
|
||||
|_, _| {
|
||||
should_insert = false;
|
||||
false
|
||||
},
|
||||
);
|
||||
}
|
||||
if should_insert {
|
||||
new_visible_entities.insert(*e);
|
||||
}
|
||||
}
|
||||
opacity
|
||||
} else {
|
||||
opacity
|
||||
0
|
||||
}
|
||||
})),
|
||||
);
|
||||
let mut new_visible = HashSet::new();
|
||||
let mut new_visible_entities = HashSet::new();
|
||||
// println!("Start: {viewer_entity}");
|
||||
context.for_each_visible(
|
||||
Coord::new(start.x_i32(), start.y_i32()),
|
||||
&visibility_grid,
|
||||
|
@ -156,11 +186,6 @@ impl Viewshed {
|
|||
u8::MAX,
|
||||
|coord, _directions, _visibility| {
|
||||
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 {
|
||||
|
@ -168,12 +193,17 @@ impl Viewshed {
|
|||
}
|
||||
if new_visible_entities != **visible_entities {
|
||||
for lost in visible_entities.difference(&new_visible_entities) {
|
||||
commands.trigger_targets(VisibilityChanged::Lost(*lost), *viewer_entity);
|
||||
events.send(VisibilityChanged::Lost {
|
||||
viewer: *viewer_entity,
|
||||
viewed: *lost,
|
||||
});
|
||||
}
|
||||
for gained in new_visible_entities.difference(visible_entities) {
|
||||
// println!("transition: {:?} gains {:?}", viewer_entity,
|
||||
// gained);
|
||||
commands.trigger_targets(VisibilityChanged::Gained(*gained), *viewer_entity);
|
||||
// println!("transition: {:?} gains {:?}", viewer_entity, gained);
|
||||
events.send(VisibilityChanged::Gained {
|
||||
viewer: *viewer_entity,
|
||||
viewed: *gained,
|
||||
});
|
||||
}
|
||||
**visible_entities = new_visible_entities;
|
||||
}
|
||||
|
@ -220,8 +250,8 @@ impl ViewshedBundle {
|
|||
|
||||
#[derive(Event)]
|
||||
pub enum VisibilityChanged {
|
||||
Gained(Entity),
|
||||
Lost(Entity),
|
||||
Gained { viewer: Entity, viewed: Entity },
|
||||
Lost { viewer: Entity, viewed: Entity },
|
||||
}
|
||||
|
||||
impl PointLike for Coord {
|
||||
|
@ -248,14 +278,17 @@ fn add_visibility_indices<MapData: 'static + Clone + Default + Send + Sync>(
|
|||
}
|
||||
|
||||
fn viewshed_removed(
|
||||
mut commands: Commands,
|
||||
mut query: RemovedComponents<Viewshed>,
|
||||
visible_entities: Query<&VisibleEntities>,
|
||||
mut events: EventWriter<VisibilityChanged>,
|
||||
) {
|
||||
for entity in query.read() {
|
||||
if let Ok(visible) = visible_entities.get(entity) {
|
||||
for e in visible.iter() {
|
||||
commands.trigger_targets(VisibilityChanged::Lost(*e), entity);
|
||||
events.send(VisibilityChanged::Lost {
|
||||
viewer: entity,
|
||||
viewed: *e,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -281,7 +314,6 @@ where
|
|||
}
|
||||
|
||||
fn update_viewshed(
|
||||
mut commands: Commands,
|
||||
config: Res<RapierConfiguration>,
|
||||
visible: Query<(&Visible, &Collider, &GlobalTransform)>,
|
||||
mut viewers: Query<(
|
||||
|
@ -291,26 +323,26 @@ fn update_viewshed(
|
|||
&GlobalTransform,
|
||||
)>,
|
||||
rapier_context: Res<RapierContext>,
|
||||
mut changed: EventWriter<VisibilityChanged>,
|
||||
) {
|
||||
if !config.query_pipeline_active {
|
||||
return;
|
||||
}
|
||||
let mut cache = default();
|
||||
let mut cache = HashMap::new();
|
||||
for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers {
|
||||
viewshed.update(
|
||||
&mut commands,
|
||||
&viewer_entity,
|
||||
&mut visible_entities,
|
||||
&viewer_transform.translation().truncate(),
|
||||
viewer_transform,
|
||||
&rapier_context,
|
||||
&visible,
|
||||
&mut changed,
|
||||
&mut cache,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_visible(
|
||||
mut commands: Commands,
|
||||
mut removed: RemovedComponents<Visible>,
|
||||
mut viewers: Query<(
|
||||
Entity,
|
||||
|
@ -320,21 +352,23 @@ fn remove_visible(
|
|||
)>,
|
||||
rapier_context: Res<RapierContext>,
|
||||
visible: Query<(&Visible, &Collider, &GlobalTransform)>,
|
||||
mut changed: EventWriter<VisibilityChanged>,
|
||||
) {
|
||||
if !removed.is_empty() {
|
||||
let mut cache = default();
|
||||
let mut cache = HashMap::new();
|
||||
for removed in removed.read() {
|
||||
for (viewer_entity, mut viewshed, mut visible_entities, start) in &mut viewers {
|
||||
if !visible_entities.contains(&removed) {
|
||||
continue;
|
||||
}
|
||||
visible_entities.remove(&removed);
|
||||
viewshed.update(
|
||||
&mut commands,
|
||||
&viewer_entity,
|
||||
&mut visible_entities,
|
||||
&start.translation().truncate(),
|
||||
start,
|
||||
&rapier_context,
|
||||
&visible,
|
||||
&mut changed,
|
||||
&mut cache,
|
||||
);
|
||||
}
|
||||
|
@ -360,38 +394,53 @@ fn update_revealed_tiles<D: 'static + Clone + Default + Send + Sync>(
|
|||
}
|
||||
|
||||
fn log_visible(
|
||||
trigger: Trigger<VisibilityChanged>,
|
||||
viewers: Query<(&GlobalTransform, Option<&Collider>), (With<Player>, With<Viewshed>)>,
|
||||
visible: Query<(&Name, &GlobalTransform, Option<&Collider>), Without<DontLogWhenVisible>>,
|
||||
time: Res<Time>,
|
||||
mut recently_lost: Local<HashMap<Entity, Timer>>,
|
||||
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>>,
|
||||
) {
|
||||
if let VisibilityChanged::Gained(entity) = trigger.event() {
|
||||
if *entity == trigger.entity() {
|
||||
return;
|
||||
}
|
||||
if let Ok((viewer_transform, viewer_collider)) = viewers.get(trigger.entity()) {
|
||||
if let Ok((name, viewed_transform, viewed_collider)) = visible.get(*entity) {
|
||||
// println!("Gain {name}: {entity}");
|
||||
let location = if let (Some(viewer_collider), Some(viewed_collider)) =
|
||||
(viewer_collider, viewed_collider)
|
||||
{
|
||||
viewer_transform.collider_direction_and_distance(
|
||||
viewer_collider,
|
||||
viewed_transform,
|
||||
viewed_collider,
|
||||
)
|
||||
} else {
|
||||
let yaw = viewer_transform.yaw();
|
||||
viewer_transform.direction_and_distance(viewed_transform, Some(yaw))
|
||||
};
|
||||
if let Ok(mut log) = log.get_single_mut() {
|
||||
log.push(format!("{}: {location}", name));
|
||||
for timer in recently_lost.values_mut() {
|
||||
timer.tick(time.delta());
|
||||
}
|
||||
recently_lost.retain(|_entity, timer| !timer.finished());
|
||||
for event in events.read() {
|
||||
let viewer = match event {
|
||||
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)) =
|
||||
(viewer_collider, viewed_collider)
|
||||
{
|
||||
viewer_transform.collider_direction_and_distance(
|
||||
viewer_collider,
|
||||
viewed_transform,
|
||||
viewed_collider,
|
||||
)
|
||||
} else {
|
||||
let yaw = viewer_transform.yaw();
|
||||
viewer_transform.direction_and_distance(viewed_transform, Some(yaw))
|
||||
};
|
||||
if let Ok(mut log) = log.get_single_mut() {
|
||||
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>);
|
||||
|
||||
impl<MapData: 'static + Clone + Default + Send + Sync> Default for VisibilityPlugin<MapData> {
|
||||
|
@ -402,15 +451,18 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Default for VisibilityPlu
|
|||
|
||||
impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlugin<MapData> {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(
|
||||
FixedPreUpdate,
|
||||
(
|
||||
add_visibility_indices::<MapData>,
|
||||
update_viewshed,
|
||||
update_revealed_tiles::<MapData>,
|
||||
),
|
||||
)
|
||||
.add_systems(FixedPostUpdate, (viewshed_removed, remove_visible))
|
||||
.observe(log_visible);
|
||||
app.add_event::<VisibilityChanged>()
|
||||
.add_systems(
|
||||
FixedPreUpdate,
|
||||
(
|
||||
add_visibility_indices::<MapData>,
|
||||
update_viewshed,
|
||||
update_revealed_tiles::<MapData>,
|
||||
),
|
||||
)
|
||||
.add_systems(
|
||||
FixedPostUpdate,
|
||||
(log_visible, viewshed_removed, remove_visible),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user