Compare commits

...

21 Commits

Author SHA1 Message Date
8db8b72824 Remove bundles. 2025-01-07 12:27:37 -05:00
08c91380ad Various pathfinding/navigation fixes. 2025-01-06 20:33:46 -05:00
b524fc39da Fix off-by-1 errors in mapping. 2025-01-06 20:33:18 -05:00
ecec85d37c Return 0 opacity if out of range. 2025-01-06 20:32:25 -05:00
90351718cc Shuffle marker components out of `map module. 2025-01-03 20:13:53 -05:00
c2d6a1f0e8 Set gravity to 0. 2025-01-03 17:23:26 -05:00
380506b75c Initial port to Bevy 0.15. 2025-01-03 14:19:57 -05:00
f6c34057aa Don't update if physics is paused. 2025-01-03 11:15:32 -05:00
34613bfe07 Fix condition for visibility self-hit. 2024-12-10 14:26:59 -06:00
330d915267 Get pathfinding working. 2024-12-10 13:17:55 -06:00
850c5a5cdd Back to full-size rectangles. 2024-12-05 14:25:33 -06:00
0185b9c590 Update opacity map when collider AABBs change. 2024-12-04 18:28:52 -06:00
56f4b6ce14 Remove logging. 2024-12-04 18:28:34 -06:00
478644491a Fix typo and shrink colliders to minimize spawning warnings. 2024-12-04 17:40:25 -06:00
ed10eabb63 Lots of Avian updates and QoL fixes. 2024-12-04 16:51:25 -06:00
8dc4de0bd1 Begin slimming down PointLike. 2024-12-04 12:23:26 -06:00
2379ee6900 No need to calculate AABB separately. 2024-12-03 21:38:55 -06:00
224a4043e2 Appease Clippy. 2024-12-03 10:15:11 -06:00
2f85dcda91 Merge branch 'main' into avian 2024-12-03 10:08:51 -06:00
0554e2dded Merge branch 'main' into avian 2024-10-06 11:35:53 -05:00
7c7504834f WIP: Refactor to Avian. 2024-10-06 11:10:46 -05:00
10 changed files with 401 additions and 560 deletions

View File

@ -14,7 +14,7 @@ speech_dispatcher_0_10 = ["bevy_tts/speech_dispatcher_0_10"]
speech_dispatcher_0_11 = ["bevy_tts/speech_dispatcher_0_11"]
[dependencies.bevy]
version = "0.14"
version = "0.15"
default-features = false
features = [
"android_shared_stdcxx",
@ -48,12 +48,12 @@ features = [
]
[dependencies]
bevy_rapier2d = "0.27"
bevy_synthizer = "0.8"
bevy_tts = { version = "0.9", default-features = false, features = ["tolk"] }
avian2d = "0.2"
bevy_synthizer = "0.9"
bevy_tts = { version = "0.10", default-features = false, features = ["tolk"] }
coord_2d = "0.3"
here_be_dragons = { version = "0.3", features = ["serde"] }
leafwing-input-manager = "0.15"
leafwing-input-manager = "0.16"
maze_generator = "2"
once_cell = "1"
pathfinding = "4"

View File

@ -5,20 +5,32 @@ use std::{
sync::RwLock,
};
use avian2d::{
parry::{
math::Isometry,
query::{closest_points, distance, ClosestPoints},
},
prelude::*,
};
use bevy::{
app::PluginGroupBuilder,
math::{CompassOctant, CompassQuadrant, FloatOrd},
prelude::*,
};
use bevy_rapier2d::{
parry::query::{closest_points, distance, ClosestPoints},
prelude::*,
rapier::{math::Isometry, prelude::Aabb},
};
use once_cell::sync::Lazy;
use rand::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Component, Clone, Debug, Default, Reflect)]
#[reflect(Component)]
#[require(Transform, Collider(||Collider::rectangle(1., 1.)), RigidBody(|| RigidBody::Static))]
pub struct Obstacle;
#[derive(Default, Component, Clone, Debug, Reflect)]
#[reflect(Component)]
#[require(Transform, Collider, Sensor)]
pub struct Zone;
fn relative_desc(rot: &Rot2) -> String {
let mode = RELATIVE_DIRECTION_MODE.read().unwrap();
match rot.as_radians() {
@ -331,6 +343,16 @@ impl PointLike for Vec2 {
}
}
impl PointLike for IVec2 {
fn x(&self) -> f32 {
self.x as f32
}
fn y(&self) -> f32 {
self.y as f32
}
}
impl PointLike for (i32, i32) {
fn x(&self) -> f32 {
self.0 as f32
@ -371,27 +393,6 @@ impl PointLike for here_be_dragons::geometry::Point {
}
}
#[macro_export]
macro_rules! impl_pointlike_for_tuple_component {
($source:ty) => {
impl PointLike for $source {
fn x(&self) -> f32 {
self.0 .0 as f32
}
fn y(&self) -> f32 {
self.0 .1 as f32
}
}
};
}
impl From<&dyn PointLike> for (i32, i32) {
fn from(val: &dyn PointLike) -> Self {
val.i32()
}
}
pub trait TransformExt {
fn yaw(&self) -> Rot2;
}
@ -442,7 +443,14 @@ impl GlobalTransformExt for GlobalTransform {
(other.translation() / *scale).xy().into(),
other.yaw().as_radians(),
);
closest_points(&pos1, &*collider.raw, &pos2, &*other_collider.raw, f32::MAX).unwrap()
closest_points(
&pos1,
collider.shape().as_ref(),
&pos2,
other_collider.shape().as_ref(),
f32::MAX,
)
.unwrap()
}
fn collider_direction_and_distance(
@ -461,7 +469,13 @@ impl GlobalTransformExt for GlobalTransform {
other.yaw().as_radians(),
);
let closest = self.closest_points(collider, other, other_collider);
let distance = distance(&pos1, &*collider.raw, &pos2, &*other_collider.raw).unwrap() as u32;
let distance = distance(
&pos1,
collider.shape().as_ref(),
&pos2,
other_collider.shape().as_ref(),
)
.unwrap() as u32;
let tile_or_tiles = if distance == 1 { "tile" } else { "tiles" };
if distance > 0 {
if let ClosestPoints::WithinMargin(p1, p2) = closest {
@ -481,9 +495,6 @@ impl GlobalTransformExt for GlobalTransform {
}
}
#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, PartialEq)]
pub struct Area(pub Aabb);
#[derive(Component, Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct Player;
@ -589,9 +600,8 @@ impl Plugin for CorePlugin {
};
app.insert_resource(config)
.register_type::<CardinalDirection>()
.add_plugins(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(
config.pixels_per_unit as f32,
))
.add_plugins(PhysicsPlugins::default().with_length_unit(config.pixels_per_unit as f32))
.insert_resource(Gravity(Vec2::ZERO))
.add_systems(Startup, setup)
.add_systems(Update, sync_config);
}

View File

@ -5,8 +5,8 @@ use std::{
marker::PhantomData,
};
use avian2d::prelude::*;
use bevy::prelude::*;
use bevy_rapier2d::prelude::*;
use bevy_tts::Tts;
use leafwing_input_manager::prelude::*;
@ -42,9 +42,17 @@ pub struct ExplorationFocused;
#[derive(Component, Clone, Copy, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct Exploring(pub (f32, f32));
pub struct Exploring(pub Vec2);
impl_pointlike_for_tuple_component!(Exploring);
impl PointLike for Exploring {
fn x(&self) -> f32 {
self.0.x
}
fn y(&self) -> f32 {
self.0.y
}
}
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
pub struct FocusedExplorationType<T>(pub Option<T>)
@ -122,34 +130,45 @@ fn exploration_type_focus<ExplorationType>(
mut tts: ResMut<Tts>,
explorers: Query<(
Entity,
&GlobalTransform,
&ActionState<ExplorationAction>,
&VisibleEntities,
&FocusedExplorationType<ExplorationType>,
Option<&Exploring>,
)>,
features: Query<(Entity, &Transform, &ExplorationType)>,
features: Query<(Entity, &GlobalTransform, &ExplorationType)>,
) -> Result<(), Box<dyn Error>>
where
ExplorationType: Component + Default + PartialEq,
{
for (entity, actions, visible_entities, focused_type, exploring) in &explorers {
for (entity, transform, actions, visible_entities, focused_type, exploring) in &explorers {
let mut features = features
.iter()
.filter(|v| visible_entities.contains(&v.0))
.map(|v| (v.1.trunc(), v.2))
.collect::<Vec<((f32, f32), &ExplorationType)>>();
.map(|v| (v.1.translation().truncate(), v.2))
.collect::<Vec<(Vec2, &ExplorationType)>>();
if features.is_empty() {
tts.speak("Nothing visible.", true)?;
return Ok(());
}
features.sort_by(|(c1, _), (c2, _)| c1.partial_cmp(c2).unwrap());
features.sort_by(|(c1, _), (c2, _)| {
transform
.translation()
.truncate()
.distance(*c1)
.partial_cmp(&transform.translation().truncate().distance(*c2))
.unwrap()
});
if let Some(focused) = &focused_type.0 {
features.retain(|(_, t)| **t == *focused);
}
let mut target: Option<&((f32, f32), &ExplorationType)> = None;
let mut target = None;
if actions.just_pressed(&ExplorationAction::FocusNext) {
if let Some(exploring) = exploring {
target = features.iter().find(|(c, _)| *c > **exploring);
target = features.iter().find(|(c, _)| {
transform.translation().truncate().distance(*c)
> transform.translation().truncate().distance(**exploring)
});
if target.is_none() {
target = features.first();
}
@ -159,7 +178,10 @@ where
} else if actions.just_pressed(&ExplorationAction::FocusPrev) {
if let Some(exploring) = exploring {
features.reverse();
target = features.iter().find(|(c, _)| *c < **exploring);
target = features.iter().find(|(c, _)| {
transform.translation().truncate().distance(*c)
< transform.translation().truncate().distance(**exploring)
});
if target.is_none() {
target = features.first();
}
@ -170,7 +192,7 @@ where
if let Some((coordinates, _)) = target {
commands
.entity(entity)
.insert(Exploring(coordinates.trunc()));
.insert(Exploring(*coordinates));
}
}
Ok(())
@ -212,7 +234,7 @@ fn exploration_focus<MapData>(
(
Entity,
&ActionState<ExplorationAction>,
&Transform,
&GlobalTransform,
Option<&Exploring>,
),
With<Player>,
@ -221,22 +243,20 @@ fn exploration_focus<MapData>(
MapData: 'static + Clone + Default + Send + Sync,
{
for (entity, actions, transform, exploring) in &explorers {
let coordinates = transform.translation;
let mut exploring = if let Some(exploring) = exploring {
**exploring
} else {
let floor = coordinates.floor();
(floor.x, floor.y)
transform.translation().truncate()
};
let orig = exploring;
if actions.just_pressed(&ExplorationAction::Forward) {
exploring.1 += 1.;
exploring.y += 1.;
} else if actions.just_pressed(&ExplorationAction::Backward) {
exploring.1 -= 1.;
exploring.y -= 1.;
} else if actions.just_pressed(&ExplorationAction::Left) {
exploring.0 -= 1.;
exploring.x -= 1.;
} else if actions.just_pressed(&ExplorationAction::Right) {
exploring.0 += 1.;
exploring.x += 1.;
}
let dimensions = if let Ok(map) = map.get_single() {
Some((map.width as f32, map.height as f32))
@ -244,11 +264,11 @@ fn exploration_focus<MapData>(
None
};
if let Some((width, height)) = dimensions {
if exploring.0 >= width || exploring.1 >= height {
if exploring.x >= width || exploring.y >= height {
return;
}
}
if orig != exploring && exploring.0 >= 0. && exploring.1 >= 0. {
if orig != exploring && exploring.x >= 0. && exploring.y >= 0. {
commands.entity(entity).insert(Exploring(exploring));
}
}
@ -269,7 +289,7 @@ fn navigate_to_explored<MapData>(
if actions.just_pressed(&ExplorationAction::NavigateTo) && known {
commands
.entity(entity)
.insert(Destination((point.x_i32(), point.y_i32())));
.insert(Destination(point.as_ivec2()));
}
}
}
@ -285,7 +305,7 @@ fn exploration_changed_announcement<ExplorationType, MapData>(
names: Query<&Name>,
types: Query<&ExplorationType>,
mappables: Query<&Mappable>,
rapier_context: Res<RapierContext>,
spatial_query: SpatialQuery,
) -> Result<(), Box<dyn Error>>
where
ExplorationType: Component + Copy + Display,
@ -294,14 +314,14 @@ where
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
let coordinates = coordinates.trunc();
let point = **exploring;
let shape = Collider::cuboid(0.5 - f32::EPSILON, 0.5 - f32::EPSILON);
let shape = Collider::rectangle(1. - f32::EPSILON, 1. - f32::EPSILON);
let (known, idx) = if let Ok((map, revealed_tiles)) = map.get_single() {
let idx = point.to_index(map.width);
(revealed_tiles[idx], Some(idx))
} else {
(false, None)
};
let visible = viewshed.is_point_visible(exploring);
let visible = viewshed.is_point_visible(exploring.as_ivec2());
let fog_of_war = !visible && known;
let description: String = if known || visible {
let mut tokens: Vec<String> = vec![];
@ -309,20 +329,22 @@ where
commands.entity(entity).remove::<ExplorationFocused>();
}
let exploring = Vec2::new(exploring.x(), exploring.y());
rapier_context.intersections_with_shape(
spatial_query.shape_intersections_callback(
&shape,
exploring,
0.,
&shape,
QueryFilter::new().predicate(&|v| explorable.get(v).is_ok()),
&default(),
|entity| {
commands.entity(entity).insert(ExplorationFocused);
if visible || mappables.get(entity).is_ok() {
if let Ok(name) = names.get(entity) {
tokens.push(name.to_string());
}
if tokens.is_empty() {
if let Ok(t) = types.get(entity) {
tokens.push(format!("{t}"));
if explorable.contains(entity) {
commands.entity(entity).insert(ExplorationFocused);
if visible || mappables.get(entity).is_ok() {
if let Ok(name) = names.get(entity) {
tokens.push(name.to_string());
}
if tokens.is_empty() {
if let Ok(t) = types.get(entity) {
tokens.push(format!("{t}"));
}
}
}
}

View File

@ -2,8 +2,8 @@
#![allow(clippy::too_many_arguments)]
#![allow(clippy::type_complexity)]
pub use avian2d;
pub use bevy;
pub use bevy_rapier2d;
pub use bevy_synthizer;
pub use bevy_tts;
pub use coord_2d;

View File

@ -1,22 +1,20 @@
use std::marker::PhantomData;
use avian2d::prelude::*;
use bevy::prelude::*;
use bevy_rapier2d::{
na::{Isometry2, Vector2},
prelude::*,
};
pub use here_be_dragons::Map as MapgenMap;
use here_be_dragons::{geometry::Rect as MRect, MapFilter, Tile};
use maze_generator::{prelude::*, recursive_backtracking::RbGenerator};
use rand::prelude::StdRng;
use crate::{
core::{Area, PointLike},
core::{Obstacle, PointLike, Zone},
exploration::Mappable,
visibility::Visible,
};
#[derive(Component, Clone, Default, Deref, DerefMut)]
#[require(Transform, SpawnColliders, SpawnPortals)]
pub struct Map<D: 'static + Clone + Default + Send + Sync>(pub MapgenMap<D>);
impl<D: Clone + Default + Send + Sync> From<MapgenMap<D>> for Map<D> {
@ -27,10 +25,7 @@ impl<D: Clone + Default + Send + Sync> From<MapgenMap<D>> for Map<D> {
#[derive(Component, Clone, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct MapObstruction;
#[derive(Component, Clone, Debug, Default, Reflect)]
#[reflect(Component)]
#[require(Transform, Mappable)]
pub struct Portal;
#[derive(Component, Clone, Debug, Deref, DerefMut, Reflect)]
@ -43,12 +38,6 @@ impl Default for SpawnColliders {
}
}
impl From<bool> for SpawnColliders {
fn from(v: bool) -> Self {
Self(v)
}
}
#[derive(Component, Clone, Debug, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct SpawnPortals(pub bool);
@ -59,10 +48,6 @@ impl Default for SpawnPortals {
}
}
#[derive(Default, Component, Clone, Debug, Reflect)]
#[reflect(Component)]
pub struct Zone;
pub trait ITileType {
fn blocks_motion(&self) -> bool;
fn blocks_visibility(&self) -> bool;
@ -78,89 +63,6 @@ impl ITileType for Tile {
}
}
#[derive(Bundle, Default)]
pub struct PortalBundle {
pub portal: Portal,
pub mappable: Mappable,
pub transform: TransformBundle,
}
#[derive(Bundle, Clone, Default)]
pub struct MapBundle<D: 'static + Clone + Default + Send + Sync> {
pub map: Map<D>,
pub spawn_colliders: SpawnColliders,
pub spawn_portals: SpawnPortals,
pub transform: TransformBundle,
}
#[derive(Bundle, Clone, Debug)]
pub struct TileBundle {
pub transform: TransformBundle,
pub collider: Collider,
pub rigid_body: RigidBody,
pub active_collision_types: ActiveCollisionTypes,
pub map_obstruction: MapObstruction,
}
impl Default for TileBundle {
fn default() -> Self {
Self {
transform: default(),
collider: Collider::cuboid(0.5, 0.5),
rigid_body: RigidBody::Fixed,
active_collision_types: ActiveCollisionTypes::default()
| ActiveCollisionTypes::KINEMATIC_STATIC
| ActiveCollisionTypes::DYNAMIC_STATIC,
map_obstruction: MapObstruction,
}
}
}
impl TileBundle {
pub fn new(x: i32, y: i32) -> Self {
Self {
transform: Transform::from_xyz(x as f32 + 0.5, y as f32 + 0.5, 0.).into(),
..default()
}
}
}
#[derive(Bundle, Clone, Debug)]
pub struct ZoneBundle {
pub collider: Collider,
pub transform: TransformBundle,
pub area: Area,
pub zone: Zone,
pub sensor: Sensor,
pub active_events: ActiveEvents,
}
impl ZoneBundle {
fn new(collider: Collider, position: (f32, f32)) -> Self {
let point = Isometry2::new(Vector2::new(position.0, position.1), 0.);
let aabb = collider.raw.compute_aabb(&point);
Self {
collider,
area: Area(aabb),
transform: Transform::from_translation(Vec3::new(position.0, position.1, 0.)).into(),
zone: default(),
sensor: default(),
active_events: ActiveEvents::COLLISION_EVENTS,
}
}
}
impl From<&MRect> for ZoneBundle {
fn from(rect: &MRect) -> Self {
let collider = Collider::cuboid(
rect.width() as f32 / 2. + 0.5,
rect.height() as f32 / 2. + 0.5,
);
let position = (rect.center().x(), rect.center().y());
Self::new(collider, position)
}
}
pub struct GridBuilder {
width_in_rooms: usize,
height_in_rooms: usize,
@ -196,21 +98,24 @@ impl<D: Clone + Default> MapFilter<D> for GridBuilder {
let half_height = self.room_height / 2;
for y in 0..self.height_in_rooms {
for x in 0..self.width_in_rooms {
// println!("({x}, {y}): ");
let x_offset = x * (self.room_width + 1);
let y_offset = total_height - (y + 1) * (self.room_height + 1) - 1;
// println!("Offsets: {x_offset}, {y_offset}");
let room = MRect::new_i32(
x_offset as i32 + 1,
y_offset as i32 + 1,
self.room_width as i32,
self.room_height as i32,
);
// println!("{room:?}");
map.add_room(room);
let coords = maze_generator::prelude::Coordinates::new(x as i32, y as i32);
if let Some(field) = maze.get_field(&coords) {
use maze_generator::prelude::Direction::*;
if field.has_passage(&North) {
let x = x_offset + half_width;
let y = y_offset + self.room_height;
let y = y_offset + self.room_height + 1;
map.set_tile(x, y, Tile::floor());
}
if field.has_passage(&South) {
@ -219,7 +124,7 @@ impl<D: Clone + Default> MapFilter<D> for GridBuilder {
map.set_tile(x, y, Tile::floor());
}
if field.has_passage(&East) {
let x = x_offset + self.room_width;
let x = x_offset + self.room_width + 1;
let y = y_offset + half_height;
map.set_tile(x, y, Tile::floor());
}
@ -255,18 +160,27 @@ fn spawn_colliders<D: 'static + Clone + Default + Send + Sync>(
for x in 0..map.width {
if let Some(tile) = map.at(x, y) {
if tile.blocks_motion() {
let id = commands.spawn(TileBundle::new(x as i32, y as i32)).id();
let id = commands
.spawn((
Obstacle,
Transform::from_xyz(x as f32 + 0.5, y as f32 + 0.5, 0.),
))
.id();
if tile.blocks_visibility() {
commands.entity(id).insert(Visible::opaque());
}
commands.entity(map_entity).push_children(&[id]);
commands.entity(map_entity).add_children(&[id]);
}
}
}
}
for room in &map.rooms {
commands.entity(map_entity).with_children(|parent| {
parent.spawn(ZoneBundle::from(room));
parent.spawn((
Zone,
Transform::from_xyz(room.center().x as f32, room.center().y as f32, 0.),
Collider::rectangle(room.width() as f32 + 1., room.height() as f32 + 1.),
));
});
}
}
@ -312,10 +226,7 @@ fn spawn_portals<D: 'static + Clone + Default + Send + Sync>(
}
for (x, y) in portals {
commands.entity(map_entity).with_children(|parent| {
parent.spawn(PortalBundle {
transform: Transform::from_translation(Vec3::new(x, y, 0.)).into(),
..default()
});
parent.spawn((Portal, Transform::from_xyz(x, y, 0.)));
});
}
}
@ -332,7 +243,7 @@ fn spawn_portal_colliders<D: 'static + Clone + Default + Send + Sync>(
for portal_entity in &portals {
commands
.entity(portal_entity)
.insert((Collider::cuboid(0.5, 0.5), Sensor));
.insert((Collider::rectangle(1., 1.), Sensor));
}
commands.entity(entity).remove::<SpawnColliders>();
}

View File

@ -1,12 +1,14 @@
#![allow(clippy::map_entry)]
use std::{collections::HashMap, error::Error, f32::consts::PI, fmt::Debug, hash::Hash};
use avian2d::prelude::*;
use bevy::{math::CompassQuadrant, prelude::*};
use bevy_rapier2d::prelude::*;
use bevy_tts::Tts;
use leafwing_input_manager::prelude::*;
use crate::{
core::{Area, CardinalDirection, GlobalTransformExt, Player, TransformExt},
core::{CardinalDirection, GlobalTransformExt, Player, Zone},
error::error_handler,
log::Log,
utils::target_and_other,
@ -133,10 +135,8 @@ fn snap(
snap_timers.insert(entity, SnapTimer::default());
transform.rotate(Quat::from_rotation_z(PI));
} else if actions.just_pressed(&NavigationAction::SnapCardinal) {
println!("Direction: {direction:?}");
let yaw: Rot2 = direction.into();
let yaw = yaw.as_radians();
println!("Yaw: {yaw}");
let rotation = Quat::from_rotation_z(yaw);
if transform.rotation != rotation {
transform.rotation = rotation;
@ -153,19 +153,22 @@ fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
}
fn controls(
rapier_context: Res<RapierContext>,
mut commands: Commands,
spatial_query: SpatialQuery,
time: Res<Time>,
snap_timers: Res<SnapTimers>,
sensors: Query<Entity, With<Sensor>>,
mut query: Query<(
Entity,
&mut ActionState<NavigationAction>,
&mut Velocity,
&mut LinearVelocity,
&Speed,
Option<&RotationSpeed>,
Option<&BackwardMovementFactor>,
Option<&ForwardMovementFactor>,
Option<&StrafeMovementFactor>,
&mut Transform,
&GlobalTransform,
&Collider,
)>,
) {
@ -179,6 +182,7 @@ fn controls(
forward_movement_factor,
strafe_movement_factor,
mut transform,
global_transform,
collider,
) in &mut query
{
@ -211,31 +215,34 @@ fn controls(
let mut speed = **speed;
speed *= movement_factor;
let move_velocity = direction * speed;
// println!("{entity:?}: SetLinearVelocity: {velocity:?}");
actions.set_axis_pair(&NavigationAction::SetLinearVelocity, move_velocity);
}
if velocity.linvel != actions.axis_pair(&NavigationAction::SetLinearVelocity) {
velocity.linvel = actions.axis_pair(&NavigationAction::SetLinearVelocity);
if velocity.0 != actions.axis_pair(&NavigationAction::SetLinearVelocity) {
**velocity = actions.axis_pair(&NavigationAction::SetLinearVelocity);
}
if actions.axis_pair(&NavigationAction::Translate) != Vec2::ZERO {
let pair = actions.axis_pair(&NavigationAction::Translate);
if rapier_context
.cast_shape(
transform.translation.truncate(),
transform.yaw().as_radians(),
pair,
collider,
ShapeCastOptions {
max_time_of_impact: 1.,
..default()
},
QueryFilter::new()
.exclude_sensors()
.exclude_collider(entity),
)
.is_none()
{
let dir = Dir2::new_unchecked(pair.normalize());
let hit = spatial_query.cast_shape(
collider,
global_transform.translation().truncate(),
global_transform.yaw().as_radians(),
dir,
&ShapeCastConfig {
max_distance: pair.length(),
ignore_origin_penetration: true,
..default()
},
&SpatialQueryFilter::from_excluded_entities(&sensors),
);
if hit.is_none() {
transform.translation += pair.extend(0.);
} else {
// println!("Can't translate: {:?}", pair.extend(0.));
// println!("Delta: {}", pair.length());
if let Some(hit) = hit {
commands.entity(hit.entity).log_components();
}
}
actions.set_axis_pair(&NavigationAction::Translate, Vec2::ZERO);
}
@ -247,10 +254,8 @@ fn controls(
}
}
if actions.value(&NavigationAction::SetAngularVelocity) != 0. {
// velocity.angvel =
// actions.value(&NavigationAction::SetAngularVelocity);
transform.rotation *= Quat::from_rotation_z(
actions.value(&NavigationAction::SetAngularVelocity) * time.delta_seconds(),
actions.value(&NavigationAction::SetAngularVelocity) * time.delta_secs(),
);
}
}
@ -299,18 +304,18 @@ fn speak_direction(
Ok(())
}
fn add_speed(mut commands: Commands, query: Query<Entity, (Added<Speed>, Without<Velocity>)>) {
fn add_speed(
mut commands: Commands,
query: Query<Entity, (Added<Speed>, Without<LinearVelocity>)>,
) {
for entity in &query {
commands.entity(entity).insert(Velocity {
linvel: Vec2::ZERO,
..default()
});
commands.entity(entity).insert(LinearVelocity::default());
}
}
fn log_area_descriptions(
mut events: EventReader<CollisionEvent>,
areas: Query<(&Area, Option<&Name>)>,
fn log_zone_descriptions(
mut events: EventReader<Collision>,
zones: Query<(&ColliderAabb, Option<&Name>), With<Zone>>,
players: Query<&Player>,
config: Res<NavigationPlugin>,
mut log: Query<&mut Log>,
@ -318,19 +323,21 @@ fn log_area_descriptions(
if !config.log_area_descriptions {
return;
}
for event in events.read() {
let (entity1, entity2, started) = match event {
CollisionEvent::Started(collider1, collider2, _) => (collider1, collider2, true),
CollisionEvent::Stopped(collider1, collider2, _) => (collider1, collider2, false),
};
if let Some((area, other)) = target_and_other(*entity1, *entity2, &|v| areas.get(v).is_ok())
for Collision(contacts) in events.read() {
let started = contacts.during_current_frame && !contacts.during_previous_frame;
let stopped = !contacts.during_current_frame && contacts.during_previous_frame;
if !started && !stopped {
continue;
}
if let Some((area, other)) =
target_and_other(contacts.entity1, contacts.entity2, &|v| zones.contains(v))
{
if players.get(other).is_ok() {
if let Ok((aabb, area_name)) = areas.get(area) {
if players.contains(other) {
if let Ok((aabb, area_name)) = zones.get(area) {
let name = if let Some(name) = area_name {
Some(name.to_string())
} else if config.describe_undescribed_areas {
Some(format!("{}-by-{} area", aabb.extents().x, aabb.extents().y))
Some(format!("{}-by-{} area", aabb.size().x, aabb.size().y))
} else {
None
};
@ -377,17 +384,12 @@ impl Plugin for NavigationPlugin {
.register_type::<RotationSpeed>()
.register_type::<Speed>()
.add_plugins(InputManagerPlugin::<NavigationAction>::default())
.add_systems(PreUpdate, (update_direction, add_speed))
.add_systems(
Update,
(snap, controls)
.chain()
.in_set(Movement),
)
.add_systems(FixedPreUpdate, (update_direction, add_speed))
.add_systems(FixedUpdate, (snap, controls).chain().in_set(Movement))
.add_systems(
FixedUpdate,
(tick_snap_timers, speak_direction.pipe(error_handler)),
)
.add_systems(PostUpdate, (remove_direction, log_area_descriptions));
.add_systems(PostUpdate, (remove_direction, log_zone_descriptions));
}
}

View File

@ -1,19 +1,11 @@
use bevy::{
prelude::*,
tasks::{futures_lite::future, prelude::*, Task},
utils::HashMap,
};
use bevy_rapier2d::{
na::{Isometry2, Vector2},
prelude::*,
rapier::prelude::{ColliderHandle, ColliderSet, QueryPipeline, RigidBodySet},
};
use avian2d::prelude::*;
use bevy::{prelude::*, utils::HashMap};
use leafwing_input_manager::{plugin::InputManagerSystem, prelude::*};
use pathfinding::prelude::*;
use crate::{
core::{PointLike, TransformExt},
map::{Map, MapObstruction},
core::{GlobalTransformExt, Obstacle},
map::Map,
navigation::{NavigationAction, RotationSpeed, Speed},
};
@ -26,15 +18,9 @@ impl Actionlike for NegotiatePathAction {
}
}
#[derive(Component, Debug, Deref, DerefMut)]
struct Calculating(Task<Option<Path>>);
#[derive(Component, Clone, Copy, Debug, Default, Deref, DerefMut, Eq, Hash, PartialEq, Reflect)]
#[reflect(Component)]
pub struct Destination(pub (i32, i32));
impl_pointlike_for_tuple_component!(Destination);
impl_pointlike_for_tuple_component!(&Destination);
pub struct Destination(pub IVec2);
#[derive(Component, Clone, Debug, Default, Reflect)]
#[reflect(Component)]
@ -42,11 +28,11 @@ pub struct NoPath;
#[derive(Component, Clone, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct Path(pub Vec<(i32, i32)>);
pub struct Path(pub Vec<IVec2>);
#[derive(Component, Clone, Debug, Default, Reflect, Deref, DerefMut)]
#[reflect(Component)]
pub struct CostMap(pub HashMap<(i32, i32), f32>);
pub struct CostMap(pub HashMap<IVec2, f32>);
#[derive(Bundle, Deref, DerefMut)]
pub struct PathfindingControlsBundle(pub ActionState<NegotiatePathAction>);
@ -60,211 +46,141 @@ impl Default for PathfindingControlsBundle {
}
pub fn find_path<D: 'static + Clone + Default + Send + Sync>(
start: &dyn PointLike,
destination: &dyn PointLike,
start: IVec2,
destination: IVec2,
map: &Map<D>,
cost_map: &Option<CostMap>,
) -> Option<(Vec<(i32, i32)>, u32)> {
) -> Option<(Vec<IVec2>, u32)> {
astar(
&start.into(),
&start,
|p| {
let mut successors: Vec<((i32, i32), u32)> = vec![];
if p.0 >= 0 && p.1 >= 0 {
if let Some(tile) = map.at(p.0 as usize, p.1 as usize) {
let mut successors: Vec<(IVec2, u32)> = vec![];
if p.x >= 0 && p.y >= 0 {
if let Some(tile) = map.at(p.x as usize, p.y as usize) {
if tile.is_walkable() {
for tile in map.get_available_exits(p.0 as usize, p.1 as usize) {
for tile in map.get_available_exits(p.x as usize, p.y as usize) {
let mut cost = tile.2 * 100.;
if let Some(cost_map) = cost_map {
if let Some(modifier) =
cost_map.get(&(tile.0 as i32, tile.1 as i32))
{
if let Some(modifier) = cost_map.get(p) {
cost *= modifier;
}
}
successors.push(((tile.0 as i32, tile.1 as i32), cost as u32));
successors
.push((IVec2::new(tile.0 as i32, tile.1 as i32), cost as u32));
}
}
}
}
successors
},
|p| (p.distance_squared(destination) * 100.) as u32,
|p| *p == destination.into(),
|p| (p.distance_squared(destination) * 100) as u32,
|p| *p == destination,
)
}
fn find_path_for_shape(
initiator: ColliderHandle,
start: Transform,
destination: Destination,
cost_map: &Option<CostMap>,
query_pipeline: QueryPipeline,
collider_set: ColliderSet,
rigid_body_set: RigidBodySet,
shape: Collider,
) -> Option<Path> {
let path = astar(
&start.i32(),
|p| {
let mut successors: Vec<((i32, i32), u32)> = vec![];
let x = p.0;
let y = p.1;
let exits = vec![
((x - 1, y), 1.),
((x + 1, y), 1.),
((x, y - 1), 1.),
((x, y + 1), 1.),
((x - 1, y - 1), 1.5),
((x + 1, y - 1), 1.5),
((x - 1, y + 1), 1.5),
((x + 1, y + 1), 1.5),
];
for exit in &exits {
let mut should_push = true;
let dest = Isometry2::new(Vector2::new(exit.0 .0 as f32, exit.0 .1 as f32), 0.);
if query_pipeline
.intersection_with_shape(
&rigid_body_set,
&collider_set,
&dest,
&*shape.raw,
bevy_rapier2d::rapier::pipeline::QueryFilter::new()
.exclude_sensors()
.exclude_collider(initiator),
)
.is_some()
{
should_push = false;
}
if should_push {
let mut cost = exit.1 * 100.;
if let Some(cost_map) = cost_map {
if let Some(modifier) = cost_map.get(&(exit.0 .0, exit.0 .1)) {
cost *= modifier;
}
}
successors.push((exit.0, cost as u32));
}
}
successors
},
|p| (p.distance_squared(&destination) * 100.) as u32,
|p| *p == destination.i32(),
);
if let Some(path) = path {
Some(Path(path.0))
} else {
None
}
}
fn calculate_path(
mut commands: Commands,
rapier_context: Res<RapierContext>,
obstructions: Query<&RapierColliderHandle, With<MapObstruction>>,
query: Query<
spatial_query: SpatialQuery,
mut query: Query<
(
Entity,
&RapierColliderHandle,
&Destination,
&Transform,
&GlobalTransform,
&Collider,
Option<&CostMap>,
Option<&mut ActionState<NegotiatePathAction>>,
),
Changed<Destination>,
>,
obstacles: Query<Entity, With<Obstacle>>,
sensors: Query<Entity, With<Sensor>>,
) {
for (entity, handle, destination, coordinates, shape, cost_map) in &query {
for (entity, destination, transform, collider, cost_map, actions) in &mut query {
trace!("{entity}: destination: {destination:?}");
if coordinates.i32() == **destination {
trace!("{entity}: remove1");
commands
.entity(entity)
.remove::<Path>()
.remove::<NoPath>()
.remove::<Calculating>()
.remove::<Destination>();
commands.entity(entity).remove::<Path>().remove::<NoPath>();
if transform.translation().truncate().as_ivec2() == **destination {
commands.entity(entity).remove::<Destination>();
continue;
}
trace!(
"{entity:?}: Calculating path from {:?} to {destination:?}",
coordinates.translation.truncate().i32()
);
let coordinates_clone = *coordinates;
let destination_clone = *destination;
let query_pipeline = rapier_context.query_pipeline.clone();
let cost_map_clone = cost_map.cloned();
let handle_clone = *handle;
let mut collider_set = rapier_context.colliders.clone();
let mut to_remove = vec![handle.0];
for handle in collider_set.iter() {
if !obstructions.iter().map(|v| v.0).any(|x| x == handle.0) {
to_remove.push(handle.0);
}
}
let mut bodies = rapier_context.bodies.clone();
if !to_remove.is_empty() {
let mut islands = rapier_context.islands.clone();
for handle in to_remove {
collider_set.remove(handle, &mut islands, &mut bodies, false);
}
}
let shape_clone = (*shape).clone();
trace!(
"{entity:?}: path: calculating from {:?} to {destination:?}",
coordinates.i32(),
);
let pool = AsyncComputeTaskPool::get();
let task = pool.spawn(async move {
find_path_for_shape(
handle_clone.0,
coordinates_clone,
destination_clone,
&cost_map_clone,
query_pipeline,
collider_set,
bodies,
shape_clone,
)
});
trace!("{entity}: remove2");
commands
.entity(entity)
.insert(Calculating(task))
.remove::<Path>()
.remove::<NoPath>();
}
}
fn poll_tasks(
mut commands: Commands,
mut query: Query<(
Entity,
&mut Calculating,
&Transform,
&Destination,
Option<&mut ActionState<NegotiatePathAction>>,
)>,
) {
for (entity, mut calculating, transform, destination, actions) in &mut query {
if let Some(result) = future::block_on(future::poll_once(&mut **calculating)) {
if let Some(path) = result {
trace!("{entity:?}: Path: {path:?}");
commands.entity(entity).insert(path);
} else {
trace!(
"{entity:?}: path: no path from {:?} to {:?}",
transform.translation.truncate().i32(),
**destination
);
commands.entity(entity).insert(NoPath);
if let Some(mut actions) = actions {
trace!("{entity:?}: Disabling and resetting because no path");
actions.disable();
actions.reset_all();
let path = astar(
&transform.translation().truncate().as_ivec2(),
|p| {
let mut start = Vec2::new(p.x as f32, p.y as f32);
if start.x >= 0. {
start.x += 0.5;
} else {
start.x -= 0.5;
}
if start.y >= 0. {
start.y += 0.5;
} else {
start.y -= 0.5;
}
let mut successors: Vec<(IVec2, u32)> = vec![];
let x = p.x;
let y = p.y;
let exits = vec![
(IVec2::new(x - 1, y), 1.),
(IVec2::new(x + 1, y), 1.),
(IVec2::new(x, y - 1), 1.),
(IVec2::new(x, y + 1), 1.),
(IVec2::new(x - 1, y - 1), 1.5),
(IVec2::new(x + 1, y - 1), 1.5),
(IVec2::new(x - 1, y + 1), 1.5),
(IVec2::new(x + 1, y + 1), 1.5),
];
for exit in &exits {
let mut check = exit.0.as_vec2();
if check.x >= 0. {
check.x += 0.5;
} else {
check.x -= 0.5;
}
if check.y >= 0. {
check.y += 0.5;
} else {
check.y -= 0.5;
}
let dir = (check - start).normalize();
let dir = Dir2::new_unchecked(dir);
let delta = (check - start).length();
let hits = spatial_query.cast_shape_predicate(
collider,
start,
transform.yaw().as_radians(),
dir,
&ShapeCastConfig {
max_distance: delta,
ignore_origin_penetration: true,
..default()
},
&SpatialQueryFilter::from_excluded_entities(&sensors),
&|entity| obstacles.contains(entity),
);
if hits.is_none() {
let mut cost = exit.1 * 100.;
if let Some(cost_map) = cost_map {
if let Some(modifier) = cost_map.get(&exit.0) {
cost *= modifier;
}
}
successors.push((exit.0, cost as u32));
}
}
successors
},
|p| (p.distance_squared(**destination) * 100) as u32,
|p| *p == **destination,
);
if let Some(path) = path {
commands.entity(entity).insert(Path(path.0));
} else {
commands.entity(entity).insert(NoPath);
if let Some(mut actions) = actions {
trace!("{entity:?}: Disabling and resetting because no path");
actions.disable();
actions.reset_all();
}
commands.entity(entity).remove::<Calculating>();
}
}
}
@ -272,10 +188,7 @@ fn poll_tasks(
fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Destination>) {
for entity in removed.read() {
if let Some(mut commands) = commands.get_entity(entity) {
commands
.remove::<Calculating>()
.remove::<Path>()
.remove::<NoPath>();
commands.remove::<Path>().remove::<NoPath>();
}
}
}
@ -283,20 +196,22 @@ fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Des
fn negotiate_path(
mut commands: Commands,
time: Res<Time>,
physics_config: Res<RapierConfiguration>,
physics_time: Res<Time<Physics>>,
spatial_query: SpatialQuery,
mut query: Query<(
Entity,
Option<&mut ActionState<NegotiatePathAction>>,
&mut ActionState<NavigationAction>,
&mut Path,
&mut Transform,
&GlobalTransform,
&Collider,
&Speed,
Option<&RotationSpeed>,
)>,
rapier_context: Res<RapierContext>,
sensors: Query<Entity, With<Sensor>>,
) {
if !physics_config.physics_pipeline_active || !physics_config.query_pipeline_active {
if physics_time.is_paused() {
return;
}
for (
@ -305,25 +220,21 @@ fn negotiate_path(
mut navigation_actions,
mut path,
mut transform,
global_transform,
collider,
speed,
rotation_speed,
) in &mut query
{
trace!("{entity:?}: negotiating path");
let start_i32 = transform.translation.truncate().i32();
trace!(
"{entity:?}: start pathfinding from {start_i32:?} to {:?}: at {:?}",
path.last(),
transform.translation.truncate().i32()
);
if path.len() > 0 && path[0] == start_i32 {
let start = global_transform.translation().truncate().as_ivec2();
if path.len() > 0 && path[0] == start {
trace!("At start, removing");
path.remove(0);
}
if let Some(next) = path.first() {
let start = transform.translation.truncate();
let mut next = Vec2::new(next.0 as f32, next.1 as f32);
let start = global_transform.translation().truncate();
let mut next = next.as_vec2();
if next.x >= 0. {
next.x += 0.5;
} else {
@ -334,37 +245,30 @@ fn negotiate_path(
} else {
next.y -= 0.5;
}
let mut direction = next - start;
direction = direction.normalize();
direction *= **speed;
direction *= time.delta_seconds();
trace!(
"{entity:?}: Direction: {direction:?}, Distance: {}",
(next - start).length()
let direction = (next - start).normalize();
let delta = time.delta_secs() * **speed;
let dir = Dir2::new_unchecked(direction);
let hit = spatial_query.cast_shape(
collider,
start,
global_transform.yaw().as_radians(),
dir,
&ShapeCastConfig {
max_distance: delta,
ignore_origin_penetration: true,
..default()
},
&SpatialQueryFilter::from_excluded_entities(&sensors),
);
if rapier_context
.cast_shape(
start,
transform.yaw().as_radians(),
direction,
collider,
ShapeCastOptions {
max_time_of_impact: 1.,
..default()
},
QueryFilter::new()
.exclude_sensors()
.exclude_collider(entity),
)
.is_some()
{
trace!("{entity:?} is stuck");
if hit.is_some() {
// println!("{entity} is stuck");
// TODO: Remove when we have an actual character controller.
next.x = next.x.trunc();
next.y = next.y.trunc();
transform.translation = next.extend(0.);
} else {
navigation_actions.set_axis_pair(&NavigationAction::Translate, direction);
// println!("Translating: {:?}", direction * delta);
navigation_actions.set_axis_pair(&NavigationAction::Translate, direction * delta);
}
if rotation_speed.is_some() {
let angle = direction.y.atan2(direction.x);
@ -404,12 +308,11 @@ fn actions(
} else {
let pair = actions.axis_pair(&NegotiatePathAction);
trace!("{entity:?}: Negotiating path to {pair:?}");
let dest = Destination(pair.xy().i32());
let dest = Destination(pair.as_ivec2());
if let Some(mut current_dest) = destination {
trace!("Got a destination");
if *current_dest != dest {
trace
!("{entity:?}: New destination {dest:?} differs from {current_dest:?}, zeroing velocity");
trace!("{entity:?}: New destination {dest:?} differs from {current_dest:?}, zeroing velocity");
navigation_action
.set_axis_pair(&NavigationAction::SetLinearVelocity, Vec2::ZERO);
*current_dest = dest;
@ -427,15 +330,14 @@ pub struct PathfindingPlugin;
impl Plugin for PathfindingPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(InputManagerPlugin::<NegotiatePathAction>::default())
app.add_plugins((InputManagerPlugin::<NegotiatePathAction>::default(),))
.register_type::<Destination>()
.register_type::<NoPath>()
.register_type::<Path>()
.register_type::<CostMap>()
.add_systems(PreUpdate, (poll_tasks, negotiate_path).chain())
.add_systems(
PreUpdate,
(actions, calculate_path)
FixedPreUpdate,
(actions, calculate_path, negotiate_path)
.chain()
.after(InputManagerSystem::Tick),
)

View File

@ -22,7 +22,7 @@ pub use volumetric::Volumetric;
pub struct SoundPlugins<'a, S>(std::marker::PhantomData<&'a S>);
impl<'a, S> Default for SoundPlugins<'a, S> {
impl<S> Default for SoundPlugins<'_, S> {
fn default() -> Self {
Self(std::marker::PhantomData)
}

View File

@ -1,5 +1,5 @@
use avian2d::{parry::query::ClosestPoints, prelude::*};
use bevy::{prelude::*, transform::TransformSystem};
use bevy_rapier2d::{parry::query::ClosestPoints, prelude::*};
use bevy_synthizer::{Listener, Sound};
use crate::core::GlobalTransformExt;
@ -39,12 +39,9 @@ fn update(
);
commands
.entity(sound_entity)
.insert(TransformBundle::from_transform(
Transform::from_translation(sound_translation),
));
.insert(Transform::from_translation(sound_translation));
}
} else if closest == ClosestPoints::Intersecting && sound_transform.is_some() {
println!("Clearing volumetric");
commands
.entity(sound_entity)
.remove::<Transform>()
@ -61,7 +58,7 @@ fn removed(
) {
for entity in removed.read() {
if transforms.get(entity).is_ok() {
commands.entity(entity).insert(TransformBundle::default());
commands.entity(entity).insert(Transform::default());
}
}
}

View File

@ -3,14 +3,12 @@ use std::{
marker::PhantomData,
};
use avian2d::prelude::*;
use bevy::prelude::*;
use bevy_rapier2d::na::Isometry2;
use coord_2d::{Coord, Size};
use shadowcast::{vision_distance, Context, InputGrid};
use crate::{
bevy_rapier2d::prelude::*,
core::{GlobalTransformExt, Player, PointLike},
log::Log,
map::{Map, MapPlugin},
@ -25,9 +23,10 @@ pub struct DontLogWhenVisible;
pub struct RevealedTiles(pub Vec<bool>);
#[derive(Component, Clone, Debug, Eq, PartialEq)]
#[require(VisibleEntities)]
pub struct Viewshed {
pub range: u32,
pub visible_points: HashSet<(i32, i32)>,
pub visible_points: HashSet<IVec2>,
}
impl Default for Viewshed {
@ -40,8 +39,8 @@ impl Default for Viewshed {
}
impl Viewshed {
pub fn is_point_visible(&self, point: &dyn PointLike) -> bool {
self.visible_points.contains(&point.into())
pub fn is_point_visible(&self, point: IVec2) -> bool {
self.visible_points.contains(&point)
}
fn update(
@ -52,7 +51,7 @@ impl Viewshed {
start: &Vec2,
opacity_map: &OpacityMap,
sensors: &Query<&Sensor>,
rapier_context: &RapierContext,
spatial_query: &SpatialQuery,
) {
let mut context: Context<u8> = Context::default();
let vision_distance = vision_distance::Circle::new(self.range);
@ -60,7 +59,12 @@ impl Viewshed {
(start.x.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(
*viewer_entity,
start.as_ivec2(),
self.range,
opacity_map.clone(),
);
let mut new_visible = HashSet::new();
let mut new_visible_entities = HashSet::new();
// println!("Start: {viewer_entity}");
@ -71,34 +75,34 @@ impl Viewshed {
vision_distance,
u8::MAX,
|coord, _directions, _visibility| {
new_visible.insert((coord.x, coord.y));
let coord = IVec2::new(coord.x, coord.y);
new_visible.insert(coord);
// println!("Checking {coord:?}");
if let Some((_, entities)) = opacity_map.get(&coord) {
for e in entities {
if entities.len() == 1 || sensors.contains(*e) {
// println!("Spotted {e:?}");
new_visible_entities.insert(*e);
} else {
let mut should_push = true;
let should_push = std::cell::RefCell::new(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(
let dir = Dir2::new_unchecked((coord - *start).normalize());
// println!("Casting from {coord} to {dir:?}");
spatial_query.cast_ray_predicate(
*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;
&default(),
&|entity| {
if *e != entity && entities.contains(e) {
// println!("{entities:?} contains {e}");
*should_push.borrow_mut() = false;
}
true
},
);
if should_push {
if *should_push.borrow() {
new_visible_entities.insert(*e);
}
}
@ -111,9 +115,11 @@ impl Viewshed {
}
if new_visible_entities != **visible_entities {
for lost in visible_entities.difference(&new_visible_entities) {
// println!("Lost {lost}");
commands.trigger_targets(VisibilityChanged::Lost(*lost), *viewer_entity);
}
for gained in new_visible_entities.difference(visible_entities) {
// println!("Gained {gained}");
commands.trigger_targets(VisibilityChanged::Gained(*gained), *viewer_entity);
}
**visible_entities = new_visible_entities;
@ -147,23 +153,29 @@ pub struct OpacityMap(HashMap<IVec2, (u8, HashSet<Entity>)>);
impl OpacityMap {
fn update(
&mut self,
rapier_context: &RapierContext,
spatial_query: &SpatialQuery,
coordinates: HashSet<IVec2>,
visible: &Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
) {
self.retain(|k, _| !coordinates.contains(k));
let shape = Collider::cuboid(0.49, 0.49);
let shape = Collider::rectangle(0.98, 0.98);
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
});
spatial_query.shape_intersections_callback(
&shape,
shape_pos,
0.,
&default(),
|entity| {
if let Ok((_, _, _, visible)) = visible.get(entity) {
coord_entities.insert(entity);
opacity = opacity.max(**visible);
}
true
},
);
self.insert(*coords, (opacity, coord_entities));
}
}
@ -171,15 +183,19 @@ impl OpacityMap {
fn update_opacity_map(
mut opacity_map: ResMut<OpacityMap>,
rapier_context: Res<RapierContext>,
spatial_query: SpatialQuery,
query: Query<
(Entity, &GlobalTransform, &Collider, &Visible),
Or<(Changed<GlobalTransform>, Changed<Visible>)>,
(Entity, &GlobalTransform, &ColliderAabb, &Visible),
Or<(
Changed<GlobalTransform>,
Changed<ColliderAabb>,
Changed<Visible>,
)>,
>,
visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
) {
let mut to_update = HashSet::new();
for (entity, transform, collider, _) in &query {
for (entity, transform, aabb, _) in &query {
// println!(
// "Updating {entity} at {:?}",
// transform.translation().truncate().as_ivec2()
@ -193,18 +209,13 @@ fn update_opacity_map(
}
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 {
for x in aabb.min.x as i32..aabb.max.x as i32 {
for y in aabb.min.y as i32..aabb.max.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));
current.insert(IVec2::new(x, y));
}
}
if prev != current {
@ -212,27 +223,12 @@ fn update_opacity_map(
to_update.extend(current);
}
}
opacity_map.update(&rapier_context, to_update, &visible);
opacity_map.update(&spatial_query, to_update, &visible);
}
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
pub struct VisibleEntities(HashSet<Entity>);
#[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()
}
}
}
#[derive(Event)]
pub enum VisibilityChanged {
Gained(Entity),
@ -276,7 +272,7 @@ fn viewshed_removed(
}
}
pub struct VisibilityGrid(pub (u32, u32), pub Entity, pub OpacityMap);
struct VisibilityGrid(Entity, IVec2, u32, OpacityMap);
impl InputGrid for VisibilityGrid {
type Grid = (u32, u32);
@ -289,8 +285,12 @@ impl InputGrid for VisibilityGrid {
fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity {
// 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) {
let coord = IVec2::new(coord.x, coord.y);
if coord.distance(&self.1) > self.2 as f32 {
return 0;
}
if let Some((opacity, entities)) = self.3.get(&coord) {
if entities.contains(&self.0) {
// println!("Hit viewer, 0");
0
} else {
@ -306,7 +306,7 @@ impl InputGrid for VisibilityGrid {
fn update_viewshed(
mut commands: Commands,
config: Res<RapierConfiguration>,
physics_time: Res<Time<Physics>>,
mut viewers: Query<(
Entity,
&mut Viewshed,
@ -315,9 +315,9 @@ fn update_viewshed(
)>,
opacity_map: Res<OpacityMap>,
sensors: Query<&Sensor>,
rapier_context: Res<RapierContext>,
spatial_query: SpatialQuery,
) {
if !config.query_pipeline_active {
if physics_time.is_paused() {
return;
}
for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers {
@ -328,7 +328,7 @@ fn update_viewshed(
&viewer_transform.translation().truncate(),
&opacity_map,
&sensors,
&*rapier_context,
&spatial_query,
);
}
}
@ -343,7 +343,7 @@ fn remove_visible(
&GlobalTransform,
)>,
sensors: Query<&Sensor>,
rapier_context: Res<RapierContext>,
spatial_query: SpatialQuery,
mut opacity_map: ResMut<OpacityMap>,
visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
) {
@ -356,7 +356,7 @@ fn remove_visible(
}
}
}
opacity_map.update(&rapier_context, to_update, &visible);
opacity_map.update(&spatial_query, to_update, &visible);
for removed in removed.read() {
for (viewer_entity, mut viewshed, mut visible_entities, start) in &mut viewers {
if !visible_entities.contains(&removed) {
@ -369,7 +369,7 @@ fn remove_visible(
&start.translation().truncate(),
&opacity_map,
&sensors,
&*rapier_context,
&spatial_query,
);
}
}
@ -436,10 +436,7 @@ 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.init_resource::<OpacityMap>()
.add_systems(
FixedPreUpdate,
update_opacity_map.before(update_viewshed),
)
.add_systems(FixedPreUpdate, update_opacity_map.before(update_viewshed))
.add_systems(
FixedPreUpdate,
(
@ -449,6 +446,6 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlug
),
)
.add_systems(FixedPostUpdate, (viewshed_removed, remove_visible))
.observe(log_visible);
.add_observer(log_visible);
}
}