Compare commits

...

2 Commits

5 changed files with 235 additions and 191 deletions

View File

@ -20,7 +20,7 @@ bevy_synthizer = "0.7"
bevy_tts = { version = "0.9", default-features = false, features = ["tolk"] }
coord_2d = "0.3"
here_be_dragons = { version = "0.3", features = ["serde"] }
leafwing-input-manager = "0.14"
leafwing-input-manager = "0.15"
maze_generator = "2"
once_cell = "1"
pathfinding = "4"

View File

@ -9,6 +9,7 @@ use crate::{
core::{Player, PointLike},
error::error_handler,
map::Map,
navigation::NavigationAction,
pathfinding::Destination,
visibility::{RevealedTiles, Viewshed, Visible, VisibleEntities},
};
@ -354,6 +355,25 @@ where
Ok(())
}
fn cancel_on_navigate(
mut commands: Commands,
explorers: Query<
Entity,
(
With<ActionState<ExplorationAction>>,
Changed<ActionState<NavigationAction>>,
),
>,
focused: Query<Entity, With<ExplorationFocused>>,
) {
if !explorers.is_empty() {
for entity in &focused {
println!("Clearing focus");
commands.entity(entity).remove::<ExplorationFocused>();
}
}
}
fn cleanup(
mut commands: Commands,
explorers: Query<Entity, With<Exploring>>,
@ -398,7 +418,7 @@ where
.register_type::<Explorable>()
.add_plugins(InputManagerPlugin::<ExplorationAction>::default())
.add_systems(
Update,
FixedUpdate,
(
exploration_type_change::<ExplorationType>.pipe(error_handler),
exploration_type_changed_announcement::<ExplorationType>.pipe(error_handler),
@ -407,7 +427,7 @@ where
.in_set(Exploration),
)
.add_systems(
Update,
FixedUpdate,
(
exploration_focus::<MapData>,
exploration_type_focus::<ExplorationType>.pipe(error_handler),
@ -417,11 +437,14 @@ where
.chain()
.in_set(Exploration),
)
.add_systems(Update, navigate_to_explored::<MapData>.in_set(Exploration));
.add_systems(
FixedUpdate,
(navigate_to_explored::<MapData>, cancel_on_navigate).in_set(Exploration),
);
if !config.states.is_empty() {
let states = config.states;
for state in states {
app.configure_sets(Update, Exploration.run_if(in_state(state.clone())))
app.configure_sets(FixedUpdate, Exploration.run_if(in_state(state.clone())))
.add_systems(OnExit(state), cleanup);
}
}

View File

@ -3,17 +3,16 @@ use std::{collections::HashMap, error::Error, f32::consts::PI, fmt::Debug, hash:
use bevy::prelude::*;
use bevy_rapier2d::prelude::*;
use bevy_tts::Tts;
use leafwing_input_manager::{axislike::DualAxisData, prelude::*};
use leafwing_input_manager::prelude::*;
use crate::{
core::{Angle, Area, CardinalDirection, GlobalTransformExt, Player, TransformExt},
error::error_handler,
exploration::{ExplorationFocused, Exploring},
log::Log,
utils::target_and_other,
};
#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Hash, Debug, Reflect)]
#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug, Reflect)]
pub enum NavigationAction {
Move,
Translate,
@ -26,6 +25,23 @@ pub enum NavigationAction {
SnapReverse,
}
impl Actionlike for NavigationAction {
fn input_control_kind(&self) -> InputControlKind {
match &self {
NavigationAction::Move
| NavigationAction::Translate
| NavigationAction::SetLinearVelocity => InputControlKind::DualAxis,
NavigationAction::Rotate | NavigationAction::SetAngularVelocity => {
InputControlKind::Axis
}
NavigationAction::SnapLeft
| NavigationAction::SnapRight
| NavigationAction::SnapCardinal
| NavigationAction::SnapReverse => InputControlKind::Button,
}
}
}
#[derive(Component, Clone, Copy, Debug, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct BackwardMovementFactor(pub f32);
@ -135,7 +151,6 @@ fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
}
fn controls(
mut commands: Commands,
rapier_context: Res<RapierContext>,
time: Res<Time>,
snap_timers: Res<SnapTimers>,
@ -151,7 +166,6 @@ fn controls(
&mut Transform,
&Collider,
)>,
exploration_focused: Query<Entity, With<ExplorationFocused>>,
) {
for (
entity,
@ -166,131 +180,76 @@ fn controls(
collider,
) in &mut query
{
let mut cleanup = false;
if actions.pressed(&NavigationAction::Move) {
if let Some(pair) = actions.clamped_axis_pair(&NavigationAction::Move) {
cleanup = true;
let mut direction = pair.xy();
let forward_movement_factor =
forward_movement_factor.map(|v| v.0).unwrap_or_else(|| 1.);
let backward_movement_factor =
backward_movement_factor.map(|v| v.0).unwrap_or_else(|| 1.);
let strafe_movement_factor =
strafe_movement_factor.map(|v| v.0).unwrap_or_else(|| 1.);
let forward_backward_movement_factor = if direction.x > 0. {
forward_movement_factor
} else if direction.x < 0. {
backward_movement_factor
} else {
1.
};
let movement_factor = if direction.x != 0. && direction.y != 0. {
strafe_movement_factor.min(forward_backward_movement_factor)
} else if direction.y != 0. {
strafe_movement_factor
} else {
forward_backward_movement_factor
};
trace!("{entity:?}: move: {direction:?}");
direction = transform
.compute_matrix()
.transform_vector3(direction.extend(0.))
.truncate();
let mut speed = **speed;
speed *= movement_factor;
let velocity = direction * speed;
// println!("{entity:?}: SetLinearVelocity: {velocity:?}");
actions.press(&NavigationAction::SetLinearVelocity);
actions
.action_data_mut_or_default(&NavigationAction::SetLinearVelocity)
.axis_pair = Some(DualAxisData::from_xy(velocity));
}
} else if actions.just_released(&NavigationAction::Move) {
trace!("{entity:?}: Stopped moving");
actions.release(&NavigationAction::SetLinearVelocity);
actions.release(&NavigationAction::Translate);
actions
.action_data_mut_or_default(&NavigationAction::Move)
.axis_pair = Some(DualAxisData::from_xy(Vec2::ZERO));
}
if actions.pressed(&NavigationAction::SetLinearVelocity) {
if let Some(pair) = actions.axis_pair(&NavigationAction::SetLinearVelocity) {
// println!("{entity:?}: SetLinearVelocity: {pair:?}");
velocity.linvel = pair.into();
if !actions.action_disabled(&NavigationAction::Move) {
let mut direction = actions.clamped_axis_pair(&NavigationAction::Move);
let forward_movement_factor =
forward_movement_factor.map(|v| v.0).unwrap_or_else(|| 1.);
let backward_movement_factor =
backward_movement_factor.map(|v| v.0).unwrap_or_else(|| 1.);
let strafe_movement_factor = strafe_movement_factor.map(|v| v.0).unwrap_or_else(|| 1.);
let forward_backward_movement_factor = if direction.x > 0. {
forward_movement_factor
} else if direction.x < 0. {
backward_movement_factor
} else {
// println!("{entity:?}: SetLinearVelocity: 0");
velocity.linvel = Vec2::ZERO;
}
} else if actions.just_released(&NavigationAction::SetLinearVelocity) {
// println!("{entity:?}: Released velocity");
velocity.linvel = Vec2::ZERO;
actions
.action_data_mut_or_default(&NavigationAction::SetLinearVelocity)
.axis_pair = None;
1.
};
let movement_factor = if direction.x != 0. && direction.y != 0. {
strafe_movement_factor.min(forward_backward_movement_factor)
} else if direction.y != 0. {
strafe_movement_factor
} else {
forward_backward_movement_factor
};
trace!("{entity:?}: move: {direction:?}");
direction = transform
.compute_matrix()
.transform_vector3(direction.extend(0.))
.truncate();
let mut speed = **speed;
speed *= movement_factor;
let move_velocity = direction * speed;
// println!("{entity:?}: SetLinearVelocity: {velocity:?}");
actions.set_axis_pair(&NavigationAction::SetLinearVelocity, move_velocity);
}
if actions.pressed(&NavigationAction::Translate) {
if let Some(pair) = actions.axis_pair(&NavigationAction::Translate) {
let vel = pair.xy();
if rapier_context
.cast_shape(
transform.translation.truncate(),
transform.yaw().radians(),
vel,
collider,
ShapeCastOptions {
max_time_of_impact: 1.,
..default()
},
QueryFilter::new()
.exclude_sensors()
.exclude_collider(entity),
)
.is_none()
{
transform.translation += vel.extend(0.);
}
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);
if rapier_context
.cast_shape(
transform.translation.truncate(),
transform.yaw().radians(),
pair,
collider,
ShapeCastOptions {
max_time_of_impact: 1.,
..default()
},
QueryFilter::new()
.exclude_sensors()
.exclude_collider(entity),
)
.is_none()
{
transform.translation += pair.extend(0.);
}
} else if actions.just_released(&NavigationAction::Translate) {
actions
.action_data_mut_or_default(&NavigationAction::Translate)
.axis_pair = None;
actions.set_axis_pair(&NavigationAction::Translate, Vec2::ZERO);
}
if !snap_timers.contains_key(&entity) {
if let Some(rotation_speed) = rotation_speed {
if actions.pressed(&NavigationAction::Rotate) {
cleanup = true;
let delta = -rotation_speed.radians()
* actions.clamped_value(&NavigationAction::Rotate);
actions.press(&NavigationAction::SetAngularVelocity);
actions
.action_data_mut_or_default(&NavigationAction::SetAngularVelocity)
.value = delta;
}
let delta =
-rotation_speed.radians() * actions.clamped_value(&NavigationAction::Rotate);
actions.set_value(&NavigationAction::SetAngularVelocity, delta);
}
}
if actions.just_released(&NavigationAction::Rotate) {
actions.release(&NavigationAction::SetAngularVelocity);
actions
.action_data_mut_or_default(&NavigationAction::Rotate)
.value = 0.;
}
if actions.pressed(&NavigationAction::SetAngularVelocity) {
if actions.value(&NavigationAction::SetAngularVelocity) != 0. {
// velocity.angvel =
// actions.value(&NavigationAction::SetAngularVelocity);
transform.rotation *= Quat::from_rotation_z(
actions.value(&NavigationAction::SetAngularVelocity) * time.delta_seconds(),
);
} else if actions.just_released(&NavigationAction::SetAngularVelocity) {
actions
.action_data_mut_or_default(&NavigationAction::SetAngularVelocity)
.value = 0.;
velocity.angvel = 0.;
}
if cleanup {
commands.entity(entity).remove::<Exploring>();
for entity in &exploration_focused {
commands.entity(entity).remove::<ExplorationFocused>();
}
}
}
}
@ -436,12 +395,17 @@ where
.in_set(Movement),
)
.add_systems(
Update,
FixedUpdate,
(tick_snap_timers, speak_direction.pipe(error_handler)),
)
.add_systems(
PostUpdate,
(remove_direction, log_area_descriptions::<State>),
);
if !self.states.is_empty() {
for state in &self.states {
app.configure_sets(Update, Movement.run_if(in_state(state.clone())));
}
}
}
}

View File

@ -1,5 +1,4 @@
use bevy::{
ecs::entity::Entities,
prelude::*,
tasks::{futures_lite::future, prelude::*, Task},
utils::HashMap,
@ -9,7 +8,7 @@ use bevy_rapier2d::{
prelude::*,
rapier::prelude::{ColliderHandle, ColliderSet, QueryPipeline, RigidBodySet},
};
use leafwing_input_manager::{axislike::DualAxisData, plugin::InputManagerSystem, prelude::*};
use leafwing_input_manager::{plugin::InputManagerSystem, prelude::*};
use pathfinding::prelude::*;
use crate::{
@ -21,7 +20,11 @@ use crate::{
#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug, Reflect)]
pub struct NegotiatePathAction;
impl Actionlike for NegotiatePathAction {}
impl Actionlike for NegotiatePathAction {
fn input_control_kind(&self) -> InputControlKind {
InputControlKind::DualAxis
}
}
#[derive(Component, Debug, Deref, DerefMut)]
struct Calculating(Task<Option<Path>>);
@ -45,6 +48,17 @@ pub struct Path(pub Vec<(i32, i32)>);
#[reflect(Component)]
pub struct CostMap(pub HashMap<(i32, i32), f32>);
#[derive(Bundle, Deref, DerefMut)]
pub struct PathfindingControlsBundle(pub ActionState<NegotiatePathAction>);
impl Default for PathfindingControlsBundle {
fn default() -> Self {
let mut input: ActionState<NegotiatePathAction> = Default::default();
input.disable();
Self(input)
}
}
pub fn find_path<D: 'static + Clone + Default + Send + Sync>(
start: &dyn PointLike,
destination: &dyn PointLike,
@ -161,7 +175,11 @@ fn calculate_path(
>,
) {
for (entity, handle, destination, coordinates, shape, cost_map) in &query {
trace
!("{entity}: destination: {destination:?}");
if coordinates.i32() == **destination {
trace
!("{entity}: remove1");
commands
.entity(entity)
.remove::<Path>()
@ -211,6 +229,8 @@ fn calculate_path(
shape_clone,
)
});
trace
!("{entity}: remove2");
commands
.entity(entity)
.insert(Calculating(task))
@ -221,34 +241,45 @@ fn calculate_path(
fn poll_tasks(
mut commands: Commands,
mut query: Query<(Entity, &mut Calculating, &Transform, &Destination)>,
mut query: Query<(
Entity,
&mut Calculating,
&Transform,
&Destination,
Option<&mut ActionState<NegotiatePathAction>>,
)>,
) {
for (entity, mut calculating, transform, destination) in &mut query {
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!(
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();
}
}
commands.entity(entity).remove::<Calculating>();
}
}
}
fn remove_destination(
mut commands: Commands,
entities: &Entities,
mut removed: RemovedComponents<Destination>,
) {
fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Destination>) {
for entity in removed.read() {
if entities.contains(entity) {
commands.entity(entity).remove::<Calculating>();
if let Some(mut commands) = commands.get_entity(entity) {
commands
.remove::<Calculating>()
.remove::<Path>()
.remove::<NoPath>();
}
}
}
@ -259,6 +290,7 @@ fn negotiate_path(
physics_config: Res<RapierConfiguration>,
mut query: Query<(
Entity,
Option<&mut ActionState<NegotiatePathAction>>,
&mut ActionState<NavigationAction>,
&mut Path,
&mut Transform,
@ -271,9 +303,18 @@ fn negotiate_path(
if !physics_config.physics_pipeline_active || !physics_config.query_pipeline_active {
return;
}
for (entity, mut actions, mut path, mut transform, collider, speed, rotation_speed) in
&mut query
for (
entity,
actions,
mut navigation_actions,
mut path,
mut transform,
collider,
speed,
rotation_speed,
) in &mut query
{
trace!("{entity:?}: negotiating path");
let start_i32 = transform.translation.truncate().i32();
trace!(
"{entity:?}: start pathfinding from {start_i32:?} to {:?}: at {:?}",
@ -285,7 +326,6 @@ fn negotiate_path(
path.remove(0);
}
if let Some(next) = path.first() {
trace!("{entity:?}: path: moving from {start_i32:?} to {next:?}");
let start = transform.translation.truncate();
let mut next = Vec2::new(next.0 as f32, next.1 as f32);
if next.x >= 0. {
@ -322,22 +362,27 @@ fn negotiate_path(
)
.is_some()
{
// trace!("{entity:?} is stuck, hit: {hit:?}, TOI: {toi:?}");
trace
!("{entity:?} is stuck");
// TODO: Remove when we have an actual character controller.
next.x = next.x.trunc();
next.y = next.y.trunc();
transform.translation = next.extend(0.);
continue;
} else {
navigation_actions.set_axis_pair(&NavigationAction::Translate, direction);
}
trace!("{entity:?}: path: direction: {direction:?}");
actions.press(&NavigationAction::Translate);
actions
.action_data_mut_or_default(&NavigationAction::Translate)
.axis_pair = Some(DualAxisData::from_xy(direction));
if rotation_speed.is_some() {
let angle = direction.y.atan2(direction.x);
transform.rotation = Quat::from_rotation_z(angle);
}
} else {
trace!("{entity:?}: empty path, cleaning");
trace
!("{entity:?}: empty path, cleaning");
if let Some(mut actions) = actions {
trace!("{entity:?}: Disabling pathfind because at destination");
actions.reset_all();
actions.disable();
}
commands
.entity(entity)
.remove::<Path>()
@ -352,46 +397,35 @@ fn actions(
mut commands: Commands,
mut query: Query<(
Entity,
&mut ActionState<NegotiatePathAction>,
&ActionState<NegotiatePathAction>,
&mut ActionState<NavigationAction>,
Option<&mut Destination>,
)>,
) {
for (entity, mut actions, mut navigation_action, destination) in &mut query {
if actions.pressed(&NegotiatePathAction) {
if let Some(pair) = actions.axis_pair(&NegotiatePathAction) {
trace!("{entity:?}: Negotiating path to {pair:?}");
let dest = Destination(pair.xy().i32());
if let Some(mut current_dest) = destination {
trace!("Got a destination");
if *current_dest != dest {
trace!("{entity:?}: New destination {dest:?} differs from {current_dest:?}, zeroing velocity");
navigation_action.press(&NavigationAction::SetLinearVelocity);
navigation_action
.action_data_mut_or_default(&NavigationAction::SetLinearVelocity)
.axis_pair = Some(DualAxisData::from_xy(Vec2::ZERO));
*current_dest = dest;
}
} else {
trace!("{entity:?}: Adding destination, zeroing velocity");
navigation_action.press(&NavigationAction::SetLinearVelocity);
navigation_action
.action_data_mut_or_default(&NavigationAction::SetLinearVelocity)
.axis_pair = Some(DualAxisData::from_xy(Vec2::ZERO));
commands.entity(entity).insert(dest);
}
} else if destination.is_some() {
trace!("No value, resetting");
commands
.entity(entity)
.remove::<Destination>()
.remove::<Path>()
.remove::<NoPath>();
for (entity, actions, mut navigation_action, destination) in &mut query {
if actions.action_disabled(&NegotiatePathAction) {
if destination.is_some() {
commands.entity(entity).remove::<Destination>();
}
} else {
let pair = actions.axis_pair(&NegotiatePathAction);
trace!("{entity:?}: Negotiating path to {pair:?}");
let dest = Destination(pair.xy().i32());
if let Some(mut current_dest) = destination {
trace!("Got a destination");
if *current_dest != dest {
trace
!("{entity:?}: New destination {dest:?} differs from {current_dest:?}, zeroing velocity");
navigation_action
.set_axis_pair(&NavigationAction::SetLinearVelocity, Vec2::ZERO);
*current_dest = dest;
}
} else {
trace
!("{entity:?}: Adding destination, zeroing velocity");
navigation_action.set_axis_pair(&NavigationAction::SetLinearVelocity, Vec2::ZERO);
commands.entity(entity).insert(dest);
}
actions.release(&NegotiatePathAction);
actions
.action_data_mut_or_default(&NegotiatePathAction)
.axis_pair = None;
}
}
}
@ -405,16 +439,13 @@ impl Plugin for PathfindingPlugin {
.register_type::<NoPath>()
.register_type::<Path>()
.register_type::<CostMap>()
.add_systems(
FixedPreUpdate,
(poll_tasks, apply_deferred, negotiate_path).chain(),
)
.add_systems(PreUpdate, (poll_tasks, negotiate_path).chain())
.add_systems(
PreUpdate,
(actions, apply_deferred, calculate_path)
(actions, calculate_path)
.chain()
.after(InputManagerSystem::Tick),
)
.add_systems(FixedPostUpdate, remove_destination);
.add_systems(PostUpdate, remove_destination);
}
}

View File

@ -146,7 +146,30 @@ impl Viewshed {
};
if let Some((opacity, coord_entities)) = result {
for e in &coord_entities {
new_visible_entities.insert(*e);
let mut should_insert = true;
if coord_entities.len() > 1 {
let start = start.translation().truncate();
let dest = Vec2::new(coord.x as f32, coord.y as f32);
let dir = dest - start;
rapier_context.intersections_with_ray(
start,
dir,
1.,
true,
QueryFilter::new()
.exclude_sensors()
.exclude_collider(*viewer_entity)
.exclude_collider(*e)
.predicate(&|e| visible_query.contains(e)),
|_, _| {
should_insert = false;
false
},
);
}
if should_insert {
new_visible_entities.insert(*e);
}
}
opacity
} else {
@ -187,7 +210,7 @@ impl Viewshed {
}
}
#[derive(Component, Clone, Copy, Debug, Deref, DerefMut, Reflect)]
#[derive(Component, Clone, Copy, Debug, Deref, DerefMut, Eq, PartialEq, Reflect)]
#[reflect(Component)]
pub struct Visible(pub u8);
@ -437,6 +460,9 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlug
update_revealed_tiles::<MapData>,
),
)
.add_systems(FixedPostUpdate, (log_visible, viewshed_removed, remove_visible));
.add_systems(
FixedPostUpdate,
(log_visible, viewshed_removed, remove_visible),
);
}
}