oxijolt 1.1.0+jolt-5.6.0

Safe Rust API for Jolt Physics
Documentation
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
//! The study's scenes: heightfield slopes, crests, ridges, steps, ledges, walls, box ramps and
//! chunk seams, each with the decoded geometry the law predicates measure against.
//!
//! Planar scenes are built in local coordinates (slope rising along +x, up +y) and placed by a
//! [`Frame`]; their up is the frame's. Radial scenes sit at the anchor of the walker fixtures'
//! planet (radius 99) and use radial up.

use std::sync::atomic::{AtomicU32, Ordering};

use oxijolt::*;

use super::frame::{Frame, UpPolicy};
use super::geometry::{Block, Field, Surface};
use crate::common::math::{add, rotate, rvec3, scale, sub, vec3, V3};
use crate::common::walker::{
    capsule, chunk_pose, fixture_world, flat_terrain, up_at, Layers, CENTRE_UP, R, RADIUS,
    REST_HEIGHT,
};
use crate::common::{quat_about, Groups};

/// Samples per side of every study heightfield except the continuous seam field.
pub const SAMPLES: usize = 33;

/// The drop of the high ledge beside a wall, metres.
pub const HIGH_LEDGE_DROP: f64 = 2.0;

/// When not 0, the bits per sample of every study heightfield built from now on (the survey's
/// precision runs); the walker fixtures' planet chunks keep 16.
pub static FIELD_BITS_OVERRIDE: AtomicU32 = AtomicU32::new(0);

/// The heights of a seam scene, rising along +x.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Profile {
    Flat,
    /// Flat, 30 degrees for `-6 <= x <= 6`, then a plateau.
    Rise30,
    /// As `Rise30` at 44.5 degrees; the runs walk it down.
    Descent44_5,
}

impl Profile {
    pub fn height(self, x: f64) -> f64 {
        let tan = match self {
            Self::Flat => return 0.0,
            Self::Rise30 => 30.0_f64.to_radians().tan(),
            Self::Descent44_5 => 44.5_f64.to_radians().tan(),
        };
        tan * (x.clamp(-6.0, 6.0) + 6.0)
    }

    pub fn name(self) -> &'static str {
        match self {
            Self::Flat => "flat",
            Self::Rise30 => "rise30",
            Self::Descent44_5 => "descent44.5",
        }
    }
}

/// How a seam scene's terrain is split.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Split {
    /// Two adjacent 33-sample bodies meeting at x = 0.
    Pair,
    /// As `Pair` with the second body 0.03 m higher (the law 6 control).
    Raised,
    /// One 65-sample body over the same span.
    Continuous,
    /// The two fields of `Pair` as the children of one static compound body: a seam remedy
    /// candidate, since Jolt's enhanced internal edge removal works within one body.
    Compound,
}

/// Which scene to build. Angles are in tenths of a degree, heights in millimetres.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum SceneKey {
    /// `h = tan * x` over the whole field.
    Plane { deg10: u16, bits: u8, tilted: bool },
    /// Flat for `x < -6`, the slope for `-6..6`, a plateau beyond: a concave toe and a convex
    /// crest at x = 6.
    Ramp { deg10: u16, tilted: bool },
    /// Up at the angle for `-6..0`, down for `0..6`, flat outside.
    Ridge { deg10: u16, tilted: bool },
    /// A box step with its face at x = 0 on flat terrain, its top `height_mm` high.
    Step { height_mm: u16, rounded: bool },
    /// A platform over `-4 <= x <= 0` whose edge at x = 0 drops `drop_mm` to flat terrain.
    Ledge { drop_mm: u16, rounded: bool },
    /// Flat terrain and a sharp wall whose face is at x = 0.35: half (0.1, 1, 2), or half
    /// (1, 1, 2) when thick.
    Wall { thick: bool },
    /// A tilted sharp box whose top face rises along +x at the angle through the origin.
    BoxRamp { deg10: u16, tilted: bool },
    /// Flat terrain.
    Flat,
    /// Seam terrain over `-32 <= x <= 32`.
    Seam { profile: Profile, split: Split },
    /// The log spiral `r = 99 exp(tan * phi)` at the anchor: a constant angle to radial up.
    RadialSpiral {
        deg10: u16,
        spacing_mm: u16,
        bits: u8,
    },
    /// The planet's surface for `x >= 0` and the spiral for `x < 0`: a convex crest at x = 0.
    RadialCrest { deg10: u16 },
    /// The walker fixtures' block at the anchor: flat chunk, sharp box face at x = 1.4.
    RadialStep { height_mm: u16 },
    /// Two flat chunks meeting at x = 16.
    RadialSeam,
    /// A flat chunk and a sharp wall of half (0.1, 1, 2) centred at x = 0.45.
    RadialWall,
    /// A sharp platform over `-4 <= x <= 0` whose edge at x = 0 drops [`HIGH_LEDGE_DROP`] to flat
    /// terrain, and a sharp wall along x whose face passes z = `face_mm` at the height of a body
    /// origin resting on the platform, leaning back by `lean_cdeg` hundredths of a degree (its face
    /// then looks up; negative: an overhang).
    HighLedgeBesideWall { face_mm: u16, lean_cdeg: i16 },
    /// As `HighLedgeBesideWall` on the anchor chunk of the planet.
    RadialHighLedgeBesideWall { face_mm: u16, lean_cdeg: i16 },
}

impl SceneKey {
    pub fn plane(deg: f64) -> Self {
        Self::Plane {
            deg10: tenths(deg),
            bits: 16,
            tilted: false,
        }
    }

    /// Whether the scene uses radial up.
    pub fn is_radial(self) -> bool {
        matches!(
            self,
            Self::RadialSpiral { .. }
                | Self::RadialCrest { .. }
                | Self::RadialStep { .. }
                | Self::RadialSeam
                | Self::RadialWall
                | Self::RadialHighLedgeBesideWall { .. }
        )
    }
}

/// `deg` in tenths of a degree.
pub fn tenths(deg: f64) -> u16 {
    (deg * 10.0).round() as u16
}

fn degrees(deg10: u16) -> f64 {
    f64::from(deg10) / 10.0
}

/// A built scene.
pub struct Scene {
    pub world: PhysicsWorld,
    pub layers: Layers,
    pub frame: Frame,
    pub up: UpPolicy,
    pub surface: Surface,
    /// The terrain bodies in creation order.
    pub terrain: Vec<BodyId>,
    /// The game's kinematic actor capsule, which follows the character of the case being run
    /// and which the controller filter excludes.
    pub actor: BodyId,
}

impl Scene {
    /// Builds the scene of `key` in a world with one worker thread.
    pub fn build(key: SceneKey) -> Self {
        Self::build_with_threads(key, 1)
    }

    /// Builds the scene of `key` in a world with `worker_threads` worker threads.
    pub fn build_with_threads(key: SceneKey, worker_threads: u32) -> Self {
        let frame = match key {
            SceneKey::Plane { tilted: true, .. }
            | SceneKey::Ramp { tilted: true, .. }
            | SceneKey::Ridge { tilted: true, .. }
            | SceneKey::BoxRamp { tilted: true, .. } => Frame::tilted(),
            _ => Frame::IDENTITY,
        };
        let (world, layers) = fixture_world(worker_threads);
        let up = if key.is_radial() {
            UpPolicy::Radial
        } else {
            UpPolicy::Frame(frame)
        };
        let mut builder = Builder {
            world,
            layers,
            frame,
            surface: Surface::default(),
            terrain: Vec::new(),
        };
        builder.add(key);
        let actor = builder.actor();
        builder.world.optimize_broad_phase();
        Self {
            world: builder.world,
            layers: builder.layers,
            frame,
            up,
            surface: builder.surface,
            terrain: builder.terrain,
            actor,
        }
    }

    /// A scene around an existing fixture world (radial up, no decoded geometry), with an actor
    /// capsule added.
    pub fn from_world(world: PhysicsWorld, layers: Layers) -> Self {
        let mut builder = Builder {
            world,
            layers,
            frame: Frame::IDENTITY,
            surface: Surface::default(),
            terrain: Vec::new(),
        };
        let actor = builder.actor();
        Self {
            world: builder.world,
            layers,
            frame: Frame::IDENTITY,
            up: UpPolicy::Radial,
            surface: builder.surface,
            terrain: builder.terrain,
            actor,
        }
    }

    /// Moves the actor capsule to body origin `origin` with rotation `rotation`.
    pub fn place_actor(&mut self, origin: V3, rotation: Quat) {
        self.world
            .body_mut(self.actor)
            .unwrap()
            .set_position_and_rotation(rvec3(origin), rotation, Activation::DontActivate)
            .unwrap();
    }
}

/// Builds the bodies of a scene and records their geometry.
struct Builder {
    world: PhysicsWorld,
    layers: Layers,
    frame: Frame,
    surface: Surface,
    terrain: Vec<BodyId>,
}

impl Builder {
    fn add(&mut self, key: SceneKey) {
        match key {
            SceneKey::Plane { deg10, bits, .. } => {
                let tan = degrees(deg10).to_radians().tan();
                self.field([0.0; 3], SAMPLES, 1.0, bits.into(), move |x, _| tan * x);
            }
            SceneKey::Ramp { deg10, .. } => {
                let tan = degrees(deg10).to_radians().tan();
                self.field([0.0; 3], SAMPLES, 1.0, 16, move |x, _| {
                    tan * (x.clamp(-6.0, 6.0) + 6.0)
                });
            }
            SceneKey::Ridge { deg10, .. } => {
                let tan = degrees(deg10).to_radians().tan();
                self.field([0.0; 3], SAMPLES, 1.0, 16, move |x, _| {
                    tan * (6.0 - x.abs()).max(0.0)
                });
            }
            SceneKey::Step { height_mm, rounded } => {
                self.flat();
                let h = f64::from(height_mm) / 1000.0;
                let bottom = -1.0;
                self.block(
                    [2.0, 0.5 * (h + bottom), 0.0],
                    [2.0, 0.5 * (h - bottom), 6.0],
                    0.0,
                    radius(rounded),
                );
            }
            SceneKey::Ledge { drop_mm, rounded } => {
                self.flat();
                let h = f64::from(drop_mm) / 1000.0;
                let bottom = -1.0;
                self.block(
                    [-2.0, 0.5 * (h + bottom), 0.0],
                    [2.0, 0.5 * (h - bottom), 6.0],
                    0.0,
                    radius(rounded),
                );
            }
            SceneKey::Wall { thick } => {
                self.flat();
                let half_x = if thick { 1.0 } else { 0.1 };
                let face = f64::from(RADIUS) - 0.05;
                self.block([face + half_x, 1.0, 0.0], [half_x, 1.0, 2.0], 0.0, 0.0);
            }
            SceneKey::BoxRamp { deg10, .. } => {
                let angle = degrees(deg10).to_radians();
                let thickness = 0.5;
                // The top face's middle sits at the local origin.
                let centre = [thickness * angle.sin(), -thickness * angle.cos(), 0.0];
                self.block(centre, [12.0, thickness, 9.0], angle as f32, 0.0);
                // Ground far below, so nothing falls forever.
                self.field([0.0, -20.0, 0.0], SAMPLES, 1.0, 16, |_, _| 0.0);
            }
            SceneKey::Flat => self.flat(),
            SceneKey::Seam { profile, split } => match split {
                Split::Continuous => {
                    self.field([0.0; 3], 65, 1.0, 16, move |x, _| profile.height(x));
                }
                Split::Compound => {
                    self.fields_in_one_body(&[[-16.0, 0.0, 0.0], [16.0, 0.0, 0.0]], move |x, _| {
                        profile.height(x)
                    });
                }
                Split::Pair | Split::Raised => {
                    let lift = if split == Split::Raised { 0.03 } else { 0.0 };
                    self.field([-16.0, 0.0, 0.0], SAMPLES, 1.0, 16, move |x, _| {
                        profile.height(x)
                    });
                    self.field([16.0, 0.0, 0.0], SAMPLES, 1.0, 16, move |x, _| {
                        profile.height(x) + lift
                    });
                }
            },
            SceneKey::RadialSpiral {
                deg10,
                spacing_mm,
                bits,
            } => {
                let tan = degrees(deg10).to_radians().tan();
                let spacing = f64::from(spacing_mm) / 1000.0;
                self.field([0.0; 3], SAMPLES, spacing, bits.into(), move |x, _| {
                    spiral_height(tan, x)
                });
            }
            SceneKey::RadialCrest { deg10 } => {
                let tan = degrees(deg10).to_radians().tan();
                self.field([0.0; 3], SAMPLES, 0.5, 16, move |x, _| {
                    if x >= 0.0 {
                        (R * R - x * x).sqrt() - R
                    } else {
                        spiral_height(tan, x)
                    }
                });
            }
            SceneKey::RadialStep { height_mm } => {
                self.planet_chunk(0.0);
                let face = 1.0 + f64::from(RADIUS);
                let top = flat_ground(face, 0.0) + f64::from(height_mm) / 1000.0;
                self.block([face + 2.0, top - 1.5, 0.0], [2.0, 1.5, 2.0], 0.0, 0.0);
            }
            SceneKey::RadialSeam => {
                self.planet_chunk(0.0);
                self.planet_chunk(2.0 * (16.0 / R).asin());
            }
            SceneKey::RadialWall => {
                self.planet_chunk(0.0);
                self.block([0.45, 1.0, 0.0], [0.1, 1.0, 2.0], 0.0, 0.0);
            }
            SceneKey::HighLedgeBesideWall { face_mm, lean_cdeg } => {
                self.flat();
                self.high_ledge_beside_wall(face_mm, lean_cdeg);
            }
            SceneKey::RadialHighLedgeBesideWall { face_mm, lean_cdeg } => {
                self.planet_chunk(0.0);
                self.high_ledge_beside_wall(face_mm, lean_cdeg);
            }
        }
    }

    /// The platform and the wall of [`SceneKey::HighLedgeBesideWall`] over ground at height 0.
    /// The wall turns about x around its face point at the resting origin's height, which
    /// turns its face normal from -z to `(0, sin lean, -cos lean)`.
    fn high_ledge_beside_wall(&mut self, face_mm: u16, lean_cdeg: i16) {
        let top = HIGH_LEDGE_DROP;
        self.block([-2.0, top - 1.5, 0.0], [2.0, 1.5, 2.0], 0.0, 0.0);
        let face = [
            0.0,
            top + f64::from(REST_HEIGHT),
            f64::from(face_mm) / 1000.0,
        ];
        let half = [4.0, 0.5 * top + 1.5, 0.1];
        let upright_centre = [0.0, 0.5 * top + 0.5, face[2] + half[2]];
        let lean = (f64::from(lean_cdeg) / 100.0).to_radians() as f32;
        let turn = quat_about(Vec3::new(1.0, 0.0, 0.0), lean);
        let centre = add(face, rotate(turn, sub(upright_centre, face)));
        self.turned_block(centre, half, turn, 0.0);
    }

    fn flat(&mut self) {
        self.field([0.0; 3], SAMPLES, 1.0, 16, |_, _| 0.0);
    }

    /// A static terrain heightfield of `samples` per side, `spacing` apart, centred on local
    /// point `centre`, with heights `height(x, z)` of scene-local x and z.
    fn field(
        &mut self,
        centre: V3,
        samples: usize,
        spacing: f64,
        bits: u32,
        height: impl Fn(f64, f64) -> f64,
    ) {
        let (shape, field) = self.field_shape(centre, samples, spacing, bits, height);
        let body = self
            .world
            .create_body(
                &shape,
                &BodySettings::new_static()
                    .position(rvec3(field.frame.origin))
                    .rotation(field.frame.rotation)
                    .object_layer(self.layers.terrain),
            )
            .unwrap();
        self.terrain.push(body);
        self.surface.fields.push(field);
    }

    /// 33-sample, 1 m, 16-bit heightfields centred on the local points `centres`, as the
    /// children of one static compound in the terrain layer. The children carry the feature
    /// group: the controller filter collides with compound children of the structure, feature
    /// and actor groups only.
    fn fields_in_one_body(&mut self, centres: &[V3], height: impl Fn(f64, f64) -> f64 + Copy) {
        let parts: Vec<(Shape, Field)> = centres
            .iter()
            .map(|&centre| self.field_shape(centre, SAMPLES, 1.0, 16, height))
            .collect();
        let children: Vec<CompoundChild<'_>> = parts
            .iter()
            .zip(centres)
            .map(|((shape, _), &centre)| CompoundChild {
                shape,
                position: vec3(centre),
                rotation: Quat::IDENTITY,
                user_data: Groups::FEATURE,
            })
            .collect();
        let compound = Shape::new_compound(&children).unwrap();
        let body = self
            .world
            .create_body(
                &compound,
                &BodySettings::new_static()
                    .position(rvec3(self.frame.origin))
                    .rotation(self.frame.rotation)
                    .object_layer(self.layers.terrain),
            )
            .unwrap();
        self.terrain.push(body);
        self.surface
            .fields
            .extend(parts.into_iter().map(|(_, field)| field));
    }

    /// The shape of a heightfield as [`field`](Self::field) describes it, and its decoded
    /// geometry.
    fn field_shape(
        &self,
        centre: V3,
        samples: usize,
        spacing: f64,
        bits: u32,
        height: impl Fn(f64, f64) -> f64,
    ) -> (Shape, Field) {
        let half = (samples - 1) as f64 / 2.0 * spacing;
        let mut heights = Vec::with_capacity(samples * samples);
        for iz in 0..samples {
            for ix in 0..samples {
                let (x, z) = (ix as f64 * spacing - half, iz as f64 * spacing - half);
                heights.push(height(centre[0] + x, centre[2] + z));
            }
        }
        let bits = match FIELD_BITS_OVERRIDE.load(Ordering::Relaxed) {
            0 => bits,
            forced => forced,
        };
        let offset = [-half, 0.0, -half];
        let settings = HeightFieldSettings::default()
            .offset(vec3(offset))
            .scale(Vec3::new(spacing as f32, 1.0, spacing as f32))
            .bits_per_sample(bits);
        let samples_f32: Vec<f32> = heights.iter().map(|&h| h as f32).collect();
        let shape = Shape::new_height_field(samples as u32, &samples_f32, &settings).unwrap();
        let frame = Frame {
            origin: self.frame.to_world_point(centre),
            rotation: self.frame.rotation,
        };
        let intended = heights.iter().map(|&h| f64::from(h as f32)).collect();
        let field = Field::decode(&shape, frame, samples, spacing, offset, intended, bits);
        (shape, field)
    }

    /// The flat terrain of the walker fixtures' chunk at `angle` from the anchor.
    fn planet_chunk(&mut self, angle: f64) {
        let shape = flat_terrain();
        let (position, rotation) = chunk_pose(angle);
        let body = self
            .world
            .create_body(
                &shape,
                &BodySettings::new_static()
                    .position(position)
                    .rotation(rotation)
                    .object_layer(self.layers.terrain),
            )
            .unwrap();
        self.terrain.push(body);
        let intended = (0..SAMPLES * SAMPLES)
            .map(|i| {
                let (x, z) = ((i % SAMPLES) as f64 - 16.0, (i / SAMPLES) as f64 - 16.0);
                f64::from(((R * R - x * x - z * z).sqrt() - R) as f32)
            })
            .collect();
        let frame = Frame {
            origin: crate::common::math::v3(position),
            rotation,
        };
        self.surface.fields.push(Field::decode(
            &shape,
            frame,
            SAMPLES,
            1.0,
            [-16.0, 0.0, -16.0],
            intended,
            16,
        ));
    }

    /// A static chunk compound holding one box of half extents `half` at local `centre`,
    /// turned by `tilt_z` radians about local z, with the structure group.
    fn block(&mut self, centre: V3, half: V3, tilt_z: f32, convex_radius: f64) {
        let tilt = quat_about(Vec3::new(0.0, 0.0, 1.0), tilt_z);
        self.turned_block(centre, half, tilt, convex_radius);
    }

    /// As [`block`](Self::block), turned by `tilt`.
    fn turned_block(&mut self, centre: V3, half: V3, tilt: Quat, convex_radius: f64) {
        let shape = Shape::new_box_with_convex_radius(vec3(half), convex_radius as f32).unwrap();
        let chunk = Shape::new_compound(&[CompoundChild {
            shape: &shape,
            position: vec3(centre),
            rotation: tilt,
            user_data: Groups::STRUCTURE,
        }])
        .unwrap();
        self.world
            .create_body(
                &chunk,
                &BodySettings::new_static()
                    .position(rvec3(self.frame.origin))
                    .rotation(self.frame.rotation)
                    .object_layer(self.layers.chunk),
            )
            .unwrap();
        self.surface.blocks.push(Block {
            frame: Frame {
                origin: self.frame.to_world_point(centre),
                rotation: self.frame.to_world_rotation(tilt),
            },
            half,
            convex_radius,
        });
    }

    /// The game's kinematic actor capsule, parked far below the scene.
    fn actor(&mut self) -> BodyId {
        add_actor(&mut self.world, &self.layers)
    }
}

/// Adds the game's kinematic actor capsule to `world`, parked far below the scenes.
pub fn add_actor(world: &mut PhysicsWorld, layers: &Layers) -> BodyId {
    let capsule = capsule();
    let shape = Shape::new_compound(&[CompoundChild {
        shape: &capsule,
        position: Vec3::new(0.0, CENTRE_UP, 0.0),
        rotation: Quat::IDENTITY,
        user_data: Groups::ACTOR,
    }])
    .unwrap();
    world
        .create_body(
            &shape,
            &BodySettings::new_kinematic()
                .position(RVec3::new(0.0, -500.0, 0.0))
                .object_layer(layers.actor),
        )
        .unwrap()
}

fn radius(rounded: bool) -> f64 {
    if rounded {
        0.05
    } else {
        0.0
    }
}

/// Height above the anchor plane of the log spiral `r = R exp(tan * phi)` (in the x-y plane
/// around the planet's centre) at chart x: `phi` solved by bisection from `r sin phi = x`.
pub fn spiral_height(tan: f64, x: f64) -> f64 {
    let at = |phi: f64| R * (tan * phi).exp() * phi.sin();
    let (mut low, mut high) = (-0.5, 0.5);
    for _ in 0..200 {
        let mid = 0.5 * (low + high);
        if at(mid) < x {
            low = mid;
        } else {
            high = mid;
        }
    }
    let phi = 0.5 * (low + high);
    R * (tan * phi).exp() * phi.cos() - R
}

/// Ground height of the anchor chunk's flat terrain at `x`, `z`.
pub fn flat_ground(x: f64, z: f64) -> f64 {
    (R * R - x * x - z * z).sqrt() - R
}

/// The body origin resting on the anchor chunk's flat terrain at `(x, z)`.
pub fn resting_on_planet(x: f64, z: f64) -> V3 {
    let ground = [x, flat_ground(x, z), z];
    add(ground, scale(up_at(ground), f64::from(REST_HEIGHT)))
}