diff options
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/fparkan-runtime/src/builder_supply.rs | 188 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/construction.rs | 184 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 10 |
3 files changed, 350 insertions, 32 deletions
diff --git a/crates/fparkan-runtime/src/builder_supply.rs b/crates/fparkan-runtime/src/builder_supply.rs new file mode 100644 index 00000000..52a29e5e --- /dev/null +++ b/crates/fparkan-runtime/src/builder_supply.rs @@ -0,0 +1,188 @@ +use crate::{unit_patrol::UnitPatrol, BehaviorOreState}; +use fparkan_world::{ + identity_metadata, registration_sequence, transform_state, ObjectHandle, OwnerId, World, +}; + +// Behavior.dll config constructor RVA 0x16250 and build task RVA 0x28ff0. +const BUILDING_COST_THRESHOLD: f32 = 100.0; +const LOADING_RATE: f32 = 100.0; + +pub(super) struct BuilderSupply { + pub(super) source: ObjectHandle, + last_ms: Option<u32>, +} + +impl BuilderSupply { + pub(super) fn plan( + world: &World, + ores: &[BehaviorOreState], + builder: ObjectHandle, + owner: OwnerId, + class: u32, + stock: f32, + ) -> Result<Option<Self>, String> { + if class == crate::mining::MINE_CLASS || stock >= BUILDING_COST_THRESHOLD { + return Ok(None); + } + let source = source(world, ores, builder, owner).ok_or("builder has no ore source")?; + Ok(Some(Self { + source, + last_ms: None, + })) + } + + pub(super) fn tick( + &mut self, + world: &World, + ores: &mut [BehaviorOreState], + patrol: &mut Option<UnitPatrol>, + builder: ObjectHandle, + owner: OwnerId, + cost: f32, + now_ms: u32, + ) -> Result<bool, String> { + let elapsed = self.last_ms.map_or(0, |last| now_ms.wrapping_sub(last)); + self.last_ms = Some(now_ms); + if !owned(world, self.source, owner) { + self.source = + source(world, ores, builder, owner).ok_or("builder lost its ore source")?; + } + let target = ores + .iter() + .position(|ore| ore.handle == self.source) + .ok_or("builder ore source is unavailable")?; + let cargo = ores + .iter() + .position(|ore| ore.handle == builder) + .ok_or("builder ore state is unavailable")?; + let [x, y, _] = transform_state(world, builder) + .map_err(|err| err.to_string())? + .position + .map(f32::from_bits); + let [a, b, _] = transform_state(world, self.source) + .map_err(|err| err.to_string())? + .position + .map(f32::from_bits); + let distance = (x - a).hypot(y - b); + let moving = patrol + .as_ref() + .is_some_and(|patrol| patrol.is_moving_to_destination(builder)); + // shortcut: use an exterior approach until native dock and port movement are wired. + if distance > 48.0 { + if !moving { + let offset = 40.0 / distance; + patrol.get_or_insert_with(UnitPatrol::scripted).move_to( + world, + builder, + [a + (x - a) * offset, b + (y - b) * offset], + false, + ); + eprintln!( + "script_builder_supply_route clan={} builder={} source={} queue_time_ms={now_ms}", + owner.0, builder.slot, self.source.slot + ); + } + return Ok(false); + } + if let Some(patrol) = patrol { + patrol.clear_move(builder); + } + let stock = f32::from_bits(ores[cargo].current_ore_bits); + let available = f32::from_bits(ores[target].current_ore_bits); + if !stock.is_finite() || !available.is_finite() { + return Err("builder supply contains non-finite ore".into()); + } + let amount = batch(stock, available, cost, elapsed); + ores[target].current_ore_bits = (available - amount).to_bits(); + let collected = stock + amount; + ores[cargo].current_ore_bits = collected.to_bits(); + Ok(collected >= cost) + } +} + +fn owned(world: &World, handle: ObjectHandle, owner: OwnerId) -> bool { + registration_sequence(world, handle) + .ok() + .flatten() + .is_some() + && identity_metadata(world, handle).is_ok_and(|id| id.owner_id == Some(owner)) +} + +fn source( + world: &World, + ores: &[BehaviorOreState], + builder: ObjectHandle, + owner: OwnerId, +) -> Option<ObjectHandle> { + let from = transform_state(world, builder) + .ok()? + .position + .map(f32::from_bits); + ores.iter() + .filter(|ore| { + matches!(ore.class_flags, crate::mining::MINE_CLASS | 0x8000_0008) + && eligible_source(f32::from_bits(ore.current_ore_bits)) + && owned(world, ore.handle, owner) + }) + .filter_map(|ore| { + let to = transform_state(world, ore.handle) + .ok()? + .position + .map(f32::from_bits); + let distance = (from[0] - to[0]) + .hypot(from[1] - to[1]) + .hypot(from[2] - to[2]); + distance.is_finite().then_some((ore.handle, distance)) + }) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(handle, _)| handle) +} + +fn eligible_source(stock: f32) -> bool { + stock.is_finite() && stock > BUILDING_COST_THRESHOLD * 1.5 +} + +fn batch(stock: f32, available: f32, cost: f32, elapsed_ms: u32) -> f32 { + let missing = (cost - stock).max(0.0); + let limit = elapsed_ms as f32 * 0.001 * LOADING_RATE; + limit.min(available).min(missing) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn native_start_uses_the_fixed_threshold_and_bypasses_supply_for_a_mine() { + let world = fparkan_world::new(fparkan_world::WorldConfig); + let builder = ObjectHandle { + slot: 0, + generation: 0, + }; + for (class, stock) in [(0x8000_0010, 100.0), (crate::mining::MINE_CLASS, 0.0)] { + assert!( + BuilderSupply::plan(&world, &[], builder, OwnerId(1), class, stock) + .unwrap() + .is_none() + ); + } + assert!( + matches!(BuilderSupply::plan(&world, &[], builder, OwnerId(1), 0x8000_0010, 99.0), Err(reason) if reason == "builder has no ore source") + ); + } + + #[test] + fn native_loading_stops_at_the_price_or_available_ore() { + for (stock, available, cost, elapsed, expected) in [ + (0.0, 1000.0, 770.0, 1000, 100.0), + (700.0, 1000.0, 770.0, 1000, 70.0), + (0.0, 10.0, 770.0, 1000, 10.0), + (800.0, 1000.0, 770.0, 1000, 0.0), + (-670.0, 1000.0, 560.0, 1000, 100.0), + ] { + assert_eq!(batch(stock, available, cost, elapsed), expected); + } + assert!(!eligible_source(150.0)); + assert!(eligible_source(150.01)); + } +} diff --git a/crates/fparkan-runtime/src/construction.rs b/crates/fparkan-runtime/src/construction.rs index 571617b3..2061b446 100644 --- a/crates/fparkan-runtime/src/construction.rs +++ b/crates/fparkan-runtime/src/construction.rs @@ -45,6 +45,7 @@ pub(super) struct Construction { first_slot: usize, controls: Vec<crate::MissionControlDeviceTableState>, tasks: Vec<Task>, + pub(super) supply_orders: std::collections::BTreeMap<(u16, u32, u32), u64>, } struct Task { @@ -55,6 +56,7 @@ struct Task { position: [f32; 3], cost: f32, arrived_at: Option<u32>, + supply: Option<crate::builder_supply::BuilderSupply>, } impl Construction { @@ -66,6 +68,7 @@ impl Construction { first_slot, controls, tasks: Vec::new(), + supply_orders: Default::default(), } } @@ -104,7 +107,18 @@ impl Construction { class: u32, position: [f32; 3], cost: f32, + supply: Option<crate::builder_supply::BuilderSupply>, ) { + if let Some(supply) = &supply { + *self + .supply_orders + .entry((owner.0, builder.slot, supply.source.slot)) + .or_default() += 1; + eprintln!( + "sim_coverage script_builder_supply_approx=1 clan={} builder={} source={}", + owner.0, builder.slot, supply.source.slot + ); + } self.tasks.push(Task { builder, owner, @@ -113,6 +127,7 @@ impl Construction { position, cost, arrived_at: None, + supply, }); } } @@ -170,19 +185,22 @@ pub(super) fn order( .map_err(|err| err.to_string())? .ore; let stock = f32::from_bits(cargo.current_ore_bits); - // shortcut: require ore onboard until the builder can fetch it from a warehouse. - if !stock.is_finite() || stock < cost { - return Err("builder has insufficient ore".into()); + if !stock.is_finite() { + return Err("builder has non-finite ore".into()); } + let supply = + crate::builder_supply::BuilderSupply::plan(world, ores, builder, owner, class, stock)?; let from = transform_state(world, builder) .map_err(|err| err.to_string())? .position .map(f32::from_bits); let position = destination(terrain, from, xy).ok_or("no route to the building site")?; - patrol - .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted) - .move_to(world, builder, [position[0], position[1]], false); - construction.start(builder, owner, slot, class, position, cost); + if supply.is_none() { + patrol + .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted) + .move_to(world, builder, [position[0], position[1]], false); + } + construction.start(builder, owner, slot, class, position, cost, supply); Ok(()) } @@ -205,25 +223,62 @@ pub(super) fn tick( .ok() .filter(|_| owned && running) { - let [x, y, _] = pose.position.map(f32::from_bits); - let [a, b, _] = task.position; - if (x - a).hypot(y - b) > ARRIVAL_RADIUS { - task.arrived_at = None; - if mission - .unit_patrol - .as_ref() - .is_some_and(|patrol| patrol.is_moving_to_destination(task.builder)) - { - index += 1; - continue; + if let Some(supply) = &mut task.supply { + match supply.tick( + world, + &mut mission.behavior_ore_states, + &mut mission.unit_patrol, + task.builder, + task.owner, + task.cost, + now_ms, + ) { + Ok(ready) => { + if ready { + task.supply = None; + mission + .unit_patrol + .get_or_insert_with(crate::unit_patrol::UnitPatrol::scripted) + .move_to( + world, + task.builder, + [task.position[0], task.position[1]], + false, + ); + eprintln!( + "script_builder_supplied clan={} builder={} queue_time_ms={now_ms}", + task.owner.0, task.builder.slot + ); + } + index += 1; + continue; + } + Err(reason) => eprintln!( + "script_builder_supply_failed clan={} builder={} reason={reason}", + task.owner.0, task.builder.slot + ), } } else { - let arrived_at = *task.arrived_at.get_or_insert(now_ms); - if now_ms.wrapping_sub(arrived_at) < WAIT_MS { - index += 1; - continue; + let [x, y, _] = pose.position.map(f32::from_bits); + let [a, b, _] = task.position; + if (x - a).hypot(y - b) > ARRIVAL_RADIUS { + task.arrived_at = None; + if mission + .unit_patrol + .as_ref() + .is_some_and(|patrol| patrol.is_moving_to_destination(task.builder)) + { + index += 1; + continue; + } + } else { + let arrived_at = *task.arrived_at.get_or_insert(now_ms); + if now_ms.wrapping_sub(arrived_at) < WAIT_MS { + index += 1; + continue; + } + finish = true; } - finish = true; } } let task = mission.construction.tasks.remove(index); @@ -250,9 +305,9 @@ fn complete( let index = crate::behavior_ore_index_for_handle(&mission.behavior_ore_states, task.builder) .map_err(crate::EngineError::Production)?; let stock = f32::from_bits(mission.behavior_ore_states[index].current_ore_bits); - if !stock.is_finite() || stock < task.cost { + if !stock.is_finite() { return Err(crate::EngineError::Production( - "builder has insufficient ore".into(), + "builder has non-finite ore".into(), )); } let [x, y, _] = task.position; @@ -353,6 +408,75 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] + fn licensed_stock_builder_resupplies_and_finishes_another_building() { + let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap(); + let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(root)))).unwrap(); + load_gameplay_mission( + &mut engine, + MissionRequest { + key: "MISSIONS/Single.02/data.tma".into(), + mode: MissionMode::SingleMission, + }, + MissionStartupInput { + queue_time_ms: 0, + research_creation_gate: false, + }, + None, + ) + .unwrap(); + let mut supplied = None; + for now in (0..=900_000).step_by(100) { + crate::frame(&mut engine, now).unwrap(); + let loaded = engine.loaded.as_ref().unwrap(); + assert!(loaded.clan_ai_events.stops().next().is_none()); + if supplied.is_none() { + if let Some(task) = loaded + .construction + .tasks + .iter() + .find(|task| task.supply.is_some()) + { + let source = task.supply.as_ref().unwrap().source; + assert_eq!( + identity_metadata(&engine.world, source).unwrap().owner_id, + Some(task.owner) + ); + let ore = loaded + .behavior_ore_states + .iter() + .find(|ore| ore.handle == task.builder) + .unwrap(); + assert!(f32::from_bits(ore.current_ore_bits) < 100.0); + supplied = Some(( + loaded.object_drafts[task.slot].original_id.unwrap(), + task.builder, + )); + } + } + if let Some((id, builder)) = supplied { + if let Some(building) = handle_by_original_id(&engine.world, id) { + assert_eq!( + identity_metadata(&engine.world, building).unwrap().owner_id, + identity_metadata(&engine.world, builder).unwrap().owner_id + ); + assert!(loaded + .construction + .supply_orders + .keys() + .any(|&(_, slot, _)| slot == builder.slot)); + println!( + "stock builder {} resupplied and completed {} at {now} ms", + builder.slot, building.slot + ); + return; + } + } + } + panic!("stock builders did not resupply and complete another building"); + } + + #[test] + #[ignore = "requires licensed corpus"] fn licensed_stock_clan_builds_a_working_factory() { let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap(); let vfs = Arc::new(DirectoryVfs::new(root)); @@ -426,7 +550,7 @@ mod tests { #[test] #[ignore = "requires licensed corpus"] - fn tower_order_rejects_unresearched_parts_and_spawns_when_available() { + fn tower_order_rejects_unresearched_parts_and_preserves_native_ore_debt() { let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").unwrap(); let vfs = Arc::new(DirectoryVfs::new(root)); let mut engine = create(EngineServices::new(vfs.clone())).unwrap(); @@ -494,17 +618,13 @@ mod tests { .contains("unavailable for construction")); let table = crate::research::load_technology_table(vfs.as_ref(), &mission.mission, owner).unwrap(); - // Set up a supplied builder after testing the unchanged mission's research gate. + // Debug setup isolates the native payment rule after the stock research gate. for component in &mission.object_drafts[slot].unit_components { if let Some(row) = table.find_key(&component.resource_raw).unwrap() { mission.free_research.learned.insert((owner, row)); } } - assert_eq!( - order_for(mission, &engine.world).unwrap_err(), - "builder has insufficient ore" - ); - let stock_before = 2000.0_f32; + let stock_before = 500.0_f32; mission.behavior_ore_states[builder_ore].current_ore_bits = stock_before.to_bits(); order_for(mission, &engine.world).unwrap(); assert!(mission.construction.active(builder)); diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index b1e63120..10e8e2a0 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -43,6 +43,7 @@ use std::sync::Arc; mod autodemo; mod boarding; +mod builder_supply; mod building_door; mod clan_ai_events; mod clan_area_strength; @@ -2939,6 +2940,7 @@ pub struct SimulationReport { pub script_class_limit_queries: Vec<(usize, u32, bool, u64)>, pub script_mine_queries: Vec<(usize, u32, u32, u32, u64)>, pub script_construction_orders: Vec<(usize, u32, u32, u64, u64)>, + pub script_builder_supplies: Vec<(u16, u32, u32, u64)>, pub script_capturer_queries: Vec<(usize, u64)>, pub script_capture_approaches: Vec<(u32, u32, u64)>, /// First factory completion by clan, in milliseconds. @@ -3004,6 +3006,7 @@ pub fn simulate_mission_report( script_class_limit_queries: Vec::new(), script_mine_queries: Vec::new(), script_construction_orders: Vec::new(), + script_builder_supplies: Vec::new(), script_capturer_queries: Vec::new(), script_capture_approaches: Vec::new(), first_factory_completion_ms: Default::default(), @@ -3155,6 +3158,13 @@ pub fn simulate_mission_report( report .script_construction_orders .extend(loaded.clan_ai_events.construction_orders()); + report.script_builder_supplies.extend( + loaded + .construction + .supply_orders + .iter() + .map(|(&(clan, builder, source), &count)| (clan, builder, source, count)), + ); report .script_capturer_queries .extend(loaded.clan_ai_events.capturer_queries()); |
