WIP: Refactor to Avian.

This commit is contained in:
Nolan Darilek 2024-10-06 11:10:46 -05:00
parent fb34f6ef12
commit 7c7504834f
9 changed files with 179 additions and 308 deletions

View File

@ -14,8 +14,8 @@ speech_dispatcher_0_10 = ["bevy_tts/speech_dispatcher_0_10"]
speech_dispatcher_0_11 = ["bevy_tts/speech_dispatcher_0_11"] speech_dispatcher_0_11 = ["bevy_tts/speech_dispatcher_0_11"]
[dependencies] [dependencies]
avian2d = "0.1"
bevy = "0.14" bevy = "0.14"
bevy_rapier2d = "0.27"
bevy_synthizer = "0.7" bevy_synthizer = "0.7"
bevy_tts = { version = "0.9", default-features = false, features = ["tolk"] } bevy_tts = { version = "0.9", default-features = false, features = ["tolk"] }
coord_2d = "0.3" coord_2d = "0.3"

View File

@ -6,12 +6,14 @@ use std::{
sync::RwLock, sync::RwLock,
}; };
use bevy::{app::PluginGroupBuilder, math::FloatOrd, prelude::*}; use avian2d::{
use bevy_rapier2d::{ parry::{
parry::query::{closest_points, distance, ClosestPoints}, math::Isometry,
query::{closest_points, distance, ClosestPoints},
},
prelude::*, prelude::*,
rapier::{math::Isometry, prelude::Aabb},
}; };
use bevy::{app::PluginGroupBuilder, math::FloatOrd, prelude::*};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use rand::prelude::*; use rand::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -530,7 +532,14 @@ impl GlobalTransformExt for GlobalTransform {
(other.translation() / *scale).xy().into(), (other.translation() / *scale).xy().into(),
other.yaw().radians(), other.yaw().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( fn collider_direction_and_distance(
@ -549,7 +558,13 @@ impl GlobalTransformExt for GlobalTransform {
other.yaw().radians(), other.yaw().radians(),
); );
let closest = self.closest_points(collider, other, other_collider); 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" }; let tile_or_tiles = if distance == 1 { "tile" } else { "tiles" };
if distance > 0 { if distance > 0 {
if let ClosestPoints::WithinMargin(p1, p2) = closest { if let ClosestPoints::WithinMargin(p1, p2) = closest {
@ -568,9 +583,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)] #[derive(Component, Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)] #[reflect(Component)]
pub struct Player; pub struct Player;
@ -676,9 +688,7 @@ impl Plugin for CorePlugin {
}; };
app.insert_resource(config) app.insert_resource(config)
.register_type::<CardinalDirection>() .register_type::<CardinalDirection>()
.add_plugins(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter( .add_plugins(PhysicsPlugins::default().with_length_unit(config.pixels_per_unit as f32))
config.pixels_per_unit as f32,
))
.add_systems(Startup, setup) .add_systems(Startup, setup)
.add_systems(Update, sync_config); .add_systems(Update, sync_config);
} }

View File

@ -1,7 +1,7 @@
use std::{error::Error, fmt::Debug, hash::Hash, marker::PhantomData}; use std::{error::Error, fmt::Debug, hash::Hash, marker::PhantomData};
use avian2d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::prelude::*;
use bevy_tts::Tts; use bevy_tts::Tts;
use leafwing_input_manager::prelude::*; use leafwing_input_manager::prelude::*;
@ -281,7 +281,7 @@ fn exploration_changed_announcement<ExplorationType, MapData>(
names: Query<&Name>, names: Query<&Name>,
types: Query<&ExplorationType>, types: Query<&ExplorationType>,
mappables: Query<&Mappable>, mappables: Query<&Mappable>,
rapier_context: Res<RapierContext>, spatial_query: SpatialQuery,
) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>
where where
ExplorationType: Component + Copy + Into<String>, ExplorationType: Component + Copy + Into<String>,
@ -290,7 +290,7 @@ where
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() { if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
let coordinates = coordinates.trunc(); let coordinates = coordinates.trunc();
let point = **exploring; let point = **exploring;
let shape = Collider::cuboid(0.5 - f32::EPSILON, 0.5 - f32::EPSILON); let shape = Collider::rectangle(0.5 - f32::EPSILON, 0.5 - f32::EPSILON);
let (known, idx) = if let Ok((map, revealed_tiles)) = map.get_single() { let (known, idx) = if let Ok((map, revealed_tiles)) = map.get_single() {
let idx = point.to_index(map.width); let idx = point.to_index(map.width);
(revealed_tiles[idx], Some(idx)) (revealed_tiles[idx], Some(idx))
@ -305,20 +305,22 @@ where
commands.entity(entity).remove::<ExplorationFocused>(); commands.entity(entity).remove::<ExplorationFocused>();
} }
let exploring = Vec2::new(exploring.x(), exploring.y()); let exploring = Vec2::new(exploring.x(), exploring.y());
rapier_context.intersections_with_shape( spatial_query.shape_intersections_callback(
&shape,
exploring, exploring,
0., 0.,
&shape, SpatialQueryFilter::default(),
QueryFilter::new().predicate(&|v| explorable.get(v).is_ok()),
|entity| { |entity| {
commands.entity(entity).insert(ExplorationFocused); if explorable.contains(entity) {
if visible || mappables.get(entity).is_ok() { commands.entity(entity).insert(ExplorationFocused);
if let Ok(name) = names.get(entity) { if visible || mappables.get(entity).is_ok() {
tokens.push(name.to_string()); if let Ok(name) = names.get(entity) {
} tokens.push(name.to_string());
if tokens.is_empty() { }
if let Ok(t) = types.get(entity) { if tokens.is_empty() {
tokens.push((*t).into()); if let Ok(t) = types.get(entity) {
tokens.push((*t).into());
}
} }
} }
} }

View File

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

View File

@ -1,20 +1,13 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use avian2d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::{
na::{Isometry2, Vector2},
prelude::*,
};
pub use here_be_dragons::Map as MapgenMap; pub use here_be_dragons::Map as MapgenMap;
use here_be_dragons::{geometry::Rect as MRect, MapFilter, Tile}; use here_be_dragons::{geometry::Rect as MRect, MapFilter, Tile};
use maze_generator::{prelude::*, recursive_backtracking::RbGenerator}; use maze_generator::{prelude::*, recursive_backtracking::RbGenerator};
use rand::prelude::StdRng; use rand::prelude::StdRng;
use crate::{ use crate::{core::PointLike, exploration::Mappable, visibility::Visible};
core::{Area, PointLike},
exploration::Mappable,
visibility::Visible,
};
#[derive(Component, Clone, Default, Deref, DerefMut)] #[derive(Component, Clone, Default, Deref, DerefMut)]
pub struct Map<D: 'static + Clone + Default + Send + Sync>(pub MapgenMap<D>); pub struct Map<D: 'static + Clone + Default + Send + Sync>(pub MapgenMap<D>);
@ -80,9 +73,9 @@ impl ITileType for Tile {
#[derive(Bundle, Default)] #[derive(Bundle, Default)]
pub struct PortalBundle { pub struct PortalBundle {
pub transform: TransformBundle,
pub portal: Portal, pub portal: Portal,
pub mappable: Mappable, pub mappable: Mappable,
pub transform: TransformBundle,
} }
#[derive(Bundle, Clone, Default)] #[derive(Bundle, Clone, Default)]
@ -98,7 +91,6 @@ pub struct TileBundle {
pub transform: TransformBundle, pub transform: TransformBundle,
pub collider: Collider, pub collider: Collider,
pub rigid_body: RigidBody, pub rigid_body: RigidBody,
pub active_collision_types: ActiveCollisionTypes,
pub map_obstruction: MapObstruction, pub map_obstruction: MapObstruction,
} }
@ -106,12 +98,9 @@ impl Default for TileBundle {
fn default() -> Self { fn default() -> Self {
Self { Self {
transform: default(), transform: default(),
collider: Collider::cuboid(0.5, 0.5), collider: Collider::rectangle(0.5, 0.5),
rigid_body: RigidBody::Fixed, rigid_body: RigidBody::Static,
active_collision_types: ActiveCollisionTypes::default() map_obstruction: default(),
| ActiveCollisionTypes::KINEMATIC_STATIC
| ActiveCollisionTypes::DYNAMIC_STATIC,
map_obstruction: MapObstruction,
} }
} }
} }
@ -129,34 +118,28 @@ impl TileBundle {
pub struct ZoneBundle { pub struct ZoneBundle {
pub collider: Collider, pub collider: Collider,
pub transform: TransformBundle, pub transform: TransformBundle,
pub area: Area,
pub zone: Zone, pub zone: Zone,
pub sensor: Sensor, pub sensor: Sensor,
pub active_events: ActiveEvents,
} }
impl ZoneBundle { impl ZoneBundle {
fn new(collider: Collider, position: (f32, f32)) -> Self { fn new(collider: Collider, position: Vec2) -> Self {
let point = Isometry2::new(Vector2::new(position.0, position.1), 0.);
let aabb = collider.raw.compute_aabb(&point);
Self { Self {
collider, collider,
area: Area(aabb), transform: Transform::from_translation(position.extend(0.)).into(),
transform: Transform::from_translation(Vec3::new(position.0, position.1, 0.)).into(),
zone: default(), zone: default(),
sensor: default(), sensor: default(),
active_events: ActiveEvents::COLLISION_EVENTS,
} }
} }
} }
impl From<&MRect> for ZoneBundle { impl From<&MRect> for ZoneBundle {
fn from(rect: &MRect) -> Self { fn from(rect: &MRect) -> Self {
let collider = Collider::cuboid( let collider = Collider::rectangle(
rect.width() as f32 / 2. + 0.5, rect.width() as f32 / 2. + 0.5,
rect.height() as f32 / 2. + 0.5, rect.height() as f32 / 2. + 0.5,
); );
let position = (rect.center().x(), rect.center().y()); let position = Vec2::new(rect.center().x(), rect.center().y());
Self::new(collider, position) Self::new(collider, position)
} }
} }
@ -332,7 +315,7 @@ fn spawn_portal_colliders<D: 'static + Clone + Default + Send + Sync>(
for portal_entity in &portals { for portal_entity in &portals {
commands commands
.entity(portal_entity) .entity(portal_entity)
.insert((Collider::cuboid(0.5, 0.5), Sensor)); .insert((Collider::rectangle(0.5, 0.5), Sensor));
} }
commands.entity(entity).remove::<SpawnColliders>(); commands.entity(entity).remove::<SpawnColliders>();
} }

View File

@ -1,14 +1,17 @@
#![allow(clippy::map_entry)]
use std::{collections::HashMap, error::Error, f32::consts::PI, fmt::Debug, hash::Hash}; use std::{collections::HashMap, error::Error, f32::consts::PI, fmt::Debug, hash::Hash};
use avian2d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::prelude::*;
use bevy_tts::Tts; use bevy_tts::Tts;
use leafwing_input_manager::prelude::*; use leafwing_input_manager::prelude::*;
use crate::{ use crate::{
core::{Angle, Area, CardinalDirection, GlobalTransformExt, Player, TransformExt}, core::{Angle, CardinalDirection, GlobalTransformExt, Player, TransformExt},
error::error_handler, error::error_handler,
log::Log, log::Log,
map::Zone,
utils::target_and_other, utils::target_and_other,
}; };
@ -151,13 +154,14 @@ fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
} }
fn controls( fn controls(
rapier_context: Res<RapierContext>, spatial_query: SpatialQuery,
time: Res<Time>, time: Res<Time>,
snap_timers: Res<SnapTimers>, snap_timers: Res<SnapTimers>,
sensors: Query<Entity, With<Sensor>>,
mut query: Query<( mut query: Query<(
Entity, Entity,
&mut ActionState<NavigationAction>, &mut ActionState<NavigationAction>,
&mut Velocity, &mut LinearVelocity,
&Speed, &Speed,
Option<&RotationSpeed>, Option<&RotationSpeed>,
Option<&BackwardMovementFactor>, Option<&BackwardMovementFactor>,
@ -212,24 +216,21 @@ fn controls(
// println!("{entity:?}: SetLinearVelocity: {velocity:?}"); // println!("{entity:?}: SetLinearVelocity: {velocity:?}");
actions.set_axis_pair(&NavigationAction::SetLinearVelocity, move_velocity); actions.set_axis_pair(&NavigationAction::SetLinearVelocity, move_velocity);
} }
if velocity.linvel != actions.axis_pair(&NavigationAction::SetLinearVelocity) { if velocity.0 != actions.axis_pair(&NavigationAction::SetLinearVelocity) {
velocity.linvel = actions.axis_pair(&NavigationAction::SetLinearVelocity); **velocity = actions.axis_pair(&NavigationAction::SetLinearVelocity);
} }
if actions.axis_pair(&NavigationAction::Translate) != Vec2::ZERO { if actions.axis_pair(&NavigationAction::Translate) != Vec2::ZERO {
let pair = actions.axis_pair(&NavigationAction::Translate); let pair = actions.axis_pair(&NavigationAction::Translate);
if rapier_context let dir = Dir2::new_unchecked(pair.normalize());
if spatial_query
.cast_shape( .cast_shape(
collider,
transform.translation.truncate(), transform.translation.truncate(),
transform.yaw().radians(), transform.yaw().radians(),
pair, dir,
collider, 1.,
ShapeCastOptions { true,
max_time_of_impact: 1., SpatialQueryFilter::from_excluded_entities(&sensors),
..default()
},
QueryFilter::new()
.exclude_sensors()
.exclude_collider(entity),
) )
.is_none() .is_none()
{ {
@ -302,18 +303,18 @@ fn speak_direction(
Ok(()) 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 { for entity in &query {
commands.entity(entity).insert(Velocity { commands.entity(entity).insert(LinearVelocity::default());
linvel: Vec2::ZERO,
..default()
});
} }
} }
fn log_area_descriptions<State>( fn log_zone_descriptions<State>(
mut events: EventReader<CollisionEvent>, mut events: EventReader<Collision>,
areas: Query<(&Area, Option<&Name>)>, zones: Query<(&ColliderAabb, Option<&Name>), With<Zone>>,
players: Query<&Player>, players: Query<&Player>,
config: Res<NavigationPlugin<State>>, config: Res<NavigationPlugin<State>>,
mut log: Query<&mut Log>, mut log: Query<&mut Log>,
@ -323,19 +324,21 @@ fn log_area_descriptions<State>(
if !config.log_area_descriptions { if !config.log_area_descriptions {
return; return;
} }
for event in events.read() { for Collision(contacts) in events.read() {
let (entity1, entity2, started) = match event { let started = contacts.during_current_frame && !contacts.during_previous_frame;
CollisionEvent::Started(collider1, collider2, _) => (collider1, collider2, true), let stopped = !contacts.during_current_frame && contacts.during_previous_frame;
CollisionEvent::Stopped(collider1, collider2, _) => (collider1, collider2, false), if !started && !stopped {
}; continue;
if let Some((area, other)) = target_and_other(*entity1, *entity2, &|v| areas.get(v).is_ok()) }
if let Some((area, other)) =
target_and_other(contacts.entity1, contacts.entity2, &|v| zones.contains(v))
{ {
if players.get(other).is_ok() { if players.contains(other) {
if let Ok((aabb, area_name)) = areas.get(area) { if let Ok((aabb, area_name)) = zones.get(area) {
let name = if let Some(name) = area_name { let name = if let Some(name) = area_name {
Some(name.to_string()) Some(name.to_string())
} else if config.describe_undescribed_areas { } 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 { } else {
None None
}; };
@ -400,7 +403,7 @@ where
) )
.add_systems( .add_systems(
PostUpdate, PostUpdate,
(remove_direction, log_area_descriptions::<State>), (remove_direction, log_zone_descriptions::<State>),
); );
if !self.states.is_empty() { if !self.states.is_empty() {
for state in &self.states { for state in &self.states {

View File

@ -1,19 +1,11 @@
use bevy::{ use avian2d::prelude::*;
prelude::*, use bevy::{prelude::*, utils::HashMap};
tasks::{futures_lite::future, prelude::*, Task},
utils::HashMap,
};
use bevy_rapier2d::{
na::{Isometry2, Vector2},
prelude::*,
rapier::prelude::{ColliderHandle, ColliderSet, QueryPipeline, RigidBodySet},
};
use leafwing_input_manager::{plugin::InputManagerSystem, prelude::*}; use leafwing_input_manager::{plugin::InputManagerSystem, prelude::*};
use pathfinding::prelude::*; use pathfinding::prelude::*;
use crate::{ use crate::{
core::{PointLike, TransformExt}, core::{PointLike, TransformExt},
map::{Map, MapObstruction}, map::Map,
navigation::{NavigationAction, RotationSpeed, Speed}, navigation::{NavigationAction, RotationSpeed, Speed},
}; };
@ -26,9 +18,6 @@ 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)] #[derive(Component, Clone, Copy, Debug, Default, Deref, DerefMut, Eq, Hash, PartialEq, Reflect)]
#[reflect(Component)] #[reflect(Component)]
pub struct Destination(pub (i32, i32)); pub struct Destination(pub (i32, i32));
@ -93,182 +82,94 @@ pub fn find_path<D: 'static + Clone + Default + Send + Sync>(
) )
} }
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( fn calculate_path(
mut commands: Commands, mut commands: Commands,
rapier_context: Res<RapierContext>, spatial_query: SpatialQuery,
obstructions: Query<&RapierColliderHandle, With<MapObstruction>>, mut query: Query<
query: Query<
( (
Entity, Entity,
&RapierColliderHandle,
&Destination, &Destination,
&Transform, &Transform,
&Collider, &Collider,
Option<&CostMap>, Option<&CostMap>,
Option<&mut ActionState<NegotiatePathAction>>,
), ),
Changed<Destination>, Changed<Destination>,
>, >,
) { ) {
for (entity, handle, destination, coordinates, shape, cost_map) in &query { for (entity, destination, start, collider, cost_map, actions) in &mut query {
trace trace!("{entity}: destination: {destination:?}");
!("{entity}: destination: {destination:?}"); if start.i32() == **destination {
if coordinates.i32() == **destination { trace!("{entity}: remove1");
trace
!("{entity}: remove1");
commands commands
.entity(entity) .entity(entity)
.remove::<Path>() .remove::<Path>()
.remove::<NoPath>() .remove::<NoPath>()
.remove::<Calculating>()
.remove::<Destination>(); .remove::<Destination>();
continue; continue;
} }
trace!( trace!(
"{entity:?}: Calculating path from {:?} to {destination:?}", "{entity:?}: Calculating path from {:?} to {destination:?}",
coordinates.translation.truncate().i32() start.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!( trace!(
"{entity:?}: path: calculating from {:?} to {destination:?}", "{entity:?}: path: calculating from {:?} to {destination:?}",
coordinates.i32(), start.i32(),
); );
let pool = AsyncComputeTaskPool::get(); commands.entity(entity).remove::<Path>().remove::<NoPath>();
let task = pool.spawn(async move { let path = astar(
find_path_for_shape( &start.i32(),
handle_clone.0, |p| {
coordinates_clone, let mut successors: Vec<((i32, i32), u32)> = vec![];
destination_clone, let x = p.0;
&cost_map_clone, let y = p.1;
query_pipeline, let exits = vec![
collider_set, ((x - 1, y), 1.),
bodies, ((x + 1, y), 1.),
shape_clone, ((x, y - 1), 1.),
) ((x, y + 1), 1.),
}); ((x - 1, y - 1), 1.5),
trace ((x + 1, y - 1), 1.5),
!("{entity}: remove2"); ((x - 1, y + 1), 1.5),
commands ((x + 1, y + 1), 1.5),
.entity(entity) ];
.insert(Calculating(task)) for exit in &exits {
.remove::<Path>() let mut should_push = true;
.remove::<NoPath>(); if !spatial_query
} .shape_intersections(
} collider,
start.translation.truncate(),
fn poll_tasks( start.yaw().radians(),
mut commands: Commands, SpatialQueryFilter::default(),
mut query: Query<( )
Entity, .is_empty()
&mut Calculating, {
&Transform, should_push = false;
&Destination, }
Option<&mut ActionState<NegotiatePathAction>>, if should_push {
)>, let mut cost = exit.1 * 100.;
) { if let Some(cost_map) = cost_map {
for (entity, mut calculating, transform, destination, actions) in &mut query { if let Some(modifier) = cost_map.get(&(exit.0 .0, exit.0 .1)) {
if let Some(result) = future::block_on(future::poll_once(&mut **calculating)) { cost *= modifier;
if let Some(path) = result { }
trace!("{entity:?}: Path: {path:?}"); }
commands.entity(entity).insert(path); successors.push((exit.0, cost as u32));
} 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();
} }
successors
},
|p| (p.distance_squared(&destination) * 100.) as u32,
|p| *p == destination.i32(),
);
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>();
} }
} }
} }
@ -276,10 +177,7 @@ fn poll_tasks(
fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Destination>) { fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Destination>) {
for entity in removed.read() { for entity in removed.read() {
if let Some(mut commands) = commands.get_entity(entity) { if let Some(mut commands) = commands.get_entity(entity) {
commands commands.remove::<Path>().remove::<NoPath>();
.remove::<Calculating>()
.remove::<Path>()
.remove::<NoPath>();
} }
} }
} }
@ -287,7 +185,7 @@ fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Des
fn negotiate_path( fn negotiate_path(
mut commands: Commands, mut commands: Commands,
time: Res<Time>, time: Res<Time>,
physics_config: Res<RapierConfiguration>, spatial_query: SpatialQuery,
mut query: Query<( mut query: Query<(
Entity, Entity,
Option<&mut ActionState<NegotiatePathAction>>, Option<&mut ActionState<NegotiatePathAction>>,
@ -298,11 +196,7 @@ fn negotiate_path(
&Speed, &Speed,
Option<&RotationSpeed>, Option<&RotationSpeed>,
)>, )>,
rapier_context: Res<RapierContext>,
) { ) {
if !physics_config.physics_pipeline_active || !physics_config.query_pipeline_active {
return;
}
for ( for (
entity, entity,
actions, actions,
@ -346,24 +240,19 @@ fn negotiate_path(
"{entity:?}: Direction: {direction:?}, Distance: {}", "{entity:?}: Direction: {direction:?}, Distance: {}",
(next - start).length() (next - start).length()
); );
if rapier_context if spatial_query
.cast_shape( .cast_shape(
collider,
start, start,
transform.yaw().radians(), transform.yaw().radians(),
direction, Dir2::new_unchecked(direction.normalize()),
collider, direction.length(),
ShapeCastOptions { true,
max_time_of_impact: 1., SpatialQueryFilter::default(),
..default()
},
QueryFilter::new()
.exclude_sensors()
.exclude_collider(entity),
) )
.is_some() .is_some()
{ {
trace trace!("{entity:?} is stuck");
!("{entity:?} is stuck");
// TODO: Remove when we have an actual character controller. // TODO: Remove when we have an actual character controller.
next.x = next.x.trunc(); next.x = next.x.trunc();
next.y = next.y.trunc(); next.y = next.y.trunc();
@ -376,8 +265,7 @@ fn negotiate_path(
transform.rotation = Quat::from_rotation_z(angle); transform.rotation = Quat::from_rotation_z(angle);
} }
} else { } else {
trace trace!("{entity:?}: empty path, cleaning");
!("{entity:?}: empty path, cleaning");
if let Some(mut actions) = actions { if let Some(mut actions) = actions {
trace!("{entity:?}: Disabling pathfind because at destination"); trace!("{entity:?}: Disabling pathfind because at destination");
actions.reset_all(); actions.reset_all();
@ -421,8 +309,7 @@ fn actions(
*current_dest = dest; *current_dest = dest;
} }
} else { } else {
trace trace!("{entity:?}: Adding destination, zeroing velocity");
!("{entity:?}: Adding destination, zeroing velocity");
navigation_action.set_axis_pair(&NavigationAction::SetLinearVelocity, Vec2::ZERO); navigation_action.set_axis_pair(&NavigationAction::SetLinearVelocity, Vec2::ZERO);
commands.entity(entity).insert(dest); commands.entity(entity).insert(dest);
} }
@ -439,7 +326,7 @@ impl Plugin for PathfindingPlugin {
.register_type::<NoPath>() .register_type::<NoPath>()
.register_type::<Path>() .register_type::<Path>()
.register_type::<CostMap>() .register_type::<CostMap>()
.add_systems(PreUpdate, (poll_tasks, negotiate_path).chain()) .add_systems(PreUpdate, negotiate_path)
.add_systems( .add_systems(
PreUpdate, PreUpdate,
(actions, calculate_path) (actions, calculate_path)

View File

@ -1,5 +1,5 @@
use avian2d::{parry::query::ClosestPoints, prelude::*};
use bevy::{prelude::*, transform::TransformSystem}; use bevy::{prelude::*, transform::TransformSystem};
use bevy_rapier2d::{parry::query::ClosestPoints, prelude::*};
use bevy_synthizer::{Listener, Sound}; use bevy_synthizer::{Listener, Sound};
use crate::core::GlobalTransformExt; use crate::core::GlobalTransformExt;

View File

@ -4,14 +4,12 @@ use std::{
marker::PhantomData, marker::PhantomData,
}; };
use avian2d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
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};
use crate::{ use crate::{
bevy_rapier2d::prelude::*,
core::{GlobalTransformExt, Player, PointLike}, core::{GlobalTransformExt, Player, PointLike},
log::Log, log::Log,
map::{Map, MapPlugin}, map::{Map, MapPlugin},
@ -51,29 +49,22 @@ impl Viewshed {
viewer_entity: &Entity, viewer_entity: &Entity,
visible_entities: &mut VisibleEntities, visible_entities: &mut VisibleEntities,
start: &Vec2, start: &Vec2,
rapier_context: &RapierContext, spatial_query: &SpatialQuery,
visible_query: &Query<(&Visible, &Collider, &GlobalTransform)>, visible_query: &Query<(&Visible, &Collider, &GlobalTransform)>,
cache: &mut RefCell<HashMap<(i32, i32), (u8, HashSet<Entity>)>>, cache: &mut RefCell<HashMap<(i32, i32), (u8, HashSet<Entity>)>>,
) { ) {
// println!("Start"); // println!("Start");
let mut boxes = vec![]; let mut boxes = vec![];
let shape = Collider::cuboid(self.range as f32, self.range as f32); let shape = Collider::rectangle(self.range as f32, self.range as f32);
rapier_context.intersections_with_shape(*start, 0., &shape, default(), |entity| { spatial_query.shape_intersections_callback(&shape, *start, 0., default(), |entity| {
if let Ok((_, collider, transform)) = visible_query.get(entity) { if let Ok((_, collider, transform)) = visible_query.get(entity) {
let position = boxes.push(collider.aabb(transform.translation().truncate(), 0.));
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 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 shape = Collider::rectangle(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,
@ -96,15 +87,14 @@ impl Viewshed {
coord_entities = entities.clone(); coord_entities = entities.clone();
*opacity *opacity
} else { } else {
let position = Isometry2::translation(shape_pos.x, shape_pos.y); let aabb = shape.aabb(shape_pos, 0.);
let aabb = shape.raw.compute_aabb(&position);
if boxes.iter().any(|b| b.intersects(&aabb)) { if boxes.iter().any(|b| b.intersects(&aabb)) {
// println!("Hit"); // println!("Hit");
let mut opacity = 0; let mut opacity = 0;
rapier_context.intersections_with_shape( spatial_query.shape_intersections_callback(
&shape,
shape_pos, shape_pos,
0., 0.,
&shape,
default(), default(),
|entity| { |entity| {
if let Ok((visible, _, _)) = visible_query.get(entity) { if let Ok((visible, _, _)) = visible_query.get(entity) {
@ -130,7 +120,7 @@ impl Viewshed {
if let Some((k, v)) = to_insert { if let Some((k, v)) = to_insert {
cache.borrow_mut().insert(k, v); cache.borrow_mut().insert(k, v);
} }
if coord_entities.contains(&viewer_entity) { if coord_entities.contains(viewer_entity) {
let mut coord_entities = coord_entities.clone(); let mut coord_entities = coord_entities.clone();
coord_entities.retain(|e| e != viewer_entity); coord_entities.retain(|e| e != viewer_entity);
let opacity = coord_entities let opacity = coord_entities
@ -282,7 +272,6 @@ where
fn update_viewshed( fn update_viewshed(
mut commands: Commands, mut commands: Commands,
config: Res<RapierConfiguration>,
visible: Query<(&Visible, &Collider, &GlobalTransform)>, visible: Query<(&Visible, &Collider, &GlobalTransform)>,
mut viewers: Query<( mut viewers: Query<(
Entity, Entity,
@ -290,11 +279,8 @@ fn update_viewshed(
&mut VisibleEntities, &mut VisibleEntities,
&GlobalTransform, &GlobalTransform,
)>, )>,
rapier_context: Res<RapierContext>, spatial_query: SpatialQuery,
) { ) {
if !config.query_pipeline_active {
return;
}
let mut cache = default(); 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(
@ -302,7 +288,7 @@ fn update_viewshed(
&viewer_entity, &viewer_entity,
&mut visible_entities, &mut visible_entities,
&viewer_transform.translation().truncate(), &viewer_transform.translation().truncate(),
&rapier_context, &spatial_query,
&visible, &visible,
&mut cache, &mut cache,
); );
@ -318,7 +304,7 @@ fn remove_visible(
&mut VisibleEntities, &mut VisibleEntities,
&GlobalTransform, &GlobalTransform,
)>, )>,
rapier_context: Res<RapierContext>, spatial_query: SpatialQuery,
visible: Query<(&Visible, &Collider, &GlobalTransform)>, visible: Query<(&Visible, &Collider, &GlobalTransform)>,
) { ) {
if !removed.is_empty() { if !removed.is_empty() {
@ -333,7 +319,7 @@ fn remove_visible(
&viewer_entity, &viewer_entity,
&mut visible_entities, &mut visible_entities,
&start.translation().truncate(), &start.translation().truncate(),
&rapier_context, &spatial_query,
&visible, &visible,
&mut cache, &mut cache,
); );