Compare commits

..
6 Commits
Author SHA1 Message Date
EIREXE cbb357d30a Implement Melee-style knockback stacking (#97)
CI / build-and-test (push) Successful in 2m11s
CI / production-build (push) Successful in 12m25s
## Summary

- stack residual airborne knockback per axis after the configured launch-frame threshold
- apply DI after combining the launch vectors while retaining the second hit's hitstun
- preserve and decay residual knockback after hitstun
- make stacking state rollback-safe and include it in debug save states
- clear launch state on landing, ledge interactions, KO, and respawn

## Testing

- `cargo check --tests`
- `cargo test` (159 tests passed)
- `git diff --check`

## Asset configuration

For Melee timing, `knockback_stacking_window` should be set to `10`. The local ignored asset package has been updated accordingly.

Reviewed-on: #97
Co-authored-by: Álex Román Núñez <eirexe@eirteam.moe>
2026-10-25 21:02:13 +00:00
EIREXE 7f720119fa Fix hitbox editor and add dair
CI / build-and-test (push) Canceled after 0s
CI / production-build (push) Canceled after 0s
2026-10-22 11:53:38 +02:00
EIREXE 9dfae1de77 Implement land from below, fix attacks not lifting fighters off the ground (#96)
CI / build-and-test (push) Successful in 1m44s
CI / production-build (push) Successful in 12m17s
Reviewed-on: #96
Co-authored-by: Álex Román Núñez <eirexe@eirteam.moe>
2026-10-14 18:33:17 +00:00
EIREXE 4185bd90d5 Add waveland snapping (#95)
CI / build-and-test (push) Successful in 2m16s
CI / production-build (push) Successful in 12m36s
Reviewed-on: #95
Co-authored-by: Álex Román Núñez <eirexe@eirteam.moe>
2026-10-14 06:27:51 +00:00
EIREXE 472a0b6a19 Improve ECB behaviour, add ECB interpolation, wall/ceiling support etc (#94)
CI / build-and-test (push) Successful in 1m43s
CI / production-build (push) Successful in 11m52s
Reviewed-on: #94
Co-authored-by: Álex Román Núñez <eirexe@eirteam.moe>
2026-10-13 19:20:29 +00:00
EIREXE f1da5c1172 Add ledge getup, ledge intangibility limit & fix walk-off velocity (#93)
CI / production-build (push) Successful in 12m14s
CI / build-and-test (push) Successful in 1m40s
Reviewed-on: #93
Co-authored-by: Álex Román Núñez <eirexe@eirteam.moe>
2026-10-13 15:52:10 +00:00
24 changed files with 1440 additions and 252 deletions
+29 -6
View File
@@ -1,12 +1,26 @@
use bevy::prelude::*; use bevy::prelude::*;
use crate::{ use crate::{
camera::MatchCamera, fighter::{ camera::MatchCamera,
FighterECB, FighterFacingDirection, FighterHitboxes, FighterHitstop, FighterHitstopShake, FighterInvulnerabilityState, FighterPendingRespawn, FighterPreviousFacingDirection, FighterPreviousTranslation, FighterSurfaceState, FighterTranslation, FighterVelocity, animation::FighterAnimationFrame, attack::{ fighter::{
FighterDamage, FighterKnockbackVelocity, FighterPendingHitReaction, FighterPendingHits, FighterECB, FighterFacingDirection, FighterHitboxes, FighterHitstop, FighterHitstopShake,
FighterSolvedHurtboxes, FighterStaleMoveQueue, FighterInvulnerabilityState, FighterLedgeInformation, FighterPendingRespawn,
}, baked_animation::FighterBoneMatrices, state::FighterState, FighterPreviousFacingDirection, FighterPreviousTranslation, FighterSurfaceState,
}, input::FighterInput, match_runtime::MatchState, player::Player, stage::line::StageCollision, FighterTranslation, FighterVelocity,
animation::FighterAnimationFrame,
attack::{
FighterDamage, FighterKnockbackState, FighterKnockbackVelocity,
FighterPendingHitReaction, FighterPendingHits, FighterSolvedHurtboxes,
FighterStaleMoveQueue,
},
baked_animation::FighterBoneMatrices,
ecb::FighterDesiredECB,
state::FighterState,
},
input::FighterInput,
match_runtime::MatchState,
player::Player,
stage::line::StageCollision,
}; };
#[derive(Resource, Default)] #[derive(Resource, Default)]
@@ -27,6 +41,7 @@ struct FighterCheckpoint {
entity: Entity, entity: Entity,
handle: usize, handle: usize,
ecb: FighterECB, ecb: FighterECB,
desired_ecb: FighterDesiredECB,
previous_ecb: crate::fighter::ecb::FighterPreviousECB, previous_ecb: crate::fighter::ecb::FighterPreviousECB,
velocity: FighterVelocity, velocity: FighterVelocity,
translation: FighterTranslation, translation: FighterTranslation,
@@ -41,6 +56,7 @@ struct FighterCheckpoint {
hitstop: FighterHitstop, hitstop: FighterHitstop,
hitstop_shake: FighterHitstopShake, hitstop_shake: FighterHitstopShake,
knockback_velocity: FighterKnockbackVelocity, knockback_velocity: FighterKnockbackVelocity,
knockback_state: FighterKnockbackState,
stale_moves: FighterStaleMoveQueue, stale_moves: FighterStaleMoveQueue,
hitboxes: FighterHitboxes, hitboxes: FighterHitboxes,
solved_hurtboxes: FighterSolvedHurtboxes, solved_hurtboxes: FighterSolvedHurtboxes,
@@ -48,6 +64,7 @@ struct FighterCheckpoint {
surface: FighterSurfaceState, surface: FighterSurfaceState,
pending_respawn: FighterPendingRespawn, pending_respawn: FighterPendingRespawn,
invulnerability_state: FighterInvulnerabilityState, invulnerability_state: FighterInvulnerabilityState,
ledge_information: FighterLedgeInformation,
} }
pub(super) fn save_or_restore(world: &mut World) { pub(super) fn save_or_restore(world: &mut World) {
@@ -130,6 +147,7 @@ pub(super) fn save_or_restore(world: &mut World) {
let mut entity = world.entity_mut(saved.entity); let mut entity = world.entity_mut(saved.entity);
entity.insert(saved.ecb); entity.insert(saved.ecb);
entity.insert(saved.desired_ecb);
entity.insert(saved.previous_ecb); entity.insert(saved.previous_ecb);
entity.insert(saved.velocity); entity.insert(saved.velocity);
entity.insert(saved.translation); entity.insert(saved.translation);
@@ -144,6 +162,7 @@ pub(super) fn save_or_restore(world: &mut World) {
entity.insert(saved.hitstop); entity.insert(saved.hitstop);
entity.insert(saved.hitstop_shake); entity.insert(saved.hitstop_shake);
entity.insert(saved.knockback_velocity); entity.insert(saved.knockback_velocity);
entity.insert(saved.knockback_state);
entity.insert(saved.stale_moves.clone()); entity.insert(saved.stale_moves.clone());
entity.insert(saved.hitboxes.clone()); entity.insert(saved.hitboxes.clone());
entity.insert(saved.solved_hurtboxes.clone()); entity.insert(saved.solved_hurtboxes.clone());
@@ -151,6 +170,7 @@ pub(super) fn save_or_restore(world: &mut World) {
entity.insert(saved.surface.clone()); entity.insert(saved.surface.clone());
entity.insert(saved.pending_respawn.clone()); entity.insert(saved.pending_respawn.clone());
entity.insert(saved.invulnerability_state.clone()); entity.insert(saved.invulnerability_state.clone());
entity.insert(saved.ledge_information.clone());
} }
world.insert_resource(checkpoint.pending_hits.clone()); world.insert_resource(checkpoint.pending_hits.clone());
world.insert_resource(checkpoint.stage_collision); world.insert_resource(checkpoint.stage_collision);
@@ -167,6 +187,7 @@ fn capture_fighter(world: &World, entity: Entity) -> Option<FighterCheckpoint> {
entity, entity,
handle: fighter.get::<Player>()?.handle, handle: fighter.get::<Player>()?.handle,
ecb: *fighter.get::<FighterECB>()?, ecb: *fighter.get::<FighterECB>()?,
desired_ecb: *fighter.get::<FighterDesiredECB>()?,
previous_ecb: *fighter.get::<crate::fighter::ecb::FighterPreviousECB>()?, previous_ecb: *fighter.get::<crate::fighter::ecb::FighterPreviousECB>()?,
velocity: *fighter.get::<FighterVelocity>()?, velocity: *fighter.get::<FighterVelocity>()?,
translation: *fighter.get::<FighterTranslation>()?, translation: *fighter.get::<FighterTranslation>()?,
@@ -181,6 +202,7 @@ fn capture_fighter(world: &World, entity: Entity) -> Option<FighterCheckpoint> {
hitstop: *fighter.get::<FighterHitstop>()?, hitstop: *fighter.get::<FighterHitstop>()?,
hitstop_shake: *fighter.get::<FighterHitstopShake>()?, hitstop_shake: *fighter.get::<FighterHitstopShake>()?,
knockback_velocity: *fighter.get::<FighterKnockbackVelocity>()?, knockback_velocity: *fighter.get::<FighterKnockbackVelocity>()?,
knockback_state: *fighter.get::<FighterKnockbackState>()?,
stale_moves: fighter.get::<FighterStaleMoveQueue>()?.clone(), stale_moves: fighter.get::<FighterStaleMoveQueue>()?.clone(),
hitboxes: fighter.get::<FighterHitboxes>()?.clone(), hitboxes: fighter.get::<FighterHitboxes>()?.clone(),
solved_hurtboxes: fighter.get::<FighterSolvedHurtboxes>()?.clone(), solved_hurtboxes: fighter.get::<FighterSolvedHurtboxes>()?.clone(),
@@ -188,6 +210,7 @@ fn capture_fighter(world: &World, entity: Entity) -> Option<FighterCheckpoint> {
surface: fighter.get::<FighterSurfaceState>()?.clone(), surface: fighter.get::<FighterSurfaceState>()?.clone(),
pending_respawn: fighter.get::<FighterPendingRespawn>()?.clone(), pending_respawn: fighter.get::<FighterPendingRespawn>()?.clone(),
invulnerability_state: fighter.get::<FighterInvulnerabilityState>()?.clone(), invulnerability_state: fighter.get::<FighterInvulnerabilityState>()?.clone(),
ledge_information: fighter.get::<FighterLedgeInformation>()?.clone(),
}) })
} }
+1
View File
@@ -104,6 +104,7 @@ pub enum AnimKind {
AttackDownTilt, AttackDownTilt,
AttackNeutralAir, AttackNeutralAir,
AttackForwardAir, AttackForwardAir,
AttackDownAir,
AttackDash, AttackDash,
AttackUpSmash, AttackUpSmash,
} }
+32 -3
View File
@@ -15,6 +15,16 @@ pub fn apply_directional_influence(
let (sin, cos) = attack_angle.sin_cos(); let (sin, cos) = attack_angle.sin_cos();
let base_launch_direction = FGVec2::new(cos, sin); let base_launch_direction = FGVec2::new(cos, sin);
apply_directional_influence_to_direction(receiver_stick, base_launch_direction, di_max_angle)
}
/// Applies DI to an already-computed launch direction. This is used after
/// knockback stacking, where the resulting angle may differ from either hit.
pub fn apply_directional_influence_to_direction(
receiver_stick: FGVec2,
base_launch_direction: FGVec2,
di_max_angle: FGi32,
) -> FGVec2 {
let Some(base_launch_direction) = base_launch_direction.normalize() else { let Some(base_launch_direction) = base_launch_direction.normalize() else {
return FGVec2::ZERO; return FGVec2::ZERO;
}; };
@@ -30,14 +40,20 @@ pub fn apply_directional_influence(
-di_max_angle.to_fixed::<FGWide>(), -di_max_angle.to_fixed::<FGWide>(),
di_max_angle.to_fixed::<FGWide>(), di_max_angle.to_fixed::<FGWide>(),
); );
let (sin, cos) = (attack_angle + angle_change.to_fixed::<FGi32>()).sin_cos(); let (sin, cos) = angle_change.to_fixed::<FGi32>().sin_cos();
FGVec2::new(cos, sin).normalize_or_zero() FGVec2::new(
base_launch_direction.x * cos - base_launch_direction.y * sin,
base_launch_direction.x * sin + base_launch_direction.y * cos,
)
.normalize_or_zero()
} }
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use crate::{ use crate::{
fighter::attack::directional_influence::apply_directional_influence, fighter::attack::directional_influence::{
apply_directional_influence, apply_directional_influence_to_direction,
},
math::{int::FGi32, vec::FGVec2}, math::{int::FGi32, vec::FGVec2},
}; };
@@ -66,4 +82,17 @@ mod test {
assert!(di.x > FGi32::ZERO); assert!(di.x > FGi32::ZERO);
assert!(di.y < FGi32::ZERO); assert!(di.y < FGi32::ZERO);
} }
#[test]
fn vector_di_preserves_a_stacked_direction_without_input() {
let direction = FGVec2::lit("-0.6", "0.8");
let result = apply_directional_influence_to_direction(
FGVec2::ZERO,
direction,
FGi32::lit("18.0"),
);
const EPSILON: FGi32 = FGi32::from_bits(6);
assert!(result.x.abs_diff(direction.x) < EPSILON);
assert!(result.y.abs_diff(direction.y) < EPSILON);
}
} }
+117 -1
View File
@@ -33,6 +33,75 @@ use crate::{
#[derive(Deref, Component, Default, Hash, Debug, Copy, Clone)] #[derive(Deref, Component, Default, Hash, Debug, Copy, Clone)]
pub struct FighterKnockbackVelocity(pub FGVec2); pub struct FighterKnockbackVelocity(pub FGVec2);
/// Lifecycle state for the currently active launch velocity.
///
/// This counts frames where knockback was actually applied to movement; hitstop
/// therefore does not advance it. Melee uses this age to decide whether a
/// subsequent airborne hit replaces or stacks with the previous launch.
#[derive(Component, Default, Hash, Debug, Copy, Clone)]
pub struct FighterKnockbackState {
pub frames_since_launch: u32,
}
impl FighterKnockbackState {
pub fn restart(&mut self) {
self.frames_since_launch = 0;
}
pub fn clear(&mut self) {
self.frames_since_launch = 0;
}
pub fn advance(&mut self) {
self.frames_since_launch = self.frames_since_launch.saturating_add(1);
}
pub fn can_stack(&self, minimum_frames: u32) -> bool {
self.frames_since_launch >= minimum_frames
}
}
fn stack_knockback_component(previous: FGi32, new: FGi32) -> FGi32 {
if previous.is_zero() {
return new;
}
if new.is_zero() {
return previous;
}
if previous.signum() != new.signum() {
previous + new
} else if previous.abs() > new.abs() {
previous
} else {
new
}
}
/// Applies Melee's knockback-stacking rule independently to both axes.
pub fn stack_knockback(previous: FGVec2, new: FGVec2) -> FGVec2 {
FGVec2::new(
stack_knockback_component(previous.x, new.x),
stack_knockback_component(previous.y, new.y),
)
}
pub fn decay_knockback(
velocity: &mut FighterKnockbackVelocity,
state: &mut FighterKnockbackState,
decay_per_frame: FGi32,
) {
let speed = velocity.length();
let next_speed = speed.saturating_sub(decay_per_frame).max(FGi32::ZERO);
velocity.0 = velocity.normalize_or_zero() * next_speed;
if next_speed.is_zero() {
state.clear();
} else {
state.advance();
}
}
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, Component, Hash, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, Component, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct FighterDamage(FGi32); pub struct FighterDamage(FGi32);
@@ -73,6 +142,53 @@ pub struct FighterLastAttackDebug {
pub trajectory_points: Vec<Vec3>, pub trajectory_points: Vec<Vec3>,
} }
#[cfg(test)]
mod knockback_stacking_tests {
use super::*;
#[test]
fn same_direction_keeps_the_stronger_component() {
assert_eq!(
stack_knockback(FGVec2::lit("3", "8"), FGVec2::lit("5", "4")),
FGVec2::lit("5", "8")
);
}
#[test]
fn opposing_components_add_independently() {
assert_eq!(
stack_knockback(FGVec2::lit("3", "8"), FGVec2::lit("-5", "-3")),
FGVec2::lit("-2", "5")
);
}
#[test]
fn opposing_components_can_cancel() {
assert_eq!(
stack_knockback(FGVec2::lit("3", "-4"), FGVec2::lit("-3", "4")),
FGVec2::ZERO
);
}
#[test]
fn zero_components_preserve_the_nonzero_value() {
assert_eq!(
stack_knockback(FGVec2::lit("0", "2"), FGVec2::lit("-3", "0")),
FGVec2::lit("-3", "2")
);
}
#[test]
fn stacking_threshold_is_inclusive() {
let mut state = FighterKnockbackState {
frames_since_launch: 9,
};
assert!(!state.can_stack(10));
state.advance();
assert!(state.can_stack(10));
}
}
#[derive(Debug, Default, Clone, Deref, DerefMut, Hash, PartialEq, PartialOrd)] #[derive(Debug, Default, Clone, Deref, DerefMut, Hash, PartialEq, PartialOrd)]
pub struct HitStop(u32); pub struct HitStop(u32);
@@ -231,8 +347,8 @@ impl AttackKind {
AttackKind::Jab => AnimKind::AttackJab1, AttackKind::Jab => AnimKind::AttackJab1,
AttackKind::UpTilt => AnimKind::AttackUpTilt, AttackKind::UpTilt => AnimKind::AttackUpTilt,
AttackKind::ForwardAir => AnimKind::AttackForwardAir, AttackKind::ForwardAir => AnimKind::AttackForwardAir,
AttackKind::DownAir => AnimKind::AttackDownAir,
AttackKind::BackAir => AnimKind::AttackUpTilt, AttackKind::BackAir => AnimKind::AttackUpTilt,
AttackKind::DownAir => AnimKind::AttackUpTilt,
AttackKind::UpAir => AnimKind::AttackUpTilt, AttackKind::UpAir => AnimKind::AttackUpTilt,
AttackKind::DownTilt => AnimKind::AttackDownTilt, AttackKind::DownTilt => AnimKind::AttackDownTilt,
AttackKind::ForwardTilt => AnimKind::AttackForwardTilt, AttackKind::ForwardTilt => AnimKind::AttackForwardTilt,
+684 -43
View File
@@ -1,11 +1,17 @@
//! Resolving an integrated fighter position against the stage. //! Resolving an integrated fighter position against the stage.
use crate::fighter::ecb::FighterPreviousECB; use crate::fighter::ecb::{self as ecb_module, FighterDesiredECB};
use crate::fighter::{FighterECB, FighterPreviousTranslation, FighterTranslation}; use crate::fighter::{FighterPreviousTranslation, FighterTranslation};
use crate::fighter::FighterVelocity;
#[cfg(test)]
use crate::fighter::{FighterECB, ecb::FighterPreviousECB};
use crate::math::int::FGi32;
use crate::math::rect::FGRect; use crate::math::rect::FGRect;
use crate::math::segment::FGSegment2d; use crate::math::segment::FGSegment2d;
use crate::math::vec::FGVec2; use crate::math::vec::FGVec2;
use crate::stage::line::{StageCollision, StageLineID, StagePolyType, StageVertexID}; use crate::stage::line::{
StageCollision, StageLineID, StagePolyLineSegmentType, StagePolyType, StageVertexID,
};
/* /*
pub fn collide_fighter_with_scene( pub fn collide_fighter_with_scene(
fighters: Query<(&FighterECB, &mut FighterVelocity, &mut FighterTranslation)>, fighters: Query<(&FighterECB, &mut FighterVelocity, &mut FighterTranslation)>,
@@ -36,54 +42,395 @@ pub fn collide_fighter_with_scene(
pub struct AirCollisionWithStageResult { pub struct AirCollisionWithStageResult {
pub line_id: StageLineID, pub line_id: StageLineID,
pub hit_position: FGVec2, pub hit_position: FGVec2,
/// Fighter origin at the collision substep. The ECB remains local to this
/// origin; callers must not rebase the ECB by the frame-sized movement.
pub resolved_translation: FGVec2,
pub hit_normal: FGVec2, pub hit_normal: FGVec2,
} }
pub fn air_collide_with_stage( #[derive(Clone, Copy, Debug, Default)]
pub struct AirCollisionOptions {
/// Allow downward input to disable collision with pass-through platforms.
pub can_pass_through_soft_platforms: bool,
/// Treat an upward crossing of a pass-through platform by the ECB bottom as a landing.
pub land_on_soft_platforms_from_below: bool,
}
#[cfg(test)]
fn air_collide_with_stage(
prev_translation: &FighterPreviousTranslation, prev_translation: &FighterPreviousTranslation,
translation: &FighterTranslation, translation: &FighterTranslation,
prev_ecb: &FighterPreviousECB, prev_ecb: &FighterPreviousECB,
ecb: &FighterECB, ecb: &FighterECB,
stage_collision: &StageCollision, stage_collision: &StageCollision,
ignored_polys: &[usize], ignored_polys: &[usize],
can_ignore_soft_platforms: bool, options: AirCollisionOptions,
) -> Option<AirCollisionWithStageResult> { ) -> Option<AirCollisionWithStageResult> {
let ray_segment = FGSegment2d::new( let mut translation = *translation;
prev_translation.0 + prev_ecb.get_bottom_point(), let mut velocity = FighterVelocity::default();
translation.0 + ecb.get_bottom_point(), air_collide_with_stage_substepped(
); prev_translation,
&mut translation,
&mut velocity,
&mut ecb_module::FighterECB {
top: prev_ecb.top,
bottom: prev_ecb.bottom,
left: prev_ecb.left,
right: prev_ecb.right,
},
&FighterDesiredECB::from(*ecb),
stage_collision,
ignored_polys,
options,
)
}
/// Sweeps movement and ECB shape changes together.
pub(crate) fn collision_step_count(max_change: FGi32) -> u32 {
let six = FGi32::lit("6.0");
if max_change <= six {
return 1;
}
let mut quotient = 0;
let mut remainder = max_change;
while remainder >= six {
quotient += 1;
remainder -= six;
}
quotient + 1
}
pub fn air_collide_with_stage_substepped(
prev_translation: &FighterPreviousTranslation,
translation: &mut FighterTranslation,
velocity: &mut FighterVelocity,
ecb: &mut crate::fighter::FighterECB,
desired: &FighterDesiredECB,
stage_collision: &StageCollision,
ignored_polys: &[usize],
options: AirCollisionOptions,
) -> Option<AirCollisionWithStageResult> {
let requested_translation = translation.0;
let movement = requested_translation - prev_translation.0;
let mut largest_change = movement.x.abs().max(movement.y.abs());
largest_change = largest_change.max(ecb_module::ecb_max_delta(ecb, desired));
let steps = collision_step_count(largest_change);
let step_count = FGi32::from_num(steps);
let movement_per_step = movement / step_count;
let mut current_position = prev_translation.0;
let mut current_ecb = *ecb;
let mut collision_offset = FGVec2::ZERO;
for step in 0..steps {
let previous_position = current_position;
let previous_ecb = current_ecb;
let remaining_steps = FGi32::from_num(steps - step);
ecb_module::interpolate_ecb(&mut current_ecb, *desired, FGi32::ONE / remaining_steps);
current_position = if step + 1 == steps {
// Fixed-point division may truncate. Always make the final
// substep land exactly on the requested frame endpoint.
requested_translation + collision_offset
} else {
prev_translation.0
+ movement_per_step * FGi32::from_num(step + 1)
+ collision_offset
};
let lower_edges = [
(
previous_ecb.bottom,
previous_ecb.left,
current_ecb.bottom,
current_ecb.left,
),
(
previous_ecb.bottom,
previous_ecb.right,
current_ecb.bottom,
current_ecb.right,
),
];
if let Some(result) = sweep_edges(
stage_collision,
previous_position,
current_position,
&lower_edges,
StagePolyLineSegmentType::Floor,
ignored_polys,
options.can_pass_through_soft_platforms,
) {
*ecb = current_ecb;
translation.0 = current_position + result.correction;
velocity.0 -= velocity.0.project_onto_normalized(result.hit_normal);
let bottom_contact = translation.0 + current_ecb.bottom;
return Some(AirCollisionWithStageResult {
line_id: result.line_id,
hit_position: bottom_contact,
resolved_translation: translation.0,
hit_normal: result.hit_normal,
});
}
let upper_edges = [
(
previous_ecb.top,
previous_ecb.left,
current_ecb.top,
current_ecb.left,
),
(
previous_ecb.top,
previous_ecb.right,
current_ecb.top,
current_ecb.right,
),
];
if let Some(contact) = sweep_edges(
stage_collision,
previous_position,
current_position,
&upper_edges,
StagePolyLineSegmentType::Ceiling,
ignored_polys,
true,
) {
current_position += contact.correction;
collision_offset += contact.correction;
velocity.0 -= velocity.0.project_onto_normalized(contact.hit_normal);
}
if options.land_on_soft_platforms_from_below
&& let Some(result) = sweep_bottom_point_through_platforms(
stage_collision,
previous_position + previous_ecb.bottom,
current_position + current_ecb.bottom,
ignored_polys,
)
{
*ecb = current_ecb;
translation.0 = current_position + result.correction;
velocity.0 -= velocity.0.project_onto_normalized(result.hit_normal);
let bottom_contact = translation.0 + current_ecb.bottom;
return Some(AirCollisionWithStageResult {
line_id: result.line_id,
hit_position: bottom_contact,
resolved_translation: translation.0,
hit_normal: result.hit_normal,
});
}
let side_edges = [
(
previous_ecb.bottom,
previous_ecb.right,
current_ecb.bottom,
current_ecb.right,
),
(
previous_ecb.right,
previous_ecb.top,
current_ecb.right,
current_ecb.top,
),
(
previous_ecb.top,
previous_ecb.left,
current_ecb.top,
current_ecb.left,
),
(
previous_ecb.left,
previous_ecb.bottom,
current_ecb.left,
current_ecb.bottom,
),
];
if let Some(contact) = sweep_edges(
stage_collision,
previous_position,
current_position,
&side_edges,
StagePolyLineSegmentType::Wall,
ignored_polys,
true,
) {
current_position += contact.correction;
collision_offset += contact.correction;
velocity.0 -= velocity.0.project_onto_normalized(contact.hit_normal);
}
}
*ecb = current_ecb;
translation.0 = current_position;
None
}
struct PointSweepResult {
line_id: StageLineID,
hit_normal: FGVec2,
correction: FGVec2,
}
fn sweep_bottom_point_through_platforms(
stage_collision: &StageCollision,
previous_bottom: FGVec2,
current_bottom: FGVec2,
ignored_polys: &[usize],
) -> Option<PointSweepResult> {
let bottom_sweep = FGSegment2d::new(previous_bottom, current_bottom);
stage_collision stage_collision
.stage_polys .stage_polys
.iter() .iter()
.enumerate() .enumerate()
.filter(|(poly_idx, poly)| { .filter(|(poly_idx, poly)| {
!ignored_polys.contains(poly_idx) !ignored_polys.contains(poly_idx) && matches!(poly.poly_type, StagePolyType::Platform)
&& !(can_ignore_soft_platforms && matches!(poly.poly_type, StagePolyType::Platform))
}) })
.filter_map(|(poly_idx, poly)| { .flat_map(|(poly_idx, poly)| {
poly.intersect_ray(ray_segment).map(|intersect_result| { poly.segments
( .iter()
AirCollisionWithStageResult { .enumerate()
line_id: { .filter(|(_, segment)| {
StageLineID { matches!(segment.segment_type, StagePolyLineSegmentType::Floor)
})
.filter_map(move |(segment_idx, segment)| {
let previous_distance = segment
.normal
.dot(previous_bottom - segment.segment.point1());
let current_distance = segment
.normal
.dot(current_bottom - segment.segment.point1());
if previous_distance >= crate::math::int::FGWide::ZERO
|| current_distance < crate::math::int::FGWide::ZERO
{
return None;
}
let hit_position = segment.segment.segment_intersection(&bottom_sweep)?;
Some((
PointSweepResult {
line_id: StageLineID {
polygon: poly_idx, polygon: poly_idx,
segment: intersect_result.segment_idx, segment: segment_idx,
} },
hit_normal: segment.normal,
correction: hit_position - current_bottom,
}, },
hit_position: intersect_result.position, hit_position.distance_squared(previous_bottom),
hit_normal: intersect_result.normal, ))
}, })
intersect_result })
.position .min_by_key(|(_, distance)| *distance)
.distance_squared(ray_segment.point2()), .map(|(result, _)| result)
) }
})
fn sweep_edges(
stage_collision: &StageCollision,
previous_position: FGVec2,
current_position: FGVec2,
edges: &[(FGVec2, FGVec2, FGVec2, FGVec2)],
segment_type: StagePolyLineSegmentType,
ignored_polys: &[usize],
ignore_platforms: bool,
) -> Option<PointSweepResult> {
stage_collision
.stage_polys
.iter()
.enumerate()
.filter(|(poly_idx, poly)| {
!ignored_polys.contains(poly_idx)
&& !(ignore_platforms && matches!(poly.poly_type, StagePolyType::Platform))
})
.flat_map(|(poly_idx, poly)| {
poly.segments
.iter()
.enumerate()
.filter(move |(_, segment)| segment.segment_type == segment_type)
.filter_map(move |(segment_idx, segment)| {
edges
.iter()
.filter_map(|(previous_a, previous_b, current_a, current_b)| {
let previous_a = previous_position + *previous_a;
let previous_b = previous_position + *previous_b;
let current_a = current_position + *current_a;
let current_b = current_position + *current_b;
let previous_min = segment
.normal
.dot(previous_a - segment.segment.point1())
.min(segment.normal.dot(previous_b - segment.segment.point1()));
let current_a_distance =
segment.normal.dot(current_a - segment.segment.point1());
let current_b_distance =
segment.normal.dot(current_b - segment.segment.point1());
let current_min = current_a_distance.min(current_b_distance);
if previous_min < crate::math::int::FGWide::ZERO
|| current_min > crate::math::int::FGWide::ZERO
{
return None;
}
let boundary = [
FGSegment2d::new(previous_a, previous_b),
FGSegment2d::new(previous_a, current_a),
FGSegment2d::new(previous_b, current_b),
FGSegment2d::new(current_a, current_b),
];
let quad = [previous_a, previous_b, current_b, current_a];
let position = boundary
.iter()
.filter_map(|edge| segment.segment.segment_intersection(edge))
.max_by_key(|position| position.distance_squared(current_a))
.or_else(|| {
[segment.segment.point1(), segment.segment.point2()]
.into_iter()
.find(|point| point_in_convex_quad(*point, quad))
})?;
let penetration = FGi32::from_num(-current_min);
Some((position, segment.normal * penetration))
})
.max_by_key(|(position, _)| {
position.distance_squared(segment.segment.point1())
})
.map(|(position, correction)| {
(
PointSweepResult {
line_id: StageLineID {
polygon: poly_idx,
segment: segment_idx,
},
hit_normal: segment.normal,
correction,
},
position.distance_squared(segment.segment.point2()),
)
})
})
}) })
.max_by(|(_, a), (_, b)| a.cmp(b)) .max_by(|(_, a), (_, b)| a.cmp(b))
.map(|(result, _)| result) .map(|(result, _)| result)
} }
fn point_in_convex_quad(point: FGVec2, quad: [FGVec2; 4]) -> bool {
let mut has_positive = false;
let mut has_negative = false;
for (a, b) in quad.into_iter().zip(quad.into_iter().cycle().skip(1)).take(4) {
let edge = b - a;
let offset = point - a;
let cross = crate::math::int::FGWide::from_num(edge.x)
* crate::math::int::FGWide::from_num(offset.y)
- crate::math::int::FGWide::from_num(edge.y)
* crate::math::int::FGWide::from_num(offset.x);
has_positive |= cross > crate::math::int::FGWide::ZERO;
has_negative |= cross < crate::math::int::FGWide::ZERO;
if has_positive && has_negative {
return false;
}
}
true
}
#[derive(Clone)] #[derive(Clone)]
pub struct AirCollisionWithLedgeResult { pub struct AirCollisionWithLedgeResult {
pub ledge: StageVertexID, pub ledge: StageVertexID,
@@ -93,9 +440,11 @@ pub fn air_collide_with_ledges(
ledge_box: &FGRect, ledge_box: &FGRect,
stage_collision: &StageCollision, stage_collision: &StageCollision,
) -> Option<AirCollisionWithLedgeResult> { ) -> Option<AirCollisionWithLedgeResult> {
stage_collision.intersect_ledges(ledge_box).map(|result| { stage_collision
AirCollisionWithLedgeResult { ledge: result.vertex_id } .intersect_ledges(ledge_box)
}) .map(|result| AirCollisionWithLedgeResult {
ledge: result.vertex_id,
})
} }
#[cfg(test)] #[cfg(test)]
@@ -126,6 +475,173 @@ mod tests {
) )
} }
fn single_segment(
start: FGVec2,
end: FGVec2,
segment_type: StagePolyLineSegmentType,
) -> StagePoly {
let segment = FGSegment2d::new(start, end);
StagePoly {
poly_type: StagePolyType::Closed,
segments: vec![crate::stage::line::StagePolyLineSegment {
segment,
normal: segment.left_normal(),
segment_type,
}],
}
}
#[test]
fn melee_step_count_adds_one_step_after_each_six_unit_block() {
assert_eq!(collision_step_count(FGi32::lit("6")), 1);
assert_eq!(collision_step_count(FGi32::lit("6.01")), 2);
assert_eq!(collision_step_count(FGi32::lit("12")), 3);
assert_eq!(collision_step_count(FGi32::lit("18")), 4);
}
#[test]
fn collision_result_keeps_ecb_local_to_resolved_origin() {
let stage_collision = StageCollision {
stage_polys: vec![horizontal_platform("0")],
..StageCollision::default()
};
let previous_translation = FighterPreviousTranslation(FGVec2::lit("0", "2"));
let mut translation = FighterTranslation(FGVec2::lit("0", "-1"));
let mut velocity = FighterVelocity(FGVec2::lit("0", "-3"));
let mut ecb = FighterECB {
top: FGVec2::lit("0", "2"),
bottom: FGVec2::lit("0", "-1"),
left: FGVec2::lit("-1", "0.5"),
right: FGVec2::lit("1", "0.5"),
};
let desired = FighterDesiredECB::from(ecb);
let collision = air_collide_with_stage_substepped(
&previous_translation,
&mut translation,
&mut velocity,
&mut ecb,
&desired,
&stage_collision,
&[],
Default::default(),
)
.expect("the floor should be hit");
assert_eq!(
collision.resolved_translation + ecb.bottom,
collision.hit_position
);
assert_eq!(velocity.0.y, FGi32::ZERO);
}
#[test]
fn airborne_side_point_resolves_wall_and_projects_velocity() {
let stage_collision = StageCollision {
stage_polys: vec![single_segment(
FGVec2::lit("2", "2"),
FGVec2::lit("2", "-2"),
StagePolyLineSegmentType::Wall,
)],
..StageCollision::default()
};
let previous = FighterPreviousTranslation(FGVec2::lit("4", "0"));
let mut translation = FighterTranslation(FGVec2::lit("0", "0"));
let mut velocity = FighterVelocity(FGVec2::lit("-4", "0"));
let mut ecb = FighterECB {
top: FGVec2::lit("0", "1"),
bottom: FGVec2::lit("0", "-1"),
left: FGVec2::lit("-1", "0"),
right: FGVec2::lit("1", "0"),
};
let desired = FighterDesiredECB::from(ecb);
assert!(air_collide_with_stage_substepped(
&previous,
&mut translation,
&mut velocity,
&mut ecb,
&desired,
&stage_collision,
&[],
Default::default(),
)
.is_none());
assert_eq!(translation.0, FGVec2::lit("3", "0"));
assert_eq!(velocity.0.x, FGi32::ZERO);
}
#[test]
fn stage_corner_cannot_pass_through_middle_of_diamond_edge() {
let stage_collision = StageCollision {
stage_polys: vec![single_segment(
FGVec2::lit("2", "0.6"),
FGVec2::lit("2", "0.4"),
StagePolyLineSegmentType::Wall,
)],
..StageCollision::default()
};
let previous = FighterPreviousTranslation(FGVec2::lit("4", "0"));
let mut translation = FighterTranslation(FGVec2::ZERO);
let mut velocity = FighterVelocity(FGVec2::lit("-4", "0"));
let mut ecb = FighterECB {
top: FGVec2::lit("0", "1"),
bottom: FGVec2::lit("0", "-1"),
left: FGVec2::lit("-1", "0"),
right: FGVec2::lit("1", "0"),
};
let desired = FighterDesiredECB::from(ecb);
assert!(air_collide_with_stage_substepped(
&previous,
&mut translation,
&mut velocity,
&mut ecb,
&desired,
&stage_collision,
&[],
Default::default(),
)
.is_none());
assert_eq!(translation.0.x, FGi32::lit("3"));
assert_eq!(velocity.0.x, FGi32::ZERO);
}
#[test]
fn airborne_top_point_resolves_ceiling_and_projects_velocity() {
let stage_collision = StageCollision {
stage_polys: vec![single_segment(
FGVec2::lit("2", "2"),
FGVec2::lit("-2", "2"),
StagePolyLineSegmentType::Ceiling,
)],
..StageCollision::default()
};
let previous = FighterPreviousTranslation(FGVec2::ZERO);
let mut translation = FighterTranslation(FGVec2::lit("0", "4"));
let mut velocity = FighterVelocity(FGVec2::lit("0", "4"));
let mut ecb = FighterECB {
top: FGVec2::lit("0", "1"),
bottom: FGVec2::lit("0", "-1"),
left: FGVec2::lit("-1", "0"),
right: FGVec2::lit("1", "0"),
};
let desired = FighterDesiredECB::from(ecb);
assert!(air_collide_with_stage_substepped(
&previous,
&mut translation,
&mut velocity,
&mut ecb,
&desired,
&stage_collision,
&[],
Default::default(),
)
.is_none());
assert_eq!(translation.0, FGVec2::lit("0", "1"));
assert_eq!(velocity.0.y, FGi32::ZERO);
}
#[test] #[test]
fn airborne_collision_skips_ignored_polygons() { fn airborne_collision_skips_ignored_polygons() {
let stage_collision = StageCollision { let stage_collision = StageCollision {
@@ -154,7 +670,7 @@ mod tests {
&ecb, &ecb,
&stage_collision, &stage_collision,
&[1], &[1],
false, Default::default(),
) )
.expect("the non-ignored platform should still be collidable"); .expect("the non-ignored platform should still be collidable");
@@ -183,16 +699,21 @@ mod tests {
right: FGVec2::ZERO, right: FGVec2::ZERO,
}; };
assert!(air_collide_with_stage( assert!(
&previous_translation, air_collide_with_stage(
&translation, &previous_translation,
&previous_ecb, &translation,
&ecb, &previous_ecb,
&stage_collision, &ecb,
&[], &stage_collision,
true, &[],
) AirCollisionOptions {
.is_none()); can_pass_through_soft_platforms: true,
..Default::default()
},
)
.is_none()
);
assert_eq!( assert_eq!(
air_collide_with_stage( air_collide_with_stage(
@@ -202,7 +723,7 @@ mod tests {
&ecb, &ecb,
&stage_collision, &stage_collision,
&[], &[],
false, Default::default(),
) )
.expect("air dodges still collide with soft platforms") .expect("air dodges still collide with soft platforms")
.hit_position, .hit_position,
@@ -238,11 +759,131 @@ mod tests {
&ecb, &ecb,
&stage_collision, &stage_collision,
&[], &[],
true, AirCollisionOptions {
can_pass_through_soft_platforms: true,
..Default::default()
},
) )
.expect("solid floors remain collidable while passing down"); .expect("solid floors remain collidable while passing down");
assert_eq!(collision.line_id.polygon, 0); assert_eq!(collision.line_id.polygon, 0);
assert_eq!(collision.hit_position, FGVec2::lit("0", "0")); assert_eq!(collision.hit_position, FGVec2::lit("0", "0"));
} }
#[test]
fn upward_bottom_crossing_can_land_on_soft_platform() {
let stage_collision = StageCollision {
stage_polys: vec![horizontal_platform("0")],
..Default::default()
};
let previous_translation = FighterPreviousTranslation(FGVec2::lit("0", "-1"));
let mut translation = FighterTranslation(FGVec2::lit("0", "1"));
let mut velocity = FighterVelocity(FGVec2::lit("0", "2"));
let mut ecb = FighterECB::default();
let desired = FighterDesiredECB::from(ecb);
let collision = air_collide_with_stage_substepped(
&previous_translation,
&mut translation,
&mut velocity,
&mut ecb,
&desired,
&stage_collision,
&[],
AirCollisionOptions {
land_on_soft_platforms_from_below: true,
..Default::default()
},
)
.expect("the upward bottom-point crossing should land on the platform");
assert_eq!(collision.hit_position, FGVec2::ZERO);
assert_eq!(collision.line_id, StageLineID { polygon: 0, segment: 0 });
assert_eq!(translation.0, FGVec2::ZERO);
assert_eq!(velocity.y, FGi32::ZERO);
}
#[test]
fn upward_platform_landing_requires_crossing_and_opt_in() {
let stage_collision = StageCollision {
stage_polys: vec![horizontal_platform("0")],
..Default::default()
};
let previous_ecb = FighterPreviousECB::default();
let ecb = FighterECB::default();
let options = AirCollisionOptions {
land_on_soft_platforms_from_below: true,
..Default::default()
};
assert!(
air_collide_with_stage(
&FighterPreviousTranslation(FGVec2::lit("0", "-2")),
&FighterTranslation(FGVec2::lit("0", "-1")),
&previous_ecb,
&ecb,
&stage_collision,
&[],
options,
)
.is_none()
);
assert!(
air_collide_with_stage(
&FighterPreviousTranslation(FGVec2::lit("0", "-1")),
&FighterTranslation(FGVec2::lit("0", "1")),
&previous_ecb,
&ecb,
&stage_collision,
&[],
Default::default(),
)
.is_none()
);
}
#[test]
fn upward_crossing_does_not_land_on_solid_or_ignored_platforms() {
let previous_translation = FighterPreviousTranslation(FGVec2::lit("0", "-1"));
let translation = FighterTranslation(FGVec2::lit("0", "1"));
let previous_ecb = FighterPreviousECB::default();
let ecb = FighterECB::default();
let options = AirCollisionOptions {
land_on_soft_platforms_from_below: true,
..Default::default()
};
let solid_stage = StageCollision {
stage_polys: vec![solid_floor()],
..Default::default()
};
let platform_stage = StageCollision {
stage_polys: vec![horizontal_platform("0")],
..Default::default()
};
assert!(
air_collide_with_stage(
&previous_translation,
&translation,
&previous_ecb,
&ecb,
&solid_stage,
&[],
options,
)
.is_none()
);
assert!(
air_collide_with_stage(
&previous_translation,
&translation,
&previous_ecb,
&ecb,
&platform_stage,
&[0],
options,
)
.is_none()
);
}
} }
+207 -24
View File
@@ -4,14 +4,12 @@ use crate::{
fighter::{ fighter::{
FighterFacingDirection, FighterSurfaceState, FighterTranslation, FighterFacingDirection, FighterSurfaceState, FighterTranslation,
baked_animation::FighterBoneMatrices, baked_animation::FighterBoneMatrices,
}, math::{int::FGi32, vec::FGVec2}, },
math::{int::FGi32, vec::FGVec2},
}; };
/// Environment collision box: the diamond used to resolve a fighter against
/// the stage. Purely geometry — the collision response lives in
/// [`super::collision`].
#[derive(Component, Debug, Clone, Copy, Hash, Default)] #[derive(Component, Debug, Clone, Copy, Hash, Default)]
#[require(FighterPreviousECB)] #[require(FighterPreviousECB, FighterDesiredECB)]
pub struct FighterECB { pub struct FighterECB {
pub top: FGVec2, pub top: FGVec2,
pub bottom: FGVec2, pub bottom: FGVec2,
@@ -19,6 +17,14 @@ pub struct FighterECB {
pub right: FGVec2, pub right: FGVec2,
} }
#[derive(Component, Debug, Clone, Copy, Hash, Default)]
pub struct FighterDesiredECB {
pub top: FGVec2,
pub bottom: FGVec2,
pub left: FGVec2,
pub right: FGVec2,
}
#[derive(Component, Debug, Clone)] #[derive(Component, Debug, Clone)]
pub struct FighterECBBoneIndices { pub struct FighterECBBoneIndices {
pub indices: Vec<usize>, pub indices: Vec<usize>,
@@ -43,12 +49,96 @@ impl From<FighterECB> for FighterPreviousECB {
} }
} }
impl From<FighterECB> for FighterDesiredECB {
fn from(ecb: FighterECB) -> Self {
Self {
top: ecb.top,
bottom: ecb.bottom,
left: ecb.left,
right: ecb.right,
}
}
}
impl FighterDesiredECB {
pub fn as_ecb(self) -> FighterECB {
FighterECB {
top: self.top,
bottom: self.bottom,
left: self.left,
right: self.right,
}
}
pub fn validate(&mut self) {
let minimum = FGi32::lit("1.0");
if (self.top.y - self.bottom.y).abs() < minimum {
self.top.y += minimum;
let midpoint = (self.top.y + self.bottom.y) / FGi32::lit("2.0");
self.left.y = midpoint;
self.right.y = midpoint;
}
if self.top.y < minimum {
self.top.y = minimum;
}
if self.left.x > -minimum {
self.left.x = -minimum;
}
if self.right.x < minimum {
self.right.x = minimum;
}
if self.top.y < self.bottom.y {
self.top.y = self.bottom.y + minimum;
}
let midpoint = (self.top.y + self.bottom.y) / FGi32::lit("2.0");
if self.left.y < self.bottom.y || self.left.y > self.top.y {
self.left.y = midpoint;
}
if self.right.y < self.bottom.y || self.right.y > self.top.y {
self.left.y = midpoint;
self.right.y = midpoint;
}
let epsilon = FGi32::from_bits(66);
if self.top.y - self.right.y < epsilon
|| self.right.y - self.bottom.y < epsilon
{
self.right.y = midpoint;
}
if self.top.y - self.left.y < epsilon
|| self.left.y - self.bottom.y < epsilon
{
self.left.y = midpoint;
}
}
}
pub fn snapshot_fighter_ecb(fighters: Query<(&FighterECB, &mut FighterPreviousECB)>) { pub fn snapshot_fighter_ecb(fighters: Query<(&FighterECB, &mut FighterPreviousECB)>) {
for (ecb, mut previous_ecb) in fighters { for (ecb, mut previous_ecb) in fighters {
*previous_ecb = (*ecb).into(); *previous_ecb = (*ecb).into();
} }
} }
pub fn interpolate_ecb(ecb: &mut FighterECB, desired: FighterDesiredECB, time: FGi32) {
let lerp = |a: FGVec2, b: FGVec2| a + (b - a) * time;
ecb.top = lerp(ecb.top, desired.top);
ecb.bottom = lerp(ecb.bottom, desired.bottom);
ecb.left = lerp(ecb.left, desired.left);
ecb.right = lerp(ecb.right, desired.right);
}
pub fn ecb_max_delta(ecb: &FighterECB, desired: &FighterDesiredECB) -> FGi32 {
[
(desired.left.x - ecb.left.x).abs(),
(desired.right.x - ecb.right.x).abs(),
(desired.top.y - ecb.top.y).abs(),
(desired.right.y - ecb.right.y).abs(),
]
.into_iter()
.max()
.unwrap_or(FGi32::ZERO)
}
impl FighterECB { impl FighterECB {
pub fn to_3d_lineloop(&self, trf: Transform) -> [Vec3; 4] { pub fn to_3d_lineloop(&self, trf: Transform) -> [Vec3; 4] {
[self.top, self.right, self.bottom, self.left] [self.top, self.right, self.bottom, self.left]
@@ -58,6 +148,17 @@ impl FighterECB {
pub fn get_bottom_point(&self) -> FGVec2 { pub fn get_bottom_point(&self) -> FGVec2 {
self.bottom self.bottom
} }
/// Change the local origin to the bottom point without moving the ECB in
/// world space. Grounded fighters use the floor contact as their origin.
pub fn rebase_onto_bottom(&mut self) -> FGVec2 {
let bottom = self.bottom;
self.top -= bottom;
self.left -= bottom;
self.right -= bottom;
self.bottom = FGVec2::ZERO;
bottom
}
} }
impl FighterPreviousECB { impl FighterPreviousECB {
@@ -73,7 +174,7 @@ impl FighterPreviousECB {
pub fn update_ecb( pub fn update_ecb(
query: Query<( query: Query<(
&mut FighterECB, &mut FighterDesiredECB,
&FighterSurfaceState, &FighterSurfaceState,
&FighterECBBoneIndices, &FighterECBBoneIndices,
&FighterBoneMatrices, &FighterBoneMatrices,
@@ -81,23 +182,44 @@ pub fn update_ecb(
&FighterFacingDirection, &FighterFacingDirection,
)>, )>,
) { ) {
for (mut ecb, surface_state, bone_indices, bone_matrices, translation, facing_dir) in query { for (mut desired, surface_state, bone_indices, bone_matrices, translation, facing_dir) in query
{
let trf = translation.get_3d_transform(facing_dir); let trf = translation.get_3d_transform(facing_dir);
let transformed_ecb_bones = bone_indices.indices.iter().filter_map(|idx| { let transformed_ecb_bones = bone_indices
let Some((_, bone_matrix)) = bone_matrices.get_by_idx(*idx) else { .indices
return None; .iter()
}; .filter_map(|idx| {
let Some((_, bone_matrix)) = bone_matrices.get_by_idx(*idx) else {
return None;
};
let pt = trf.transform_point(bone_matrix.get_translation()); let pt = trf.transform_point(bone_matrix.get_translation());
Some(FGVec2::new(pt.x, pt.y) - translation.0) Some(FGVec2::new(pt.x, pt.y) - translation.0)
}).collect::<Vec<_>>(); })
.collect::<Vec<_>>();
let max_x = transformed_ecb_bones.iter().max_by(|a, b| a.x.cmp(&b.x)).map(|final_val| final_val.x).unwrap_or(FGi32::lit("0.5")); let max_x = transformed_ecb_bones
let min_x = transformed_ecb_bones.iter().min_by(|a, b| a.x.cmp(&b.x)).map(|final_val| final_val.x).unwrap_or(FGi32::lit("-0.5")); .iter()
let max_y = transformed_ecb_bones.iter().max_by(|a, b| a.y.cmp(&b.y)).map(|final_val| final_val.y).unwrap_or(FGi32::lit("0.5")); .max_by(|a, b| a.x.cmp(&b.x))
let min_y = transformed_ecb_bones.iter().min_by(|a, b| a.y.cmp(&b.y)).map(|final_val| final_val.y).unwrap_or(FGi32::lit("-0.5")); .map(|final_val| final_val.x)
.unwrap_or(FGi32::lit("0.5"));
let min_x = transformed_ecb_bones
.iter()
.min_by(|a, b| a.x.cmp(&b.x))
.map(|final_val| final_val.x)
.unwrap_or(FGi32::lit("-0.5"));
let max_y = transformed_ecb_bones
.iter()
.max_by(|a, b| a.y.cmp(&b.y))
.map(|final_val| final_val.y)
.unwrap_or(FGi32::lit("0.5"));
let min_y = transformed_ecb_bones
.iter()
.min_by(|a, b| a.y.cmp(&b.y))
.map(|final_val| final_val.y)
.unwrap_or(FGi32::lit("-0.5"));
let midpoint_height = (max_y + min_y) / FGi32::lit("2.0"); let midpoint_height = (max_y + min_y) / FGi32::lit("2.0");
let top = FGVec2::new(FGi32::ZERO, max_y); let top = FGVec2::new(FGi32::ZERO, max_y);
@@ -105,24 +227,29 @@ pub fn update_ecb(
let left = FGVec2::new(min_x, midpoint_height); let left = FGVec2::new(min_x, midpoint_height);
let right = FGVec2::new(max_x, midpoint_height); let right = FGVec2::new(max_x, midpoint_height);
let ecb_lock_frames_remaining = if let FighterSurfaceState::Airborne { ecb_lock_frames_remaining, .. } = surface_state { let ecb_lock_frames_remaining = if let FighterSurfaceState::Airborne {
ecb_lock_frames_remaining,
..
} = surface_state
{
*ecb_lock_frames_remaining *ecb_lock_frames_remaining
} else { } else {
0 0
}; };
ecb.top = top; desired.top = top;
if ecb_lock_frames_remaining == 0 { if ecb_lock_frames_remaining == 0 {
ecb.bottom = bottom; desired.bottom = bottom;
} }
ecb.left = left; desired.left = left;
ecb.right = right; desired.right = right;
if surface_state.is_grounded() { if surface_state.is_grounded() {
ecb.bottom = FGVec2::ZERO; desired.bottom = FGVec2::ZERO;
} }
desired.validate();
} }
} }
@@ -152,4 +279,60 @@ mod tests {
assert_eq!(previous.left, current.left); assert_eq!(previous.left, current.left);
assert_eq!(previous.right, current.right); assert_eq!(previous.right, current.right);
} }
#[test]
fn interpolation_reaches_target_with_full_step() {
let mut current = FighterECB {
top: FGVec2::lit("0", "1"),
bottom: FGVec2::lit("0", "0"),
left: FGVec2::lit("-1", "0.5"),
right: FGVec2::lit("1", "0.5"),
};
let desired = FighterDesiredECB {
top: FGVec2::lit("0", "3"),
bottom: FGVec2::lit("0", "-1"),
left: FGVec2::lit("-2", "1"),
right: FGVec2::lit("2", "1"),
};
interpolate_ecb(&mut current, desired, FGi32::ONE);
assert_eq!(current.top, desired.top);
assert_eq!(current.bottom, desired.bottom);
assert_eq!(current.left, desired.left);
assert_eq!(current.right, desired.right);
}
#[test]
fn validation_repairs_tiny_and_out_of_range_diamond() {
let mut desired = FighterDesiredECB {
top: FGVec2::lit("0", "0.25"),
bottom: FGVec2::lit("0", "0"),
left: FGVec2::lit("0", "4"),
right: FGVec2::lit("0", "-4"),
};
desired.validate();
assert_eq!(desired.top.y, FGi32::lit("1.25"));
assert_eq!(desired.left.x, FGi32::lit("-1"));
assert_eq!(desired.right.x, FGi32::lit("1"));
assert_eq!(desired.left.y, FGi32::lit("0.625"));
assert_eq!(desired.right.y, FGi32::lit("0.625"));
}
#[test]
fn rebasing_onto_bottom_preserves_world_points() {
let origin = FGVec2::lit("4", "8");
let mut ecb = FighterECB {
top: FGVec2::lit("0", "3"),
bottom: FGVec2::lit("0", "-1"),
left: FGVec2::lit("-2", "1"),
right: FGVec2::lit("2", "1"),
};
let old_world_points = [ecb.top, ecb.bottom, ecb.left, ecb.right].map(|p| origin + p);
let new_origin = origin + ecb.bottom;
ecb.rebase_onto_bottom();
let new_world_points = [ecb.top, ecb.bottom, ecb.left, ecb.right].map(|p| new_origin + p);
assert_eq!(old_world_points, new_world_points);
assert_eq!(ecb.bottom, FGVec2::ZERO);
}
} }
+49 -19
View File
@@ -10,6 +10,7 @@ pub mod animation;
pub mod attack; pub mod attack;
pub mod attributes; pub mod attributes;
pub mod baked_animation; pub mod baked_animation;
pub mod blast_zones;
pub mod collision; pub mod collision;
pub mod debug; pub mod debug;
pub mod ecb; pub mod ecb;
@@ -21,7 +22,6 @@ pub mod push;
pub mod state; pub mod state;
pub mod surface; pub mod surface;
pub mod visual; pub mod visual;
pub mod blast_zones;
// The fighter components are re-exported so the rest of the crate can say // The fighter components are re-exported so the rest of the crate can say
// `fighter::FighterVelocity` without caring which file it lives in. Named // `fighter::FighterVelocity` without caring which file it lives in. Named
@@ -37,13 +37,25 @@ pub use motion::{
pub use surface::FighterSurfaceState; pub use surface::FighterSurfaceState;
use crate::{ use crate::{
AppState, fighter::{ AppState,
fighter::{
attack::{ attack::{
AttackKind, FighterAttackPlugin, FighterAttackScriptAssets, FighterDamage, AttackKind, FighterAttackPlugin, FighterAttackScriptAssets, FighterDamage,
FighterKnockbackVelocity, FighterPendingHitReaction, FighterSolvedHurtboxes, FighterKnockbackState, FighterKnockbackVelocity, FighterPendingHitReaction,
FighterStaleMoveQueue, FighterSolvedHurtboxes, FighterStaleMoveQueue,
}, baked_animation::FighterBoneIndexMap, ecb::FighterECBBoneIndices, manifest::FighterManifest, state::{FighterState, air::AirborneStateCommon, fall::FallState}, visual::{FighterAnimations, FighterInvulnerabilityVisualState}, },
}, game_settings::GameSettings, input::FighterInput, math::{int::FGi32, vec::FGVec2}, player::Player, schedule::GameplaySet, scripting::FighterAttackScript, baked_animation::FighterBoneIndexMap,
ecb::{FighterDesiredECB, FighterECBBoneIndices},
manifest::FighterManifest,
state::{FighterState, air::AirborneStateCommon, fall::FallState},
visual::{FighterAnimations, FighterInvulnerabilityVisualState},
},
game_settings::GameSettings,
input::FighterInput,
math::{int::FGi32, vec::FGVec2},
player::Player,
schedule::GameplaySet,
scripting::FighterAttackScript,
}; };
use state::state_interrupt_system; use state::state_interrupt_system;
@@ -102,7 +114,8 @@ impl FighterLedgeInformation {
} }
fn tick(&mut self) { fn tick(&mut self) {
self.regrab_lockout_remaining_frames = self.regrab_lockout_remaining_frames.saturating_sub(1); self.regrab_lockout_remaining_frames =
self.regrab_lockout_remaining_frames.saturating_sub(1);
} }
} }
@@ -135,8 +148,12 @@ mod ledge_grab_lockout_tests {
pub enum FighterInvulnerabilityState { pub enum FighterInvulnerabilityState {
#[default] #[default]
Vulnerable, Vulnerable,
Invulnerable { frames_remaining: Option<u32> }, Invulnerable {
Intangible { frames_remaining: Option<u32> } frames_remaining: Option<u32>,
},
Intangible {
frames_remaining: Option<u32>,
},
} }
impl FighterFacingDirection { impl FighterFacingDirection {
@@ -195,9 +212,10 @@ pub struct FighterPendingRespawn(bool);
FighterHitstop, FighterHitstop,
FighterLedgeInformation, FighterLedgeInformation,
FighterKnockbackVelocity, FighterKnockbackVelocity,
FighterKnockbackState,
FighterTranslation, FighterTranslation,
FighterInvulnerabilityState, FighterInvulnerabilityState,
FighterInvulnerabilityVisualState, FighterInvulnerabilityVisualState
)] )]
pub struct Fighter { pub struct Fighter {
pub manifest: Handle<FighterManifest>, pub manifest: Handle<FighterManifest>,
@@ -226,7 +244,10 @@ impl Plugin for FighterPlugin {
) )
.add_systems( .add_systems(
GgrsSchedule, GgrsSchedule,
(state::state_update_system, decay_hitstop, decay_invulnerability) (
state::state_update_system,
decay_invulnerability,
)
.chain() .chain()
.in_set(GameplaySet::StateUpdate), .in_set(GameplaySet::StateUpdate),
) )
@@ -241,11 +262,14 @@ impl Plugin for FighterPlugin {
( (
( (
blast_zones::apply_blast_zones, blast_zones::apply_blast_zones,
ecb::update_ecb,
ecb::decrement_ecb_lockout, ecb::decrement_ecb_lockout,
ecb::update_ecb,
state::state_collision_interrupt_system, state::state_collision_interrupt_system,
// Every gameplay phase must observe the same hitstop value.
decay_hitstop,
decay_ledge_grab_lockout, decay_ledge_grab_lockout,
).chain(), )
.chain(),
baked_animation::resample_fighter_bone_matrices, baked_animation::resample_fighter_bone_matrices,
) )
.chain() .chain()
@@ -272,6 +296,8 @@ impl Plugin for FighterPlugin {
// is a desync waiting to happen. // is a desync waiting to happen.
.rollback_component_with_copy::<FighterECB>() .rollback_component_with_copy::<FighterECB>()
.checksum_component_with_hash::<FighterECB>() .checksum_component_with_hash::<FighterECB>()
.rollback_component_with_copy::<FighterDesiredECB>()
.checksum_component_with_hash::<FighterDesiredECB>()
.rollback_component_with_clone::<FighterStaleMoveQueue>() .rollback_component_with_clone::<FighterStaleMoveQueue>()
.checksum_component_with_hash::<FighterStaleMoveQueue>() .checksum_component_with_hash::<FighterStaleMoveQueue>()
.rollback_component_with_copy::<ecb::FighterPreviousECB>() .rollback_component_with_copy::<ecb::FighterPreviousECB>()
@@ -305,6 +331,8 @@ impl Plugin for FighterPlugin {
.checksum_component_with_hash::<FighterInvulnerabilityState>() .checksum_component_with_hash::<FighterInvulnerabilityState>()
.rollback_component_with_copy::<FighterKnockbackVelocity>() .rollback_component_with_copy::<FighterKnockbackVelocity>()
.checksum_component_with_hash::<FighterKnockbackVelocity>() .checksum_component_with_hash::<FighterKnockbackVelocity>()
.rollback_component_with_copy::<FighterKnockbackState>()
.checksum_component_with_hash::<FighterKnockbackState>()
.rollback_component_with_clone::<baked_animation::FighterBoneMatrices>() .rollback_component_with_clone::<baked_animation::FighterBoneMatrices>()
.checksum_component_with_hash::<baked_animation::FighterBoneMatrices>() .checksum_component_with_hash::<baked_animation::FighterBoneMatrices>()
// Debug views. // Debug views.
@@ -335,8 +363,9 @@ impl Plugin for FighterPlugin {
.run_if(crate::debug_tools::attack_hitboxes_enabled) .run_if(crate::debug_tools::attack_hitboxes_enabled)
.run_if(in_state(AppState::InMatch)), .run_if(in_state(AppState::InMatch)),
) )
.add_systems(FixedPostUpdate, .add_systems(
visual::update_status_colors.run_if(resource_exists::<GameSettings>) FixedPostUpdate,
visual::update_status_colors.run_if(resource_exists::<GameSettings>),
) )
.add_systems( .add_systems(
FixedPostUpdate, FixedPostUpdate,
@@ -396,10 +425,11 @@ pub fn spawn_fighter(
Transform::from_scale(Vec3::splat(model_scale.to_num())), Transform::from_scale(Vec3::splat(model_scale.to_num())),
( (
FighterECB::default(), FighterECB::default(),
FighterDesiredECB::default(),
FighterHitboxes::default(), FighterHitboxes::default(),
FighterECBBoneIndices { FighterECBBoneIndices {
indices: ecb_bone_indices indices: ecb_bone_indices,
} },
), ),
( (
FighterVelocity::default(), FighterVelocity::default(),
@@ -449,7 +479,7 @@ pub fn decay_invulnerability(query: Query<&mut FighterInvulnerabilityState>) {
} else { } else {
None None
} }
}, }
FighterInvulnerabilityState::Intangible { frames_remaining } => { FighterInvulnerabilityState::Intangible { frames_remaining } => {
if let Some(frames_remaining) = frames_remaining { if let Some(frames_remaining) = frames_remaining {
*frames_remaining = frames_remaining.saturating_sub(1); *frames_remaining = frames_remaining.saturating_sub(1);
@@ -457,7 +487,7 @@ pub fn decay_invulnerability(query: Query<&mut FighterInvulnerabilityState>) {
} else { } else {
None None
} }
}, }
}; };
if let Some(frames_remaining) = frames_remaining { if let Some(frames_remaining) = frames_remaining {
+23 -9
View File
@@ -93,6 +93,19 @@ pub fn apply_air_motion(
translation.0 += velocity.0; translation.0 += velocity.0;
} }
/// Applies ordinary and launch velocity together, then advances launch decay.
/// Hitstop skips state updates entirely, so neither decay nor launch age moves
/// while the fighter is frozen.
pub fn apply_air_motion_with_knockback(ctx: &mut crate::fighter::state::UpdateContext) {
let combined_velocity = FighterVelocity(ctx.velocity.0 + ctx.knockback_velocity.0);
apply_air_motion(&combined_velocity, ctx.translation, ctx.prev_translation);
attack::decay_knockback(
ctx.knockback_velocity,
ctx.knockback_state,
ctx.game_settings.fighter_common.knockback_decay_per_frame,
);
}
pub fn update_standard_motion( pub fn update_standard_motion(
ctx: &mut crate::fighter::state::UpdateContext, ctx: &mut crate::fighter::state::UpdateContext,
airborne_common: &mut AirborneStateCommon, airborne_common: &mut AirborneStateCommon,
@@ -109,7 +122,7 @@ pub fn update_standard_motion(
airborne_common.is_fast_falling, airborne_common.is_fast_falling,
); );
apply_air_drift(ctx.velocity, ctx.fighter_attributes, ctx.input); apply_air_drift(ctx.velocity, ctx.fighter_attributes, ctx.input);
apply_air_motion(ctx.velocity, ctx.translation, ctx.prev_translation); apply_air_motion_with_knockback(ctx);
} }
pub fn air_interrupts_common( pub fn air_interrupts_common(
@@ -125,23 +138,24 @@ pub fn air_interrupts_common(
pub fn collision_interrupt( pub fn collision_interrupt(
ctx: &mut CollisionContext, ctx: &mut CollisionContext,
landing_type: LandingType, landing_type: LandingType,
can_ignore_soft_platforms: bool, options: crate::fighter::collision::AirCollisionOptions,
) -> Option<FighterState> { ) -> Option<FighterState> {
if ctx.velocity.y <= FGi32::ZERO { if ctx.velocity.y <= FGi32::ZERO {
if let Some(ledge_result) = ctx.air_collide_with_ledges() { if let Some(ledge_result) = ctx.air_collide_with_ledges() {
ctx.apply_desired_ecb();
return Some(FighterState::LedgeGrab(LedgeGrabState::new(ledge_result.ledge))); return Some(FighterState::LedgeGrab(LedgeGrabState::new(ledge_result.ledge)));
} }
} }
let res = ctx.air_collide_with_stage(can_ignore_soft_platforms)?; let res = ctx.air_collide_with_stage(options)?;
let diff = res.hit_position - ctx.translation.0; ctx.translation.0 = res.resolved_translation;
ctx.ecb.bottom -= diff; let bottom_offset = ctx.ecb.rebase_onto_bottom();
ctx.ecb.top -= diff; ctx.translation.0 += bottom_offset;
ctx.ecb.left -= diff; *ctx.desired_ecb = crate::fighter::ecb::FighterDesiredECB::from(*ctx.ecb);
ctx.ecb.right -= diff;
ctx.translation.0 = res.hit_position;
ctx.presentation_snap.0 = true; ctx.presentation_snap.0 = true;
ctx.surface.land(res.line_id, ctx.ledge_info); ctx.surface.land(res.line_id, ctx.ledge_info);
ctx.knockback_velocity.0 = FGVec2::ZERO;
ctx.knockback_state.clear();
Some(FighterState::Land(LandingState::create(landing_type))) Some(FighterState::Land(LandingState::create(landing_type)))
} }
+1 -1
View File
@@ -93,7 +93,7 @@ impl FighterStateImpl for AirAttackState {
let coll_interrupt = air::collision_interrupt( let coll_interrupt = air::collision_interrupt(
state_context, state_context,
crate::fighter::state::land::LandingType::Normal, crate::fighter::state::land::LandingType::Normal,
false, Default::default(),
); );
coll_interrupt.map(|state| { coll_interrupt.map(|state| {
+35 -17
View File
@@ -1,17 +1,9 @@
use crate::{ use crate::{
fighter::{ fighter::{
FighterInvulnerabilityState, FighterInvulnerabilityState, animation::AnimKind, state::{
animation::AnimKind, CollisionContext, EnterContext, FighterState, FighterStateImpl, InterruptContext, UpdateContext, air::{self, AirborneStateCommon}, fall::FallState, land::{LandingState, LandingType},
state::{
CollisionContext, EnterContext, FighterState, FighterStateImpl, InterruptContext,
UpdateContext,
air::{self, AirborneStateCommon},
fall::FallState,
land::LandingType,
}, },
}, }, input, math::vec::FGVec2, stage::line::{StageLineID, StagePolyLineSegmentType},
input,
math::vec::FGVec2,
}; };
#[derive(Debug, Clone, Hash)] #[derive(Debug, Clone, Hash)]
@@ -41,18 +33,44 @@ impl FighterStateImpl for AirDodgeState {
} }
state_context.velocity.0 *= state_context.fighter_attributes.air_dodge_decay; state_context.velocity.0 *= state_context.fighter_attributes.air_dodge_decay;
air::apply_air_motion( air::apply_air_motion_with_knockback(state_context);
state_context.velocity,
state_context.translation,
state_context.prev_translation,
);
} }
fn check_collision_interrupt( fn check_collision_interrupt(
&mut self, &mut self,
state_context: &mut CollisionContext, state_context: &mut CollisionContext,
) -> Option<FighterState> { ) -> Option<FighterState> {
air::collision_interrupt(state_context, LandingType::Special, false) let can_wavesnap = self.direction.y.is_zero() || self.direction.y.is_negative();
if can_wavesnap {
for (poly_idx, poly) in state_context.stage_collision.stage_polys.iter().enumerate() {
for (segment_idx, segment) in poly.segments.iter().enumerate() {
if !matches!(segment.segment_type, StagePolyLineSegmentType::Floor) {
continue;
}
let bottom_point = state_context.translation.0 + state_context.ecb.get_bottom_point();
let point_in_segment = segment.segment.closest_point(bottom_point);
let dist_to_segment = point_in_segment.distance(bottom_point);
if dist_to_segment <= state_context.waveland_snap_distance {
state_context.ecb.bottom = point_in_segment - state_context.translation.0;
state_context.ecb.rebase_onto_bottom();
state_context.surface.land(StageLineID { polygon: poly_idx, segment: segment_idx }, state_context.ledge_info);
state_context.knockback_velocity.0 = FGVec2::ZERO;
state_context.knockback_state.clear();
return Some(FighterState::Land(LandingState::create(LandingType::Special)));
}
}
}
}
air::collision_interrupt(
state_context,
LandingType::Special,
crate::fighter::collision::AirCollisionOptions {
land_on_soft_platforms_from_below: true,
..Default::default()
},
)
} }
fn on_enter(&mut self, state_context: &mut EnterContext) { fn on_enter(&mut self, state_context: &mut EnterContext) {
+3 -2
View File
@@ -43,12 +43,13 @@ impl FighterStateImpl for AngelState {
fn check_collision_interrupt( fn check_collision_interrupt(
&mut self, &mut self,
_state_context: &mut super::CollisionContext, state_context: &mut super::CollisionContext,
) -> Option<super::FighterState> { ) -> Option<super::FighterState> {
state_context.apply_desired_ecb();
None None
} }
fn surface_policy(&self) -> super::SurfacePolicy { fn surface_policy(&self) -> super::SurfacePolicy {
super::SurfacePolicy::Airborne(crate::fighter::surface::EcbLockPolicy::Clear) super::SurfacePolicy::Airborne(crate::fighter::surface::EcbLockPolicy::Clear)
} }
} }
+4 -1
View File
@@ -39,7 +39,10 @@ impl FighterStateImpl for FallState {
air::collision_interrupt( air::collision_interrupt(
state_context, state_context,
crate::fighter::state::land::LandingType::Normal, crate::fighter::state::land::LandingType::Normal,
true, crate::fighter::collision::AirCollisionOptions {
can_pass_through_soft_platforms: true,
..Default::default()
},
) )
} }
+81 -54
View File
@@ -4,16 +4,18 @@
use crate::fighter::state::air_dodge::AirDodgeState; use crate::fighter::state::air_dodge::AirDodgeState;
use crate::fighter::state::{ use crate::fighter::state::{
CollisionContext, FighterState, InterruptContext, air, crouch, dash, fall, ground_attack, turn, wait, walk, CollisionContext, FighterState, InterruptContext, air, crouch, dash, fall, ground_attack, turn,
}; wait, walk,
use crate::fighter::{
FighterAttributes, FighterTranslation, FighterVelocity,
}; };
use crate::fighter::{collision, ecb};
use crate::fighter::{FighterAttributes, FighterTranslation, FighterVelocity};
use crate::game_settings::GameSettings; use crate::game_settings::GameSettings;
use crate::input::FighterInput; use crate::input::FighterInput;
use crate::math::int::{FGWide, FGi32}; use crate::math::int::{FGWide, FGi32};
use crate::math::vec::FGVec2; use crate::math::vec::FGVec2;
use crate::stage::line::{StageLineID, StagePoly, StagePolyLineSegment, StagePolyLineSegmentType}; use crate::stage::line::{StagePoly, StagePolyLineSegment, StagePolyLineSegmentType};
#[cfg(test)]
use crate::stage::line::StageLineID;
pub fn apply_grounded_friction(friction: FGi32, ground_vel: FGi32) -> FGi32 { pub fn apply_grounded_friction(friction: FGi32, ground_vel: FGi32) -> FGi32 {
if friction.abs() > ground_vel.abs() { if friction.abs() > ground_vel.abs() {
@@ -148,10 +150,7 @@ fn resolve_grounded_position(
GroundedPositionResult::InAir GroundedPositionResult::InAir
} }
pub fn apply_grounded_motion( pub fn apply_grounded_motion(velocity: &FighterVelocity, translation: &mut FighterTranslation) {
velocity: &FighterVelocity,
translation: &mut FighterTranslation,
) {
// Vertical velocity should be 0 on the ground // Vertical velocity should be 0 on the ground
translation.0 += FGVec2::new(velocity.0.x, FGi32::ZERO); translation.0 += FGVec2::new(velocity.0.x, FGi32::ZERO);
} }
@@ -176,61 +175,77 @@ pub fn collide_with_stage_grounded(
state_context: &mut CollisionContext, state_context: &mut CollisionContext,
can_walk_off: bool, can_walk_off: bool,
) -> GroundedMotionResult { ) -> GroundedMotionResult {
let translation = &mut state_context.translation; let Some(mut line_id) = state_context.surface.line_id() else {
let ecb = &state_context.ecb; state_context.apply_desired_ecb();
let stage_collision = state_context.stage_collision;
let Some(current_line_id) = state_context.surface.line_id() else {
return GroundedMotionResult::InAir; return GroundedMotionResult::InAir;
}; };
let requested_translation = state_context.translation.0;
let movement = requested_translation - state_context.prev_translation.0;
let largest_change = movement
.x
.abs()
.max(movement.y.abs())
.max(ecb::ecb_max_delta(state_context.ecb, state_context.desired_ecb));
let steps = collision::collision_step_count(largest_change);
let movement_per_step = movement / FGi32::from_num(steps);
let mut current_position = state_context.prev_translation.0;
let mut current_ecb = *state_context.ecb;
let stage_poly = stage_collision.stage_polys.get(current_line_id.polygon); for step in 0..steps {
ecb::interpolate_ecb(
&mut current_ecb,
*state_context.desired_ecb,
FGi32::ONE / FGi32::from_num(steps - step),
);
current_position = if step + 1 == steps {
requested_translation
} else {
state_context.prev_translation.0
+ movement_per_step * FGi32::from_num(step + 1)
};
if let Some(stage_poly) = stage_poly { let Some(stage_poly) = state_context.stage_collision.stage_polys.get(line_id.polygon) else {
let ecb_bottom_pos = translation.0 + ecb.get_bottom_point(); *state_context.ecb = current_ecb;
state_context.translation.0 = current_position;
state_context.surface.apply_airborne_policy(
crate::fighter::surface::EcbLockPolicy::StartOnDetach,
state_context.leave_ground_ecb_lock_duration,
);
return GroundedMotionResult::InAir;
};
match resolve_grounded_position( match resolve_grounded_position(
stage_poly, stage_poly,
current_line_id.segment, line_id.segment,
ecb_bottom_pos, current_position + current_ecb.bottom,
can_walk_off, can_walk_off,
) { ) {
GroundedPositionResult::InGround { GroundedPositionResult::InGround { point, segment_idx, blocked } => {
point, line_id.segment = segment_idx;
segment_idx, current_position = point - current_ecb.bottom;
blocked, let segment = stage_poly.get_segment(segment_idx).unwrap();
} => {
let current_segment = stage_poly.get_segment(segment_idx).unwrap();
translation.0 = point - ecb.get_bottom_point();
state_context.velocity.0 = if blocked { state_context.velocity.0 = if blocked {
FGVec2::ZERO FGVec2::ZERO
} else { } else {
state_context.velocity.0 state_context.velocity.0
- state_context - state_context.velocity.0.project_onto_normalized(segment.normal)
.velocity
.0
.project_onto_normalized(current_segment.normal)
}; };
state_context.surface.land(StageLineID {
polygon: current_line_id.polygon,
segment: segment_idx,
}, state_context.ledge_info);
GroundedMotionResult::InGround
} }
GroundedPositionResult::InAir => { GroundedPositionResult::InAir => {
*state_context.ecb = current_ecb;
state_context.translation.0 = current_position;
state_context.surface.apply_airborne_policy( state_context.surface.apply_airborne_policy(
crate::fighter::surface::EcbLockPolicy::StartOnDetach, crate::fighter::surface::EcbLockPolicy::StartOnDetach,
state_context.leave_ground_ecb_lock_duration, state_context.leave_ground_ecb_lock_duration,
); );
GroundedMotionResult::InAir return GroundedMotionResult::InAir;
} }
} }
} else {
state_context.surface.apply_airborne_policy(
crate::fighter::surface::EcbLockPolicy::StartOnDetach,
state_context.leave_ground_ecb_lock_duration,
);
GroundedMotionResult::InAir
} }
*state_context.ecb = current_ecb;
state_context.translation.0 = current_position;
state_context.surface.land(line_id, state_context.ledge_info);
GroundedMotionResult::InGround
} }
pub fn collision_interrupt(ctx: &mut CollisionContext, can_walk_off: bool) -> Option<FighterState> { pub fn collision_interrupt(ctx: &mut CollisionContext, can_walk_off: bool) -> Option<FighterState> {
@@ -245,11 +260,14 @@ pub fn collision_interrupt(ctx: &mut CollisionContext, can_walk_off: bool) -> Op
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::fighter::ecb::FighterPreviousECB; use crate::fighter::attack::{FighterKnockbackState, FighterKnockbackVelocity};
use crate::fighter::{FighterECB, FighterLedgeInformation, FighterPreviousTranslation, FighterSurfaceState}; use crate::fighter::ecb::{FighterDesiredECB, FighterPreviousECB};
use crate::math::rect::FGRect; use crate::fighter::{
use crate::stage::line::StagePolyType; FighterECB, FighterLedgeInformation, FighterPreviousTranslation, FighterSurfaceState,
};
use crate::input::FighterInput; use crate::input::FighterInput;
use crate::math::rect::FGRect;
use crate::stage::line::StagePolyType;
fn two_segment_floor() -> StagePoly { fn two_segment_floor() -> StagePoly {
StagePoly::build( StagePoly::build(
@@ -371,6 +389,8 @@ use crate::stage::line::StagePolyType;
let mut translation = FighterTranslation(FGVec2::lit("11", "0")); let mut translation = FighterTranslation(FGVec2::lit("11", "0"));
let previous_translation = FighterPreviousTranslation(translation.0); let previous_translation = FighterPreviousTranslation(translation.0);
let mut velocity = FighterVelocity::default(); let mut velocity = FighterVelocity::default();
let mut knockback_velocity = FighterKnockbackVelocity::default();
let mut knockback_state = FighterKnockbackState::default();
let mut ledge_info = FighterLedgeInformation::default(); let mut ledge_info = FighterLedgeInformation::default();
let mut ecb = FighterECB { let mut ecb = FighterECB {
bottom: FGVec2::lit("0.0", "-0.5"), bottom: FGVec2::lit("0.0", "-0.5"),
@@ -379,14 +399,18 @@ use crate::stage::line::StagePolyType;
right: FGVec2::lit("0.5", "0.0"), right: FGVec2::lit("0.5", "0.0"),
}; };
let previous_ecb = FighterPreviousECB::from(ecb); let previous_ecb = FighterPreviousECB::from(ecb);
let mut desired_ecb = FighterDesiredECB::from(ecb);
let mut presentation_snap = crate::fighter::FighterPresentationSnap::default(); let mut presentation_snap = crate::fighter::FighterPresentationSnap::default();
let mut context = CollisionContext { let mut context = CollisionContext {
translation: &mut translation, translation: &mut translation,
prev_translation: &previous_translation, prev_translation: &previous_translation,
input: &FighterInput::default(), input: &FighterInput::default(),
velocity: &mut velocity, velocity: &mut velocity,
knockback_velocity: &mut knockback_velocity,
knockback_state: &mut knockback_state,
surface: &mut surface, surface: &mut surface,
ecb: &mut ecb, ecb: &mut ecb,
desired_ecb: &mut desired_ecb,
ledge_info: &mut ledge_info, ledge_info: &mut ledge_info,
prev_ecb: &previous_ecb, prev_ecb: &previous_ecb,
stage_collision: &stage_collision, stage_collision: &stage_collision,
@@ -397,6 +421,7 @@ use crate::stage::line::StagePolyType;
origin: FGVec2::ZERO, origin: FGVec2::ZERO,
end: FGVec2::ZERO, end: FGVec2::ZERO,
}, },
waveland_snap_distance: FGi32::ZERO,
}; };
assert!(matches!( assert!(matches!(
@@ -433,6 +458,8 @@ use crate::stage::line::StagePolyType;
let mut translation = FighterTranslation(FGVec2::lit("11", "0")); let mut translation = FighterTranslation(FGVec2::lit("11", "0"));
let previous_translation = FighterPreviousTranslation(translation.0); let previous_translation = FighterPreviousTranslation(translation.0);
let mut velocity = FighterVelocity::default(); let mut velocity = FighterVelocity::default();
let mut knockback_velocity = FighterKnockbackVelocity::default();
let mut knockback_state = FighterKnockbackState::default();
let mut ecb = FighterECB { let mut ecb = FighterECB {
bottom: FGVec2::lit("0.0", "-0.5"), bottom: FGVec2::lit("0.0", "-0.5"),
top: FGVec2::lit("0.0", "0.5"), top: FGVec2::lit("0.0", "0.5"),
@@ -440,6 +467,7 @@ use crate::stage::line::StagePolyType;
right: FGVec2::lit("0.5", "0.0"), right: FGVec2::lit("0.5", "0.0"),
}; };
let previous_ecb = FighterPreviousECB::from(ecb); let previous_ecb = FighterPreviousECB::from(ecb);
let mut desired_ecb = FighterDesiredECB::from(ecb);
let mut presentation_snap = crate::fighter::FighterPresentationSnap::default(); let mut presentation_snap = crate::fighter::FighterPresentationSnap::default();
let mut ledge_info = FighterLedgeInformation::default(); let mut ledge_info = FighterLedgeInformation::default();
let mut context = CollisionContext { let mut context = CollisionContext {
@@ -447,8 +475,11 @@ use crate::stage::line::StagePolyType;
prev_translation: &previous_translation, prev_translation: &previous_translation,
input: &FighterInput::default(), input: &FighterInput::default(),
velocity: &mut velocity, velocity: &mut velocity,
knockback_velocity: &mut knockback_velocity,
knockback_state: &mut knockback_state,
surface: &mut surface, surface: &mut surface,
ecb: &mut ecb, ecb: &mut ecb,
desired_ecb: &mut desired_ecb,
ledge_info: &mut ledge_info, ledge_info: &mut ledge_info,
prev_ecb: &previous_ecb, prev_ecb: &previous_ecb,
stage_collision: &stage_collision, stage_collision: &stage_collision,
@@ -459,6 +490,7 @@ use crate::stage::line::StagePolyType;
origin: FGVec2::ZERO, origin: FGVec2::ZERO,
end: FGVec2::ZERO, end: FGVec2::ZERO,
}, },
waveland_snap_distance: FGi32::ZERO,
}; };
assert!(matches!( assert!(matches!(
@@ -498,15 +530,10 @@ pub fn grounded_movement_standstill_common_interrupts(
pub fn perform_wavedash(input: &FighterInput, game_settings: &GameSettings) -> FighterState { pub fn perform_wavedash(input: &FighterInput, game_settings: &GameSettings) -> FighterState {
// If aiming sideways and in the deadzone, do a perfect wavedash // If aiming sideways and in the deadzone, do a perfect wavedash
// TODO: Improve this so we don't have to go through the airborne state first // TODO: Improve this so we don't have to go through the airborne state first
let mut wavedash_dir = let mut wavedash_dir = input.get_last_frame().movement.normalize_or_zero();
input
.get_last_frame()
.movement
.normalize_or_zero();
let movement = input.get_last_frame().movement; let movement = input.get_last_frame().movement;
if movement.y.is_zero() && !movement.x.is_zero() { if movement.y.is_zero() && !movement.x.is_zero() {
wavedash_dir.y = wavedash_dir.y = -game_settings.input_common.stick_deadzone - FGi32::lit("-0.01");
-game_settings.input_common.stick_deadzone - FGi32::lit("-0.01");
wavedash_dir.x = movement.x.signum(); wavedash_dir.x = movement.x.signum();
} }
@@ -517,4 +544,4 @@ pub fn perform_wavedash(input: &FighterInput, game_settings: &GameSettings) -> F
FighterState::AirDodge(AirDodgeState { FighterState::AirDodge(AirDodgeState {
direction: wavedash_dir.normalize_or_zero(), direction: wavedash_dir.normalize_or_zero(),
}) })
} }
+64 -41
View File
@@ -1,8 +1,6 @@
use crate::{ use crate::{
fighter::{ fighter::{
animation::AnimKind, animation::AnimKind, attack::{self, FighterHitReaction}, state::{
attack::{self, FighterHitReaction},
state::{
CollisionContext, EnterContext, ExitContext, FighterState, FighterStateImpl, CollisionContext, EnterContext, ExitContext, FighterState, FighterStateImpl,
InterruptContext, UpdateContext, InterruptContext, UpdateContext,
air::{self, AirborneStateCommon}, air::{self, AirborneStateCommon},
@@ -11,7 +9,7 @@ use crate::{
land::LandingType, land::LandingType,
wait::WaitState, wait::WaitState,
}, },
}, math::{int::FGi32, vec::FGVec2}, }, math::vec::FGVec2,
}; };
#[derive(Clone, Debug, Hash)] #[derive(Clone, Debug, Hash)]
@@ -25,14 +23,20 @@ pub struct HitstunState {
pub hit_reaction: FighterHitReaction, pub hit_reaction: FighterHitReaction,
pub hitstop_kind: HitstopStateKind, pub hitstop_kind: HitstopStateKind,
knockback_applied: bool, knockback_applied: bool,
stack_previous_knockback: bool,
} }
impl HitstunState { impl HitstunState {
pub fn new(hit_reaction: FighterHitReaction, hitstop_kind: HitstopStateKind) -> Self { pub fn new(
hit_reaction: FighterHitReaction,
hitstop_kind: HitstopStateKind,
stack_previous_knockback: bool,
) -> Self {
Self { Self {
hit_reaction, hit_reaction,
hitstop_kind, hitstop_kind,
knockback_applied: false, knockback_applied: false,
stack_previous_knockback,
} }
} }
} }
@@ -40,6 +44,35 @@ impl HitstunState {
impl FighterStateImpl for HitstunState { impl FighterStateImpl for HitstunState {
const NAME: &'static str = "Hitstun"; const NAME: &'static str = "Hitstun";
fn check_interrupt(&self, state_context: &mut InterruptContext) -> Option<FighterState> {
if state_context.get_current_animation_frame() > self.hit_reaction.hitstun_frames {
match &self.hitstop_kind {
HitstopStateKind::Grounded => Some(FighterState::Wait(WaitState)),
HitstopStateKind::Airborne => Some(FighterState::Fall(FallState::new(
AirborneStateCommon::default(),
))),
}
} else {
None
}
}
fn on_enter(&mut self, state_context: &mut EnterContext) {
let animation = match self.hitstop_kind {
HitstopStateKind::Grounded => AnimKind::FlinchGround,
HitstopStateKind::Airborne => AnimKind::FlinchAir,
};
state_context.play_animation(animation, false);
state_context.velocity.0 = FGVec2::ZERO;
}
fn on_exit(&mut self, state_context: &mut ExitContext) {
if matches!(self.hitstop_kind, HitstopStateKind::Grounded) {
state_context.knockback_velocity.0 = FGVec2::ZERO;
state_context.knockback_state.clear();
}
}
fn name(&self) -> String { fn name(&self) -> String {
let hitstop_kind = match self.hitstop_kind { let hitstop_kind = match self.hitstop_kind {
HitstopStateKind::Grounded => "Grounded", HitstopStateKind::Grounded => "Grounded",
@@ -54,28 +87,29 @@ impl FighterStateImpl for HitstunState {
format!("Hitstun ({hitstop_kind}, {hit_reaction_type})") format!("Hitstun ({hitstop_kind}, {hit_reaction_type})")
} }
fn check_interrupt(&self, state_context: &mut InterruptContext) -> Option<FighterState> {
if state_context.get_current_animation_frame() > self.hit_reaction.hitstun_frames {
match &self.hitstop_kind {
HitstopStateKind::Grounded => Some(FighterState::Wait(WaitState)),
HitstopStateKind::Airborne => Some(FighterState::Fall(FallState::new(
AirborneStateCommon::default(),
))),
}
} else {
None
}
}
fn update(&mut self, ctx: &mut UpdateContext) { fn update(&mut self, ctx: &mut UpdateContext) {
if !self.knockback_applied { if !self.knockback_applied {
let launch_direction = attack::directional_influence::apply_directional_influence( let new_launch_direction = attack::directional_influence::apply_directional_influence(
ctx.input.get_last_frame().movement, FGVec2::ZERO,
self.hit_reaction.launch_angle, self.hit_reaction.launch_angle,
ctx.game_settings.fighter_common.di_max_angle, ctx.game_settings.fighter_common.di_max_angle,
); );
let new_knockback = new_launch_direction * self.hit_reaction.launch_velocity;
let combined_knockback = if self.stack_previous_knockback {
attack::stack_knockback(ctx.knockback_velocity.0, new_knockback)
} else {
new_knockback
};
let launch_speed = combined_knockback.length();
let launch_direction =
attack::directional_influence::apply_directional_influence_to_direction(
ctx.input.get_last_frame().movement,
combined_knockback.normalize_or_zero(),
ctx.game_settings.fighter_common.di_max_angle,
);
ctx.knockback_velocity.0 = launch_direction * self.hit_reaction.launch_velocity; ctx.knockback_velocity.0 = launch_direction * launch_speed;
ctx.knockback_state.restart();
self.knockback_applied = true; self.knockback_applied = true;
} }
@@ -83,30 +117,19 @@ impl FighterStateImpl for HitstunState {
HitstopStateKind::Grounded => {} HitstopStateKind::Grounded => {}
HitstopStateKind::Airborne => { HitstopStateKind::Airborne => {
air::integrate_gravity(ctx.velocity, ctx.fighter_attributes, false); air::integrate_gravity(ctx.velocity, ctx.fighter_attributes, false);
air::apply_air_motion_with_knockback(ctx);
} }
} }
let speed = ctx.knockback_velocity.length(); if matches!(self.hitstop_kind, HitstopStateKind::Grounded) {
let next_speed = speed attack::decay_knockback(
.saturating_sub(ctx.game_settings.fighter_common.knockback_decay_per_frame) ctx.knockback_velocity,
.max(FGi32::ZERO); ctx.knockback_state,
ctx.game_settings.fighter_common.knockback_decay_per_frame,
ctx.knockback_velocity.0 = ctx.knockback_velocity.normalize_or_zero() * next_speed; );
}
ctx.translation.0 += ctx.velocity.0 + ctx.knockback_velocity.0;
} }
fn on_enter(&mut self, state_context: &mut EnterContext) {
let animation = match self.hitstop_kind {
HitstopStateKind::Grounded => AnimKind::FlinchGround,
HitstopStateKind::Airborne => AnimKind::FlinchAir,
};
state_context.play_animation(animation, false);
state_context.velocity.0 = FGVec2::ZERO;
}
fn on_exit(&mut self, _state_context: &mut ExitContext) {}
fn check_collision_interrupt( fn check_collision_interrupt(
&mut self, &mut self,
state_context: &mut CollisionContext, state_context: &mut CollisionContext,
@@ -114,7 +137,7 @@ impl FighterStateImpl for HitstunState {
match &mut self.hitstop_kind { match &mut self.hitstop_kind {
HitstopStateKind::Grounded => collision_interrupt(state_context, true), HitstopStateKind::Grounded => collision_interrupt(state_context, true),
HitstopStateKind::Airborne => { HitstopStateKind::Airborne => {
air::collision_interrupt(state_context, LandingType::Normal, false) air::collision_interrupt(state_context, LandingType::Normal, Default::default())
} }
} }
} }
+6 -1
View File
@@ -99,6 +99,8 @@ impl FighterStateImpl for JumpSquatState {
fn on_exit(&mut self, state_context: &mut crate::fighter::state::ExitContext) { fn on_exit(&mut self, state_context: &mut crate::fighter::state::ExitContext) {
state_context.input.disable_hold_all(); state_context.input.disable_hold_all();
// We clear tap jump here, it may have weird interactions with air dodging up
state_context.input.clear_command(FighterCommands::TapJump);
} }
fn is_visually_grounded<'a>(&'a self) -> bool { fn is_visually_grounded<'a>(&'a self) -> bool {
@@ -174,7 +176,10 @@ impl FighterStateImpl for JumpState {
air::collision_interrupt( air::collision_interrupt(
state_context, state_context,
crate::fighter::state::land::LandingType::Normal, crate::fighter::state::land::LandingType::Normal,
true, crate::fighter::collision::AirCollisionOptions {
can_pass_through_soft_platforms: true,
..Default::default()
},
) )
} }
+3 -1
View File
@@ -84,6 +84,7 @@ impl FighterStateImpl for LedgeActionState {
state_context.velocity.0 = FGVec2::ZERO; state_context.velocity.0 = FGVec2::ZERO;
state_context.knockback_velocity.0 = FGVec2::ZERO; state_context.knockback_velocity.0 = FGVec2::ZERO;
state_context.knockback_state.clear();
let Some(ledge) = state_context.stage_collision.find_ledge_by_vertex(self.ledge_id) else { let Some(ledge) = state_context.stage_collision.find_ledge_by_vertex(self.ledge_id) else {
return; return;
}; };
@@ -144,8 +145,9 @@ impl FighterStateImpl for LedgeActionState {
fn check_collision_interrupt( fn check_collision_interrupt(
&mut self, &mut self,
_state_context: &mut CollisionContext, state_context: &mut CollisionContext,
) -> Option<FighterState> { ) -> Option<FighterState> {
state_context.apply_desired_ecb();
None None
} }
+2
View File
@@ -36,6 +36,8 @@ impl FighterStateImpl for LedgeGrabState {
fn on_enter(&mut self, state_context: &mut EnterContext) { fn on_enter(&mut self, state_context: &mut EnterContext) {
state_context.play_animation(AnimKind::LedgeGrab, false); state_context.play_animation(AnimKind::LedgeGrab, false);
state_context.knockback_velocity.0 = crate::math::vec::FGVec2::ZERO;
state_context.knockback_state.clear();
*state_context.vulnerability = FighterInvulnerabilityState::Intangible { *state_context.vulnerability = FighterInvulnerabilityState::Intangible {
frames_remaining: None, frames_remaining: None,
+4 -2
View File
@@ -65,8 +65,9 @@ impl FighterStateImpl for LedgeWaitState {
fn on_enter(&mut self, state_context: &mut EnterContext) { fn on_enter(&mut self, state_context: &mut EnterContext) {
state_context.velocity.0 = FGVec2::ZERO; state_context.velocity.0 = FGVec2::ZERO;
state_context.knockback_velocity.0 = FGVec2::ZERO; state_context.knockback_velocity.0 = FGVec2::ZERO;
state_context.knockback_state.clear();
if state_context.ledge_info.grab_count < state_context.game_settings.fighter_common.max_ledge_regrab_count { if state_context.ledge_info.grab_count < state_context.game_settings.fighter_common.max_ledge_grab_count {
*state_context.vulnerability = FighterInvulnerabilityState::Intangible { *state_context.vulnerability = FighterInvulnerabilityState::Intangible {
frames_remaining: Some( frames_remaining: Some(
state_context state_context
@@ -102,8 +103,9 @@ impl FighterStateImpl for LedgeWaitState {
fn check_collision_interrupt( fn check_collision_interrupt(
&mut self, &mut self,
_state_context: &mut CollisionContext, state_context: &mut CollisionContext,
) -> Option<FighterState> { ) -> Option<FighterState> {
state_context.apply_desired_ecb();
None None
} }
+69 -18
View File
@@ -7,12 +7,12 @@ use bevy::prelude::*;
use crate::fighter::animation::{AnimKind, FighterAnimationFrame}; use crate::fighter::animation::{AnimKind, FighterAnimationFrame};
use crate::fighter::attack::{ use crate::fighter::attack::{
FighterAttackScriptAssets, FighterKnockbackVelocity, FighterPendingHitReaction, FighterAttackScriptAssets, FighterKnockbackState, FighterKnockbackVelocity,
FighterStaleMoveQueue, HitStop, FighterPendingHitReaction, FighterStaleMoveQueue, HitStop,
}; };
use crate::fighter::attributes::FighterAttributes; use crate::fighter::attributes::FighterAttributes;
use crate::fighter::baked_animation::{BakedFighterAnimations, FighterBoneMatrices}; use crate::fighter::baked_animation::{BakedFighterAnimations, FighterBoneMatrices};
use crate::fighter::ecb::FighterPreviousECB; use crate::fighter::ecb::{self, FighterDesiredECB, FighterPreviousECB};
use crate::fighter::manifest::FighterManifest; use crate::fighter::manifest::FighterManifest;
use crate::fighter::state::hitstun::HitstunState; use crate::fighter::state::hitstun::HitstunState;
use crate::fighter::surface::EcbLockPolicy; use crate::fighter::surface::EcbLockPolicy;
@@ -49,14 +49,14 @@ pub mod ground_attack;
pub mod hitstun; pub mod hitstun;
pub mod jump; pub mod jump;
pub mod land; pub mod land;
pub mod ledge_action;
pub mod ledge_grab;
pub mod ledge_wait;
pub mod platform_pass; pub mod platform_pass;
pub mod run; pub mod run;
pub mod turn; pub mod turn;
pub mod wait; pub mod wait;
pub mod walk; pub mod walk;
pub mod ledge_wait;
pub mod ledge_action;
pub mod ledge_grab;
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum SurfacePolicy { pub enum SurfacePolicy {
@@ -120,8 +120,9 @@ pub trait FighterStateImpl: Sized {
fn check_collision_interrupt( fn check_collision_interrupt(
&mut self, &mut self,
_state_context: &mut CollisionContext, state_context: &mut CollisionContext,
) -> Option<FighterState> { ) -> Option<FighterState> {
state_context.apply_desired_ecb();
None None
} }
@@ -166,6 +167,7 @@ pub struct EnterContext<'a> {
pub velocity: &'a mut FighterVelocity, pub velocity: &'a mut FighterVelocity,
pub translation: &'a mut FighterTranslation, pub translation: &'a mut FighterTranslation,
pub knockback_velocity: &'a mut FighterKnockbackVelocity, pub knockback_velocity: &'a mut FighterKnockbackVelocity,
pub knockback_state: &'a mut FighterKnockbackState,
pub stale_move_queue: &'a mut FighterStaleMoveQueue, pub stale_move_queue: &'a mut FighterStaleMoveQueue,
pub facing_direction: &'a mut FighterFacingDirection, pub facing_direction: &'a mut FighterFacingDirection,
pub animation_frame: &'a mut FighterAnimationFrame, pub animation_frame: &'a mut FighterAnimationFrame,
@@ -192,10 +194,7 @@ impl EnterContext<'_> {
let position = self let position = self
.baked_animations .baked_animations
.initial_root_position(self.animation_frame.kind, self.model_scale)?; .initial_root_position(self.animation_frame.kind, self.model_scale)?;
Some( Some(self.translation.0 + animation_position_to_gameplay(position, self.facing_direction))
self.translation.0
+ animation_position_to_gameplay(position, self.facing_direction),
)
} }
pub fn get_animation_duration(&self, kind: AnimKind) -> Option<usize> { pub fn get_animation_duration(&self, kind: AnimKind) -> Option<usize> {
@@ -206,6 +205,8 @@ impl EnterContext<'_> {
pub struct ExitContext<'a> { pub struct ExitContext<'a> {
pub input: &'a mut FighterInput, pub input: &'a mut FighterInput,
pub hitboxes: &'a mut FighterHitboxes, pub hitboxes: &'a mut FighterHitboxes,
pub knockback_velocity: &'a mut FighterKnockbackVelocity,
pub knockback_state: &'a mut FighterKnockbackState,
pub surface: &'a mut FighterSurfaceState, pub surface: &'a mut FighterSurfaceState,
pub vulnerability: &'a mut FighterInvulnerabilityState, pub vulnerability: &'a mut FighterInvulnerabilityState,
} }
@@ -218,6 +219,7 @@ pub struct UpdateContext<'a> {
pub velocity: &'a mut FighterVelocity, pub velocity: &'a mut FighterVelocity,
pub surface: &'a mut FighterSurfaceState, pub surface: &'a mut FighterSurfaceState,
pub knockback_velocity: &'a mut FighterKnockbackVelocity, pub knockback_velocity: &'a mut FighterKnockbackVelocity,
pub knockback_state: &'a mut FighterKnockbackState,
pub vulnerability: &'a mut FighterInvulnerabilityState, pub vulnerability: &'a mut FighterInvulnerabilityState,
pub ledge_info: &'a mut FighterLedgeInformation, pub ledge_info: &'a mut FighterLedgeInformation,
pub game_settings: &'a GameSettings, pub game_settings: &'a GameSettings,
@@ -253,8 +255,11 @@ pub struct CollisionContext<'a> {
pub prev_translation: &'a FighterPreviousTranslation, pub prev_translation: &'a FighterPreviousTranslation,
pub input: &'a FighterInput, pub input: &'a FighterInput,
pub velocity: &'a mut FighterVelocity, pub velocity: &'a mut FighterVelocity,
pub knockback_velocity: &'a mut FighterKnockbackVelocity,
pub knockback_state: &'a mut FighterKnockbackState,
pub surface: &'a mut FighterSurfaceState, pub surface: &'a mut FighterSurfaceState,
pub ecb: &'a mut FighterECB, pub ecb: &'a mut FighterECB,
pub desired_ecb: &'a mut FighterDesiredECB,
pub prev_ecb: &'a FighterPreviousECB, pub prev_ecb: &'a FighterPreviousECB,
pub stage_collision: &'a StageCollision, pub stage_collision: &'a StageCollision,
pub leave_ground_ecb_lock_duration: u32, pub leave_ground_ecb_lock_duration: u32,
@@ -262,24 +267,32 @@ pub struct CollisionContext<'a> {
pub ledge_info: &'a mut FighterLedgeInformation, pub ledge_info: &'a mut FighterLedgeInformation,
pub fighter_ledge_collision_box: FGRect, pub fighter_ledge_collision_box: FGRect,
pub downward_stick_threshold: FGi32, pub downward_stick_threshold: FGi32,
pub waveland_snap_distance: FGi32,
} }
impl CollisionContext<'_> { impl CollisionContext<'_> {
/// Commit the target pose before resolving this frame. The collision
/// substep resolver can later replace this with fractional steps.
pub fn apply_desired_ecb(&mut self) {
ecb::interpolate_ecb(self.ecb, *self.desired_ecb, FGi32::ONE);
}
pub fn air_collide_with_stage( pub fn air_collide_with_stage(
&self, &mut self,
can_ignore_soft_platforms: bool, mut options: crate::fighter::collision::AirCollisionOptions,
) -> Option<crate::fighter::collision::AirCollisionWithStageResult> { ) -> Option<crate::fighter::collision::AirCollisionWithStageResult> {
let ignored_polys = self.surface.ignored_polygon_ids(); let ignored_polys = self.surface.ignored_polygon_ids();
let ignore_soft_platforms = can_ignore_soft_platforms options.can_pass_through_soft_platforms = options.can_pass_through_soft_platforms
&& self.input.get_last_frame().movement.y <= -self.downward_stick_threshold; && self.input.get_last_frame().movement.y <= -self.downward_stick_threshold;
crate::fighter::collision::air_collide_with_stage( crate::fighter::collision::air_collide_with_stage_substepped(
self.prev_translation, self.prev_translation,
self.translation, self.translation,
self.prev_ecb, self.velocity,
self.ecb, self.ecb,
self.desired_ecb,
self.stage_collision, self.stage_collision,
&ignored_polys, &ignored_polys,
ignore_soft_platforms, options,
) )
} }
pub fn air_collide_with_ledges( pub fn air_collide_with_ledges(
@@ -328,8 +341,10 @@ pub struct FighterFrameQuery {
pub velocity: &'static mut FighterVelocity, pub velocity: &'static mut FighterVelocity,
pub surface: &'static mut FighterSurfaceState, pub surface: &'static mut FighterSurfaceState,
pub knockback_velocity: &'static mut FighterKnockbackVelocity, pub knockback_velocity: &'static mut FighterKnockbackVelocity,
pub knockback_state: &'static mut FighterKnockbackState,
pub stale_move_queue: &'static mut FighterStaleMoveQueue, pub stale_move_queue: &'static mut FighterStaleMoveQueue,
pub ecb: &'static mut FighterECB, pub ecb: &'static mut FighterECB,
pub desired_ecb: &'static mut FighterDesiredECB,
pub prev_ecb: &'static FighterPreviousECB, pub prev_ecb: &'static FighterPreviousECB,
pub facing_direction: &'static mut FighterFacingDirection, pub facing_direction: &'static mut FighterFacingDirection,
pub animation_frame: &'static mut FighterAnimationFrame, pub animation_frame: &'static mut FighterAnimationFrame,
@@ -395,6 +410,7 @@ impl<'w, 's> FighterFrameQueryItem<'w, 's> {
hitboxes: &mut self.hitboxes, hitboxes: &mut self.hitboxes,
velocity: &mut self.velocity, velocity: &mut self.velocity,
knockback_velocity: &mut self.knockback_velocity, knockback_velocity: &mut self.knockback_velocity,
knockback_state: &mut self.knockback_state,
translation: &mut self.translation, translation: &mut self.translation,
stale_move_queue: &mut self.stale_move_queue, stale_move_queue: &mut self.stale_move_queue,
facing_direction: &mut self.facing_direction, facing_direction: &mut self.facing_direction,
@@ -416,6 +432,8 @@ impl<'w, 's> FighterFrameQueryItem<'w, 's> {
ExitContext { ExitContext {
input: &mut self.input, input: &mut self.input,
hitboxes: &mut self.hitboxes, hitboxes: &mut self.hitboxes,
knockback_velocity: &mut self.knockback_velocity,
knockback_state: &mut self.knockback_state,
surface: &mut self.surface, surface: &mut self.surface,
vulnerability: &mut self.vulnerability, vulnerability: &mut self.vulnerability,
} }
@@ -445,6 +463,7 @@ impl<'w, 's> FighterFrameQueryItem<'w, 's> {
velocity: &mut self.velocity, velocity: &mut self.velocity,
surface: &mut self.surface, surface: &mut self.surface,
knockback_velocity: &mut self.knockback_velocity, knockback_velocity: &mut self.knockback_velocity,
knockback_state: &mut self.knockback_state,
game_settings, game_settings,
animation_root_motion_delta, animation_root_motion_delta,
animation_root_position, animation_root_position,
@@ -475,8 +494,11 @@ impl<'w, 's> FighterFrameQueryItem<'w, 's> {
presentation_snap: &mut self.presentation_snap, presentation_snap: &mut self.presentation_snap,
input: &self.input, input: &self.input,
velocity: &mut self.velocity, velocity: &mut self.velocity,
knockback_velocity: &mut self.knockback_velocity,
knockback_state: &mut self.knockback_state,
surface: &mut self.surface, surface: &mut self.surface,
ecb: &mut self.ecb, ecb: &mut self.ecb,
desired_ecb: &mut self.desired_ecb,
ledge_info: &mut self.ledge_information, ledge_info: &mut self.ledge_information,
prev_ecb: &self.prev_ecb, prev_ecb: &self.prev_ecb,
stage_collision, stage_collision,
@@ -485,6 +507,7 @@ impl<'w, 's> FighterFrameQueryItem<'w, 's> {
.leave_ground_ecb_frame_lock_duration, .leave_ground_ecb_frame_lock_duration,
downward_stick_threshold: game_settings.input_common.run_stick_threshold, downward_stick_threshold: game_settings.input_common.run_stick_threshold,
fighter_ledge_collision_box, fighter_ledge_collision_box,
waveland_snap_distance: game_settings.fighter_common.waveland_snap_distance,
} }
} }
} }
@@ -645,9 +668,16 @@ pub fn state_interrupt_system(
} }
info!("Entering hitstop kind: {:?}", hitstop_kind); info!("Entering hitstop kind: {:?}", hitstop_kind);
let stack_previous_knockback = !frame.surface.is_grounded()
&& !frame.knockback_velocity.0.length_squared().is_zero()
&& frame
.knockback_state
.can_stack(game_settings.fighter_common.knockback_stacking_window);
Some(FighterState::Hitstun(HitstunState::new( Some(FighterState::Hitstun(HitstunState::new(
reaction, reaction,
hitstop_kind, hitstop_kind,
stack_previous_knockback,
))) )))
} else if hitstop.remaining_frames > 0 { } else if hitstop.remaining_frames > 0 {
None None
@@ -743,6 +773,8 @@ pub fn state_collision_interrupt_system(
// Clear hitstop // Clear hitstop
hitstop.remaining_frames = 0; hitstop.remaining_frames = 0;
frame.knockback_velocity.0 = FGVec2::ZERO;
frame.knockback_state.clear();
// subtract one stock // subtract one stock
@@ -757,6 +789,9 @@ pub fn state_collision_interrupt_system(
// reset percentage // reset percentage
*damage = FighterDamage::default(); *damage = FighterDamage::default();
// reset ledge
*frame.ledge_information = FighterLedgeInformation::default();
transition_state( transition_state(
&mut state, &mut state,
@@ -833,9 +868,20 @@ mod tests {
let input = FighterInput::default(); let input = FighterInput::default();
let mut translation = FighterTranslation::default(); let mut translation = FighterTranslation::default();
let mut velocity = FighterVelocity::default(); let mut velocity = FighterVelocity::default();
let mut knockback_velocity = FighterKnockbackVelocity::default();
let mut knockback_state = FighterKnockbackState::default();
let mut surface = FighterSurfaceState::default(); let mut surface = FighterSurfaceState::default();
let mut ecb = FighterECB::default(); let mut ecb = FighterECB::default();
let mut ledge_info = FighterLedgeInformation::default(); let mut desired_ecb = FighterDesiredECB {
top: FGVec2::lit("0", "2"),
bottom: FGVec2::ZERO,
left: FGVec2::lit("-1", "1"),
right: FGVec2::lit("1", "1"),
};
let mut ledge_info = FighterLedgeInformation {
regrab_lockout_remaining_frames: 5,
..default()
};
let previous_ecb = FighterPreviousECB::from(ecb); let previous_ecb = FighterPreviousECB::from(ecb);
let mut presentation_snap = FighterPresentationSnap::default(); let mut presentation_snap = FighterPresentationSnap::default();
let context = CollisionContext { let context = CollisionContext {
@@ -843,8 +889,11 @@ mod tests {
prev_translation: &previous_translation, prev_translation: &previous_translation,
input: &input, input: &input,
velocity: &mut velocity, velocity: &mut velocity,
knockback_velocity: &mut knockback_velocity,
knockback_state: &mut knockback_state,
surface: &mut surface, surface: &mut surface,
ecb: &mut ecb, ecb: &mut ecb,
desired_ecb: &mut desired_ecb,
ledge_info: &mut ledge_info, ledge_info: &mut ledge_info,
prev_ecb: &previous_ecb, prev_ecb: &previous_ecb,
stage_collision: &stage_collision, stage_collision: &stage_collision,
@@ -855,9 +904,11 @@ mod tests {
end: FGVec2::lit("1", "-1"), end: FGVec2::lit("1", "-1"),
}, },
downward_stick_threshold: FGi32::ONE, downward_stick_threshold: FGi32::ONE,
waveland_snap_distance: FGi32::ZERO,
}; };
assert!(context.air_collide_with_ledges().is_none()); assert!(context.air_collide_with_ledges().is_none());
context.ledge_info.regrab_lockout_remaining_frames = 0;
assert_eq!( assert_eq!(
context.air_collide_with_ledges().map(|result| result.ledge), context.air_collide_with_ledges().map(|result| result.ledge),
Some(ledge_id) Some(ledge_id)
+4 -1
View File
@@ -46,7 +46,10 @@ impl FighterStateImpl for PlatformPassState {
air::collision_interrupt( air::collision_interrupt(
state_context, state_context,
crate::fighter::state::land::LandingType::Normal, crate::fighter::state::land::LandingType::Normal,
true, crate::fighter::collision::AirCollisionOptions {
can_pass_through_soft_platforms: true,
..Default::default()
},
) )
} }
+5 -2
View File
@@ -18,6 +18,7 @@ pub struct FighterSettingsCommon {
/// Ground friction applied when the fighter is above the walk speed /// Ground friction applied when the fighter is above the walk speed
pub ground_friction_over_walk_speed_multiplier: FGi32, pub ground_friction_over_walk_speed_multiplier: FGi32,
/// Minimum active launch frames between hits before airborne knockback stacks.
pub knockback_stacking_window: u32, pub knockback_stacking_window: u32,
pub knockback_decay_per_frame: FGi32, pub knockback_decay_per_frame: FGi32,
@@ -55,8 +56,8 @@ pub struct FighterSettingsCommon {
pub ledge_drop_regrab_lockout_duration_frames: u32, pub ledge_drop_regrab_lockout_duration_frames: u32,
/// How many frames (+ the ledge animation duration) the fighter will be invulnerable after grabbing the ledge /// How many frames (+ the ledge animation duration) the fighter will be invulnerable after grabbing the ledge
pub ledge_grab_invulnerability_duration: u32, pub ledge_grab_invulnerability_duration: u32,
/// How many times the fighter can regrab the ledge and still get invulnerability /// How many times the fighter can grab the ledge without landing and still get invulnerability
pub max_ledge_regrab_count: u32, pub max_ledge_grab_count: u32,
/// When hit while the receiver is in the air, use this angle /// When hit while the receiver is in the air, use this angle
pub sakurai_angle_aerial_angle: FGi32, pub sakurai_angle_aerial_angle: FGi32,
@@ -66,6 +67,8 @@ pub struct FighterSettingsCommon {
pub sakurai_angle_high_knockback_angle: FGi32, pub sakurai_angle_high_knockback_angle: FGi32,
/// past this threshold, the knockback is considered high, so it will use [sakurai_angle_high_knockback_angle] /// past this threshold, the knockback is considered high, so it will use [sakurai_angle_high_knockback_angle]
pub sakurai_angle_knockback_threshold: FGi32, pub sakurai_angle_knockback_threshold: FGi32,
pub waveland_snap_distance: FGi32,
} }
#[derive(Reflect, Serialize, Deserialize, Clone)] #[derive(Reflect, Serialize, Deserialize, Clone)]
#[reflect(opaque)] #[reflect(opaque)]
+2
View File
@@ -10,6 +10,7 @@ use bevy::{
world_serialization::WorldAssetRoot, world_serialization::WorldAssetRoot,
}; };
use bevy_egui::{EguiContexts, EguiPrimaryContextPass, egui}; use bevy_egui::{EguiContexts, EguiPrimaryContextPass, egui};
use bevy_ggrs::SnapshotPlugin;
use clap::{Parser, ValueEnum}; use clap::{Parser, ValueEnum};
use egui_extras::Column; use egui_extras::Column;
use itertools::Itertools; use itertools::Itertools;
@@ -131,6 +132,7 @@ impl Plugin for HitboxViewerPlugin {
) )
}; };
app.add_plugins(( app.add_plugins((
SnapshotPlugin,
GameAssetPlugin, GameAssetPlugin,
FighterScriptImportPlugin, FighterScriptImportPlugin,
BakedAnimationAssetProcessingPlugin, BakedAnimationAssetProcessingPlugin,
-1
View File
@@ -717,7 +717,6 @@ pub fn postprocess_input(
FighterAttackCommandType::Neutral FighterAttackCommandType::Neutral
}; };
dbg!(input.movement_flick.y, attack_type);
input.set_lifetime(FighterCommands::Attack, tap); input.set_lifetime(FighterCommands::Attack, tap);
input.set_attack_command_type(attack_type); input.set_attack_command_type(attack_type);
} }
+15 -5
View File
@@ -1,15 +1,15 @@
use bevy::{color::palettes::css::RED, prelude::*}; use bevy::{color::palettes::css::RED, prelude::*};
use crate::{ use crate::{
match_loading::MatchConfig, math::{int::FGi32, vec3::FGVec3}, stage::{ game_settings::GameSettings, match_loading::MatchConfig, math::{int::FGi32, vec3::FGVec3}, stage::{
line::{StageCollision, StageLedgeSide}, line::{StageCollision, StageLedgeSide, StagePolyLineSegmentType}, manifest::{StageManifest, StageManifestRegistry},
manifest::{StageManifest, StageManifestRegistry},
}, },
}; };
pub fn debug_draw_scene(mut gizmos: Gizmos, stage_collision: Res<StageCollision>) { pub fn debug_draw_scene(mut gizmos: Gizmos, stage_collision: Res<StageCollision>, game_settings: Res<GameSettings>) {
for poly in stage_collision.stage_polys.iter() { for poly in stage_collision.stage_polys.iter() {
for segment in &poly.segments { for (segment, next_segment) in poly.segments.iter().zip(poly.segments.iter().cycle().skip(1)) {
let wavedash_normal = ((next_segment.normal.to_vec2() + segment.normal.to_vec2()) * 0.5).normalize();
let from = segment.segment.point1().to_vec2(); let from = segment.segment.point1().to_vec2();
let to = segment.segment.point2().to_vec2(); let to = segment.segment.point2().to_vec2();
let from_3d = Vec3::new(from.x, from.y, 0.0); let from_3d = Vec3::new(from.x, from.y, 0.0);
@@ -18,6 +18,16 @@ pub fn debug_draw_scene(mut gizmos: Gizmos, stage_collision: Res<StageCollision>
gizmos.line(from_3d, end_3d, RED); gizmos.line(from_3d, end_3d, RED);
let midpoint = (from_3d + end_3d) * 0.5; let midpoint = (from_3d + end_3d) * 0.5;
gizmos.arrow(midpoint, midpoint + normal_3d, RED); gizmos.arrow(midpoint, midpoint + normal_3d, RED);
if matches!(segment.segment_type, StagePolyLineSegmentType::Floor) {
let radius = game_settings.fighter_common.waveland_snap_distance.to_num::<f32>();
let a = segment.segment.point1().to_vec2();
let a = Vec3::new(a.x, a.y, 0.0);
let b = segment.segment.point2().to_vec2();
let b = Vec3::new(b.x, b.y, 0.0);
let offset = Vec3::new(wavedash_normal.x, wavedash_normal.y, 0.0) * radius;
gizmos.line(a + offset, b + offset, bevy::color::palettes::css::HOT_PINK);
gizmos.line(a - offset, b - offset, bevy::color::palettes::css::HOT_PINK);
}
} }
} }