primase-core 0.2.0

primase core: the world store, core components, frames, the pass manager and gates
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
//! Collision as the source states it, before any triangles: shapes (`core.collider`) and heightfields
//! (`core.heightfield`). Lowering them to `core.collision` triangles is a pass (`tessellate-colliders`) that only the
//! outputs needing triangles run; the shapes follow Khronos `KHR_implicit_shapes`, so a glTF output can carry them.

use serde::Serialize;
use serde_json::{Value, json};

use crate::{Component, Entity, JsonError, Surfaces, World};

/// `core.collider`: a collision shape in the entity's own space, placed like `core.collision` (on a prototype, by its
/// instances; else by the entity's transform). The geometry is exact under the entity's full transform: a sphere
/// under a non-uniform scale is an ellipsoid. A source whose physics treats scale otherwise (PhysX scales a sphere's
/// radius by its largest axis) has its lowering pass choose the shape and transform that collide as the game does.
#[derive(Clone, Debug, PartialEq)]
pub struct Collider {
    pub shape: Shape,
    /// Into the world's `core.surfaces` (a heightfield's per-cell surfaces override it).
    pub surface: u16,
}

/// A collider's shape, in the entity's space, metres.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Shape {
    /// Centred on `center`, axis-aligned in the entity's space.
    Box {
        center: [f32; 3],
        half_extents: [f32; 3],
    },
    Sphere {
        center: [f32; 3],
        radius: f32,
    },
    /// The segment `a`-`b` swept by `radius`: the caps are included in its length.
    Capsule {
        a: [f32; 3],
        b: [f32; 3],
        radius: f32,
    },
    /// A cylinder from `a` to `b` (a disc is a short one).
    Cylinder {
        a: [f32; 3],
        b: [f32; 3],
        radius: f32,
    },
    /// The convex hull of the points (no faces are stored: a consumer builds the hull).
    Convex {
        points: Vec<[f32; 3]>,
    },
    /// The entity's [`Heightfield`].
    Heightfield,
}

/// Which corners a heightfield cell's two triangles share.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Diagonal {
    /// The cell's (column, row) corner and its (column + 1, row + 1) corner.
    Main,
    /// The cell's (column + 1, row) corner and its (column, row + 1) corner.
    Anti,
}

/// `core.heightfield`: a regular grid of heights in the entity's space: `columns` x `rows` samples along +X and +Z
/// from the origin, `spacing` metres apart (x, z), each a height along +Y. Cells are split into two triangles along
/// `diagonal`. A terrain's drawn surface and its collision are the same grid: drawing it is a later pass; colliding
/// with it is a [`Collider`] of shape [`Shape::Heightfield`] on the same entity.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Heightfield {
    pub columns: u32,
    pub rows: u32,
    pub spacing: [f32; 2],
    /// Metres, row by row (a row along +X, rows along +Z).
    pub heights: Vec<f32>,
    pub diagonal: Diagonal,
    /// One per cell (row by row, `(columns - 1) * (rows - 1)`), true where there is no surface.
    pub holes: Option<Vec<bool>>,
    /// One per cell into `core.surfaces`; `None`: the collider's surface.
    pub surfaces: Option<Vec<u16>>,
}

impl Heightfield {
    /// The number of cells, `(columns - 1) * (rows - 1)`.
    pub fn cells(&self) -> usize {
        (self.columns.saturating_sub(1) as usize) * (self.rows.saturating_sub(1) as usize)
    }
}

fn finite(values: impl IntoIterator<Item = f32>, what: &str) -> Result<(), String> {
    match values.into_iter().find(|v| !v.is_finite()) {
        Some(v) => Err(format!("{what}: {v} is not finite")),
        None => Ok(()),
    }
}

fn positive(v: f32, what: &str) -> Result<(), String> {
    if v.is_finite() && v > 0.0 {
        Ok(())
    } else {
        Err(format!("{what} {v} is not positive"))
    }
}

fn surface_known(w: &World, s: u16) -> Result<(), String> {
    let known = w.resource::<Surfaces>().map_or(0, |t| t.0.len());
    if usize::from(s) < known {
        Ok(())
    } else {
        Err(format!("surface {s} past the world's {known} surfaces"))
    }
}

impl Component for Collider {
    const NAME: &'static str = "core.collider";
    const GEOMETRY: crate::Geometry = crate::Geometry::None;
    /// Exact or not at all: a convex shape's points mapped; a box under a map that keeps axes a box, under any other
    /// the convex hull of its eight mapped corners; a sphere, capsule or cylinder under a similarity (a rotation or
    /// mirror times a uniform scale) mapped with its radius scaled, under any other unsupported (a sheared sphere is
    /// an ellipsoid, no shape: tessellate it first); a heightfield shape follows its `core.heightfield`.
    fn apply_linear(&self, l: &crate::Linear) -> crate::world::Linearity<Self> {
        use crate::world::Linearity;
        let scaled = |r: f32, s: f64| (f64::from(r) * s) as f32;
        let shape = match &self.shape {
            Shape::Convex { points } => Shape::Convex {
                points: points.iter().map(|&p| l.point(p)).collect(),
            },
            Shape::Box { center, half_extents } => {
                let corners: Vec<[f32; 3]> = (0..8)
                    .map(|k| {
                        let sign = |bit: usize| if k & (1 << bit) == 0 { -1.0 } else { 1.0 };
                        l.point(std::array::from_fn(|i| center[i] + sign(i) * half_extents[i]))
                    })
                    .collect();
                if l.axis_map().is_some() {
                    let lo: [f32; 3] =
                        std::array::from_fn(|i| corners.iter().map(|c| c[i]).fold(f32::INFINITY, f32::min));
                    let hi: [f32; 3] = std::array::from_fn(|i| {
                        corners.iter().map(|c| c[i]).fold(f32::NEG_INFINITY, f32::max)
                    });
                    Shape::Box {
                        center: l.point(*center),
                        half_extents: std::array::from_fn(|i| (hi[i] - lo[i]) / 2.0),
                    }
                } else {
                    Shape::Convex { points: corners }
                }
            }
            Shape::Sphere { center, radius } => match l.similarity() {
                Some(s) => Shape::Sphere {
                    center: l.point(*center),
                    radius: scaled(*radius, s),
                },
                None => return Linearity::Unsupported,
            },
            Shape::Capsule { a, b, radius } => match l.similarity() {
                Some(s) => Shape::Capsule {
                    a: l.point(*a),
                    b: l.point(*b),
                    radius: scaled(*radius, s),
                },
                None => return Linearity::Unsupported,
            },
            Shape::Cylinder { a, b, radius } => match l.similarity() {
                Some(s) => Shape::Cylinder {
                    a: l.point(*a),
                    b: l.point(*b),
                    radius: scaled(*radius, s),
                },
                None => return Linearity::Unsupported,
            },
            Shape::Heightfield => return Linearity::Invariant,
        };
        Linearity::Applied(Collider {
            shape,
            surface: self.surface,
        })
    }
    /// The shape in full, a convex shape's points as a count.
    fn to_json(&self) -> Result<Option<Value>, JsonError> {
        let shape = match &self.shape {
            Shape::Convex { points } => json!({"convex": {"points": points.len()}}),
            other => crate::json::to_value(other)?,
        };
        Ok(Some(json!({"shape": shape, "surface": self.surface})))
    }
    /// Finite values, positive extents and radii, a known surface; a heightfield shape needs the entity's
    /// `core.heightfield`, a convex one a point.
    fn verify(&self, e: Entity, w: &World) -> Result<(), String> {
        surface_known(w, self.surface)?;
        match &self.shape {
            Shape::Box { center, half_extents } => {
                finite(*center, "box centre")?;
                half_extents
                    .iter()
                    .try_for_each(|&h| positive(h, "box half extent"))
            }
            Shape::Sphere { center, radius } => {
                finite(*center, "sphere centre")?;
                positive(*radius, "sphere radius")
            }
            Shape::Capsule { a, b, radius } | Shape::Cylinder { a, b, radius } => {
                finite(a.iter().chain(b).copied(), "axis ends")?;
                positive(*radius, "radius")
            }
            Shape::Convex { points } => {
                if points.is_empty() {
                    return Err("a convex shape without points".into());
                }
                finite(points.iter().flatten().copied(), "convex points")
            }
            Shape::Heightfield => {
                if w.has::<Heightfield>(e) {
                    Ok(())
                } else {
                    Err("a heightfield shape without the entity's core.heightfield".into())
                }
            }
        }
    }
}

impl Component for Heightfield {
    const NAME: &'static str = "core.heightfield";
    const GEOMETRY: crate::Geometry = crate::Geometry::None;
    /// A grid along +X and +Z with heights along +Y stays one exactly under a positive scale along each axis
    /// (`diag(sx, sy, sz)`, all positive): spacing times (sx, sz), heights times sy. Under any other map (a mirror, a
    /// rotation, a shear) unsupported: tessellate it first.
    fn apply_linear(&self, l: &crate::Linear) -> crate::world::Linearity<Self> {
        use crate::world::Linearity;
        let col = |k: usize| l.point(std::array::from_fn(|i| if i == k { 1.0 } else { 0.0 }));
        let (x, y, z) = (col(0), col(1), col(2));
        let diagonal = x[1] == 0.0 && x[2] == 0.0 && y[0] == 0.0 && y[2] == 0.0 && z[0] == 0.0 && z[1] == 0.0;
        if !(diagonal && x[0] > 0.0 && y[1] > 0.0 && z[2] > 0.0) {
            return Linearity::Unsupported;
        }
        let scale = |v: f32, s: f32| (f64::from(v) * f64::from(s)) as f32;
        let mut h = self.clone();
        h.spacing = [scale(h.spacing[0], x[0]), scale(h.spacing[1], z[2])];
        h.heights.iter_mut().for_each(|v| *v = scale(*v, y[1]));
        Linearity::Applied(h)
    }
    /// The grid's shape and options, the heights, holes and surfaces as counts.
    fn to_json(&self) -> Result<Option<Value>, JsonError> {
        Ok(Some(json!({
            "columns": self.columns,
            "rows": self.rows,
            "spacing": crate::json::to_value(&self.spacing)?,
            "heights": self.heights.len(),
            "diagonal": crate::json::to_value(&self.diagonal)?,
            "holes": self.holes.as_ref().map(|h| h.iter().filter(|&&x| x).count()),
            "surfaces": self.surfaces.as_ref().map(Vec::len),
        })))
    }
    /// At least 2 x 2 samples, positive spacing, finite heights, one height per sample, and holes and surfaces (known
    /// to the world) one per cell.
    fn verify(&self, _e: Entity, w: &World) -> Result<(), String> {
        if self.columns < 2 || self.rows < 2 {
            return Err(format!(
                "{} x {} samples: a heightfield has at least 2 x 2",
                self.columns, self.rows
            ));
        }
        self.spacing.iter().try_for_each(|&s| positive(s, "spacing"))?;
        let samples = self.columns as usize * self.rows as usize;
        if self.heights.len() != samples {
            return Err(format!("{} heights for {samples} samples", self.heights.len()));
        }
        finite(self.heights.iter().copied(), "heights")?;
        let cells = self.cells();
        if let Some(h) = &self.holes
            && h.len() != cells
        {
            return Err(format!("{} holes for {cells} cells", h.len()));
        }
        if let Some(s) = &self.surfaces {
            if s.len() != cells {
                return Err(format!("{} surfaces for {cells} cells", s.len()));
            }
            s.iter().try_for_each(|&s| surface_known(w, s))?;
        }
        Ok(())
    }
}

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

    fn world() -> World {
        let mut w = World::new();
        let mut s = Surfaces::default();
        s.index("concrete").unwrap();
        w.insert_resource(s);
        w
    }

    fn field(columns: u32, rows: u32) -> Heightfield {
        Heightfield {
            columns,
            rows,
            spacing: [1.0, 2.0],
            heights: vec![0.0; (columns * rows) as usize],
            diagonal: Diagonal::Main,
            holes: None,
            surfaces: None,
        }
    }

    #[test]
    fn shapes_verify_their_sizes_surfaces_and_heightfield() {
        let mut w = world();
        let ok = [
            Shape::Box {
                center: [0.0; 3],
                half_extents: [1.0, 2.0, 3.0],
            },
            Shape::Sphere {
                center: [0.0; 3],
                radius: 0.5,
            },
            Shape::Capsule {
                a: [0.0; 3],
                b: [0.0, 2.0, 0.0],
                radius: 0.5,
            },
            Shape::Convex {
                points: vec![[0.0; 3]],
            },
        ];
        for shape in ok {
            let e = w.spawn();
            w.insert(e, Collider { shape, surface: 0 });
        }
        let terrain = w.spawn();
        w.insert(terrain, field(3, 2));
        w.insert(
            terrain,
            Collider {
                shape: Shape::Heightfield,
                surface: 0,
            },
        );
        assert!(w.verify_components().is_empty(), "{:?}", w.verify_components());
        let bad = [
            (
                Shape::Sphere {
                    center: [0.0; 3],
                    radius: 0.0,
                },
                0,
                "sphere radius 0 is not positive",
            ),
            (
                Shape::Box {
                    center: [f32::NAN, 0.0, 0.0],
                    half_extents: [1.0; 3],
                },
                0,
                "box centre: NaN is not finite",
            ),
            (
                Shape::Convex { points: Vec::new() },
                0,
                "a convex shape without points",
            ),
            (
                Shape::Heightfield,
                0,
                "a heightfield shape without the entity's core.heightfield",
            ),
            (
                Shape::Sphere {
                    center: [0.0; 3],
                    radius: 1.0,
                },
                1,
                "surface 1 past the world's 1 surfaces",
            ),
        ];
        for (shape, surface, message) in bad {
            let mut w = world();
            let e = w.spawn();
            w.insert(e, Collider { shape, surface });
            assert_eq!(w.verify_components(), [("core.collider", e, message.to_owned())]);
        }
    }

    #[test]
    fn a_heightfield_has_a_height_per_sample_and_a_hole_per_cell() {
        for (f, message) in [
            (field(1, 2), "1 x 2 samples: a heightfield has at least 2 x 2"),
            (
                Heightfield {
                    heights: vec![0.0; 5],
                    ..field(3, 2)
                },
                "5 heights for 6 samples",
            ),
            (
                Heightfield {
                    holes: Some(vec![false; 3]),
                    ..field(3, 2)
                },
                "3 holes for 2 cells",
            ),
            (
                Heightfield {
                    surfaces: Some(vec![0, 4]),
                    ..field(3, 2)
                },
                "surface 4 past the world's 1 surfaces",
            ),
        ] {
            let mut w = world();
            let e = w.spawn();
            w.insert(e, f);
            assert_eq!(
                w.verify_components(),
                [("core.heightfield", e, message.to_owned())]
            );
        }
    }

    #[test]
    fn json_shows_shapes_and_counts() {
        let c = Collider {
            shape: Shape::Capsule {
                a: [0.0; 3],
                b: [0.0, 1.0, 0.0],
                radius: 0.25,
            },
            surface: 0,
        };
        assert_eq!(
            c.to_json().unwrap(),
            Some(
                json!({"shape": {"capsule": {"a": [0.0, 0.0, 0.0], "b": [0.0, 1.0, 0.0], "radius": 0.25}}, "surface": 0})
            )
        );
        let c = Collider {
            shape: Shape::Convex {
                points: vec![[0.0; 3]; 4],
            },
            surface: 0,
        };
        assert_eq!(
            c.to_json().unwrap(),
            Some(json!({"shape": {"convex": {"points": 4}}, "surface": 0}))
        );
        let h = Heightfield {
            holes: Some(vec![true, false]),
            ..field(3, 2)
        };
        assert_eq!(
            h.to_json().unwrap(),
            Some(
                json!({"columns": 3, "rows": 2, "spacing": [1.0, 2.0], "heights": 6, "diagonal": "main", "holes": 1, "surfaces": null})
            )
        );
    }
}