Get rid of Coordinates.

This commit is contained in:
Nolan Darilek 2022-05-10 13:56:49 -05:00
parent f3d03d531a
commit 13d1cb0734
7 changed files with 51 additions and 180 deletions

View File

@ -3,115 +3,16 @@ use std::{
f32::consts::PI, f32::consts::PI,
fmt::Display, fmt::Display,
marker::PhantomData, marker::PhantomData,
ops::{Add, AddAssign, Sub, SubAssign}, ops::Sub,
sync::RwLock, sync::RwLock,
}; };
use bevy::{core::FloatOrd, ecs::query::WorldQuery, prelude::*, transform::TransformSystem}; use bevy::{core::FloatOrd, ecs::query::WorldQuery, prelude::*};
use bevy_rapier2d::prelude::*; use bevy_rapier2d::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};
#[derive(
Component, Clone, Copy, Debug, Default, Deref, DerefMut, PartialEq, PartialOrd, Reflect,
)]
#[reflect(Component)]
pub struct Coordinates(pub (f32, f32));
impl Coordinates {
pub fn from_transform(transform: &Transform, config: &CoreConfig) -> Self {
Self((
transform.x() / config.pixels_per_unit as f32,
transform.y() / config.pixels_per_unit as f32,
))
}
pub fn to_transform(&self, config: &CoreConfig) -> Transform {
Transform::from_translation(Vec3::new(
self.0 .0 * config.pixels_per_unit as f32,
self.0 .1 * config.pixels_per_unit as f32,
0.,
))
}
}
impl Add for Coordinates {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self((self.0 .0 + rhs.0 .0, self.0 .1 + rhs.0 .1))
}
}
impl AddAssign for Coordinates {
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs
}
}
impl Sub for Coordinates {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self((self.0 .0 - rhs.0 .0, self.0 .1 - rhs.0 .1))
}
}
impl SubAssign for Coordinates {
fn sub_assign(&mut self, rhs: Self) {
*self = *self - rhs
}
}
impl From<Vec2> for Coordinates {
fn from(v: Vec2) -> Self {
Self((v.x, v.y))
}
}
impl From<Vec3> for Coordinates {
fn from(v: Vec3) -> Self {
Self((v.x, v.y))
}
}
impl From<Coordinates> for Vec2 {
fn from(c: Coordinates) -> Self {
Vec2::new(c.0 .0, c.0 .1)
}
}
impl From<Coordinates> for Vec3 {
fn from(c: Coordinates) -> Self {
Vec3::new(c.0 .0, c.0 .1, 0.)
}
}
impl From<(f32, f32)> for Coordinates {
fn from(v: (f32, f32)) -> Self {
Coordinates((v.0, v.1))
}
}
impl From<(i32, i32)> for Coordinates {
fn from(v: (i32, i32)) -> Self {
Coordinates((v.0 as f32, v.1 as f32))
}
}
impl From<(u32, u32)> for Coordinates {
fn from(v: (u32, u32)) -> Self {
Coordinates((v.0 as f32, v.1 as f32))
}
}
impl From<(usize, usize)> for Coordinates {
fn from(v: (usize, usize)) -> Self {
Coordinates((v.0 as f32, v.1 as f32))
}
}
#[derive(Clone, Copy, Debug, Reflect)] #[derive(Clone, Copy, Debug, Reflect)]
pub enum Angle { pub enum Angle {
Degrees(f32), Degrees(f32),
@ -467,6 +368,16 @@ impl PointLike for Transform {
} }
} }
impl PointLike for &Transform {
fn x(&self) -> f32 {
self.translation.x
}
fn y(&self) -> f32 {
self.translation.y
}
}
impl PointLike for Vec2 { impl PointLike for Vec2 {
fn x(&self) -> f32 { fn x(&self) -> f32 {
self.x self.x
@ -507,16 +418,6 @@ impl PointLike for (usize, usize) {
} }
} }
impl PointLike for &Coordinates {
fn x(&self) -> f32 {
self.0 .0
}
fn y(&self) -> f32 {
self.0 .1
}
}
impl PointLike for here_be_dragons::geometry::Point { impl PointLike for here_be_dragons::geometry::Point {
fn x(&self) -> f32 { fn x(&self) -> f32 {
self.x as f32 self.x as f32
@ -542,8 +443,6 @@ macro_rules! impl_pointlike_for_tuple_component {
}; };
} }
impl_pointlike_for_tuple_component!(Coordinates);
impl From<&dyn PointLike> for (i32, i32) { impl From<&dyn PointLike> for (i32, i32) {
fn from(val: &dyn PointLike) -> Self { fn from(val: &dyn PointLike) -> Self {
val.i32() val.i32()
@ -618,22 +517,6 @@ fn setup(core_config: Res<CoreConfig>) {
*mode = core_config.relative_direction_mode; *mode = core_config.relative_direction_mode;
} }
fn copy_coordinates_to_transform(
config: Res<CoreConfig>,
mut query: Query<(&Coordinates, &mut Transform), Changed<Transform>>,
) {
for (coordinates, mut transform) in query.iter_mut() {
let x = coordinates.0 .0 * config.pixels_per_unit as f32;
if transform.translation.x != x {
transform.translation.x = x;
}
let y = coordinates.0 .1 * config.pixels_per_unit as f32;
if transform.translation.y != y {
transform.translation.y = y;
}
}
}
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub struct CoreConfig { pub struct CoreConfig {
pub relative_direction_mode: RelativeDirectionMode, pub relative_direction_mode: RelativeDirectionMode,
@ -670,15 +553,10 @@ impl<RapierUserData: 'static + WorldQuery + Send + Sync> Plugin for CorePlugin<R
app.insert_resource(CoreConfig::default()); app.insert_resource(CoreConfig::default());
} }
let config = *app.world.get_resource::<CoreConfig>().unwrap(); let config = *app.world.get_resource::<CoreConfig>().unwrap();
app.register_type::<Coordinates>() app.add_plugin(RapierPhysicsPlugin::<RapierUserData>::pixels_per_meter(
.add_plugin(RapierPhysicsPlugin::<RapierUserData>::pixels_per_meter(
config.pixels_per_unit as f32, config.pixels_per_unit as f32,
)) ))
.add_startup_system(setup) .add_startup_system(setup)
.add_system_to_stage(
CoreStage::PostUpdate,
copy_coordinates_to_transform.before(TransformSystem::TransformPropagate),
)
.add_system(sync_config); .add_system(sync_config);
} }
} }

View File

@ -62,7 +62,7 @@ impl Plugin for ErrorPlugin {
dsn.as_str(), dsn.as_str(),
sentry::ClientOptions { sentry::ClientOptions {
release: Some(release.into()), release: Some(release.into()),
..Default::default() ..default()
}, },
)); ));
app.insert_resource(guard); app.insert_resource(guard);

View File

@ -6,7 +6,7 @@ use bevy_rapier2d::prelude::*;
use bevy_tts::Tts; use bevy_tts::Tts;
use crate::{ use crate::{
core::{Coordinates, Player, PointLike}, core::{Player, PointLike},
error::error_handler, error::error_handler,
map::Map, map::Map,
pathfinding::Destination, pathfinding::Destination,
@ -154,7 +154,7 @@ fn exploration_type_focus<S, A: 'static>(
&FocusedExplorationType, &FocusedExplorationType,
Option<&Exploring>, Option<&Exploring>,
)>, )>,
features: Query<(Entity, &Coordinates, &ExplorationType)>, features: Query<(Entity, &Transform, &ExplorationType)>,
) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>
where where
S: 'static + Clone + Debug + Eq + Hash + Send + Sync, S: 'static + Clone + Debug + Eq + Hash + Send + Sync,
@ -246,7 +246,7 @@ fn exploration_focus<S, A: 'static, D: 'static + Clone + Default + Send + Sync>(
config: Res<ExplorationConfig<S, A>>, config: Res<ExplorationConfig<S, A>>,
input: Res<InputMap<A>>, input: Res<InputMap<A>>,
map: Query<&Map<D>>, map: Query<&Map<D>>,
explorers: Query<(Entity, &Coordinates, Option<&Exploring>), With<Player>>, explorers: Query<(Entity, &Transform, Option<&Exploring>), With<Player>>,
) where ) where
S: 'static + Clone + Debug + Eq + Hash + Send + Sync, S: 'static + Clone + Debug + Eq + Hash + Send + Sync,
A: Hash + Eq + Clone + Send + Sync, A: Hash + Eq + Clone + Send + Sync,
@ -263,12 +263,13 @@ fn exploration_focus<S, A: 'static, D: 'static + Clone + Default + Send + Sync>(
config.action_explore_right.clone(), config.action_explore_right.clone(),
) { ) {
for map in map.iter() { for map in map.iter() {
if let Ok((entity, coordinates, exploring)) = explorers.get_single() { if let Ok((entity, transform, exploring)) = explorers.get_single() {
let coordinates = **coordinates; let coordinates = transform.translation;
let mut exploring = if let Some(exploring) = exploring { let mut exploring = if let Some(exploring) = exploring {
**exploring **exploring
} else { } else {
coordinates.floor() let floor = coordinates.floor();
(floor.x, floor.y)
}; };
let orig = exploring; let orig = exploring;
if input.just_active(explore_forward.clone()) { if input.just_active(explore_forward.clone()) {
@ -323,7 +324,7 @@ fn exploration_changed_announcement<D: 'static + Clone + Default + Send + Sync>(
mut commands: Commands, mut commands: Commands,
mut tts: ResMut<Tts>, mut tts: ResMut<Tts>,
map: Query<(&Map<D>, &RevealedTiles)>, map: Query<(&Map<D>, &RevealedTiles)>,
explorer: Query<(&Coordinates, &Exploring, &Viewshed), Changed<Exploring>>, explorer: Query<(&Transform, &Exploring, &Viewshed), Changed<Exploring>>,
focused: Query<Entity, With<ExplorationFocused>>, focused: Query<Entity, With<ExplorationFocused>>,
explorable: Query<Entity, Or<(With<Visible>, With<Explorable>)>>, explorable: Query<Entity, Or<(With<Visible>, With<Explorable>)>>,
names: Query<&Name>, names: Query<&Name>,

View File

@ -12,19 +12,13 @@ use maze_generator::{prelude::*, recursive_backtracking::RbGenerator};
use rand::prelude::StdRng; use rand::prelude::StdRng;
use crate::{ use crate::{
core::{Coordinates, Player, PointLike}, core::{Player, PointLike},
exploration::{ExplorationType, Mappable}, exploration::{ExplorationType, Mappable},
log::Log, log::Log,
utils::target_and_other, utils::target_and_other,
visibility::Visible, visibility::Visible,
}; };
impl From<here_be_dragons::geometry::Point> for Coordinates {
fn from(point: here_be_dragons::geometry::Point) -> Self {
Self((point.x as f32, point.y as f32))
}
}
#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, PartialEq)] #[derive(Component, Copy, Clone, Debug, Deref, DerefMut, PartialEq)]
pub struct Area(pub AABB); pub struct Area(pub AABB);
@ -115,7 +109,6 @@ impl Default for MapConfig {
#[derive(Bundle)] #[derive(Bundle)]
pub struct PortalBundle { pub struct PortalBundle {
pub coordinates: Coordinates,
pub portal: Portal, pub portal: Portal,
pub exploration_type: ExplorationType, pub exploration_type: ExplorationType,
pub mappable: Mappable, pub mappable: Mappable,
@ -126,7 +119,6 @@ pub struct PortalBundle {
impl Default for PortalBundle { impl Default for PortalBundle {
fn default() -> Self { fn default() -> Self {
Self { Self {
coordinates: Default::default(),
portal: Default::default(), portal: Default::default(),
exploration_type: ExplorationType::Portal, exploration_type: ExplorationType::Portal,
mappable: Default::default(), mappable: Default::default(),
@ -412,11 +404,10 @@ fn spawn_portals<D: 'static + Clone + Default + Send + Sync>(
for portal in portals { for portal in portals {
let x = portal.0 as f32; let x = portal.0 as f32;
let y = portal.1 as f32; let y = portal.1 as f32;
let coordinates = Coordinates((x, y));
let portal = commands let portal = commands
.spawn_bundle(PortalBundle { .spawn_bundle(PortalBundle {
coordinates, transform: Transform::from_translation(Vec3::new(x, y, 0.)),
..Default::default() ..default()
}) })
.id(); .id();
commands.entity(entity).push_children(&[portal]); commands.entity(entity).push_children(&[portal]);
@ -428,7 +419,7 @@ fn spawn_portals<D: 'static + Clone + Default + Send + Sync>(
fn spawn_portal_colliders<D: 'static + Clone + Default + Send + Sync>( fn spawn_portal_colliders<D: 'static + Clone + Default + Send + Sync>(
mut commands: Commands, mut commands: Commands,
map: Query<(Entity, &SpawnColliders), With<Map<D>>>, map: Query<(Entity, &SpawnColliders), With<Map<D>>>,
portals: Query<(Entity, &Coordinates), Without<Collider>>, portals: Query<(Entity, &Transform), Without<Collider>>,
) { ) {
for (map_entity, spawn_colliders) in map.iter() { for (map_entity, spawn_colliders) in map.iter() {
if **spawn_colliders { if **spawn_colliders {

View File

@ -16,7 +16,7 @@ use pathfinding::prelude::*;
use crate::{ use crate::{
commands::RunIfExistsExt, commands::RunIfExistsExt,
core::{Coordinates, PointLike}, core::PointLike,
map::{Map, MapObstruction}, map::{Map, MapObstruction},
navigation::{RotationSpeed, Speed}, navigation::{RotationSpeed, Speed},
}; };
@ -61,7 +61,7 @@ pub fn find_path<D: 'static + Clone + Default + Send + Sync>(
fn find_path_for_shape<D: 'static + Clone + Default + Send + Sync>( fn find_path_for_shape<D: 'static + Clone + Default + Send + Sync>(
initiator: ColliderHandle, initiator: ColliderHandle,
start: Coordinates, start: Transform,
destination: Destination, destination: Destination,
map: Map<D>, map: Map<D>,
query_pipeline: QueryPipeline, query_pipeline: QueryPipeline,
@ -114,7 +114,7 @@ fn calculate_path<D: 'static + Clone + Default + Send + Sync>(
Entity, Entity,
&RapierColliderHandle, &RapierColliderHandle,
&Destination, &Destination,
&Coordinates, &Transform,
&Collider, &Collider,
), ),
Changed<Destination>, Changed<Destination>,

View File

@ -7,7 +7,7 @@ use rand::random;
use crate::{ use crate::{
commands::RunIfExistsExt, commands::RunIfExistsExt,
core::{Coordinates, CoreConfig, Player, PointLike}, core::{CoreConfig, Player, PointLike},
exploration::ExplorationFocused, exploration::ExplorationFocused,
visibility::VisibleEntities, visibility::VisibleEntities,
}; };
@ -98,19 +98,19 @@ fn add_footstep_sounds(
buffer, buffer,
state: SoundState::Stopped, state: SoundState::Stopped,
gain, gain,
..Default::default() ..default()
}); });
}); });
} }
} }
fn footstep( fn footstep(
mut last_step_distance: Local<HashMap<Entity, (f32, Coordinates)>>, mut last_step_distance: Local<HashMap<Entity, (f32, Transform)>>,
mut footsteps: Query<(Entity, &Footstep, &Parent, &mut Sound), Changed<GlobalTransform>>, mut footsteps: Query<(Entity, &Footstep, &Parent, &mut Sound), Changed<GlobalTransform>>,
coordinates_storage: Query<&Coordinates>, transforms_storage: Query<&Transform>,
) { ) {
for (entity, footstep, parent, mut sound) in footsteps.iter_mut() { for (entity, footstep, parent, mut sound) in footsteps.iter_mut() {
let coordinates = coordinates_storage.get(**parent).unwrap(); let coordinates = transforms_storage.get(**parent).unwrap();
if let Some(last) = last_step_distance.get(&entity) { if let Some(last) = last_step_distance.get(&entity) {
let distance = last.0 + (last.1.distance(coordinates)); let distance = last.0 + (last.1.distance(coordinates));
if distance >= footstep.step_length { if distance >= footstep.step_length {
@ -158,7 +158,7 @@ fn add_sound_icon_sounds(
reference_distance, reference_distance,
max_distance, max_distance,
rolloff_factor, rolloff_factor,
..Default::default() ..default()
}); });
}); });
} }
@ -172,7 +172,7 @@ fn sound_icon<S>(
mut icons: Query<( mut icons: Query<(
Entity, Entity,
&mut SoundIcon, &mut SoundIcon,
Option<&Coordinates>, Option<&Transform>,
Option<&Parent>, Option<&Parent>,
&mut Sound, &mut Sound,
)>, )>,

View File

@ -15,7 +15,7 @@ use shadowcast::{vision_distance, Context, InputGrid};
use crate::{ use crate::{
bevy_rapier2d::prelude::*, bevy_rapier2d::prelude::*,
commands::RunIfExistsExt, commands::RunIfExistsExt,
core::{Angle, Coordinates, Player, PointLike}, core::{Angle, Player, PointLike},
log::Log, log::Log,
map::{ITileType, Map, MapConfig}, map::{ITileType, Map, MapConfig},
}; };
@ -182,11 +182,8 @@ pub struct ViewshedBundle {
impl ViewshedBundle { impl ViewshedBundle {
pub fn new(range: u32) -> Self { pub fn new(range: u32) -> Self {
Self { Self {
viewshed: Viewshed { viewshed: Viewshed { range, ..default() },
range, ..default()
..Default::default()
},
..Default::default()
} }
} }
} }
@ -268,7 +265,7 @@ fn update_viewshed<D: 'static + Clone + Default + Send + Sync>(
Entity, Entity,
&mut Viewshed, &mut Viewshed,
&mut VisibleEntities, &mut VisibleEntities,
&Coordinates, &Transform,
Option<&LastCoordinates>, Option<&LastCoordinates>,
)>, )>,
map: Query<&Map<D>>, map: Query<&Map<D>>,
@ -348,7 +345,7 @@ fn update_viewshed<D: 'static + Clone + Default + Send + Sync>(
fn remove_visible<D: 'static + Clone + Default + Send + Sync>( fn remove_visible<D: 'static + Clone + Default + Send + Sync>(
removed: RemovedComponents<Visible>, removed: RemovedComponents<Visible>,
mut viewers: Query<(Entity, &mut Viewshed, &mut VisibleEntities, &Coordinates)>, mut viewers: Query<(Entity, &mut Viewshed, &mut VisibleEntities, &Transform)>,
map: Query<&Map<D>>, map: Query<&Map<D>>,
rapier_context: Res<RapierContext>, rapier_context: Res<RapierContext>,
visible: Query<&Visible>, visible: Query<&Visible>,
@ -399,7 +396,7 @@ fn log_visible(
mut recently_lost: Local<HashMap<Entity, Timer>>, mut recently_lost: Local<HashMap<Entity, Timer>>,
mut events: EventReader<VisibilityChanged>, mut events: EventReader<VisibilityChanged>,
mut log: Query<&mut Log>, mut log: Query<&mut Log>,
viewers: Query<(Entity, &Coordinates, &Transform), (With<Player>, With<Viewshed>)>, viewers: Query<(Entity, &Transform), (With<Player>, With<Viewshed>)>,
visible: Query<(&Name, &Transform), Without<DontLogWhenVisible>>, visible: Query<(&Name, &Transform), Without<DontLogWhenVisible>>,
) { ) {
for timer in recently_lost.values_mut() { for timer in recently_lost.values_mut() {
@ -411,7 +408,7 @@ fn log_visible(
VisibilityChanged::Gained { viewer, .. } => viewer, VisibilityChanged::Gained { viewer, .. } => viewer,
VisibilityChanged::Lost { viewer, .. } => viewer, VisibilityChanged::Lost { viewer, .. } => viewer,
}; };
if let Ok((viewer_entity, viewer_coordinates, viewer_transform)) = viewers.get(*viewer) { if let Ok((viewer_entity, viewer_transform)) = viewers.get(*viewer) {
if let VisibilityChanged::Gained { viewed, .. } = event { if let VisibilityChanged::Gained { viewed, .. } = event {
if *viewed == viewer_entity || recently_lost.contains_key(viewed) { if *viewed == viewer_entity || recently_lost.contains_key(viewed) {
continue; continue;
@ -420,6 +417,10 @@ fn log_visible(
let viewed_coordinates = (transform.translation.x, transform.translation.y); let viewed_coordinates = (transform.translation.x, transform.translation.y);
let forward = viewer_transform.local_x(); let forward = viewer_transform.local_x();
let yaw = Angle::Radians(forward.y.atan2(forward.x)); let yaw = Angle::Radians(forward.y.atan2(forward.x));
let viewer_coordinates = (
viewer_transform.translation.x,
viewer_transform.translation.y,
);
let location = let location =
viewer_coordinates.direction_and_distance(&viewed_coordinates, Some(yaw)); viewer_coordinates.direction_and_distance(&viewed_coordinates, Some(yaw));
if let Ok(mut log) = log.get_single_mut() { if let Ok(mut log) = log.get_single_mut() {