Merge branch 'zesterer/phys-fixes' into 'master'

Added Colliders, made projectiles point particles

See merge request veloren/veloren!947
This commit is contained in:
Joshua Barretto 2020-04-26 18:24:33 +00:00
commit dcc20590bf
11 changed files with 352 additions and 258 deletions

View File

@ -120,8 +120,7 @@ impl Tool {
prepare_duration: Duration::from_millis(100), prepare_duration: Duration::from_millis(100),
recover_duration: Duration::from_millis(500), recover_duration: Duration::from_millis(500),
projectile: Projectile { projectile: Projectile {
hit_ground: vec![projectile::Effect::Stick], hit_solid: vec![projectile::Effect::Stick],
hit_wall: vec![projectile::Effect::Stick],
hit_entity: vec![ hit_entity: vec![
projectile::Effect::Damage(HealthChange { projectile::Effect::Damage(HealthChange {
// TODO: This should not be fixed (?) // TODO: This should not be fixed (?)
@ -162,8 +161,7 @@ impl Tool {
prepare_duration: Duration::from_millis(0), prepare_duration: Duration::from_millis(0),
recover_duration: Duration::from_millis(200), recover_duration: Duration::from_millis(200),
projectile: Projectile { projectile: Projectile {
hit_ground: vec![projectile::Effect::Vanish], hit_solid: vec![projectile::Effect::Vanish],
hit_wall: vec![projectile::Effect::Vanish],
hit_entity: vec![ hit_entity: vec![
projectile::Effect::Damage(HealthChange { projectile::Effect::Damage(HealthChange {
// TODO: This should not be fixed (?) // TODO: This should not be fixed (?)
@ -190,11 +188,7 @@ impl Tool {
prepare_duration: Duration::from_millis(800), prepare_duration: Duration::from_millis(800),
recover_duration: Duration::from_millis(50), recover_duration: Duration::from_millis(50),
projectile: Projectile { projectile: Projectile {
hit_ground: vec![ hit_solid: vec![
projectile::Effect::Explode { power: 1.4 },
projectile::Effect::Vanish,
],
hit_wall: vec![
projectile::Effect::Explode { power: 1.4 }, projectile::Effect::Explode { power: 1.4 },
projectile::Effect::Vanish, projectile::Effect::Vanish,
], ],
@ -250,8 +244,7 @@ impl Tool {
prepare_duration: Duration::from_millis(0), prepare_duration: Duration::from_millis(0),
recover_duration: Duration::from_millis(300), recover_duration: Duration::from_millis(300),
projectile: Projectile { projectile: Projectile {
hit_ground: vec![projectile::Effect::Stick], hit_solid: vec![projectile::Effect::Stick],
hit_wall: vec![projectile::Effect::Stick],
hit_entity: vec![projectile::Effect::Stick, projectile::Effect::Possess], hit_entity: vec![projectile::Effect::Stick, projectile::Effect::Possess],
time_left: Duration::from_secs(10), time_left: Duration::from_secs(10),
owner: None, owner: None,

View File

@ -35,7 +35,7 @@ pub use inventory::{
}; };
pub use last::Last; pub use last::Last;
pub use location::{Waypoint, WaypointArea}; pub use location::{Waypoint, WaypointArea};
pub use phys::{ForceUpdate, Gravity, Mass, Ori, PhysicsState, Pos, Scale, Sticky, Vel}; pub use phys::{Collider, ForceUpdate, Gravity, Mass, Ori, PhysicsState, Pos, Scale, Sticky, Vel};
pub use player::Player; pub use player::Player;
pub use projectile::Projectile; pub use projectile::Projectile;
pub use stats::{Exp, HealthChange, HealthSource, Level, Stats}; pub use stats::{Exp, HealthChange, HealthSource, Level, Stats};

View File

@ -43,6 +43,17 @@ impl Component for Mass {
type Storage = FlaggedStorage<Self, IDVStorage<Self>>; type Storage = FlaggedStorage<Self, IDVStorage<Self>>;
} }
// Mass
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Collider {
Box { radius: f32, z_min: f32, z_max: f32 },
Point,
}
impl Component for Collider {
type Storage = FlaggedStorage<Self, IDVStorage<Self>>;
}
#[derive(Copy, Clone, Default, Debug, PartialEq, Serialize, Deserialize)] #[derive(Copy, Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct Gravity(pub f32); pub struct Gravity(pub f32);
@ -61,6 +72,7 @@ impl Component for Sticky {
#[derive(Copy, Clone, Default, Debug, PartialEq, Serialize, Deserialize)] #[derive(Copy, Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct PhysicsState { pub struct PhysicsState {
pub on_ground: bool, pub on_ground: bool,
pub on_ceiling: bool,
pub on_wall: Option<Vec3<f32>>, pub on_wall: Option<Vec3<f32>>,
pub touch_entity: Option<Uid>, pub touch_entity: Option<Uid>,
pub in_fluid: bool, pub in_fluid: bool,

View File

@ -17,8 +17,7 @@ pub enum Effect {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Projectile { pub struct Projectile {
// TODO: use SmallVec for these effects // TODO: use SmallVec for these effects
pub hit_ground: Vec<Effect>, pub hit_solid: Vec<Effect>,
pub hit_wall: Vec<Effect>,
pub hit_entity: Vec<Effect>, pub hit_entity: Vec<Effect>,
/// Time left until the projectile will despawn /// Time left until the projectile will despawn
pub time_left: Duration, pub time_left: Duration,
@ -28,12 +27,7 @@ pub struct Projectile {
impl Projectile { impl Projectile {
pub fn set_owner(&mut self, new_owner: Uid) { pub fn set_owner(&mut self, new_owner: Uid) {
self.owner = Some(new_owner); self.owner = Some(new_owner);
for e in self for e in self.hit_solid.iter_mut().chain(self.hit_entity.iter_mut()) {
.hit_ground
.iter_mut()
.chain(self.hit_wall.iter_mut())
.chain(self.hit_entity.iter_mut())
{
if let Effect::Damage(comp::HealthChange { if let Effect::Damage(comp::HealthChange {
cause: comp::HealthSource::Projectile { owner, .. }, cause: comp::HealthSource::Projectile { owner, .. },
.. ..

View File

@ -19,6 +19,7 @@ sum_type! {
MountState(comp::MountState), MountState(comp::MountState),
Mounting(comp::Mounting), Mounting(comp::Mounting),
Mass(comp::Mass), Mass(comp::Mass),
Collider(comp::Collider),
Gravity(comp::Gravity), Gravity(comp::Gravity),
Sticky(comp::Sticky), Sticky(comp::Sticky),
Loadout(comp::Loadout), Loadout(comp::Loadout),
@ -44,6 +45,7 @@ sum_type! {
MountState(PhantomData<comp::MountState>), MountState(PhantomData<comp::MountState>),
Mounting(PhantomData<comp::Mounting>), Mounting(PhantomData<comp::Mounting>),
Mass(PhantomData<comp::Mass>), Mass(PhantomData<comp::Mass>),
Collider(PhantomData<comp::Collider>),
Gravity(PhantomData<comp::Gravity>), Gravity(PhantomData<comp::Gravity>),
Sticky(PhantomData<comp::Sticky>), Sticky(PhantomData<comp::Sticky>),
Loadout(PhantomData<comp::Loadout>), Loadout(PhantomData<comp::Loadout>),
@ -69,6 +71,7 @@ impl sync::CompPacket for EcsCompPacket {
EcsCompPacket::MountState(comp) => sync::handle_insert(comp, entity, world), EcsCompPacket::MountState(comp) => sync::handle_insert(comp, entity, world),
EcsCompPacket::Mounting(comp) => sync::handle_insert(comp, entity, world), EcsCompPacket::Mounting(comp) => sync::handle_insert(comp, entity, world),
EcsCompPacket::Mass(comp) => sync::handle_insert(comp, entity, world), EcsCompPacket::Mass(comp) => sync::handle_insert(comp, entity, world),
EcsCompPacket::Collider(comp) => sync::handle_insert(comp, entity, world),
EcsCompPacket::Gravity(comp) => sync::handle_insert(comp, entity, world), EcsCompPacket::Gravity(comp) => sync::handle_insert(comp, entity, world),
EcsCompPacket::Sticky(comp) => sync::handle_insert(comp, entity, world), EcsCompPacket::Sticky(comp) => sync::handle_insert(comp, entity, world),
EcsCompPacket::Loadout(comp) => sync::handle_insert(comp, entity, world), EcsCompPacket::Loadout(comp) => sync::handle_insert(comp, entity, world),
@ -92,6 +95,7 @@ impl sync::CompPacket for EcsCompPacket {
EcsCompPacket::MountState(comp) => sync::handle_modify(comp, entity, world), EcsCompPacket::MountState(comp) => sync::handle_modify(comp, entity, world),
EcsCompPacket::Mounting(comp) => sync::handle_modify(comp, entity, world), EcsCompPacket::Mounting(comp) => sync::handle_modify(comp, entity, world),
EcsCompPacket::Mass(comp) => sync::handle_modify(comp, entity, world), EcsCompPacket::Mass(comp) => sync::handle_modify(comp, entity, world),
EcsCompPacket::Collider(comp) => sync::handle_modify(comp, entity, world),
EcsCompPacket::Gravity(comp) => sync::handle_modify(comp, entity, world), EcsCompPacket::Gravity(comp) => sync::handle_modify(comp, entity, world),
EcsCompPacket::Sticky(comp) => sync::handle_modify(comp, entity, world), EcsCompPacket::Sticky(comp) => sync::handle_modify(comp, entity, world),
EcsCompPacket::Loadout(comp) => sync::handle_modify(comp, entity, world), EcsCompPacket::Loadout(comp) => sync::handle_modify(comp, entity, world),
@ -117,6 +121,7 @@ impl sync::CompPacket for EcsCompPacket {
EcsCompPhantom::MountState(_) => sync::handle_remove::<comp::MountState>(entity, world), EcsCompPhantom::MountState(_) => sync::handle_remove::<comp::MountState>(entity, world),
EcsCompPhantom::Mounting(_) => sync::handle_remove::<comp::Mounting>(entity, world), EcsCompPhantom::Mounting(_) => sync::handle_remove::<comp::Mounting>(entity, world),
EcsCompPhantom::Mass(_) => sync::handle_remove::<comp::Mass>(entity, world), EcsCompPhantom::Mass(_) => sync::handle_remove::<comp::Mass>(entity, world),
EcsCompPhantom::Collider(_) => sync::handle_remove::<comp::Collider>(entity, world),
EcsCompPhantom::Gravity(_) => sync::handle_remove::<comp::Gravity>(entity, world), EcsCompPhantom::Gravity(_) => sync::handle_remove::<comp::Gravity>(entity, world),
EcsCompPhantom::Sticky(_) => sync::handle_remove::<comp::Sticky>(entity, world), EcsCompPhantom::Sticky(_) => sync::handle_remove::<comp::Sticky>(entity, world),
EcsCompPhantom::Loadout(_) => sync::handle_remove::<comp::Loadout>(entity, world), EcsCompPhantom::Loadout(_) => sync::handle_remove::<comp::Loadout>(entity, world),

View File

@ -118,6 +118,7 @@ impl State {
ecs.register::<comp::Mounting>(); ecs.register::<comp::Mounting>();
ecs.register::<comp::MountState>(); ecs.register::<comp::MountState>();
ecs.register::<comp::Mass>(); ecs.register::<comp::Mass>();
ecs.register::<comp::Collider>();
ecs.register::<comp::Sticky>(); ecs.register::<comp::Sticky>();
ecs.register::<comp::Gravity>(); ecs.register::<comp::Gravity>();
ecs.register::<comp::CharacterState>(); ecs.register::<comp::CharacterState>();

View File

@ -1,5 +1,5 @@
use crate::{ use crate::{
comp::{Body, Gravity, Mass, Mounting, Ori, PhysicsState, Pos, Scale, Sticky, Vel}, comp::{Collider, Gravity, Mass, Mounting, Ori, PhysicsState, Pos, Scale, Sticky, Vel},
event::{EventBus, ServerEvent}, event::{EventBus, ServerEvent},
state::DeltaTime, state::DeltaTime,
sync::Uid, sync::Uid,
@ -47,8 +47,8 @@ impl<'a> System<'a> for Sys {
ReadStorage<'a, Scale>, ReadStorage<'a, Scale>,
ReadStorage<'a, Sticky>, ReadStorage<'a, Sticky>,
ReadStorage<'a, Mass>, ReadStorage<'a, Mass>,
ReadStorage<'a, Collider>,
ReadStorage<'a, Gravity>, ReadStorage<'a, Gravity>,
ReadStorage<'a, Body>,
WriteStorage<'a, PhysicsState>, WriteStorage<'a, PhysicsState>,
WriteStorage<'a, Pos>, WriteStorage<'a, Pos>,
WriteStorage<'a, Vel>, WriteStorage<'a, Vel>,
@ -67,8 +67,8 @@ impl<'a> System<'a> for Sys {
scales, scales,
stickies, stickies,
masses, masses,
colliders,
gravities, gravities,
bodies,
mut physics_states, mut physics_states,
mut positions, mut positions,
mut velocities, mut velocities,
@ -79,11 +79,11 @@ impl<'a> System<'a> for Sys {
let mut event_emitter = event_bus.emitter(); let mut event_emitter = event_bus.emitter();
// Apply movement inputs // Apply movement inputs
for (entity, scale, sticky, _b, mut pos, mut vel, _ori, _) in ( for (entity, scale, sticky, collider, mut pos, mut vel, _ori, _) in (
&entities, &entities,
scales.maybe(), scales.maybe(),
stickies.maybe(), stickies.maybe(),
&bodies, &colliders,
&mut positions, &mut positions,
&mut velocities, &mut velocities,
&mut orientations, &mut orientations,
@ -93,30 +93,17 @@ impl<'a> System<'a> for Sys {
{ {
let mut physics_state = physics_states.get(entity).cloned().unwrap_or_default(); let mut physics_state = physics_states.get(entity).cloned().unwrap_or_default();
if sticky.is_some() && (physics_state.on_wall.is_some() || physics_state.on_ground) { if sticky.is_some()
&& (physics_state.on_ground
|| physics_state.on_ceiling
|| physics_state.on_wall.is_some())
{
vel.0 = Vec3::zero();
continue; continue;
} }
let scale = scale.map(|s| s.0).unwrap_or(1.0); let scale = scale.map(|s| s.0).unwrap_or(1.0);
// Basic collision with terrain
// TODO: rename this, not just the player entity
let player_rad = 0.3 * scale; // half-width of the player's AABB
let player_height = 1.5 * scale;
// Probe distances
let hdist = player_rad.ceil() as i32;
let vdist = player_height.ceil() as i32;
// Neighbouring blocks iterator
let near_iter = (-hdist..hdist + 1)
.map(move |i| {
(-hdist..hdist + 1).map(move |j| {
(1 - BlockKind::MAX_HEIGHT.ceil() as i32..vdist + 1).map(move |k| (i, j, k))
})
})
.flatten()
.flatten();
let old_vel = *vel; let old_vel = *vel;
// Integrate forces // Integrate forces
// Friction is assumed to be a constant dependent on location // Friction is assumed to be a constant dependent on location
@ -150,216 +137,293 @@ impl<'a> System<'a> for Sys {
Vec3::zero() Vec3::zero()
}; };
// Function for determining whether the player at a specific position collides match collider {
// with the ground Collider::Box {
let collision_with = |pos: Vec3<f32>, hit: &dyn Fn(&Block) -> bool, near_iter| { radius,
for (i, j, k) in near_iter { z_min,
let block_pos = pos.map(|e| e.floor() as i32) + Vec3::new(i, j, k); z_max,
} => {
// Scale collider
let radius = *radius * scale;
let z_min = *z_min * scale;
let z_max = *z_max * scale;
if let Some(block) = terrain.get(block_pos).ok().copied().filter(hit) { // Probe distances
let player_aabb = Aabb { let hdist = radius.ceil() as i32;
min: pos + Vec3::new(-player_rad, -player_rad, 0.0), // Neighbouring blocks iterator
max: pos + Vec3::new(player_rad, player_rad, player_height), let near_iter = (-hdist..hdist + 1)
}; .map(move |i| {
let block_aabb = Aabb { (-hdist..hdist + 1).map(move |j| {
min: block_pos.map(|e| e as f32), (1 - BlockKind::MAX_HEIGHT.ceil() as i32 + z_min.floor() as i32
max: block_pos.map(|e| e as f32) ..z_max.ceil() as i32 + 1)
+ Vec3::new(1.0, 1.0, block.get_height()), .map(move |k| (i, j, k))
}; })
})
.flatten()
.flatten();
if player_aabb.collides_with_aabb(block_aabb) { // Function for determining whether the player at a specific position collides
return true; // with the ground
let collision_with = |pos: Vec3<f32>,
hit: &dyn Fn(&Block) -> bool,
near_iter| {
for (i, j, k) in near_iter {
let block_pos = pos.map(|e| e.floor() as i32) + Vec3::new(i, j, k);
if let Some(block) = terrain.get(block_pos).ok().copied().filter(hit) {
let player_aabb = Aabb {
min: pos + Vec3::new(-radius, -radius, z_min),
max: pos + Vec3::new(radius, radius, z_max),
};
let block_aabb = Aabb {
min: block_pos.map(|e| e as f32),
max: block_pos.map(|e| e as f32)
+ Vec3::new(1.0, 1.0, block.get_height()),
};
if player_aabb.collides_with_aabb(block_aabb) {
return true;
}
}
} }
} false
}
false
};
let was_on_ground = physics_state.on_ground;
physics_state.on_ground = false;
let mut on_ground = false;
let mut attempts = 0; // Don't loop infinitely here
// Don't jump too far at once
let increments = (pos_delta.map(|e| e.abs()).reduce_partial_max() / 0.3)
.ceil()
.max(1.0);
let old_pos = pos.0;
for _ in 0..increments as usize {
pos.0 += pos_delta / increments;
const MAX_ATTEMPTS: usize = 16;
// While the player is colliding with the terrain...
while collision_with(pos.0, &|block| block.is_solid(), near_iter.clone())
&& attempts < MAX_ATTEMPTS
{
// Calculate the player's AABB
let player_aabb = Aabb {
min: pos.0 + Vec3::new(-player_rad, -player_rad, 0.0),
max: pos.0 + Vec3::new(player_rad, player_rad, player_height),
}; };
// Determine the block that we are colliding with most (based on minimum let was_on_ground = physics_state.on_ground;
// collision axis) physics_state.on_ground = false;
let (_block_pos, block_aabb, block_height) = near_iter
.clone() let mut on_ground = false;
// Calculate the block's position in world space let mut on_ceiling = false;
.map(|(i, j, k)| pos.0.map(|e| e.floor() as i32) + Vec3::new(i, j, k)) let mut attempts = 0; // Don't loop infinitely here
// Make sure the block is actually solid
.filter_map(|block_pos| { // Don't jump too far at once
if let Some(block) = terrain let increments = (pos_delta.map(|e| e.abs()).reduce_partial_max() / 0.3)
.get(block_pos) .ceil()
.ok() .max(1.0);
.filter(|block| block.is_solid()) let old_pos = pos.0;
{ for _ in 0..increments as usize {
// Calculate block AABB pos.0 += pos_delta / increments;
Some((
block_pos, const MAX_ATTEMPTS: usize = 16;
Aabb {
min: block_pos.map(|e| e as f32), // While the player is colliding with the terrain...
max: block_pos.map(|e| e as f32) + Vec3::new(1.0, 1.0, block.get_height()), while collision_with(pos.0, &|block| block.is_solid(), near_iter.clone())
}, && attempts < MAX_ATTEMPTS
block.get_height(), {
)) // Calculate the player's AABB
} else { let player_aabb = Aabb {
None min: pos.0 + Vec3::new(-radius, -radius, z_min),
max: pos.0 + Vec3::new(radius, radius, z_max),
};
// Determine the block that we are colliding with most (based on minimum
// collision axis)
let (_block_pos, block_aabb, block_height) = near_iter
.clone()
// Calculate the block's position in world space
.map(|(i, j, k)| pos.0.map(|e| e.floor() as i32) + Vec3::new(i, j, k))
// Make sure the block is actually solid
.filter_map(|block_pos| {
if let Some(block) = terrain
.get(block_pos)
.ok()
.filter(|block| block.is_solid())
{
// Calculate block AABB
Some((
block_pos,
Aabb {
min: block_pos.map(|e| e as f32),
max: block_pos.map(|e| e as f32) + Vec3::new(1.0, 1.0, block.get_height()),
},
block.get_height(),
))
} else {
None
}
})
// Determine whether the block's AABB collides with the player's AABB
.filter(|(_, block_aabb, _)| block_aabb.collides_with_aabb(player_aabb))
// Find the maximum of the minimum collision axes (this bit is weird, trust me that it works)
.min_by_key(|(_, block_aabb, _)| {
((block_aabb.center() - player_aabb.center() - Vec3::unit_z() * 0.5)
.map(|e| e.abs())
.sum()
* 1_000_000.0) as i32
})
.expect("Collision detected, but no colliding blocks found!");
// Find the intrusion vector of the collision
let dir = player_aabb.collision_vector_with_aabb(block_aabb);
// Determine an appropriate resolution vector (i.e: the minimum distance
// needed to push out of the block)
let max_axis = dir.map(|e| e.abs()).reduce_partial_min();
let resolve_dir = -dir.map(|e| {
if e.abs().to_bits() == max_axis.to_bits() {
e
} else {
0.0
}
});
// When the resolution direction is pointing upwards, we must be on the
// ground
if resolve_dir.z > 0.0 && vel.0.z <= 0.0 {
on_ground = true;
if !was_on_ground {
event_emitter
.emit(ServerEvent::LandOnGround { entity, vel: vel.0 });
}
} else if resolve_dir.z < 0.0 && vel.0.z >= 0.0 {
on_ceiling = true;
} }
})
// Determine whether the block's AABB collides with the player's AABB
.filter(|(_, block_aabb, _)| block_aabb.collides_with_aabb(player_aabb))
// Find the maximum of the minimum collision axes (this bit is weird, trust me that it works)
.min_by_key(|(_, block_aabb, _)| {
((block_aabb.center() - player_aabb.center() - Vec3::unit_z() * 0.5)
.map(|e| e.abs())
.sum()
* 1_000_000.0) as i32
})
.expect("Collision detected, but no colliding blocks found!");
// Find the intrusion vector of the collision // When the resolution direction is non-vertical, we must be colliding
let dir = player_aabb.collision_vector_with_aabb(block_aabb); // with a wall If the space above is free...
if !collision_with(Vec3::new(pos.0.x, pos.0.y, (pos.0.z + 0.1).ceil()), &|block| block.is_solid(), near_iter.clone())
// ...and we're being pushed out horizontally...
&& resolve_dir.z == 0.0
// ...and the vertical resolution direction is sufficiently great...
&& -dir.z > 0.1
// ...and we're falling/standing OR there is a block *directly* beneath our current origin (note: not hitbox)...
&& (vel.0.z <= 0.0 || terrain
.get((pos.0 - Vec3::unit_z() * 0.1).map(|e| e.floor() as i32))
.map(|block| block.is_solid())
.unwrap_or(false))
// ...and there is a collision with a block beneath our current hitbox...
&& collision_with(
old_pos + resolve_dir - Vec3::unit_z() * 1.05,
&|block| block.is_solid(),
near_iter.clone(),
)
{
// ...block-hop!
pos.0.z = (pos.0.z + 0.1).floor() + block_height;
vel.0.z = 0.0;
on_ground = true;
break;
} else {
// Correct the velocity
vel.0 = vel.0.map2(resolve_dir, |e, d| {
if d * e.signum() < 0.0 { 0.0 } else { e }
});
}
// Determine an appropriate resolution vector (i.e: the minimum distance needed // Resolve the collision normally
// to push out of the block) pos.0 += resolve_dir;
let max_axis = dir.map(|e| e.abs()).reduce_partial_min();
let resolve_dir = -dir.map(|e| { attempts += 1;
if e.abs().to_bits() == max_axis.to_bits() {
e
} else {
0.0
} }
});
// When the resolution direction is pointing upwards, we must be on the ground if attempts == MAX_ATTEMPTS {
if resolve_dir.z > 0.0 && vel.0.z <= 0.0 { pos.0 = old_pos;
on_ground = true; break;
if !was_on_ground {
event_emitter.emit(ServerEvent::LandOnGround { entity, vel: vel.0 });
} }
} }
// When the resolution direction is non-vertical, we must be colliding with a if on_ceiling {
// wall If the space above is free... physics_state.on_ceiling = true;
if !collision_with(Vec3::new(pos.0.x, pos.0.y, (pos.0.z + 0.1).ceil()), &|block| block.is_solid(), near_iter.clone()) }
// ...and we're being pushed out horizontally...
&& resolve_dir.z == 0.0 if on_ground {
// ...and the vertical resolution direction is sufficiently great... physics_state.on_ground = true;
&& -dir.z > 0.1 // If the space below us is free, then "snap" to the ground
// ...and we're falling/standing OR there is a block *directly* beneath our current origin (note: not hitbox)... } else if collision_with(
&& (vel.0.z <= 0.0 || terrain pos.0 - Vec3::unit_z() * 1.05,
.get((pos.0 - Vec3::unit_z() * 0.1).map(|e| e.floor() as i32)) &|block| block.is_solid(),
.map(|block| block.is_solid()) near_iter.clone(),
.unwrap_or(false)) ) && vel.0.z < 0.0
// ...and there is a collision with a block beneath our current hitbox... && vel.0.z > -1.5
&& collision_with( && was_on_ground
old_pos + resolve_dir - Vec3::unit_z() * 1.05, && !collision_with(
&|block| block.is_solid(), pos.0 - Vec3::unit_z() * 0.05,
&|block| {
block.is_solid()
&& block.get_height() >= (pos.0.z - 0.05).rem_euclid(1.0)
},
near_iter.clone(), near_iter.clone(),
) )
{ {
// ...block-hop! let snap_height = terrain
pos.0.z = (pos.0.z + 0.1).floor() + block_height; .get(
vel.0.z = 0.0; Vec3::new(pos.0.x, pos.0.y, pos.0.z - 0.05)
on_ground = true; .map(|e| e.floor() as i32),
break; )
} else { .ok()
// Correct the velocity .filter(|block| block.is_solid())
vel.0 = vel.0.map2( .map(|block| block.get_height())
resolve_dir, .unwrap_or(0.0);
|e, d| if d * e.signum() < 0.0 { 0.0 } else { e }, pos.0.z = (pos.0.z - 0.05).floor() + snap_height;
); physics_state.on_ground = true;
} }
// Resolve the collision normally let dirs = [
pos.0 += resolve_dir; Vec3::unit_x(),
Vec3::unit_y(),
-Vec3::unit_x(),
-Vec3::unit_y(),
];
attempts += 1; if let (wall_dir, true) =
} dirs.iter().fold((Vec3::zero(), false), |(a, hit), dir| {
if collision_with(
pos.0 + *dir * 0.01,
&|block| block.is_solid(),
near_iter.clone(),
) {
(a + dir, true)
} else {
(a, hit)
}
})
{
physics_state.on_wall = Some(wall_dir);
} else {
physics_state.on_wall = None;
}
if attempts == MAX_ATTEMPTS { // Figure out if we're in water
pos.0 = old_pos; physics_state.in_fluid =
break; collision_with(pos.0, &|block| block.is_fluid(), near_iter.clone());
} },
Collider::Point => {
let (dist, block) = terrain.ray(pos.0, pos.0 + pos_delta).ignore_error().cast();
pos.0 += pos_delta.try_normalized().unwrap_or(Vec3::zero()) * dist;
// Can't fair since we do ignore_error above
if block.unwrap().is_some() {
let block_center = pos.0.map(|e| e.floor()) + 0.5;
let block_rpos = (pos.0 - block_center)
.try_normalized()
.unwrap_or(Vec3::zero());
// See whether we're on the top/bottom of a block, or the side
if block_rpos.z.abs()
> block_rpos.xy().map(|e| e.abs()).reduce_partial_max()
{
if block_rpos.z > 0.0 {
physics_state.on_ground = true;
} else {
physics_state.on_ceiling = true;
}
vel.0.z = 0.0;
} else {
physics_state.on_wall =
Some(if block_rpos.x.abs() > block_rpos.y.abs() {
vel.0.x = 0.0;
Vec3::unit_x() * -block_rpos.x.signum()
} else {
vel.0.y = 0.0;
Vec3::unit_y() * -block_rpos.y.signum()
});
}
}
},
} }
if on_ground {
physics_state.on_ground = true;
// If the space below us is free, then "snap" to the ground
} else if collision_with(
pos.0 - Vec3::unit_z() * 1.05,
&|block| block.is_solid(),
near_iter.clone(),
) && vel.0.z < 0.0
&& vel.0.z > -1.5
&& was_on_ground
&& !collision_with(
pos.0 - Vec3::unit_z() * 0.05,
&|block| {
block.is_solid() && block.get_height() >= (pos.0.z - 0.05).rem_euclid(1.0)
},
near_iter.clone(),
)
{
let snap_height = terrain
.get(Vec3::new(pos.0.x, pos.0.y, pos.0.z - 0.05).map(|e| e.floor() as i32))
.ok()
.filter(|block| block.is_solid())
.map(|block| block.get_height())
.unwrap_or(0.0);
pos.0.z = (pos.0.z - 0.05).floor() + snap_height;
physics_state.on_ground = true;
}
let dirs = [
Vec3::unit_x(),
Vec3::unit_y(),
-Vec3::unit_x(),
-Vec3::unit_y(),
];
if let (wall_dir, true) = dirs.iter().fold((Vec3::zero(), false), |(a, hit), dir| {
if collision_with(
pos.0 + *dir * 0.01,
&|block| block.is_solid(),
near_iter.clone(),
) {
(a + dir, true)
} else {
(a, hit)
}
}) {
physics_state.on_wall = Some(wall_dir);
} else {
physics_state.on_wall = None;
}
// Figure out if we're in water
physics_state.in_fluid =
collision_with(pos.0, &|block| block.is_fluid(), near_iter.clone());
let _ = physics_states.insert(entity, physics_state); let _ = physics_states.insert(entity, physics_state);
} }
@ -369,7 +433,7 @@ impl<'a> System<'a> for Sys {
scales.maybe(), scales.maybe(),
masses.maybe(), masses.maybe(),
&mut velocities, &mut velocities,
&bodies, &colliders,
!&mountings, !&mountings,
stickies.maybe(), stickies.maybe(),
&mut physics_states, &mut physics_states,
@ -389,7 +453,7 @@ impl<'a> System<'a> for Sys {
&positions, &positions,
scales.maybe(), scales.maybe(),
masses.maybe(), masses.maybe(),
&bodies, &colliders,
!&mountings, !&mountings,
) )
.join() .join()

View File

@ -57,28 +57,9 @@ impl<'a> System<'a> for Sys {
) )
.join() .join()
{ {
// Hit ground // Hit something solid
if physics.on_ground { if physics.on_wall.is_some() || physics.on_ground || physics.on_ceiling {
for effect in projectile.hit_ground.drain(..) { for effect in projectile.hit_solid.drain(..) {
match effect {
projectile::Effect::Explode { power } => {
server_emitter.emit(ServerEvent::Explosion {
pos: pos.0,
power,
owner: projectile.owner,
})
},
projectile::Effect::Vanish => server_emitter.emit(ServerEvent::Destroy {
entity,
cause: HealthSource::World,
}),
_ => {},
}
}
}
// Hit wall
else if physics.on_wall.is_some() {
for effect in projectile.hit_wall.drain(..) {
match effect { match effect {
projectile::Effect::Explode { power } => { projectile::Effect::Explode { power } => {
server_emitter.emit(ServerEvent::Explosion { server_emitter.emit(ServerEvent::Explosion {

View File

@ -92,11 +92,21 @@ impl StateExt for State {
.with(pos) .with(pos)
.with(comp::Vel(Vec3::zero())) .with(comp::Vel(Vec3::zero()))
.with(comp::Ori::default()) .with(comp::Ori::default())
.with(comp::Collider::Box {
radius: 0.4,
z_min: 0.0,
z_max: 1.75,
})
.with(comp::Controller::default()) .with(comp::Controller::default())
.with(body) .with(body)
.with(stats) .with(stats)
.with(comp::Alignment::Npc) .with(comp::Alignment::Npc)
.with(comp::Energy::new(500)) .with(comp::Energy::new(500))
.with(comp::Collider::Box {
radius: 0.4,
z_min: 0.0,
z_max: 1.75,
})
.with(comp::Gravity(1.0)) .with(comp::Gravity(1.0))
.with(comp::CharacterState::default()) .with(comp::CharacterState::default())
.with(loadout) .with(loadout)
@ -111,6 +121,11 @@ impl StateExt for State {
.with(comp::Ori::default()) .with(comp::Ori::default())
.with(comp::Body::Object(object)) .with(comp::Body::Object(object))
.with(comp::Mass(100.0)) .with(comp::Mass(100.0))
.with(comp::Collider::Box {
radius: 0.4,
z_min: 0.0,
z_max: 0.9,
})
.with(comp::Gravity(1.0)) .with(comp::Gravity(1.0))
//.with(comp::LightEmitter::default()) //.with(comp::LightEmitter::default())
} }
@ -129,6 +144,7 @@ impl StateExt for State {
.with(vel) .with(vel)
.with(comp::Ori(Dir::from_unnormalized(vel.0).unwrap_or_default())) .with(comp::Ori(Dir::from_unnormalized(vel.0).unwrap_or_default()))
.with(comp::Mass(0.0)) .with(comp::Mass(0.0))
.with(comp::Collider::Point)
.with(body) .with(body)
.with(projectile) .with(projectile)
.with(comp::Sticky) .with(comp::Sticky)
@ -154,6 +170,11 @@ impl StateExt for State {
self.write_component(entity, comp::Pos(spawn_point)); self.write_component(entity, comp::Pos(spawn_point));
self.write_component(entity, comp::Vel(Vec3::zero())); self.write_component(entity, comp::Vel(Vec3::zero()));
self.write_component(entity, comp::Ori::default()); self.write_component(entity, comp::Ori::default());
self.write_component(entity, comp::Collider::Box {
radius: 0.4,
z_min: 0.0,
z_max: 1.75,
});
self.write_component(entity, comp::Gravity(1.0)); self.write_component(entity, comp::Gravity(1.0));
self.write_component(entity, comp::CharacterState::default()); self.write_component(entity, comp::CharacterState::default());
self.write_component(entity, comp::Alignment::Owned(entity)); self.write_component(entity, comp::Alignment::Owned(entity));

View File

@ -1,8 +1,8 @@
use super::SysTimer; use super::SysTimer;
use common::{ use common::{
comp::{ comp::{
Body, CanBuild, CharacterState, Energy, Gravity, Item, LightEmitter, Loadout, Mass, Body, CanBuild, CharacterState, Collider, Energy, Gravity, Item, LightEmitter, Loadout,
MountState, Mounting, Ori, Player, Pos, Scale, Stats, Sticky, Vel, Mass, MountState, Mounting, Ori, Player, Pos, Scale, Stats, Sticky, Vel,
}, },
msg::EcsCompPacket, msg::EcsCompPacket,
sync::{CompSyncPackage, EntityPackage, EntitySyncPackage, Uid, UpdateTracker, WorldSyncExt}, sync::{CompSyncPackage, EntityPackage, EntitySyncPackage, Uid, UpdateTracker, WorldSyncExt},
@ -49,6 +49,7 @@ pub struct TrackedComps<'a> {
pub mounting: ReadStorage<'a, Mounting>, pub mounting: ReadStorage<'a, Mounting>,
pub mount_state: ReadStorage<'a, MountState>, pub mount_state: ReadStorage<'a, MountState>,
pub mass: ReadStorage<'a, Mass>, pub mass: ReadStorage<'a, Mass>,
pub collider: ReadStorage<'a, Collider>,
pub sticky: ReadStorage<'a, Sticky>, pub sticky: ReadStorage<'a, Sticky>,
pub gravity: ReadStorage<'a, Gravity>, pub gravity: ReadStorage<'a, Gravity>,
pub loadout: ReadStorage<'a, Loadout>, pub loadout: ReadStorage<'a, Loadout>,
@ -104,6 +105,10 @@ impl<'a> TrackedComps<'a> {
.cloned() .cloned()
.map(|c| comps.push(c.into())); .map(|c| comps.push(c.into()));
self.mass.get(entity).copied().map(|c| comps.push(c.into())); self.mass.get(entity).copied().map(|c| comps.push(c.into()));
self.collider
.get(entity)
.copied()
.map(|c| comps.push(c.into()));
self.sticky self.sticky
.get(entity) .get(entity)
.copied() .copied()
@ -142,6 +147,7 @@ pub struct ReadTrackers<'a> {
pub mounting: ReadExpect<'a, UpdateTracker<Mounting>>, pub mounting: ReadExpect<'a, UpdateTracker<Mounting>>,
pub mount_state: ReadExpect<'a, UpdateTracker<MountState>>, pub mount_state: ReadExpect<'a, UpdateTracker<MountState>>,
pub mass: ReadExpect<'a, UpdateTracker<Mass>>, pub mass: ReadExpect<'a, UpdateTracker<Mass>>,
pub collider: ReadExpect<'a, UpdateTracker<Collider>>,
pub sticky: ReadExpect<'a, UpdateTracker<Sticky>>, pub sticky: ReadExpect<'a, UpdateTracker<Sticky>>,
pub gravity: ReadExpect<'a, UpdateTracker<Gravity>>, pub gravity: ReadExpect<'a, UpdateTracker<Gravity>>,
pub loadout: ReadExpect<'a, UpdateTracker<Loadout>>, pub loadout: ReadExpect<'a, UpdateTracker<Loadout>>,
@ -173,6 +179,7 @@ impl<'a> ReadTrackers<'a> {
.with_component(&comps.uid, &*self.mounting, &comps.mounting, filter) .with_component(&comps.uid, &*self.mounting, &comps.mounting, filter)
.with_component(&comps.uid, &*self.mount_state, &comps.mount_state, filter) .with_component(&comps.uid, &*self.mount_state, &comps.mount_state, filter)
.with_component(&comps.uid, &*self.mass, &comps.mass, filter) .with_component(&comps.uid, &*self.mass, &comps.mass, filter)
.with_component(&comps.uid, &*self.collider, &comps.collider, filter)
.with_component(&comps.uid, &*self.sticky, &comps.sticky, filter) .with_component(&comps.uid, &*self.sticky, &comps.sticky, filter)
.with_component(&comps.uid, &*self.gravity, &comps.gravity, filter) .with_component(&comps.uid, &*self.gravity, &comps.gravity, filter)
.with_component(&comps.uid, &*self.loadout, &comps.loadout, filter) .with_component(&comps.uid, &*self.loadout, &comps.loadout, filter)
@ -201,6 +208,7 @@ pub struct WriteTrackers<'a> {
mounting: WriteExpect<'a, UpdateTracker<Mounting>>, mounting: WriteExpect<'a, UpdateTracker<Mounting>>,
mount_state: WriteExpect<'a, UpdateTracker<MountState>>, mount_state: WriteExpect<'a, UpdateTracker<MountState>>,
mass: WriteExpect<'a, UpdateTracker<Mass>>, mass: WriteExpect<'a, UpdateTracker<Mass>>,
collider: WriteExpect<'a, UpdateTracker<Collider>>,
sticky: WriteExpect<'a, UpdateTracker<Sticky>>, sticky: WriteExpect<'a, UpdateTracker<Sticky>>,
gravity: WriteExpect<'a, UpdateTracker<Gravity>>, gravity: WriteExpect<'a, UpdateTracker<Gravity>>,
loadout: WriteExpect<'a, UpdateTracker<Loadout>>, loadout: WriteExpect<'a, UpdateTracker<Loadout>>,
@ -221,6 +229,7 @@ fn record_changes(comps: &TrackedComps, trackers: &mut WriteTrackers) {
trackers.mounting.record_changes(&comps.mounting); trackers.mounting.record_changes(&comps.mounting);
trackers.mount_state.record_changes(&comps.mount_state); trackers.mount_state.record_changes(&comps.mount_state);
trackers.mass.record_changes(&comps.mass); trackers.mass.record_changes(&comps.mass);
trackers.collider.record_changes(&comps.collider);
trackers.sticky.record_changes(&comps.sticky); trackers.sticky.record_changes(&comps.sticky);
trackers.gravity.record_changes(&comps.gravity); trackers.gravity.record_changes(&comps.gravity);
trackers.loadout.record_changes(&comps.loadout); trackers.loadout.record_changes(&comps.loadout);
@ -242,6 +251,7 @@ pub fn register_trackers(world: &mut World) {
world.register_tracker::<Mounting>(); world.register_tracker::<Mounting>();
world.register_tracker::<MountState>(); world.register_tracker::<MountState>();
world.register_tracker::<Mass>(); world.register_tracker::<Mass>();
world.register_tracker::<Collider>();
world.register_tracker::<Sticky>(); world.register_tracker::<Sticky>();
world.register_tracker::<Gravity>(); world.register_tracker::<Gravity>();
world.register_tracker::<Loadout>(); world.register_tracker::<Loadout>();

View File

@ -88,6 +88,7 @@ fn maps_idle() {
&CharacterState::Idle {}, &CharacterState::Idle {},
&PhysicsState { &PhysicsState {
on_ground: true, on_ground: true,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -111,6 +112,7 @@ fn maps_run_with_sufficient_velocity() {
&CharacterState::Idle {}, &CharacterState::Idle {},
&PhysicsState { &PhysicsState {
on_ground: true, on_ground: true,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -134,6 +136,7 @@ fn does_not_map_run_with_insufficient_velocity() {
&CharacterState::Idle {}, &CharacterState::Idle {},
&PhysicsState { &PhysicsState {
on_ground: true, on_ground: true,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -157,6 +160,7 @@ fn does_not_map_run_with_sufficient_velocity_but_not_on_ground() {
&CharacterState::Idle {}, &CharacterState::Idle {},
&PhysicsState { &PhysicsState {
on_ground: false, on_ground: false,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -183,6 +187,7 @@ fn maps_roll() {
}), }),
&PhysicsState { &PhysicsState {
on_ground: true, on_ground: true,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -206,6 +211,7 @@ fn maps_land_on_ground_to_run() {
&CharacterState::Idle {}, &CharacterState::Idle {},
&PhysicsState { &PhysicsState {
on_ground: true, on_ground: true,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -229,6 +235,7 @@ fn maps_glider_open() {
&CharacterState::Glide {}, &CharacterState::Glide {},
&PhysicsState { &PhysicsState {
on_ground: false, on_ground: false,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -252,6 +259,7 @@ fn maps_glide() {
&CharacterState::Glide {}, &CharacterState::Glide {},
&PhysicsState { &PhysicsState {
on_ground: false, on_ground: false,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -275,6 +283,7 @@ fn maps_glider_close_when_closing_mid_flight() {
&CharacterState::Idle {}, &CharacterState::Idle {},
&PhysicsState { &PhysicsState {
on_ground: false, on_ground: false,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -299,6 +308,7 @@ fn maps_glider_close_when_landing() {
&CharacterState::Idle {}, &CharacterState::Idle {},
&PhysicsState { &PhysicsState {
on_ground: true, on_ground: true,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -335,6 +345,7 @@ fn maps_wield_while_equipping() {
}), }),
&PhysicsState { &PhysicsState {
on_ground: true, on_ground: true,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -369,6 +380,7 @@ fn maps_unwield() {
&CharacterState::default(), &CharacterState::default(),
&PhysicsState { &PhysicsState {
on_ground: true, on_ground: true,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,
@ -391,6 +403,7 @@ fn maps_quadrupeds_running() {
let result = MovementEventMapper::map_non_humanoid_movement_event( let result = MovementEventMapper::map_non_humanoid_movement_event(
&PhysicsState { &PhysicsState {
on_ground: true, on_ground: true,
on_ceiling: false,
on_wall: None, on_wall: None,
touch_entity: None, touch_entity: None,
in_fluid: false, in_fluid: false,