retrofire-geom 0.4.0

Additional geometry tools for retrofire.
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
//! Various solids of revolution.

use alloc::vec::Vec;
use core::ops::Range;

use retrofire_core::geom::{
    Mesh, Normal2, Normal3, Polyline, Tri, Vertex, Vertex2, Vertex3, tri,
    vertex,
};
use retrofire_core::math::{
    Angle, Lerp, Parametric, Point3, Vary, Vec3, polar, pt2, pt3, rotate2,
    turns, vec2, vec3,
};
use retrofire_core::render::{TexCoord, uv};

use super::Build;

/// A surface of revolution generated by rotating a 2D curve around the y-axis.
#[derive(Clone, Debug, Default)]
pub struct Lathe<P> {
    /// The curve defining the shape.
    pub points: P,
    /// The number of facets used to approximate the surface.
    pub sectors: u32,
    /// The number of vertical segments used to approximate the surface.
    pub segments: u32,
    /// Whether to add flat caps to both ends of the object.
    pub capped: bool,
    /// The range of angles over which to rotate.
    pub az_range: Range<Angle>,
}

/// TODO
pub struct Sphere {
    pub sectors: u32,
    pub segments: u32,
    pub radius: f32,
}

/// Toroidal polyhedron.
pub struct Torus {
    /// Distance from the origin to the center of the tube.
    pub major_radius: f32,
    /// Radius of the cross-section of the tube.
    pub minor_radius: f32,

    pub major_sectors: u32,
    pub minor_sectors: u32,
}

/// Right cylinder with regular *n*-gonal cross-section.
pub struct Cylinder {
    pub sectors: u32,
    pub segments: u32,
    pub capped: bool,
    pub radius: f32,
}

/// TODO
pub struct Cone {
    pub sectors: u32,
    pub segments: u32,
    pub capped: bool,
    pub base_radius: f32,
    pub apex_radius: f32,
}

/// Cylinder with hemispherical caps.
pub struct Capsule {
    pub sectors: u32,
    pub body_segments: u32,
    pub cap_segments: u32,
    pub radius: f32,
}

//
// Inherent impls
//

impl<P: Parametric<Vertex2<Normal2, ()>>> Lathe<P> {
    /// TODO
    ///
    /// # Panics
    /// If `sectors` < 3.
    pub fn new(points: P, sectors: u32, segments: u32) -> Self {
        assert!(sectors >= 3, "sectors must be at least 3, was {sectors}");
        Self {
            points,
            sectors,
            segments,
            capped: false,
            az_range: turns(0.0)..turns(1.0),
        }
    }

    #[must_use]
    pub fn capped(self, capped: bool) -> Self {
        Self { capped, ..self }
    }

    /// Builds the lathe mesh.
    #[inline(never)]
    #[must_use]
    pub fn build_with<A>(
        self,
        f: &mut dyn FnMut(Point3, Normal3, TexCoord) -> Vertex3<A>,
    ) -> Mesh<A> {
        let secs = self.sectors as usize;
        let segs = self.segments as usize;
        let caps = 2 * self.capped as usize;

        // Fencepost problem: n + 1 vertices for n segments
        let verts_per_sec = segs + 1;

        // Precompute capacity
        let n_faces = segs * secs * 2 + (secs - 2) * caps;
        let n_verts = verts_per_sec * (secs + 1) + secs * caps;
        let mut m = Mesh {
            faces: Vec::with_capacity(n_faces),
            verts: Vec::with_capacity(n_verts),
        };

        create_faces(secs, verts_per_sec, &mut m.faces);
        create_verts(
            f,
            &self.points,
            secs,
            verts_per_sec,
            self.az_range,
            &mut m.verts,
        );

        // Create optional caps
        if self.capped && verts_per_sec > 0 {
            let l = m.verts.len();
            // Duplicate the bottom ring of vertices to make the bottom cap...
            make_cap(&mut m, f, 0..secs, -Vec3::Y);
            // ...and the top vertices to make the top cap
            make_cap(&mut m, f, l - secs..l, Vec3::Y);
        }
        m
    }
}

#[inline(never)]
fn create_faces(secs: usize, verts_per_sec: usize, out: &mut Vec<Tri<usize>>) {
    for j in 1..verts_per_sec {
        let n = secs + 1;
        for i in 1..n {
            let p = (j - 1) * n + i - 1;
            let q = (j - 1) * n + i;
            let r = j * n + i - 1;
            let s = j * n + i;
            // TODO could alternate direction of diagonal
            //    - or support quads
            // r _____ s       _____
            //   |/|/|    ->   |\|/|
            // p |/|/| q       |/|\|
            out.push(tri(p, q, s));
            out.push(tri(p, s, r));
        }
    }
}

#[inline(never)]
fn create_verts<A>(
    f: &mut dyn FnMut(Point3, Normal3, TexCoord) -> Vertex3<A>,
    pts: &dyn Parametric<Vertex2<Normal2, ()>>,
    secs: usize,
    verts_per_sec: usize,
    az_range: Range<Angle>,
    out: &mut Vec<Vertex3<A>>,
) {
    let Range { start, end } = az_range;
    let rot = rotate2((end - start) / secs as f32);
    let start = rotate2(start);

    // Create vertices
    for (v, Vertex { pos, attrib: n }) in 0.0
        .vary_to(1.0, verts_per_sec as u32)
        .map(|t| (t, pts.eval(t)))
    {
        let mut pos_xz = start.apply(&pt2(pos.x(), 0.0));
        let mut n_xz = start.apply(&vec2(n.x(), 0.0));

        for u in 0..=secs {
            let pos = pt3(pos_xz.x(), pos.y(), pos_xz.y());
            let norm = vec3(n_xz.x(), n.y(), n_xz.y());
            let v = f(pos, norm, uv(u as f32 / secs as f32, v));
            out.push(v);

            pos_xz = rot.apply(&pos_xz);
            n_xz = rot.apply(&n_xz);
        }
    }
}

#[inline(never)]
fn make_cap<A>(
    m: &mut Mesh<A>,
    f: &mut dyn FnMut(Point3, Normal3, TexCoord) -> Vertex3<A>,
    rg: Range<usize>,
    n: Normal3,
) {
    let verts = &mut m.verts;
    let secs = rg.len();
    let l = verts.len();

    verts.reserve(secs);
    for i in rg {
        let p = verts[i].pos.to();
        let uv = uv(0.0, 0.0); // TODO
        verts.push(f(p, n, uv));
    }

    // Adjust winding depending on whether top or bottom
    let (j, k) = if n.y() < 0.0 { (1, 0) } else { (0, 1) };
    for i in 1..secs - 1 {
        m.faces.push(tri(l, l + i + j, l + i + k));
    }
}

//
// Local trait impls
//

// TODO impl Build<()>

impl<P: Parametric<Vertex2<Normal2, ()>>> Build<Normal3> for Lathe<P> {
    fn build(self) -> Mesh<Normal3> {
        self.build_with(&mut |p, n, _| vertex(p.to(), n))
    }
}
// TODO Shouldn't need parametric with normal if normal not used
impl<P: Parametric<Vertex2<Normal2, ()>>> Build<TexCoord> for Lathe<P> {
    fn build(self) -> Mesh<TexCoord> {
        self.build_with(&mut |p, _, tc| vertex(p.to(), tc))
    }
}
impl<P: Parametric<Vertex2<Normal2, ()>>> Build<(Normal3, TexCoord)>
    for Lathe<P>
{
    fn build(self) -> Mesh<(Normal3, TexCoord)> {
        self.build_with(&mut |p, n, tc| vertex(p.to(), (n, tc)))
    }
}

impl Sphere {
    fn lathe(self) -> Lathe<impl Parametric<Vertex2<Normal2, ()>>> {
        let Self { sectors, segments, radius } = self;
        let pts = move |t| {
            let a = (-0.25).lerp(&0.25, t);
            let n = polar(1.0, turns(a)).to_cart();
            vertex((n * radius).to_pt(), n)
        };
        Lathe::new(pts, sectors, segments)
    }
}

impl Build<Normal3> for Sphere {
    /// Builds a spherical mesh with normals.
    fn build(self) -> Mesh<Normal3> {
        self.lathe().build()
    }
}
impl Build<TexCoord> for Sphere {
    /// Builds a spherical mesh with texture coordinates.
    fn build(self) -> Mesh<TexCoord> {
        self.lathe().build()
    }
}

impl Torus {
    fn lathe(self) -> Lathe<impl Parametric<Vertex2<Normal2, ()>>> {
        let pts = move |t| {
            let a = 0.0.lerp(&1.0, t);
            let v = polar(self.minor_radius, turns(a)).to_cart();
            vertex(pt2(self.major_radius, 0.0) + v.to(), v.normalize())
        };
        Lathe::new(pts, self.major_sectors, self.minor_sectors)
    }
}
impl Build<Normal3> for Torus {
    /// Builds the toroidal mesh.
    fn build(self) -> Mesh<Normal3> {
        self.lathe().build()
    }
}
impl Build<TexCoord> for Torus {
    /// Builds the toroidal mesh.
    fn build(self) -> Mesh<TexCoord> {
        self.lathe().build()
    }
}

impl Build<Normal3> for Cylinder {
    /// Builds the cylindrical mesh.
    fn build(self) -> Mesh<Normal3> {
        #[rustfmt::skip]
        let Self { sectors, segments, capped, radius } = self;
        Cone {
            sectors,
            segments,
            capped,
            base_radius: radius,
            apex_radius: radius,
        }
        .build()
    }
}
impl Build<TexCoord> for Cylinder {
    /// Builds the cylindrical mesh.
    fn build(self) -> Mesh<TexCoord> {
        #[rustfmt::skip]
        let Self { sectors, segments, capped, radius } = self;
        Cone {
            sectors,
            segments,
            capped,
            base_radius: radius,
            apex_radius: radius,
        }
        .build()
    }
}

impl Cone {
    fn lathe(self) -> Lathe<impl Parametric<Vertex2<Normal2, ()>>> {
        assert!(self.segments > 0, "segments cannot be zero");

        let base_pt = pt2(self.base_radius, -1.0);
        let apex_pt = pt2(self.apex_radius, 1.0);
        let n = (base_pt - apex_pt).perp().normalize();

        let pts = move |t| {
            let pt = base_pt.lerp(&apex_pt, t);
            vertex(pt, n)
        };
        Lathe::new(pts, self.sectors, self.segments).capped(self.capped)
    }
}
impl Build<Normal3> for Cone {
    /// Builds the conical mesh.
    fn build(self) -> Mesh<Normal3> {
        self.lathe().build()
    }
}
impl Build<TexCoord> for Cone {
    /// Builds the conical mesh.
    fn build(self) -> Mesh<TexCoord> {
        self.lathe().build()
    }
}

impl Capsule {
    fn lathe(self) -> Lathe<impl Parametric<Vertex2<Normal2, ()>>> {
        #[rustfmt::skip]
        let Self { sectors, body_segments, cap_segments, radius } = self;
        assert!(body_segments > 0, "body segments cannot be zero");
        assert!(cap_segments > 0, "cap segments cannot be zero");

        // Must be collected to allow rev()
        let bottom_pts: Vec<_> = turns(-0.25)
            .vary_to(turns(0.0), cap_segments + 1)
            .take(cap_segments as usize)
            .map(|alt| polar(radius, alt).to_cart())
            .map(|v| vertex(pt2(0.0, -1.0) + v, v.normalize()))
            .collect();

        let top_pts = bottom_pts
            .iter()
            .map(|Vertex { pos, attrib: n }| {
                vertex(pt2(pos.x(), -pos.y()), vec2(n.x(), -n.y()))
            })
            .rev();

        let body_pts = (-1.0)
            .vary_to(1.0, body_segments + 1)
            .map(|t| vertex(pt2(radius, t), vec2(1.0, 0.0)));

        let pts: Vec<_> = bottom_pts
            .iter()
            .copied()
            .chain(body_pts)
            .chain(top_pts)
            .collect();

        let segments = 2 * cap_segments + body_segments;
        Lathe::new(Polyline::new(pts), sectors, segments)
    }
}

impl Build<Normal3> for Capsule {
    /// Builds the capsule mesh.
    fn build(self) -> Mesh<Normal3> {
        self.lathe().build()
    }
}
impl Build<TexCoord> for Capsule {
    /// Builds the capsule mesh.
    fn build(self) -> Mesh<TexCoord> {
        self.lathe().build()
    }
}

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

    type Mesh = super::Mesh<Normal3>;

    #[test]
    fn sphere_verts_faces() {
        let sectors = 4;
        let segments = 3;
        let s: Mesh = Sphere { sectors, segments, radius: 1.0 }.build();

        assert_eq!(s.faces.len() as u32, 2 * sectors * segments);
        assert_eq!(s.faces.len(), s.faces.capacity());

        assert_eq!(s.verts.len() as u32, (sectors + 1) * (segments + 1));
        assert_eq!(s.verts.len(), s.verts.capacity());
    }

    #[test]
    fn cylinder_verts_faces_capped() {
        let sectors = 4;
        let segments = 3;
        let c: Mesh = Cylinder {
            sectors,
            segments,
            capped: true,
            radius: 1.0,
        }
        .build();

        let faces_expected = 2 * sectors * segments + 2 * (sectors - 2);
        assert_eq!(c.faces.len() as u32, faces_expected);
        assert_eq!(c.faces.len(), c.faces.capacity());

        let verts_expected = (sectors + 1) * (segments + 1) + 2 * sectors;
        assert_eq!(c.verts.len() as u32, verts_expected);
        assert_eq!(c.verts.len(), c.verts.capacity());
    }

    #[test]
    fn cylinder_verts_faces_uncapped() {
        let sectors = 4;
        let segments = 3;
        let c: Mesh = Cylinder {
            sectors,
            segments,
            capped: false,
            radius: 1.0,
        }
        .build();

        let faces_expected = 2 * sectors * segments;
        assert_eq!(c.faces.len() as u32, faces_expected);
        assert_eq!(c.faces.len(), c.faces.capacity());

        let verts_expected = (sectors + 1) * (segments + 1);
        assert_eq!(c.verts.len() as u32, verts_expected);
        assert_eq!(c.verts.len(), c.verts.capacity());
    }

    #[test]
    fn capsule_verts_faces() {
        let sectors = 4;
        let body_segments = 2;
        let cap_segments = 2;
        let c: Mesh = Capsule {
            sectors,
            body_segments,
            cap_segments,
            radius: 1.0,
        }
        .build();

        let faces_expected =
            2 * sectors * body_segments + 2 * 2 * sectors * cap_segments;
        assert_eq!(c.faces.len() as u32, faces_expected);
        assert_eq!(c.faces.len(), c.faces.capacity());

        let verts_expected = (sectors + 1) * (body_segments + 1)
            + 2 * (sectors + 1) * (cap_segments);
        assert_eq!(c.verts.len() as u32, verts_expected);
        assert_eq!(c.verts.len(), c.verts.capacity());
    }

    #[test]
    fn torus_verts_faces_capped() {
        let major_sectors = 6;
        let minor_sectors = 4;
        let t: Mesh = Torus {
            major_radius: 1.0,
            minor_radius: 0.2,
            major_sectors,
            minor_sectors,
        }
        .build();

        let faces_expected = 2 * major_sectors * minor_sectors;
        assert_eq!(t.faces.len() as u32, faces_expected);
        assert_eq!(t.faces.len(), t.faces.capacity());

        let verts_expected = (major_sectors + 1) * (minor_sectors + 1);
        assert_eq!(t.verts.len() as u32, verts_expected);
        assert_eq!(t.verts.len(), t.verts.capacity());
    }
}