From 4a20345f7e8ef833c341c0397764e28a18231389 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Sat, 14 Nov 2026 14:34:44 +0400 Subject: feat(runtime): let the player fly warbots --- README.md | 1 + apps/fparkan-game/src/main.rs | 60 +++++++++---------- crates/fparkan-runtime/src/lib.rs | 91 +++++++++++++++++++++++++++++ crates/fparkan-runtime/src/player_motion.rs | 85 +++++++++++++++++++++++++-- docs/appendices/knowledge-boundaries.md | 5 +- docs/tomes/06-behavior.md | 17 +++++- 6 files changed, 219 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index f256d9e2..f9c2a04e 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ Enter захватывает ближайшего нейтрального ва управления в пределах 12 единиц. У союзного варбота с кабиной Enter пересаживает игрока в него. Стрелки ведут варбота, цифры выбирают его орудия, левая кнопка ведёт огонь. +В летающем варботе PgUp поднимает машину, PgDn опускает её. Esc возвращает управление костюмом с прежним боезапасом. Внутри нейтрального строения встаньте на зелёную площадку коммуникатора и нажмите Enter, чтобы передать строение своему клану. diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index cba38f81..27be3e8a 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -9997,25 +9997,31 @@ fn mission_camera_coverage(cockpit: Option, demo: bool) -> &'st if demo { "autodemo_camera_follow_approx=1 autodemo_camera_target_approx=1 cockpit_pose_approx=1" } else if cockpit.is_some() { - "player_motion_approx=1 cockpit_aim_approx=1 cockpit_pose_approx=1 player_weapon_cycle_approx=1 player_projectile_flight_approx=1 player_projectile_damage_approx=1 player_projectile_hull_stub=1 player_weapon_fx_stub=1 player_capture_approx=1 player_communicator_approx=1 player_building_floor_approx=1 player_boarding_approx=1" + "player_motion_approx=1 cockpit_aim_approx=1 cockpit_pose_approx=1 player_weapon_cycle_approx=1 player_projectile_flight_approx=1 player_projectile_damage_approx=1 player_projectile_hull_stub=1 player_weapon_fx_stub=1 player_capture_approx=1 player_communicator_approx=1 player_building_floor_approx=1 player_boarding_approx=1 player_vehicle_flight_approx=1" } else { "mission_camera_stub=1" } } -fn player_arrow(physical: PhysicalKey, logical: &Key) -> Option { +const PLAYER_MOVEMENT_KEYS: [KeyCode; 6] = [ + KeyCode::ArrowRight, + KeyCode::ArrowLeft, + KeyCode::ArrowUp, + KeyCode::ArrowDown, + KeyCode::PageUp, + KeyCode::PageDown, +]; + +fn player_movement_key(physical: PhysicalKey, logical: &Key) -> Option { match logical { Key::Named(NamedKey::ArrowRight) => Some(KeyCode::ArrowRight), Key::Named(NamedKey::ArrowLeft) => Some(KeyCode::ArrowLeft), Key::Named(NamedKey::ArrowUp) => Some(KeyCode::ArrowUp), Key::Named(NamedKey::ArrowDown) => Some(KeyCode::ArrowDown), + Key::Named(NamedKey::PageUp) => Some(KeyCode::PageUp), + Key::Named(NamedKey::PageDown) => Some(KeyCode::PageDown), _ => match physical { - PhysicalKey::Code( - code @ (KeyCode::ArrowRight - | KeyCode::ArrowLeft - | KeyCode::ArrowUp - | KeyCode::ArrowDown), - ) => Some(code), + PhysicalKey::Code(code) if PLAYER_MOVEMENT_KEYS.contains(&code) => Some(code), _ => None, }, } @@ -10079,7 +10085,7 @@ struct StaticVulkanApp { pending_scene_update: Option, environment_primitive_count: usize, pressed_keys: HashSet, - player_move_pressed: [bool; 4], + player_move_pressed: [bool; PLAYER_MOVEMENT_KEYS.len()], mouse_look: bool, player_mouse: [f32; 2], player_weapon_layouts: HashMap, @@ -10213,7 +10219,7 @@ impl StaticVulkanApp { pending_scene_update: None, environment_primitive_count: 0, pressed_keys: HashSet::new(), - player_move_pressed: [false; 4], + player_move_pressed: Default::default(), mouse_look: false, player_mouse: [0.0; 2], player_weapon_layouts: HashMap::new(), @@ -10913,7 +10919,7 @@ impl StaticVulkanApp { fn set_mission_paused_at(&mut self, paused: bool, now: Instant) { self.mission_paused = paused; self.player_mouse = [0.0; 2]; - self.player_move_pressed = [false; 4]; + self.player_move_pressed = Default::default(); self.player_capture_pressed = false; self.player_build_pressed = false; self.player_mine_pressed = false; @@ -11076,21 +11082,17 @@ impl StaticVulkanApp { (&self.mission_engine, self.cockpit, &self.demo_camera) { let pressed = std::mem::take(&mut self.player_move_pressed); - let [right, left, forward, back] = [ - KeyCode::ArrowRight, - KeyCode::ArrowLeft, - KeyCode::ArrowUp, - KeyCode::ArrowDown, - ] - .map(|key| self.pressed_keys.contains(&key)); + let [right, left, forward, back, climb, descend] = std::array::from_fn(|index| { + f32::from( + pressed[index] || self.pressed_keys.contains(&PLAYER_MOVEMENT_KEYS[index]), + ) + }); if let Some(mut step) = plan_player_motion( engine, cockpit, PlayerMotion { - movement: [ - f32::from(right || pressed[0]) - f32::from(left || pressed[1]), - f32::from(forward || pressed[2]) - f32::from(back || pressed[3]), - ], + movement: [right - left, forward - back], + climb: climb - descend, mouse_x, mouse_y, delta_seconds: clock.delta_seconds, @@ -12350,7 +12352,7 @@ impl ApplicationHandler for StaticVulkanApp { self.window_focused = focused; if !focused { self.pressed_keys.clear(); - self.player_move_pressed = [false; 4]; + self.player_move_pressed = Default::default(); self.player_capture_pressed = false; self.player_build_pressed = false; self.player_mine_pressed = false; @@ -12383,7 +12385,7 @@ impl ApplicationHandler for StaticVulkanApp { return; } let key = if self.cockpit.is_some() && self.demo_camera.is_none() { - player_arrow(event.physical_key, &event.logical_key) + player_movement_key(event.physical_key, &event.logical_key) .map_or(event.physical_key, PhysicalKey::Code) } else { event.physical_key @@ -12433,14 +12435,8 @@ impl ApplicationHandler for StaticVulkanApp { weapons.select(slot); } } - if let Some(index) = [ - KeyCode::ArrowRight, - KeyCode::ArrowLeft, - KeyCode::ArrowUp, - KeyCode::ArrowDown, - ] - .iter() - .position(|&key| key == code) + if let Some(index) = + PLAYER_MOVEMENT_KEYS.iter().position(|&key| key == code) { self.player_move_pressed[index] = true; } diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index a3114a53..c3b014c7 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -17744,6 +17744,7 @@ mod tests { let original = transform_state(&engine.world, cockpit.handle).unwrap(); let input = PlayerMotion { movement: [0.0, 1.0], + climb: 0.0, mouse_x: 100.0, mouse_y: -500.0, delta_seconds: 0.1, @@ -17988,6 +17989,96 @@ mod tests { } } + #[test] + #[ignore = "requires licensed corpus"] + fn licensed_teleport_helicopter_climbs_and_keeps_altitude() { + let vfs: Arc = 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 vehicle = board_friendly_warbot(&mut engine).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() { diff --git a/crates/fparkan-runtime/src/player_motion.rs b/crates/fparkan-runtime/src/player_motion.rs index 6d9e53d8..6cccc01e 100644 --- a/crates/fparkan-runtime/src/player_motion.rs +++ b/crates/fparkan-runtime/src/player_motion.rs @@ -6,6 +6,8 @@ use crate::TerrainWorld; pub struct PlayerMotion { /// Signed strafe and forward input in the range -1 to 1. pub movement: [f32; 2], + /// Signed climb input for a flying vehicle, in the range -1 to 1. + pub climb: f32, /// Relative horizontal mouse motion for this step. pub mouse_x: f32, /// Relative vertical mouse motion for this step, positive down. @@ -19,6 +21,7 @@ pub struct PlayerMotion { pub struct PlayerMotionStep { pub(super) pose: TransformState, pub(super) pitch_bits: u32, + flying: bool, /// Sweep segment when the step translates the hero. pub sweep: Option<[[f32; 3]; 2]>, } @@ -27,6 +30,9 @@ 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 { + return None; + } let [[_, _, start_z], [x, y, _]] = self.sweep?; // shortcut: fixed step and drop limits, until the hero collider is wired. Some([[x, y, start_z + 0.1], [x, y, start_z - 2.5]]) @@ -55,6 +61,7 @@ mod tests { ..TransformState::default() }, pitch_bits: 0, + flying: false, sweep: Some([[3.0, 6.0, 12.5], [4.0, 6.0, 15.5]]), }; assert_eq!( @@ -77,19 +84,48 @@ pub fn plan_player_motion( cockpit: StartingCockpit, input: PlayerMotion, ) -> Result, EngineError> { - if input.movement == [0.0; 2] && input.mouse_x == 0.0 && input.mouse_y == 0.0 { - return Ok(None); - } let (Some(mission), Ok(pose)) = ( &engine.loaded, transform_state(&engine.world, cockpit.handle), ) else { return Ok(None); }; + let flying = mission.boarding.is_some_and(|boarding| { + boarding.cockpit.handle == cockpit.handle + && mission + .object_drafts + .get(cockpit.object_index) + .and_then(|draft| draft.unit_components.first()) + .is_some_and(|chassis| { + let key = chassis.resource_raw.split(|&byte| byte == 0).next(); + // shortcut: use the stock flying chassis until Behavior's CanFly is wired. + matches!( + key, + Some( + b"R_T_02" + | b"R_L_02" + | b"R_L_05" + | b"R_L_07" + | b"R_M_02" + | b"R_B_02" + | b"R_B_07" + | b"R_B_08" + ) + ) + }) + }); + if input.movement == [0.0; 2] + && (!flying || input.climb == 0.0) + && input.mouse_x == 0.0 + && input.mouse_y == 0.0 + { + return Ok(None); + } plan_motion( &mission.terrain, pose, f32::from_bits(mission.player_pitch_bits), + flying, input, ) .map(Some) @@ -99,6 +135,7 @@ fn plan_motion( terrain: &TerrainWorld, mut pose: TransformState, pitch: f32, + flying: bool, input: PlayerMotion, ) -> Result { let from = pose.position.map(f32::from_bits); @@ -109,6 +146,7 @@ fn plan_motion( .chain([ input.mouse_x, input.mouse_y, + input.climb, input.delta_seconds, yaw, pitch, @@ -130,19 +168,53 @@ fn plan_motion( yaw }; let [right, forward] = input.movement.map(|axis| axis.clamp(-1.0, 1.0)); - let distance = 8.0 * input.delta_seconds / right.hypot(forward).max(1.0); + // shortcut: constant flight rates until thrust, clearance and inertia are measured. + let speed = if flying { 40.0 } else { 8.0 }; + let distance = speed * input.delta_seconds / 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, ]; - if !xy.iter().all(|axis| axis.is_finite()) { + 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; - if xy != [from[0], from[1]] { + 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 { + 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 if xy != [from[0], from[1]] { if let (Some(old_ground), Some(new_ground)) = ( terrain .height_at([from[0], from[1]]) @@ -167,6 +239,7 @@ fn plan_motion( Ok(PlayerMotionStep { pose, pitch_bits: pitch.to_bits(), + flying, sweep, }) } diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 8f1c0140..4d82a8a3 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -66,7 +66,10 @@ authoring API без динамического подтверждения. без проверки направления и препятствий. Приказы союзнику и смена владельца в Behavior ещё открыты. `player_boarding_approx` отмечает выбор по близости вместо выбора цели, -ходьбу вместо ходовой модели и высадку сбоку по поверхности рельефа. +ходьбу вместо модели наземной машины и высадку сбоку по поверхности рельефа. +`player_vehicle_flight_approx` отмечает выбор летающих шасси по ключу, +постоянные скорости, точечный контакт с рельефом и открытые инерцию, +пределы высоты и сверку темпа полёта с оригиналом. `player_weapon_layout_stub`, `player_weapon_pose_stub` и `player_weapon_sound_stub` отмечают недоступные орудия, точки стволов и звуки костюма и варботов. Очерёдность устройств и темп огня из кабины варбота diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 295c8e78..10cc64cf 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -2003,7 +2003,22 @@ FParkan выбирает ближайший дружественный варб внутри. При выходе герой появляется сбоку у машины. Захваченный нейтральный варбот становится дружественным после первого Enter, а следующее нажатие позволяет сесть в его кабину. Правила выбора, допуска и высадки пока -приближённые. Для движения используется контроллер костюма. +приближённые. Наземные машины пока используют контроллер костюма. + +### Полёт из кабины варбота + +В начале «Телепорта» рядом с героем стоит лёгкий вертолёт. Брифинг +предлагает на нём перелететь через гребень к заводу в долине. +В `ui_bots.man` оригинала команды движения вверх и вниз назначены на +PgUp и PgDn. FParkan использует эти же клавиши. Отпустив их, пилот +сохраняет высоту относительно мира, поэтому машина может пересечь +склон или долину. При снижении машина останавливается у земли, а +обычная проверка строений действует вдоль всего шага, в том числе при +вертикальном движении. + +В GOG-сборке `Behavior.dll` по RVA `0x17660` загружается поле профиля +`CanFly`. FParkan пока определяет доступность полёта по штатным ключам +шасси. Скорости подъёма, снижения и движения постоянны. ### Коммуникатор здания -- cgit v1.2.3