Compare commits
1 Commits
Author | SHA1 | Date | |
---|---|---|---|
827cae1a4b |
|
@ -14,8 +14,8 @@ speech_dispatcher_0_10 = ["bevy_tts/speech_dispatcher_0_10"]
|
|||
speech_dispatcher_0_11 = ["bevy_tts/speech_dispatcher_0_11"]
|
||||
|
||||
[dependencies]
|
||||
avian2d = "0.1"
|
||||
bevy = "0.14"
|
||||
bevy_rapier2d = "0.27"
|
||||
bevy_synthizer = "0.7"
|
||||
bevy_tts = { version = "0.9", default-features = false, features = ["tolk"] }
|
||||
coord_2d = "0.3"
|
||||
|
|
409
src/core.rs
409
src/core.rs
|
@ -2,191 +2,108 @@ use std::{
|
|||
cmp::{max, min},
|
||||
f32::consts::PI,
|
||||
fmt::Display,
|
||||
ops::Sub,
|
||||
sync::RwLock,
|
||||
};
|
||||
|
||||
use avian2d::{
|
||||
parry::{
|
||||
math::Isometry,
|
||||
query::{closest_points, distance, ClosestPoints},
|
||||
},
|
||||
use bevy::{
|
||||
app::PluginGroupBuilder,
|
||||
math::{CompassOctant, CompassQuadrant, FloatOrd},
|
||||
prelude::*,
|
||||
};
|
||||
use bevy::{app::PluginGroupBuilder, math::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(Clone, Copy, Debug, Reflect)]
|
||||
pub enum Angle {
|
||||
Degrees(f32),
|
||||
Radians(f32),
|
||||
fn relative_desc(rot: &Rot2) -> String {
|
||||
let mode = RELATIVE_DIRECTION_MODE.read().unwrap();
|
||||
match rot.as_radians() {
|
||||
v if v <= PI / 12. && v > -PI / 12. => "ahead",
|
||||
v if v <= PI / 4. && v > PI / 12. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"11:00"
|
||||
} else {
|
||||
"ahead and left"
|
||||
}
|
||||
}
|
||||
v if v <= 3. * PI / 8. && v > PI / 4. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"10:00"
|
||||
} else {
|
||||
"left and ahead"
|
||||
}
|
||||
}
|
||||
v if v <= 5. * PI / 8. && v > 3. * PI / 8. => "left",
|
||||
v if v <= 3. * PI / 4. && v > 5. * PI / 8. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"8:00"
|
||||
} else {
|
||||
"left and behind"
|
||||
}
|
||||
}
|
||||
v if v <= 11. * PI / 12. && v > 3. * PI / 4. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"7:00"
|
||||
} else {
|
||||
"behind and left"
|
||||
}
|
||||
}
|
||||
v if v <= PI && v > 11. * PI / 12. || v > -PI && v <= -11. * PI / 12. => "behind",
|
||||
v if v <= -3. * PI / 4. && v > -11. * PI / 12. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"5:00"
|
||||
} else {
|
||||
"behind and right"
|
||||
}
|
||||
}
|
||||
v if v <= -5. * PI / 8. && v > -3. * PI / 4. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"4:00"
|
||||
} else {
|
||||
"right and behind"
|
||||
}
|
||||
}
|
||||
v if v <= -3. * PI / 8. && v > -5. * PI / 8. => "right",
|
||||
v if v <= -PI / 4. && v > -3. * PI / 8. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"2:00"
|
||||
} else {
|
||||
"right and ahead"
|
||||
}
|
||||
}
|
||||
v if v <= -PI / 12. && v > -PI / 4. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"1:00"
|
||||
} else {
|
||||
"ahead and right"
|
||||
}
|
||||
}
|
||||
_ => "ahead",
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
impl Default for Angle {
|
||||
fn default() -> Self {
|
||||
Self::Radians(0.)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deref, DerefMut, Reflect)]
|
||||
pub struct MovementDirection(CompassOctant);
|
||||
|
||||
impl Angle {
|
||||
pub fn degrees(&self) -> f32 {
|
||||
use Angle::*;
|
||||
let mut degrees: f32 = match self {
|
||||
Degrees(v) => *v,
|
||||
Radians(v) => v.to_degrees(),
|
||||
};
|
||||
while degrees < 0. {
|
||||
degrees += 360.;
|
||||
}
|
||||
while degrees >= 360. {
|
||||
degrees %= 360.;
|
||||
}
|
||||
degrees
|
||||
}
|
||||
|
||||
pub fn degrees_u32(&self) -> u32 {
|
||||
self.degrees() as u32
|
||||
}
|
||||
|
||||
pub fn radians(&self) -> f32 {
|
||||
use Angle::*;
|
||||
match self {
|
||||
Degrees(v) => v.to_radians(),
|
||||
Radians(v) => *v,
|
||||
}
|
||||
}
|
||||
|
||||
fn relative_desc(&self) -> String {
|
||||
let mode = RELATIVE_DIRECTION_MODE.read().unwrap();
|
||||
match self.degrees() {
|
||||
v if v <= 15. => "ahead",
|
||||
v if v <= 45. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"11:00"
|
||||
} else {
|
||||
"ahead and left"
|
||||
}
|
||||
}
|
||||
v if v <= 75. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"10:00"
|
||||
} else {
|
||||
"left and ahead"
|
||||
}
|
||||
}
|
||||
v if v <= 105. => "left",
|
||||
v if v <= 135. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"8:00"
|
||||
} else {
|
||||
"left and behind"
|
||||
}
|
||||
}
|
||||
v if v <= 165. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"7:00"
|
||||
} else {
|
||||
"behind and left"
|
||||
}
|
||||
}
|
||||
v if v <= 195. => "behind",
|
||||
v if v <= 225. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"5:00"
|
||||
} else {
|
||||
"behind and right"
|
||||
}
|
||||
}
|
||||
v if v <= 255. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"4:00"
|
||||
} else {
|
||||
"right and behind"
|
||||
}
|
||||
}
|
||||
v if v <= 285. => "right",
|
||||
v if v <= 315. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"2:00"
|
||||
} else {
|
||||
"right and ahead"
|
||||
}
|
||||
}
|
||||
v if v <= 345. => {
|
||||
if *mode == RelativeDirectionMode::ClockFacing {
|
||||
"1:00"
|
||||
} else {
|
||||
"ahead and right"
|
||||
}
|
||||
}
|
||||
_ => "ahead",
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for Angle {
|
||||
type Output = Self;
|
||||
|
||||
fn sub(self, rhs: Self) -> Self::Output {
|
||||
match self {
|
||||
Angle::Degrees(v1) => match rhs {
|
||||
Angle::Degrees(v2) => Angle::Degrees(v1 - v2),
|
||||
Angle::Radians(v2) => Angle::Degrees(v1 - v2.to_degrees()),
|
||||
},
|
||||
Angle::Radians(v1) => match rhs {
|
||||
Angle::Degrees(v2) => Angle::Radians(v1 - v2.to_radians()),
|
||||
Angle::Radians(v2) => Angle::Radians(v1 - v2),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Reflect)]
|
||||
pub enum MovementDirection {
|
||||
North,
|
||||
NorthNortheast,
|
||||
Northeast,
|
||||
EastNortheast,
|
||||
East,
|
||||
EastSoutheast,
|
||||
Southeast,
|
||||
SouthSoutheast,
|
||||
South,
|
||||
SouthSouthwest,
|
||||
Southwest,
|
||||
WestSouthwest,
|
||||
West,
|
||||
WestNorthwest,
|
||||
Northwest,
|
||||
NorthNorthwest,
|
||||
}
|
||||
|
||||
impl From<Angle> for MovementDirection {
|
||||
fn from(angle: Angle) -> Self {
|
||||
let heading = angle.degrees();
|
||||
use MovementDirection::*;
|
||||
match heading {
|
||||
h if h < 11.5 => East,
|
||||
h if h < 34.0 => EastNortheast,
|
||||
h if h < 56.5 => Northeast,
|
||||
h if h < 79.0 => NorthNortheast,
|
||||
h if h < 101.5 => North,
|
||||
h if h < 124.0 => NorthNorthwest,
|
||||
h if h < 146.5 => Northwest,
|
||||
h if h < 169.0 => WestNorthwest,
|
||||
h if h < 191.5 => West,
|
||||
h if h < 214.0 => WestSouthwest,
|
||||
h if h < 236.5 => Southwest,
|
||||
h if h < 259.0 => SouthSouthwest,
|
||||
h if h < 281.5 => South,
|
||||
h if h < 304.0 => SouthSoutheast,
|
||||
h if h < 326.5 => Southeast,
|
||||
h if h <= 349.0 => EastSoutheast,
|
||||
_ => East,
|
||||
}
|
||||
impl From<Rot2> for MovementDirection {
|
||||
fn from(rot: Rot2) -> Self {
|
||||
use CompassOctant::*;
|
||||
MovementDirection(match rot.as_radians() {
|
||||
h if h > -PI / 8. && h <= PI / 8. => East,
|
||||
h if h > PI / 8. && h <= 3. * PI / 8. => NorthEast,
|
||||
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 > 7. * PI / 8. || h <= -7. * PI / 8. => East,
|
||||
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 > -3. * PI / 8. && h <= -PI / 8. => SouthWest,
|
||||
_ => West,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -194,25 +111,18 @@ impl From<Angle> for MovementDirection {
|
|||
#[allow(clippy::from_over_into)]
|
||||
impl Into<String> for MovementDirection {
|
||||
fn into(self) -> String {
|
||||
use MovementDirection::*;
|
||||
match self {
|
||||
North => "north".to_string(),
|
||||
NorthNortheast => "north northeast".to_string(),
|
||||
Northeast => "northeast".to_string(),
|
||||
EastNortheast => "east northeast".to_string(),
|
||||
East => "east".to_string(),
|
||||
EastSoutheast => "east southeast".to_string(),
|
||||
Southeast => "southeast".to_string(),
|
||||
SouthSoutheast => "south southeast".to_string(),
|
||||
South => "south".to_string(),
|
||||
SouthSouthwest => "south southwest".to_string(),
|
||||
Southwest => "southwest".to_string(),
|
||||
WestSouthwest => "west southwest".to_string(),
|
||||
West => "west".to_string(),
|
||||
WestNorthwest => "west northwest".to_string(),
|
||||
Northwest => "northwest".to_string(),
|
||||
NorthNorthwest => "north northwest".to_string(),
|
||||
use CompassOctant::*;
|
||||
match self.0 {
|
||||
North => "north",
|
||||
NorthEast => "northeast",
|
||||
East => "east",
|
||||
SouthEast => "southeast",
|
||||
South => "south",
|
||||
SouthWest => "southwest",
|
||||
West => "west",
|
||||
NorthWest => "northwest",
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -223,38 +133,36 @@ impl Display for MovementDirection {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Component, Clone, Copy, Default, Debug, Eq, PartialEq, Reflect)]
|
||||
#[derive(Component, Clone, Copy, Debug, Eq, PartialEq, Deref, DerefMut, Reflect)]
|
||||
#[reflect(Component)]
|
||||
pub enum CardinalDirection {
|
||||
#[default]
|
||||
North,
|
||||
East,
|
||||
South,
|
||||
West,
|
||||
}
|
||||
pub struct CardinalDirection(pub CompassQuadrant);
|
||||
|
||||
impl From<Angle> for CardinalDirection {
|
||||
fn from(angle: Angle) -> Self {
|
||||
let heading = angle.degrees();
|
||||
use CardinalDirection::*;
|
||||
match heading {
|
||||
h if h <= 45. => East,
|
||||
h if h <= 135. => North,
|
||||
h if h <= 225. => West,
|
||||
h if h <= 315. => South,
|
||||
_ => East,
|
||||
}
|
||||
impl Default for CardinalDirection {
|
||||
fn default() -> Self {
|
||||
Self(CompassQuadrant::East)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&CardinalDirection> for Angle {
|
||||
impl From<Rot2> for CardinalDirection {
|
||||
fn from(rot: Rot2) -> Self {
|
||||
use CompassQuadrant::*;
|
||||
CardinalDirection(match rot.as_radians() {
|
||||
h if h > -PI / 4. && h <= PI / 4. => East,
|
||||
h if h > PI / 4. && h <= 3. * PI / 4. => North,
|
||||
h if h > 3. * PI / 4. || h <= -3. * PI / 4. => West,
|
||||
_ => South,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&CardinalDirection> for Rot2 {
|
||||
fn from(direction: &CardinalDirection) -> Self {
|
||||
use CardinalDirection::*;
|
||||
match direction {
|
||||
North => Angle::Radians(PI / 2.),
|
||||
East => Angle::Radians(0.),
|
||||
South => Angle::Radians(PI * 1.5),
|
||||
West => Angle::Radians(PI),
|
||||
use CompassQuadrant::*;
|
||||
match direction.0 {
|
||||
North => Rot2::radians(PI / 2.),
|
||||
East => Rot2::radians(0.),
|
||||
South => Rot2::radians(-PI / 2.),
|
||||
West => Rot2::radians(PI),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -263,8 +171,8 @@ impl From<&CardinalDirection> for Angle {
|
|||
#[allow(clippy::from_over_into)]
|
||||
impl Into<String> for CardinalDirection {
|
||||
fn into(self) -> String {
|
||||
use CardinalDirection::*;
|
||||
match self {
|
||||
use CompassQuadrant::*;
|
||||
match self.0 {
|
||||
North => "north".to_string(),
|
||||
East => "east".to_string(),
|
||||
South => "south".to_string(),
|
||||
|
@ -344,24 +252,26 @@ pub trait PointLike {
|
|||
self.distance_squared(other).sqrt()
|
||||
}
|
||||
|
||||
fn bearing(&self, other: &dyn PointLike) -> Angle {
|
||||
fn bearing(&self, other: &dyn PointLike) -> Rot2 {
|
||||
let y = other.y() - self.y();
|
||||
let x = other.x() - self.x();
|
||||
Angle::Radians(y.atan2(x))
|
||||
Rot2::radians(y.atan2(x))
|
||||
}
|
||||
|
||||
fn direction(&self, other: &dyn PointLike) -> MovementDirection {
|
||||
self.bearing(other).into()
|
||||
}
|
||||
|
||||
fn direction_and_distance(&self, other: &dyn PointLike, yaw: Option<Angle>) -> String {
|
||||
fn direction_and_distance(&self, other: &dyn PointLike, yaw: Option<Rot2>) -> String {
|
||||
let mut tokens: Vec<String> = vec![];
|
||||
let distance = self.distance(other).round() as i32;
|
||||
if distance > 0 {
|
||||
let tile_or_tiles = if distance == 1 { "tile" } else { "tiles" };
|
||||
let direction: String = if let Some(yaw) = yaw {
|
||||
let bearing = self.bearing(other);
|
||||
(bearing - yaw).relative_desc()
|
||||
let yaw = yaw.as_radians();
|
||||
let bearing = self.bearing(other).as_radians();
|
||||
let rot = Rot2::radians(bearing - yaw);
|
||||
relative_desc(&rot)
|
||||
} else {
|
||||
self.direction(other).into()
|
||||
};
|
||||
|
@ -483,18 +393,18 @@ impl From<&dyn PointLike> for (i32, i32) {
|
|||
}
|
||||
|
||||
pub trait TransformExt {
|
||||
fn yaw(&self) -> Angle;
|
||||
fn yaw(&self) -> Rot2;
|
||||
}
|
||||
|
||||
impl TransformExt for Transform {
|
||||
fn yaw(&self) -> Angle {
|
||||
fn yaw(&self) -> Rot2 {
|
||||
let forward = self.right();
|
||||
Angle::Radians(forward.y.atan2(forward.x))
|
||||
Rot2::radians(forward.y.atan2(forward.x))
|
||||
}
|
||||
}
|
||||
|
||||
pub trait GlobalTransformExt {
|
||||
fn yaw(&self) -> Angle;
|
||||
fn yaw(&self) -> Rot2;
|
||||
|
||||
fn closest_points(
|
||||
&self,
|
||||
|
@ -512,9 +422,9 @@ pub trait GlobalTransformExt {
|
|||
}
|
||||
|
||||
impl GlobalTransformExt for GlobalTransform {
|
||||
fn yaw(&self) -> Angle {
|
||||
fn yaw(&self) -> Rot2 {
|
||||
let forward = self.right();
|
||||
Angle::Radians(forward.y.atan2(forward.x))
|
||||
Rot2::radians(forward.y.atan2(forward.x))
|
||||
}
|
||||
|
||||
fn closest_points(
|
||||
|
@ -526,20 +436,13 @@ impl GlobalTransformExt for GlobalTransform {
|
|||
let scale = PHYSICS_SCALE.read().unwrap();
|
||||
let pos1 = Isometry::new(
|
||||
(self.translation() / *scale).xy().into(),
|
||||
self.yaw().radians(),
|
||||
self.yaw().as_radians(),
|
||||
);
|
||||
let pos2 = Isometry::new(
|
||||
(other.translation() / *scale).xy().into(),
|
||||
other.yaw().radians(),
|
||||
other.yaw().as_radians(),
|
||||
);
|
||||
closest_points(
|
||||
&pos1,
|
||||
collider.shape().as_ref(),
|
||||
&pos2,
|
||||
other_collider.shape().as_ref(),
|
||||
f32::MAX,
|
||||
)
|
||||
.unwrap()
|
||||
closest_points(&pos1, &*collider.raw, &pos2, &*other_collider.raw, f32::MAX).unwrap()
|
||||
}
|
||||
|
||||
fn collider_direction_and_distance(
|
||||
|
@ -551,28 +454,23 @@ impl GlobalTransformExt for GlobalTransform {
|
|||
let scale = PHYSICS_SCALE.read().unwrap();
|
||||
let pos1 = Isometry::new(
|
||||
(self.translation() / *scale).xy().into(),
|
||||
self.yaw().radians(),
|
||||
self.yaw().as_radians(),
|
||||
);
|
||||
let pos2 = Isometry::new(
|
||||
(other.translation() / *scale).xy().into(),
|
||||
other.yaw().radians(),
|
||||
other.yaw().as_radians(),
|
||||
);
|
||||
let closest = self.closest_points(collider, other, other_collider);
|
||||
let distance = distance(
|
||||
&pos1,
|
||||
collider.shape().as_ref(),
|
||||
&pos2,
|
||||
other_collider.shape().as_ref(),
|
||||
)
|
||||
.unwrap() as u32;
|
||||
let distance = distance(&pos1, &*collider.raw, &pos2, &*other_collider.raw).unwrap() as u32;
|
||||
let tile_or_tiles = if distance == 1 { "tile" } else { "tiles" };
|
||||
if distance > 0 {
|
||||
if let ClosestPoints::WithinMargin(p1, p2) = closest {
|
||||
let p1 = (p1.x, p1.y);
|
||||
let p2 = (p2.x, p2.y);
|
||||
let bearing = p1.bearing(&p2);
|
||||
let yaw = self.yaw();
|
||||
let direction = (bearing - yaw).relative_desc();
|
||||
let bearing = p1.bearing(&p2).as_radians();
|
||||
let yaw = self.yaw().as_radians();
|
||||
let rot = Rot2::radians(bearing - yaw);
|
||||
let direction = relative_desc(&rot);
|
||||
format!("{direction} {distance} {tile_or_tiles}")
|
||||
} else {
|
||||
format!("{} {}", distance, tile_or_tiles)
|
||||
|
@ -583,6 +481,9 @@ 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;
|
||||
|
@ -688,7 +589,9 @@ impl Plugin for CorePlugin {
|
|||
};
|
||||
app.insert_resource(config)
|
||||
.register_type::<CardinalDirection>()
|
||||
.add_plugins(PhysicsPlugins::default().with_length_unit(config.pixels_per_unit as f32))
|
||||
.add_plugins(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(
|
||||
config.pixels_per_unit as f32,
|
||||
))
|
||||
.add_systems(Startup, setup)
|
||||
.add_systems(Update, sync_config);
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use std::{error::Error, fmt::Debug, hash::Hash, marker::PhantomData};
|
||||
|
||||
use avian2d::prelude::*;
|
||||
use bevy::prelude::*;
|
||||
use bevy_rapier2d::prelude::*;
|
||||
use bevy_tts::Tts;
|
||||
use leafwing_input_manager::prelude::*;
|
||||
|
||||
|
@ -281,7 +281,7 @@ fn exploration_changed_announcement<ExplorationType, MapData>(
|
|||
names: Query<&Name>,
|
||||
types: Query<&ExplorationType>,
|
||||
mappables: Query<&Mappable>,
|
||||
spatial_query: SpatialQuery,
|
||||
rapier_context: Res<RapierContext>,
|
||||
) -> Result<(), Box<dyn Error>>
|
||||
where
|
||||
ExplorationType: Component + Copy + Into<String>,
|
||||
|
@ -290,7 +290,7 @@ where
|
|||
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
|
||||
let coordinates = coordinates.trunc();
|
||||
let point = **exploring;
|
||||
let shape = Collider::rectangle(0.5 - f32::EPSILON, 0.5 - f32::EPSILON);
|
||||
let shape = Collider::cuboid(0.5 - f32::EPSILON, 0.5 - 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))
|
||||
|
@ -305,22 +305,20 @@ where
|
|||
commands.entity(entity).remove::<ExplorationFocused>();
|
||||
}
|
||||
let exploring = Vec2::new(exploring.x(), exploring.y());
|
||||
spatial_query.shape_intersections_callback(
|
||||
&shape,
|
||||
rapier_context.intersections_with_shape(
|
||||
exploring,
|
||||
0.,
|
||||
SpatialQueryFilter::default(),
|
||||
&shape,
|
||||
QueryFilter::new().predicate(&|v| explorable.get(v).is_ok()),
|
||||
|entity| {
|
||||
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((*t).into());
|
||||
}
|
||||
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((*t).into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
|
|
39
src/map.rs
39
src/map.rs
|
@ -1,13 +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::PointLike, exploration::Mappable, visibility::Visible};
|
||||
use crate::{
|
||||
core::{Area, PointLike},
|
||||
exploration::Mappable,
|
||||
visibility::Visible,
|
||||
};
|
||||
|
||||
#[derive(Component, Clone, Default, Deref, DerefMut)]
|
||||
pub struct Map<D: 'static + Clone + Default + Send + Sync>(pub MapgenMap<D>);
|
||||
|
@ -73,9 +80,9 @@ impl ITileType for Tile {
|
|||
|
||||
#[derive(Bundle, Default)]
|
||||
pub struct PortalBundle {
|
||||
pub transform: TransformBundle,
|
||||
pub portal: Portal,
|
||||
pub mappable: Mappable,
|
||||
pub transform: TransformBundle,
|
||||
}
|
||||
|
||||
#[derive(Bundle, Clone, Default)]
|
||||
|
@ -91,6 +98,7 @@ pub struct TileBundle {
|
|||
pub transform: TransformBundle,
|
||||
pub collider: Collider,
|
||||
pub rigid_body: RigidBody,
|
||||
pub active_collision_types: ActiveCollisionTypes,
|
||||
pub map_obstruction: MapObstruction,
|
||||
}
|
||||
|
||||
|
@ -98,9 +106,12 @@ impl Default for TileBundle {
|
|||
fn default() -> Self {
|
||||
Self {
|
||||
transform: default(),
|
||||
collider: Collider::rectangle(0.5, 0.5),
|
||||
rigid_body: RigidBody::Static,
|
||||
map_obstruction: 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -118,28 +129,34 @@ impl TileBundle {
|
|||
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: Vec2) -> Self {
|
||||
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,
|
||||
transform: Transform::from_translation(position.extend(0.)).into(),
|
||||
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::rectangle(
|
||||
let collider = Collider::cuboid(
|
||||
rect.width() as f32 / 2. + 0.5,
|
||||
rect.height() as f32 / 2. + 0.5,
|
||||
);
|
||||
let position = Vec2::new(rect.center().x(), rect.center().y());
|
||||
let position = (rect.center().x(), rect.center().y());
|
||||
Self::new(collider, position)
|
||||
}
|
||||
}
|
||||
|
@ -315,7 +332,7 @@ fn spawn_portal_colliders<D: 'static + Clone + Default + Send + Sync>(
|
|||
for portal_entity in &portals {
|
||||
commands
|
||||
.entity(portal_entity)
|
||||
.insert((Collider::rectangle(0.5, 0.5), Sensor));
|
||||
.insert((Collider::cuboid(0.5, 0.5), Sensor));
|
||||
}
|
||||
commands.entity(entity).remove::<SpawnColliders>();
|
||||
}
|
||||
|
|
|
@ -1,17 +1,14 @@
|
|||
#![allow(clippy::map_entry)]
|
||||
|
||||
use std::{collections::HashMap, error::Error, f32::consts::PI, fmt::Debug, hash::Hash};
|
||||
|
||||
use avian2d::prelude::*;
|
||||
use bevy::prelude::*;
|
||||
use bevy::{math::CompassQuadrant, prelude::*};
|
||||
use bevy_rapier2d::prelude::*;
|
||||
use bevy_tts::Tts;
|
||||
use leafwing_input_manager::prelude::*;
|
||||
|
||||
use crate::{
|
||||
core::{Angle, CardinalDirection, GlobalTransformExt, Player, TransformExt},
|
||||
core::{Area, CardinalDirection, GlobalTransformExt, Player, TransformExt},
|
||||
error::error_handler,
|
||||
log::Log,
|
||||
map::Zone,
|
||||
utils::target_and_other,
|
||||
};
|
||||
|
||||
|
@ -77,7 +74,7 @@ impl Default for StrafeMovementFactor {
|
|||
|
||||
#[derive(Component, Clone, Copy, Default, Debug, Deref, DerefMut, Reflect)]
|
||||
#[reflect(Component)]
|
||||
pub struct RotationSpeed(pub Angle);
|
||||
pub struct RotationSpeed(pub Rot2);
|
||||
|
||||
#[derive(Deref, DerefMut)]
|
||||
struct SnapTimer(Timer);
|
||||
|
@ -119,26 +116,28 @@ fn snap(
|
|||
continue;
|
||||
} else if actions.just_pressed(&NavigationAction::SnapLeft) {
|
||||
snap_timers.insert(entity, SnapTimer::default());
|
||||
transform.rotation = Quat::from_rotation_z(match direction {
|
||||
CardinalDirection::North => PI,
|
||||
CardinalDirection::East => PI / 2.,
|
||||
CardinalDirection::South => 0.,
|
||||
CardinalDirection::West => -PI / 2.,
|
||||
transform.rotation = Quat::from_rotation_z(match direction.0 {
|
||||
CompassQuadrant::North => PI,
|
||||
CompassQuadrant::East => PI / 2.,
|
||||
CompassQuadrant::South => 0.,
|
||||
CompassQuadrant::West => -PI / 2.,
|
||||
});
|
||||
} else if actions.just_pressed(&NavigationAction::SnapRight) {
|
||||
snap_timers.insert(entity, SnapTimer::default());
|
||||
transform.rotation = Quat::from_rotation_z(match direction {
|
||||
CardinalDirection::North => 0.,
|
||||
CardinalDirection::East => -PI / 2.,
|
||||
CardinalDirection::South => PI,
|
||||
CardinalDirection::West => PI / 2.,
|
||||
transform.rotation = Quat::from_rotation_z(match direction.0 {
|
||||
CompassQuadrant::North => 0.,
|
||||
CompassQuadrant::East => -PI / 2.,
|
||||
CompassQuadrant::South => PI,
|
||||
CompassQuadrant::West => PI / 2.,
|
||||
});
|
||||
} else if actions.just_pressed(&NavigationAction::SnapReverse) {
|
||||
snap_timers.insert(entity, SnapTimer::default());
|
||||
transform.rotate(Quat::from_rotation_z(PI));
|
||||
} else if actions.just_pressed(&NavigationAction::SnapCardinal) {
|
||||
let yaw: Angle = direction.into();
|
||||
let yaw = yaw.radians();
|
||||
println!("Direction: {direction:?}");
|
||||
let yaw: Rot2 = direction.into();
|
||||
let yaw = yaw.as_radians();
|
||||
println!("Yaw: {yaw}");
|
||||
transform.rotation = Quat::from_rotation_z(yaw);
|
||||
tts.speak(direction.to_string(), true)?;
|
||||
}
|
||||
|
@ -154,14 +153,13 @@ fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
|
|||
}
|
||||
|
||||
fn controls(
|
||||
spatial_query: SpatialQuery,
|
||||
rapier_context: Res<RapierContext>,
|
||||
time: Res<Time>,
|
||||
snap_timers: Res<SnapTimers>,
|
||||
sensors: Query<Entity, With<Sensor>>,
|
||||
mut query: Query<(
|
||||
Entity,
|
||||
&mut ActionState<NavigationAction>,
|
||||
&mut LinearVelocity,
|
||||
&mut Velocity,
|
||||
&Speed,
|
||||
Option<&RotationSpeed>,
|
||||
Option<&BackwardMovementFactor>,
|
||||
|
@ -216,21 +214,24 @@ fn controls(
|
|||
// println!("{entity:?}: SetLinearVelocity: {velocity:?}");
|
||||
actions.set_axis_pair(&NavigationAction::SetLinearVelocity, move_velocity);
|
||||
}
|
||||
if velocity.0 != actions.axis_pair(&NavigationAction::SetLinearVelocity) {
|
||||
**velocity = actions.axis_pair(&NavigationAction::SetLinearVelocity);
|
||||
if velocity.linvel != actions.axis_pair(&NavigationAction::SetLinearVelocity) {
|
||||
velocity.linvel = actions.axis_pair(&NavigationAction::SetLinearVelocity);
|
||||
}
|
||||
if actions.axis_pair(&NavigationAction::Translate) != Vec2::ZERO {
|
||||
let pair = actions.axis_pair(&NavigationAction::Translate);
|
||||
let dir = Dir2::new_unchecked(pair.normalize());
|
||||
if spatial_query
|
||||
if rapier_context
|
||||
.cast_shape(
|
||||
collider,
|
||||
transform.translation.truncate(),
|
||||
transform.yaw().radians(),
|
||||
dir,
|
||||
1.,
|
||||
true,
|
||||
SpatialQueryFilter::from_excluded_entities(&sensors),
|
||||
transform.yaw().as_radians(),
|
||||
pair,
|
||||
collider,
|
||||
ShapeCastOptions {
|
||||
max_time_of_impact: 1.,
|
||||
..default()
|
||||
},
|
||||
QueryFilter::new()
|
||||
.exclude_sensors()
|
||||
.exclude_collider(entity),
|
||||
)
|
||||
.is_none()
|
||||
{
|
||||
|
@ -241,7 +242,7 @@ fn controls(
|
|||
if !snap_timers.contains_key(&entity) {
|
||||
if let Some(rotation_speed) = rotation_speed {
|
||||
let delta =
|
||||
-rotation_speed.radians() * actions.clamped_value(&NavigationAction::Rotate);
|
||||
rotation_speed.as_radians() * actions.clamped_value(&NavigationAction::Rotate);
|
||||
actions.set_value(&NavigationAction::SetAngularVelocity, delta);
|
||||
}
|
||||
}
|
||||
|
@ -289,32 +290,27 @@ fn remove_direction(
|
|||
|
||||
fn speak_direction(
|
||||
mut tts: ResMut<Tts>,
|
||||
player: Query<
|
||||
(&CardinalDirection, Ref<CardinalDirection>),
|
||||
(With<Player>, Changed<CardinalDirection>),
|
||||
>,
|
||||
player: Query<&CardinalDirection, (With<Player>, Changed<CardinalDirection>)>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
if let Ok((direction, change)) = player.get_single() {
|
||||
if !change.is_added() {
|
||||
let direction: String = (*direction).into();
|
||||
tts.speak(direction, true)?;
|
||||
}
|
||||
if let Ok(direction) = player.get_single() {
|
||||
let direction: String = (*direction).into();
|
||||
tts.speak(direction, true)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn add_speed(
|
||||
mut commands: Commands,
|
||||
query: Query<Entity, (Added<Speed>, Without<LinearVelocity>)>,
|
||||
) {
|
||||
fn add_speed(mut commands: Commands, query: Query<Entity, (Added<Speed>, Without<Velocity>)>) {
|
||||
for entity in &query {
|
||||
commands.entity(entity).insert(LinearVelocity::default());
|
||||
commands.entity(entity).insert(Velocity {
|
||||
linvel: Vec2::ZERO,
|
||||
..default()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn log_zone_descriptions(
|
||||
mut events: EventReader<Collision>,
|
||||
zones: Query<(&ColliderAabb, Option<&Name>), With<Zone>>,
|
||||
fn log_area_descriptions(
|
||||
mut events: EventReader<CollisionEvent>,
|
||||
areas: Query<(&Area, Option<&Name>)>,
|
||||
players: Query<&Player>,
|
||||
config: Res<NavigationPlugin>,
|
||||
mut log: Query<&mut Log>,
|
||||
|
@ -322,21 +318,19 @@ fn log_zone_descriptions(
|
|||
if !config.log_area_descriptions {
|
||||
return;
|
||||
}
|
||||
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))
|
||||
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())
|
||||
{
|
||||
if players.contains(other) {
|
||||
if let Ok((aabb, area_name)) = zones.get(area) {
|
||||
if players.get(other).is_ok() {
|
||||
if let Ok((aabb, area_name)) = areas.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.size().x, aabb.size().y))
|
||||
Some(format!("{}-by-{} area", aabb.extents().x, aabb.extents().y))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
@ -394,6 +388,6 @@ impl Plugin for NavigationPlugin {
|
|||
FixedUpdate,
|
||||
(tick_snap_timers, speak_direction.pipe(error_handler)),
|
||||
)
|
||||
.add_systems(PostUpdate, (remove_direction, log_zone_descriptions));
|
||||
.add_systems(PostUpdate, (remove_direction, log_area_descriptions));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,11 +1,19 @@
|
|||
use avian2d::prelude::*;
|
||||
use bevy::{prelude::*, utils::HashMap};
|
||||
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 leafwing_input_manager::{plugin::InputManagerSystem, prelude::*};
|
||||
use pathfinding::prelude::*;
|
||||
|
||||
use crate::{
|
||||
core::{PointLike, TransformExt},
|
||||
map::Map,
|
||||
map::{Map, MapObstruction},
|
||||
navigation::{NavigationAction, RotationSpeed, Speed},
|
||||
};
|
||||
|
||||
|
@ -18,6 +26,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));
|
||||
|
@ -82,94 +93,178 @@ 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(
|
||||
mut commands: Commands,
|
||||
spatial_query: SpatialQuery,
|
||||
mut query: Query<
|
||||
rapier_context: Res<RapierContext>,
|
||||
obstructions: Query<&RapierColliderHandle, With<MapObstruction>>,
|
||||
query: Query<
|
||||
(
|
||||
Entity,
|
||||
&RapierColliderHandle,
|
||||
&Destination,
|
||||
&Transform,
|
||||
&Collider,
|
||||
Option<&CostMap>,
|
||||
Option<&mut ActionState<NegotiatePathAction>>,
|
||||
),
|
||||
Changed<Destination>,
|
||||
>,
|
||||
) {
|
||||
for (entity, destination, start, collider, cost_map, actions) in &mut query {
|
||||
for (entity, handle, destination, coordinates, shape, cost_map) in &query {
|
||||
trace!("{entity}: destination: {destination:?}");
|
||||
if start.i32() == **destination {
|
||||
if coordinates.i32() == **destination {
|
||||
trace!("{entity}: remove1");
|
||||
commands
|
||||
.entity(entity)
|
||||
.remove::<Path>()
|
||||
.remove::<NoPath>()
|
||||
.remove::<Calculating>()
|
||||
.remove::<Destination>();
|
||||
continue;
|
||||
}
|
||||
trace!(
|
||||
"{entity:?}: Calculating path from {:?} to {destination:?}",
|
||||
start.translation.truncate().i32()
|
||||
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:?}",
|
||||
start.i32(),
|
||||
coordinates.i32(),
|
||||
);
|
||||
commands.entity(entity).remove::<Path>().remove::<NoPath>();
|
||||
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;
|
||||
if !spatial_query
|
||||
.shape_intersections(
|
||||
collider,
|
||||
start.translation.truncate(),
|
||||
start.yaw().radians(),
|
||||
SpatialQueryFilter::default(),
|
||||
)
|
||||
.is_empty()
|
||||
{
|
||||
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));
|
||||
}
|
||||
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();
|
||||
}
|
||||
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>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -177,7 +272,10 @@ fn calculate_path(
|
|||
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::<Path>().remove::<NoPath>();
|
||||
commands
|
||||
.remove::<Calculating>()
|
||||
.remove::<Path>()
|
||||
.remove::<NoPath>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -185,7 +283,7 @@ fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Des
|
|||
fn negotiate_path(
|
||||
mut commands: Commands,
|
||||
time: Res<Time>,
|
||||
spatial_query: SpatialQuery,
|
||||
physics_config: Res<RapierConfiguration>,
|
||||
mut query: Query<(
|
||||
Entity,
|
||||
Option<&mut ActionState<NegotiatePathAction>>,
|
||||
|
@ -196,7 +294,11 @@ fn negotiate_path(
|
|||
&Speed,
|
||||
Option<&RotationSpeed>,
|
||||
)>,
|
||||
rapier_context: Res<RapierContext>,
|
||||
) {
|
||||
if !physics_config.physics_pipeline_active || !physics_config.query_pipeline_active {
|
||||
return;
|
||||
}
|
||||
for (
|
||||
entity,
|
||||
actions,
|
||||
|
@ -240,15 +342,19 @@ fn negotiate_path(
|
|||
"{entity:?}: Direction: {direction:?}, Distance: {}",
|
||||
(next - start).length()
|
||||
);
|
||||
if spatial_query
|
||||
if rapier_context
|
||||
.cast_shape(
|
||||
collider,
|
||||
start,
|
||||
transform.yaw().radians(),
|
||||
Dir2::new_unchecked(direction.normalize()),
|
||||
direction.length(),
|
||||
true,
|
||||
SpatialQueryFilter::default(),
|
||||
transform.yaw().as_radians(),
|
||||
direction,
|
||||
collider,
|
||||
ShapeCastOptions {
|
||||
max_time_of_impact: 1.,
|
||||
..default()
|
||||
},
|
||||
QueryFilter::new()
|
||||
.exclude_sensors()
|
||||
.exclude_collider(entity),
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
|
@ -326,7 +432,7 @@ impl Plugin for PathfindingPlugin {
|
|||
.register_type::<NoPath>()
|
||||
.register_type::<Path>()
|
||||
.register_type::<CostMap>()
|
||||
.add_systems(PreUpdate, negotiate_path)
|
||||
.add_systems(PreUpdate, (poll_tasks, negotiate_path).chain())
|
||||
.add_systems(
|
||||
PreUpdate,
|
||||
(actions, calculate_path)
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -4,12 +4,14 @@ use std::{
|
|||
marker::PhantomData,
|
||||
};
|
||||
|
||||
use avian2d::prelude::*;
|
||||
use bevy::prelude::*;
|
||||
|
||||
use bevy_rapier2d::{na::Isometry2, parry::bounding_volume::BoundingVolume};
|
||||
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},
|
||||
|
@ -49,22 +51,29 @@ impl Viewshed {
|
|||
viewer_entity: &Entity,
|
||||
visible_entities: &mut VisibleEntities,
|
||||
start: &Vec2,
|
||||
spatial_query: &SpatialQuery,
|
||||
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::rectangle(self.range as f32, self.range as f32);
|
||||
spatial_query.shape_intersections_callback(&shape, *start, 0., default(), |entity| {
|
||||
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) {
|
||||
boxes.push(collider.aabb(transform.translation().truncate(), 0.));
|
||||
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 vision_distance = vision_distance::Circle::new(self.range);
|
||||
let shape = Collider::rectangle(0.49, 0.49);
|
||||
let shape = Collider::cuboid(0.49, 0.49);
|
||||
let size = (
|
||||
(start.x.abs() + self.range as f32 * 2.) as u32,
|
||||
(start.y.abs() + self.range as f32 * 2.) as u32,
|
||||
|
@ -87,14 +96,15 @@ impl Viewshed {
|
|||
coord_entities = entities.clone();
|
||||
*opacity
|
||||
} else {
|
||||
let aabb = shape.aabb(shape_pos, 0.);
|
||||
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;
|
||||
spatial_query.shape_intersections_callback(
|
||||
&shape,
|
||||
rapier_context.intersections_with_shape(
|
||||
shape_pos,
|
||||
0.,
|
||||
&shape,
|
||||
default(),
|
||||
|entity| {
|
||||
if let Ok((visible, _, _)) = visible_query.get(entity) {
|
||||
|
@ -120,7 +130,7 @@ impl Viewshed {
|
|||
if let Some((k, v)) = to_insert {
|
||||
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();
|
||||
coord_entities.retain(|e| e != viewer_entity);
|
||||
let opacity = coord_entities
|
||||
|
@ -272,6 +282,7 @@ where
|
|||
|
||||
fn update_viewshed(
|
||||
mut commands: Commands,
|
||||
config: Res<RapierConfiguration>,
|
||||
visible: Query<(&Visible, &Collider, &GlobalTransform)>,
|
||||
mut viewers: Query<(
|
||||
Entity,
|
||||
|
@ -279,8 +290,11 @@ fn update_viewshed(
|
|||
&mut VisibleEntities,
|
||||
&GlobalTransform,
|
||||
)>,
|
||||
spatial_query: SpatialQuery,
|
||||
rapier_context: Res<RapierContext>,
|
||||
) {
|
||||
if !config.query_pipeline_active {
|
||||
return;
|
||||
}
|
||||
let mut cache = default();
|
||||
for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers {
|
||||
viewshed.update(
|
||||
|
@ -288,7 +302,7 @@ fn update_viewshed(
|
|||
&viewer_entity,
|
||||
&mut visible_entities,
|
||||
&viewer_transform.translation().truncate(),
|
||||
&spatial_query,
|
||||
&rapier_context,
|
||||
&visible,
|
||||
&mut cache,
|
||||
);
|
||||
|
@ -304,7 +318,7 @@ fn remove_visible(
|
|||
&mut VisibleEntities,
|
||||
&GlobalTransform,
|
||||
)>,
|
||||
spatial_query: SpatialQuery,
|
||||
rapier_context: Res<RapierContext>,
|
||||
visible: Query<(&Visible, &Collider, &GlobalTransform)>,
|
||||
) {
|
||||
if !removed.is_empty() {
|
||||
|
@ -319,7 +333,7 @@ fn remove_visible(
|
|||
&viewer_entity,
|
||||
&mut visible_entities,
|
||||
&start.translation().truncate(),
|
||||
&spatial_query,
|
||||
&rapier_context,
|
||||
&visible,
|
||||
&mut cache,
|
||||
);
|
||||
|
|
Loading…
Reference in New Issue
Block a user