use std::collections::{HashMap, HashSet}; use bevy::prelude::*; use bevy_rapier2d::na::UnitComplex; use coord_2d::{Coord, Size}; use derive_more::{Deref, DerefMut}; use shadowcast::{vision_distance, Context, InputGrid}; use crate::{ bevy_rapier2d::prelude::*, core::{Angle, Coordinates, Player, PointLike}, log::Log, map::{ITileType, Map, MapConfig}, utils::target_and_other, }; #[derive(Clone, Copy, Debug, Deref, DerefMut, Reflect)] #[reflect(Component)] pub struct BlocksVisibility(pub u8); impl Default for BlocksVisibility { fn default() -> Self { Self(u8::MAX) } } #[derive(Clone, Copy, Debug, Default, Reflect)] #[reflect(Component)] pub struct DontLogWhenVisible; #[derive(Clone, Debug, Default, Deref, DerefMut, Reflect)] #[reflect(Component)] pub struct RevealedTiles(pub Vec); #[derive(Clone, Debug, Eq, PartialEq)] pub struct Viewshed { pub range: u32, pub visible_points: HashSet<(i32, i32)>, } impl Default for Viewshed { fn default() -> Self { Self { range: 15, visible_points: HashSet::new(), } } } impl Viewshed { pub fn is_point_visible(&self, point: &dyn PointLike) -> bool { self.visible_points.contains(&point.into()) } } #[derive(Clone, Copy, Debug, Default, Reflect)] struct VisibilityCollider; #[derive(Clone, Debug, Default, Deref, DerefMut)] pub struct VisibleEntities(HashSet); #[derive(Clone, Debug, Default, Deref, DerefMut, Reflect)] #[reflect(Component)] pub struct VisibleTiles(pub Vec); #[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 }, } impl PointLike for Coord { fn x(&self) -> f32 { self.x as f32 } fn y(&self) -> f32 { self.y as f32 } } fn add_visibility_indices( mut commands: Commands, query: Query<(Entity, &Map), (Added, Without, Without)>, map_config: Res, ) { for (entity, map) in query.iter() { let count = map.width * map.height; commands .entity(entity) .insert(VisibleTiles(vec![false; count])); commands .entity(entity) .insert(RevealedTiles(vec![map_config.start_revealed; count])); } } fn viewshed_added(mut commands: Commands, query: Query>) { for entity in query.iter() { let id = commands.spawn().insert(VisibilityCollider).id(); commands.entity(entity).push_children(&[id]); } } fn viewshed_changed( mut commands: Commands, query: Query<(Entity, &Viewshed, &RigidBodyPosition), Changed>, mut collider_data: Query< (&Parent, Entity, Option<&mut ColliderShape>), With, >, ) { for (entity, viewshed, position) in query.iter() { for (parent, child_entity, collider_shape) in collider_data.iter_mut() { if **parent != entity { continue; } if viewshed.visible_points.len() < 2 { commands.entity(child_entity).remove::(); } else { let position = position.position; let mut points = vec![]; for p in &viewshed.visible_points { points.push(point!( position.translation.x - p.x(), position.translation.y - p.y() )); } if let Some(shape) = ColliderShape::convex_hull(&points) { //println!("Shape for {:?}", points); if let Some(mut collider_shape) = collider_shape { *collider_shape = shape; } else { //println!("Creating collider at {:?}", coordinates.i32()); commands.entity(child_entity).insert_bundle(ColliderBundle { collider_type: ColliderType::Sensor, shape, flags: ActiveEvents::INTERSECTION_EVENTS.into(), ..Default::default() }); } } } } } } fn lock_rotation( mut query: Query<(&Parent, &mut ColliderPosition), With>, positions: Query<&RigidBodyPosition>, ) { for (parent, mut position) in query.iter_mut() { if let Ok(parent_position) = positions.get(**parent) { let delta = parent_position .position .rotation .angle_to(&UnitComplex::new(0.)); println!("Syncing: {:?}", delta); position.rotation = UnitComplex::new(delta); } } } fn viewshed_removed( mut commands: Commands, query: RemovedComponents, children: Query<&Children>, collider_shapes: Query>, ) { for entity in query.iter() { if let Ok(children) = children.get(entity) { for child in children.iter() { if collider_shapes.get(*child).is_ok() { commands.entity(*child).despawn_recursive(); break; } } } } } pub struct VisibilityGrid<'a, F>(pub &'a Map, pub F); impl<'a, F> InputGrid for VisibilityGrid<'a, F> where F: Fn(Coord) -> u8, { type Grid = VisibilityGrid<'a, F>; type Opacity = u8; fn size(&self, grid: &Self::Grid) -> Size { Size::new(grid.0.width as u32, grid.0.height as u32) } fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity { self.1(coord) } } fn update_viewshed( viewer_entity: &Entity, viewshed: &mut Viewshed, start: &dyn PointLike, query_pipeline: &QueryPipeline, collider_query: &QueryPipelineColliderComponentsQuery, map: &Map, blocks_visibility: &Query<&BlocksVisibility>, ) { let mut context: Context = 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 && blocks_visibility.get(v.entity()).is_ok()), |handle| { if let Ok(blocks_visibility) = blocks_visibility.get(handle.entity()) { opacity = **blocks_visibility; false } else { true } }, ); opacity }); let mut new_visible = HashSet::new(); context.for_each_visible( coord, &visibility_grid, &visibility_grid, vision_distance, 255, |coord, _directions, _visibility| { new_visible.insert((coord.x, coord.y)); }, ); if viewshed.visible_points != new_visible { viewshed.visible_points = new_visible; } } fn update_viewshed_for_coordinates( visible: Query<(Entity, &Coordinates), (Changed, With)>, mut viewers: Query<(Entity, &mut Viewshed, &Coordinates)>, map: Query<&Map>, query_pipeline: Res, collider_query: QueryPipelineColliderComponentsQuery, blocks_visibility: Query<&BlocksVisibility>, ) { for (visible_entity, coordinates) in visible.iter() { for (viewer_entity, mut viewshed, start) in viewers.iter_mut() { 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, &blocks_visibility, ); } } } } fn update_viewshed_for_start( mut viewers: Query<(Entity, &mut Viewshed, &Coordinates), Changed>, map: Query<&Map>, query_pipeline: Res, collider_query: QueryPipelineColliderComponentsQuery, blocks_visibility: Query<&BlocksVisibility>, ) { 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, &blocks_visibility, ); } } } fn remove_blocks_visibility( removed: RemovedComponents, mut viewers: Query<(Entity, &mut Viewshed, &mut VisibleEntities, &Coordinates)>, map: Query<&Map>, query_pipeline: Res, collider_query: QueryPipelineColliderComponentsQuery, blocks_visibility: Query<&BlocksVisibility>, ) { 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, &blocks_visibility, ); } } } } fn update_visible_and_revealed_tiles( mut map: Query<(&Map, &mut RevealedTiles, &mut VisibleTiles)>, viewers: Query<&Viewshed, With>, ) { for (map, mut revealed_tiles, mut visible_tiles) in map.iter_mut() { for viewshed in viewers.iter() { for t in visible_tiles.iter_mut() { *t = false } for v in viewshed.visible_points.iter() { let idx = v.to_index(map.width); if idx >= revealed_tiles.len() || idx >= visible_tiles.len() { continue; } revealed_tiles[idx] = true; visible_tiles[idx] = true; } } } } fn intersection( mut events: EventReader, colliders: Query<&Parent, With>, mut viewers: Query<&mut VisibleEntities>, names: Query<&Name>, parents: Query<&Parent>, mut visibility_changed: EventWriter, ) { for event in events.iter() { println!("{:?}", event); if let Some((visibility_collider, other)) = target_and_other(event.collider1.entity(), event.collider2.entity(), |v| { colliders.get(v).is_ok() }) { if let Ok(parent) = colliders.get(visibility_collider) { if let Ok(mut visible_entities) = viewers.get_mut(**parent) { if event.intersecting { println!("{:?} is visible: {:?}", other, names.get(other)); if let Ok(p) = parents.get(other) { println!("{:?}", names.get(**p)); } visibility_changed.send(VisibilityChanged::Gained { viewer: **parent, viewed: other, }); visible_entities.insert(other); } else { println!("{:?} is not visible", other); visibility_changed.send(VisibilityChanged::Lost { viewer: **parent, viewed: other, }); visible_entities.remove(&other); } } } } } } fn log_visible( time: Res