Refactor loading

This commit is contained in:
2026-08-26 19:08:58 +02:00
parent 4ff388f9c0
commit 21a5170dbc
40 changed files with 1034 additions and 426 deletions
+18 -19
View File
@@ -1,9 +1,9 @@
use std::{collections::HashMap, time::Duration};
use std::time::Duration;
use bevy::{mesh::skinning::SkinnedMesh, prelude::*};
use crate::{
fighter::{FighterECB, FighterTranslation, FighterVisual, visual::FighterAnimations}, player::Player,
fighter::{FighterECB, FighterFacingDirection, FighterTranslation, FighterVisual, visual::FighterAnimations}, player::Player,
};
#[derive(Component)]
@@ -47,44 +47,43 @@ pub fn setup_fighter_animation_player(
}
}
pub fn apply_animation(children: Query<&mut Transform, With<FighterVisual>>) {
for mut trf in children {
pub fn apply_animation(children: Query<(&mut Transform, &FighterFacingDirection), With<FighterVisual>>) {
for (mut trf, facing_direction) in children {
// Melee model scale is in decimeters
trf.rotation = Quat::IDENTITY;
trf.rotate_local_y(std::f32::consts::PI * 0.5);
trf.rotate_local_y(std::f32::consts::PI * 0.5 * facing_direction.to_sign().to_num::<f32>());
}
}
pub fn animation_init(
fighters: Query<
(
&FighterAnimations,
&FighterAnimationPlayerLink,
),
Added<FighterAnimationPlayerLink>
(&FighterAnimations, &FighterAnimationPlayerLink),
Added<FighterAnimationPlayerLink>,
>,
mut commands: Commands,
mut anim_player_query: Query<(&mut AnimationPlayer, &mut AnimationTransitions)>
mut anim_player_query: Query<(&mut AnimationPlayer, &mut AnimationTransitions)>,
) {
for (anim, link) in fighters {
commands.entity(link.0).insert(
AnimationGraphHandle(anim.graph.clone())
);
commands
.entity(link.0)
.insert(AnimationGraphHandle(anim.graph.clone()));
info!("BEGIN! {:?}", fighters);
if let Ok((mut player, mut transitions)) = anim_player_query.get_mut(link.0) {
info!("DOS");
transitions.play(&mut player, anim.clips[&AnimKind::Wait], Duration::ZERO).repeat();
transitions
.play(&mut player, anim.clips[&AnimKind::Wait], Duration::ZERO)
.repeat();
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Deserialize)]
#[derive(
Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize, Reflect,
)]
pub enum AnimKind {
Wait,
Walk,
Run,
Dash,
JumpSquat,
}
#[derive(serde::Deserialize, bevy::asset::Asset, bevy::reflect::TypePath)]
pub struct AnimManifest(pub HashMap<AnimKind, String>);
+15 -3
View File
@@ -1,11 +1,13 @@
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{input::FighterInputFrame, math::int::FGi32};
/// Per-fighter tuning values. These are character data, not global rules —
/// anything that applies to every fighter belongs in
/// [`crate::game_settings::FighterSettingsCommon`] instead.
#[derive(Component, Clone, Copy)]
#[derive(Asset, Component, Clone, Copy, Reflect, Serialize, Deserialize)]
#[reflect(opaque)]
pub struct FighterAttributes {
pub base_walk_accel: FGi32,
pub stick_walk_accel: FGi32,
@@ -19,7 +21,9 @@ pub struct FighterAttributes {
pub max_dash_vel: FGi32,
pub jumpsquat_duration: u32,
pub jump_vertical_velocity: FGi32,
pub short_hop_vertical_velocity: FGi32,
pub full_jump_vertical_velocity: FGi32,
pub jump_horizontal_velocity: FGi32,
pub ground_friction: FGi32,
pub terminal_velocity: FGi32,
@@ -27,7 +31,11 @@ pub struct FighterAttributes {
}
impl FighterAttributes {
pub fn get_accel_and_target_dashrun(&self, input: &FighterInputFrame, direction: FGi32) -> (FGi32, FGi32) {
pub fn get_accel_and_target_dashrun(
&self,
input: &FighterInputFrame,
direction: FGi32,
) -> (FGi32, FGi32) {
let accel = input.movement.x * self.stick_dash_accel;
let accel = accel + direction * self.base_dash_accel;
let target_vel = input.movement.x * self.max_dash_vel;
@@ -45,3 +53,7 @@ impl FighterAttributes {
(accel, target_vel)
}
}
pub struct FighterAttributesLink {
attributes: Handle<FighterAttributes>,
}
+17 -4
View File
@@ -9,11 +9,24 @@ use crate::fighter::state::StateNameDebug;
use crate::fighter::{FighterECB, FighterPreviousTranslation, FighterTranslation, FighterVelocity};
use crate::input::FighterInput;
pub fn debug_draw_ecb(ecbs: Query<(&FighterECB, &FighterTranslation, &FighterPreviousECB, &FighterPreviousTranslation)>, mut gizmos: Gizmos) {
pub fn debug_draw_ecb(
ecbs: Query<(
&FighterECB,
&FighterTranslation,
&FighterPreviousECB,
&FighterPreviousTranslation,
)>,
mut gizmos: Gizmos,
) {
for (ecb, trf, ecb_prev, trf_prev) in ecbs {
let transformed = ecb.to_3d_lineloop(Transform::from_xyz(trf.x.to_num(), trf.y.to_num(), 0.0));
let transformed =
ecb.to_3d_lineloop(Transform::from_xyz(trf.x.to_num(), trf.y.to_num(), 0.0));
gizmos.lineloop(transformed, YELLOW);
let prev_transformed = ecb_prev.to_3d_lineloop(Transform::from_xyz(trf_prev.x.to_num(), trf_prev.y.to_num(), -0.1));
let prev_transformed = ecb_prev.to_3d_lineloop(Transform::from_xyz(
trf_prev.x.to_num(),
trf_prev.y.to_num(),
-0.1,
));
gizmos.lineloop(prev_transformed, ORANGE);
}
}
@@ -44,4 +57,4 @@ pub fn update_config(
config.depth_bias = if config.depth_bias == 0. { -1. } else { 0. };
}
}
}
}
+1 -3
View File
@@ -28,9 +28,7 @@ impl From<FighterECB> for FighterPreviousECB {
}
}
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 {
*previous_ecb = (*ecb).into();
}
+122
View File
@@ -0,0 +1,122 @@
use std::collections::HashMap;
use bevy::{asset::UntypedHandle, prelude::*};
use bevy_asset_loader::asset_collection::AssetCollection;
use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use crate::{
AppState,
fighter::{FighterAttributes, animation::AnimKind},
game_settings::GameSettings,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Reflect, EnumIter)]
pub enum FighterId {
TestFighter,
}
#[derive(Serialize, Deserialize, Clone, Asset, Reflect)]
pub struct FighterManifest {
pub id: FighterId,
pub model_path: String,
pub attributes: FighterAttributes,
pub animations: HashMap<AnimKind, String>,
}
#[derive(Resource)]
pub struct FighterManifestAssets(pub Vec<Handle<FighterManifest>>);
impl FighterManifestAssets {
fn requested(world: &World) -> Self {
let settings = world.resource::<GameSettings>();
let asset_server = world.resource::<AssetServer>();
Self(
settings
.fighter_manifest_paths
.iter()
.map(|path| asset_server.load(path.clone()))
.collect(),
)
}
}
impl AssetCollection for FighterManifestAssets {
fn create(world: &mut World) -> Self {
Self::requested(world)
}
fn load(world: &mut World) -> Vec<UntypedHandle> {
Self::requested(world)
.0
.into_iter()
.map(Handle::untyped)
.collect()
}
}
#[derive(Resource)]
pub struct FighterManifestRegistry(HashMap<FighterId, Handle<FighterManifest>>);
impl FighterManifestRegistry {
pub fn get(&self, fighter: FighterId) -> Option<&Handle<FighterManifest>> {
self.0.get(&fighter)
}
}
pub fn prepare_fighter_manifests(
mut commands: Commands,
handles: Res<FighterManifestAssets>,
manifests: Res<Assets<FighterManifest>>,
mut next_state: ResMut<NextState<AppState>>,
) {
let mut registry = HashMap::with_capacity(handles.0.len());
for handle in &handles.0 {
let Some(manifest) = manifests.get(handle) else {
fail(&mut next_state, "a loaded fighter manifest is unavailable");
return;
};
if manifest.model_path.is_empty() {
fail(
&mut next_state,
&format!("{:?} has an empty model path", manifest.id),
);
return;
}
if !manifest.animations.contains_key(&AnimKind::Wait) {
fail(
&mut next_state,
&format!("{:?} has no Wait animation", manifest.id),
);
return;
}
if registry.insert(manifest.id, handle.clone()).is_some() {
fail(
&mut next_state,
&format!("duplicate manifest for {:?}", manifest.id),
);
return;
}
}
for fighter in FighterId::iter() {
if !registry.contains_key(&fighter) {
fail(
&mut next_state,
&format!("no manifest configured for {fighter:?}"),
);
return;
}
}
commands.insert_resource(FighterManifestRegistry(registry));
next_state.set(AppState::Idle);
}
fn fail(next_state: &mut NextState<AppState>, message: &str) {
error!("Fighter manifest preparation failed: {message}");
next_state.set(AppState::CommonAssetLoadFailed);
}
+23 -21
View File
@@ -10,6 +10,7 @@ pub mod attributes;
pub mod collision;
pub mod debug;
pub mod ecb;
pub mod manifest;
pub mod motion;
pub mod state;
pub mod visual;
@@ -20,6 +21,7 @@ pub mod visual;
// silently change what this module exports.
pub use attributes::FighterAttributes;
pub use ecb::FighterECB;
pub use manifest::FighterId;
pub use motion::{FighterPreviousTranslation, FighterTranslation, FighterVelocity, Grounded};
use crate::{
@@ -41,12 +43,21 @@ use state::state_interrupt_system;
#[derive(Default)]
pub struct FighterPlugin;
#[derive(Component, Copy, Clone, Hash)]
#[derive(Component, Copy, Clone, Hash, Debug, PartialEq, Reflect)]
pub enum FighterFacingDirection {
Left,
Right,
}
impl FighterFacingDirection {
pub fn to_sign(&self) -> FGi32 {
match self {
FighterFacingDirection::Left => FGi32::NEG_ONE,
FighterFacingDirection::Right => FGi32::ONE,
}
}
}
#[derive(Component)]
#[require(Transform)]
pub struct FighterVisual;
@@ -105,41 +116,32 @@ impl Plugin for FighterPlugin {
.add_systems(EguiPrimaryContextPass, debug::fighter_debug)
.add_systems(EguiPrimaryContextPass, debug::update_config)
.rollback_component_with_clone::<FighterState>()
.checksum_component_with_hash::<FighterState>();
.checksum_component_with_hash::<FighterState>()
.register_type::<FighterFacingDirection>();
}
}
pub fn spawn_fighter(
commands: &mut Commands,
player_handle: usize,
spawn_position: FGVec2,
attributes: FighterAttributes,
animations: FighterAnimations,
visual_root: WorldAssetRoot,
) {
commands.spawn((
Name("Fighter".into()),
Player { handle: 0 },
Name(format!("Fighter {player_handle}").into()),
Player {
handle: player_handle,
},
FighterFacingDirection::Right,
FighterECB {
vertical_half: FGi32::lit("5.0"),
horizontal_half: FGi32::lit("2.5"),
},
FighterVelocity::default(),
FighterTranslation(FGVec2::lit("5.0", "12.5")),
FighterAttributes {
base_walk_accel: FGi32::lit("0.1"),
stick_walk_accel: FGi32::lit("0.16"),
max_walk_vel: FGi32::lit("0.7"),
ground_friction: FGi32::lit("0.09"),
dash_acceleration_duration: 13,
dash_duration: 24,
base_dash_accel: FGi32::lit("0.02"),
stick_dash_accel: FGi32::lit("0.065"),
max_dash_vel: FGi32::lit("1.1"),
jump_vertical_velocity: FGi32::lit("2.5"),
dash_initial_velocity: FGi32::lit("1.4"),
terminal_velocity: FGi32::lit("2.8"),
gravity: FGi32::lit("0.23"),
jumpsquat_duration: 4,
},
FighterTranslation(spawn_position),
attributes,
visual_root,
animations,
FighterState::Fall(FallState),
+1 -3
View File
@@ -33,9 +33,7 @@ pub fn apply_air_motion(
}
}
pub fn copy_fighter_transform_to_visuals(
fighters: Query<(&FighterTranslation, &mut Transform)>,
) {
pub fn copy_fighter_transform_to_visuals(fighters: Query<(&FighterTranslation, &mut Transform)>) {
for (translation, mut transform) in fighters {
transform.translation = Vec3::new(translation.x.to_num(), translation.y.to_num(), 0.0);
}
+2 -2
View File
@@ -1,6 +1,6 @@
use bevy::prelude::*;
use crate::fighter::{*};
use crate::fighter::*;
pub fn integrate_gravity(velocity: &mut FighterVelocity, attributes: &FighterAttributes) {
velocity.y -= attributes.gravity;
@@ -15,4 +15,4 @@ pub fn apply_air_motion(
// Vertical velocity should be 0 on the ground
prev_translation.0 = translation.0;
translation.0 += velocity.0;
}
}
+35 -27
View File
@@ -3,13 +3,13 @@ use std::time::Duration;
use bevy::prelude::*;
use super::{FighterStateImpl, FighterStateContext, ground, run, wait, walk};
use super::{FighterStateContext, FighterStateImpl, ground, run, wait, walk};
use crate::fighter::animation::AnimKind;
use crate::fighter::state::FighterState;
use crate::fighter::state::fall::FallState;
use crate::fighter::state::ground::{GroundedMotionResult, GroundedStateCommon};
use crate::fighter::state::wait::WaitState;
use crate::fighter::state::{FighterState};
use crate::fighter::{FighterAttributes, FighterVelocity, collision};
use crate::fighter::{FighterAttributes, FighterFacingDirection, FighterVelocity, collision};
use crate::game_settings::GameSettings;
use crate::input::{
FighterCommands::{SmashMoveLeft, SmashMoveRight},
@@ -20,33 +20,30 @@ use crate::math::int::FGi32;
#[derive(Debug, Clone)]
pub struct DashState {
frames_in_dash: u32,
direction: FGi32,
ground_common: GroundedStateCommon
direction: FighterFacingDirection,
ground_common: GroundedStateCommon,
}
impl std::hash::Hash for DashState {
fn hash<H: Hasher>(&self, state: &mut H) {
self.direction.to_bits().hash(state);
self.direction.hash(state);
self.frames_in_dash.hash(state);
}
}
impl DashState {
pub fn new(direction: FGi32, ground_common: GroundedStateCommon) -> Self {
pub fn new(direction: FighterFacingDirection, ground_common: GroundedStateCommon) -> Self {
Self {
frames_in_dash: 0,
direction,
ground_common
ground_common,
}
}
}
impl FighterStateImpl for DashState {
const NAME: &'static str = "Dash";
fn check_interrupt(
&self,
state_context: &FighterStateContext,
) -> Option<FighterState> {
fn check_interrupt(&self, state_context: &FighterStateContext) -> Option<FighterState> {
if self.frames_in_dash > state_context.fighter_attribs.dash_duration {
run::check_input(state_context, &self.ground_common)
.or_else(|| walk::check_input(state_context, &self.ground_common))
@@ -58,13 +55,20 @@ impl FighterStateImpl for DashState {
} else {
check_smash_input_with_dir(state_context)
.filter(|dir| *dir != self.direction)
.and_then(|dir| Some(FighterState::Dash(DashState::new(dir, self.ground_common.clone()))))
.and_then(|dir| {
Some(FighterState::Dash(DashState::new(
dir,
self.ground_common.clone(),
)))
})
}
}
fn on_enter(&mut self, state_context: &mut FighterStateContext) {
*state_context.facing_direction = self.direction;
state_context.input.clear_buffer();
state_context.velocity.x = state_context.fighter_attribs.dash_initial_velocity * self.direction;
state_context.velocity.x =
state_context.fighter_attribs.dash_initial_velocity * self.direction.to_sign();
state_context.animation_transitions.play(
&mut state_context.animation_player,
@@ -72,14 +76,16 @@ impl FighterStateImpl for DashState {
Duration::ZERO,
);
}
fn update(&mut self, state_context: &mut FighterStateContext) {
self.frames_in_dash += 1;
info!("{}", self.frames_in_dash);
let last_frame = state_context.input.get_last_frame();
let (accel, target_vel) = state_context.fighter_attribs.get_accel_and_target_dashrun(&last_frame, self.direction);
let (accel, target_vel) = state_context
.fighter_attribs
.get_accel_and_target_dashrun(&last_frame, self.direction.to_sign());
let accel = ground::compute_ground_accel(
accel,
target_vel,
@@ -100,11 +106,9 @@ impl FighterStateImpl for DashState {
&mut self,
state_context: &mut FighterStateContext,
) -> Option<FighterState> {
if let GroundedMotionResult::InAir = ground::collide_with_stage_grounded(
state_context,
&mut self.ground_common,
true
) {
if let GroundedMotionResult::InAir =
ground::collide_with_stage_grounded(state_context, &mut self.ground_common, true)
{
Some(FighterState::Fall(FallState))
} else {
None
@@ -112,16 +116,20 @@ impl FighterStateImpl for DashState {
}
}
fn check_smash_input_with_dir(state_context: &FighterStateContext) -> Option<FGi32> {
fn check_smash_input_with_dir(state_context: &FighterStateContext) -> Option<FighterFacingDirection> {
if state_context.input.has_command(SmashMoveLeft) {
return Some(FGi32::NEG_ONE);
return Some(FighterFacingDirection::Left);
} else if state_context.input.has_command(SmashMoveRight) {
return Some(FGi32::ONE);
return Some(FighterFacingDirection::Right);
} else {
None
}
}
pub fn check_input(state_context: &FighterStateContext, ground_common: &GroundedStateCommon) -> Option<FighterState> {
check_smash_input_with_dir(state_context).map(|dir| FighterState::Dash(DashState::new(dir, ground_common.clone())))
pub fn check_input(
state_context: &FighterStateContext,
ground_common: &GroundedStateCommon,
) -> Option<FighterState> {
check_smash_input_with_dir(state_context)
.map(|dir| FighterState::Dash(DashState::new(dir, ground_common.clone())))
}
+12 -12
View File
@@ -1,9 +1,9 @@
use bevy::prelude::*;
use super::{FighterStateImpl, FighterStateContext, ground, walk};
use crate::fighter::state::{FighterState, air};
use super::{FighterStateContext, FighterStateImpl, ground, walk};
use crate::fighter::state::ground::GroundedStateCommon;
use crate::fighter::state::wait::WaitState;
use crate::fighter::state::{FighterState, air};
use crate::fighter::{FighterAttributes, FighterVelocity, collision, motion};
use crate::game_settings::GameSettings;
use crate::stage::line::StageCollision;
@@ -13,18 +13,19 @@ pub struct FallState;
impl FighterStateImpl for FallState {
const NAME: &'static str = "Fall";
fn check_interrupt(
&self,
state_context: &FighterStateContext,
) -> Option<FighterState> {
fn check_interrupt(&self, state_context: &FighterStateContext) -> Option<FighterState> {
None
}
fn on_enter(&mut self, _state_context: &mut super::FighterStateContext) {}
fn update(&mut self, state_context: &mut super::FighterStateContext) {
air::integrate_gravity(state_context.velocity, state_context.fighter_attribs);
air::apply_air_motion(state_context.velocity, state_context.translation, state_context.prev_translation);
air::apply_air_motion(
state_context.velocity,
state_context.translation,
state_context.prev_translation,
);
}
fn check_collision_interrupt(
@@ -35,9 +36,9 @@ impl FighterStateImpl for FallState {
// Adjust translation
state_context.translation.0 = res.hit_position - state_context.ecb.get_bottom_point();
let grounded_common = GroundedStateCommon {
current_line_id: res.line_id
current_line_id: res.line_id,
};
Some(FighterState::Wait(WaitState { grounded_common } ))
Some(FighterState::Wait(WaitState { grounded_common }))
} else {
None
}
@@ -52,4 +53,3 @@ pub fn check_input(state_context: &FighterStateContext) -> Option<FighterState>
}
None
}
+2 -2
View File
@@ -44,7 +44,7 @@ pub fn compute_ground_accel(
} else {
let mut accel = accel;
let ground_max_horizontal_velocity =
game_settings.figher_common.ground_max_horizontal_velocity;
game_settings.fighter_common.ground_max_horizontal_velocity;
if !(gr_vel * accel < FGi32::ZERO) {
// accelerating, not reversing
if accel > FGi32::ZERO {
@@ -146,7 +146,7 @@ pub fn collide_with_stage_grounded(
pub fn grounded_movement_common_interrupts(
state_context: &FighterStateContext,
ground_common: &GroundedStateCommon
ground_common: &GroundedStateCommon,
) -> Option<FighterState> {
super::jump::check_input(state_context, ground_common)
}
+17 -7
View File
@@ -1,12 +1,13 @@
use std::time::Duration;
use bevy::prelude::*;
use crate::{
fighter::state::{
fighter::{animation::AnimKind, state::{
FighterState, FighterStateContext, FighterStateImpl,
fall::FallState,
ground::{self, GroundedMotionResult, GroundedStateCommon},
},
input::FighterCommands,
}}, input::FighterCommands,
};
pub enum JumpType {
@@ -52,7 +53,7 @@ impl FighterStateImpl for JumpSquatState {
state_context.fighter_attribs.ground_friction
* state_context
.game_settings
.figher_common
.fighter_common
.ground_friction_over_walk_speed_multiplier
} else {
state_context.fighter_attribs.ground_friction
@@ -81,6 +82,17 @@ impl FighterStateImpl for JumpSquatState {
None
}
}
fn play_animation(
&self,
transitions: &mut AnimationTransitions,
player: &mut AnimationPlayer,
anims: &crate::fighter::visual::FighterAnimations,
) {
transitions.play(player, anims.clips[&AnimKind::JumpSquat], Duration::ZERO);
}
fn on_enter(&mut self, _state_context: &mut FighterStateContext) {}
}
impl FighterStateImpl for JumpState {
@@ -99,7 +111,5 @@ pub fn check_input(
state_context
.input
.has_command(FighterCommands::Jump)
.then(|| FighterState::JumpSquat(JumpSquatState::create(
ground_common.clone(),
)))
.then(|| FighterState::JumpSquat(JumpSquatState::create(ground_common.clone())))
}
+4 -1
View File
@@ -9,7 +9,7 @@ use crate::fighter::animation::FighterAnimationPlayerLink;
use crate::fighter::ecb::FighterPreviousECB;
use crate::fighter::visual::FighterAnimations;
use crate::fighter::{
FighterAttributes, FighterECB, FighterPreviousTranslation, FighterTranslation, FighterVelocity,
FighterAttributes, FighterECB, FighterFacingDirection, FighterPreviousTranslation, FighterTranslation, FighterVelocity,
};
use crate::game_settings::GameSettings;
use crate::input::FighterInput;
@@ -88,6 +88,7 @@ pub struct FighterStateContext<'a> {
pub ecb: &'a mut FighterECB,
pub prev_ecb: &'a mut FighterPreviousECB,
pub fighter_attribs: &'a FighterAttributes,
pub facing_direction: &'a mut FighterFacingDirection,
pub game_settings: &'a GameSettings,
pub stage_collision: &'a StageCollision,
pub animations: &'a FighterAnimations,
@@ -114,6 +115,7 @@ pub struct FighterFrameQuery {
pub velocity: &'static mut FighterVelocity,
pub ecb: &'static mut FighterECB,
pub prev_ecb: &'static mut FighterPreviousECB,
pub facing_direction: &'static mut FighterFacingDirection,
pub attributes: &'static FighterAttributes,
}
@@ -133,6 +135,7 @@ impl<'w, 's> FighterFrameQueryItem<'w, 's> {
velocity: &mut self.velocity,
ecb: &mut self.ecb,
prev_ecb: &mut self.prev_ecb,
facing_direction: &mut self.facing_direction,
fighter_attribs: self.attributes,
game_settings,
stage_collision,
+32 -24
View File
@@ -2,7 +2,7 @@ use std::time::Duration;
use bevy::prelude::*;
use super::{FighterStateImpl, FighterStateContext, ground, wait, walk};
use super::{FighterStateContext, FighterStateImpl, ground, wait, walk};
use crate::fighter::animation::AnimKind;
use crate::fighter::state::FighterState;
use crate::fighter::state::fall::FallState;
@@ -14,34 +14,39 @@ use crate::math::int::FGi32;
#[derive(Component, Debug, Clone, Hash)]
pub struct RunState {
pub grounded_common: GroundedStateCommon
pub grounded_common: GroundedStateCommon,
}
impl FighterStateImpl for RunState {
const NAME: &'static str = "Run";
fn check_interrupt(
&self,
state_context: &FighterStateContext,
) -> Option<FighterState> {
fn check_interrupt(&self, state_context: &FighterStateContext) -> Option<FighterState> {
let input_frame = state_context.input.get_last_frame();
if input_frame.movement.x.abs() >= state_context.game_settings.input_common.run_stick_threshold {
if input_frame.movement.x.abs()
>= state_context.game_settings.input_common.run_stick_threshold
{
None
} else {
walk::check_input(state_context, &self.grounded_common).or_else(|| wait::check_input(state_context, &self.grounded_common))
walk::check_input(state_context, &self.grounded_common)
.or_else(|| wait::check_input(state_context, &self.grounded_common))
}
}
fn on_enter(&mut self, state_context: &mut super::FighterStateContext) {
state_context.animation_transitions.play(
&mut state_context.animation_player,
state_context.animations.clips[&AnimKind::Run],
Duration::ZERO,
).repeat();
state_context
.animation_transitions
.play(
&mut state_context.animation_player,
state_context.animations.clips[&AnimKind::Run],
Duration::ZERO,
)
.repeat();
}
fn update(&mut self, state_context: &mut super::FighterStateContext) {
let last_frame = state_context.input.get_last_frame();
let (accel, target_vel) = state_context.fighter_attribs.get_accel_and_target_dashrun(&last_frame, FGi32::ONE);
let (accel, target_vel) = state_context
.fighter_attribs
.get_accel_and_target_dashrun(&last_frame, FGi32::ONE);
let accel = ground::compute_ground_accel(
accel,
target_vel,
@@ -62,11 +67,9 @@ impl FighterStateImpl for RunState {
&mut self,
state_context: &mut FighterStateContext,
) -> Option<FighterState> {
if let GroundedMotionResult::InAir = ground::collide_with_stage_grounded(
state_context,
&mut self.grounded_common,
false
) {
if let GroundedMotionResult::InAir =
ground::collide_with_stage_grounded(state_context, &mut self.grounded_common, false)
{
Some(FighterState::Fall(FallState))
} else {
None
@@ -74,11 +77,16 @@ impl FighterStateImpl for RunState {
}
}
pub fn check_input(state_context: &FighterStateContext, ground_state_common: &GroundedStateCommon) -> Option<FighterState> {
pub fn check_input(
state_context: &FighterStateContext,
ground_state_common: &GroundedStateCommon,
) -> Option<FighterState> {
let input_frame = state_context.input.get_last_frame();
if input_frame.movement.x.abs() >= state_context.game_settings.input_common.run_stick_threshold
{
return Some(FighterState::Run(RunState { grounded_common: ground_state_common.clone() }));
return Some(FighterState::Run(RunState {
grounded_common: ground_state_common.clone(),
}));
}
None
}
}
+14 -10
View File
@@ -4,11 +4,11 @@ use bevy::prelude::*;
use super::{FighterStateContext, FighterStateImpl, ground, walk};
use crate::fighter::animation::AnimKind;
use crate::fighter::state::{FighterState, dash};
use crate::fighter::state::fall::FallState;
use crate::fighter::state::ground::{
GroundedMotionResult, GroundedStateCommon, grounded_movement_common_interrupts,
};
use crate::fighter::state::{FighterState, dash};
use crate::fighter::{FighterAttributes, FighterVelocity};
use crate::game_settings::GameSettings;
use crate::stage::line::StageLineID;
@@ -21,17 +21,21 @@ pub struct WaitState {
impl FighterStateImpl for WaitState {
const NAME: &'static str = "Wait";
fn check_interrupt(&self, state_context: &FighterStateContext) -> Option<FighterState> {
dash::check_input(state_context, &self.grounded_common).or_else(||
grounded_movement_common_interrupts(state_context, &self.grounded_common)
.or_else(|| walk::check_input(state_context, &self.grounded_common)))
dash::check_input(state_context, &self.grounded_common).or_else(|| {
grounded_movement_common_interrupts(state_context, &self.grounded_common)
.or_else(|| walk::check_input(state_context, &self.grounded_common))
})
}
fn on_enter(&mut self, state_context: &mut super::FighterStateContext) {
state_context.animation_transitions.play(
&mut state_context.animation_player,
state_context.animations.clips[&AnimKind::Wait],
Duration::ZERO,
).repeat();
state_context
.animation_transitions
.play(
&mut state_context.animation_player,
state_context.animations.clips[&AnimKind::Wait],
Duration::ZERO,
)
.repeat();
}
fn update(&mut self, state_context: &mut super::FighterStateContext) {
@@ -40,7 +44,7 @@ impl FighterStateImpl for WaitState {
state_context.fighter_attribs.ground_friction
* state_context
.game_settings
.figher_common
.fighter_common
.ground_friction_over_walk_speed_multiplier
} else {
state_context.fighter_attribs.ground_friction
+8 -5
View File
@@ -24,11 +24,14 @@ impl FighterStateImpl for WalkState {
}
fn on_enter(&mut self, state_context: &mut FighterStateContext) {
state_context.animation_transitions.play(
&mut state_context.animation_player,
state_context.animations.clips[&AnimKind::Walk],
Duration::ZERO,
).repeat();
state_context
.animation_transitions
.play(
&mut state_context.animation_player,
state_context.animations.clips[&AnimKind::Walk],
Duration::ZERO,
)
.repeat();
}
fn update(&mut self, state_context: &mut FighterStateContext) {
+2 -90
View File
@@ -1,98 +1,10 @@
use bevy::gltf::Gltf;
use bevy::prelude::*;
use std::collections::HashMap;
use crate::{AppState, fighter::{
animation::{AnimKind, AnimManifest},
spawn_fighter,
}};
use crate::fighter::animation::AnimKind;
// One entry per character being loaded
pub struct PendingCharacter {
pub id: String,
pub gltf: Handle<Gltf>,
pub manifest: Handle<AnimManifest>,
pub resolved: bool,
}
#[derive(Resource, Default)]
pub struct CharacterLoadQueue(pub Vec<PendingCharacter>);
#[derive(Component)]
#[derive(Component, Clone)]
pub struct FighterAnimations {
pub graph: Handle<AnimationGraph>,
pub clips: HashMap<AnimKind, AnimationNodeIndex>,
}
pub fn start_loading(mut commands: Commands, asset_server: Res<AssetServer>) {
let queue = vec![PendingCharacter {
id: "jigglypuff".to_owned(),
gltf: asset_server.load(format!("fighters/jiggs/jigglypuff-normal.glb")),
manifest: asset_server.load(format!("fighters/jiggs/jigglypuff-anims.ron")),
resolved: false,
}];
commands.insert_resource(CharacterLoadQueue(queue));
}
pub fn resolve_character_assets(
mut commands: Commands,
mut queue: ResMut<CharacterLoadQueue>,
gltf_assets: Res<Assets<Gltf>>,
manifest_assets: Res<Assets<AnimManifest>>,
mut graphs: ResMut<Assets<AnimationGraph>>,
anim_clips: Res<Assets<AnimationClip>>,
mut next_state: ResMut<NextState<AppState>>,
) {
for pending in queue.0.iter_mut().filter(|p| !p.resolved) {
let (Some(gltf), Some(manifest)) = (
gltf_assets.get(&pending.gltf),
manifest_assets.get(&pending.manifest),
) else {
continue; // still loading, try again next frame
};
let mut graph = AnimationGraph::new();
let mut clips = HashMap::new();
let mut missing = Vec::new();
for (kind, clip_name) in manifest.0.iter() {
match gltf.named_animations.get(clip_name.as_str()) {
Some(clip_handle) => {
let animation = anim_clips.get(clip_handle);
info!("{clip_name}, {}", animation.unwrap().duration());
let node = graph.add_clip(clip_handle.clone(), 1.0, graph.root);
clips.insert(*kind, node);
}
None => missing.push(clip_name.clone()),
}
}
if !missing.is_empty() {
panic!(
"character '{}': manifest references animations not found in glb: {:?}",
pending.id, missing
);
}
let graph_handle = graphs.add(graph);
spawn_fighter(
&mut commands,
FighterAnimations {
graph: graph_handle,
clips,
},
WorldAssetRoot(gltf.scenes[0].clone()),
);
pending.resolved = true;
}
// All done? Move on.
if queue.0.iter().all(|p| p.resolved) {
next_state.set(AppState::InGame);
commands.remove_resource::<CharacterLoadQueue>();
}
}