mirage-engine 0.1.1

Mirage, an immediate-mode 3D engine for simple games on desktop and the browser
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
use core::fmt;
use core::marker::PhantomData;

use bytemuck::{Pod, Zeroable};

use crate::math::{Vec2, Vec3};
use crate::mesh::{Animation, Clip, Geometry, NoClips, NoParts, Part, Rig, Slot};
use crate::{Material, ReliefData, ShadingData, TextureData};

/// One corner of a mesh.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct Vertex {
    /// Corner position, in mesh space, in meters.
    pub position: Vec3,
    /// The corner's outward direction, used for lighting.
    pub normal: Vec3,
    /// The texture coordinate, `(0, 0)` at the texture's top left.
    pub uv: Vec2,
}

impl Vertex {
    /// A vertex at `position`, with `normal` and `uv`.
    pub const fn new(position: Vec3, normal: Vec3, uv: Vec2) -> Self {
        Self {
            position,
            normal,
            uv,
        }
    }
}

/// A mesh's vertices and indices, in the slots the parts `P` select, posed
/// by the clips `C` name.
///
/// The indices define counter-clockwise triangles; the draw's transform places
/// and scales the mesh.
#[derive(Clone, Debug)]
pub struct MeshData<P: Part = NoParts, C: Clip = NoClips> {
    /// Empty where the mesh has errors: such a mesh draws nothing.
    geometry: Geometry,
    /// The errors in how the mesh was built, which startup reports for a
    /// cataloged value.
    errors: Vec<MeshError>,
    parts: PhantomData<P>,
    clips: PhantomData<C>,
}

impl MeshData {
    /// A mesh of one slot, drawn with [`Material::default`].
    ///
    /// Every index must point to a vertex; one past them is an error the
    /// catalog run reports. Every triangle's three indices run
    /// counter-clockwise seen from outside the mesh: a triangle seen from
    /// behind is not drawn.
    pub fn new(vertices: Vec<Vertex>, indices: Vec<u32>) -> Self {
        let whole = Slot::new(indices.len() as u32, Material::default());
        Self::assembled(vertices, indices, vec![whole])
    }

    /// Sets the material of every slot.
    #[must_use]
    pub fn with_material(mut self, material: Material) -> Self {
        for slot in self.geometry.slots_mut() {
            slot.set_material(material);
        }
        self
    }

    /// Samples every slot from `texture`, in place of a white default.
    #[must_use]
    pub fn with_texture(mut self, texture: TextureData) -> Self {
        for slot in self.geometry.slots_mut() {
            slot.set_texture(texture.clone());
        }
        self
    }

    /// Reads the relief of every slot from `relief`.
    ///
    /// See [`Slot::relief`] for what the channels hold and which draws read
    /// them.
    #[must_use]
    pub fn with_relief(mut self, relief: ReliefData) -> Self {
        for slot in self.geometry.slots_mut() {
            slot.set_relief(relief.clone());
        }
        self
    }

    /// Reads the shading of every slot from `shading`.
    ///
    /// See [`Slot::shading`] for what the channels hold and what each one
    /// scales.
    #[must_use]
    pub fn with_shading(mut self, shading: ShadingData) -> Self {
        for slot in self.geometry.slots_mut() {
            slot.set_shading(shading.clone());
        }
        self
    }

    /// Reads the light every slot casts per texel from `emissive`.
    ///
    /// See [`Slot::emissive_map`] for what scales it.
    #[must_use]
    pub fn with_emissive_map(mut self, emissive: TextureData) -> Self {
        for slot in self.geometry.slots_mut() {
            slot.set_emissive_map(emissive.clone());
        }
        self
    }
}

impl<P: Part> MeshData<P, NoClips> {
    /// A mesh of one slot per part, in the order the parts count themselves,
    /// each slot taking the next indices.
    ///
    /// Required if you want a generated mesh with parts a draw repaints one
    /// at a time. `slot` runs once per part, so every part has a slot. The
    /// slot lengths must cover the indices exactly; otherwise that is an
    /// error the catalog run reports. Every triangle's three indices run
    /// counter-clockwise seen from outside the mesh: a triangle seen from
    /// behind is not drawn.
    pub fn in_parts(
        vertices: Vec<Vertex>,
        indices: Vec<u32>,
        mut slot: impl FnMut(P) -> Slot,
    ) -> Self {
        let slots = P::all()
            .into_iter()
            .map(|part| {
                let index = part.index();
                slot(part).named(index)
            })
            .collect();
        Self::assembled(vertices, indices, slots)
    }
}

impl<P: Part, C: Clip> MeshData<P, C> {
    /// The mesh's vertices, in the order the vertex buffer takes them.
    pub fn vertices(&self) -> &[Vertex] {
        self.geometry.vertices()
    }

    /// The triangle indices, three per triangle, counter-clockwise.
    pub fn indices(&self) -> &[u32] {
        self.geometry.indices()
    }

    /// The mesh's slots, in index order.
    pub fn slots(&self) -> &[Slot] {
        self.geometry.slots()
    }

    /// The mesh as the engine keeps it, its part type dropped, or the
    /// errors in how it was built: the build a mesh set calls ends in this
    /// call.
    #[doc(hidden)]
    pub fn erased(self) -> Result<Geometry, Vec<MeshError>> {
        if self.errors.is_empty() {
            Ok(self.geometry)
        } else {
            Err(self.errors)
        }
    }

    /// A mesh with nothing to draw — what an asset that never resolved
    /// becomes.
    pub(crate) fn empty() -> Self {
        Self::assembled(Vec::new(), Vec::new(), Vec::new())
    }

    /// A mesh whose slots already hold the index of the part naming each
    /// of them, as a loaded source resolves them.
    pub(crate) fn resolved(vertices: Vec<Vertex>, indices: Vec<u32>, slots: Vec<Slot>) -> Self {
        Self::assembled(vertices, indices, slots)
    }

    /// The same mesh posed by `rig`, with one animation per clip of `C` in
    /// clip order: what a model loads as.
    ///
    /// A mesh with errors in it draws nothing, so it keeps no joints either:
    /// the rig holds one entry per vertex, and that mesh has none.
    pub(crate) fn posed(mut self, rig: Rig, clips: Vec<Animation>) -> Self {
        if self.errors.is_empty() {
            self.geometry = self.geometry.posed(rig, clips);
        }
        self
    }

    fn assembled(vertices: Vec<Vertex>, indices: Vec<u32>, slots: Vec<Slot>) -> Self {
        let errors = MeshError::found(&vertices, &indices, &slots);
        let geometry = if errors.is_empty() {
            Geometry::over(vertices, indices, slots)
        } else {
            Geometry::empty()
        };
        Self {
            geometry,
            errors,
            parts: PhantomData,
            clips: PhantomData,
        }
    }
}

/// One error in how a mesh was built, which startup reports under the
/// mesh type's name.
#[doc(hidden)]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum MeshError {
    /// An index reaches past the vertices.
    IndexPastVertices { index: u32, vertices: usize },
    /// The slots cover another count of indices than the mesh holds.
    SlotsCoverage { covered: u64, indices: usize },
}

impl MeshError {
    /// Every error in a mesh built from these.
    fn found(vertices: &[Vertex], indices: &[u32], slots: &[Slot]) -> Vec<Self> {
        let past = indices
            .iter()
            .copied()
            .find(|&index| (index as usize) >= vertices.len())
            .map(|index| Self::IndexPastVertices {
                index,
                vertices: vertices.len(),
            });
        let covered: u64 = slots.iter().map(|slot| u64::from(slot.index_count())).sum();
        let uncovered = (covered != indices.len() as u64).then_some(Self::SlotsCoverage {
            covered,
            indices: indices.len(),
        });

        past.into_iter().chain(uncovered).collect()
    }
}

impl fmt::Display for MeshError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IndexPastVertices { index, vertices } => {
                write!(f, "has the index {index} past its {vertices} vertices")
            }
            Self::SlotsCoverage { covered, indices } => {
                write!(
                    f,
                    "has slots covering {covered} indices where it holds {indices}"
                )
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Color;
    use crate::math::UVec2;

    fn corners(count: usize) -> Vec<Vertex> {
        vec![Vertex::new(Vec3::ZERO, Vec3::Y, Vec2::ZERO); count]
    }

    /// Three parts named by hand, in this order.
    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
    enum Third {
        First,
        Second,
        Last,
    }

    impl Part for Third {
        fn from_name(_name: &str) -> Option<Self> {
            None
        }

        fn all() -> Vec<Self> {
            vec![Self::First, Self::Second, Self::Last]
        }

        fn index(&self) -> u32 {
            *self as u32
        }
    }

    #[test]
    fn the_memory_a_mesh_holds_counts_its_corners_its_indices_and_its_pixels() {
        let plain = MeshData::new(corners(6), (0..6).collect())
            .erased()
            .expect("built whole");
        let painted = MeshData::new(corners(6), (0..6).collect())
            .with_texture(TextureData::rgba8(UVec2::splat(2), vec![0; 16]))
            .erased()
            .expect("built whole");

        assert_eq!(
            plain.bytes(),
            6 * size_of::<Vertex>() + 6 * size_of::<u32>()
        );
        assert_eq!(
            painted.bytes(),
            plain.bytes() + 16,
            "and the texels it samples"
        );
    }

    #[test]
    fn a_mesh_in_parts_has_one_slot_per_part_in_the_order_they_count_themselves() {
        let mesh = MeshData::in_parts(corners(6), (0..6).collect(), |part: Third| match part {
            Third::First => Slot::new(3, Material::default()),
            Third::Second => Slot::new(2, Material::color(Color::BLACK)),
            Third::Last => Slot::new(1, Material::default()),
        })
        .erased()
        .expect("built whole");

        assert_eq!(mesh.part_count(), 3);
        assert_eq!(mesh.part_indices(0), 0..3);
        assert_eq!(mesh.part_indices(1), 3..5);
        assert_eq!(mesh.part_indices(2), 5..6);
        assert_eq!(
            mesh.part_of(1),
            Some(1),
            "and each slot resolves to its part"
        );
        assert_eq!(mesh.part_material(1), Material::color(Color::BLACK));
    }

    #[test]
    fn slots_that_do_not_cover_the_indices_exactly_are_an_error_and_draw_nothing() {
        let short = |part: Third| {
            Slot::new(
                if part == Third::First { 2 } else { 0 },
                Material::default(),
            )
        };
        let mesh = MeshData::in_parts(corners(6), (0..6).collect(), short);

        assert!(mesh.indices().is_empty(), "nothing of it is drawn");
        let errors = mesh.erased().expect_err("the slots stop short");
        assert_eq!(
            errors,
            vec![MeshError::SlotsCoverage {
                covered: 2,
                indices: 6
            }]
        );
        assert_eq!(
            errors[0].to_string(),
            "has slots covering 2 indices where it holds 6"
        );
    }

    #[test]
    fn an_index_past_the_vertices_is_an_error() {
        let mesh = MeshData::new(corners(2), vec![0, 1, 2]);

        assert!(mesh.vertices().is_empty());
        let errors = mesh.erased().expect_err("the last index reaches past");
        assert_eq!(
            errors,
            vec![MeshError::IndexPastVertices {
                index: 2,
                vertices: 2
            }]
        );
        assert_eq!(errors[0].to_string(), "has the index 2 past its 2 vertices");
    }

    #[test]
    fn a_mesh_of_one_slot_has_no_part_to_name_it_by() {
        let mesh = MeshData::new(corners(3), vec![0, 1, 2])
            .with_material(Material::color(Color::BLACK))
            .erased()
            .expect("built whole");

        assert_eq!(mesh.part_of(0), None);
        assert_eq!(mesh.part_indices(0), 0..3);
        assert_eq!(mesh.part_material(0), Material::color(Color::BLACK));
    }

    #[test]
    fn the_maps_a_generated_mesh_is_built_with_are_drawn_from_its_slot() {
        let pixels = |value| vec![value; 4];
        let mesh = MeshData::new(corners(3), vec![0, 1, 2])
            .with_shading(ShadingData::rgba8(UVec2::ONE, pixels(3)))
            .with_emissive_map(TextureData::rgba8(UVec2::ONE, pixels(7)))
            .erased()
            .expect("built whole");

        assert_eq!(
            mesh.part_shading(0),
            Some(&ShadingData::rgba8(UVec2::ONE, pixels(3)))
        );
        assert_eq!(
            mesh.part_emissive(0),
            Some(&TextureData::rgba8(UVec2::ONE, pixels(7)))
        );
    }

    #[test]
    fn a_mesh_with_nothing_in_it_draws_no_parts() {
        let mesh = MeshData::<NoParts>::empty()
            .erased()
            .expect("drawing nothing is no error");

        assert_eq!(mesh.part_count(), 0);
    }
}