aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/player_collision.rs
blob: 6eba3cadd916cf4f51bf828f0eaad1a5a64e77df (plain) (blame)
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! Building geometry queries shared by walking and the preview camera.

use super::{
    damage_visibility::{building_provider_rows, visible_node_stage},
    multiply_row_major, rotate_unit_vector, StaticVulkanApp,
};
use fparkan_animation::NodePoseBuffer;
use fparkan_msh::{selected_slot, Group, Lod, ModelAsset, NodeId, SlotId};
use fparkan_render::LegacyIron3dEulerTransform;
use fparkan_render_vulkan::{
    node38_pose, node38_pose_from_hierarchy, node38_pose_relative_to_root,
    node38_pose_relative_to_root_from_hierarchy, VulkanNodePose,
};
use fparkan_runtime::{
    loaded_mission_control_device_tables, query_building_segment_world, BuildingMeshNode,
};
use std::sync::Arc;

#[derive(Clone)]
pub(super) struct BuildingCollisionBinding {
    pub(super) object_index: usize,
    pub(super) component_index: usize,
    pub(super) model_source: String,
    pub(super) model: Arc<ModelAsset>,
    pub(super) root_transform: LegacyIron3dEulerTransform,
    pub(super) owner_scale: [f32; 3],
    pub(super) mounted: bool,
    pub(super) selected_nodes: Vec<(NodeId, SlotId)>,
}

pub(super) fn building_collision_binding(
    object_index: usize,
    component_index: usize,
    model_source: String,
    model: Arc<ModelAsset>,
    root_transform: LegacyIron3dEulerTransform,
    owner_scale: [f32; 3],
    mounted: bool,
) -> Result<BuildingCollisionBinding, String> {
    let context = || {
        format!(
            "building collision object {object_index} component {component_index} model {model_source}"
        )
    };
    if model.node_stride != 38 || model.node_count == 0 || model.animation.is_none() {
        return Err(format!("{} has no complete Node38 pose data", context()));
    }
    if model.triangle_descriptors.is_none() {
        return Err(format!("{} has no type-7 collision descriptors", context()));
    }
    if root_transform.try_row_major().is_none()
        || !owner_scale.iter().all(|value| value.is_finite())
        || owner_scale.contains(&0.0)
    {
        return Err(format!("{} has an invalid world transform", context()));
    }
    let first_node = usize::from(mounted);
    let mut selected_nodes = Vec::new();
    for node_index in first_node..model.node_count {
        let node = NodeId(
            u32::try_from(node_index)
                .map_err(|_| format!("{} node index exceeds u32", context()))?,
        );
        let Some(slot) = selected_slot(&model, node, Lod(0), Group(0)) else {
            continue;
        };
        let slot_index = usize::try_from(slot.0)
            .map_err(|_| format!("{} node {} has an invalid slot id", context(), node.0))?;
        let slot_data = model.slots.get(slot_index).ok_or_else(|| {
            format!(
                "{} node {} selects missing slot {}",
                context(),
                node.0,
                slot.0
            )
        })?;
        let batch_start = usize::from(slot_data.batch_start);
        let batch_end = batch_start
            .checked_add(usize::from(slot_data.batch_count))
            .ok_or_else(|| format!("{} node {} batch range overflows", context(), node.0))?;
        let batches = model.batches.get(batch_start..batch_end).ok_or_else(|| {
            format!(
                "{} node {} batch range {batch_start}..{batch_end} is invalid",
                context(),
                node.0
            )
        })?;
        if batches.iter().any(|batch| batch.index_count != 0)
            || selected_slot(&model, node, Lod(1), Group(0)).is_some()
        {
            selected_nodes.push((node, slot));
        }
    }
    Ok(BuildingCollisionBinding {
        object_index,
        component_index,
        model_source,
        model,
        root_transform,
        owner_scale,
        mounted,
        selected_nodes,
    })
}

pub(super) fn building_collision_nodes(
    binding: &BuildingCollisionBinding,
    pose_buffer: Option<&NodePoseBuffer>,
    mount_pose: Option<VulkanNodePose>,
    visible_stage: impl Fn(usize) -> u32,
) -> Result<Vec<BuildingMeshNode>, String> {
    let context = || {
        format!(
            "building collision object {} component {} model {}",
            binding.object_index, binding.component_index, binding.model_source
        )
    };
    if binding.mounted != mount_pose.is_some() {
        return Err(format!(
            "{} has {} mount pose, expected {}",
            context(),
            if mount_pose.is_some() { "a" } else { "no" },
            if binding.mounted { "a" } else { "no" }
        ));
    }
    binding
        .selected_nodes
        .iter()
        .filter_map(|&(node, intact)| {
            let slot = if selected_slot(&binding.model, node, Lod(1), Group(0)).is_some() {
                let stage = u8::try_from(visible_stage(node.0 as usize)).ok()?;
                selected_slot(&binding.model, node, Lod(stage), Group(0))?
            } else {
                intact
            };
            Some((node, slot))
        })
        .map(|(node, slot)| {
            let node_index =
                usize::try_from(node.0).map_err(|_| format!("{} node id is invalid", context()))?;
            let pose = match (pose_buffer, binding.mounted) {
                (Some(hierarchy), true) => {
                    node38_pose_relative_to_root_from_hierarchy(hierarchy, node_index)
                }
                (Some(hierarchy), false) => node38_pose_from_hierarchy(hierarchy, node_index),
                (None, true) => node38_pose_relative_to_root(&binding.model, None, node_index),
                (None, false) => node38_pose(&binding.model, None, node_index),
            }
            .ok_or_else(|| format!("{} node {} has no current Node38 pose", context(), node.0))?;
            let world_from_node = component_node_world_matrix(
                binding.root_transform,
                binding.owner_scale,
                mount_pose,
                pose,
            )
            .ok_or_else(|| format!("{} node {} has an invalid world matrix", context(), node.0))?;
            Ok(BuildingMeshNode {
                node,
                slot,
                world_from_node,
            })
        })
        .collect()
}

fn component_node_world_matrix(
    root_transform: LegacyIron3dEulerTransform,
    owner_scale: [f32; 3],
    mount_pose: Option<VulkanNodePose>,
    node_pose: VulkanNodePose,
) -> Option<[f32; 16]> {
    if !owner_scale
        .iter()
        .chain(node_pose.translation.iter())
        .chain(node_pose.rotation.iter())
        .chain(mount_pose.iter().flat_map(|pose| pose.translation.iter()))
        .chain(mount_pose.iter().flat_map(|pose| pose.rotation.iter()))
        .all(|value| value.is_finite())
    {
        return None;
    }
    let pose_matrix = |pose: VulkanNodePose| {
        let [x, y, z] = [
            rotate_unit_vector([1.0, 0.0, 0.0], pose.rotation),
            rotate_unit_vector([0.0, 1.0, 0.0], pose.rotation),
            rotate_unit_vector([0.0, 0.0, 1.0], pose.rotation),
        ];
        [
            x[0],
            y[0],
            z[0],
            pose.translation[0],
            x[1],
            y[1],
            z[1],
            pose.translation[1],
            x[2],
            y[2],
            z[2],
            pose.translation[2],
            0.0,
            0.0,
            0.0,
            1.0,
        ]
    };
    let scale = [
        owner_scale[0],
        0.0,
        0.0,
        0.0,
        0.0,
        owner_scale[1],
        0.0,
        0.0,
        0.0,
        0.0,
        owner_scale[2],
        0.0,
        0.0,
        0.0,
        0.0,
        1.0,
    ];
    let mut world = multiply_row_major(root_transform.try_row_major()?, scale);
    if let Some(mount) = mount_pose {
        world = multiply_row_major(world, pose_matrix(mount));
    }
    world = multiply_row_major(world, pose_matrix(node_pose));
    world.iter().all(|value| value.is_finite()).then_some(world)
}

impl StaticVulkanApp {
    pub(super) fn building_segment_blocked(
        &self,
        world_segment: [[f32; 3]; 2],
    ) -> Result<bool, String> {
        Ok(self.building_segment_hit(world_segment, false)?.is_some())
    }

    pub(super) fn building_segment_hit(
        &self,
        world_segment: [[f32; 3]; 2],
        nearest: bool,
    ) -> Result<Option<[f32; 3]>, String> {
        let mut best = None;
        let tables = self
            .mission_engine
            .as_ref()
            .and_then(loaded_mission_control_device_tables)
            .unwrap_or_default();
        for binding in &self.building_collision_bindings {
            if binding.selected_nodes.is_empty()
                || self.removed_mission_roots.contains(&binding.object_index)
            {
                continue;
            }
            let pose_buffer = self
                .component_pose_buffers
                .get(binding.object_index)
                .and_then(|components| components.get(binding.component_index))
                .and_then(Option::as_ref);
            let mount_pose = self
                .component_mount_poses
                .get(binding.object_index)
                .and_then(|components| components.get(binding.component_index))
                .copied()
                .flatten();
            let providers = building_provider_rows(tables, binding.object_index);
            let nodes = building_collision_nodes(binding, pose_buffer, mount_pose, |node| {
                visible_node_stage(providers, binding.component_index, node)
            })?;
            if let Some(hit) = query_building_segment_world(&binding.model, &nodes, world_segment)
                .map_err(|error| {
                format!(
                    "query building collision object {} component {} model {}: {error}",
                    binding.object_index, binding.component_index, binding.model_source
                )
            })? {
                if !nearest {
                    return Ok(Some(hit.position));
                }
                if best.is_none_or(|(distance, _)| hit.distance_squared < distance) {
                    best = Some((hit.distance_squared, hit.position));
                }
            }
        }
        Ok(best.map(|(_, position)| position))
    }

    pub(super) fn resolve_player_building_step(
        &self,
        mut step: fparkan_runtime::PlayerMotionStep,
    ) -> Result<(fparkan_runtime::PlayerMotionStep, bool), String> {
        if let Some(probe) = step.floor_probe() {
            let crossing_cut = if self.terrain.basement_foundation().is_some() {
                let [start, end] = step.sweep.expect("walking floor probe");
                let support = |[x, y, _]: [f32; 3]| {
                    self.terrain
                        .support_plane_at([x, y])
                        .map_err(|err| err.to_string())
                };
                let previous = support(start)?.map(|plane| plane.height);
                let next = support(end)?;
                step = step.with_scene_terrain(previous, next);
                previous.is_none() || next.is_none()
            } else {
                false
            };

            let mesh_floor = self
                .building_segment_hit(probe, true)?
                .map(|point| point[2]);
            let terrain_exit = step.terrain_exit_floor();
            let previous_mesh = if mesh_floor.is_some() || terrain_exit.is_some() {
                self.building_segment_hit(
                    step.previous_floor_probe().expect("walking floor probe"),
                    true,
                )?
                .map(|point| point[2])
            } else {
                None
            };
            let mut floor = mesh_floor.map(|height| (height, false));
            if let Some(height) = terrain_exit {
                if mesh_floor.is_none_or(|mesh| mesh < height)
                    && (crossing_cut || previous_mesh.is_some())
                    && !self.building_segment_blocked([
                        [probe[0][0], probe[0][1], height + 0.02],
                        probe[0],
                    ])?
                {
                    floor = Some((height, true));
                }
            }
            if let Some((height, terrain)) = floor {
                step = if terrain {
                    step.with_terrain_floor(height, previous_mesh)
                } else {
                    step.with_building_floor(height, previous_mesh)
                };
                if let Some(segments) = step.floor_sweeps() {
                    for segment in segments.into_iter().filter(|[from, to]| from != to) {
                        if self.building_segment_blocked(segment)? {
                            return Ok((step, true));
                        }
                    }
                }
                return Ok((step, false));
            }
        }
        let blocked = match step.sweep {
            Some(segment) => self.building_segment_blocked(segment)?,
            None => false,
        };
        Ok((step, blocked))
    }
}

#[cfg(test)]
#[derive(Default)]
pub(crate) struct WalkRoute {
    filtered_x: f32,
}

#[cfg(test)]
impl WalkRoute {
    pub(crate) fn toward(
        &mut self,
        pose: fparkan_world::TransformState,
        target: [f32; 2],
        max_step: f32,
    ) -> fparkan_runtime::PlayerMotion {
        use std::f32::consts::{PI, TAU};

        let [x, y, _] = pose.position.map(f32::from_bits);
        let [dx, dy] = [target[0] - x, target[1] - y];
        let yaw = f32::from_bits(pose.orientation[2]);
        let wanted = (-dx).atan2(dy);
        let turn = (yaw - wanted + PI).rem_euclid(TAU) - PI;
        // Convert the desired heading to ordinary mouse input at 100% sensitivity.
        let axis = (turn / (TAU * 0.15)).clamp(-1.0, 1.0);
        let previous = self.filtered_x * 0.05;
        let mouse_x = (axis / 0.006 - previous) / 0.95;
        self.filtered_x = if mouse_x == 0.0 {
            0.0
        } else {
            mouse_x * 0.95 + previous
        };
        let walk_time = dx.hypot(dy).min(max_step) / 14.0;
        let can_walk = turn.abs() <= (TAU * 0.15).min(50.0 * walk_time);
        fparkan_runtime::PlayerMotion {
            mouse_x,
            movement: [0.0, f32::from(can_walk)],
            delta_seconds: if can_walk { walk_time } else { 0.03 },
            ..Default::default()
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::tests::clock_test_app;
    use crate::*;

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_constructor_walks_to_factory_cabin_and_back() {
        let root = std::path::PathBuf::from(
            std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root"),
        );
        let args = Args::parse(&[
            "--root".into(),
            root.to_string_lossy().into_owned(),
            "--mission".into(),
            "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.02/data.tma".into(),
        ])
        .unwrap();
        let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(&root)))).unwrap();
        let loaded = load_requested_mission(&mut engine, &args).unwrap();
        let terrain = loaded_terrain(&engine).unwrap();
        let assets = loaded_mission_assets(&engine).unwrap();
        let drafts = loaded_mission_object_drafts(&engine).unwrap();
        let footprints =
            mission_basement_footprints(assets, &drafts[..loaded.object_count]).unwrap();
        let foundation = build_basement_foundations(
            terrain.source_mesh().unwrap(),
            &footprints
                .iter()
                .map(MissionBasementFootprint::contours)
                .collect::<Vec<_>>(),
        )
        .unwrap();
        let adjusted =
            apply_basement_placement_deltas(drafts, &footprints, &foundation.placements).unwrap();
        let factory = &adjusted[0];
        let root_transform = LegacyIron3dEulerTransform {
            translation: factory.position,
            orientation_radians: factory.orientation_raw,
        };
        let scale = factory.scale;
        let visual = assets.visual_by_id(factory.visual_ids[0]).unwrap();
        let model = Arc::new(
            assets
                .model_by_id(visual.model_id.unwrap())
                .unwrap()
                .validated
                .clone(),
        );
        let control = assets.object_component_controls[0][0]
            .as_ref()
            .unwrap()
            .clone();
        let hierarchy = node38_fallback_hierarchy(&model).unwrap();
        let route = std::iter::once([320.0, 790.0])
            .chain(
                [67, 66, 65, 58, 59, 37, 36, 6, 7, 25, 35, 28, 31].map(|index| {
                    let point = &model.hallway.points[index];
                    let local =
                        hierarchy.poses[point.node.0 as usize].transform_point(point.position);
                    let [x, y, _] = root_transform
                        .try_transform_scaled_point(local, scale)
                        .unwrap();
                    [x, y]
                }),
            )
            .collect::<Vec<_>>();
        let (mut app, _) = clock_test_app(None);
        app.terrain = Arc::new(
            terrain
                .clone()
                .with_basement_foundation(foundation)
                .unwrap(),
        );
        app.building_collision_bindings.push(
            building_collision_binding(
                0,
                0,
                "factory".into(),
                model.clone(),
                root_transform,
                scale,
                false,
            )
            .unwrap(),
        );
        app.component_pose_buffers = vec![vec![None]];
        let cockpit = starting_cockpit(&engine).unwrap();
        let pose = |frame: FrameResult| {
            frame
                .snapshot
                .transforms
                .into_iter()
                .find(|(handle, _)| *handle == cockpit.handle)
                .unwrap()
                .1
        };
        let mut now = 0;
        let mut hero = pose(step_mission_frame(&mut engine, now).unwrap());
        let mut input = super::WalkRoute::default();
        let [spawn_x, spawn_y, spawn_z] = hero.position.map(f32::from_bits);
        let spawn_clearance = spawn_z - app.terrain.height_at([spawn_x, spawn_y]).unwrap().unwrap();
        let mut door_blends = Vec::new();
        let mut footstep_surfaces = [false; 2];
        for (index, [x, y]) in route
            .iter()
            .chain(route.iter().rev().skip(1))
            .copied()
            .enumerate()
        {
            let mut stalled = 0;
            loop {
                let [hx, hy, hz] = hero.position.map(f32::from_bits);
                let distance = (x - hx).hypot(y - hy);
                if distance <= 0.04 {
                    break;
                }
                let mut node_times: Vec<_> = fparkan_runtime::initial_component_node_times(
                    model.node_count,
                    &control.bindings,
                )
                .unwrap()
                .into_iter()
                .map(|time| time.map(|time| time.0))
                .collect();
                fparkan_runtime::sample_proximity_doors(
                    &control,
                    &model,
                    root_transform,
                    scale,
                    [hx, hy, hz + 0.5],
                    0.1,
                    &mut door_blends,
                    &mut node_times,
                );
                let factory_handle =
                    mission_object_handle(&engine, fparkan_world::OriginalObjectId(0)).unwrap();
                fparkan_runtime::sample_capture_barrier(
                    &engine,
                    factory_handle,
                    &control,
                    &mut node_times,
                );
                let times: Vec<_> = node_times
                    .into_iter()
                    .map(|time| time.map(AnimationTime))
                    .collect();
                app.component_pose_buffers[0][0] =
                    node38_sampled_hierarchy_at_times(&model, &times);
                let motion = plan_player_motion_with_collision(
                    &engine,
                    cockpit,
                    input.toward(hero, [x, y], 0.8),
                    |step| {
                        app.resolve_player_building_step(step)
                            .map_err(EngineError::Movement)
                    },
                )
                .unwrap()
                .unwrap();
                now += 100;
                let frame =
                    frame_with_player_motion(&mut engine, now, cockpit, motion, false).unwrap();
                if let Some(footstep) = frame.player_footstep {
                    footstep_surfaces[usize::from(footstep.building_floor)] = true;
                }
                let moved = pose(frame);
                stalled = if moved.position == hero.position {
                    stalled + 1
                } else {
                    0
                };
                assert!(
                    stalled < 20,
                    "blocked before waypoint {index} [{x}, {y}] at [{hx}, {hy}, {hz}]"
                );
                assert!(now < 150_000, "walk stalled before waypoint {index}");
                hero = moved;
            }
            if index + 1 == route.len() {
                let z = f32::from_bits(hero.position[2]);
                assert!(z < factory.position[2] - 4.0, "factory cabin at {z}");
                assert_eq!(app.terrain.height_at([x, y]).unwrap(), None);
                assert_eq!(
                    fparkan_runtime::capture_building_with_notice(&mut engine, cockpit).unwrap(),
                    Some((
                        fparkan_world::OriginalObjectId(0),
                        fparkan_runtime::MissionNotice::BuildingCaptured { neutral: true }
                    ))
                );
                now += 17;
                step_mission_frame(&mut engine, now).unwrap();
                now += 500;
                step_mission_frame(&mut engine, now).unwrap();
            }
        }
        let [x, y, z] = hero.position.map(f32::from_bits);
        assert_eq!(footstep_surfaces, [true, true]);
        let ground = app.terrain.height_at([x, y]).unwrap().unwrap();
        assert!(
            (z - ground - spawn_clearance).abs() < 0.02,
            "factory exit clearance {}, stock outdoor clearance {spawn_clearance}",
            z - ground
        );
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn licensed_firing_range_keeps_clearance_across_bridge() {
        let root = std::path::PathBuf::from(
            std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed root"),
        );
        let args = Args::parse(&[
            "--root".into(),
            root.to_string_lossy().into_owned(),
            "--mission".into(),
            "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.01/data.tma".into(),
        ])
        .unwrap();
        let mut engine = create(EngineServices::new(Arc::new(DirectoryVfs::new(&root)))).unwrap();
        load_requested_mission(&mut engine, &args).unwrap();
        let assets = loaded_mission_assets(&engine).unwrap();

        let (mut app, _) = clock_test_app(None);
        for (i, draft) in loaded_mission_object_drafts(&engine)
            .unwrap()
            .iter()
            .enumerate()
            .filter(|(i, _)| [23, 24].contains(i))
        {
            let visual = assets.visual_by_id(draft.visual_ids[0]).unwrap();
            let model = Arc::new(
                assets
                    .model_by_id(visual.model_id.unwrap())
                    .unwrap()
                    .validated
                    .clone(),
            );
            let transform = LegacyIron3dEulerTransform {
                translation: draft.position,
                orientation_radians: draft.orientation_raw,
            };
            let binding = building_collision_binding(
                i,
                0,
                "bridge".into(),
                model,
                transform,
                draft.scale,
                false,
            )
            .unwrap();
            app.component_pose_buffers.resize_with(i + 1, || vec![None]);
            app.component_pose_buffers[i][0] = assets.object_component_controls[i][0]
                .as_ref()
                .and_then(|control| {
                    static_preview_component_pose_buffer(&binding.model, &control.bindings, None)
                        .unwrap()
                });
            app.building_collision_bindings.push(binding);
        }
        let transform = app.building_collision_bindings[0].root_transform;
        let terrain = loaded_terrain(&engine).unwrap().clone();
        let cockpit = starting_cockpit(&engine).unwrap();
        let mut now = 0;
        let pose = |frame: FrameResult| {
            frame
                .snapshot
                .transforms
                .into_iter()
                .find(|(handle, _)| *handle == cockpit.handle)
                .unwrap()
                .1
        };
        let mut hero = pose(step_mission_frame(&mut engine, now).unwrap());
        let mut input = super::WalkRoute::default();
        let [x, y, z] = hero.position.map(f32::from_bits);
        let clearance = z - terrain.height_at([x, y]).unwrap().unwrap();
        let waypoints = [-42.0, -34.0, 36.0, 115.0, 198.0];
        for dy in waypoints {
            let [x, y, _] = transform
                .try_transform_scaled_point([0.0, dy, 0.0], [1.0; 3])
                .unwrap();
            for index in 0..900 {
                let [hx, hy, hz] = hero.position.map(f32::from_bits);
                let distance = (x - hx).hypot(y - hy);
                if distance < 0.03 {
                    let support = app
                        .building_segment_hit([[hx, hy, hz], [hx, hy, hz - 2.0]], true)
                        .unwrap()
                        .map_or_else(
                            || terrain.height_at([hx, hy]).unwrap().unwrap(),
                            |point| point[2],
                        );
                    assert!(
                        (hz - support - clearance).abs() < 0.01,
                        "clearance at waypoint {dy}: {}",
                        hz - support
                    );
                    break;
                }
                assert!(index < 899, "blocked for waypoint {dy}: {hx}, {hy}, {hz}");
                let step = plan_player_motion_with_collision(
                    &engine,
                    cockpit,
                    input.toward(hero, [x, y], 0.8),
                    |step| {
                        app.resolve_player_building_step(step)
                            .map_err(EngineError::Movement)
                    },
                )
                .unwrap()
                .unwrap();
                now += 100;
                hero =
                    pose(frame_with_player_motion(&mut engine, now, cockpit, step, false).unwrap());
                let new_z = f32::from_bits(hero.position[2]);
                assert!(
                    (new_z - hz).abs() < 0.3,
                    "height jump at {hx} {hy}: {hz} -> {new_z}"
                );
            }
        }
    }
}