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
|
use super::{transform_state, Engine, EngineError, StartingCockpit, SurfaceQuery, TransformState};
use crate::TerrainWorld;
use fparkan_resource::{resource_name, CachedResourceRepository, ResourceRepository};
pub(super) fn warbot_can_fly(engine: &crate::Engine, object_index: usize) -> bool {
let profile = || {
let draft = engine.loaded.as_ref()?.object_drafts.get(object_index)?;
let chassis = draft.unit_components.first()?;
let archive = crate::bounded_ascii_c_string(&chassis.archive_raw)?;
let registry_path = crate::normalize_engine_path("chassis archive", &archive).ok()?;
let resources = CachedResourceRepository::new(engine.services.vfs.as_ref()?.clone());
let registry = resources.open_archive(®istry_path).ok()?;
let name = crate::bounded_ascii_c_string(&chassis.resource_raw)?;
let entry = resources
.find(registry, &resource_name(name.as_bytes()))
.ok()??;
let references =
fparkan_prototype::decode_registry_entry(resources.read(entry).ok()?.as_slice())
.ok()?;
// AniMesh supplies the sixth resource pair to CreateBehaviour.
let profile = references.get(5)?;
let archive = crate::bounded_ascii_c_string(&profile.archive_raw)?;
let path = crate::normalize_engine_path("chassis profile archive", &archive).ok()?;
let name = crate::bounded_ascii_c_string(&profile.resource_raw)?;
let archive = resources.open_archive(&path).ok()?;
let entry = resources
.find(archive, &resource_name(name.as_bytes()))
.ok()??;
fparkan_assets::decode_chassis_can_fly(resources.read(entry).ok()?.as_slice()).ok()?
};
profile().unwrap_or_else(|| {
eprintln!("sim_coverage player_chassis_profile_stub=1 object={object_index}");
false
})
}
// shortcut: bound stair steps and drops until the native hero collider is wired.
const STEP_UP: f32 = 0.85;
const STEP_DOWN: f32 = 2.0;
// shortcut: sample the temporary floor probe at most 0.16 units apart until native collision is wired.
const WALK_COLLISION_INTERVAL: f32 = 0.02;
/// Player controls sampled once for a simulation step.
#[derive(Clone, Copy, Debug, Default)]
pub struct PlayerMotion {
/// Signed strafe and forward input in the range -1 to 1.
pub movement: [f32; 2],
/// Signed climb input for a flying vehicle, in the range -1 to 1.
pub climb: f32,
/// Relative horizontal mouse motion for this step.
pub mouse_x: f32,
/// Relative vertical mouse motion for this step, positive down.
pub mouse_y: f32,
/// Time spent on this simulation step, excluding time spent paused.
pub delta_seconds: f32,
}
/// Proposed hero transform and the body-level sweep used to check buildings.
#[derive(Clone, Copy, Debug)]
pub struct PlayerMotionStep {
pub(super) pose: TransformState,
pub(super) pitch_bits: u32,
flying: bool,
terrain_height: Option<f32>,
/// Sweep segment when the step translates the hero.
pub sweep: Option<[[f32; 3]; 2]>,
}
impl PlayerMotionStep {
/// Vertical segment for finding a nearby building floor at the proposed XY.
#[must_use]
pub fn floor_probe(self) -> Option<[[f32; 3]; 2]> {
if self.flying {
return None;
}
let [[_, _, start_z], [x, y, _]] = self.sweep?;
let feet_z = start_z - 0.5;
Some([[x, y, feet_z + STEP_UP], [x, y, feet_z - STEP_DOWN]])
}
/// Terrain can take over at the end of a floor within the same step limits.
#[must_use]
pub fn terrain_exit_floor(self) -> Option<(f32, [[f32; 3]; 2])> {
let [top, bottom] = self.floor_probe()?;
let [start, end] = self.sweep?;
let height = self.terrain_height?;
let [x, y, body_z] = start;
((bottom[2]..=top[2]).contains(&height) && (end[2] - (height + 0.52)).abs() > 0.05)
.then_some((height, [[x, y, body_z - 0.45], [x, y, body_z - 0.60]]))
}
/// Places the player's feet just above a floor accepted by the scene query.
#[must_use]
pub fn with_building_floor(mut self, height: f32) -> Self {
if let Some(sweep) = &mut self.sweep {
self.pose.position[2] = (height + 0.02).to_bits();
sweep[1][2] = height + 0.52;
}
self
}
/// Sweeps vertically before crossing a step up, and horizontally before a step down.
#[must_use]
pub fn floor_sweeps(self) -> Option<[[[f32; 3]; 2]; 2]> {
let [start, end] = self.sweep?;
let middle = if end[2] > start[2] {
[start[0], start[1], end[2]]
} else {
[end[0], end[1], start[2]]
};
Some([[start, middle], [middle, end]])
}
}
#[cfg(test)]
mod tests {
use super::{PlayerMotionStep, TransformState};
#[test]
fn building_floor_probe_uses_proposed_xy_and_previous_height() {
let step = PlayerMotionStep {
pose: TransformState {
position: [4.0_f32, 6.0, 15.0].map(f32::to_bits),
..TransformState::default()
},
pitch_bits: 0,
flying: false,
terrain_height: Some(11.5),
sweep: Some([[3.0, 6.0, 12.5], [4.0, 6.0, 15.5]]),
};
assert_eq!(
step.floor_probe(),
Some([[4.0, 6.0, 12.85], [4.0, 6.0, 10.0]])
);
assert_eq!(
step.terrain_exit_floor().map(|(height, _)| height),
Some(11.5)
);
let lowered = step.with_building_floor(11.5);
assert_eq!(lowered.pose.position.map(f32::from_bits), [4.0, 6.0, 11.52]);
assert_eq!(lowered.sweep.unwrap()[1], [4.0, 6.0, 12.02]);
assert_eq!(
lowered.floor_sweeps().unwrap(),
[
[[3.0, 6.0, 12.5], [4.0, 6.0, 12.5]],
[[4.0, 6.0, 12.5], [4.0, 6.0, 12.02]],
]
);
assert_eq!(
step.with_building_floor(12.5).floor_sweeps().unwrap()[0],
[[3.0, 6.0, 12.5], [3.0, 6.0, 13.02]]
);
}
}
/// Proposes a hero step from the world pose and the active terrain.
///
/// # Errors
///
/// Returns an error for invalid motion values or a failed terrain query.
pub fn plan_player_motion(
engine: &Engine,
cockpit: StartingCockpit,
input: PlayerMotion,
) -> Result<Option<PlayerMotionStep>, EngineError> {
plan_player_steps(engine, cockpit, input, None)
}
/// Resolves walking in short sweeps and returns the last reachable pose for this frame.
///
/// # Errors
/// Returns an error if motion or the scene collision query fails.
pub fn plan_player_motion_with_collision(
engine: &Engine,
cockpit: StartingCockpit,
input: PlayerMotion,
mut resolve: impl FnMut(PlayerMotionStep) -> Result<(PlayerMotionStep, bool), EngineError>,
) -> Result<Option<PlayerMotionStep>, EngineError> {
plan_player_steps(engine, cockpit, input, Some(&mut resolve))
}
type ResolveMotion<'a> =
&'a mut dyn FnMut(PlayerMotionStep) -> Result<(PlayerMotionStep, bool), EngineError>;
fn plan_player_steps(
engine: &Engine,
cockpit: StartingCockpit,
mut input: PlayerMotion,
resolve: Option<ResolveMotion<'_>>,
) -> Result<Option<PlayerMotionStep>, EngineError> {
let (Some(mission), Ok(pose)) = (
&engine.loaded,
transform_state(&engine.world, cockpit.handle),
) else {
return Ok(None);
};
let flying = mission
.boarding
.is_some_and(|boarding| boarding.cockpit.handle == cockpit.handle && boarding.can_fly);
if input.movement == [0.0; 2]
&& (!flying || input.climb == 0.0)
&& input.mouse_x == 0.0
&& input.mouse_y == 0.0
{
return Ok(None);
}
let pitch = f32::from_bits(mission.player_pitch_bits);
let Some(resolve) = resolve else {
return plan_motion(&mission.terrain, pose, pitch, flying, input).map(Some);
};
if !input.delta_seconds.is_finite() || input.delta_seconds < 0.0 {
return Err(EngineError::Movement("invalid player step".into()));
}
let count = if !flying && input.movement != [0.0; 2] {
// shortcut: bound movement after a long stall while the scene uses the render clock.
input.delta_seconds = input.delta_seconds.min(0.5);
(input.delta_seconds / WALK_COLLISION_INTERVAL).ceil() as u32
} else {
1
}
.max(1);
input.delta_seconds /= count as f32;
let mut step = plan_motion(&mission.terrain, pose, pitch, flying, input)?;
let mut previous = pose;
input.mouse_x = 0.0;
input.mouse_y = 0.0;
for index in 0..count {
if index != 0 {
step = plan_motion(
&mission.terrain,
previous,
f32::from_bits(step.pitch_bits),
flying,
input,
)?;
}
let (resolved, blocked) = resolve(step)?;
step = resolved;
if blocked {
step.pose.position = previous.position;
step.sweep = None;
break;
}
previous = step.pose;
}
Ok(Some(step))
}
fn plan_motion(
terrain: &TerrainWorld,
mut pose: TransformState,
pitch: f32,
flying: bool,
input: PlayerMotion,
) -> Result<PlayerMotionStep, EngineError> {
let from = pose.position.map(f32::from_bits);
let yaw = f32::from_bits(pose.orientation[2]);
if !input
.movement
.into_iter()
.chain([
input.mouse_x,
input.mouse_y,
input.climb,
input.delta_seconds,
yaw,
pitch,
])
.chain(from)
.all(f32::is_finite)
|| input.delta_seconds < 0.0
{
return Err(EngineError::Movement("invalid player step".into()));
}
// shortcut: use constant walk speed and mouse gain until native Control
// acceleration and mouse sensitivity are measured.
let yaw = if input.mouse_x != 0.0 {
let yaw = (yaw - input.mouse_x.clamp(-1_000.0, 1_000.0) * 0.003)
.rem_euclid(std::f32::consts::TAU);
pose.orientation[2] = yaw.to_bits();
yaw
} else {
yaw
};
let [right, forward] = input.movement.map(|axis| axis.clamp(-1.0, 1.0));
// shortcut: constant flight rates until thrust, clearance and inertia are measured.
let speed = if flying { 40.0 } else { 8.0 };
let distance = speed * input.delta_seconds / right.hypot(forward).max(1.0);
let (sin, cos) = yaw.sin_cos();
let xy = [
from[0] + (cos * right - sin * forward) * distance,
from[1] + (sin * right + cos * forward) * distance,
];
let climb = if flying {
input.climb.clamp(-1.0, 1.0) * (16.0 * input.delta_seconds)
} else {
0.0
};
let altitude = from[2] + climb;
if !xy.iter().all(|axis| axis.is_finite()) || !altitude.is_finite() {
return Err(EngineError::Movement(
"player step exceeds finite coordinates".into(),
));
}
let mut sweep = None;
let mut terrain_height = None;
if flying && (xy != [from[0], from[1]] || climb != 0.0) {
let old_xy = [from[0], from[1]];
let floor = |xy| {
terrain
.height_at(xy)
.map_err(|err| EngineError::Movement(err.to_string()))
};
if let Some(old_height) = floor(old_xy)? {
let bottom = old_height + 0.02;
// A grounded machine can taxi. In the air, climb above an obstacle before crossing it.
let grounded = from[2] <= bottom && climb <= 0.0;
let floor_at_target = floor(xy)?.map(|height| height + 0.02);
let (accepted_xy, height) = match floor_at_target {
Some(floor) if grounded || floor <= altitude => (xy, floor),
_ => (old_xy, bottom),
};
let [x, y] = accepted_xy;
let to = [x, y, altitude.max(height)];
if to != from {
pose.position = to.map(f32::to_bits);
sweep = Some([
[from[0], from[1], from[2] + 0.5],
[to[0], to[1], to[2] + 0.5],
]);
}
}
} else if xy != [from[0], from[1]] {
if let (Some(old_ground), Some(new_ground)) = (
terrain
.height_at([from[0], from[1]])
.map_err(|err| EngineError::Movement(err.to_string()))?,
terrain
.height_at(xy)
.map_err(|err| EngineError::Movement(err.to_string()))?,
) {
let to = [xy[0], xy[1], new_ground + (from[2] - old_ground)];
terrain_height = Some(new_ground);
pose.position = to.map(f32::to_bits);
// shortcut: one sweep at body height until the physical collider
// and floor transitions are recovered.
sweep = Some([
[from[0], from[1], from[2] + 0.5],
[to[0], to[1], to[2] + 0.5],
]);
}
}
// shortcut: use a bounded camera aim until the native turret travel and
// sensitivity are recovered. The body remains aligned to the terrain.
let pitch = (pitch - input.mouse_y * 0.005).clamp(-1.0, 1.0);
Ok(PlayerMotionStep {
pose,
pitch_bits: pitch.to_bits(),
flying,
terrain_height,
sweep,
})
}
|