aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime
diff options
context:
space:
mode:
Diffstat (limited to 'crates/fparkan-runtime')
-rw-r--r--crates/fparkan-runtime/src/boarding.rs2
-rw-r--r--crates/fparkan-runtime/src/lib.rs144
-rw-r--r--crates/fparkan-runtime/src/manual_flight.rs311
-rw-r--r--crates/fparkan-runtime/src/player_motion.rs163
4 files changed, 403 insertions, 217 deletions
diff --git a/crates/fparkan-runtime/src/boarding.rs b/crates/fparkan-runtime/src/boarding.rs
index 7992aaf7..cb15f420 100644
--- a/crates/fparkan-runtime/src/boarding.rs
+++ b/crates/fparkan-runtime/src/boarding.rs
@@ -16,6 +16,7 @@ pub(super) struct Boarding {
pub(super) hero: StartingCockpit,
pub(super) can_fly: bool,
pub(super) ground: Option<crate::ground_support::GroundSupport>,
+ pub(super) flight_velocity: [f32; 3],
}
/// The vehicle cockpit while the player is aboard.
@@ -138,6 +139,7 @@ pub fn board_friendly_warbot(
hero,
can_fly,
ground,
+ flight_velocity: [0.0; 3],
});
mission.player_pitch_bits = 0;
}
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index a72b5f35..64c908a3 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -92,6 +92,7 @@ mod mesh_collision;
mod mining;
pub use laboratory::LaboratoryReport;
mod manual_chassis;
+mod manual_flight;
mod mission_events;
mod ore_transport;
mod patrol_points;
@@ -3033,6 +3034,7 @@ pub fn frame_with_player_motion(
if let Some(mission) = &mut engine.loaded {
mission.player_pitch_bits = motion.pitch_bits;
frame.player_pitch_bits = motion.pitch_bits;
+ player_motion::commit_flight(mission, cockpit, motion, blocked);
if !blocked
&& !drowned
&& mission.player_gait.footfall
@@ -18333,148 +18335,6 @@ mod tests {
#[test]
#[ignore = "requires licensed corpus"]
- fn licensed_teleport_helicopter_climbs_and_keeps_altitude() {
- let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(licensed_root("IS")));
- let mut engine = create(EngineServices::new(vfs)).unwrap();
- load_gameplay_mission(
- &mut engine,
- MissionRequest {
- key: "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.04/data.tma".into(),
- mode: MissionMode::SingleMission,
- },
- MissionStartupInput {
- queue_time_ms: 0,
- research_creation_gate: false,
- },
- None,
- )
- .unwrap();
- let hero = starting_cockpit(&engine).unwrap();
- let up = PlayerMotion {
- climb: 1.0,
- delta_seconds: 1.0,
- ..PlayerMotion::default()
- };
- assert!(plan_player_motion(&engine, hero, up).unwrap().is_none());
-
- let helicopter = mission_object_handle(&engine, OriginalObjectId(2)).unwrap();
- let position = |engine: &Engine, cockpit: StartingCockpit| {
- transform_state(&engine.world, cockpit.handle)
- .unwrap()
- .position
- .map(f32::from_bits)
- };
- let mut pose = transform_state(&engine.world, hero.handle).unwrap();
- let [hx, hy, _] = pose.position.map(f32::from_bits);
- let [x, y, _] = transform_state(&engine.world, helicopter)
- .unwrap()
- .position
- .map(f32::from_bits);
- let yaw = (y - hy).atan2(x - hx) - std::f32::consts::FRAC_PI_2;
- pose.orientation[2] = yaw.to_bits();
- set_transform(&mut engine.world, hero.handle, pose).unwrap();
- let walk = PlayerMotion {
- movement: [0.0, 1.0],
- delta_seconds: 0.1,
- ..PlayerMotion::default()
- };
- for tick in 1..=45 {
- let step = plan_player_motion(&engine, hero, walk).unwrap().unwrap();
- frame_with_player_motion(&mut engine, tick * 100, hero, step, false).unwrap();
- }
- let table = engine
- .loaded
- .as_mut()
- .unwrap()
- .control_device_tables
- .iter_mut()
- .find(|table| table.handle == helicopter)
- .unwrap();
- let MissionControlDeviceTableStatus::Available(devices) = &mut table.status else {
- panic!("helicopter Control devices unavailable");
- };
- let pilot = devices
- .iter_mut()
- .find(|device| device.descriptor.tag == 1)
- .unwrap();
- let key = pilot.key as usize;
- let MissionControlNodeProviderTableStatus::Available(nodes) =
- &mut table.node_provider_status
- else {
- panic!("helicopter Control nodes unavailable");
- };
- nodes[key].current_type1_value_bits = 0.0_f32.to_bits();
- assert_eq!(
- board_friendly_warbot(&mut engine, Some(helicopter)).unwrap(),
- None
- );
- let table = engine
- .loaded
- .as_mut()
- .unwrap()
- .control_device_tables
- .iter_mut()
- .find(|table| table.handle == helicopter)
- .unwrap();
- let MissionControlNodeProviderTableStatus::Available(nodes) =
- &mut table.node_provider_status
- else {
- panic!("helicopter Control nodes unavailable");
- };
- nodes[key].current_type1_value_bits = 1.0_f32.to_bits();
- assert_eq!(board_friendly_warbot(&mut engine, None).unwrap(), None);
- let [hx, hy, hz] = position(&engine, hero);
- let [tx, ty, tz] = transform_state(&engine.world, helicopter)
- .unwrap()
- .position
- .map(f32::from_bits);
- assert_eq!(
- select_boarding_target(&engine, hero, [[hx, hy, hz + 1.0], [tx, ty, tz + 0.5]]),
- Some(helicopter),
- );
- let vehicle = board_friendly_warbot(&mut engine, Some(helicopter))
- .unwrap()
- .unwrap();
- assert_eq!(vehicle.handle, helicopter);
- let [x, y, z] = position(&engine, vehicle);
- let step = plan_player_motion(&engine, vehicle, up).unwrap().unwrap();
- assert!(step.sweep.is_some());
- assert!(step.floor_probe().is_none());
- frame_with_player_motion(&mut engine, 5_500, vehicle, step, false).unwrap();
- assert_eq!(position(&engine, vehicle), [x, y, z + 16.0]);
- assert_eq!(position(&engine, hero), [x, y, z + 16.0]);
-
- let forward = PlayerMotion {
- climb: 0.0,
- movement: [0.0, 1.0],
- delta_seconds: 0.25,
- ..up
- };
- let step = plan_player_motion(&engine, vehicle, forward)
- .unwrap()
- .unwrap();
- frame_with_player_motion(&mut engine, 5_750, vehicle, step, false).unwrap();
- let [fx, fy, fz] = position(&engine, vehicle);
- assert!(((fx - x).hypot(fy - y) - 10.0).abs() < 0.0001);
- assert_eq!(fz, z + 16.0);
-
- let down = PlayerMotion {
- climb: -1.0,
- delta_seconds: 2.0,
- ..up
- };
- let step = plan_player_motion(&engine, vehicle, down).unwrap().unwrap();
- frame_with_player_motion(&mut engine, 7_750, vehicle, step, false).unwrap();
- let ground = loaded_terrain(&engine)
- .unwrap()
- .height_at([fx, fy])
- .unwrap()
- .unwrap();
- assert_eq!(position(&engine, vehicle), [fx, fy, ground + 0.02]);
- }
-
- #[test]
- #[ignore = "requires licensed corpus"]
fn licensed_teleport_checks_free_capturer_and_counts_captured_mobile_hq() {
let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(licensed_root("IS")));
let mut engine = create(EngineServices::new(vfs)).unwrap();
diff --git a/crates/fparkan-runtime/src/manual_flight.rs b/crates/fparkan-runtime/src/manual_flight.rs
new file mode 100644
index 00000000..db6bee42
--- /dev/null
+++ b/crates/fparkan-runtime/src/manual_flight.rs
@@ -0,0 +1,311 @@
+//! Translational inertia for a boarded aircraft.
+
+use crate::{EngineError, TerrainWorld};
+use fparkan_terrain::SurfaceQuery;
+
+#[derive(Clone, Copy)]
+pub(super) struct FlightProfile {
+ pub(super) acceleration: [f32; 3],
+ pub(super) limits: [f32; 3],
+}
+
+impl FlightProfile {
+ pub(super) fn from_control(words: &[u32; 27]) -> Option<Self> {
+ let acceleration = [0, 1, 2].map(|word| f32::from_bits(words[word]));
+ let limits = [6, 7, 8].map(|word| f32::from_bits(words[word]));
+ acceleration
+ .into_iter()
+ .chain(limits)
+ .all(|rate| rate.is_finite() && rate >= 0.0)
+ .then_some(Self {
+ acceleration,
+ limits,
+ })
+ }
+
+ // shortcut: retain the previous speed limits when the Control profile is unavailable.
+ pub(super) const FALLBACK: Self = Self {
+ acceleration: [40.0, 40.0, 16.0],
+ limits: [40.0, 40.0, 16.0],
+ };
+}
+
+#[derive(Clone, Copy)]
+pub(super) struct FlightDrive {
+ pub(super) profile: FlightProfile,
+ pub(super) velocity: [f32; 3],
+}
+
+impl FlightDrive {
+ pub(super) fn step(
+ self,
+ terrain: &TerrainWorld,
+ from: [f32; 3],
+ yaw: f32,
+ axes: [f32; 3],
+ seconds: f32,
+ ) -> Result<([f32; 3], [f32; 3]), EngineError> {
+ let [(vx, across), (vy, along), (vz, climb)] = std::array::from_fn(|axis| {
+ let target = axes[axis].clamp(-1.0, 1.0) * self.profile.limits[axis];
+ ramp_axis(
+ self.velocity[axis],
+ target,
+ self.profile.acceleration[axis],
+ seconds,
+ )
+ });
+ if [across, along, climb] == [0.0; 3] {
+ return Ok((from, [vx, vy, vz]));
+ }
+ let (sin, cos) = yaw.sin_cos();
+ let old_xy = [from[0], from[1]];
+ let xy = [
+ from[0] + cos * across - sin * along,
+ from[1] + sin * across + cos * along,
+ ];
+ let altitude = from[2] + climb;
+ if !xy.iter().all(|axis| axis.is_finite()) || !altitude.is_finite() {
+ return Err(EngineError::Movement(
+ "player step exceeds finite coordinates".into(),
+ ));
+ }
+ let floor = |xy| terrain.height_at(xy).map_err(EngineError::Terrain);
+ let Some(bottom) = floor(old_xy)?.map(|height| height + 0.02) else {
+ return Ok((from, [0.0; 3]));
+ };
+ // A grounded aircraft can taxi; airborne travel must clear the terrain.
+ let grounded = from[2] <= bottom && climb <= 0.0;
+ let (accepted_xy, height, horizontal) = match floor(xy)?.map(|height| height + 0.02) {
+ Some(floor) if grounded || floor <= altitude.max(from[2]) => (xy, floor, [vx, vy]),
+ _ => (old_xy, bottom, [0.0; 2]),
+ };
+ let [x, y] = accepted_xy;
+ let vz = if altitude <= height { vz.max(0.0) } else { vz };
+ Ok((
+ [x, y, altitude.max(height)],
+ [horizontal[0], horizontal[1], vz],
+ ))
+ }
+}
+
+fn ramp_axis(velocity: f32, target: f32, acceleration: f32, seconds: f32) -> (f32, f32) {
+ if acceleration == 0.0 || velocity == target {
+ return (velocity, velocity * seconds);
+ }
+ let difference = target - velocity;
+ let arrival_time = difference.abs() / acceleration;
+ let ramp_time = seconds.min(arrival_time);
+ let next = if seconds >= arrival_time {
+ target
+ } else {
+ velocity + acceleration.copysign(difference) * ramp_time
+ };
+ let distance = (velocity + next) * 0.5 * ramp_time + next * (seconds - ramp_time);
+ (next, distance)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::ramp_axis;
+
+ #[test]
+ fn control_ramp_matches_stock_helicopter_velocity_through_release_and_reversal() {
+ // Control.dll RVA 0x153c0, R_T_02 active profile.
+ let limit = f32::from_bits(1096943108);
+ let mut velocity = 0.0;
+ for (target, seconds, expected) in [
+ (limit, 0.25, 10.0),
+ (limit, 1.0, limit),
+ (0.0, 0.25, limit - 10.0),
+ (-limit, 0.25, limit - 20.0),
+ (0.0, 2.0, 0.0),
+ ] {
+ (velocity, _) = ramp_axis(velocity, target, 40.0, seconds);
+ assert!((velocity - expected).abs() < 0.000_001);
+ }
+ }
+
+ #[test]
+ fn coasting_ends_at_the_same_point_across_frame_boundaries() {
+ assert_eq!(ramp_axis(15.0, 0.0, 30.0, 1.0), (0.0, 3.75));
+ let (next, first) = ramp_axis(15.0, 0.0, 30.0, 0.25);
+ let (rest, second) = ramp_axis(next, 0.0, 30.0, 0.75);
+ assert_eq!(rest, 0.0);
+ assert_eq!(first + second, 3.75);
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
+ fn licensed_teleport_helicopter_climbs_and_keeps_altitude() {
+ use crate::{
+ board_friendly_warbot, create, frame_with_player_motion, load_gameplay_mission,
+ loaded_terrain, mission_object_handle, plan_player_motion, select_boarding_target,
+ starting_cockpit, Engine, EngineServices, MissionControlDeviceTableStatus,
+ MissionControlNodeProviderTableStatus, MissionMode, MissionRequest,
+ MissionStartupInput, PlayerMotion, StartingCockpit,
+ };
+ use fparkan_terrain::SurfaceQuery;
+ use fparkan_vfs::DirectoryVfs;
+ use fparkan_world::{set_transform, transform_state, OriginalObjectId};
+ use std::sync::Arc;
+
+ let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root");
+ let vfs = Arc::new(DirectoryVfs::new(std::path::PathBuf::from(root)));
+ let mut engine = create(EngineServices::new(vfs)).unwrap();
+ load_gameplay_mission(
+ &mut engine,
+ MissionRequest {
+ key: "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.04/data.tma".into(),
+ mode: MissionMode::SingleMission,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ None,
+ )
+ .unwrap();
+ let hero = starting_cockpit(&engine).unwrap();
+ let up = PlayerMotion {
+ climb: 1.0,
+ delta_seconds: 1.0,
+ ..PlayerMotion::default()
+ };
+ assert!(plan_player_motion(&engine, hero, up).unwrap().is_none());
+
+ let helicopter = mission_object_handle(&engine, OriginalObjectId(2)).unwrap();
+ let position = |engine: &Engine, cockpit: StartingCockpit| {
+ transform_state(&engine.world, cockpit.handle)
+ .unwrap()
+ .position
+ .map(f32::from_bits)
+ };
+ let mut pose = transform_state(&engine.world, hero.handle).unwrap();
+ let [hx, hy, _] = pose.position.map(f32::from_bits);
+ let [x, y, _] = transform_state(&engine.world, helicopter)
+ .unwrap()
+ .position
+ .map(f32::from_bits);
+ let yaw = (y - hy).atan2(x - hx) - std::f32::consts::FRAC_PI_2;
+ pose.orientation[2] = yaw.to_bits();
+ set_transform(&mut engine.world, hero.handle, pose).unwrap();
+ let walk = PlayerMotion {
+ movement: [0.0, 1.0],
+ delta_seconds: 0.1,
+ ..PlayerMotion::default()
+ };
+ for tick in 1..=26 {
+ let step = plan_player_motion(&engine, hero, walk).unwrap().unwrap();
+ frame_with_player_motion(&mut engine, tick * 100, hero, step, false).unwrap();
+ }
+ let table = engine
+ .loaded
+ .as_mut()
+ .unwrap()
+ .control_device_tables
+ .iter_mut()
+ .find(|table| table.handle == helicopter)
+ .unwrap();
+ let MissionControlDeviceTableStatus::Available(devices) = &mut table.status else {
+ panic!("helicopter Control devices unavailable");
+ };
+ let pilot = devices
+ .iter_mut()
+ .find(|device| device.descriptor.tag == 1)
+ .unwrap();
+ let key = pilot.key as usize;
+ let MissionControlNodeProviderTableStatus::Available(nodes) =
+ &mut table.node_provider_status
+ else {
+ panic!("helicopter Control nodes unavailable");
+ };
+ nodes[key].current_type1_value_bits = 0.0_f32.to_bits();
+ assert_eq!(
+ board_friendly_warbot(&mut engine, Some(helicopter)).unwrap(),
+ None
+ );
+ let table = engine
+ .loaded
+ .as_mut()
+ .unwrap()
+ .control_device_tables
+ .iter_mut()
+ .find(|table| table.handle == helicopter)
+ .unwrap();
+ let MissionControlNodeProviderTableStatus::Available(nodes) =
+ &mut table.node_provider_status
+ else {
+ panic!("helicopter Control nodes unavailable");
+ };
+ nodes[key].current_type1_value_bits = 1.0_f32.to_bits();
+ assert_eq!(board_friendly_warbot(&mut engine, None).unwrap(), None);
+ let [hx, hy, hz] = position(&engine, hero);
+ let [tx, ty, tz] = transform_state(&engine.world, helicopter)
+ .unwrap()
+ .position
+ .map(f32::from_bits);
+ assert_eq!(
+ select_boarding_target(&engine, hero, [[hx, hy, hz + 1.0], [tx, ty, tz + 0.5]]),
+ Some(helicopter),
+ );
+ let vehicle = board_friendly_warbot(&mut engine, Some(helicopter))
+ .unwrap()
+ .unwrap();
+ assert_eq!(vehicle.handle, helicopter);
+ let [x, y, z] = position(&engine, vehicle);
+ let step = plan_player_motion(&engine, vehicle, up).unwrap().unwrap();
+ assert!(step.sweep.is_some());
+ assert!(step.floor_probe().is_none());
+ frame_with_player_motion(&mut engine, 5_500, vehicle, step, false).unwrap();
+ let [_, _, climb_z] = position(&engine, vehicle);
+ assert!((8.0..16.0).contains(&(climb_z - z)));
+ assert_eq!(position(&engine, hero), [x, y, climb_z]);
+
+ let coast = PlayerMotion {
+ delta_seconds: 1.0,
+ ..Default::default()
+ };
+ let step = plan_player_motion(&engine, vehicle, coast)
+ .unwrap()
+ .unwrap();
+ frame_with_player_motion(&mut engine, 6_500, vehicle, step, false).unwrap();
+ let [_, _, hover_z] = position(&engine, vehicle);
+ assert!(hover_z > climb_z);
+ assert!(plan_player_motion(&engine, vehicle, coast)
+ .unwrap()
+ .is_none());
+
+ let forward = PlayerMotion {
+ climb: 0.0,
+ movement: [0.0, 1.0],
+ delta_seconds: 0.25,
+ ..up
+ };
+ let step = plan_player_motion(&engine, vehicle, forward)
+ .unwrap()
+ .unwrap();
+ frame_with_player_motion(&mut engine, 6_750, vehicle, step, false).unwrap();
+ let [fx, fy, fz] = position(&engine, vehicle);
+ assert!(((fx - x).hypot(fy - y) - 1.25).abs() < 0.0001);
+ assert_eq!(fz, hover_z);
+
+ let down = PlayerMotion {
+ climb: -1.0,
+ delta_seconds: 2.0,
+ ..up
+ };
+ let step = plan_player_motion(&engine, vehicle, down).unwrap().unwrap();
+ frame_with_player_motion(&mut engine, 8_750, vehicle, step, false).unwrap();
+ let [lx, ly, lz] = position(&engine, vehicle);
+ assert!(((lx - fx).hypot(ly - fy) - 1.25).abs() < 0.0001);
+ let ground = loaded_terrain(&engine)
+ .unwrap()
+ .height_at([lx, ly])
+ .unwrap()
+ .unwrap();
+ assert_eq!(lz, ground + 0.02);
+ assert!(plan_player_motion(&engine, vehicle, coast)
+ .unwrap()
+ .is_none());
+ }
+}
diff --git a/crates/fparkan-runtime/src/player_motion.rs b/crates/fparkan-runtime/src/player_motion.rs
index d6ba8ade..5a999546 100644
--- a/crates/fparkan-runtime/src/player_motion.rs
+++ b/crates/fparkan-runtime/src/player_motion.rs
@@ -1,4 +1,5 @@
use super::{transform_state, Engine, EngineError, StartingCockpit, SurfaceQuery, TransformState};
+use crate::manual_flight::{FlightDrive, FlightProfile};
use crate::TerrainWorld;
use fparkan_resource::CachedResourceRepository;
use fparkan_terrain::FullSurfaceMask;
@@ -30,7 +31,6 @@ const WATER_SURFACE: u32 = 0x0002_0000;
// shortcut: sample the temporary floor probe at most 0.16 units apart until native collision is wired.
const WALK_COLLISION_DISTANCE: f32 = 0.16;
const WALK_SPEED_FALLBACK: f32 = 8.0;
-const FLIGHT_SPEED_FALLBACK: f32 = 40.0;
/// Player controls sampled once for a simulation step.
#[derive(Clone, Copy, Debug, Default)]
@@ -52,7 +52,7 @@ pub struct PlayerMotion {
pub struct PlayerMotionStep {
pub(super) pose: TransformState,
pub(super) pitch_bits: u32,
- flying: bool,
+ flight_velocity: Option<[f32; 3]>,
max_floor_clearance: f32,
previous_terrain_height: Option<f32>,
terrain_height: Option<f32>,
@@ -103,7 +103,7 @@ impl PlayerMotionStep {
/// Vertical segment for finding a nearby building floor at the proposed XY.
#[must_use]
pub fn floor_probe(self) -> Option<[[f32; 3]; 2]> {
- if self.flying {
+ if self.flight_velocity.is_some() {
return None;
}
let [[_, _, start_z], [x, y, _]] = self.sweep?;
@@ -198,7 +198,7 @@ mod tests {
..TransformState::default()
},
pitch_bits: 0,
- flying: false,
+ flight_velocity: None,
max_floor_clearance: FLOOR_CLEARANCE,
previous_terrain_height: None,
terrain_height: Some(11.5),
@@ -233,7 +233,7 @@ mod tests {
let step = PlayerMotionStep {
pose: TransformState::default(),
pitch_bits: 0,
- flying: false,
+ flight_velocity: None,
max_floor_clearance: 1.25,
previous_terrain_height: Some(10.0),
terrain_height: Some(10.0),
@@ -255,7 +255,7 @@ mod tests {
let step = PlayerMotionStep {
pose: TransformState::default(),
pitch_bits: 0,
- flying: false,
+ flight_velocity: None,
max_floor_clearance: FLOOR_CLEARANCE,
previous_terrain_height: None,
terrain_height: None,
@@ -387,10 +387,23 @@ fn plan_player_steps(
let boarded = mission
.boarding
.filter(|boarding| boarding.cockpit.handle == cockpit.handle);
- let flying = boarded.is_some_and(|boarding| boarding.can_fly);
+ let flight = boarded.filter(|boarding| boarding.can_fly).map(|boarding| {
+ let profile = mission
+ .control_device_tables
+ .iter()
+ .find(|table| table.handle == cockpit.handle)
+ .and_then(|table| table.owner_profile.as_ref())
+ .and_then(|profile| FlightProfile::from_control(&profile.current_words))
+ .unwrap_or(FlightProfile::FALLBACK);
+ FlightDrive {
+ profile,
+ velocity: boarding.flight_velocity,
+ }
+ });
+ let flying = flight.is_some();
let chassis_ground = boarded.and_then(|boarding| boarding.ground);
if input.movement == [0.0; 2]
- && (!flying || input.climb == 0.0)
+ && flight.is_none_or(|drive| input.climb == 0.0 && drive.velocity == [0.0; 3])
&& input.mouse_x == 0.0
&& input.mouse_y == 0.0
{
@@ -400,9 +413,7 @@ fn plan_player_steps(
if !input.delta_seconds.is_finite() || input.delta_seconds < 0.0 {
return Err(EngineError::Movement("invalid player step".into()));
}
- let speeds = if flying {
- [FLIGHT_SPEED_FALLBACK; 2]
- } else if boarded.is_some() {
+ let speeds = if boarded.is_some() && !flying {
crate::manual_chassis::speed_limits(mission, cockpit.handle)
.unwrap_or([WALK_SPEED_FALLBACK; 2])
} else if mission.local_hero == Some(cockpit.handle) {
@@ -433,7 +444,7 @@ fn plan_player_steps(
}
}
let Some(resolve) = resolve else {
- let mut step = plan_motion(&mission.terrain, pose, pitch, flying, speeds, input)?;
+ let mut step = plan_motion(&mission.terrain, pose, pitch, flight, speeds, input)?;
step.max_floor_clearance = max_floor_clearance;
crate::manual_chassis::support_step(chassis_ground, &mission.terrain, pose, &mut step)?;
return Ok(Some(step));
@@ -448,7 +459,7 @@ fn plan_player_steps(
}
.max(1);
input.delta_seconds /= count as f32;
- let mut step = plan_motion(&mission.terrain, pose, pitch, flying, speeds, input)?;
+ let mut step = plan_motion(&mission.terrain, pose, pitch, flight, speeds, input)?;
let mut previous = pose;
let mut previous_surface = WalkingSurface::Ground;
input.mouse_x = 0.0;
@@ -459,7 +470,7 @@ fn plan_player_steps(
&mission.terrain,
previous,
f32::from_bits(step.pitch_bits),
- flying,
+ flight,
speeds,
input,
)?;
@@ -471,6 +482,7 @@ fn plan_player_steps(
step.pose.position = previous.position;
step.sweep = None;
step.surface = previous_surface;
+ step.flight_velocity = step.flight_velocity.map(|_| [0.0; 3]);
break;
}
crate::manual_chassis::support_step(chassis_ground, &mission.terrain, previous, &mut step)?;
@@ -483,6 +495,19 @@ fn plan_player_steps(
Ok(Some(step))
}
+pub(super) fn commit_flight(
+ mission: &mut crate::LoadedMissionState,
+ cockpit: StartingCockpit,
+ step: PlayerMotionStep,
+ blocked: bool,
+) {
+ if let (Some(boarding), Some(velocity)) = (&mut mission.boarding, step.flight_velocity) {
+ if boarding.cockpit.handle == cockpit.handle {
+ boarding.flight_velocity = if blocked { [0.0; 3] } else { velocity };
+ }
+ }
+}
+
fn body_velocity(movement: [f32; 2], [side_speed, forward_speed]: [f32; 2]) -> [f32; 2] {
let [right, forward] = movement.map(|axis| axis.clamp(-1.0, 1.0));
let length = right.hypot(forward).max(1.0);
@@ -496,7 +521,7 @@ fn plan_motion(
terrain: &TerrainWorld,
mut pose: TransformState,
pitch: f32,
- flying: bool,
+ flight: Option<FlightDrive>,
speeds: [f32; 2],
input: PlayerMotion,
) -> Result<PlayerMotionStep, EngineError> {
@@ -528,76 +553,64 @@ fn plan_motion(
} else {
yaw
};
- // shortcut: apply the requested velocity immediately until native acceleration is known.
- let [across, along] =
- body_velocity(input.movement, speeds).map(|speed| speed * input.delta_seconds);
- let (sin, cos) = yaw.sin_cos();
- let xy = [
- from[0] + cos * across - sin * along,
- from[1] + sin * across + cos * along,
- ];
- let climb = if flying {
- input.climb.clamp(-1.0, 1.0) * (16.0 * input.delta_seconds)
- } else {
- 0.0
- };
- let altitude = from[2] + climb;
- if !xy.iter().all(|axis| axis.is_finite()) || !altitude.is_finite() {
- return Err(EngineError::Movement(
- "player step exceeds finite coordinates".into(),
- ));
- }
let mut sweep = None;
+ let mut flight_velocity = None;
let mut previous_terrain_height = None;
let mut terrain_height = None;
let mut surface = WalkingSurface::Ground;
- if flying && (xy != [from[0], from[1]] || climb != 0.0) {
- let old_xy = [from[0], from[1]];
- let floor = |xy| {
- terrain
- .height_at(xy)
- .map_err(|err| EngineError::Movement(err.to_string()))
- };
- if let Some(old_height) = floor(old_xy)? {
- let bottom = old_height + 0.02;
- // A grounded machine can taxi. In the air, climb above an obstacle before crossing it.
- let grounded = from[2] <= bottom && climb <= 0.0;
- let floor_at_target = floor(xy)?.map(|height| height + 0.02);
- let (accepted_xy, height) = match floor_at_target {
- Some(floor) if grounded || floor <= altitude => (xy, floor),
- _ => (old_xy, bottom),
- };
- let [x, y] = accepted_xy;
- let to = [x, y, altitude.max(height)];
- if to != from {
+ if let Some(flight) = flight {
+ let [across, along] = input.movement;
+ let (to, velocity) = flight.step(
+ terrain,
+ from,
+ yaw,
+ [across, along, input.climb],
+ input.delta_seconds,
+ )?;
+ flight_velocity = Some(velocity);
+ if to != from {
+ pose.position = to.map(f32::to_bits);
+ sweep = Some([
+ [from[0], from[1], from[2] + 0.5],
+ [to[0], to[1], to[2] + 0.5],
+ ]);
+ }
+ } else {
+ // shortcut: apply the requested ground velocity immediately.
+ let [across, along] =
+ body_velocity(input.movement, speeds).map(|speed| speed * input.delta_seconds);
+ let (sin, cos) = yaw.sin_cos();
+ let xy = [
+ from[0] + cos * across - sin * along,
+ from[1] + sin * across + cos * along,
+ ];
+ if !xy.iter().all(|axis| axis.is_finite()) {
+ return Err(EngineError::Movement(
+ "player step exceeds finite coordinates".into(),
+ ));
+ }
+ if xy != [from[0], from[1]] {
+ if let (Some(old_ground), Some((new_ground, mask))) = (
+ terrain
+ .height_at([from[0], from[1]])
+ .map_err(|err| EngineError::Movement(err.to_string()))?,
+ terrain
+ .support_at(xy)
+ .map_err(|err| EngineError::Movement(err.to_string()))?,
+ ) {
+ let to = [xy[0], xy[1], new_ground + (from[2] - old_ground)];
+ previous_terrain_height = Some(old_ground);
+ terrain_height = Some(new_ground);
+ surface = WalkingSurface::terrain(mask);
pose.position = to.map(f32::to_bits);
+ // shortcut: one sweep at body height until the physical collider
+ // and floor transitions are recovered.
sweep = Some([
[from[0], from[1], from[2] + 0.5],
[to[0], to[1], to[2] + 0.5],
]);
}
}
- } else if xy != [from[0], from[1]] {
- if let (Some(old_ground), Some((new_ground, mask))) = (
- terrain
- .height_at([from[0], from[1]])
- .map_err(|err| EngineError::Movement(err.to_string()))?,
- terrain
- .support_at(xy)
- .map_err(|err| EngineError::Movement(err.to_string()))?,
- ) {
- let to = [xy[0], xy[1], new_ground + (from[2] - old_ground)];
- previous_terrain_height = Some(old_ground);
- terrain_height = Some(new_ground);
- surface = WalkingSurface::terrain(mask);
- pose.position = to.map(f32::to_bits);
- // shortcut: one sweep at body height until the physical collider
- // and floor transitions are recovered.
- sweep = Some([
- [from[0], from[1], from[2] + 0.5],
- [to[0], to[1], to[2] + 0.5],
- ]);
- }
}
// shortcut: use a bounded camera aim until the native turret travel and
// sensitivity are recovered. The body remains aligned to the terrain.
@@ -605,7 +618,7 @@ fn plan_motion(
Ok(PlayerMotionStep {
pose,
pitch_bits: pitch.to_bits(),
- flying,
+ flight_velocity,
max_floor_clearance: FLOOR_CLEARANCE,
previous_terrain_height,
terrain_height,