mln-rs-runtime 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
//! What a render session renders into, and how it attaches.

// The matches over the backends' enums list a variant per backend that the
// build's features and target have, so whether their `_` arm is unreachable,
// or matches a single variant, and whether a `let` of one variant is
// irrefutable, depends on the build.
#![allow(
    unreachable_patterns,
    irrefutable_let_patterns,
    clippy::match_wildcard_for_single_variants,
    reason = "the backends' variants depend on the build's features and target"
)]

use std::sync::Arc;

use mln_gfx::Window;
pub use mln_gfx::backend::Type as BackendType;
pub use mln_gfx::{
    ConsumerSync, DepthStencilFormat, DepthStencilFormats, DmaBufFormat, DmaBufPlane, ExportKind, ExportKinds,
    ExportedImage, ExportedRing, FrameDepth, GpuSync, NativeTexture, SyncKind, SyncKinds,
};
use mln_style::error::Error;
use mln_style::size::Size;

#[cfg(any(has_metal, has_vulkan, has_d3d12, feature = "webgpu", feature = "gl"))]
use super::backends;

/// A callback that tells the host about something it should act on, such as
/// frame results to drain. It runs on a library thread and must not block.
pub type Wake = Arc<dyn Fn() + Send + Sync>;

/// The thread that runs a render session's graphics work.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Driver {
    /// A thread of the session's own.
    #[default]
    CoreWorker,
    /// The host's graphics thread, which runs the work through the session's
    /// [`DriverWork`](crate::DriverWork).
    CallerThread,
}

/// How a session attaches to its map.
#[derive(Clone, Default)]
pub struct AttachOptions {
    pub driver: Driver,
    /// Runs when frame results wait for
    /// [`drain_frame_results`](crate::RenderSession::drain_frame_results),
    /// and not again until a drain takes them.
    pub frame_wake: Option<Wake>,
    /// Runs when the map has something new to draw, and not again until the
    /// host demands a frame, or while the session has no target. A session
    /// without one can have a frame pacer demand its frames instead
    /// ([`RenderSession::set_frame_pacer`](crate::RenderSession::set_frame_pacer)).
    pub redraw_wake: Option<Wake>,
    /// Runs when a [`Driver::CallerThread`] session has work for
    /// [`DriverWork::service`](crate::DriverWork::service), and not again
    /// until a service starts.
    pub driver_work_wake: Option<Wake>,
    /// The kinds of sync that the host can wait for before it reads a
    /// borrowed ring's frame. The session picks the one of them that its
    /// target supports and that waits least: see [`SyncKinds::pick`].
    pub producer_sync_kinds: SyncKinds,
}

impl std::fmt::Debug for AttachOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AttachOptions")
            .field("driver", &self.driver)
            .field("frame_wake", &self.frame_wake.is_some())
            .field("redraw_wake", &self.redraw_wake.is_some())
            .field("driver_work_wake", &self.driver_work_wake.is_some())
            .field("producer_sync_kinds", &self.producer_sync_kinds)
            .finish()
    }
}

/// What a render session renders into. The session builds it into the
/// backend's objects on the thread that renders, on `device`, or on a device
/// that [`Device::new`] makes when that is `None`. The device's backend is
/// the session's.
#[derive(Debug)]
pub enum RenderTarget {
    /// An image of `size` logical pixels, rendered at the map's pixel ratio,
    /// whose pixels [`read_texture`](crate::RenderSession::read_texture)
    /// reads.
    Offscreen { size: Size, device: Option<Device> },
    /// A surface of `size` logical pixels, rendered at the map's pixel ratio,
    /// that shows each frame that the session renders. Without a device, a
    /// window renders on the platform's native backend where that takes
    /// windows, and on WebGPU otherwise (on Apple's platforms, whose Metal
    /// takes a layer); a Metal layer renders on Metal.
    ///
    /// A frame finishes as
    /// [`TargetNotReady`](crate::FrameDisposition::TargetNotReady) while the
    /// surface can't show it: while a window is minimized or has no client
    /// area, or the surface has an empty extent or gives no image for it.
    ///
    /// [`release_target`](crate::RenderSession::release_target) lets go of
    /// the surface, and [`set_surface`](crate::RenderSession::set_surface)
    /// gives the session another one.
    Surface { size: Size, surface: Surface, device: Option<Device> },
    /// A ring of the host's textures of `size` logical pixels, on `device`,
    /// whose backend is the ring's. Each frame goes to the host, which
    /// takes it with [`acquire_frame`](crate::RenderSession::acquire_frame)
    /// and gives it back once it has read it. The ring's textures set the
    /// size in pixels, and [`set_ring`](crate::RenderSession::set_ring)
    /// gives the session new ones.
    Borrowed { size: Size, ring: BorrowedRing, device: Device },
    /// A ring of images of `size` logical pixels, rendered at the map's
    /// pixel ratio, that the session allocates on `device` and shares with
    /// the host in a kind of `ring.kinds`: the first, by
    /// [`ExportKind::BY_PREFERENCE`], that the device exports. Without a
    /// device, the session renders on the first of [`Device::new`]'s
    /// backends whose device exports one. Each frame goes to the host, which
    /// takes it with [`acquire_frame`](crate::RenderSession::acquire_frame)
    /// and gives it back once it has read it.
    /// [`resize`](crate::RenderSession::resize) gives the ring images of a
    /// new size, and the frames that the host holds keep theirs.
    Exported { size: Size, ring: ExportedRing, device: Option<Device> },
}

/// A ring of the host's textures, of one backend.
#[derive(Clone, Debug, PartialEq)]
pub struct BorrowedRing {
    pub(crate) kind: RingKind,
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) enum RingKind {
    #[cfg(has_vulkan)]
    Vulkan(mln_vulkan::BorrowedImages),
    #[cfg(has_metal)]
    Metal(mln_mtl::BorrowedTextures),
    #[cfg(feature = "gl")]
    Gl(mln_gl::BorrowedTextures),
    #[cfg(feature = "webgpu")]
    WebGpu(mln_webgpu::BorrowedTextures),
    #[cfg(has_d3d12)]
    D3d12(mln_d3d12::BorrowedTextures),
}

/// The host's texture that an acquired frame was rendered into, of `size`
/// pixels.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FrameTexture {
    pub size: mln_gfx::Size,
    pub kind: FrameTextureKind,
    /// An exported ring's image as the API of the session's device names it,
    /// for a host on the device, or `None` for a borrowed ring's texture.
    pub native: Option<FrameTextureKind>,
    /// The texture that holds the frame's depth and stencil: a borrowed
    /// ring's depth texture, or an exported ring's that keeps depth.
    pub depth: Option<FrameDepth>,
}

impl FrameTexture {
    /// The frame's texture as the API of the session's device names it: a
    /// borrowed ring's, or an exported ring's on its device.
    #[must_use]
    pub fn native_kind(&self) -> Option<&FrameTextureKind> {
        match &self.kind {
            FrameTextureKind::Exported(_) => self.native.as_ref(),
            kind => Some(kind),
        }
    }

    /// An exported ring's frame, of the session's `device`.
    pub(crate) fn exported(frame: mln_gfx::ExportedFrame, device: &Device) -> FrameTexture {
        FrameTexture {
            size: frame.size,
            kind: FrameTextureKind::Exported(frame.image),
            native: native_kind(frame.texture, device),
            depth: frame.depth,
        }
    }
}

/// `texture`, which `device` drew into, with the device.
fn native_kind(texture: NativeTexture, device: &Device) -> Option<FrameTextureKind> {
    match (texture, device) {
        #[cfg(has_vulkan)]
        (NativeTexture::Vulkan { image, view, format, layout }, Device::Vulkan(device)) => {
            Some(backends::vulkan::native_texture(image, view, format, layout, device))
        }
        #[cfg(has_metal)]
        (NativeTexture::Metal { texture, pixel_format }, Device::Metal(device)) => {
            Some(backends::metal::native_texture(texture, pixel_format, device))
        }
        (NativeTexture::OpenGl { texture, target, .. }, _) => Some(FrameTextureKind::OpenGl { texture, target }),
        #[cfg(has_d3d12)]
        (NativeTexture::D3d12 { resource, format, state }, Device::D3d12(device)) => {
            Some(backends::d3d12::native_texture(resource, format, state, device))
        }
        _ => None,
    }
}

/// A [`FrameTexture`]'s backend objects.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FrameTextureKind {
    /// A `VkImage` and its `VkImageView` of a `VkDevice`, in a `VkFormat`,
    /// left in a `VkImageLayout`.
    Vulkan { image: u64, view: u64, device: u64, format: i32, layout: i32 },
    /// An `id<MTLTexture>` of an `id<MTLDevice>`, in an `MTLPixelFormat`.
    Metal { texture: u64, device: u64, pixel_format: u64 },
    /// An OpenGL texture name, of a texture target.
    OpenGl { texture: u32, target: u32 },
    /// A WebGL2 `WebGLTexture`, of a texture target, with an optional depth
    /// and stencil texture.
    #[cfg(has_webgl)]
    WebGl { texture: mln_gl::WebTexture, target: u32, depth: Option<mln_gl::WebTexture> },
    /// A WebGPU texture: the host's at the frame's slot of its ring.
    WebGpu,
    /// An `ID3D12Resource*` of an `ID3D12Device*`, in a `DXGI_FORMAT`, left
    /// in a `D3D12_RESOURCE_STATES`.
    D3d12 { resource: u64, device: u64, format: u32, state: u32 },
    /// An image of an exported ring, and its shared memory.
    Exported(ExportedImage),
}

impl BorrowedRing {
    /// The backend whose device renders into the ring.
    #[must_use]
    pub fn backend(&self) -> BackendType {
        match self.kind {
            #[cfg(has_vulkan)]
            RingKind::Vulkan(_) => BackendType::Vulkan,
            #[cfg(has_metal)]
            RingKind::Metal(_) => BackendType::Metal,
            #[cfg(feature = "gl")]
            RingKind::Gl(_) => BackendType::OpenGL,
            #[cfg(feature = "webgpu")]
            RingKind::WebGpu(_) => BackendType::WebGPU,
            #[cfg(has_d3d12)]
            RingKind::D3d12(_) => BackendType::D3D12,
            // A build without a backend renders into no ring.
            _ => BackendType::WebGPU,
        }
    }

    /// How many textures the ring has.
    #[must_use]
    pub fn depth(&self) -> usize {
        match &self.kind {
            #[cfg(has_vulkan)]
            RingKind::Vulkan(images) => images.images.len(),
            #[cfg(has_metal)]
            RingKind::Metal(textures) => textures.textures.len(),
            #[cfg(feature = "gl")]
            RingKind::Gl(textures) => textures.textures.len(),
            #[cfg(feature = "webgpu")]
            RingKind::WebGpu(textures) => textures.textures.len(),
            #[cfg(has_d3d12)]
            RingKind::D3d12(textures) => textures.textures.len(),
            _ => 0,
        }
    }

    /// The textures' size in pixels.
    #[must_use]
    pub fn physical_size(&self) -> mln_gfx::Size {
        match &self.kind {
            #[cfg(has_vulkan)]
            RingKind::Vulkan(images) => images.size,
            #[cfg(has_metal)]
            RingKind::Metal(textures) => textures.size,
            #[cfg(feature = "gl")]
            RingKind::Gl(textures) => textures.size,
            #[cfg(feature = "webgpu")]
            RingKind::WebGpu(textures) => textures.size,
            #[cfg(has_d3d12)]
            RingKind::D3d12(textures) => textures.size,
            _ => mln_gfx::Size::default(),
        }
    }

    /// Whether `device` draws into the ring's depth textures: true for a ring
    /// without them, or of OpenGL textures, whose names say no format, and
    /// otherwise whether their format is one of the device's
    /// [`depth_stencil_formats`](Device::depth_stencil_formats).
    #[must_use]
    pub fn takes_depth_on(&self, device: &Device) -> bool {
        // Irrefutable in a build with OpenGL alone, and refutable in one
        // with other backends.
        #[cfg(feature = "gl")]
        if let RingKind::Gl(_) = self.kind {
            return true;
        }
        !self.has_depth()
            || self.depth_stencil_format().is_some_and(|format| device.depth_stencil_formats().contains(format))
    }

    /// The format of the ring's depth textures, when it has them and their
    /// format is a depth and stencil one that an API names.
    #[must_use]
    pub fn depth_stencil_format(&self) -> Option<DepthStencilFormat> {
        match &self.kind {
            #[cfg(has_vulkan)]
            RingKind::Vulkan(images) => backends::vulkan::ring_depth_stencil_format(images),
            #[cfg(has_metal)]
            RingKind::Metal(textures) => backends::metal::ring_depth_stencil_format(textures),
            #[cfg(feature = "webgpu")]
            RingKind::WebGpu(textures) => backends::webgpu::ring_depth_stencil_format(textures),
            #[cfg(has_d3d12)]
            RingKind::D3d12(textures) => backends::d3d12::ring_depth_stencil_format(textures),
            _ => None,
        }
    }

    /// Whether the ring has depth textures.
    #[must_use]
    pub fn has_depth(&self) -> bool {
        match &self.kind {
            #[cfg(has_vulkan)]
            RingKind::Vulkan(images) => images.depth.is_some(),
            #[cfg(has_metal)]
            RingKind::Metal(textures) => !textures.depth_textures.is_empty(),
            #[cfg(feature = "gl")]
            RingKind::Gl(textures) => !textures.depth_textures.is_empty(),
            #[cfg(feature = "webgpu")]
            RingKind::WebGpu(textures) => !textures.depth_textures.is_empty(),
            #[cfg(has_d3d12)]
            RingKind::D3d12(textures) => !textures.depth_textures.is_empty(),
            _ => false,
        }
    }

    /// Whether the texture at `slot` is the one at `other`'s `other_slot`.
    pub(crate) fn same_texture(&self, slot: usize, other: &BorrowedRing, other_slot: usize) -> bool {
        match (&self.kind, &other.kind) {
            #[cfg(has_vulkan)]
            (RingKind::Vulkan(images), RingKind::Vulkan(others)) => {
                backends::vulkan::ring_same_texture(images, slot, others, other_slot)
            }
            #[cfg(has_metal)]
            (RingKind::Metal(textures), RingKind::Metal(others)) => {
                backends::metal::ring_same_texture(textures, slot, others, other_slot)
            }
            #[cfg(feature = "gl")]
            (RingKind::Gl(textures), RingKind::Gl(others)) => {
                backends::gl::ring_same_texture(textures, slot, others, other_slot)
            }
            #[cfg(feature = "webgpu")]
            (RingKind::WebGpu(textures), RingKind::WebGpu(others)) => {
                backends::webgpu::ring_same_texture(textures, slot, others, other_slot)
            }
            #[cfg(has_d3d12)]
            (RingKind::D3d12(textures), RingKind::D3d12(others)) => {
                backends::d3d12::ring_same_texture(textures, slot, others, other_slot)
            }
            _ => false,
        }
    }

    /// The texture at `slot`, which sessions on `device` render into.
    #[must_use]
    pub fn texture(&self, slot: usize, device: &Device) -> Option<FrameTexture> {
        match (&self.kind, device) {
            #[cfg(has_vulkan)]
            (RingKind::Vulkan(images), Device::Vulkan(device)) => backends::vulkan::ring_texture(images, slot, device),
            #[cfg(has_metal)]
            (RingKind::Metal(textures), Device::Metal(device)) => backends::metal::ring_texture(textures, slot, device),
            #[cfg(has_native_gl)]
            (RingKind::Gl(textures), Device::Gl(_)) => backends::gl::ring_texture_native(textures, slot),
            #[cfg(has_webgl)]
            (RingKind::Gl(textures), Device::WebGl(Some(_))) => backends::gl::ring_texture_webgl(textures, slot),
            #[cfg(feature = "webgpu")]
            (RingKind::WebGpu(textures), Device::WebGpu(_)) => backends::webgpu::ring_texture(textures, slot),
            #[cfg(has_d3d12)]
            (RingKind::D3d12(textures), Device::D3d12(device)) => backends::d3d12::ring_texture(textures, slot, device),
            _ => None,
        }
    }
}

/// What a surface session presents to.
///
/// In the browser, a canvas's surface stays on the instance's thread, as
/// its canvas does.
pub struct Surface {
    pub(crate) kind: SurfaceKind,
    /// Whether presenting waits for the display: see
    /// [`without_frame_rate_cap`](Self::without_frame_rate_cap).
    pub(crate) cap_frame_rate: bool,
}

/// What a host draws over each frame that a surface session presents, after
/// the map and before the frame is presented (and read back): the overlay
/// of the backend that the session presents with
/// ([`DriverWork::set_overlay`](crate::DriverWork::set_overlay)).
pub enum SurfaceOverlay {
    #[cfg(feature = "webgpu")]
    WebGpu(mln_webgpu::Overlay),
    #[cfg(has_metal)]
    Metal(mln_mtl::surface_target::Overlay),
    #[cfg(has_vulkan)]
    Vulkan(Box<dyn mln_vulkan::Overlay>),
    #[cfg(has_d3d12)]
    D3d12(Box<dyn mln_d3d12::Overlay>),
    #[cfg(has_gl_window)]
    Gl(mln_gl::Overlay),
}

pub(crate) enum SurfaceKind {
    Window(Arc<dyn Window>),
    #[cfg(has_metal)]
    MetalLayer(mln_mtl::Layer),
    #[cfg(has_native_webgpu)]
    Wgpu(wgpu::Surface<'static>),
    /// The host's `VkSurfaceKHR`, of the instance of the session's device.
    #[cfg(has_vulkan)]
    Vulkan(mln_vulkan::HostSurface),
    /// The host's `EGLSurface`, of the display of the session's device.
    #[cfg(has_native_gl)]
    Gl(mln_gl::HostSurface),
    /// What shows a D3D12 composition swap chain: a `DirectComposition`
    /// visual or a XAML `SwapChainPanel`, and the thread that made the
    /// surface, which a `SwapChainPanel` takes its swap chain on.
    #[cfg(has_d3d12)]
    D3d12Composition {
        composition: mln_d3d12::Composition,
        thread: std::thread::ThreadId,
    },
    /// In the browser, an `OffscreenCanvas` or an `HTMLCanvasElement`, on
    /// the instance's one thread.
    #[cfg(target_family = "wasm")]
    WebCanvas {
        canvas: wasm_bindgen::JsValue,
        format: Option<CanvasFormat>,
    },
}

/// A `GPUTextureFormat` that a WebGPU canvas takes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CanvasFormat {
    /// `bgra8unorm`.
    Bgra8Unorm,
    /// `rgba8unorm`.
    Rgba8Unorm,
    /// `rgba16float`.
    Rgba16Float,
}

impl CanvasFormat {
    /// The format by its `GPUTextureFormat` name, if a canvas takes it.
    #[must_use]
    pub fn from_name(name: &str) -> Option<CanvasFormat> {
        match name {
            "bgra8unorm" => Some(CanvasFormat::Bgra8Unorm),
            "rgba8unorm" => Some(CanvasFormat::Rgba8Unorm),
            "rgba16float" => Some(CanvasFormat::Rgba16Float),
            _ => None,
        }
    }
}

impl Surface {
    pub(super) fn of(kind: SurfaceKind) -> Surface {
        Surface { kind, cap_frame_rate: true }
    }

    /// The surface, presenting frames as they finish instead of one per
    /// refresh of the display, where the backend and the surface can: a
    /// benchmark's way to measure frame times. Metal on macOS, Vulkan,
    /// WebGPU outside the browser and OpenGL on a window take it; the
    /// others keep the display's pace.
    #[must_use]
    pub fn without_frame_rate_cap(self) -> Surface {
        Surface { cap_frame_rate: false, ..self }
    }

    /// A window, which the session makes its surface on. The window must
    /// outlive the session's use of it: until a
    /// [`set_surface`](crate::RenderSession::set_surface) or
    /// [`release_target`](crate::RenderSession::release_target) replaces it,
    /// or the session detaches or is abandoned.
    ///
    /// On Apple platforms, the session presents to a `CAMetalLayer` that it
    /// puts in the window's view, which only the main thread may do: attach
    /// the window with [`Driver::CallerThread`], serviced there, or make the
    /// layer yourself and attach `Surface::metal_layer`.
    pub fn window(window: impl Window + 'static) -> Surface {
        Surface::of(SurfaceKind::Window(Arc::new(window)))
    }

    /// In the browser, a canvas that the session presents to with its
    /// device's backend: an `OffscreenCanvas`, such as one that the page
    /// transferred to the instance's Web Worker, or an `HTMLCanvasElement`
    /// when the instance runs on the page's thread. The session makes the
    /// canvas's "webgpu" or "webgl2" context, and sizes the canvas to the
    /// target's size at the map's scale factor. Without a device, it renders
    /// with the browser's WebGPU where the build has it, and with WebGL2
    /// otherwise.
    ///
    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for
    /// anything else.
    ///
    /// A WebGPU session configures the canvas with `format`, or else with a
    /// format that its device's adapter prefers. Other backends ignore it.
    ///
    /// When the browser loses a WebGPU session's device, the session fails
    /// with [`ErrorKind::TargetLost`](mln_style::error::ErrorKind), and once it is
    /// released, a new session can attach to the canvas. After Chromium's GPU
    /// process restarts, though, an `OffscreenCanvas` in a Web Worker shows no
    /// new frames, and the worker gets no more animation frames: the page has
    /// to load again.
    #[cfg(target_family = "wasm")]
    pub fn web_canvas(canvas: wasm_bindgen::JsValue, format: Option<CanvasFormat>) -> Result<Surface, Error> {
        use wasm_bindgen::JsCast as _;
        if !canvas.is_instance_of::<web_sys::OffscreenCanvas>()
            && !canvas.is_instance_of::<web_sys::HtmlCanvasElement>()
        {
            return Err(Error::invalid_argument("a web canvas is an OffscreenCanvas or an HTMLCanvasElement"));
        }
        Ok(Surface::of(SurfaceKind::WebCanvas { canvas, format }))
    }

    /// The backend of the device whose instance or share group a host's
    /// surface is of, or `None` for a window or layer.
    #[must_use]
    pub fn host_backend(&self) -> Option<BackendType> {
        match self.kind {
            #[cfg(has_vulkan)]
            SurfaceKind::Vulkan(_) => Some(BackendType::Vulkan),
            #[cfg(has_native_gl)]
            SurfaceKind::Gl(_) => Some(BackendType::OpenGL),
            _ => None,
        }
    }

    /// The surface again, if it is a window, or a surface that a new
    /// backend presents to.
    pub(crate) fn clone_window(&self) -> Option<Surface> {
        let kind = match &self.kind {
            SurfaceKind::Window(window) => SurfaceKind::Window(Arc::clone(window)),
            #[cfg(has_native_gl)]
            SurfaceKind::Gl(surface) => SurfaceKind::Gl(*surface),
            _ => return None,
        };
        Some(Surface { kind, cap_frame_rate: self.cap_frame_rate })
    }

    /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a
    /// window that has no area to present to: a minimized Win32 window, or
    /// one whose client area is empty ([`mln_gfx::window::has_area`]).
    pub(crate) fn check_area(&self) -> Result<(), Error> {
        if let SurfaceKind::Window(window) = &self.kind
            && !mln_gfx::window::has_area(&**window)
        {
            return Err(Error::invalid_state("the window is minimized or has no client area"));
        }
        Ok(())
    }

    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
    /// Win32 window whose pixel format isn't the library's when OpenGL
    /// presents to it: on `device`, or without a device, in a build whose
    /// first backend is OpenGL. Windows doesn't let a pixel format change.
    /// A session that falls back to OpenGL because Vulkan and D3D12 are
    /// missing finds out as it starts.
    #[cfg_attr(
        not(all(feature = "gl", windows)),
        expect(clippy::unnecessary_wraps, reason = "only OpenGL on Windows checks the window's pixel format")
    )]
    pub(crate) fn check_pixel_format(&self, device: Option<&Device>) -> Result<(), Error> {
        #[cfg(all(feature = "gl", windows))]
        if let SurfaceKind::Window(window) = &self.kind
            && device.map_or(cfg!(not(any(has_vulkan, has_d3d12))), |device| device.backend() == BackendType::OpenGL)
        {
            backends::gl::check_window_pixel_format(&**window)?;
        }
        #[cfg(not(all(feature = "gl", windows)))]
        let _ = (self, device);
        Ok(())
    }

    /// The window, for a surface of one.
    pub(crate) fn host_window(&self) -> Option<Arc<dyn Window>> {
        match &self.kind {
            SurfaceKind::Window(window) => Some(Arc::clone(window)),
            _ => None,
        }
    }

    /// Whether the session can make the surface without the host's device.
    pub(crate) fn needs_no_device(&self) -> bool {
        match self.kind {
            SurfaceKind::Window(_) => true,
            #[cfg(has_metal)]
            SurfaceKind::MetalLayer(_) => true,
            #[cfg(has_native_webgpu)]
            SurfaceKind::Wgpu(_) => false,
            #[cfg(has_vulkan)]
            SurfaceKind::Vulkan(_) => false,
            #[cfg(has_native_gl)]
            SurfaceKind::Gl(_) => false,
            #[cfg(has_d3d12)]
            SurfaceKind::D3d12Composition { .. } => true,
            #[cfg(target_family = "wasm")]
            SurfaceKind::WebCanvas { .. } => true,
        }
    }
}

/// A surface on its way to the worker of a session, which takes it on the
/// session's thread.
///
/// In the browser, a canvas waits on the instance's thread, in the
/// session's side there (`crate::web`), and the surface carries its key.
#[cfg(not(target_family = "wasm"))]
pub(crate) struct SentSurface(Surface);

/// A surface on its way to the worker of a session, which takes it on the
/// session's thread.
///
/// In the browser, a canvas waits on the instance's thread, in the
/// session's side there (`crate::web`), and the surface carries its key.
#[cfg(target_family = "wasm")]
pub(crate) enum SentSurface {
    Window(Arc<dyn Window>),
    WebCanvas { canvas: crate::web::HandedCanvas, format: Option<CanvasFormat> },
}

impl SentSurface {
    /// `surface`, on its way to the worker of session `session`.
    pub(crate) fn new(surface: Surface, session: super::SessionId) -> SentSurface {
        #[cfg(not(target_family = "wasm"))]
        {
            let _ = session;
            SentSurface(surface)
        }
        #[cfg(target_family = "wasm")]
        match surface.kind {
            SurfaceKind::Window(window) => SentSurface::Window(window),
            SurfaceKind::WebCanvas { canvas, format } => {
                SentSurface::WebCanvas { canvas: crate::web::hand_canvas(session, canvas), format }
            }
        }
    }

    /// The surface, on the session's thread. In the browser, fails with
    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when its canvas no
    /// longer waits there.
    #[cfg_attr(
        not(target_family = "wasm"),
        expect(clippy::unnecessary_wraps, reason = "only the browser's canvases wait for their session's thread")
    )]
    pub(crate) fn receive(self) -> Result<Surface, Error> {
        #[cfg(not(target_family = "wasm"))]
        {
            Ok(self.0)
        }
        #[cfg(target_family = "wasm")]
        match self {
            SentSurface::Window(window) => Ok(Surface::of(SurfaceKind::Window(window))),
            SentSurface::WebCanvas { canvas, format } => {
                let canvas = canvas.take().ok_or_else(|| Error::invalid_state("the surface's canvas is gone"))?;
                Ok(Surface::of(SurfaceKind::WebCanvas { canvas, format }))
            }
        }
    }

    /// In the browser, whether a session without a device presents to the
    /// surface with WebGPU.
    #[cfg(target_family = "wasm")]
    pub(crate) fn presents_with_web_gpu(&self) -> bool {
        matches!(self, SentSurface::WebCanvas { .. }) && cfg!(feature = "webgpu")
    }
}

impl std::fmt::Debug for Surface {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Surface").finish_non_exhaustive()
    }
}

/// A GPU that sessions on many maps and threads share: one backend's
/// device. Sessions on it keep working after the last handle drops, until
/// they detach.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Device {
    /// A WebGPU device: the library's, through wgpu, or the host's
    /// (`Device::webgpu`). In the browser, the browser's
    /// (`Device::request_web_gpu`).
    #[cfg(feature = "webgpu")]
    WebGpu(mln_webgpu::Device),
    /// A Metal device and command queue.
    #[cfg(has_metal)]
    Metal(mln_mtl::Device),
    /// A Vulkan GPU.
    #[cfg(has_vulkan)]
    Vulkan(mln_vulkan::Device),
    /// A D3D12 device and its direct queue.
    #[cfg(has_d3d12)]
    D3d12(mln_d3d12::Device),
    /// An OpenGL share group, or the one context that its sessions take
    /// turns in.
    #[cfg(has_native_gl)]
    Gl(mln_gl::Device),
    /// In the browser, WebGL2: each session renders with the context of its
    /// canvas, or with the host's wrapped `WebGL2RenderingContext`
    /// ([`Device::web_gl`]).
    #[cfg(has_webgl)]
    WebGl(Option<mln_gl::WebGlDevice>),
}

/// How to create a [`Device`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct DeviceOptions {
    /// The GPU to use. `None` picks the default one.
    pub adapter: Option<Adapter>,
    /// The API that an OpenGL device renders with. Only Linux's and
    /// FreeBSD's EGL renders desktop OpenGL, and Windows' WGL renders it
    /// only. Other backends ignore it.
    pub gl_api: GlApi,
    /// Whether the sessions of an OpenGL device take turns in one context
    /// instead of having one each. Other backends ignore it.
    pub gl_single_context: bool,
}

/// The OpenGL API that an OpenGL device renders with. By default the
/// platform's: desktop OpenGL on Windows, and OpenGL ES elsewhere.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum GlApi {
    /// OpenGL ES 3.0 or later.
    Gles,
    /// Desktop OpenGL 3.3 or later.
    Gl,
}

impl Default for GlApi {
    fn default() -> GlApi {
        if cfg!(windows) { GlApi::Gl } else { GlApi::Gles }
    }
}

/// A GPU, by what names it to a backend.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Adapter {
    /// An index into the backend's list of GPUs.
    Index(usize),
    /// The GPU's 16-byte UUID, as Vulkan's
    /// `VkPhysicalDeviceIDProperties.deviceUUID` reports it.
    Uuid([u8; 16]),
    /// The GPU's 8-byte LUID, as Vulkan's
    /// `VkPhysicalDeviceIDProperties.deviceLUID` reports it: on Windows, its
    /// DXGI adapter's.
    Luid([u8; 8]),
}

/// A kind of window or layer that a session presents to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SurfaceType {
    /// A `CAMetalLayer`.
    MetalLayer,
    /// A Win32 window.
    Win32,
    /// An X11 window, through Xlib.
    Xlib,
    /// An X11 window, through XCB.
    Xcb,
    /// A Wayland surface.
    Wayland,
    /// An Android `ANativeWindow`.
    AndroidNdk,
    /// An `OpenHarmony` `OHNativeWindow`.
    OhosNdk,
}

impl SurfaceType {
    /// Whether a device of `backend` presents to the surfaces of this type
    /// on this platform, in this build.
    #[must_use]
    pub fn presents_with(self, backend: BackendType) -> bool {
        let windowing = match self {
            SurfaceType::MetalLayer => false,
            SurfaceType::Win32 => cfg!(windows),
            SurfaceType::Xlib | SurfaceType::Xcb | SurfaceType::Wayland => {
                cfg!(all(unix, not(target_vendor = "apple"), not(target_os = "android"), not(target_env = "ohos")))
            }
            SurfaceType::AndroidNdk => cfg!(target_os = "android"),
            SurfaceType::OhosNdk => cfg!(target_env = "ohos"),
        };
        match backend {
            BackendType::Metal => cfg!(has_metal) && self == SurfaceType::MetalLayer,
            BackendType::Vulkan => cfg!(has_vulkan) && windowing,
            // EGL presents to these windows, and on Windows WGL to Win32
            // windows.
            BackendType::OpenGL => {
                cfg!(has_gl_window)
                    && windowing
                    && matches!(
                        self,
                        SurfaceType::Win32
                            | SurfaceType::Xlib
                            | SurfaceType::Wayland
                            | SurfaceType::AndroidNdk
                            | SurfaceType::OhosNdk
                    )
            }
            // wgpu's Vulkan backend makes no OpenHarmony surface, and this
            // build has no wgpu GLES backend.
            BackendType::WebGPU => cfg!(has_native_webgpu) && windowing && self != SurfaceType::OhosNdk,
            BackendType::D3D12 => cfg!(has_d3d12) && self == SurfaceType::Win32,
        }
    }

    /// Whether a device of any backend of this build presents to the
    /// surfaces of this type.
    #[must_use]
    pub fn presents_with_any(self) -> bool {
        [BackendType::Metal, BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
            .into_iter()
            .any(|backend| self.presents_with(backend))
    }

    /// Whether a session of this build presents to the surfaces of this
    /// type without the host's device: on the device that a surface session
    /// makes when it gets none.
    #[must_use]
    pub fn presents_without_device(self) -> bool {
        match self {
            SurfaceType::MetalLayer => self.presents_with(BackendType::Metal),
            _ => [BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
                .into_iter()
                .any(|backend| self.presents_with(backend)),
        }
    }
}

/// Whether a backend that failed with `error` is missing, so the next one
/// may take its place.
#[cfg(not(target_family = "wasm"))]
fn missing(error: &Error) -> bool {
    error.kind == mln_style::error::ErrorKind::Unsupported
}

/// A session's hold on what its [`Device`] shares with the host: a Vulkan
/// device's hold on the host's queue lock. [`DeviceLease::revoke`] ends it.
#[derive(Debug, Default)]
pub(crate) struct DeviceLease {
    #[cfg(has_vulkan)]
    queue: Option<mln_vulkan::QueueLease>,
}

impl DeviceLease {
    /// Ends the hold: the leased device calls the host's queue lock no more,
    /// and lets go of it.
    #[cfg_attr(
        not(has_vulkan),
        expect(clippy::unused_self, reason = "only a Vulkan device holds the host's queue lock")
    )]
    pub(crate) fn revoke(&self) {
        #[cfg(has_vulkan)]
        if let Some(queue) = &self.queue {
            queue.revoke();
        }
    }
}

impl Device {
    /// The device for one session, and the session's lease on it, which
    /// ends the session's hold on what the device shares with the host when
    /// the session lets go of the device without dropping it: an abandon
    /// that keeps its graphics objects.
    pub(crate) fn lease(self) -> (Device, DeviceLease) {
        match self {
            #[cfg(has_vulkan)]
            Device::Vulkan(device) => {
                let (device, queue) = device.lease();
                (Device::Vulkan(device), DeviceLease { queue: Some(queue) })
            }
            device => (device, DeviceLease::default()),
        }
    }

    /// Why the device was lost, once the library's WebGPU device is: the
    /// failure of the sessions that render on it.
    pub(crate) fn lost(&self) -> Option<Error> {
        match *self {
            #[cfg(feature = "webgpu")]
            Device::WebGpu(ref device) => device.lost().map(|message| Error::target_lost(message.to_owned())),
            _ => None,
        }
    }

    /// Whether an abandon keeps a session's graphics objects on the device
    /// until the process exits, which only a detach frees: OpenGL's and
    /// WebGPU's, as the C API promises, since only the session's own thread
    /// may destroy them, and the host's graphics objects behind them may be
    /// going away.
    pub(crate) fn abandon_keeps_graphics(&self) -> bool {
        match *self {
            #[cfg(feature = "webgpu")]
            Device::WebGpu(_) => true,
            #[cfg(has_metal)]
            Device::Metal(_) => false,
            #[cfg(has_vulkan)]
            Device::Vulkan(_) => false,
            #[cfg(has_d3d12)]
            Device::D3d12(_) => false,
            #[cfg(has_native_gl)]
            Device::Gl(_) => true,
            #[cfg(has_webgl)]
            Device::WebGl(_) => true,
        }
    }

    /// The library's device, on the platform's native backend: Metal on
    /// Apple's platforms, and Vulkan elsewhere, then D3D12 on Windows, or
    /// OpenGL where there is neither, and last WebGPU (wgpu) in a build with
    /// the `webgpu` feature. A backend that can't name the GPU that
    /// `options` names is skipped: only Vulkan names one by UUID, and only
    /// Vulkan and D3D12 by LUID. OpenGL lists one GPU, the one its
    /// display renders on, at index 0.
    /// So is OpenGL where it can't render with `options.gl_api`.
    ///
    /// Fails with [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when
    /// the options name no GPU, with
    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when no backend has a
    /// GPU or in the browser, where a session renders on the page's device,
    /// and with [`ErrorKind::Failed`](mln_style::error::ErrorKind) when the GPU
    /// can't create the device.
    pub fn new(options: DeviceOptions) -> Result<Device, Error> {
        #[cfg(target_family = "wasm")]
        {
            let _ = options;
            Err(Error::unsupported("the browser has no library devices"))
        }
        #[cfg(not(target_family = "wasm"))]
        {
            let mut error = Error::unsupported("this build has no backend");
            for backend in Self::native_order() {
                match Self::with_backend(*backend, options) {
                    Ok(device) => return Ok(device),
                    Err(e) if missing(&e) => error = e,
                    Err(e) => return Err(e),
                }
            }
            Err(error)
        }
    }

    /// The library's device on `backend`.
    ///
    /// Fails as [`new`](Self::new) does, and with
    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a backend that
    /// isn't in this build or on this platform.
    ///
    /// In the browser, only OpenGL's: `Device::WebGl`. The browser makes
    /// a WebGPU device asynchronously (`Device::request_web_gpu`).
    pub fn with_backend(backend: BackendType, options: DeviceOptions) -> Result<Device, Error> {
        match backend {
            #[cfg(has_native_webgpu)]
            BackendType::WebGPU => backends::webgpu::create_device(options.adapter),
            #[cfg(has_metal)]
            BackendType::Metal => backends::metal::create_device(options.adapter),
            #[cfg(has_vulkan)]
            BackendType::Vulkan => backends::vulkan::create_device(options.adapter),
            #[cfg(has_d3d12)]
            BackendType::D3D12 => backends::d3d12::create_device(options.adapter),
            #[cfg(has_gl_device)]
            BackendType::OpenGL => backends::gl::create_device(options),
            #[cfg(has_webgl)]
            BackendType::OpenGL if options.adapter.is_none() => Ok(Device::WebGl(None)),
            _ => {
                let _ = options;
                Err(Error::unsupported(format!("this build has no {backend:?} backend")))
            }
        }
    }

    /// The kinds of sync with which the host can wait for a frame of `ring`
    /// on the device (the producer's), and with which a session waits for
    /// the host's reads (the consumer's).
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the
    /// device can't render into the ring: one of another backend, or one the
    /// device lacks a feature for.
    pub fn borrowed_sync_kinds(&self, ring: &BorrowedRing) -> Result<(SyncKinds, SyncKinds), Error> {
        match (self, &ring.kind) {
            #[cfg(has_vulkan)]
            (Device::Vulkan(device), RingKind::Vulkan(images)) => backends::vulkan::borrowed_sync_kinds(device, images),
            #[cfg(has_metal)]
            (Device::Metal(device), RingKind::Metal(textures)) => {
                backends::metal::borrowed_sync_kinds(device, textures)
            }
            #[cfg(has_native_gl)]
            (Device::Gl(device), RingKind::Gl(_)) => backends::gl::borrowed_sync_kinds_native(device),
            #[cfg(has_webgl)]
            (Device::WebGl(device), RingKind::Gl(_)) => backends::gl::borrowed_sync_kinds_webgl(device.as_ref()),
            #[cfg(feature = "webgpu")]
            (Device::WebGpu(_), RingKind::WebGpu(textures)) => backends::webgpu::borrowed_sync_kinds(textures),
            #[cfg(has_d3d12)]
            (Device::D3d12(device), RingKind::D3d12(textures)) => {
                backends::d3d12::borrowed_sync_kinds(device, textures)
            }
            _ => Err(Error::unsupported(format!(
                "a {:?} device renders into no ring of {:?} textures",
                self.backend(),
                ring.backend()
            ))),
        }
    }

    /// The formats of the depth textures that a borrowed ring takes on the
    /// device.
    #[must_use]
    pub fn depth_stencil_formats(&self) -> DepthStencilFormats {
        match *self {
            #[cfg(has_vulkan)]
            Device::Vulkan(ref device) => device.depth_stencil_formats(),
            #[cfg(has_d3d12)]
            Device::D3d12(_) => mln_d3d12::BorrowedTextures::depth_stencil_formats(),
            #[cfg(has_metal)]
            Device::Metal(_) => mln_mtl::BorrowedTextures::depth_stencil_formats(),
            #[cfg(has_native_gl)]
            Device::Gl(_) => mln_gl::BorrowedTextures::depth_stencil_formats(),
            #[cfg(has_webgl)]
            Device::WebGl(Some(_)) => mln_gl::BorrowedTextures::depth_stencil_formats(),
            #[cfg(feature = "webgpu")]
            Device::WebGpu(ref device) => mln_webgpu::BorrowedTextures::depth_stencil_formats(device.device()),
            #[cfg(target_family = "wasm")]
            _ => DepthStencilFormats::NONE,
        }
    }

    /// The kinds of [`export_kinds`](Self::export_kinds) whose rings also
    /// share each frame's depth texture, when they keep depth: only
    /// [`ExportKind::OpaqueFd`], since an `IOSurface`, a dmabuf or an Android
    /// hardware buffer holds no depth format. A ring of those keeps its depth
    /// on the device.
    #[must_use]
    pub fn depth_export_kinds(&self) -> ExportKinds {
        match self {
            #[cfg(has_vulkan)]
            Device::Vulkan(device) => device.depth_export_kinds(),
            _ => ExportKinds::NONE,
        }
    }

    /// The kinds of exported ring that sessions on the device share their
    /// images in: those that the device has exported an image of.
    #[must_use]
    pub fn export_kinds(&self) -> ExportKinds {
        match self {
            #[cfg(has_vulkan)]
            Device::Vulkan(device) => device.export_kinds(),
            #[cfg(has_metal)]
            Device::Metal(device) => mln_mtl::exported_target::export_kinds(device),
            #[cfg(has_gl_exported)]
            Device::Gl(device) => mln_gl::exported_target::export_kinds(device),
            #[cfg(has_d3d12)]
            Device::D3d12(device) => device.export_kinds(),
            _ => ExportKinds::NONE,
        }
    }

    /// The kind that a session on the device shares `ring`'s images in, and
    /// the kinds of sync with which the host can wait for a frame (the
    /// producer's) and a session for the host's reads (the consumer's).
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the
    /// device exports none of the ring's kinds.
    pub fn export_plan(&self, ring: &ExportedRing) -> Result<(ExportKind, SyncKinds, SyncKinds), Error> {
        match self {
            #[cfg(has_vulkan)]
            Device::Vulkan(device) => backends::vulkan::export_plan(device, ring),
            #[cfg(has_metal)]
            Device::Metal(device) => backends::metal::export_plan(device, ring),
            #[cfg(has_gl_exported)]
            Device::Gl(device) => backends::gl::export_plan(device, ring),
            #[cfg(has_d3d12)]
            Device::D3d12(device) => backends::d3d12::export_plan(device, ring),
            _ => {
                let _ = ring;
                Err(Error::unsupported(format!("a {:?} device exports no ring", self.backend())))
            }
        }
    }

    /// The kinds of sync with which the host can wait for an exported
    /// ring's frame (the producer's) and a session for the host's reads (the
    /// consumer's), on a device that exports a ring.
    #[must_use]
    pub fn export_sync_kinds(&self) -> (SyncKinds, SyncKinds) {
        if self.export_kinds().is_empty() {
            return (SyncKinds::NONE, SyncKinds::NONE);
        }
        match self {
            #[cfg(has_vulkan)]
            Device::Vulkan(device) => mln_vulkan::exported_target::sync_kinds(device),
            #[cfg(has_metal)]
            Device::Metal(device) => mln_mtl::exported_target::sync_kinds(device),
            #[cfg(has_gl_exported)]
            Device::Gl(device) => mln_gl::exported_target::sync_kinds(device),
            #[cfg(has_d3d12)]
            Device::D3d12(_) => mln_d3d12::exported_target::sync_kinds(),
            _ => (SyncKinds::NONE, SyncKinds::NONE),
        }
    }

    /// The library's device for `ring`: on the first of [`new`](Self::new)'s
    /// backends whose device exports one of the ring's kinds.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when no
    /// backend's device does, and as [`new`](Self::new) does.
    pub fn for_exported_ring(ring: &ExportedRing) -> Result<Device, Error> {
        #[cfg(target_family = "wasm")]
        {
            let _ = ring;
            Err(Error::unsupported("the browser has no library devices"))
        }
        #[cfg(not(target_family = "wasm"))]
        {
            let mut error = Error::unsupported("no backend of this build exports the ring's kinds of image");
            for backend in Self::native_order() {
                match Self::with_backend(*backend, DeviceOptions::default()) {
                    Ok(device) => match device.export_plan(ring) {
                        Ok(_) => return Ok(device),
                        Err(e) => error = e,
                    },
                    Err(e) if missing(&e) => {}
                    Err(e) => return Err(e),
                }
            }
            Err(error)
        }
    }

    /// Whether sessions on the device present to the host's own surfaces:
    /// a Vulkan device's `VkSurfaceKHR`s, or the `EGLSurface`s of an OpenGL
    /// device that wraps the host's context.
    #[must_use]
    pub fn presents_to_host_surfaces(&self) -> bool {
        match self {
            #[cfg(has_vulkan)]
            Device::Vulkan(device) => device.presents(),
            #[cfg(has_native_gl)]
            Device::Gl(device) => device.is_host(),
            _ => false,
        }
    }

    /// Whether sessions on the device present to the surfaces of
    /// `surface`'s type: a Vulkan device's instance needs the type's surface
    /// extension, which the loader may lack.
    #[must_use]
    pub fn presents_to(&self, surface: SurfaceType) -> bool {
        if !surface.presents_with(self.backend()) {
            return false;
        }
        match self {
            #[cfg(has_vulkan)]
            Device::Vulkan(device) => {
                backends::vulkan::surface_extension(surface).is_some_and(|name| device.presents_through(name))
            }
            _ => true,
        }
    }

    /// The backends [`new`](Self::new) tries, in order. Vulkan comes before
    /// D3D12 on Windows, as it renders frames faster on the GPUs measured.
    #[cfg(not(target_family = "wasm"))]
    fn native_order() -> &'static [BackendType] {
        if cfg!(target_os = "macos") {
            &[BackendType::Metal, BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
        } else if cfg!(target_vendor = "apple") {
            &[BackendType::Metal, BackendType::WebGPU]
        } else if cfg!(windows) {
            &[BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
        } else {
            &[BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
        }
    }

    /// The backend the device is of.
    #[must_use]
    pub fn backend(&self) -> BackendType {
        match *self {
            #[cfg(feature = "webgpu")]
            Device::WebGpu(_) => BackendType::WebGPU,
            #[cfg(has_metal)]
            Device::Metal(_) => BackendType::Metal,
            #[cfg(has_vulkan)]
            Device::Vulkan(_) => BackendType::Vulkan,
            #[cfg(has_d3d12)]
            Device::D3d12(_) => BackendType::D3D12,
            #[cfg(has_native_gl)]
            Device::Gl(_) => BackendType::OpenGL,
            #[cfg(has_webgl)]
            Device::WebGl(_) => BackendType::OpenGL,
        }
    }
}