aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime
diff options
context:
space:
mode:
Diffstat (limited to 'crates/fparkan-runtime')
-rw-r--r--crates/fparkan-runtime/src/lib.rs91
-rw-r--r--crates/fparkan-runtime/src/player_motion.rs100
2 files changed, 191 insertions, 0 deletions
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 5441d72d..32a4d8d1 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -44,12 +44,14 @@ use std::sync::Arc;
mod autodemo;
mod mesh_collision;
mod mission_events;
+mod player_motion;
pub use autodemo::{autodemo_camera, AutoDemoCamera, AutoDemoView};
pub use fparkan_assets::MissionAssets;
pub use mesh_collision::{query_building_segment_world, BuildingMeshHit, BuildingMeshNode};
use mission_events::MissionEvents;
pub use mission_events::{MissionEventStop, MissionEventTick, MissionNotice};
+pub use player_motion::{plan_player_motion, PlayerMotion, PlayerMotionStep};
const MISSION_DECODED_PAYLOAD_CACHE_ENTRIES: usize = 256;
const MAX_MISSION_AI_RECORD_SLOTS: usize = 1_000_000;
@@ -2293,6 +2295,32 @@ pub fn frame(engine: &mut Engine, queue_time_ms: u32) -> Result<FrameResult, Eng
step_headless(engine, InputSnapshot, queue_time_ms)
}
+/// Applies a proposed hero step and publishes the resulting world snapshot.
+/// A blocked sweep keeps the previous position and still applies the turn.
+///
+/// # Errors
+///
+/// Returns an error for a stale hero handle or a failed world step.
+pub fn frame_with_player_motion(
+ engine: &mut Engine,
+ queue_time_ms: u32,
+ cockpit: StartingCockpit,
+ motion: PlayerMotionStep,
+ blocked: bool,
+) -> Result<FrameResult, EngineError> {
+ let previous = transform_state(&engine.world, cockpit.handle)?;
+ let mut pose = motion.pose;
+ if blocked {
+ pose.position = previous.position;
+ }
+ set_transform(&mut engine.world, cockpit.handle, pose)?;
+ let result = frame(engine, queue_time_ms);
+ if result.is_err() {
+ set_transform(&mut engine.world, cockpit.handle, previous)?;
+ }
+ result
+}
+
/// Coverage entries for the subsystems still absent from the mission loop.
pub const SIMULATION_COVERAGE: &str =
"sim_coverage research_startup_gate_stub=1 mission_handlers_stub=1 unit_behavior_stub=1 render_object_lifecycle_stub=1 render_winding_change_stub=1 mission_event_clock_approx=1 mission_tactical_ids_stub=1 mission_clan_roster_stub=1 mission_message_ui_stub=1";
@@ -17085,6 +17113,69 @@ mod tests {
#[test]
#[ignore = "requires licensed corpus"]
+ fn licensed_player_walk_and_blocked_turn_update_the_world_snapshot() {
+ let vfs = Arc::new(DirectoryVfs::new(licensed_root("IS")));
+ let mut engine = create(EngineServices::new(vfs)).unwrap();
+ load_mission_with_init_stubs(
+ &mut engine,
+ MissionRequest {
+ key: "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma".into(),
+ mode: MissionMode::SingleMission,
+ },
+ MissionStartupInput {
+ queue_time_ms: 0,
+ research_creation_gate: false,
+ },
+ )
+ .unwrap();
+ let cockpit = starting_cockpit(&engine).unwrap();
+ let original = transform_state(&engine.world, cockpit.handle).unwrap();
+ let input = PlayerMotion {
+ movement: [0.0, 1.0],
+ mouse_x: 100.0,
+ delta_seconds: 0.1,
+ };
+ let proposed = plan_player_motion(&engine, cockpit, input)
+ .unwrap()
+ .unwrap();
+ assert!(proposed.sweep.is_some());
+ let blocked = frame_with_player_motion(&mut engine, 100, cockpit, proposed, true).unwrap();
+ let pose = |frame: &FrameResult| {
+ frame
+ .snapshot
+ .transforms
+ .iter()
+ .find(|(handle, _)| *handle == cockpit.handle)
+ .unwrap()
+ .1
+ };
+ let turned = pose(&blocked);
+ assert_eq!(turned.position, original.position);
+ assert_ne!(turned.orientation[2], original.orientation[2]);
+ let movement = PlayerMotion {
+ mouse_x: 0.0,
+ ..input
+ };
+ let proposed = plan_player_motion(&engine, cockpit, movement)
+ .unwrap()
+ .unwrap();
+ let walked =
+ pose(&frame_with_player_motion(&mut engine, 200, cockpit, proposed, false).unwrap());
+ let [x0, y0, z0] = original.position.map(f32::from_bits);
+ let [x1, y1, z1] = walked.position.map(f32::from_bits);
+ assert!(((x1 - x0).hypot(y1 - y0) - 0.8).abs() < 1e-4);
+ let ground = |xy| {
+ loaded_terrain(&engine)
+ .unwrap()
+ .height_at(xy)
+ .unwrap()
+ .unwrap()
+ };
+ assert!(((z1 - ground([x1, y1])) - (z0 - ground([x0, y0]))).abs() < 1e-5);
+ }
+
+ #[test]
+ #[ignore = "requires licensed corpus"]
fn licensed_firing_range_reports_target_loss_and_completes_all_objectives() {
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/player_motion.rs b/crates/fparkan-runtime/src/player_motion.rs
new file mode 100644
index 00000000..291b0451
--- /dev/null
+++ b/crates/fparkan-runtime/src/player_motion.rs
@@ -0,0 +1,100 @@
+use super::{transform_state, Engine, EngineError, StartingCockpit, SurfaceQuery, TransformState};
+use crate::TerrainWorld;
+
+/// Player controls sampled once for a simulation step.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct PlayerMotion {
+ /// Signed strafe and forward input in the range -1 to 1.
+ pub movement: [f32; 2],
+ /// Relative horizontal mouse motion for this step.
+ pub mouse_x: f32,
+ /// Time spent on this simulation step, excluding time spent paused.
+ pub delta_seconds: f32,
+}
+
+/// Proposed hero transform and the body-level sweep used to check buildings.
+#[derive(Clone, Copy, Debug)]
+pub struct PlayerMotionStep {
+ pub(super) pose: TransformState,
+ /// Sweep segment when the step translates the hero.
+ pub sweep: Option<[[f32; 3]; 2]>,
+}
+
+/// Proposes a hero step from the world pose and the active terrain.
+///
+/// # Errors
+///
+/// Returns an error for invalid motion values or a failed terrain query.
+pub fn plan_player_motion(
+ engine: &Engine,
+ cockpit: StartingCockpit,
+ input: PlayerMotion,
+) -> Result<Option<PlayerMotionStep>, EngineError> {
+ if input.movement == [0.0; 2] && input.mouse_x == 0.0 {
+ return Ok(None);
+ }
+ let (Some(mission), Ok(pose)) = (
+ &engine.loaded,
+ transform_state(&engine.world, cockpit.handle),
+ ) else {
+ return Ok(None);
+ };
+ plan_motion(&mission.terrain, pose, input).map(Some)
+}
+
+fn plan_motion(
+ terrain: &TerrainWorld,
+ mut pose: TransformState,
+ input: PlayerMotion,
+) -> Result<PlayerMotionStep, EngineError> {
+ let from = pose.position.map(f32::from_bits);
+ let yaw = f32::from_bits(pose.orientation[2]);
+ if !input
+ .movement
+ .into_iter()
+ .chain([input.mouse_x, input.delta_seconds, yaw])
+ .chain(from)
+ .all(f32::is_finite)
+ || input.delta_seconds < 0.0
+ {
+ return Err(EngineError::Movement("invalid player step".into()));
+ }
+ // shortcut: use constant walk speed and mouse gain until native Control
+ // acceleration and mouse sensitivity are measured.
+ let yaw = if input.mouse_x != 0.0 {
+ let yaw = (yaw - input.mouse_x.clamp(-1_000.0, 1_000.0) * 0.003)
+ .rem_euclid(std::f32::consts::TAU);
+ pose.orientation[2] = yaw.to_bits();
+ yaw
+ } else {
+ yaw
+ };
+ let [right, forward] = input.movement.map(|axis| axis.clamp(-1.0, 1.0));
+ let distance = 8.0 * input.delta_seconds.min(0.1) / right.hypot(forward).max(1.0);
+ let (sin, cos) = yaw.sin_cos();
+ let xy = [
+ from[0] + (cos * right - sin * forward) * distance,
+ from[1] + (sin * right + cos * forward) * distance,
+ ];
+ let mut sweep = None;
+ if xy != [from[0], from[1]] {
+ if let (Some(old_ground), Some(new_ground)) = (
+ terrain
+ .height_at([from[0], from[1]])
+ .map_err(|err| EngineError::Movement(err.to_string()))?,
+ terrain
+ .height_at(xy)
+ .map_err(|err| EngineError::Movement(err.to_string()))?,
+ ) {
+ let to = [xy[0], xy[1], new_ground + (from[2] - old_ground)];
+ 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],
+ ]);
+ }
+ }
+ Ok(PlayerMotionStep { pose, sweep })
+}