Compare commits

..

No commits in common. "1601354f409a85cb105d945c1a2feac62c1db5c6" and "827cae1a4b7d5b2bc6f7a2b66335077c7b38e833" have entirely different histories.

4 changed files with 135 additions and 177 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. => West, h if h > 7. * PI / 8. || h <= -7. * PI / 8. => East,
h if h > -7. * PI / 8. && h <= -5. * PI / 8. => SouthWest, h if h > -7. * PI / 8. && h <= -5. * PI / 8. => SouthEast,
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. => SouthEast, h if h > -3. * PI / 8. && h <= -PI / 8. => SouthWest,
_ => West, _ => West,
}) })
} }

View File

@ -1,9 +1,4 @@
use std::{ use std::{error::Error, fmt::Debug, hash::Hash, marker::PhantomData};
error::Error,
fmt::{Debug, Display},
hash::Hash,
marker::PhantomData,
};
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::prelude::*; use bevy_rapier2d::prelude::*;
@ -187,7 +182,7 @@ fn exploration_type_changed_announcement<ExplorationType>(
>, >,
) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>
where where
ExplorationType: Component + Default + Copy + Display, ExplorationType: Component + Default + Copy + Into<String>,
{ {
for (focused, changed) in &focused { for (focused, changed) in &focused {
if changed.is_added() { if changed.is_added() {
@ -195,7 +190,8 @@ where
} }
match &focused.0 { match &focused.0 {
Some(v) => { Some(v) => {
tts.speak(format!("{v}"), true)?; let v: String = (*v).into();
tts.speak(v, true)?;
} }
None => { None => {
tts.speak("Everything", true)?; tts.speak("Everything", true)?;
@ -288,7 +284,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 + Display, ExplorationType: Component + Copy + Into<String>,
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() {
@ -322,7 +318,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(format!("{t}")); tokens.push((*t).into());
} }
} }
} }
@ -389,7 +385,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 + Display, ExplorationType: 'static + Component + Default + Copy + Ord + PartialEq + Into<String>,
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,6 +99,7 @@ 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<
( (
@ -109,7 +110,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;
@ -137,12 +138,11 @@ 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}");
let rotation = Quat::from_rotation_z(yaw); transform.rotation = Quat::from_rotation_z(yaw);
if transform.rotation != rotation { tts.speak(direction.to_string(), true)?;
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, controls) (snap.pipe(error_handler), controls)
.chain() .chain()
.in_set(Movement), .in_set(Movement),
) )

View File

@ -1,11 +1,12 @@
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; use bevy_rapier2d::{na::Isometry2, 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,17 +51,100 @@ 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(size, *viewer_entity, opacity_map.clone()); 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:?}");
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}");
@ -72,36 +156,9 @@ 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));
let coord = IVec2::new(coord.x, coord.y); if let Some((_, entities)) = cache.borrow().get(&(coord.x, coord.y)) {
// println!("Checking {coord:?}");
if let Some((_, entities)) = opacity_map.get(&coord) {
for e in entities { for e in entities {
if entities.len() == 1 || sensors.contains(*e) {
new_visible_entities.insert(*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);
}
}
} }
} }
}, },
@ -114,6 +171,8 @@ 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;
@ -141,80 +200,6 @@ 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>);
@ -276,9 +261,12 @@ fn viewshed_removed(
} }
} }
pub struct VisibilityGrid(pub (u32, u32), pub Entity, pub OpacityMap); pub struct VisibilityGrid<F>(pub (u32, u32), pub RefCell<Box<F>>);
impl InputGrid for VisibilityGrid { impl<F> InputGrid for VisibilityGrid<F>
where
F: FnMut(Coord) -> u8,
{
type Grid = (u32, u32); type Grid = (u32, u32);
type Opacity = u8; type Opacity = u8;
@ -288,47 +276,35 @@ impl InputGrid for VisibilityGrid {
} }
fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity { fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity {
// println!("Checking {coord:?}"); (self.1.borrow_mut())(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(),
&opacity_map, &rapier_context,
&sensors, &visible,
&*rapier_context, &mut cache,
); );
} }
} }
@ -342,21 +318,11 @@ fn remove_visible(
&mut VisibleEntities, &mut VisibleEntities,
&GlobalTransform, &GlobalTransform,
)>, )>,
sensors: Query<&Sensor>,
rapier_context: Res<RapierContext>, rapier_context: Res<RapierContext>,
mut opacity_map: ResMut<OpacityMap>, visible: Query<(&Visible, &Collider, &GlobalTransform)>,
visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
) { ) {
if !removed.is_empty() { if !removed.is_empty() {
let mut to_update = HashSet::new(); let mut cache = default();
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) {
@ -367,9 +333,9 @@ fn remove_visible(
&viewer_entity, &viewer_entity,
&mut visible_entities, &mut visible_entities,
&start.translation().truncate(), &start.translation().truncate(),
&opacity_map, &rapier_context,
&sensors, &visible,
&*rapier_context, &mut cache,
); );
} }
} }
@ -405,6 +371,7 @@ 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)
{ {
@ -435,12 +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.init_resource::<OpacityMap>() app.add_systems(
.add_systems(
FixedPreUpdate,
update_opacity_map.before(update_viewshed),
)
.add_systems(
FixedPreUpdate, FixedPreUpdate,
( (
add_visibility_indices::<MapData>, add_visibility_indices::<MapData>,