diff options
| -rw-r--r-- | crates/fparkan-runtime/src/player_weapon.rs | 9 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/projectile.rs | 3 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/unit_combat.rs | 120 | ||||
| -rw-r--r-- | docs/appendices/knowledge-boundaries.md | 3 | ||||
| -rw-r--r-- | docs/tomes/06-behavior.md | 20 |
5 files changed, 131 insertions, 24 deletions
diff --git a/crates/fparkan-runtime/src/player_weapon.rs b/crates/fparkan-runtime/src/player_weapon.rs index ffc488b1..cfec0524 100644 --- a/crates/fparkan-runtime/src/player_weapon.rs +++ b/crates/fparkan-runtime/src/player_weapon.rs @@ -21,6 +21,7 @@ pub struct PlayerWeapon { pub(super) control_record_index: usize, pub(super) charge: Option<crate::mobile_budget::Charge>, pub(super) energy_waits: u64, + pub(super) autonomous_fire_distance: f32, /// Name of the projectile prototype. pub projectile: String, /// Archive named by the weapon's projectile descriptor. @@ -126,13 +127,13 @@ impl PlayerWeapons { trigger: bool, clock_ms: u32, ) -> impl Iterator<Item = (usize, &PlayerWeapon, &PreparedControlPoint)> { - self.fire_where(clock_ms, move |_, _| trigger) + self.fire_where(clock_ms, move |_, _, _| trigger) } pub(super) fn fire_where( &mut self, clock_ms: u32, - mut trigger: impl FnMut(&PlayerWeapon, &PreparedControlPoint) -> bool, + mut trigger: impl FnMut(usize, &PlayerWeapon, &PreparedControlPoint) -> bool, ) -> impl Iterator<Item = (usize, &PlayerWeapon, &PreparedControlPoint)> { if let Some(last) = self.last_sample_ms.replace(clock_ms) { self.clock_ms += f64::from(clock_ms.wrapping_sub(last)); @@ -144,7 +145,7 @@ impl PlayerWeapons { .enumerate() .filter_map(move |(index, weapon)| { let start = selected.is_none_or(|selected| selected == index) - && trigger(weapon, &weapon.barrels[weapon.barrel_index].muzzle); + && trigger(index, weapon, &weapon.barrels[weapon.barrel_index].muzzle); let barrel = weapon.sample_fire(start, now)?; Some((index, &*weapon, &weapon.barrels[barrel].muzzle)) }) @@ -354,6 +355,7 @@ fn prepare_weapons( control_record_index, charge: None, energy_waits: 0, + autonomous_fire_distance: f32::from_bits(record.fixed_words[19]), projectile, projectile_archive, effect, @@ -436,6 +438,7 @@ mod tests { control_record_index: 0, charge: None, energy_waits: 0, + autonomous_fire_distance: 0.0, projectile: String::from("test"), projectile_archive: String::from("test.rlb"), effect: None, diff --git a/crates/fparkan-runtime/src/projectile.rs b/crates/fparkan-runtime/src/projectile.rs index 4ffb6fae..48018933 100644 --- a/crates/fparkan-runtime/src/projectile.rs +++ b/crates/fparkan-runtime/src/projectile.rs @@ -25,6 +25,7 @@ pub struct ProjectileAssets { pub lifetime_ms: u32, /// Initial provider volume of the projectile. pub volume: Option<f32>, + pub(super) autonomous_fire_distance: f32, } /// Prepares the BULL prototype referenced by a manual weapon. @@ -74,6 +75,7 @@ pub(super) fn load_projectile( }; let speed = f32::from_bits(control.native_profile_words[7]); let lifetime_ms = control.native_profile_words[18]; + let autonomous_fire_distance = f32::from_bits(control.native_profile_words[22]); let volume = control.node_data.as_ref().and_then(|data| { let amount = data.rows.first()?.max_volume; (amount.is_finite() && amount > 0.0).then_some(amount) @@ -86,6 +88,7 @@ pub(super) fn load_projectile( speed, lifetime_ms, volume, + autonomous_fire_distance, }) } diff --git a/crates/fparkan-runtime/src/unit_combat.rs b/crates/fparkan-runtime/src/unit_combat.rs index 0491c078..f209a480 100644 --- a/crates/fparkan-runtime/src/unit_combat.rs +++ b/crates/fparkan-runtime/src/unit_combat.rs @@ -17,7 +17,7 @@ use std::sync::Arc; // Behavior's default Patrol_Attack_Range and Attack_MaxFireDistance. const ATTACK_RANGE: f32 = 400.0; -const FIRE_RANGE: f32 = 200.0; +const ATTACK_STOP_RANGE: f32 = 200.0; /// An autonomous projectile type, in render-pool order. pub struct AutoDemoProjectileType { @@ -30,6 +30,7 @@ pub struct AutoDemoProjectileType { speed: f32, lifetime_ms: u32, volume: Option<f32>, + autonomous_fire_distance: f32, } /// The prepared scene instance associated with a weapon's firing effect. @@ -208,6 +209,7 @@ impl AutoDemoCombat { speed: data.speed, lifetime_ms: data.lifetime_ms, volume: data.volume, + autonomous_fire_distance: data.autonomous_fire_distance, }); Some(battle.projectiles.len() - 1) })?; @@ -324,6 +326,17 @@ impl AutoDemoCombat { patrol: Option<&UnitPatrol>, controls: &[super::MissionControlDeviceTableState], ) -> Vec<(ObjectHandle, CombatTarget)> { + self.select_targets(world, assets, patrol, controls, false) + } + + fn select_targets( + &self, + world: &fparkan_world::World, + assets: &MissionAssets, + patrol: Option<&UnitPatrol>, + controls: &[super::MissionControlDeviceTableState], + use_weapon_range: bool, + ) -> Vec<(ObjectHandle, CombatTarget)> { let live: Vec<_> = self .units .iter() @@ -332,7 +345,7 @@ impl AutoDemoCombat { let state = transform_state(world, unit.handle).ok()?; let (center, radius) = unit_sphere(assets, unit.index, state)?; Some(( - unit.handle, + unit, usize::from(owner.0), center, radius, @@ -341,7 +354,8 @@ impl AutoDemoCombat { }) .collect(); live.iter() - .filter_map(|&(handle, clan, from, _, position)| { + .filter_map(|&(unit, clan, from, _, position)| { + let handle = unit.handle; if patrol.is_some_and(|patrol| { patrol.is_shut_down(handle) || patrol.is_moving_to_destination(handle) @@ -365,20 +379,32 @@ impl AutoDemoCombat { handle: target, center, radius, - in_range: distance <= FIRE_RANGE, + in_range: distance <= ATTACK_STOP_RANGE, }, )); } - let limit = patrol.and_then(|patrol| patrol.attack_limit(world, handle)); + // The patrol area bounds pursuit. A Control weapon can fire + // across that boundary while the hull follows its order. + let limit = if use_weapon_range { + None + } else { + patrol.and_then(|patrol| patrol.attack_limit(world, handle)) + }; if limit.is_some_and(|limit| !limit.allows_attack(position)) { return None; } + let search_distance = if use_weapon_range { + self.maximum_firing_distance(unit) + } else { + ATTACK_RANGE + }; let (enemy, center, radius, distance) = live .iter() .filter_map(|&(enemy, other, to, radius, target_position)| { + let enemy = enemy.handle; let distance = (to[0] - from[0]).hypot(to[1] - from[1]); (enemy != handle - && distance <= ATTACK_RANGE + && distance <= search_distance && limit .is_none_or(|limit| limit.allows_target(enemy, target_position)) && self.hostile.get(clan)?.get(other) == Some(&true)) @@ -391,13 +417,27 @@ impl AutoDemoCombat { handle: enemy, center, radius, - in_range: distance <= FIRE_RANGE, + in_range: distance <= ATTACK_STOP_RANGE, }, )) }) .collect() } + fn maximum_firing_distance(&self, unit: &Unit) -> f32 { + unit.weapons + .weapons() + .iter() + .zip(&unit.slots) + .filter_map(|(weapon, slot)| { + Some(firing_distance( + weapon.autonomous_fire_distance, + self.projectiles[(*slot)?].autonomous_fire_distance, + )) + }) + .fold(0.0, f32::max) + } + pub(super) fn tick( &mut self, engine: &mut Engine, @@ -480,11 +520,12 @@ impl AutoDemoCombat { let Some(mission) = &engine.loaded else { return (events, unavailable); }; - let targets = self.targets( + let targets = self.select_targets( &engine.world, &mission.mission_assets, mission.unit_patrol.as_ref(), &mission.control_device_tables, + true, ); for unit in &mut self.units { unit.weapons.read_control_energy(engine, unit.handle); @@ -522,7 +563,7 @@ impl AutoDemoCombat { .then(|| { targets .iter() - .find(|(handle, target)| *handle == unit.handle && target.in_range) + .find(|(handle, _)| *handle == unit.handle) .map(|(_, target)| (target.handle, target.center, target.radius)) .or_else(|| { let (factory, index) = @@ -537,14 +578,8 @@ impl AutoDemoCombat { { return None; } - let state = transform_state(&engine.world, unit.handle).ok()?; - let (from, _) = - unit_sphere(&mission.mission_assets, unit.index, state)?; let target = transform_state(&engine.world, factory).ok()?; let (to, _) = unit_sphere(&mission.mission_assets, index, target)?; - if (to[0] - from[0]).hypot(to[1] - from[1]) > FIRE_RANGE { - return None; - } // shortcut: the native attack task's selected building node is unresolved. Some((factory, to, 0.0)) }) @@ -573,10 +608,21 @@ impl AutoDemoCombat { .is_some_and(|contact| ground.is_none_or(|ground| contact < ground)) }) }; - for (slot, weapon, barrel) in unit.weapons.fire_where(now, |weapon, barrel| { + let hull_position = state.position.map(f32::from_bits); + for (slot, weapon, barrel) in unit.weapons.fire_where(now, |slot, weapon, barrel| { let Some((_, to, radius)) = aim else { return false; }; + let Some(projectile) = unit.slots[slot] else { + return false; + }; + let distance = firing_distance( + weapon.autonomous_fire_distance, + self.projectiles[projectile].autonomous_fire_distance, + ); + if !within_firing_distance(hull_position, to, distance) { + return false; + } let Some(from) = poses.muzzle(state, weapon.component_index, barrel) else { missing += 1; return false; @@ -659,6 +705,24 @@ impl AutoDemoCombat { } } +fn firing_distance(weapon: f32, projectile: f32) -> f32 { + // Control+0x297e0 overrides the weapon's selector 8 with a positive + // value from the projectile's owner profile. + if projectile > 0.0 { + projectile + } else { + weapon.max(0.0) + } +} + +fn within_firing_distance(from: [f32; 3], to: [f32; 3], range: f32) -> bool { + if range <= 0.0 || !range.is_finite() { + return false; + } + let distance_sq: f32 = (0..3).map(|axis| (to[axis] - from[axis]).powi(2)).sum(); + distance_sq <= range * range +} + fn clip_segment([start, end]: [[f32; 3]; 2], fraction: f32) -> [[f32; 3]; 2] { if fraction == 1.0 { [start, end] @@ -675,6 +739,19 @@ mod tests { use super::*; #[test] + fn autonomous_weapon_checks_projectile_range_in_three_dimensions() { + assert_eq!(firing_distance(100.0, 350.0), 350.0); + assert_eq!(firing_distance(100.0, 0.0), 100.0); + assert_eq!(firing_distance(-1.0, 0.0), 0.0); + assert!(within_firing_distance([0.0; 3], [300.0, 400.0, 0.0], 500.0)); + assert!(!within_firing_distance( + [0.0; 3], + [300.0, 400.0, 15.0], + 500.0 + )); + } + + #[test] fn visible_segment_ends_at_world_contact() { let segment = [[10.0, 20.0, 8.0], [18.0, 24.0, 0.0]]; assert_eq!( @@ -820,6 +897,7 @@ mod tests { let mut observed_aimed_turret = false; let mut observed_finished_segment = false; let mut observed_weapon_effect = false; + let mut observed_opening_shot = false; crate::collect_unit_destruction_effects(&mut engine); let mut observed_unavailable = engine.autodemo_combat.as_ref().unwrap().unavailable as u64; for now in (0..=120_000).step_by(50) { @@ -868,6 +946,8 @@ mod tests { { let AutoDemoCombatEvent::Shot { shooter, + target, + projectile, effect, effect_instance, muzzle_bits, @@ -878,6 +958,10 @@ mod tests { }; assert_eq!(flight.shooter, shooter); assert_eq!(flight.pose.position.map(f32::to_bits), muzzle_bits); + observed_opening_shot |= now <= 2_000 + && CombatObject::read(&engine.world, shooter).original_id == Some(3) + && CombatObject::read(&engine.world, target).original_id == Some(0) + && combat.projectiles[projectile].name == "bl_m_01"; if let Some(effect) = effect { assert!(effect < combat.weapon_effects().len()); let instance = effect_instance.expect("shot names its prepared effect row"); @@ -948,6 +1032,10 @@ mod tests { assert_eq!(total.first_ms, now); assert_eq!(total.count, 1); assert!(observed_shots > 0); + assert!( + observed_opening_shot, + "the stock laser can reach the opposite flank" + ); assert!(observed_aimed_turret, "no stock turret tracked its target"); assert!( observed_finished_segment, diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index 35cd797b..2ee681af 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -120,6 +120,9 @@ authoring API без динамического подтверждения. явные заглушки исследований сохраняются отдельными счётчиками. Свободный вооружённый варбот может защищаться с места. `unit_behavior_stub` остаётся для базовой задачи Behavior, включая выбор цели и преследование. +Орудие использует дальность из CTL оружия и профиля снаряда. Выбор ближайшей +цели в этой дальности приближённый. Дополнительный предел из интерфейса +`0x204` и угол допуска выстрела пока открыты. `mission_patrol_points_approx` считает цели, списки и проверки областей по ID: начальные состояния RNG, порядок владельцев и наземная проходимость приближённые. `mission_patrol_points_stub` считает обновления без границ карты или `CanFly`. diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index d39ccc05..85e2054e 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -2664,6 +2664,14 @@ FParkan обновляет позу ствола перед расчётом еÐ точка `(1, 2, 3)` при масштабе `(2, 3, 4)`, повороте на 90° вокруг Z и переносе `(20, 30, 40)` даёт `(14, 32, 52)`. +Дальность выстрела задаёт устройство оружия. Если слово 22 профиля +снаряда положительно, `Control.dll+0x297e0` подставляет его в селектор 8 +орудия. Ветка `0x29e23` сравнивает квадрат этой дальности с квадратом +расстояния до цели по трём осям. Например, `bl_m_01` в штатном AutoDemo +передаёт 1000 единиц, а `bm_l_01` в той же машине передаёт 350. +Огонь на этой дистанции возможен, пока корпус идёт по своему маршруту. +FParkan отдельно проверяет, пора ли корпусу остановиться для атаки. + Проверка рельефа начинается у выбранного ствола, поэтому низкий гребень перед корпусом не закрывает орудие, установленное выше него. Цель переводится в систему координат крепления башни. Две строки CTLD связывают азимут и @@ -3237,8 +3245,10 @@ FParkan берёт векторы ширины и длины как полуос 0,33–0,54 секунды. В одном запуске первая машина исчерпала корневой запас через 29,36 секунды и в тот же тик вызвала новое пополнение. Измерение истощения использует ветвь `0x110b1` для корня мобильного объекта. -В FParkan со штатного старта первый выстрел был через 19,38 секунды, -а первое уничтожение с учётом силовых полей — через 72,30 секунды. +В FParkan со штатного старта первым стреляет варбот 3 по варботу 0. +Расстояние между ними около 405 единиц. Выстрел происходит через +0,15 секунды, а первое уничтожение с учётом силовых полей — через +23,43 секунды. Вызов атаки `Behavior.dll+0x25320` до первого выстрела оригинала не наблюдался, поэтому время само по себе не задаёт правило выбора цели. @@ -3254,9 +3264,9 @@ FParkan выпустил первого робота клана противни к GOG `Control.dll` с SHA-256 `bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e`. -В FParkan стоящий рядом с заводом варбот игрока стреляет по подошедшему -захватчику на 166,90 секунде от старта. Поле и корпус захватчика истощаются -к 174,45 секунде. Полный обмен огнём и хронология захвата ещё открыты. +В FParkan стоящий рядом с заводом варбот игрока впервые стреляет +на 88,73 секунде от старта. Ближайший захватчик погибает на 171,08 секунде. +Полный обмен огнём и хронология захвата ещё открыты. В записи сохраняются исходный ID объекта, слот и поколение. Поколение |
