1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
|
//! Health service inside the repair volumes authored on facilities.
use crate::{
initial_component_node_times, node_amount::distribute_control_node_amount,
ControlNodeDistributionMode, MissionAssets, MissionControlDeviceTableState, MissionObjectDraft,
TransformState, World,
};
use fparkan_assets::PreparedControlPoint;
use fparkan_msh::{node38_fallback_hierarchy, node38_sampled_hierarchy_at_times};
use fparkan_render::LegacyIron3dEulerTransform;
use fparkan_world::{
handle_by_original_id, identity_metadata, registration_sequence, transform_state,
OriginalObjectId, OwnerId,
};
// Behavior.dll+0x193b2 adds this fraction of total provider capacity per second.
const HEALTH_FRACTION_PER_SECOND: f32 = 0.1;
#[derive(Clone, Copy)]
struct RepairVolume {
floor: [f32; 3],
axes: [[f32; 3]; 3],
}
impl RepairVolume {
fn contains(self, local: [f32; 3]) -> bool {
let offset: [f32; 3] = std::array::from_fn(|axis| local[axis] - self.floor[axis]);
self.axes.into_iter().enumerate().all(|(axis, vector)| {
let length_sq: f32 = vector.iter().map(|component| component * component).sum();
let distance = offset
.into_iter()
.zip(vector)
.map(|(a, b)| a * b)
.sum::<f32>();
let portion = distance / length_sq;
if axis == 2 {
(0.0..=1.0).contains(&portion)
} else {
portion.abs() <= 1.0
}
})
}
}
struct Facility {
id: OriginalObjectId,
volumes: Vec<RepairVolume>,
}
#[derive(Default)]
pub(super) struct RepairZones {
facilities: Vec<Facility>,
prepared_count: usize,
}
pub(super) struct ActiveFacility<'a> {
owner: OwnerId,
matrix: [f32; 16],
scale: [f32; 3],
volumes: &'a [RepairVolume],
}
impl RepairZones {
pub(super) fn prepare(&mut self, assets: &MissionAssets, drafts: &[MissionObjectDraft]) {
if self.prepared_count > drafts.len() {
self.facilities.clear();
self.prepared_count = 0;
}
for (index, draft) in drafts.iter().enumerate().skip(self.prepared_count) {
if !draft
.unit_dat_header_flags
.is_some_and(|class| class & 0x8000_0000 != 0)
{
continue;
}
if let Some(id) = draft.original_id {
let volumes = facility_volumes(assets, index);
if !volumes.is_empty() {
self.facilities.push(Facility { id, volumes });
}
}
}
self.prepared_count = drafts.len();
}
pub(super) fn active(&self, world: &World) -> Vec<ActiveFacility<'_>> {
self.facilities
.iter()
.filter_map(|facility| {
let handle = handle_by_original_id(world, facility.id)?;
registration_sequence(world, handle).ok()??;
let owner = identity_metadata(world, handle).ok()?.owner_id?;
let pose = transform_state(world, handle).ok()?;
let scale = pose.scale.map(f32::from_bits);
if scale.contains(&0.0) {
return None;
}
let matrix = LegacyIron3dEulerTransform {
translation: pose.position.map(f32::from_bits),
orientation_radians: pose.orientation.map(f32::from_bits),
}
.try_row_major()?;
Some(ActiveFacility {
owner,
matrix,
scale,
volumes: &facility.volumes,
})
})
.collect()
}
}
fn facility_volumes(assets: &MissionAssets, index: usize) -> Vec<RepairVolume> {
let Some(control) = assets
.object_component_controls
.get(index)
.and_then(|controls| controls.first())
.and_then(Option::as_ref)
else {
return Vec::new();
};
let Some(points) = control.point_list.as_ref() else {
return Vec::new();
};
let Some(model) = assets
.visual_for_object(index)
.and_then(|id| assets.visual_by_id(id))
.and_then(|visual| visual.model_id)
.and_then(|model| assets.model_by_id(model))
else {
return Vec::new();
};
let model = &model.validated;
let Some(poses) = initial_component_node_times(model.node_count, &control.bindings)
.ok()
.and_then(|times| node38_sampled_hierarchy_at_times(model, ×))
.or_else(|| node38_fallback_hierarchy(model))
else {
return Vec::new();
};
let named = |name: &[u8]| {
points.points.iter().find(|point| {
let end = point
.name
.iter()
.position(|&b| b == 0)
.unwrap_or(point.name.len());
point.raw_flags & 0x8000_0000 != 0 && point.name[..end].eq_ignore_ascii_case(name)
})
};
let world_point = |point: &PreparedControlPoint| {
let pose = poses
.poses
.get(usize::try_from(point.raw_signed_field_04).ok()?)?;
let origin = pose.transform_point(point.position);
let end = pose.transform_point(std::array::from_fn(|axis| {
point.position[axis] + point.direction[axis]
}));
let axis = std::array::from_fn(|i| end[i] - origin[i]);
Some((origin, axis))
};
[
[b"rech_w".as_slice(), b"rech_h", b"rech_d"],
[b"rech_w_i", b"rech_h_i", b"rech_d_i"],
]
.into_iter()
.filter_map(|[w, h, d]| {
let (_, width) = world_point(named(w)?)?;
let (_, length) = world_point(named(h)?)?;
let (floor, up) = world_point(named(d)?)?;
Some(RepairVolume {
floor,
axes: [width, length, up],
})
})
.collect()
}
pub(super) fn service_unit(
table: &mut MissionControlDeviceTableState,
world: &World,
pose: TransformState,
facilities: &[ActiveFacility<'_>],
seconds: f32,
) {
if table.node_provider_depletion_marked || seconds <= 0.0 {
return;
}
let Some(owner) = identity_metadata(world, table.handle)
.ok()
.and_then(|meta| meta.owner_id)
else {
return;
};
let position = pose.position.map(f32::from_bits);
let in_service = facilities
.iter()
.filter(|site| site.owner == owner)
.any(|site| {
let m = &site.matrix;
let [x, y, z] = [position[0] - m[3], position[1] - m[7], position[2] - m[11]];
let local =
std::array::from_fn(|i| (m[i] * x + m[i + 4] * y + m[i + 8] * z) / site.scale[i]);
site.volumes.iter().any(|volume| volume.contains(local))
});
if in_service {
let fraction = seconds * HEALTH_FRACTION_PER_SECOND;
repair_nodes(table, fraction);
crate::weapon_resupply::refill(&mut table.status, fraction);
}
}
fn repair_nodes(table: &mut MissionControlDeviceTableState, fraction: f32) {
let Some((amount, maximum)) = table
.node_provider_amount_bits
.zip(table.node_provider_maximum_amount_bits)
.map(|(amount, maximum)| (f32::from_bits(amount), f32::from_bits(maximum)))
else {
return;
};
if 0.0 < amount && amount < maximum {
let target = (amount / maximum + fraction).min(1.0);
let _ = distribute_control_node_amount(
table,
target * maximum - amount,
ControlNodeDistributionMode::Sequential,
true,
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
apply_loaded_mission_control_node_delta, create, frame, load_gameplay_mission,
starting_cockpit, starting_player_weapons, EngineServices, MissionControlDeviceTableStatus,
MissionMode, MissionRequest, MissionStartupInput,
};
use fparkan_vfs::DirectoryVfs;
use fparkan_world::{set_owner, set_transform};
use std::sync::Arc;
#[test]
fn repair_volume_extends_up_from_the_deck_and_uses_its_two_lateral_axes() {
let area = RepairVolume {
floor: [10.0, 20.0, 30.0],
axes: [[0.0, 4.0, 0.0], [-3.0, 0.0, 0.0], [0.0, 0.0, 5.0]],
};
assert!(area.contains([8.0, 23.0, 30.0]));
assert!(area.contains([12.0, 17.0, 34.0]));
assert!(!area.contains([8.0, 23.0, 29.0]));
assert!(!area.contains([8.0, 25.0, 34.0]));
}
#[test]
#[ignore = "requires licensed corpus"]
fn licensed_constructor_repairs_the_hero_at_friendly_authored_pads() {
licensed_repair_pads(
"MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.02/data.tma",
&[0x8000_0010, 0x8000_0040],
);
}
#[test]
#[ignore = "requires licensed corpus"]
fn licensed_fortresses_repairs_the_hero_at_fort_and_generator_pads() {
licensed_repair_pads("MISSIONS/Single.01/data.tma", &[0x8002_0000, 0x8000_0002]);
}
fn licensed_repair_pads(key: &str, classes: &[u32]) {
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: key.into(),
mode: MissionMode::SingleMission,
},
MissionStartupInput {
queue_time_ms: 0,
research_creation_gate: false,
},
None,
)
.unwrap();
let cockpit = starting_cockpit(&engine).unwrap();
let hero = cockpit.handle;
let mut cockpit_weapons = starting_player_weapons(&engine, cockpit);
let slot = cockpit_weapons
.weapons()
.iter()
.position(|weapon| weapon.rounds_remaining().is_some_and(|rounds| rounds > 0))
.unwrap();
let weapon = &cockpit_weapons.weapons()[slot];
let component = weapon.component_index;
let record = weapon.control_record_index;
let initial_pose = transform_state(&engine.world, hero).unwrap();
let read_node = |engine: &crate::Engine, key| {
let table = engine
.loaded
.as_ref()
.unwrap()
.control_device_tables
.iter()
.find(|table| table.handle == hero)
.unwrap();
let row = crate::control_node_provider_row(table, key).unwrap();
(
f32::from_bits(row.current_amount_bits),
row.source_row.max_volume,
)
};
for (case, &class) in classes.iter().enumerate() {
let start = case as u32 * 3000;
let mission = engine.loaded.as_ref().unwrap();
let (index, draft) = mission
.object_drafts
.iter()
.enumerate()
.find(|(_, draft)| draft.unit_dat_header_flags == Some(class))
.unwrap();
let facility =
handle_by_original_id(&engine.world, draft.original_id.unwrap()).unwrap();
let zone = facility_volumes(&mission.mission_assets, index)[0];
let floor = std::array::from_fn(|axis| zone.floor[axis] + zone.axes[2][axis] * 0.5);
let pose = transform_state(&engine.world, facility).unwrap();
let world = LegacyIron3dEulerTransform {
translation: pose.position.map(f32::from_bits),
orientation_radians: pose.orientation.map(f32::from_bits),
};
let mut actor = initial_pose;
actor.position = world
.try_transform_scaled_point(floor, pose.scale.map(f32::from_bits))
.unwrap()
.map(f32::to_bits);
// Exercise the hull first, then a damaged component with a full hull.
let damage_key = u32::from(case != 0);
if damage_key != 0 {
let (amount, maximum) = read_node(&engine, 0);
apply_loaded_mission_control_node_delta(&mut engine, hero, 0, maximum - amount)
.unwrap();
}
let (health, max) = read_node(&engine, damage_key);
apply_loaded_mission_control_node_delta(
&mut engine,
hero,
damage_key,
max * 0.5 - health,
)
.unwrap();
let damaged = read_node(&engine, damage_key).0;
let table = engine
.loaded
.as_mut()
.unwrap()
.control_device_tables
.iter_mut()
.find(|table| table.handle == hero)
.unwrap();
let MissionControlDeviceTableStatus::Available(devices) = &mut table.status else {
panic!("hero device table unavailable");
};
let device = devices
.iter_mut()
.find(|device| {
device.factory_provenance.unit_component_index == component
&& device.factory_provenance.typed_record_index == record
})
.unwrap();
device.weapon_rounds = Some(0);
set_transform(&mut engine.world, hero, actor).unwrap();
set_owner(&mut engine.world, facility, Some(OwnerId(1))).unwrap();
frame(&mut engine, start).unwrap();
frame(&mut engine, start + 1000).unwrap();
assert_eq!(read_node(&engine, damage_key).0, damaged);
cockpit_weapons.read_control_energy(&engine, hero);
assert_eq!(cockpit_weapons.weapons()[slot].rounds_remaining(), Some(0));
set_owner(&mut engine.world, facility, Some(OwnerId(0))).unwrap();
frame(&mut engine, start + 2000).unwrap();
let repaired = read_node(&engine, damage_key).0;
assert!(repaired > damaged && repaired <= max);
cockpit_weapons.read_control_energy(&engine, hero);
let rounds = cockpit_weapons.weapons()[slot].rounds_remaining().unwrap();
assert!(rounds > 0);
set_transform(&mut engine.world, hero, initial_pose).unwrap();
frame(&mut engine, start + 3000).unwrap();
assert_eq!(read_node(&engine, damage_key).0, repaired);
cockpit_weapons.read_control_energy(&engine, hero);
assert_eq!(
cockpit_weapons.weapons()[slot].rounds_remaining(),
Some(rounds)
);
}
}
}
|