From f5f67b58d9b03945d1e22c797dd7f10e6048c4df Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Thu, 26 Nov 2026 07:35:54 +0400 Subject: fix(production): wait for a clear ground release point Validate stock completions from Single.01 with Vulkan validation and check produced hulls against live occupancy. The licensed long transport scenario still fails at storage unloading with both the previous and the new release point. --- crates/fparkan-runtime/src/factory_release.rs | 93 +++++++++++++++++++++++++++ crates/fparkan-runtime/src/lib.rs | 1 + crates/fparkan-runtime/src/production.rs | 41 +++++++++++- crates/fparkan-runtime/src/route_obstacles.rs | 14 +++- crates/fparkan-runtime/src/route_traffic.rs | 6 +- docs/appendices/knowledge-boundaries.md | 3 +- docs/tomes/06-behavior.md | 14 +++- 7 files changed, 164 insertions(+), 8 deletions(-) create mode 100644 crates/fparkan-runtime/src/factory_release.rs diff --git a/crates/fparkan-runtime/src/factory_release.rs b/crates/fparkan-runtime/src/factory_release.rs new file mode 100644 index 00000000..d6b29eda --- /dev/null +++ b/crates/fparkan-runtime/src/factory_release.rs @@ -0,0 +1,93 @@ +//! Select a free point on the ground for the current outdoor factory release. + +use crate::{ + route_obstacles::{BuildingFootprints, Footprint}, + route_traffic::{body_radius, FrameTraffic}, + EngineError, LoadedMissionState, ObjectHandle, TransformState, World, +}; +use fparkan_terrain::SurfaceQuery; + +pub(super) fn clear_release_position( + world: &World, + mission: &LoadedMissionState, + buildings: &mut BuildingFootprints, + plant: ObjectHandle, + slot: usize, + preferred: [f32; 3], +) -> Result, EngineError> { + let draft = &mission.object_drafts[slot]; + let pose = TransformState { + position: preferred.map(f32::to_bits), + orientation: draft.orientation_raw.map(f32::to_bits), + scale: draft.scale.map(f32::to_bits), + }; + buildings.refresh(world, mission); + // The outdoor approximation remains the fallback for unprepared bounds. + let (Some(plant_bounds), Some(radius)) = ( + buildings.for_handle(plant), + body_radius(&mission.mission_assets, slot, pose), + ) else { + return Ok(Some(preferred)); + }; + let mut blocked = buildings.with_clearance(radius); + let [x, y, _] = preferred; + let traffic = FrameTraffic::read(world, mission); + let Some(neighbors) = traffic.blockers(plant, [x, y], radius) else { + return Ok(None); + }; + blocked.extend(neighbors); + release_position([x, y], plant_bounds.expanded(radius), &blocked, |point| { + mission + .terrain + .height_at(point) + .map_err(EngineError::Terrain) + }) +} + +fn release_position( + preferred: [f32; 2], + plant: Footprint, + blocked: &[Footprint], + mut height_at: impl FnMut([f32; 2]) -> Result, EngineError>, +) -> Result, EngineError> { + let center = plant.center(); + let mut alternatives = Vec::from(plant.exits(center)); + alternatives.extend(plant.corners()); + let distance = |p: [f32; 2]| (p[0] - preferred[0]).hypot(p[1] - preferred[1]); + alternatives.sort_by(|&a, &b| distance(a).total_cmp(&distance(b))); + for point in std::iter::once(preferred).chain(alternatives) { + if blocked.iter().any(|bounds| bounds.contains(point)) { + continue; + } + if let Some(z) = height_at(point)? { + return Ok(Some([point[0], point[1], z + 2.0])); + } + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn release_keeps_the_preferred_clear_point_or_checks_the_factory_perimeter() { + let plant = Footprint::point([0.0; 2]).expanded(5.0); + let parked = Footprint::point([6.0, 0.0]).expanded(1.0); + let flat = |_| Ok(Some(3.0)); + assert_eq!( + release_position([7.5, 0.0], plant, &[plant, parked], flat).unwrap(), + Some([7.5, 0.0, 5.0]) + ); + let [x, y, z] = release_position([6.0, 0.0], plant, &[plant, parked], flat) + .unwrap() + .unwrap(); + assert!(!plant.contains([x, y]) && !parked.contains([x, y])); + assert_eq!(z, 5.0); + let occupied = Footprint::point([0.0; 2]).expanded(8.0); + assert_eq!( + release_position([6.0, 0.0], plant, &[occupied], flat).unwrap(), + None + ); + } +} diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index b27c0090..fa2201a0 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -96,6 +96,7 @@ mod player_motion; mod unit_speed; pub use patrol_points::PatrolPointReport; pub use unit_speed::{UnitSpeedKind, UnitSpeedReport}; +mod factory_release; mod player_status; mod player_weapon; mod production; diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index 90256903..ed39eb6a 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -4,6 +4,7 @@ use super::{ mission_events::on_communicator, normalize_engine_path, query_behavior_profile_ore_rate, research::{load_clan_table, RESEARCHED}, + route_obstacles::BuildingFootprints, set_control_device_table_selector, unit_spawn::{spawn_prepared_unit, SpawnedUnit}, BehaviorOreState, Engine, EngineError, LoadedMissionState, MissionControlDeviceTableState, @@ -72,6 +73,7 @@ pub(super) struct Production { plants: Vec<(usize, u32)>, pending: VecDeque, clock_ticks: std::collections::BTreeMap<(u16, u32), u64>, + buildings: BuildingFootprints, rng: u32, } @@ -197,6 +199,7 @@ impl Production { plants: Vec::new(), pending: VecDeque::new(), clock_ticks: Default::default(), + buildings: BuildingFootprints::default(), rng: 1, }; production.register_factories(0, &drafts[..reserve_start]); @@ -291,9 +294,9 @@ impl Production { return Ok(None); } let pose = transform_state(world, order.plant)?; - // shortcut: reuse the outdoor spawn point until the factory exit - // device and its clear-space check are available. - let position = reinforcement_position( + // shortcut: prefer the old outdoor point until the factory's elevated + // release and protected exit order are simulated. + let preferred = reinforcement_position( pose.position.map(f32::from_bits), pose.orientation.map(f32::from_bits), pose.scale.map(f32::from_bits), @@ -302,6 +305,17 @@ impl Production { &mission.terrain, &mut self.rng, )?; + let Some(position) = super::factory_release::clear_release_position( + world, + mission, + &mut self.buildings, + order.plant, + order.slot, + preferred, + )? + else { + return Ok(None); + }; let handle = spawn_prepared_unit( world, mission, @@ -925,6 +939,27 @@ mod tests { .unwrap() .produced_unit { + let pose = transform_state(&engine.world, unit.handle).unwrap(); + let [x, y, _] = pose.position.map(f32::from_bits); + let mission = engine.loaded.as_ref().unwrap(); + let radius = crate::route_traffic::body_radius( + &mission.mission_assets, + unit.object_index, + pose, + ) + .unwrap(); + let mut buildings = BuildingFootprints::default(); + buildings.refresh(&engine.world, mission); + assert!(buildings + .with_clearance(radius) + .iter() + .all(|bounds| !bounds.contains([x, y]))); + let traffic = crate::route_traffic::FrameTraffic::read(&engine.world, mission); + assert!(traffic + .blockers(unit.handle, [x, y], radius) + .unwrap() + .iter() + .all(|bounds| !bounds.contains([x, y]))); completed.push((unit.clan, unit.object_index)); } } diff --git a/crates/fparkan-runtime/src/route_obstacles.rs b/crates/fparkan-runtime/src/route_obstacles.rs index a5737399..fb029bd2 100644 --- a/crates/fparkan-runtime/src/route_obstacles.rs +++ b/crates/fparkan-runtime/src/route_obstacles.rs @@ -69,6 +69,12 @@ impl BuildingFootprints { .filter_map(|(_, _, footprint)| footprint.map(|bounds| bounds.expanded(radius))) .collect() } + + pub(super) fn for_handle(&self, handle: ObjectHandle) -> Option { + self.entries + .values() + .find_map(|&(owner, _, bounds)| (owner == handle).then_some(bounds).flatten()) + } } fn model_footprint( @@ -161,7 +167,7 @@ impl Footprint { true } - fn corners(self) -> [[f32; 2]; 4] { + pub(super) fn corners(self) -> [[f32; 2]; 4] { let Self { min: [x0, y0], max: [x1, y1], @@ -169,13 +175,17 @@ impl Footprint { [[x0, y0], [x0, y1], [x1, y0], [x1, y1]] } - fn exits(self, p: [f32; 2]) -> [[f32; 2]; 4] { + pub(super) fn exits(self, p: [f32; 2]) -> [[f32; 2]; 4] { let Self { min: [x0, y0], max: [x1, y1], } = self.expanded(CORNER_GAP); [[x0, p[1]], [x1, p[1]], [p[0], y0], [p[0], y1]] } + + pub(super) fn center(self) -> [f32; 2] { + std::array::from_fn(|axis| self.min[axis].midpoint(self.max[axis])) + } } fn distance(a: [f32; 2], b: [f32; 2]) -> f32 { diff --git a/crates/fparkan-runtime/src/route_traffic.rs b/crates/fparkan-runtime/src/route_traffic.rs index 193ea995..4aaad17d 100644 --- a/crates/fparkan-runtime/src/route_traffic.rs +++ b/crates/fparkan-runtime/src/route_traffic.rs @@ -18,7 +18,11 @@ pub(super) struct FrameTraffic { bodies: Vec, } -fn body_radius(assets: &MissionAssets, index: usize, pose: TransformState) -> Option { +pub(super) fn body_radius( + assets: &MissionAssets, + index: usize, + pose: TransformState, +) -> Option { let (center, radius) = unit_sphere(assets, index, pose)?; let [x, y, _] = pose.position.map(f32::from_bits); let radius = radius + (center[0] - x).hypot(center[1] - y); diff --git a/docs/appendices/knowledge-boundaries.md b/docs/appendices/knowledge-boundaries.md index d937c8b7..806fc074 100644 --- a/docs/appendices/knowledge-boundaries.md +++ b/docs/appendices/knowledge-boundaries.md @@ -186,7 +186,8 @@ Behavior: самостоятельная защита до получения п Здоровье и ресурсы одиночной миссии выводятся в заголовке окна. `factory_orders_approx` отмечает восемь мест для живых роботов, один заказ в -работе, типоразмеры по ключу и появление вокруг завода. Удалённый заказ +работе, типоразмеры по ключу и появление на свободном грунте снаружи завода. +Спуск с площадки и отдельная задача выезда открыты. Удалённый заказ доступен через тот же список B, пока тактический интерфейс и пакетная сборка оригинала открыты. `script_factory_clock_approx` считает допущенные шаги по клану и заводу. diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 94c567c1..9a6c3b92 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -3038,7 +3038,19 @@ RVA `0x10abc` он задаёт диапазон случайного смеще и рендеру. Следующий заказ можно дать после выпуска. Каждый робот получает свою запись мира, а после уничтожения его место можно занять новым корпусом. Если завод исчез или сменил владельца во время сборки, заказ снимается. -Положение готовой машины пока рассчитывается вокруг завода. +Готовая машина появляется на свободном грунте снаружи. Движок проверяет +проекции строений и соседних машин с запасом под ширину нового корпуса. +Если выбранная точка занята, он ищет место вдоль границы завода. Когда +подходящей точки нет, готовый заказ ждёт следующего шага завода. + +В оригинале выпуск начинается выше. Со штатного старта «Двух крепостей» +GOG `Behavior.dll` (SHA-256 из раздела выше) по RVA `0x2aa14` передала +положение первого робота `X=1824,21 Y=2032,02 Z=205,06`. Координаты на +плоскости совпали с центром завода из TMA. Высота над найденной опорой +прибавляется по RVA `0x2a9c4` и составляет 15 единиц. Вызов по RVA +`0x2aae7` поставил задачу выхода. В отдельном запуске первый приказ +после выпуска попал в очередь по RVA `0x456c`. Посадка на площадку, +выезд с неё и эффект сборки в FParkan ещё открыты. Число машин ограничивает запас «мозгов» клана. `Handler(49)` в GOG `ai.dll` (SHA-256 `c19cd6cd31cd2896f8c4ba0f0e700dd3408aec8182daaf4863d98a7d233a2abc`, -- cgit v1.2.3