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
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
use core::fmt;
use std::sync::{Arc, Mutex};

use winit::window::Window;

use crate::Error;
use crate::math::UVec2;
use crate::platform::{AFTER_LOSS, AFTER_OUT_OF_MEMORY};

/// The depth buffer's format, shared by the texture and the pipelines that
/// test against it.
pub(crate) const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;

/// The smallest buffer a set of values is bound through, which is what a set
/// with no field of its own is still bound through.
pub(crate) const SMALLEST_VALUES: wgpu::BufferAddress = 16;

/// The device, queue, and surface a window draws through.
pub(crate) struct Gpu {
    instance: wgpu::Instance,
    window: Arc<Window>,
    device: wgpu::Device,
    queue: wgpu::Queue,
    surface: wgpu::Surface<'static>,
    format: wgpu::TextureFormat,
    physical_size: UVec2,
    faults: FaultSlot,
    adapter: String,
}

impl Gpu {
    /// Gets a device for `window`, sets up its surface, and keeps whatever
    /// fault the device reports from there on. `facts` is what the platform
    /// states of the adapter beyond what wgpu reads, in the log beside it.
    pub(crate) async fn new(
        instance: wgpu::Instance,
        window: Arc<Window>,
        facts: Option<String>,
    ) -> Result<Self, Error> {
        let surface = instance
            .create_surface(Arc::clone(&window))
            .map_err(|error| Error::msg(format!("no rendering surface for the window: {error}")))?;

        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: Some(&surface),
                ..Default::default()
            })
            .await
            .map_err(|error| Error::msg(format!("no usable graphics adapter: {error}")))?;
        let named = named(&adapter.get_info(), facts);
        log::info!("graphics adapter: {named}");

        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("mirage-engine"),
                ..Default::default()
            })
            .await
            .map_err(|error| {
                Error::msg(format!("the graphics adapter refused a device: {error}"))
            })?;
        let faults = FaultSlot::watching(&device);

        let capabilities = surface.get_capabilities(&adapter);
        let format = capabilities
            .formats
            .first()
            .copied()
            .ok_or_else(|| Error::msg("the rendering surface supports no texture format"))?;

        let physical_size = physical_size(&window);
        let mut gpu = Self {
            instance,
            window,
            device,
            queue,
            surface,
            format,
            physical_size,
            faults,
            adapter: named,
        };
        gpu.configure_surface();

        Ok(gpu)
    }

    /// The adapter the run draws on, as the startup log named it.
    pub(crate) fn adapter(&self) -> &str {
        &self.adapter
    }

    pub(crate) fn device(&self) -> &wgpu::Device {
        &self.device
    }

    pub(crate) fn queue(&self) -> &wgpu::Queue {
        &self.queue
    }

    pub(crate) fn window(&self) -> Arc<Window> {
        Arc::clone(&self.window)
    }

    /// The format frames are drawn in, sRGB-encoded when presented.
    pub(crate) fn target_format(&self) -> wgpu::TextureFormat {
        self.format.add_srgb_suffix()
    }

    /// The format the UI and a screen past the tone map draw in: the same
    /// pixels taken as the encoded values they hold, which is the space
    /// egui blends in.
    pub(crate) fn overlay_format(&self) -> wgpu::TextureFormat {
        self.format.remove_srgb_suffix()
    }

    pub(crate) fn physical_size(&self) -> UVec2 {
        self.physical_size
    }

    /// The fault last written to the slot, taken out of it; the run ends
    /// when this returns one, and no frame is drawn for that call.
    pub(crate) fn fault(&self) -> Option<Fault> {
        self.faults.taken()
    }

    pub(crate) fn request_frame(&self) {
        if self.drawable_size().is_some() {
            self.window.request_redraw();
        }
    }

    pub(crate) fn resize(&mut self, physical_size: UVec2) {
        if physical_size == self.physical_size {
            return;
        }
        self.physical_size = physical_size;
        self.configure_surface();
    }

    /// The frame to draw into, or `None` to skip drawing while the window has
    /// no area, or the surface is being replaced.
    pub(crate) fn begin_frame(&mut self) -> Option<Frame> {
        let size = self.drawable_size()?;
        let surface = self.acquire_surface_texture()?;
        let view = |format| {
            surface.texture.create_view(&wgpu::TextureViewDescriptor {
                format: Some(format),
                ..Default::default()
            })
        };
        let target = Target::new(
            view(self.target_format()),
            view(self.overlay_format()),
            size,
        );

        Some(Frame { surface, target })
    }

    pub(crate) fn present(&self, frame: Frame) {
        self.window.pre_present_notify();
        frame.surface.present();
    }

    fn acquire_surface_texture(&mut self) -> Option<wgpu::SurfaceTexture> {
        match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(frame) => Some(frame),
            wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => None,
            wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
                drop(frame);
                self.configure_surface();
                None
            }
            wgpu::CurrentSurfaceTexture::Outdated => {
                self.configure_surface();
                None
            }
            wgpu::CurrentSurfaceTexture::Lost => {
                self.rebuild_surface();
                None
            }
            wgpu::CurrentSurfaceTexture::Validation => {
                log::error!("the graphics driver rejected the request for a frame");
                None
            }
        }
    }

    /// The size to draw at, absent while the window is minimized to nothing.
    fn drawable_size(&self) -> Option<UVec2> {
        let size = self.physical_size;
        (size.x > 0 && size.y > 0).then_some(size)
    }

    fn configure_surface(&mut self) {
        let Some(size) = self.drawable_size() else {
            return;
        };

        self.surface.configure(
            &self.device,
            &wgpu::SurfaceConfiguration {
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                format: self.format,
                view_formats: vec![self.target_format(), self.overlay_format()],
                alpha_mode: wgpu::CompositeAlphaMode::Auto,
                width: size.x,
                height: size.y,
                desired_maximum_frame_latency: 2,
                present_mode: wgpu::PresentMode::AutoVsync,
            },
        );
    }

    fn rebuild_surface(&mut self) {
        match self.instance.create_surface(Arc::clone(&self.window)) {
            Ok(surface) => {
                self.surface = surface;
                self.configure_surface();
            }
            Err(error) => log::error!("the rendering surface could not be rebuilt: {error}"),
        }
    }
}

/// A graphics fault the run ends on, with the text wgpu stated about it.
pub(crate) enum Fault {
    /// The device was lost, and no work of the run's goes on past it.
    Lost(String),
    /// The device ran out of memory.
    OutOfMemory(String),
}

impl Fault {
    /// The fault a lost device reports: `text` where wgpu names one, else
    /// `reason`'s debug name.
    fn lost(reason: wgpu::DeviceLostReason, text: String) -> Self {
        match text.is_empty() {
            true => Self::Lost(format!("{reason:?}")),
            false => Self::Lost(text),
        }
    }

    /// The fault `error` ends the run on; `None` when the run goes on,
    /// dropping only the call `error` names.
    fn of(error: &wgpu::Error) -> Option<Self> {
        match error {
            wgpu::Error::OutOfMemory { source } => Some(Self::OutOfMemory(source.to_string())),
            wgpu::Error::Validation { .. } | wgpu::Error::Internal { .. } => None,
        }
    }

    /// What the player reads over the canvas or on the console: the fault,
    /// the `adapter` it happened on, and the platform's own next step.
    pub(crate) fn told(&self, adapter: &str) -> String {
        match self {
            Self::Lost(_) => format!(
                "The graphics device was lost on {adapter}: the graphics driver stopped responding. {AFTER_LOSS}"
            ),
            Self::OutOfMemory(_) => {
                format!("The graphics device on {adapter} ran out of memory. {AFTER_OUT_OF_MEMORY}")
            }
        }
    }
}

/// The adapter in one line: its name where wgpu reads one, `facts` where the
/// platform states any, its kind where wgpu states it, and its backend.
fn named(info: &wgpu::AdapterInfo, facts: Option<String>) -> String {
    let kind = match info.device_type {
        wgpu::DeviceType::IntegratedGpu => Some("integrated"),
        wgpu::DeviceType::DiscreteGpu => Some("discrete"),
        wgpu::DeviceType::VirtualGpu => Some("virtual"),
        wgpu::DeviceType::Cpu => Some("software"),
        wgpu::DeviceType::Other => None,
    };
    let backend = match info.backend {
        wgpu::Backend::Vulkan => "Vulkan",
        wgpu::Backend::Metal => "Metal",
        wgpu::Backend::Dx12 => "Direct3D 12",
        wgpu::Backend::Gl => "OpenGL",
        wgpu::Backend::BrowserWebGpu => "the browser's WebGPU",
        wgpu::Backend::Noop => "no backend",
    };
    let mut parts: Vec<String> = [Some(info.name.clone()), facts]
        .into_iter()
        .flatten()
        .filter(|part| !part.is_empty())
        .collect();
    if parts.is_empty() {
        parts.push("(no name given)".to_owned());
    }
    parts.extend(kind.map(str::to_owned));
    parts.push(backend.to_owned());

    parts.join(", ")
}

impl fmt::Display for Fault {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Lost(text) => write!(f, "the graphics device was lost: {text}"),
            Self::OutOfMemory(text) => write!(f, "the graphics device ran out of memory: {text}"),
        }
    }
}

/// The one slot every fault of the device reaches; it keeps the first fault
/// and drops the ones after it.
#[derive(Clone)]
pub(crate) struct FaultSlot(Arc<Mutex<Option<Fault>>>);

impl FaultSlot {
    /// The slot that fills with every fault `device` reports: that it was
    /// lost, or an error no scope caught.
    fn watching(device: &wgpu::Device) -> Self {
        let slot = Self(Arc::default());

        let lost = slot.clone();
        device.set_device_lost_callback(move |reason, text| lost.set(Fault::lost(reason, text)));

        let uncaught = slot.clone();
        device.on_uncaptured_error(Arc::new(move |error: wgpu::Error| {
            match Fault::of(&error) {
                Some(fault) => uncaught.set(fault),
                None => log::error!("the graphics device refused a call: {error}"),
            }
        }));

        slot
    }

    fn set(&self, fault: Fault) {
        let Ok(mut slot) = self.0.lock() else {
            return;
        };
        slot.get_or_insert(fault);
    }

    fn taken(&self) -> Option<Fault> {
        self.0.lock().ok()?.take()
    }
}

/// Target for one presented frame: what the tone map and the UI draw into,
/// and the size the projection uses.
pub(crate) struct Target {
    /// The view the tone map writes through: what it returns is sRGB-encoded
    /// on its way to the pixels.
    color: wgpu::TextureView,
    /// The same pixels taken as the encoded values they hold, which is what
    /// the UI blends in and what a screen past the tone map writes.
    encoded: wgpu::TextureView,
    size: UVec2,
}

impl Target {
    pub(crate) fn new(color: wgpu::TextureView, encoded: wgpu::TextureView, size: UVec2) -> Self {
        Self {
            color,
            encoded,
            size,
        }
    }

    pub(crate) fn color(&self) -> &wgpu::TextureView {
        &self.color
    }

    pub(crate) fn encoded(&self) -> &wgpu::TextureView {
        &self.encoded
    }

    pub(crate) fn size(&self) -> UVec2 {
        self.size
    }

    /// This target's aspect ratio, needed by the projection; the game never
    /// sets one.
    pub(crate) fn aspect(&self) -> f32 {
        let size = self.size();
        size.x as f32 / size.y as f32
    }
}

/// A window frame: its target, and the surface texture held until presented.
pub(crate) struct Frame {
    surface: wgpu::SurfaceTexture,
    target: Target,
}

impl Frame {
    pub(crate) fn target(&self) -> &Target {
        &self.target
    }
}

/// The depth buffer a `size`-sized target drawn over `samples` samples tests
/// against.
pub(crate) fn depth_texture(device: &wgpu::Device, size: UVec2, samples: u32) -> wgpu::Texture {
    texture(
        device,
        "mirage-engine depth",
        size,
        samples,
        DEPTH_FORMAT,
        &[],
    )
}

/// A `size`-sized texture called `label`, drawn into over `samples` samples;
/// viewed after that in its own format or any of `views`.
pub(crate) fn texture(
    device: &wgpu::Device,
    label: &str,
    size: UVec2,
    samples: u32,
    format: wgpu::TextureFormat,
    views: &[wgpu::TextureFormat],
) -> wgpu::Texture {
    device.create_texture(&wgpu::TextureDescriptor {
        label: Some(label),
        size: wgpu::Extent3d {
            width: size.x,
            height: size.y,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: samples,
        dimension: wgpu::TextureDimension::D2,
        format,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
        view_formats: views,
    })
}

/// A buffer the queue writes, never mapped at creation: `size` bytes,
/// `usage` plus `COPY_DST`, called `label`.
pub(crate) fn buffer(
    device: &wgpu::Device,
    label: &str,
    size: wgpu::BufferAddress,
    usage: wgpu::BufferUsages,
) -> wgpu::Buffer {
    device.create_buffer(&wgpu::BufferDescriptor {
        label: Some(label),
        size,
        usage: usage | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    })
}

/// A pipeline layout called `label`, binding `groups`.
pub(crate) fn pipeline_layout(
    device: &wgpu::Device,
    label: &str,
    groups: &[Option<&wgpu::BindGroupLayout>],
) -> wgpu::PipelineLayout {
    device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: Some(label),
        bind_group_layouts: groups,
        immediate_size: 0,
    })
}

/// A texture the fragment stage samples at `binding`; `filterable` where a
/// sampler filters it.
pub(crate) fn sampled(binding: u32, filterable: bool) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Texture {
            sample_type: wgpu::TextureSampleType::Float { filterable },
            view_dimension: wgpu::TextureViewDimension::D2,
            multisampled: false,
        },
        count: None,
    }
}

/// A sampler called `label` that clamps to the texture's edges on every
/// axis and filters what it samples, larger or smaller.
pub(crate) fn clamped_sampler(device: &wgpu::Device, label: &str) -> wgpu::Sampler {
    device.create_sampler(&wgpu::SamplerDescriptor {
        label: Some(label),
        address_mode_u: wgpu::AddressMode::ClampToEdge,
        address_mode_v: wgpu::AddressMode::ClampToEdge,
        address_mode_w: wgpu::AddressMode::ClampToEdge,
        mag_filter: wgpu::FilterMode::Linear,
        min_filter: wgpu::FilterMode::Linear,
        ..Default::default()
    })
}

/// The sampler a fragment stage reads a texture through at `binding`, which
/// filters what it samples.
pub(crate) fn sampler(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
        count: None,
    }
}

/// A buffer of values the stages `visibility` names read at `binding`.
pub(crate) fn uniform(binding: u32, visibility: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility,
        ty: wgpu::BindingType::Buffer {
            ty: wgpu::BufferBindingType::Uniform,
            has_dynamic_offset: false,
            min_binding_size: None,
        },
        count: None,
    }
}

fn physical_size(window: &Window) -> UVec2 {
    let size = window.inner_size();
    UVec2::new(size.width, size.height)
}

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

    /// What wgpu states under an error of its own.
    fn source(text: &'static str) -> wgpu::ErrorSource {
        Box::<dyn std::error::Error + Send + Sync>::from(text)
    }

    #[test]
    fn a_device_out_of_memory_ends_the_run_with_wgpu_s_own_text() {
        let error = wgpu::Error::OutOfMemory {
            source: source("the heap has no room left"),
        };

        match Fault::of(&error) {
            Some(fault) => assert_eq!(
                fault.to_string(),
                "the graphics device ran out of memory: the heap has no room left"
            ),
            None => panic!("running out of memory ends the run"),
        }
    }

    #[test]
    fn a_validation_or_internal_error_leaves_the_run_going() {
        let validation = wgpu::Error::Validation {
            source: source("the bind group is not the layout's"),
            description: "binding 3 is missing".to_owned(),
        };
        let internal = wgpu::Error::Internal {
            source: source("the backend stopped"),
            description: "a limit inside wgpu was reached".to_owned(),
        };

        assert!(
            Fault::of(&validation).is_none(),
            "only the call a validation error names is dropped"
        );
        assert!(Fault::of(&internal).is_none(), "and an internal one too");
    }

    #[test]
    fn a_lost_device_states_a_reason_whatever_wgpu_stated() {
        assert_eq!(
            Fault::lost(
                wgpu::DeviceLostReason::Unknown,
                "the driver timed out".to_owned()
            )
            .to_string(),
            "the graphics device was lost: the driver timed out"
        );
        assert_eq!(
            Fault::lost(wgpu::DeviceLostReason::Destroyed, String::new()).to_string(),
            "the graphics device was lost: Destroyed",
            "and wgpu naming no text of its own leaves the debug reason"
        );
    }

    #[test]
    fn the_slot_holds_the_first_fault_and_hands_it_over_once() {
        let slot = FaultSlot(Arc::default());
        slot.set(Fault::Lost("the driver timed out".to_owned()));
        slot.set(Fault::OutOfMemory("the heap has no room left".to_owned()));

        match slot.taken() {
            Some(fault) => assert_eq!(
                fault.to_string(),
                "the graphics device was lost: the driver timed out",
                "the fault that ended the run is the first one"
            ),
            None => panic!("a slot written to holds a fault"),
        }
        assert!(slot.taken().is_none(), "and it is taken out only once");
    }

    fn info(
        name: &str,
        device_type: wgpu::DeviceType,
        backend: wgpu::Backend,
    ) -> wgpu::AdapterInfo {
        wgpu::AdapterInfo {
            name: name.to_owned(),
            vendor: 0,
            device: 0,
            device_type,
            device_pci_bus_id: String::new(),
            driver: String::new(),
            driver_info: String::new(),
            backend,
            subgroup_min_size: 0,
            subgroup_max_size: 0,
            transient_saves_memory: false,
        }
    }

    #[test]
    fn the_adapter_line_states_what_is_known_and_never_an_empty_name() {
        assert_eq!(
            named(
                &info(
                    "NVIDIA GeForce RTX 3060 Laptop GPU",
                    wgpu::DeviceType::DiscreteGpu,
                    wgpu::Backend::Vulkan
                ),
                None
            ),
            "NVIDIA GeForce RTX 3060 Laptop GPU, discrete, Vulkan"
        );
        assert_eq!(
            named(
                &info("", wgpu::DeviceType::Other, wgpu::Backend::BrowserWebGpu),
                Some("amd gcn-5".to_owned())
            ),
            "amd gcn-5, the browser's WebGPU",
            "a browser names no adapter, so what it states of it stands in"
        );
        assert_eq!(
            named(
                &info("", wgpu::DeviceType::Other, wgpu::Backend::BrowserWebGpu),
                None
            ),
            "(no name given), the browser's WebGPU"
        );
    }

    #[test]
    fn a_fault_tells_the_player_the_adapter_and_the_next_step() {
        let told = Fault::Lost("Device is lost".to_owned()).told("amd gcn-5, the browser's WebGPU");
        assert_eq!(
            told,
            format!(
                "The graphics device was lost on amd gcn-5, the browser's WebGPU: the graphics driver stopped responding. {AFTER_LOSS}"
            )
        );
        let told =
            Fault::OutOfMemory("no room".to_owned()).told("Intel UHD 620, integrated, Vulkan");
        assert_eq!(
            told,
            format!(
                "The graphics device on Intel UHD 620, integrated, Vulkan ran out of memory. {AFTER_OUT_OF_MEMORY}"
            )
        );
    }
}