mirage-engine 0.1.0

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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! What a model drawn in a pose reads back, and what it casts.

use super::*;
use crate::mesh::{Clip, NoClips, NoParts, Posing};

/// The skinned fixture, read from the working directory a test runs in: a
/// wall of four rings of corners up a rig of three joints, under the clips
/// `idle` and `walk`.
const WALKER: &str = "tests/assets/a_rig.glb";

/// The time along `walk` the clip moves the wall furthest: its middle key,
/// where its first key and its last both leave it at rest.
const LEANING: f32 = 0.458_333_34;

/// The side of the target every scene below is read off.
const TALL: u32 = 64;

/// The camera every wall below is seen from: level with the middle of it,
/// over four meters of world each way, so a corner the clip swings two
/// meters is still drawn.
const ASIDE: Camera = Camera::new(
    View::look_at(Vec3::new(8.0, 1.5, 0.0), Vec3::new(0.0, 1.5, 0.0)),
    Projection::orthographic(4.0),
);

meshes! { enum WalkerSet { Walker, Bare } }
meshes! { enum StandingSet { Walker, Ground } }

/// The clips the fixture holds, spelled out by hand: the derive names
/// `::mirage_engine`, which the engine's own tests are not.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
enum Paces {
    Idle,
    Walk,
}

impl Clip for Paces {
    fn from_name(name: &str) -> Option<Self> {
        match name {
            "idle" => Some(Self::Idle),
            "walk" => Some(Self::Walk),
            _ => None,
        }
    }

    fn all() -> Vec<Self> {
        vec![Self::Idle, Self::Walk]
    }

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

/// The model of that source, posed by the clips it holds.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
struct Walker;

impl Catalog for Walker {
    fn catalog() -> Vec<Self> {
        vec![Self]
    }
}

impl Mesh<NoParts, Paces> for Walker {
    fn build(&self, assets: &Assets) -> MeshData<NoParts, Paces> {
        assets.model("Rig")
    }
}

/// The same corners as a mesh of that source, with no joints at all.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
struct Bare;

impl Catalog for Bare {
    fn catalog() -> Vec<Self> {
        vec![Self]
    }
}

impl Mesh<NoParts, NoClips> for Bare {
    fn build(&self, assets: &Assets) -> MeshData {
        assets.mesh("BodyMesh")
    }
}

/// The wall drawn unlit, so every pixel of it reads back white against the
/// sky: either the model in the pose `at` holds, or the same corners with no
/// joints, and at `standing` on the ground.
struct Wall {
    at: Option<f32>,
    joints: bool,
    standing: Vec3,
}

impl Wall {
    /// The model posed at the middle key of `walk`.
    fn leaning() -> Self {
        Self {
            at: Some(LEANING),
            joints: true,
            standing: Vec3::ZERO,
        }
    }

    /// The same model in no pose at all.
    fn at_rest() -> Self {
        Self {
            at: None,
            joints: true,
            standing: Vec3::ZERO,
        }
    }
}

impl Game for Wall {
    type Meshes = WalkerSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        ctx.set_camera(ASIDE);
        let white = Material::color(Color::WHITE);
        if !self.joints {
            ctx.draw(Bare.at(self.standing).material(white));
            return;
        }
        let walker = Walker.at(self.standing).material(white);
        ctx.draw(match self.at {
            Some(at) => walker.posed_by(Posing::clip(Paces::Walk.index(), at)),
            None => walker,
        });
    }
}

/// One step of `scene` read back off a target `TALL` pixels square.
fn walled(scene: Wall) -> Option<Vec<u8>> {
    sized(
        raw("headless poses").with_assets([WALKER]),
        UVec2::splat(TALL),
        scene,
    )
}

/// The pixel `x` across and `y` down one of those targets.
fn read(pixels: &[u8], x: u32, y: u32) -> [u8; 4] {
    let at = ((y * TALL + x) * 4) as usize;
    [pixels[at], pixels[at + 1], pixels[at + 2], pixels[at + 3]]
}

/// Whether that pixel is the wall itself, which is drawn white where
/// nothing else is.
fn wall(pixels: &[u8], x: u32, y: u32) -> bool {
    read(pixels, x, y) == [u8::MAX; 4]
}

#[test]
fn a_model_in_no_pose_draws_the_corners_a_mesh_with_no_joints_draws() {
    let Some(posed) = walled(Wall::at_rest()) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(bare) = walled(Wall {
        at: None,
        joints: false,
        standing: Vec3::ZERO,
    }) else {
        return;
    };

    assert!(drawn_pixels(&posed) > 0, "the wall is drawn at all");
    assert_eq!(
        posed, bare,
        "a model at rest reads back as the same corners drawn with no joints"
    );
}

#[test]
fn a_posed_draw_is_drawn_where_its_clip_holds_its_corners() {
    let Some(resting) = walled(Wall::at_rest()) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(leaning) = walled(Wall::leaning()) else {
        return;
    };

    assert_ne!(resting, leaning, "the pose reaches the corners drawn");
    assert!(
        wall(&resting, TALL / 2, 10) && !wall(&leaning, TALL / 2, 10),
        "the top of the wall stands in the middle of the target at rest and \
         the pose leans it out of there"
    );
    assert!(
        !wall(&resting, 5, 30) && wall(&leaning, 5, 30),
        "and leans it two meters across, where the rest never reaches"
    );
}

/// A ground plane with the wall on it, lit by a sun across it, seen from
/// above: the shadow the wall casts lies along the ground from where it is
/// drawn.
struct Standing {
    at: Option<f32>,
}

impl Game for Standing {
    type Meshes = StandingSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        ctx.set_camera(Camera::new(
            View::look_at(Vec3::Y * 12.0, Vec3::ZERO).with_up(Vec3::NEG_Z),
            Projection::orthographic(ACROSS),
        ));
        ctx.light(Light::directional(Vec3::new(1.0, -1.0, 0.0), Color::WHITE).shadow());
        ctx.draw(
            Ground::Floor
                .at(Transform::from_scale(Vec3::splat(ACROSS)))
                .material(Material::lit(Color::WHITE)),
        );
        let walker = Walker.at(Vec3::ZERO).material(Material::lit(Color::WHITE));
        ctx.draw(match self.at {
            Some(at) => walker.posed_by(Posing::clip(Paces::Walk.index(), at)),
            None => walker,
        });
    }
}

/// The light left at the pixel `x` across and `y` down one of those
/// targets, which the sun's own map darkens wherever the wall casts.
fn sunlit(pixels: &[u8], x: u32, y: u32) -> u8 {
    pixels[((y * YARD + x) * 4) as usize]
}

/// One step of that scene, read off a `YARD`-sized target.
fn shadowed(at: Option<f32>) -> Option<Vec<u8>> {
    let config = raw("headless posed shadow")
        .with_assets([WALKER])
        .with_shadow_resolution(512);

    sized(config, UVec2::splat(YARD), Standing { at })
}

#[test]
fn the_shadow_of_a_posed_draw_follows_the_pose_it_is_drawn_in() {
    let Some(resting) = shadowed(None) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(leaning) = shadowed(Some(LEANING)) else {
        return;
    };

    // The far end of the shadow the wall casts at rest, three meters along
    // the sun from where it is drawn, and the ground the pose takes that end
    // over instead.
    let (end, leaned) = ((56, 32), (45, 45));
    assert!(
        sunlit(&resting, end.0, end.1) < sunlit(&leaning, end.0, end.1),
        "the ground the wall shadows at rest is lit once the pose leans off \
         it: {} against {}",
        sunlit(&resting, end.0, end.1),
        sunlit(&leaning, end.0, end.1)
    );
    assert!(
        sunlit(&leaning, leaned.0, leaned.1) < sunlit(&resting, leaned.0, leaned.1),
        "and the ground the pose leans over is shadowed where the rest left \
         it lit: {} against {}",
        sunlit(&leaning, leaned.0, leaned.1),
        sunlit(&resting, leaned.0, leaned.1)
    );
    assert_eq!(
        sunlit(&resting, 5, 5),
        sunlit(&leaning, 5, 5),
        "and the ground neither of them reaches is left as it was"
    );
}

#[test]
fn a_draw_the_pose_of_a_clip_reaches_into_is_drawn_where_its_rest_is_not() {
    // Four meters along `-Z`, where the sphere over the wall's own corners
    // lies outside what the camera covers, whole, and the sphere over every
    // pose its clips reach crosses into it.
    let standing = Vec3::new(0.0, 0.0, -4.0);
    let Some(resting) = walled(Wall {
        at: None,
        joints: true,
        standing,
    }) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(leaning) = walled(Wall {
        at: Some(LEANING),
        joints: true,
        standing,
    }) else {
        return;
    };
    let Some(empty) = walled(Wall {
        at: None,
        joints: true,
        standing: Vec3::new(0.0, 0.0, -40.0),
    }) else {
        return;
    };

    let covered = |pixels: &[u8]| {
        (0..TALL)
            .flat_map(|y| (0..TALL).map(move |x| (x, y)))
            .filter(|&(x, y)| wall(pixels, x, y))
            .count()
    };

    assert_eq!(
        covered(&resting),
        covered(&empty),
        "the rest covers nothing"
    );
    assert_eq!(resting, empty, "so it reads back as an empty target");
    assert!(
        covered(&leaning) > 0,
        "and the pose that leans into the view is drawn there"
    );
}

#[test]
fn posed_draws_of_one_model_are_drawn_in_one_instanced_draw() {
    let scene = Crowd {
        count: 3,
        apart: 2.0,
        drift: 0.0,
    };
    let config = raw("headless crowd").with_assets([WALKER]);
    let Ok(mut session) = Session::new(config, UVec2::splat(TALL), |_ctx| Ok(scene)) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    let stats = session.step();
    assert_eq!(stats.instances(), 3, "one instance per draw");
    assert_eq!(
        stats.draw_calls(),
        1,
        "and one instanced draw over the three of them"
    );
}

#[test]
fn a_frame_of_more_poses_than_the_palette_holds_draws_every_one_of_them() {
    // Each draw is posed one step further along the clip than the one
    // before it, so every one takes a run of the palette of its own, past
    // the matrix count it starts with room for. The step is small enough
    // that no corner moves as far as a pixel, so every one of the draws
    // lands where the first of them does.
    let drifting = Crowd {
        count: 90,
        apart: 0.0,
        drift: 1e-7,
    };
    let Some(many) = crowded(drifting) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Some(alone) = crowded(Crowd {
        count: 1,
        apart: 0.0,
        drift: 0.0,
    }) else {
        return;
    };

    assert!(drawn_pixels(&alone) > 0, "the wall is drawn at all");
    assert_eq!(
        many, alone,
        "the draws past what the palette held read the poses they were given"
    );
}

/// One step of `scene` read back off a target `TALL` pixels square.
fn crowded(scene: Crowd) -> Option<Vec<u8>> {
    sized(
        raw("headless crowd").with_assets([WALKER]),
        UVec2::splat(TALL),
        scene,
    )
}

/// A few draws of the model, `apart` meters along `X` from each other and
/// each posed `drift` seconds along the clip from the one before it, where
/// the camera covers them all.
struct Crowd {
    count: u32,
    apart: f32,
    drift: f32,
}

impl Game for Crowd {
    type Meshes = WalkerSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        ctx.set_camera(Camera::new(
            View::look_at(Vec3::new(0.0, 1.5, 16.0), Vec3::new(0.0, 1.5, 0.0)),
            Projection::orthographic(12.0),
        ));
        for at in 0..self.count {
            let along = LEANING + at as f32 * self.drift;
            ctx.draw(
                Walker
                    .at(Vec3::X * (at as f32 * self.apart))
                    .material(Material::color(Color::WHITE))
                    .posed_by(Posing::clip(Paces::Walk.index(), along)),
            );
        }
    }
}