diff options
| author | Valentin Popov <valentin@popov.link> | 2026-12-02 09:24:37 +0300 |
|---|---|---|
| committer | Valentin Popov <valentin@popov.link> | 2026-12-02 09:24:37 +0300 |
| commit | 149a8142d17e166fda8f15ce09eb3777b0e12ce7 (patch) | |
| tree | 39c552f7c78b57294ca822150a4a09f049779222 | |
| parent | d2a9f21927fd20c15f02bcf4af791f18c309b072 (diff) | |
| download | fparkan-149a8142d17e166fda8f15ce09eb3777b0e12ce7.tar.xz fparkan-149a8142d17e166fda8f15ce09eb3777b0e12ce7.zip | |
feat(ui): move the strategic bunker camera
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 2 | ||||
| -rw-r--r-- | apps/fparkan-game/src/strategic_view.rs | 74 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/strategic_view.rs | 272 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 7 | ||||
| -rw-r--r-- | docs/appendices/ui-shell.md | 12 |
5 files changed, 309 insertions, 58 deletions
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index d3d36128..8f96ec40 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -9751,7 +9751,7 @@ impl StaticVulkanApp { ) -> Result<(), String> { self.cockpit_geometry.clear(); self.player_aim_direction = None; - if let Some(camera) = self.strategic_frame(viewport) { + if let Some(camera) = self.strategic_frame(viewport, delta_seconds) { self.camera = camera.vulkan_camera(); self.view_camera = camera; return Ok(()); diff --git a/apps/fparkan-game/src/strategic_view.rs b/apps/fparkan-game/src/strategic_view.rs index 7c9ada0a..aeb782be 100644 --- a/apps/fparkan-game/src/strategic_view.rs +++ b/apps/fparkan-game/src/strategic_view.rs @@ -1,14 +1,16 @@ -use super::{LegacyD3d7Projection, PreviewCameraFrame, StaticVulkanApp}; +use super::{player_movement_key, LegacyD3d7Projection, PreviewCameraFrame, StaticVulkanApp}; use fparkan_assets::strategy_toolbar::{command_button_at, ToolbarAction}; -use fparkan_runtime::strategic_view::{command_post, command_view, CommandPost}; +use fparkan_runtime::strategic_view::{ + command_post, CommandCamera, CommandCameraInput, COMMAND_FOV, +}; use winit::{ event::{ElementState, KeyEvent, MouseButton, WindowEvent}, keyboard::{KeyCode, PhysicalKey}, }; pub(super) struct ActiveCommandView { - post: CommandPost, - pointer_button: Option<ToolbarAction>, + camera: CommandCamera, + pointer: Option<[f32; 2]>, } impl StaticVulkanApp { @@ -22,9 +24,12 @@ impl StaticVulkanApp { let Some(post) = command_post(engine, cockpit) else { return false; }; + let Some(camera) = CommandCamera::new(engine, post) else { + return false; + }; self.command_view = Some(ActiveCommandView { - post, - pointer_button: None, + camera, + pointer: None, }); self.camera_mode = "strategic"; self.player_mouse = [0.0; 2]; @@ -36,6 +41,7 @@ impl StaticVulkanApp { pub(super) fn close_strategy(&mut self) { self.command_view = None; + self.pressed_keys.clear(); self.camera_mode = if self.boarded_hero_index.is_some() { "vehicle-cockpit" } else { @@ -44,13 +50,39 @@ impl StaticVulkanApp { self.set_mouse_look(self.window_focused && !self.mission_paused); } - pub(super) fn strategic_frame(&mut self, viewport: [f32; 2]) -> Option<PreviewCameraFrame> { - let post = self.command_view.as_ref()?.post; + pub(super) fn strategic_frame( + &mut self, + viewport: [f32; 2], + dt: f32, + ) -> Option<PreviewCameraFrame> { + let mut view = self.command_view.take()?; + let axis = |first, second, first_sign: i8| { + if self.pressed_keys.contains(&first) { + first_sign + } else { + -first_sign * i8::from(self.pressed_keys.contains(&second)) + } + }; + let input = CommandCameraInput { + translation: [ + axis(KeyCode::ArrowLeft, KeyCode::ArrowRight, -1), + axis(KeyCode::ArrowUp, KeyCode::ArrowDown, 1), + axis(KeyCode::PageUp, KeyCode::PageDown, 1), + ], + rotation: view + .pointer + .map_or([0, 0], CommandCameraInput::edge_rotation), + }; + let dt = if self.mission_paused || !self.window_focused { + 0.0 + } else { + dt + }; let frame = self .mission_engine .as_ref() .and_then(|engine| { - command_view(engine, post, |segment| { + view.camera.sample(engine, dt, input, |segment| { self.building_segment_hit(segment, true) .inspect_err(|error| eprintln!("strategic camera height: {error}")) .ok() @@ -65,11 +97,13 @@ impl StaticVulkanApp { viewport: [0, 0, viewport[0] as i32, viewport[1] as i32], near_plane: 0.5, far_plane: 700.0, - field_of_view_radians: 1.04, + field_of_view_radians: COMMAND_FOV, }, ) }); - if frame.is_none() { + if frame.is_some() { + self.command_view = Some(view); + } else { self.close_strategy(); } frame @@ -85,6 +119,16 @@ impl StaticVulkanApp { ) && self.open_strategy(); } + if let Some(code) = player_movement_key(event.physical_key, &event.logical_key) { + match event.state { + ElementState::Pressed => { + self.pressed_keys.insert(code); + } + ElementState::Released => { + self.pressed_keys.remove(&code); + } + } + } if pressed { match event.physical_key { PhysicalKey::Code(KeyCode::Escape) => self.close_strategy(), @@ -105,16 +149,16 @@ impl StaticVulkanApp { }; match event { WindowEvent::CursorMoved { position, .. } => { - view.pointer_button = self.window.as_ref().and_then(|window| { + view.pointer = self.window.as_ref().and_then(|window| { let size = window.inner_size(); - command_button_at([ + (size.width != 0 && size.height != 0).then_some([ position.x as f32 * 640.0 / size.width as f32, position.y as f32 * 480.0 / size.height as f32, ]) }); } WindowEvent::CursorLeft { .. } | WindowEvent::Focused(false) => { - view.pointer_button = None; + view.pointer = None; return false; } WindowEvent::MouseInput { state, button, .. } => { @@ -122,7 +166,7 @@ impl StaticVulkanApp { && *button == MouseButton::Left && !self.mission_paused { - match view.pointer_button { + match view.pointer.and_then(command_button_at) { Some(ToolbarAction::Hero) => { self.close_strategy(); self.player_disembark_pressed = self.boarded_hero_index.is_some(); diff --git a/crates/fparkan-runtime/src/strategic_view.rs b/crates/fparkan-runtime/src/strategic_view.rs index 81d822eb..250f943e 100644 --- a/crates/fparkan-runtime/src/strategic_view.rs +++ b/crates/fparkan-runtime/src/strategic_view.rs @@ -5,6 +5,9 @@ use fparkan_render::{LegacyIron3dEulerTransform, RawCameraTransform}; use fparkan_world::{identity_metadata, registration_sequence, transform_state, ObjectHandle}; use std::f32::consts::FRAC_PI_2; +/// Horizontal field of view of the strategic camera. +pub const COMMAND_FOV: f32 = 1.04; + /// The object providing the command interface. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CommandPost { @@ -75,38 +78,182 @@ fn has_command_link(devices: &[crate::EffectiveControlDevice]) -> bool { .is_some_and(|device| device.descriptor.fixed_words[2] & 0x0800_0000 != 0) } -/// Initial external viewpoint of a command post, sampled from the current world. -/// `building_height` returns the highest building hit on the downward segment. -#[must_use] -pub fn command_view( - engine: &Engine, - post: CommandPost, - building_height: impl FnOnce([[f32; 3]; 2]) -> Option<f32>, -) -> Option<RawCameraTransform> { - let (handle, clearance) = match post { - CommandPost::Bunker(handle) => (handle, 36.0), - CommandPost::Warbot(handle) => (handle, 2.5), - }; +fn post_position(engine: &Engine, handle: ObjectHandle) -> Option<[f32; 3]> { registration_sequence(&engine.world, handle).ok()??; - let [x, y, z] = transform_state(&engine.world, handle) - .ok()? - .position - .map(f32::from_bits); - let terrain = &engine.loaded.as_ref()?.terrain; - let ground = terrain.height_at([x, y]).ok()??; - let [_, [_, _, top]] = terrain.surface_bounds()?; - // iron3d+0xa1470 casts down from the map's upper plane and includes roofs. - let surface = building_height([[x, y, top], [x, y, ground]]).unwrap_or(ground); - // iron3d+0x63ec0/+0x64140 start at the post, looking north. - // The first external update sets pitch and raises the eye over the surface. - let matrix = LegacyIron3dEulerTransform { - translation: [x, y, z.max(surface + clearance)], - orientation_radians: [0.0, FRAC_PI_2 - 1.0, FRAC_PI_2], + Some( + transform_state(&engine.world, handle) + .ok()? + .position + .map(f32::from_bits), + ) +} + +/// Held directions of the bunker camera during the current frame. +#[derive(Clone, Copy, Default)] +pub struct CommandCameraInput { + /// Motion along the camera's right, forward and vertical axes. + pub translation: [i8; 3], + /// Yaw and upward tilt when the pointer is at a screen edge. + pub rotation: [i8; 2], +} + +impl CommandCameraInput { + /// Native edge zones in the 640×480 command interface space. + #[must_use] + pub fn edge_rotation([x, y]: [f32; 2]) -> [i8; 2] { + let x = x.round_ties_even(); + let y = y.round_ties_even(); + [ + i8::from(x < 7.0) - i8::from(x > 633.0), + i8::from(y < 7.0) - i8::from(y > 473.0), + ] + } +} + +#[derive(Clone, Copy, Default)] +struct CameraAxis { + direction: i8, + held: f32, + rate: f32, +} + +impl CameraAxis { + fn step(&mut self, direction: i8, max_rate: f32, dt: f32) -> f32 { + // iron3d+0x372a0/+0x37540 use a half-second ramp, then multiply + // the previous frame's rate by (0.5 - dt) during release. + if direction == 0 { + self.rate *= (0.5 - dt).max(0.0); + } else { + self.held = if direction == self.direction { + (self.held + dt).min(0.5) + } else { + 0.0 + }; + self.rate = f32::from(direction.signum()) * max_rate * (2.0 * self.held); + } + self.direction = direction; + self.rate * dt + } +} + +/// The external camera retained while the player uses a command post. +pub struct CommandCamera { + post: CommandPost, + position: [f32; 3], + yaw: f32, + tilt: f32, + axes: [CameraAxis; 5], +} + +impl CommandCamera { + /// Starts at the command post, looking north. + #[must_use] + pub fn new(engine: &Engine, post: CommandPost) -> Option<Self> { + let handle = match post { + CommandPost::Bunker(handle) | CommandPost::Warbot(handle) => handle, + }; + Some(Self { + post, + position: post_position(engine, handle)?, + yaw: FRAC_PI_2, + tilt: 1.0, + axes: [CameraAxis::default(); 5], + }) + } + + /// Advances the external view and returns the pose for this frame. + /// `building_height` reports the highest building hit on the downward segment. + pub fn sample( + &mut self, + engine: &Engine, + dt: f32, + input: CommandCameraInput, + building_height: impl FnOnce([[f32; 3]; 2]) -> Option<f32>, + ) -> Option<RawCameraTransform> { + let terrain = &engine.loaded.as_ref()?.terrain; + let [min, max] = terrain.surface_bounds()?; + let clearance = match self.post { + CommandPost::Bunker(_) => { + self.advance_bunker(dt, input, max); + 36.0 + } + CommandPost::Warbot(handle) => { + self.position = post_position(engine, handle)?; + 2.5 + } + }; + let [x, y, z] = self.position; + let ground = terrain.height_at([x, y]).ok()?; + // iron3d+0xa1470 casts from the map's upper plane and includes roofs. + let surface = building_height([[x, y, max[2]], [x, y, ground.unwrap_or(min[2])]]) + .or(ground) + .unwrap_or(0.0); + self.position[2] = z.max(surface + clearance); + if let CommandPost::Bunker(handle) = self.post { + self.position[2] = self.position[2].min(surface + clearance + 200.0); + self.limit_to_bunker(post_position(engine, handle)?); + } + let matrix = LegacyIron3dEulerTransform { + translation: self.position, + orientation_radians: [0.0, FRAC_PI_2 - self.tilt, self.yaw], + } + .try_row_major()?; + Some(RawCameraTransform { + words: matrix.map(f32::to_bits), + }) + } + + fn advance_bunker(&mut self, dt: f32, input: CommandCameraInput, map_max: [f32; 3]) { + if dt <= 0.0 { + return; + } + // On a stalled frame one large step can be rejected at both tilt limits. + // Use the ordinary 60 Hz step size to keep those slow frames controllable. + let steps = if dt > 0.1 { + (dt * 60.0).ceil() as u32 + } else { + 1 + }; + let slice = dt / steps as f32; + for _ in 0..steps { + self.move_bunker(slice, input, map_max); + } + } + + fn move_bunker(&mut self, dt: f32, input: CommandCameraInput, map_max: [f32; 3]) { + let [right, forward, up] = input.translation; + let [yaw, tilt] = input.rotation; + let right = self.axes[0].step(right, 125.0, dt); + let forward = self.axes[1].step(forward, 125.0, dt); + let up = self.axes[2].step(up, 62.5, dt); + let (sin, cos) = self.yaw.sin_cos(); + let margin = (0.5 * COMMAND_FOV).tan() * self.position[2]; + // The native update checks each of the two motions separately. + for [dx, dy] in [[right * sin, -right * cos], [forward * cos, forward * sin]] { + for (axis, step) in [dx, dy].into_iter().enumerate() { + let next = self.position[axis] + step; + if margin < next && next < map_max[axis] { + self.position[axis] = next; + } + } + } + self.position[2] += up; + self.yaw += self.axes[3].step(yaw, 1.5, dt); + let next_tilt = self.tilt + self.axes[4].step(tilt, 1.5, dt); + if 0.0 < next_tilt && next_tilt < FRAC_PI_2 { + self.tilt = next_tilt; + } + } + + fn limit_to_bunker(&mut self, origin: [f32; 3]) { + // iron3d+0x37720 rounds each relative coordinate before testing it. + for (point, center) in self.position[..2].iter_mut().zip(origin) { + let offset = *point - center; + if offset.round_ties_even().abs() > 200.0 { + *point = center + offset.signum() * 200.0; + } + } } - .try_row_major()?; - Some(RawCameraTransform { - words: matrix.map(f32::to_bits), - }) } #[cfg(test)] @@ -137,6 +284,50 @@ mod tests { } #[test] + fn bunker_camera_moves_in_view_axes_with_native_limits() { + let origin = [300.0, 300.0, 100.0]; + let mut camera = CommandCamera { + post: CommandPost::Bunker(ObjectHandle { + generation: 0, + slot: 0, + }), + position: origin, + yaw: FRAC_PI_2, + tilt: 1.0, + axes: [CameraAxis::default(); 5], + }; + let input = CommandCameraInput { + translation: [1, 1, 1], + rotation: [0, 0], + }; + let map_max = [1024.0, 1024.0, 220.0]; + camera.move_bunker(0.25, input, map_max); + assert_eq!(camera.position, origin); + camera.move_bunker(0.25, input, map_max); + assert_eq!(camera.position, [315.625, 315.625, 107.8125]); + camera.move_bunker(0.25, CommandCameraInput::default(), map_max); + assert_eq!(camera.position, [319.53125, 319.53125, 109.765625]); + camera.position[0] = 500.5; + camera.limit_to_bunker(origin); + assert_eq!(camera.position[0], 500.5); + camera.position[0] = 500.6; + camera.limit_to_bunker(origin); + assert_eq!(camera.position[0], 500.0); + + assert_eq!(CommandCameraInput::edge_rotation([634.0, 6.0]), [-1, 1]); + assert_eq!(CommandCameraInput::edge_rotation([633.0, 7.0]), [0, 0]); + camera.advance_bunker( + 0.8, + CommandCameraInput { + rotation: [0, 1], + ..Default::default() + }, + map_max, + ); + assert!(camera.tilt > 1.5 && camera.tilt < FRAC_PI_2); + } + + #[test] #[ignore = "requires licensed corpus"] fn licensed_starting_bunker_supplies_strategy_camera() { let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap(); @@ -158,15 +349,20 @@ mod tests { let bunker = crate::mission_object_handle(&engine, OriginalObjectId(0)).unwrap(); let post = command_post(&engine, hero); assert_eq!(post, Some(CommandPost::Bunker(bunker))); - let post = post.unwrap(); - let previous = command_view(&engine, post, |_| None).unwrap().translation(); + let mut camera = CommandCamera::new(&engine, post.unwrap()).unwrap(); + let input = CommandCameraInput::default(); + let previous = camera + .sample(&engine, 0.0, input, |_| None) + .unwrap() + .translation(); let native_roof = 108.54639; - let raised = command_view(&engine, post, |[[x, y, top], [_, _, ground]]| { - assert_eq!([x, y], [previous[0], previous[1]]); - assert!(ground < native_roof && native_roof < top); - Some(native_roof) - }) - .unwrap(); + let raised = camera + .sample(&engine, 0.0, input, |[[x, y, top], [_, _, ground]]| { + assert_eq!([x, y], [previous[0], previous[1]]); + assert!(ground < native_roof && native_roof < top); + Some(native_roof) + }) + .unwrap(); assert_eq!(raised.translation(), [previous[0], previous[1], 144.54639]); } } diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 83cf9057..d38bf18d 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -305,10 +305,9 @@ seed и общий порядок Control RNG открыты. `control_resource_ `autodemo_camera_follow_approx` и `autodemo_camera_target_approx` отмечают приближённое слежение и выбор размещённых юнитов с камерой через селектор AI. -Для стратегического экрана открыты указатель и движение внешней камеры, -балансы клана и списки объектов панели. Для повторного входа из -бункера используется материал пола. Вход из варбота с МФУ и возврат предстоит -проверить в штатной игре. +Для стратегического экрана открыты указатель, балансы клана и списки объектов +панели. Для повторного входа из бункера используется материал пола. Движение +камеры из варбота с МФУ и проверка входа и возврата в штатной игре остаются открытыми. ## Render state diff --git a/docs/appendices/ui-shell.md b/docs/appendices/ui-shell.md index 5940ddc2..3a15ad32 100644 --- a/docs/appendices/ui-shell.md +++ b/docs/appendices/ui-shell.md @@ -285,6 +285,18 @@ RVA `0x9be40` рисует рамку из набора состояний и к оригинал поднимает камеру до `Z = 144,546` над крышей на высоте `108,546`. Поэтому FParkan берёт верхнее попадание по строениям вместе с рельефом. +В бункере стрелки двигают камеру вдоль её горизонтальных осей, а Page Up и +Page Down меняют высоту. Эти клавиши заданы в `ui_hq.man`. У боковых краёв +указатель поворачивает камеру, у верхнего и нижнего меняет наклон. Границы +зон — `x < 7`, `x > 633`, `y < 7`, `y > 473` в системе 640×480 (RVA `0x37bc0`). +За полсекунды камера набирает 125 единиц в секунду по горизонтали, 62,5 по +вертикали или 1,5 рад/с при повороте. После отпускания прежняя скорость +умножается на `max(0, 0,5 − Δt)` за кадр (RVA `0x372a0` и `0x37540`). +Высота ограничена поверхностью плюс 36–236 единиц, а координаты по каждой +горизонтальной оси — расстоянием 200 единиц от бункера после округления. +При кадре длиннее 0,1 секунды FParkan разбивает движение на шаги до 1/60 +секунды. Иначе шаг наклона может перескочить предел и оставить камеру на месте. + ## Оружейные строки кабины В `iron3d.dll` RVA `0x74f40` читает четыре имени орудий героя из строк |
