diff options
| -rw-r--r-- | apps/fparkan-game/src/main.rs | 75 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 2 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/wheel_animation.rs | 302 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 2 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 17 |
5 files changed, 382 insertions, 16 deletions
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs index 8482161e..088cc0f3 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -4765,6 +4765,7 @@ struct ControlAnimationInstance { last_sampled_node_times: Vec<Option<f32>>, reported_unsupported_fallback: bool, door_blends: Vec<f32>, + wheels: Option<fparkan_runtime::WheelAnimation>, } #[derive(Clone)] @@ -4818,6 +4819,18 @@ struct MissionRenderRoot { rendered: LivePlacement, } +fn live_root_pose( + handle: ObjectHandle, + snapshot: &WorldSnapshot, +) -> Option<fparkan_world::TransformState> { + let offset = snapshot + .transforms + .binary_search_by_key(&handle.slot, |(owner, _)| owner.slot) + .ok()?; + let (owner, state) = snapshot.transforms[offset]; + (owner == handle).then_some(state) +} + fn live_placements( roots: &mut [Option<MissionRenderRoot>], snapshot: &WorldSnapshot, @@ -4825,12 +4838,7 @@ fn live_placements( let mut placements = HashMap::new(); for (index, root) in roots.iter_mut().enumerate() { let Some(root) = root else { continue }; - let state = snapshot - .transforms - .binary_search_by_key(&root.handle.slot, |(handle, _)| handle.slot) - .ok() - .map(|offset| snapshot.transforms[offset]) - .and_then(|(handle, state)| (handle == root.handle).then_some(state)); + let state = live_root_pose(root.handle, snapshot); // shortcut: retain the last pose until draw slots follow object lifecycle. let mut placement = state.map_or(root.rendered, |state| LivePlacement { transform: LegacyIron3dEulerTransform { @@ -7273,7 +7281,14 @@ fn update_control_animation_pose_buffers( native_clock_ms: u32, aim: Option<(StartingCockpit, f32)>, ) -> Result<(), String> { - update_gameplay_animation_pose_buffers(instances, pose_buffers, native_clock_ms, aim, None) + update_gameplay_animation_pose_buffers( + instances, + pose_buffers, + native_clock_ms, + aim, + None, + None, + ) } fn update_gameplay_animation_pose_buffers( @@ -7282,6 +7297,7 @@ fn update_gameplay_animation_pose_buffers( native_clock_ms: u32, aim: Option<(StartingCockpit, f32)>, player_doors: Option<([f32; 3], f32, &[BuildingCollisionBinding])>, + motion: Option<(&[Option<MissionRenderRoot>], &WorldSnapshot)>, ) -> Result<(), String> { for (object_index, components) in instances.iter_mut().enumerate() { let Some(object_pose_buffers) = pose_buffers.get_mut(object_index) else { @@ -7362,6 +7378,13 @@ fn update_gameplay_animation_pose_buffers( } } } + if let (Some(wheels), Some((roots, snapshot))) = (&mut instance.wheels, motion) { + if let Some(root) = roots.get(object_index).and_then(Option::as_ref) { + if let Some(pose) = live_root_pose(root.handle, snapshot) { + wheels.sample(root.handle, pose, &mut node_times); + } + } + } instance.last_sampled_node_times.clone_from(&node_times); let times = node_times .into_iter() @@ -8354,6 +8377,15 @@ fn static_preview_mesh_and_materials( last_sampled_node_times: Vec::new(), reported_unsupported_fallback: false, door_blends: Vec::new(), + wheels: if component_index == 0 + && mission_root + .unit_dat_header_flags + .is_some_and(|class| class & 0x0100_0000 != 0) + { + fparkan_runtime::WheelAnimation::prepare(control, &model.validated) + } else { + None + }, }); } } @@ -8362,15 +8394,19 @@ fn static_preview_mesh_and_materials( component_bindings, static_animation_frame, )?; + let wheel_root = control_animation_instances[0] + .as_ref() + .is_some_and(|instance| instance.wheels.is_some()); let timeline_moves_component = static_animation_frame.is_none() - && control_tree_chain_animates( - component_index, - tree.as_deref(), - component_controls.map_or(&[][..], |controls| controls.as_slice()), - cockpit - .filter(|cockpit| cockpit.object_index == object_index) - .map(|cockpit| cockpit.component_index), - ); + && (wheel_root + || control_tree_chain_animates( + component_index, + tree.as_deref(), + component_controls.map_or(&[][..], |controls| controls.as_slice()), + cockpit + .filter(|cockpit| cockpit.object_index == object_index) + .map(|cockpit| cockpit.component_index), + )); // Native AniMesh only resolves global MSH node sockets for EXTO // geometry. Internal INTO components use controller/equipment // slots, whose `parent_or_link` values are not MSH node indices. @@ -11357,6 +11393,9 @@ impl StaticVulkanApp { .map(|frame| f32::from_bits(frame.player_pitch_bits)), ), player_doors, + self.mission_frame + .as_ref() + .map(|frame| (self.mission_render_roots.as_slice(), &frame.snapshot)), )?; let placements = self .mission_frame @@ -13792,6 +13831,7 @@ mod tests { last_sampled_node_times: Vec::new(), reported_unsupported_fallback: false, door_blends: Vec::new(), + wheels: None, }); let first = FrameClockSample { @@ -13896,6 +13936,7 @@ mod tests { last_sampled_node_times: Vec::new(), reported_unsupported_fallback: false, door_blends: Vec::new(), + wheels: None, })]]; let hierarchy = static_preview_component_pose_buffer(&model, &controls.bindings, None).unwrap(); @@ -13974,6 +14015,7 @@ mod tests { now, None, Some(([hx, hy, hz], 0.292, &app.building_collision_bindings)), + None, ) .unwrap(); hero = @@ -14475,6 +14517,7 @@ mod tests { last_sampled_node_times: Vec::new(), reported_unsupported_fallback: false, door_blends: Vec::new(), + wheels: None, }), None, ]]; @@ -14817,6 +14860,7 @@ mod tests { last_sampled_node_times: Vec::new(), reported_unsupported_fallback: false, door_blends: Vec::new(), + wheels: None, }), None, ]]; @@ -15781,6 +15825,7 @@ mod tests { last_sampled_node_times: Vec::new(), reported_unsupported_fallback: false, door_blends: Vec::new(), + wheels: None, }); let turret_pose = |app: &StaticVulkanApp, node| { let hierarchy = app.component_pose_buffers[cockpit.object_index] diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index 309ff388..e27d9c18 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -108,7 +108,9 @@ mod unit_patrol; mod unit_size_class; mod unit_spawn; mod weapon_pose; +mod wheel_animation; pub use weapon_pose::{initial_component_node_times, WeaponPoseReport}; +pub use wheel_animation::WheelAnimation; pub use autodemo::{autodemo_camera, AutoDemoCamera, AutoDemoReinforcement, AutoDemoView}; pub use boarding::{ diff --git a/crates/fparkan-runtime/src/wheel_animation.rs b/crates/fparkan-runtime/src/wheel_animation.rs new file mode 100644 index 00000000..2fd2dcf3 --- /dev/null +++ b/crates/fparkan-runtime/src/wheel_animation.rs @@ -0,0 +1,302 @@ +//! Distance-driven playback of authored wheel roll loops. + +use crate::{ObjectHandle, TransformState}; +use fparkan_assets::{PreparedComponentControl, PreparedControlTimelineRow}; +use fparkan_msh::{node38_metadata, selected_slot, Group, Lod, ModelAsset, NodeId}; +use std::f32::consts::TAU; + +#[derive(Clone)] +struct Wheel { + row: PreparedControlTimelineRow, + radius: f32, + phase: f32, +} + +/// One chassis instance's wheel animation. The world transform drives its +/// phase, independently of the material and effect clocks. +#[derive(Clone)] +pub struct WheelAnimation { + wheels: Vec<Wheel>, + previous: Option<(ObjectHandle, [f32; 2])>, +} + +impl WheelAnimation { + /// Selects enabled wrapping controller rows whose mapped node keys form + /// one complete spin around a stationary local axle. + pub fn prepare(control: &PreparedComponentControl, model: &ModelAsset) -> Option<Self> { + let wheels: Vec<_> = control + .timeline_rows + .iter() + .copied() + .filter_map(|row| { + if row.flags & 5 != 1 + || !row.initial_blend.is_finite() + || !control.typed_records.iter().any(|record| { + record.tag == 3 && record.values.contains(&(row.row_index as u32)) + }) + { + return None; + } + Some(Wheel { + row, + radius: wheel_radius(model, row)?, + phase: row.initial_blend.rem_euclid(1.0), + }) + }) + .collect(); + (!wheels.is_empty()).then_some(Self { + wheels, + previous: None, + }) + } + + /// Applies the part of the recent displacement along the chassis's + /// forward axis. Repeated snapshots and idle turns spend no distance. + pub fn sample( + &mut self, + handle: ObjectHandle, + pose: TransformState, + times: &mut [Option<f32>], + ) { + let [x, y, _] = pose.position.map(f32::from_bits); + let previous = self.previous.replace((handle, [x, y])); + let scale = pose + .scale + .map(|bits| f32::from_bits(bits).abs()) + .into_iter() + .fold(0.0, f32::max); + let yaw = f32::from_bits(pose.orientation[2]); + for wheel in &mut self.wheels { + match previous { + Some((owner, [old_x, old_y])) if owner == handle => { + let distance = (old_x - x) * yaw.sin() + (y - old_y) * yaw.cos(); + let revolutions = distance / (TAU * wheel.radius * scale); + if revolutions.is_finite() { + wheel.phase = (wheel.phase + revolutions).rem_euclid(1.0); + } + } + _ => wheel.phase = wheel.row.initial_blend.rem_euclid(1.0), + } + if let Some(time) = times.get_mut(wheel.row.node_index) { + let phase = if wheel.row.flags & 2 != 0 { + 1.0 - wheel.phase + } else { + wheel.phase + }; + *time = Some(wheel.row.frame_a + phase * (wheel.row.frame_b - wheel.row.frame_a)); + } + } + } +} + +fn wheel_radius(model: &ModelAsset, row: PreparedControlTimelineRow) -> Option<f32> { + let animation = model.animation.as_ref()?; + let [a, b] = [row.frame_a, row.frame_b]; + if ![a, b] + .into_iter() + .all(|frame| frame.is_finite() && frame >= 0.0 && frame.fract() == 0.0) + || b - a < 3.0 + || b >= animation.frame_count as f32 + { + return None; + } + let node = NodeId(u32::try_from(row.node_index).ok()?); + let offset = usize::from(node38_metadata(model, node)?.anim_map_start); + if offset == usize::from(u16::MAX) { + return None; + } + let map = animation + .frame_map + .get(offset + a as usize..=offset + b as usize)?; + let first = animation.keys.get(map[0] as usize)?.sampling_pose(); + let mut previous = first.rotation; + let mut axis = None; + let target_step = TAU / (b - a); + for &key in &map[1..] { + let pose = animation.keys.get(key as usize)?.sampling_pose(); + if pose + .translation + .into_iter() + .zip(first.translation) + .any(|(a, b)| (a - b).abs() > 0.0001) + { + return None; + } + let dot: f32 = previous + .into_iter() + .zip(pose.rotation) + .map(|(a, b)| a * b) + .sum(); + if (2.0 * dot.abs().min(1.0).acos() - target_step).abs() > 0.01 { + return None; + } + // Imaginary part of conjugate(previous) * next, in slot-local axes. + let next = pose.rotation; + let relative: [f32; 3] = std::array::from_fn(|i| { + let j = (i + 1) % 3; + let k = (i + 2) % 3; + (previous[3] * next[i] - next[3] * previous[i] - previous[j] * next[k] + + previous[k] * next[j]) + * dot.signum() + }); + let (i, value) = relative + .into_iter() + .enumerate() + .max_by(|a, b| a.1.abs().total_cmp(&b.1.abs()))?; + if relative + .iter() + .enumerate() + .any(|(other, v)| i != other && v.abs() > 0.01) + || axis.is_some_and(|last| last != (i, value.is_sign_positive())) + { + return None; + } + axis = Some((i, value.is_sign_positive())); + previous = next; + } + let axle = axis?.0; + let bounds = model + .slots + .get(selected_slot(model, node, Lod(0), Group(0))?.0 as usize)?; + let radius = (0..3) + .filter(|&i| i != axle) + .map(|i| (bounds.aabb_max[i] - bounds.aabb_min[i]) * 0.5) + .fold(0.0, f32::max); + (radius.is_finite() && radius > 0.0).then_some(radius) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wheel_travel_respects_scale_reverse_and_lifetime() { + let handle = ObjectHandle { + slot: 7, + generation: 2, + }; + let wheel = Wheel { + row: PreparedControlTimelineRow { + row_index: 0, + node_index: 0, + frame_a: 2.0, + frame_b: 6.0, + initial_blend: 0.0, + raw_parameters: [0; 4], + flags: 3, + }, + radius: 2.0, + phase: 0.0, + }; + let mut animation = WheelAnimation { + wheels: vec![wheel], + previous: None, + }; + let mut pose = TransformState { + scale: [2.0_f32.to_bits(); 3], + ..Default::default() + }; + let mut times = [None, Some(12.0)]; + animation.sample(handle, pose, &mut times); + assert_eq!(times, [Some(6.0), Some(12.0)]); + pose.position[1] = TAU.to_bits(); + animation.sample(handle, pose, &mut times); + assert_eq!(times, [Some(5.0), Some(12.0)]); + pose.position[2] = 10.0_f32.to_bits(); + animation.sample(handle, pose, &mut times); + assert_eq!(times[0], Some(5.0)); + pose.position[1] = 0; + animation.sample(handle, pose, &mut times); + assert_eq!(times[0], Some(6.0)); + pose.position[1] = TAU.to_bits(); + animation.sample( + ObjectHandle { + generation: 3, + ..handle + }, + pose, + &mut times, + ); + assert_eq!(times[0], Some(6.0)); + } + + #[test] + #[ignore = "requires licensed corpus"] + fn licensed_wheeled_chassis_samples_rolling_msh_keys() { + use crate::{ + create, load_gameplay_mission, loaded_mission_assets, loaded_mission_object_drafts, + EngineServices, MissionMode, MissionRequest, MissionStartupInput, + }; + use fparkan_animation::AnimationTime; + use fparkan_msh::node38_sampled_hierarchy_at_times; + use fparkan_vfs::DirectoryVfs; + use std::sync::Arc; + + let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus"); + let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap(); + load_gameplay_mission( + &mut engine, + MissionRequest { + key: "MISSIONS/Autodemo.00/data.tma".into(), + mode: MissionMode::AutoDemo, + }, + MissionStartupInput { + queue_time_ms: 0, + research_creation_gate: false, + }, + None, + ) + .unwrap(); + let assets = loaded_mission_assets(&engine).unwrap(); + let drafts = loaded_mission_object_drafts(&engine).unwrap(); + let (index, draft) = drafts + .iter() + .enumerate() + .find(|(_, draft)| draft.resource_name_raw.ends_with(b"w_s_wel1.dat")) + .unwrap(); + let control = assets.object_component_controls[index][0].as_ref().unwrap(); + let visual = assets + .visual_by_id(assets.visual_for_object(index).unwrap()) + .unwrap(); + let model = &assets + .model_by_id(visual.model_id.unwrap()) + .unwrap() + .validated; + let mut wheels = WheelAnimation::prepare(control, model).unwrap(); + assert_eq!(wheels.wheels.len(), 4); + let wheel = &wheels.wheels[0]; + let radius = wheel.radius; + let node = wheel.row.node_index; + let handle = ObjectHandle { + slot: 1, + generation: 1, + }; + let mut pose = TransformState { + scale: draft.scale.map(f32::to_bits), + ..Default::default() + }; + let mut times = vec![Some(0.0); model.node_count]; + let sample = |times: &[Option<f32>]| { + let values: Vec<_> = times.iter().map(|t| t.map(AnimationTime)).collect(); + node38_sampled_hierarchy_at_times(model, &values) + .unwrap() + .poses[node] + }; + wheels.sample(handle, pose, &mut times); + let start = sample(×); + pose.position[1] = + (radius * TAU * 0.25 * draft.scale.into_iter().map(f32::abs).fold(0.0, f32::max)) + .to_bits(); + wheels.sample(handle, pose, &mut times); + let turned = sample(×); + let dot: f32 = start + .rotation + .into_iter() + .zip(turned.rotation) + .map(|(a, b)| a * b) + .sum(); + assert!((dot.abs() - std::f32::consts::FRAC_1_SQRT_2).abs() < 0.0001); + wheels.sample(handle, pose, &mut times); + assert_eq!(sample(×), turned); + } +} diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index c4081364..c3a031ca 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -80,6 +80,8 @@ authoring API без динамического подтверждения. объекту и поколению. Нативный MWalker и передача движения в Control открыты. Обход проверяет проекции основных моделей и участки, занятые машинами за кадр. Открыты формы проёмов, проверка проходимости всего отрезка и разъезд в тесноте. +Прокат колёс использует полные циклы MSH и радиус из габаритов модели. +Поворот на месте, проскальзывание, походка и движение гусениц пока открыты. `go_speed_profile_approx` считает кадровые запросы Go по текущему пределу Control и коэффициенту Behavior; `go_speed_stub` считает подмену 9 при отсутствии данных. Удержание запроса MWalker входит в незавершённый `unit_motion_controller_stub`. diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 4d50660f..8620f70c 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -2397,7 +2397,22 @@ Go, Patrol и сближение с целью передают маршрут Ð `unit_motion_controller_stub` остаётся в отчёте. Препятствия имеют прямоугольную форму, а очередь хода машин влияет на разъезд. Открыты узкие -проезды, высота полёта и связь движения с анимацией. +проезды, высота полёта, анимация шага и гусениц. + +#### Прокат колёс + +На колёсном шасси `R_L_03` управляющий ресурс связывает четыре узла с +зацикленными строками CTLD. Ключи каждой строки задают полный оборот вокруг +неподвижной локальной оси. FParkan подключает такие строки, когда ключи +образуют равномерный оборот и размер колеса можно прочитать из модели. +Один оборот соответствует пути `2πr`. Пройденное за кадр расстояние вдоль +корпуса сдвигает фазу, задний ход крутит колёса в обратную сторону, +пауза сохраняет угол. Появление новой машины начинает новый цикл. + +Фаза отбирает исходные позы узлов MSH, поэтому за ними обновляются и +крепления деталей. Радиус оценён по габаритам модели, вертикальное +движение и проскальзывание не учитываются. У шагающих шасси есть ключи +поз, но проверенные CTLD не указывают диапазон шага. Ходьба остаётся открытой. В GOG `Behavior.dll` ([сборка](../reference/original-binaries.md)) задача Go (RVA `0x2b670`) обращается к MWalker, а не изменяет transform сама. |
