Compare commits
No commits in common. "224a4043e2e4b07001f4a2922154bf78f8af52f3" and "0554e2dded9d44a7d4adcf7a322d7b583918ee63" have entirely different histories.
224a4043e2
...
0554e2dded
37
Cargo.toml
37
Cargo.toml
|
@ -13,43 +13,10 @@ speech_dispatcher_0_9 = ["bevy_tts/speech_dispatcher_0_9"]
|
||||||
speech_dispatcher_0_10 = ["bevy_tts/speech_dispatcher_0_10"]
|
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.bevy]
|
|
||||||
version = "0.14"
|
|
||||||
default-features = false
|
|
||||||
features = [
|
|
||||||
"android_shared_stdcxx",
|
|
||||||
"animation",
|
|
||||||
"bevy_animation",
|
|
||||||
"bevy_asset",
|
|
||||||
"bevy_color",
|
|
||||||
"bevy_core_pipeline",
|
|
||||||
"bevy_gilrs",
|
|
||||||
"bevy_gizmos",
|
|
||||||
"bevy_gltf",
|
|
||||||
"bevy_pbr",
|
|
||||||
"bevy_render",
|
|
||||||
"bevy_scene",
|
|
||||||
"bevy_sprite",
|
|
||||||
"bevy_state",
|
|
||||||
"bevy_text",
|
|
||||||
"bevy_ui",
|
|
||||||
"bevy_winit",
|
|
||||||
"default_font",
|
|
||||||
"hdr",
|
|
||||||
"ktx2",
|
|
||||||
"multi_threaded",
|
|
||||||
"png",
|
|
||||||
"smaa_luts",
|
|
||||||
"sysinfo_plugin",
|
|
||||||
"tonemapping_luts",
|
|
||||||
"webgl2",
|
|
||||||
"x11",
|
|
||||||
"zstd",
|
|
||||||
]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
avian2d = "0.1"
|
avian2d = "0.1"
|
||||||
bevy_synthizer = "0.8"
|
bevy = "0.14"
|
||||||
|
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"
|
||||||
here_be_dragons = { version = "0.3", features = ["serde"] }
|
here_be_dragons = { version = "0.3", features = ["serde"] }
|
||||||
|
|
377
src/core.rs
377
src/core.rs
|
@ -2,6 +2,7 @@ use std::{
|
||||||
cmp::{max, min},
|
cmp::{max, min},
|
||||||
f32::consts::PI,
|
f32::consts::PI,
|
||||||
fmt::Display,
|
fmt::Display,
|
||||||
|
ops::Sub,
|
||||||
sync::RwLock,
|
sync::RwLock,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -12,100 +13,180 @@ use avian2d::{
|
||||||
},
|
},
|
||||||
prelude::*,
|
prelude::*,
|
||||||
};
|
};
|
||||||
use bevy::{
|
use bevy::{app::PluginGroupBuilder, math::FloatOrd, prelude::*};
|
||||||
app::PluginGroupBuilder,
|
|
||||||
math::{CompassOctant, CompassQuadrant, 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};
|
||||||
|
|
||||||
fn relative_desc(rot: &Rot2) -> String {
|
#[derive(Clone, Copy, Debug, Reflect)]
|
||||||
let mode = RELATIVE_DIRECTION_MODE.read().unwrap();
|
pub enum Angle {
|
||||||
match rot.as_radians() {
|
Degrees(f32),
|
||||||
v if v <= PI / 12. && v > -PI / 12. => "ahead",
|
Radians(f32),
|
||||||
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()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deref, DerefMut, Reflect)]
|
impl Default for Angle {
|
||||||
pub struct MovementDirection(CompassOctant);
|
fn default() -> Self {
|
||||||
|
Self::Radians(0.)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<Rot2> for MovementDirection {
|
impl Angle {
|
||||||
fn from(rot: Rot2) -> Self {
|
pub fn degrees(&self) -> f32 {
|
||||||
use CompassOctant::*;
|
use Angle::*;
|
||||||
MovementDirection(match rot.as_radians() {
|
let mut degrees: f32 = match self {
|
||||||
h if h > -PI / 8. && h <= PI / 8. => East,
|
Degrees(v) => *v,
|
||||||
h if h > PI / 8. && h <= 3. * PI / 8. => NorthEast,
|
Radians(v) => v.to_degrees(),
|
||||||
h if h > 3. * PI / 8. && h <= 5. * PI / 8. => North,
|
};
|
||||||
h if h > 5. * PI / 8. && h <= 7. * PI / 8. => NorthWest,
|
while degrees < 0. {
|
||||||
h if h > 7. * PI / 8. || h <= -7. * PI / 8. => West,
|
degrees += 360.;
|
||||||
h if h > -7. * PI / 8. && h <= -5. * PI / 8. => SouthWest,
|
}
|
||||||
h if h > -5. * PI / 8. && h <= -3. * PI / 8. => South,
|
while degrees >= 360. {
|
||||||
h if h > -3. * PI / 8. && h <= -PI / 8. => SouthEast,
|
degrees %= 360.;
|
||||||
_ => West,
|
}
|
||||||
})
|
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,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -113,18 +194,25 @@ impl From<Rot2> for MovementDirection {
|
||||||
#[allow(clippy::from_over_into)]
|
#[allow(clippy::from_over_into)]
|
||||||
impl Into<String> for MovementDirection {
|
impl Into<String> for MovementDirection {
|
||||||
fn into(self) -> String {
|
fn into(self) -> String {
|
||||||
use CompassOctant::*;
|
use MovementDirection::*;
|
||||||
match self.0 {
|
match self {
|
||||||
North => "north",
|
North => "north".to_string(),
|
||||||
NorthEast => "northeast",
|
NorthNortheast => "north northeast".to_string(),
|
||||||
East => "east",
|
Northeast => "northeast".to_string(),
|
||||||
SouthEast => "southeast",
|
EastNortheast => "east northeast".to_string(),
|
||||||
South => "south",
|
East => "east".to_string(),
|
||||||
SouthWest => "southwest",
|
EastSoutheast => "east southeast".to_string(),
|
||||||
West => "west",
|
Southeast => "southeast".to_string(),
|
||||||
NorthWest => "northwest",
|
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(),
|
||||||
}
|
}
|
||||||
.into()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -135,36 +223,38 @@ impl Display for MovementDirection {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Component, Clone, Copy, Debug, Eq, PartialEq, Deref, DerefMut, Reflect)]
|
#[derive(Component, Clone, Copy, Default, Debug, Eq, PartialEq, Reflect)]
|
||||||
#[reflect(Component)]
|
#[reflect(Component)]
|
||||||
pub struct CardinalDirection(pub CompassQuadrant);
|
pub enum CardinalDirection {
|
||||||
|
#[default]
|
||||||
|
North,
|
||||||
|
East,
|
||||||
|
South,
|
||||||
|
West,
|
||||||
|
}
|
||||||
|
|
||||||
impl Default for CardinalDirection {
|
impl From<Angle> for CardinalDirection {
|
||||||
fn default() -> Self {
|
fn from(angle: Angle) -> Self {
|
||||||
Self(CompassQuadrant::East)
|
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 From<Rot2> for CardinalDirection {
|
impl From<&CardinalDirection> for Angle {
|
||||||
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 {
|
fn from(direction: &CardinalDirection) -> Self {
|
||||||
use CompassQuadrant::*;
|
use CardinalDirection::*;
|
||||||
match direction.0 {
|
match direction {
|
||||||
North => Rot2::radians(PI / 2.),
|
North => Angle::Radians(PI / 2.),
|
||||||
East => Rot2::radians(0.),
|
East => Angle::Radians(0.),
|
||||||
South => Rot2::radians(-PI / 2.),
|
South => Angle::Radians(PI * 1.5),
|
||||||
West => Rot2::radians(PI),
|
West => Angle::Radians(PI),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -173,8 +263,8 @@ impl From<&CardinalDirection> for Rot2 {
|
||||||
#[allow(clippy::from_over_into)]
|
#[allow(clippy::from_over_into)]
|
||||||
impl Into<String> for CardinalDirection {
|
impl Into<String> for CardinalDirection {
|
||||||
fn into(self) -> String {
|
fn into(self) -> String {
|
||||||
use CompassQuadrant::*;
|
use CardinalDirection::*;
|
||||||
match self.0 {
|
match self {
|
||||||
North => "north".to_string(),
|
North => "north".to_string(),
|
||||||
East => "east".to_string(),
|
East => "east".to_string(),
|
||||||
South => "south".to_string(),
|
South => "south".to_string(),
|
||||||
|
@ -254,26 +344,24 @@ pub trait PointLike {
|
||||||
self.distance_squared(other).sqrt()
|
self.distance_squared(other).sqrt()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn bearing(&self, other: &dyn PointLike) -> Rot2 {
|
fn bearing(&self, other: &dyn PointLike) -> Angle {
|
||||||
let y = other.y() - self.y();
|
let y = other.y() - self.y();
|
||||||
let x = other.x() - self.x();
|
let x = other.x() - self.x();
|
||||||
Rot2::radians(y.atan2(x))
|
Angle::Radians(y.atan2(x))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn direction(&self, other: &dyn PointLike) -> MovementDirection {
|
fn direction(&self, other: &dyn PointLike) -> MovementDirection {
|
||||||
self.bearing(other).into()
|
self.bearing(other).into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn direction_and_distance(&self, other: &dyn PointLike, yaw: Option<Rot2>) -> String {
|
fn direction_and_distance(&self, other: &dyn PointLike, yaw: Option<Angle>) -> String {
|
||||||
let mut tokens: Vec<String> = vec![];
|
let mut tokens: Vec<String> = vec![];
|
||||||
let distance = self.distance(other).round() as i32;
|
let distance = self.distance(other).round() as i32;
|
||||||
if distance > 0 {
|
if distance > 0 {
|
||||||
let tile_or_tiles = if distance == 1 { "tile" } else { "tiles" };
|
let tile_or_tiles = if distance == 1 { "tile" } else { "tiles" };
|
||||||
let direction: String = if let Some(yaw) = yaw {
|
let direction: String = if let Some(yaw) = yaw {
|
||||||
let yaw = yaw.as_radians();
|
let bearing = self.bearing(other);
|
||||||
let bearing = self.bearing(other).as_radians();
|
(bearing - yaw).relative_desc()
|
||||||
let rot = Rot2::radians(bearing - yaw);
|
|
||||||
relative_desc(&rot)
|
|
||||||
} else {
|
} else {
|
||||||
self.direction(other).into()
|
self.direction(other).into()
|
||||||
};
|
};
|
||||||
|
@ -395,18 +483,18 @@ impl From<&dyn PointLike> for (i32, i32) {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait TransformExt {
|
pub trait TransformExt {
|
||||||
fn yaw(&self) -> Rot2;
|
fn yaw(&self) -> Angle;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TransformExt for Transform {
|
impl TransformExt for Transform {
|
||||||
fn yaw(&self) -> Rot2 {
|
fn yaw(&self) -> Angle {
|
||||||
let forward = self.right();
|
let forward = self.right();
|
||||||
Rot2::radians(forward.y.atan2(forward.x))
|
Angle::Radians(forward.y.atan2(forward.x))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait GlobalTransformExt {
|
pub trait GlobalTransformExt {
|
||||||
fn yaw(&self) -> Rot2;
|
fn yaw(&self) -> Angle;
|
||||||
|
|
||||||
fn closest_points(
|
fn closest_points(
|
||||||
&self,
|
&self,
|
||||||
|
@ -424,9 +512,9 @@ pub trait GlobalTransformExt {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlobalTransformExt for GlobalTransform {
|
impl GlobalTransformExt for GlobalTransform {
|
||||||
fn yaw(&self) -> Rot2 {
|
fn yaw(&self) -> Angle {
|
||||||
let forward = self.right();
|
let forward = self.right();
|
||||||
Rot2::radians(forward.y.atan2(forward.x))
|
Angle::Radians(forward.y.atan2(forward.x))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn closest_points(
|
fn closest_points(
|
||||||
|
@ -438,11 +526,11 @@ impl GlobalTransformExt for GlobalTransform {
|
||||||
let scale = PHYSICS_SCALE.read().unwrap();
|
let scale = PHYSICS_SCALE.read().unwrap();
|
||||||
let pos1 = Isometry::new(
|
let pos1 = Isometry::new(
|
||||||
(self.translation() / *scale).xy().into(),
|
(self.translation() / *scale).xy().into(),
|
||||||
self.yaw().as_radians(),
|
self.yaw().radians(),
|
||||||
);
|
);
|
||||||
let pos2 = Isometry::new(
|
let pos2 = Isometry::new(
|
||||||
(other.translation() / *scale).xy().into(),
|
(other.translation() / *scale).xy().into(),
|
||||||
other.yaw().as_radians(),
|
other.yaw().radians(),
|
||||||
);
|
);
|
||||||
closest_points(
|
closest_points(
|
||||||
&pos1,
|
&pos1,
|
||||||
|
@ -463,11 +551,11 @@ impl GlobalTransformExt for GlobalTransform {
|
||||||
let scale = PHYSICS_SCALE.read().unwrap();
|
let scale = PHYSICS_SCALE.read().unwrap();
|
||||||
let pos1 = Isometry::new(
|
let pos1 = Isometry::new(
|
||||||
(self.translation() / *scale).xy().into(),
|
(self.translation() / *scale).xy().into(),
|
||||||
self.yaw().as_radians(),
|
self.yaw().radians(),
|
||||||
);
|
);
|
||||||
let pos2 = Isometry::new(
|
let pos2 = Isometry::new(
|
||||||
(other.translation() / *scale).xy().into(),
|
(other.translation() / *scale).xy().into(),
|
||||||
other.yaw().as_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(
|
let distance = distance(
|
||||||
|
@ -482,10 +570,9 @@ impl GlobalTransformExt for GlobalTransform {
|
||||||
if let ClosestPoints::WithinMargin(p1, p2) = closest {
|
if let ClosestPoints::WithinMargin(p1, p2) = closest {
|
||||||
let p1 = (p1.x, p1.y);
|
let p1 = (p1.x, p1.y);
|
||||||
let p2 = (p2.x, p2.y);
|
let p2 = (p2.x, p2.y);
|
||||||
let bearing = p1.bearing(&p2).as_radians();
|
let bearing = p1.bearing(&p2);
|
||||||
let yaw = self.yaw().as_radians();
|
let yaw = self.yaw();
|
||||||
let rot = Rot2::radians(bearing - yaw);
|
let direction = (bearing - yaw).relative_desc();
|
||||||
let direction = relative_desc(&rot);
|
|
||||||
format!("{direction} {distance} {tile_or_tiles}")
|
format!("{direction} {distance} {tile_or_tiles}")
|
||||||
} else {
|
} else {
|
||||||
format!("{} {}", distance, tile_or_tiles)
|
format!("{} {}", distance, tile_or_tiles)
|
||||||
|
|
|
@ -1,9 +1,4 @@
|
||||||
use std::{
|
use std::{error::Error, fmt::Debug, hash::Hash, marker::PhantomData};
|
||||||
error::Error,
|
|
||||||
fmt::{Debug, Display},
|
|
||||||
hash::Hash,
|
|
||||||
marker::PhantomData,
|
|
||||||
};
|
|
||||||
|
|
||||||
use avian2d::prelude::*;
|
use avian2d::prelude::*;
|
||||||
use bevy::prelude::*;
|
use bevy::prelude::*;
|
||||||
|
@ -187,7 +182,7 @@ fn exploration_type_changed_announcement<ExplorationType>(
|
||||||
>,
|
>,
|
||||||
) -> Result<(), Box<dyn Error>>
|
) -> Result<(), Box<dyn Error>>
|
||||||
where
|
where
|
||||||
ExplorationType: Component + Default + Copy + Display,
|
ExplorationType: Component + Default + Copy + Into<String>,
|
||||||
{
|
{
|
||||||
for (focused, changed) in &focused {
|
for (focused, changed) in &focused {
|
||||||
if changed.is_added() {
|
if changed.is_added() {
|
||||||
|
@ -195,7 +190,8 @@ where
|
||||||
}
|
}
|
||||||
match &focused.0 {
|
match &focused.0 {
|
||||||
Some(v) => {
|
Some(v) => {
|
||||||
tts.speak(format!("{v}"), true)?;
|
let v: String = (*v).into();
|
||||||
|
tts.speak(v, true)?;
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
tts.speak("Everything", true)?;
|
tts.speak("Everything", true)?;
|
||||||
|
@ -288,7 +284,7 @@ fn exploration_changed_announcement<ExplorationType, MapData>(
|
||||||
spatial_query: SpatialQuery,
|
spatial_query: SpatialQuery,
|
||||||
) -> Result<(), Box<dyn Error>>
|
) -> Result<(), Box<dyn Error>>
|
||||||
where
|
where
|
||||||
ExplorationType: Component + Copy + Display,
|
ExplorationType: Component + Copy + Into<String>,
|
||||||
MapData: 'static + Clone + Default + Send + Sync,
|
MapData: 'static + Clone + Default + Send + Sync,
|
||||||
{
|
{
|
||||||
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
|
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
|
||||||
|
@ -323,7 +319,7 @@ where
|
||||||
}
|
}
|
||||||
if tokens.is_empty() {
|
if tokens.is_empty() {
|
||||||
if let Ok(t) = types.get(entity) {
|
if let Ok(t) = types.get(entity) {
|
||||||
tokens.push(format!("{t}"));
|
tokens.push((*t).into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -391,7 +387,7 @@ pub struct Exploration;
|
||||||
|
|
||||||
impl<ExplorationType, MapData> Plugin for ExplorationPlugin<ExplorationType, MapData>
|
impl<ExplorationType, MapData> Plugin for ExplorationPlugin<ExplorationType, MapData>
|
||||||
where
|
where
|
||||||
ExplorationType: 'static + Component + Default + Copy + Ord + PartialEq + Display,
|
ExplorationType: 'static + Component + Default + Copy + Ord + PartialEq + Into<String>,
|
||||||
MapData: 'static + Clone + Default + Send + Sync,
|
MapData: 'static + Clone + Default + Send + Sync,
|
||||||
{
|
{
|
||||||
fn build(&self, app: &mut App) {
|
fn build(&self, app: &mut App) {
|
||||||
|
|
|
@ -3,12 +3,12 @@
|
||||||
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 avian2d::prelude::*;
|
||||||
use bevy::{math::CompassQuadrant, prelude::*};
|
use bevy::prelude::*;
|
||||||
use bevy_tts::Tts;
|
use bevy_tts::Tts;
|
||||||
use leafwing_input_manager::prelude::*;
|
use leafwing_input_manager::prelude::*;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
core::{CardinalDirection, GlobalTransformExt, Player, TransformExt},
|
core::{Angle, CardinalDirection, GlobalTransformExt, Player, TransformExt},
|
||||||
error::error_handler,
|
error::error_handler,
|
||||||
log::Log,
|
log::Log,
|
||||||
map::Zone,
|
map::Zone,
|
||||||
|
@ -77,7 +77,7 @@ impl Default for StrafeMovementFactor {
|
||||||
|
|
||||||
#[derive(Component, Clone, Copy, Default, Debug, Deref, DerefMut, Reflect)]
|
#[derive(Component, Clone, Copy, Default, Debug, Deref, DerefMut, Reflect)]
|
||||||
#[reflect(Component)]
|
#[reflect(Component)]
|
||||||
pub struct RotationSpeed(pub Rot2);
|
pub struct RotationSpeed(pub Angle);
|
||||||
|
|
||||||
#[derive(Deref, DerefMut)]
|
#[derive(Deref, DerefMut)]
|
||||||
struct SnapTimer(Timer);
|
struct SnapTimer(Timer);
|
||||||
|
@ -102,6 +102,7 @@ impl Default for Speed {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn snap(
|
fn snap(
|
||||||
|
mut tts: ResMut<Tts>,
|
||||||
mut snap_timers: ResMut<SnapTimers>,
|
mut snap_timers: ResMut<SnapTimers>,
|
||||||
mut query: Query<
|
mut query: Query<
|
||||||
(
|
(
|
||||||
|
@ -112,40 +113,37 @@ fn snap(
|
||||||
),
|
),
|
||||||
With<Player>,
|
With<Player>,
|
||||||
>,
|
>,
|
||||||
) {
|
) -> Result<(), Box<dyn Error>> {
|
||||||
for (entity, actions, mut transform, direction) in &mut query {
|
for (entity, actions, mut transform, direction) in &mut query {
|
||||||
if snap_timers.contains_key(&entity) {
|
if snap_timers.contains_key(&entity) {
|
||||||
continue;
|
continue;
|
||||||
} else if actions.just_pressed(&NavigationAction::SnapLeft) {
|
} else if actions.just_pressed(&NavigationAction::SnapLeft) {
|
||||||
snap_timers.insert(entity, SnapTimer::default());
|
snap_timers.insert(entity, SnapTimer::default());
|
||||||
transform.rotation = Quat::from_rotation_z(match direction.0 {
|
transform.rotation = Quat::from_rotation_z(match direction {
|
||||||
CompassQuadrant::North => PI,
|
CardinalDirection::North => PI,
|
||||||
CompassQuadrant::East => PI / 2.,
|
CardinalDirection::East => PI / 2.,
|
||||||
CompassQuadrant::South => 0.,
|
CardinalDirection::South => 0.,
|
||||||
CompassQuadrant::West => -PI / 2.,
|
CardinalDirection::West => -PI / 2.,
|
||||||
});
|
});
|
||||||
} else if actions.just_pressed(&NavigationAction::SnapRight) {
|
} else if actions.just_pressed(&NavigationAction::SnapRight) {
|
||||||
snap_timers.insert(entity, SnapTimer::default());
|
snap_timers.insert(entity, SnapTimer::default());
|
||||||
transform.rotation = Quat::from_rotation_z(match direction.0 {
|
transform.rotation = Quat::from_rotation_z(match direction {
|
||||||
CompassQuadrant::North => 0.,
|
CardinalDirection::North => 0.,
|
||||||
CompassQuadrant::East => -PI / 2.,
|
CardinalDirection::East => -PI / 2.,
|
||||||
CompassQuadrant::South => PI,
|
CardinalDirection::South => PI,
|
||||||
CompassQuadrant::West => PI / 2.,
|
CardinalDirection::West => PI / 2.,
|
||||||
});
|
});
|
||||||
} else if actions.just_pressed(&NavigationAction::SnapReverse) {
|
} else if actions.just_pressed(&NavigationAction::SnapReverse) {
|
||||||
snap_timers.insert(entity, SnapTimer::default());
|
snap_timers.insert(entity, SnapTimer::default());
|
||||||
transform.rotate(Quat::from_rotation_z(PI));
|
transform.rotate(Quat::from_rotation_z(PI));
|
||||||
} else if actions.just_pressed(&NavigationAction::SnapCardinal) {
|
} else if actions.just_pressed(&NavigationAction::SnapCardinal) {
|
||||||
println!("Direction: {direction:?}");
|
let yaw: Angle = direction.into();
|
||||||
let yaw: Rot2 = direction.into();
|
let yaw = yaw.radians();
|
||||||
let yaw = yaw.as_radians();
|
transform.rotation = Quat::from_rotation_z(yaw);
|
||||||
println!("Yaw: {yaw}");
|
tts.speak(direction.to_string(), true)?;
|
||||||
let rotation = Quat::from_rotation_z(yaw);
|
|
||||||
if transform.rotation != rotation {
|
|
||||||
transform.rotation = rotation;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
|
fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
|
||||||
|
@ -228,7 +226,7 @@ fn controls(
|
||||||
.cast_shape(
|
.cast_shape(
|
||||||
collider,
|
collider,
|
||||||
transform.translation.truncate(),
|
transform.translation.truncate(),
|
||||||
transform.yaw().as_radians(),
|
transform.yaw().radians(),
|
||||||
dir,
|
dir,
|
||||||
1.,
|
1.,
|
||||||
true,
|
true,
|
||||||
|
@ -243,7 +241,7 @@ fn controls(
|
||||||
if !snap_timers.contains_key(&entity) {
|
if !snap_timers.contains_key(&entity) {
|
||||||
if let Some(rotation_speed) = rotation_speed {
|
if let Some(rotation_speed) = rotation_speed {
|
||||||
let delta =
|
let delta =
|
||||||
rotation_speed.as_radians() * actions.clamped_value(&NavigationAction::Rotate);
|
-rotation_speed.radians() * actions.clamped_value(&NavigationAction::Rotate);
|
||||||
actions.set_value(&NavigationAction::SetAngularVelocity, delta);
|
actions.set_value(&NavigationAction::SetAngularVelocity, delta);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -291,11 +289,16 @@ fn remove_direction(
|
||||||
|
|
||||||
fn speak_direction(
|
fn speak_direction(
|
||||||
mut tts: ResMut<Tts>,
|
mut tts: ResMut<Tts>,
|
||||||
player: Query<&CardinalDirection, (With<Player>, Changed<CardinalDirection>)>,
|
player: Query<
|
||||||
|
(&CardinalDirection, Ref<CardinalDirection>),
|
||||||
|
(With<Player>, Changed<CardinalDirection>),
|
||||||
|
>,
|
||||||
) -> Result<(), Box<dyn Error>> {
|
) -> Result<(), Box<dyn Error>> {
|
||||||
if let Ok(direction) = player.get_single() {
|
if let Ok((direction, change)) = player.get_single() {
|
||||||
let direction: String = (*direction).into();
|
if !change.is_added() {
|
||||||
tts.speak(direction, true)?;
|
let direction: String = (*direction).into();
|
||||||
|
tts.speak(direction, true)?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -381,7 +384,12 @@ impl Plugin for NavigationPlugin {
|
||||||
.register_type::<Speed>()
|
.register_type::<Speed>()
|
||||||
.add_plugins(InputManagerPlugin::<NavigationAction>::default())
|
.add_plugins(InputManagerPlugin::<NavigationAction>::default())
|
||||||
.add_systems(PreUpdate, (update_direction, add_speed))
|
.add_systems(PreUpdate, (update_direction, add_speed))
|
||||||
.add_systems(Update, (snap, controls).chain().in_set(Movement))
|
.add_systems(
|
||||||
|
Update,
|
||||||
|
(snap.pipe(error_handler), controls)
|
||||||
|
.chain()
|
||||||
|
.in_set(Movement),
|
||||||
|
)
|
||||||
.add_systems(
|
.add_systems(
|
||||||
FixedUpdate,
|
FixedUpdate,
|
||||||
(tick_snap_timers, speak_direction.pipe(error_handler)),
|
(tick_snap_timers, speak_direction.pipe(error_handler)),
|
||||||
|
|
|
@ -139,7 +139,7 @@ fn calculate_path(
|
||||||
.shape_intersections(
|
.shape_intersections(
|
||||||
collider,
|
collider,
|
||||||
start.translation.truncate(),
|
start.translation.truncate(),
|
||||||
start.yaw().as_radians(),
|
start.yaw().radians(),
|
||||||
SpatialQueryFilter::default(),
|
SpatialQueryFilter::default(),
|
||||||
)
|
)
|
||||||
.is_empty()
|
.is_empty()
|
||||||
|
@ -244,7 +244,7 @@ fn negotiate_path(
|
||||||
.cast_shape(
|
.cast_shape(
|
||||||
collider,
|
collider,
|
||||||
start,
|
start,
|
||||||
transform.yaw().as_radians(),
|
transform.yaw().radians(),
|
||||||
Dir2::new_unchecked(direction.normalize()),
|
Dir2::new_unchecked(direction.normalize()),
|
||||||
direction.length(),
|
direction.length(),
|
||||||
true,
|
true,
|
||||||
|
|
|
@ -75,43 +75,42 @@ fn update<S>(
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
let Some(entity) = entity else {
|
if let Some(entity) = entity {
|
||||||
continue;
|
if visible.contains(&entity) {
|
||||||
};
|
if let Some(interval) = icon.interval.as_mut() {
|
||||||
if visible.contains(&entity) {
|
if interval.finished() {
|
||||||
if let Some(interval) = icon.interval.as_mut() {
|
interval.reset();
|
||||||
if interval.finished() {
|
continue;
|
||||||
interval.reset();
|
} else if interval.fraction() == 0. {
|
||||||
continue;
|
sound.generator = None;
|
||||||
} else if interval.fraction() == 0. {
|
}
|
||||||
sound.playback_position = 0.;
|
interval.tick(time.delta());
|
||||||
|
}
|
||||||
|
if sound.audio != icon.audio {
|
||||||
|
sound.audio = icon.audio.clone();
|
||||||
|
}
|
||||||
|
if sound.gain != icon.gain {
|
||||||
|
sound.gain = icon.gain;
|
||||||
|
}
|
||||||
|
if sound.pitch != icon.pitch {
|
||||||
|
sound.pitch = icon.pitch;
|
||||||
|
}
|
||||||
|
let looping = icon.interval.is_none();
|
||||||
|
if sound.looping != looping {
|
||||||
|
sound.looping = looping;
|
||||||
|
}
|
||||||
|
if sound.paused {
|
||||||
|
sound.paused = false;
|
||||||
sound.generator = None;
|
sound.generator = None;
|
||||||
}
|
}
|
||||||
interval.tick(time.delta());
|
} else if !sound.paused {
|
||||||
}
|
sound.paused = true;
|
||||||
if sound.audio != icon.audio {
|
if let Some(interval) = icon.interval.as_mut() {
|
||||||
sound.audio = icon.audio.clone();
|
interval.reset();
|
||||||
}
|
}
|
||||||
if sound.gain != icon.gain {
|
|
||||||
sound.gain = icon.gain;
|
|
||||||
}
|
|
||||||
if sound.pitch != icon.pitch {
|
|
||||||
sound.pitch = icon.pitch;
|
|
||||||
}
|
|
||||||
let looping = icon.interval.is_none();
|
|
||||||
if sound.looping != looping {
|
|
||||||
sound.looping = looping;
|
|
||||||
}
|
|
||||||
if sound.paused {
|
|
||||||
sound.paused = false;
|
|
||||||
sound.playback_position = 0.;
|
|
||||||
sound.generator = None;
|
|
||||||
}
|
|
||||||
} else if !sound.paused {
|
|
||||||
sound.paused = true;
|
|
||||||
if let Some(interval) = icon.interval.as_mut() {
|
|
||||||
interval.reset();
|
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
panic!("Should not happen");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -22,7 +22,7 @@ pub use volumetric::Volumetric;
|
||||||
|
|
||||||
pub struct SoundPlugins<'a, S>(std::marker::PhantomData<&'a S>);
|
pub struct SoundPlugins<'a, S>(std::marker::PhantomData<&'a S>);
|
||||||
|
|
||||||
impl<S> Default for SoundPlugins<'_, S> {
|
impl<'a, S> Default for SoundPlugins<'a, S> {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self(std::marker::PhantomData)
|
Self(std::marker::PhantomData)
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,46 +9,31 @@ use crate::core::GlobalTransformExt;
|
||||||
pub struct Volumetric;
|
pub struct Volumetric;
|
||||||
|
|
||||||
fn update(
|
fn update(
|
||||||
mut commands: Commands,
|
|
||||||
listener: Query<(&Collider, &GlobalTransform), With<Listener>>,
|
listener: Query<(&Collider, &GlobalTransform), With<Listener>>,
|
||||||
mut sounds: Query<(Entity, &Sound, &Parent, Option<&mut Transform>), With<Volumetric>>,
|
mut sounds: Query<(&Sound, &Parent, &mut Transform), With<Volumetric>>,
|
||||||
colliders: Query<(&Collider, &GlobalTransform)>,
|
colliders: Query<(&Collider, &GlobalTransform)>,
|
||||||
) {
|
) {
|
||||||
if let Ok((listener_collider, listener_global_transform)) = listener.get_single() {
|
if let Ok((listener_collider, listener_global_transform)) = listener.get_single() {
|
||||||
for (sound_entity, sound, parent, sound_transform) in &mut sounds {
|
for (sound, parent, mut sound_transform) in &mut sounds {
|
||||||
if sound.paused {
|
if sound.paused {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let Ok((sound_collider, sound_global_transform)) = colliders.get(**parent) else {
|
if let Ok((sound_collider, sound_global_transform)) = colliders.get(**parent) {
|
||||||
continue;
|
let closest = listener_global_transform.closest_points(
|
||||||
};
|
listener_collider,
|
||||||
let closest = listener_global_transform.closest_points(
|
sound_global_transform,
|
||||||
listener_collider,
|
sound_collider,
|
||||||
sound_global_transform,
|
);
|
||||||
sound_collider,
|
if let ClosestPoints::WithinMargin(_p1, p2) = closest {
|
||||||
);
|
let p2 = Vec3::new(p2.x, p2.y, 0.);
|
||||||
if let ClosestPoints::WithinMargin(_p1, p2) = closest {
|
|
||||||
if let Some(mut sound_transform) = sound_transform {
|
|
||||||
sound_transform.translation.x = p2.x - sound_global_transform.translation().x;
|
sound_transform.translation.x = p2.x - sound_global_transform.translation().x;
|
||||||
sound_transform.translation.y = p2.y - sound_global_transform.translation().y;
|
sound_transform.translation.y = p2.y - sound_global_transform.translation().y;
|
||||||
} else {
|
} else if closest == ClosestPoints::Intersecting {
|
||||||
let sound_translation = Vec3::new(
|
sound_transform.translation.x = listener_global_transform.translation().x
|
||||||
p2.x - sound_global_transform.translation().x,
|
- sound_global_transform.translation().x;
|
||||||
p2.y - sound_global_transform.translation().y,
|
sound_transform.translation.y = listener_global_transform.translation().y
|
||||||
0.,
|
- sound_global_transform.translation().y;
|
||||||
);
|
|
||||||
commands
|
|
||||||
.entity(sound_entity)
|
|
||||||
.insert(TransformBundle::from_transform(
|
|
||||||
Transform::from_translation(sound_translation),
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
} else if closest == ClosestPoints::Intersecting && sound_transform.is_some() {
|
|
||||||
println!("Clearing volumetric");
|
|
||||||
commands
|
|
||||||
.entity(sound_entity)
|
|
||||||
.remove::<Transform>()
|
|
||||||
.remove::<GlobalTransform>();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
use std::{
|
use std::{
|
||||||
|
cell::RefCell,
|
||||||
collections::{HashMap, HashSet},
|
collections::{HashMap, HashSet},
|
||||||
marker::PhantomData,
|
marker::PhantomData,
|
||||||
};
|
};
|
||||||
|
@ -48,17 +49,92 @@ impl Viewshed {
|
||||||
viewer_entity: &Entity,
|
viewer_entity: &Entity,
|
||||||
visible_entities: &mut VisibleEntities,
|
visible_entities: &mut VisibleEntities,
|
||||||
start: &Vec2,
|
start: &Vec2,
|
||||||
opacity_map: &OpacityMap,
|
|
||||||
sensors: &Query<&Sensor>,
|
|
||||||
spatial_query: &SpatialQuery,
|
spatial_query: &SpatialQuery,
|
||||||
|
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| {
|
||||||
|
if let Ok((_, collider, transform)) = visible_query.get(entity) {
|
||||||
|
boxes.push(collider.aabb(transform.translation().truncate(), 0.));
|
||||||
|
}
|
||||||
|
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::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,
|
||||||
);
|
);
|
||||||
let visibility_grid = VisibilityGrid(size, *viewer_entity, opacity_map.clone());
|
let visibility_grid = VisibilityGrid(
|
||||||
|
size,
|
||||||
|
RefCell::new(Box::new(|coord: Coord| {
|
||||||
|
let shape_pos = Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5);
|
||||||
|
// println!("Checking {coord:?}: {shape_pos:?}");
|
||||||
|
if start.distance(&shape_pos) > self.range as f32 {
|
||||||
|
// println!("Out of range");
|
||||||
|
return u8::MAX;
|
||||||
|
}
|
||||||
|
let mut coord_entities = HashSet::new();
|
||||||
|
let mut to_insert = None;
|
||||||
|
let opacity = if let Some((opacity, entities)) =
|
||||||
|
cache.borrow().get(&(coord.x, coord.y))
|
||||||
|
{
|
||||||
|
// println!("Cache hit: {opacity:?}: {entities:?}");
|
||||||
|
coord_entities = entities.clone();
|
||||||
|
*opacity
|
||||||
|
} else {
|
||||||
|
let aabb = shape.aabb(shape_pos, 0.);
|
||||||
|
if boxes.iter().any(|b| b.intersects(&aabb)) {
|
||||||
|
// println!("Hit");
|
||||||
|
let mut opacity = 0;
|
||||||
|
spatial_query.shape_intersections_callback(
|
||||||
|
&shape,
|
||||||
|
shape_pos,
|
||||||
|
0.,
|
||||||
|
default(),
|
||||||
|
|entity| {
|
||||||
|
if let Ok((visible, _, _)) = visible_query.get(entity) {
|
||||||
|
// println!(
|
||||||
|
// "{entity:?}: {visible:?}: {:?}",
|
||||||
|
// transform.translation().truncate()
|
||||||
|
// );
|
||||||
|
coord_entities.insert(entity);
|
||||||
|
opacity = opacity.max(**visible);
|
||||||
|
}
|
||||||
|
true
|
||||||
|
},
|
||||||
|
);
|
||||||
|
to_insert = Some(((coord.x, coord.y), (opacity, coord_entities.clone())));
|
||||||
|
// println!("New opacity: {opacity}");
|
||||||
|
opacity
|
||||||
|
} else {
|
||||||
|
// println!("No hits, 0");
|
||||||
|
to_insert = Some(((coord.x, coord.y), default()));
|
||||||
|
0
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some((k, v)) = to_insert {
|
||||||
|
cache.borrow_mut().insert(k, v);
|
||||||
|
}
|
||||||
|
if coord_entities.contains(viewer_entity) {
|
||||||
|
let mut coord_entities = coord_entities.clone();
|
||||||
|
coord_entities.retain(|e| e != viewer_entity);
|
||||||
|
let opacity = coord_entities
|
||||||
|
.iter()
|
||||||
|
.map(|v| visible_query.get(*v).unwrap().0 .0)
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0);
|
||||||
|
// println!("Viewer hit, removing viewer opacity: {opacity}");
|
||||||
|
opacity
|
||||||
|
} else {
|
||||||
|
opacity
|
||||||
|
}
|
||||||
|
})),
|
||||||
|
);
|
||||||
let mut new_visible = HashSet::new();
|
let mut new_visible = HashSet::new();
|
||||||
let mut new_visible_entities = HashSet::new();
|
let mut new_visible_entities = HashSet::new();
|
||||||
// println!("Start: {viewer_entity}");
|
// println!("Start: {viewer_entity}");
|
||||||
|
@ -70,36 +146,9 @@ impl Viewshed {
|
||||||
u8::MAX,
|
u8::MAX,
|
||||||
|coord, _directions, _visibility| {
|
|coord, _directions, _visibility| {
|
||||||
new_visible.insert((coord.x, coord.y));
|
new_visible.insert((coord.x, coord.y));
|
||||||
let coord = IVec2::new(coord.x, coord.y);
|
if let Some((_, entities)) = cache.borrow().get(&(coord.x, coord.y)) {
|
||||||
// println!("Checking {coord:?}");
|
|
||||||
if let Some((_, entities)) = opacity_map.get(&coord) {
|
|
||||||
for e in entities {
|
for e in entities {
|
||||||
if entities.len() == 1 || sensors.contains(*e) {
|
new_visible_entities.insert(*e);
|
||||||
new_visible_entities.insert(*e);
|
|
||||||
} else {
|
|
||||||
let 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 = Dir2::new_unchecked((coord - *start).normalize());
|
|
||||||
// println!("Casting from {coord}");
|
|
||||||
spatial_query.cast_ray_predicate(
|
|
||||||
*start,
|
|
||||||
dir,
|
|
||||||
dir.distance(*start),
|
|
||||||
true,
|
|
||||||
default(),
|
|
||||||
&|entity| {
|
|
||||||
if *e != entity && entities.contains(e) {
|
|
||||||
// println!("{entities:?} contains {e} and hits at {:?}", hit.point);
|
|
||||||
// commands.entity(*e).log_components();
|
|
||||||
*should_push.borrow_mut() = false;
|
|
||||||
}
|
|
||||||
true
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if *should_push.borrow() {
|
|
||||||
new_visible_entities.insert(*e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -112,6 +161,8 @@ impl Viewshed {
|
||||||
commands.trigger_targets(VisibilityChanged::Lost(*lost), *viewer_entity);
|
commands.trigger_targets(VisibilityChanged::Lost(*lost), *viewer_entity);
|
||||||
}
|
}
|
||||||
for gained in new_visible_entities.difference(visible_entities) {
|
for gained in new_visible_entities.difference(visible_entities) {
|
||||||
|
// println!("transition: {:?} gains {:?}", viewer_entity,
|
||||||
|
// gained);
|
||||||
commands.trigger_targets(VisibilityChanged::Gained(*gained), *viewer_entity);
|
commands.trigger_targets(VisibilityChanged::Gained(*gained), *viewer_entity);
|
||||||
}
|
}
|
||||||
**visible_entities = new_visible_entities;
|
**visible_entities = new_visible_entities;
|
||||||
|
@ -139,82 +190,6 @@ impl Visible {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Resource, Clone, Deref, DerefMut, Default)]
|
|
||||||
pub struct OpacityMap(HashMap<IVec2, (u8, HashSet<Entity>)>);
|
|
||||||
|
|
||||||
impl OpacityMap {
|
|
||||||
fn update(
|
|
||||||
&mut self,
|
|
||||||
spatial_query: &SpatialQuery,
|
|
||||||
coordinates: HashSet<IVec2>,
|
|
||||||
visible: &Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
|
|
||||||
) {
|
|
||||||
self.retain(|k, _| !coordinates.contains(k));
|
|
||||||
let shape = Collider::rectangle(0.49, 0.49);
|
|
||||||
for coords in &coordinates {
|
|
||||||
let shape_pos = Vec2::new(coords.x as f32 + 0.5, coords.y as f32 + 0.5);
|
|
||||||
let mut opacity = 0;
|
|
||||||
let mut coord_entities = HashSet::new();
|
|
||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn update_opacity_map(
|
|
||||||
mut opacity_map: ResMut<OpacityMap>,
|
|
||||||
spatial_query: SpatialQuery,
|
|
||||||
query: Query<
|
|
||||||
(Entity, &GlobalTransform, &Collider, &Visible),
|
|
||||||
Or<(Changed<GlobalTransform>, Changed<Visible>)>,
|
|
||||||
>,
|
|
||||||
visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
|
|
||||||
) {
|
|
||||||
let mut to_update = HashSet::new();
|
|
||||||
for (entity, transform, collider, _) in &query {
|
|
||||||
// println!(
|
|
||||||
// "Updating {entity} at {:?}",
|
|
||||||
// transform.translation().truncate().as_ivec2()
|
|
||||||
// );
|
|
||||||
let mut prev = HashSet::new();
|
|
||||||
for (k, v) in opacity_map.iter() {
|
|
||||||
if v.1.contains(&entity) {
|
|
||||||
// println!("Also updating {k} because it contained entity");
|
|
||||||
prev.insert(*k);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut current = HashSet::new();
|
|
||||||
current.insert(transform.translation().truncate().as_ivec2());
|
|
||||||
let aabb = collider.aabb(transform.translation().truncate(), transform);
|
|
||||||
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, y));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if prev != current {
|
|
||||||
to_update.extend(prev);
|
|
||||||
to_update.extend(current);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
opacity_map.update(&spatial_query, to_update, &visible);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
|
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
|
||||||
pub struct VisibleEntities(HashSet<Entity>);
|
pub struct VisibleEntities(HashSet<Entity>);
|
||||||
|
|
||||||
|
@ -276,9 +251,12 @@ fn viewshed_removed(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct VisibilityGrid(pub (u32, u32), pub Entity, pub OpacityMap);
|
pub struct VisibilityGrid<F>(pub (u32, u32), pub RefCell<Box<F>>);
|
||||||
|
|
||||||
impl InputGrid for VisibilityGrid {
|
impl<F> InputGrid for VisibilityGrid<F>
|
||||||
|
where
|
||||||
|
F: FnMut(Coord) -> u8,
|
||||||
|
{
|
||||||
type Grid = (u32, u32);
|
type Grid = (u32, u32);
|
||||||
|
|
||||||
type Opacity = u8;
|
type Opacity = u8;
|
||||||
|
@ -288,43 +266,31 @@ impl InputGrid for VisibilityGrid {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity {
|
fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity {
|
||||||
// println!("Checking {coord:?}");
|
(self.1.borrow_mut())(coord)
|
||||||
if let Some((opacity, entities)) = self.2.get(&IVec2::new(coord.x, coord.y)) {
|
|
||||||
if entities.len() == 1 && entities.contains(&self.1) {
|
|
||||||
// println!("Hit viewer, 0");
|
|
||||||
0
|
|
||||||
} else {
|
|
||||||
// println!("{opacity:?}");
|
|
||||||
*opacity
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// println!("Miss, 0");
|
|
||||||
0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_viewshed(
|
fn update_viewshed(
|
||||||
mut commands: Commands,
|
mut commands: Commands,
|
||||||
|
visible: Query<(&Visible, &Collider, &GlobalTransform)>,
|
||||||
mut viewers: Query<(
|
mut viewers: Query<(
|
||||||
Entity,
|
Entity,
|
||||||
&mut Viewshed,
|
&mut Viewshed,
|
||||||
&mut VisibleEntities,
|
&mut VisibleEntities,
|
||||||
&GlobalTransform,
|
&GlobalTransform,
|
||||||
)>,
|
)>,
|
||||||
opacity_map: Res<OpacityMap>,
|
|
||||||
sensors: Query<&Sensor>,
|
|
||||||
spatial_query: SpatialQuery,
|
spatial_query: SpatialQuery,
|
||||||
) {
|
) {
|
||||||
|
let mut cache = default();
|
||||||
for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers {
|
for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers {
|
||||||
viewshed.update(
|
viewshed.update(
|
||||||
&mut commands,
|
&mut commands,
|
||||||
&viewer_entity,
|
&viewer_entity,
|
||||||
&mut visible_entities,
|
&mut visible_entities,
|
||||||
&viewer_transform.translation().truncate(),
|
&viewer_transform.translation().truncate(),
|
||||||
&opacity_map,
|
|
||||||
&sensors,
|
|
||||||
&spatial_query,
|
&spatial_query,
|
||||||
|
&visible,
|
||||||
|
&mut cache,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -338,21 +304,11 @@ fn remove_visible(
|
||||||
&mut VisibleEntities,
|
&mut VisibleEntities,
|
||||||
&GlobalTransform,
|
&GlobalTransform,
|
||||||
)>,
|
)>,
|
||||||
sensors: Query<&Sensor>,
|
|
||||||
spatial_query: SpatialQuery,
|
spatial_query: SpatialQuery,
|
||||||
mut opacity_map: ResMut<OpacityMap>,
|
visible: Query<(&Visible, &Collider, &GlobalTransform)>,
|
||||||
visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
|
|
||||||
) {
|
) {
|
||||||
if !removed.is_empty() {
|
if !removed.is_empty() {
|
||||||
let mut to_update = HashSet::new();
|
let mut cache = default();
|
||||||
for e in removed.read() {
|
|
||||||
for (k, v) in opacity_map.iter() {
|
|
||||||
if v.1.contains(&e) {
|
|
||||||
to_update.insert(*k);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
opacity_map.update(&spatial_query, to_update, &visible);
|
|
||||||
for removed in removed.read() {
|
for removed in removed.read() {
|
||||||
for (viewer_entity, mut viewshed, mut visible_entities, start) in &mut viewers {
|
for (viewer_entity, mut viewshed, mut visible_entities, start) in &mut viewers {
|
||||||
if !visible_entities.contains(&removed) {
|
if !visible_entities.contains(&removed) {
|
||||||
|
@ -363,9 +319,9 @@ fn remove_visible(
|
||||||
&viewer_entity,
|
&viewer_entity,
|
||||||
&mut visible_entities,
|
&mut visible_entities,
|
||||||
&start.translation().truncate(),
|
&start.translation().truncate(),
|
||||||
&opacity_map,
|
|
||||||
&sensors,
|
|
||||||
&spatial_query,
|
&spatial_query,
|
||||||
|
&visible,
|
||||||
|
&mut cache,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -401,6 +357,7 @@ fn log_visible(
|
||||||
}
|
}
|
||||||
if let Ok((viewer_transform, viewer_collider)) = viewers.get(trigger.entity()) {
|
if let Ok((viewer_transform, viewer_collider)) = viewers.get(trigger.entity()) {
|
||||||
if let Ok((name, viewed_transform, viewed_collider)) = visible.get(*entity) {
|
if let Ok((name, viewed_transform, viewed_collider)) = visible.get(*entity) {
|
||||||
|
// println!("Gain {name}: {entity}");
|
||||||
let location = if let (Some(viewer_collider), Some(viewed_collider)) =
|
let location = if let (Some(viewer_collider), Some(viewed_collider)) =
|
||||||
(viewer_collider, viewed_collider)
|
(viewer_collider, viewed_collider)
|
||||||
{
|
{
|
||||||
|
@ -431,17 +388,15 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Default for VisibilityPlu
|
||||||
|
|
||||||
impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlugin<MapData> {
|
impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlugin<MapData> {
|
||||||
fn build(&self, app: &mut App) {
|
fn build(&self, app: &mut App) {
|
||||||
app.init_resource::<OpacityMap>()
|
app.add_systems(
|
||||||
.add_systems(FixedPreUpdate, update_opacity_map.before(update_viewshed))
|
FixedPreUpdate,
|
||||||
.add_systems(
|
(
|
||||||
FixedPreUpdate,
|
add_visibility_indices::<MapData>,
|
||||||
(
|
update_viewshed,
|
||||||
add_visibility_indices::<MapData>,
|
update_revealed_tiles::<MapData>,
|
||||||
update_viewshed,
|
),
|
||||||
update_revealed_tiles::<MapData>,
|
)
|
||||||
),
|
.add_systems(FixedPostUpdate, (viewshed_removed, remove_visible))
|
||||||
)
|
.observe(log_visible);
|
||||||
.add_systems(FixedPostUpdate, (viewshed_removed, remove_visible))
|
|
||||||
.observe(log_visible);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user