Compare commits

...

4 Commits

4 changed files with 177 additions and 135 deletions

View File

@ -98,10 +98,10 @@ impl From<Rot2> for MovementDirection {
h if h > PI / 8. && h <= 3. * PI / 8. => NorthEast, h if h > PI / 8. && h <= 3. * PI / 8. => NorthEast,
h if h > 3. * PI / 8. && h <= 5. * PI / 8. => North, h if h > 3. * PI / 8. && h <= 5. * PI / 8. => North,
h if h > 5. * PI / 8. && h <= 7. * PI / 8. => NorthWest, h if h > 5. * PI / 8. && h <= 7. * PI / 8. => NorthWest,
h if h > 7. * PI / 8. || h <= -7. * PI / 8. => East, h if h > 7. * PI / 8. || h <= -7. * PI / 8. => West,
h if h > -7. * PI / 8. && h <= -5. * PI / 8. => SouthEast, h if h > -7. * PI / 8. && h <= -5. * PI / 8. => SouthWest,
h if h > -5. * PI / 8. && h <= -3. * PI / 8. => South, h if h > -5. * PI / 8. && h <= -3. * PI / 8. => South,
h if h > -3. * PI / 8. && h <= -PI / 8. => SouthWest, h if h > -3. * PI / 8. && h <= -PI / 8. => SouthEast,
_ => West, _ => West,
}) })
} }

View File

@ -1,4 +1,9 @@
use std::{error::Error, fmt::Debug, hash::Hash, marker::PhantomData}; use std::{
error::Error,
fmt::{Debug, Display},
hash::Hash,
marker::PhantomData,
};
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::prelude::*; use bevy_rapier2d::prelude::*;
@ -182,7 +187,7 @@ fn exploration_type_changed_announcement<ExplorationType>(
>, >,
) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>
where where
ExplorationType: Component + Default + Copy + Into<String>, ExplorationType: Component + Default + Copy + Display,
{ {
for (focused, changed) in &focused { for (focused, changed) in &focused {
if changed.is_added() { if changed.is_added() {
@ -190,8 +195,7 @@ where
} }
match &focused.0 { match &focused.0 {
Some(v) => { Some(v) => {
let v: String = (*v).into(); tts.speak(format!("{v}"), true)?;
tts.speak(v, true)?;
} }
None => { None => {
tts.speak("Everything", true)?; tts.speak("Everything", true)?;
@ -284,7 +288,7 @@ fn exploration_changed_announcement<ExplorationType, MapData>(
rapier_context: Res<RapierContext>, rapier_context: Res<RapierContext>,
) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>
where where
ExplorationType: Component + Copy + Into<String>, ExplorationType: Component + Copy + Display,
MapData: 'static + Clone + Default + Send + Sync, MapData: 'static + Clone + Default + Send + Sync,
{ {
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() { if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
@ -318,7 +322,7 @@ where
} }
if tokens.is_empty() { if tokens.is_empty() {
if let Ok(t) = types.get(entity) { if let Ok(t) = types.get(entity) {
tokens.push((*t).into()); tokens.push(format!("{t}"));
} }
} }
} }
@ -385,7 +389,7 @@ pub struct Exploration;
impl<ExplorationType, MapData> Plugin for ExplorationPlugin<ExplorationType, MapData> impl<ExplorationType, MapData> Plugin for ExplorationPlugin<ExplorationType, MapData>
where where
ExplorationType: 'static + Component + Default + Copy + Ord + PartialEq + Into<String>, ExplorationType: 'static + Component + Default + Copy + Ord + PartialEq + Display,
MapData: 'static + Clone + Default + Send + Sync, MapData: 'static + Clone + Default + Send + Sync,
{ {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {

View File

@ -99,7 +99,6 @@ impl Default for Speed {
} }
fn snap( fn snap(
mut tts: ResMut<Tts>,
mut snap_timers: ResMut<SnapTimers>, mut snap_timers: ResMut<SnapTimers>,
mut query: Query< mut query: Query<
( (
@ -110,7 +109,7 @@ fn snap(
), ),
With<Player>, With<Player>,
>, >,
) -> Result<(), Box<dyn Error>> { ) {
for (entity, actions, mut transform, direction) in &mut query { for (entity, actions, mut transform, direction) in &mut query {
if snap_timers.contains_key(&entity) { if snap_timers.contains_key(&entity) {
continue; continue;
@ -138,11 +137,12 @@ fn snap(
let yaw: Rot2 = direction.into(); let yaw: Rot2 = direction.into();
let yaw = yaw.as_radians(); let yaw = yaw.as_radians();
println!("Yaw: {yaw}"); println!("Yaw: {yaw}");
transform.rotation = Quat::from_rotation_z(yaw); let rotation = Quat::from_rotation_z(yaw);
tts.speak(direction.to_string(), true)?; if transform.rotation != rotation {
transform.rotation = rotation;
}
} }
} }
Ok(())
} }
fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) { fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
@ -380,7 +380,7 @@ impl Plugin for NavigationPlugin {
.add_systems(PreUpdate, (update_direction, add_speed)) .add_systems(PreUpdate, (update_direction, add_speed))
.add_systems( .add_systems(
Update, Update,
(snap.pipe(error_handler), controls) (snap, controls)
.chain() .chain()
.in_set(Movement), .in_set(Movement),
) )

View File

@ -1,12 +1,11 @@
use std::{ use std::{
cell::RefCell,
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
marker::PhantomData, marker::PhantomData,
}; };
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::{na::Isometry2, parry::bounding_volume::BoundingVolume}; use bevy_rapier2d::na::Isometry2;
use coord_2d::{Coord, Size}; use coord_2d::{Coord, Size};
use shadowcast::{vision_distance, Context, InputGrid}; use shadowcast::{vision_distance, Context, InputGrid};
@ -51,100 +50,17 @@ impl Viewshed {
viewer_entity: &Entity, viewer_entity: &Entity,
visible_entities: &mut VisibleEntities, visible_entities: &mut VisibleEntities,
start: &Vec2, start: &Vec2,
opacity_map: &OpacityMap,
sensors: &Query<&Sensor>,
rapier_context: &RapierContext, rapier_context: &RapierContext,
visible_query: &Query<(&Visible, &Collider, &GlobalTransform)>,
cache: &mut RefCell<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
});
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.49, 0.49);
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,
); );
let visibility_grid = VisibilityGrid( let visibility_grid = VisibilityGrid(size, *viewer_entity, opacity_map.clone());
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:?}");
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))
{
// 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(
shape_pos,
0.,
&shape,
default(),
|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
} else {
// println!("No hits, 0");
to_insert = Some(((coord.x, coord.y), default()));
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(); let mut new_visible_entities = HashSet::new();
// println!("Start: {viewer_entity}"); // println!("Start: {viewer_entity}");
@ -156,9 +72,36 @@ 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)) { let coord = IVec2::new(coord.x, coord.y);
// println!("Checking {coord:?}");
if let Some((_, entities)) = opacity_map.get(&coord) {
for e in entities { for e in entities {
new_visible_entities.insert(*e); if entities.len() == 1 || sensors.contains(*e) {
new_visible_entities.insert(*e);
} else {
let mut should_push = true;
let coord = Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5);
let dir = (coord - *start).normalize();
// println!("Casting from {coord}");
rapier_context.intersections_with_ray(
*start,
dir,
dir.distance(*start),
true,
default(),
|entity, _hit| {
if *e != entity && entities.contains(&e) {
// println!("{entities:?} contains {e} and hits at {:?}", hit.point);
// commands.entity(*e).log_components();
should_push = false;
}
true
},
);
if should_push {
new_visible_entities.insert(*e);
}
}
} }
} }
}, },
@ -171,8 +114,6 @@ impl Viewshed {
commands.trigger_targets(VisibilityChanged::Lost(*lost), *viewer_entity); commands.trigger_targets(VisibilityChanged::Lost(*lost), *viewer_entity);
} }
for gained in new_visible_entities.difference(visible_entities) { for gained in new_visible_entities.difference(visible_entities) {
// println!("transition: {:?} gains {:?}", viewer_entity,
// gained);
commands.trigger_targets(VisibilityChanged::Gained(*gained), *viewer_entity); commands.trigger_targets(VisibilityChanged::Gained(*gained), *viewer_entity);
} }
**visible_entities = new_visible_entities; **visible_entities = new_visible_entities;
@ -200,6 +141,80 @@ impl Visible {
} }
} }
#[derive(Resource, Clone, Deref, DerefMut, Default)]
pub struct OpacityMap(HashMap<IVec2, (u8, HashSet<Entity>)>);
impl OpacityMap {
fn update(
&mut self,
rapier_context: &RapierContext,
coordinates: HashSet<IVec2>,
visible: &Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
) {
self.retain(|k, _| !coordinates.contains(k));
let shape = Collider::cuboid(0.49, 0.49);
for coords in &coordinates {
let shape_pos = Vec2::new(coords.x as f32 + 0.5, coords.y as f32 + 0.5);
let mut opacity = 0;
let mut coord_entities = HashSet::new();
rapier_context.intersections_with_shape(shape_pos, 0., &shape, default(), |entity| {
if let Ok((_, _, _, visible)) = visible.get(entity) {
coord_entities.insert(entity);
opacity = opacity.max(**visible);
}
true
});
self.insert(*coords, (opacity, coord_entities));
}
}
}
fn update_opacity_map(
mut opacity_map: ResMut<OpacityMap>,
rapier_context: Res<RapierContext>,
query: Query<
(Entity, &GlobalTransform, &Collider, &Visible),
Or<(Changed<GlobalTransform>, Changed<Visible>)>,
>,
visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
) {
let mut to_update = HashSet::new();
for (entity, transform, collider, _) in &query {
// println!(
// "Updating {entity} at {:?}",
// transform.translation().truncate().as_ivec2()
// );
let mut prev = HashSet::new();
for (k, v) in opacity_map.iter() {
if v.1.contains(&entity) {
// println!("Also updating {k} because it contained entity");
prev.insert(*k);
}
}
let mut current = HashSet::new();
current.insert(transform.translation().truncate().as_ivec2());
let position = Isometry2::new(
transform.translation().truncate().into(),
transform.yaw().as_radians(),
);
let aabb = collider.raw.compute_aabb(&position);
for x in aabb.mins.x as i32..aabb.maxs.x as i32 {
for y in aabb.mins.y as i32..aabb.maxs.y as i32 {
// println!(
// "Also updating coordinates at {:?}",
// IVec2::new(x as i32, y as i32)
// );
current.insert(IVec2::new(x as i32, y as i32));
}
}
if prev != current {
to_update.extend(prev);
to_update.extend(current);
}
}
opacity_map.update(&rapier_context, to_update, &visible);
}
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)] #[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
pub struct VisibleEntities(HashSet<Entity>); pub struct VisibleEntities(HashSet<Entity>);
@ -261,12 +276,9 @@ fn viewshed_removed(
} }
} }
pub struct VisibilityGrid<F>(pub (u32, u32), pub RefCell<Box<F>>); pub struct VisibilityGrid(pub (u32, u32), pub Entity, pub OpacityMap);
impl<F> InputGrid for VisibilityGrid<F> impl InputGrid for VisibilityGrid {
where
F: FnMut(Coord) -> u8,
{
type Grid = (u32, u32); type Grid = (u32, u32);
type Opacity = u8; type Opacity = u8;
@ -276,35 +288,47 @@ where
} }
fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity { fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity {
(self.1.borrow_mut())(coord) // println!("Checking {coord:?}");
if let Some((opacity, entities)) = self.2.get(&IVec2::new(coord.x, coord.y)) {
if entities.len() == 1 && entities.contains(&self.1) {
// println!("Hit viewer, 0");
0
} else {
// println!("{opacity:?}");
*opacity
}
} else {
// println!("Miss, 0");
0
}
} }
} }
fn update_viewshed( fn update_viewshed(
mut commands: Commands, mut commands: Commands,
config: Res<RapierConfiguration>, config: Res<RapierConfiguration>,
visible: Query<(&Visible, &Collider, &GlobalTransform)>,
mut viewers: Query<( mut viewers: Query<(
Entity, Entity,
&mut Viewshed, &mut Viewshed,
&mut VisibleEntities, &mut VisibleEntities,
&GlobalTransform, &GlobalTransform,
)>, )>,
opacity_map: Res<OpacityMap>,
sensors: Query<&Sensor>,
rapier_context: Res<RapierContext>, rapier_context: Res<RapierContext>,
) { ) {
if !config.query_pipeline_active { if !config.query_pipeline_active {
return; return;
} }
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, &mut commands,
&viewer_entity, &viewer_entity,
&mut visible_entities, &mut visible_entities,
&viewer_transform.translation().truncate(), &viewer_transform.translation().truncate(),
&rapier_context, &opacity_map,
&visible, &sensors,
&mut cache, &*rapier_context,
); );
} }
} }
@ -318,11 +342,21 @@ fn remove_visible(
&mut VisibleEntities, &mut VisibleEntities,
&GlobalTransform, &GlobalTransform,
)>, )>,
sensors: Query<&Sensor>,
rapier_context: Res<RapierContext>, rapier_context: Res<RapierContext>,
visible: Query<(&Visible, &Collider, &GlobalTransform)>, mut opacity_map: ResMut<OpacityMap>,
visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
) { ) {
if !removed.is_empty() { if !removed.is_empty() {
let mut cache = default(); let mut to_update = HashSet::new();
for e in removed.read() {
for (k, v) in opacity_map.iter() {
if v.1.contains(&e) {
to_update.insert(*k);
}
}
}
opacity_map.update(&rapier_context, to_update, &visible);
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) {
@ -333,9 +367,9 @@ fn remove_visible(
&viewer_entity, &viewer_entity,
&mut visible_entities, &mut visible_entities,
&start.translation().truncate(), &start.translation().truncate(),
&rapier_context, &opacity_map,
&visible, &sensors,
&mut cache, &*rapier_context,
); );
} }
} }
@ -371,7 +405,6 @@ fn log_visible(
} }
if let Ok((viewer_transform, viewer_collider)) = viewers.get(trigger.entity()) { if let Ok((viewer_transform, viewer_collider)) = viewers.get(trigger.entity()) {
if let Ok((name, viewed_transform, viewed_collider)) = visible.get(*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)) = let location = if let (Some(viewer_collider), Some(viewed_collider)) =
(viewer_collider, viewed_collider) (viewer_collider, viewed_collider)
{ {
@ -402,15 +435,20 @@ 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_systems( app.init_resource::<OpacityMap>()
FixedPreUpdate, .add_systems(
( FixedPreUpdate,
add_visibility_indices::<MapData>, update_opacity_map.before(update_viewshed),
update_viewshed, )
update_revealed_tiles::<MapData>, .add_systems(
), FixedPreUpdate,
) (
.add_systems(FixedPostUpdate, (viewshed_removed, remove_visible)) add_visibility_indices::<MapData>,
.observe(log_visible); update_viewshed,
update_revealed_tiles::<MapData>,
),
)
.add_systems(FixedPostUpdate, (viewshed_removed, remove_visible))
.observe(log_visible);
} }
} }