-
Notifications
You must be signed in to change notification settings - Fork 23
/
mod.rs
1450 lines (1334 loc) · 51 KB
/
mod.rs
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
use crate::gl_utils::GlClearer;
use crate::SurfmanGL;
use euclid::Point2D;
use euclid::Rect;
use euclid::RigidTransform3D;
use euclid::Rotation3D;
use euclid::Size2D;
use euclid::Transform3D;
use euclid::Vector3D;
use log::{error, warn};
use openxr::d3d::{Requirements, SessionCreateInfoD3D11, D3D11};
use openxr::Graphics;
use openxr::{
self, ActionSet, ActiveActionSet, ApplicationInfo, CompositionLayerFlags,
CompositionLayerProjection, Entry, EnvironmentBlendMode, ExtensionSet, Extent2Di, FormFactor,
Fovf, FrameState, FrameStream, FrameWaiter, Instance, Posef, Quaternionf, ReferenceSpaceType,
SecondaryEndInfo, Session, Space, Swapchain, SwapchainCreateFlags, SwapchainCreateInfo,
SwapchainUsageFlags, SystemId, Vector3f, ViewConfigurationType,
};
use sparkle::gl;
use sparkle::gl::GLuint;
use std::collections::HashMap;
use std::mem;
use std::ops::Deref;
use std::ptr;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use surfman::Adapter as SurfmanAdapter;
use surfman::Context as SurfmanContext;
use surfman::Device as SurfmanDevice;
use surfman::Error as SurfmanError;
use surfman::SurfaceTexture;
use webxr_api;
use webxr_api::util::{self, ClipPlanes};
use webxr_api::Capture;
use webxr_api::ContextId;
use webxr_api::DeviceAPI;
use webxr_api::DiscoveryAPI;
use webxr_api::Display;
use webxr_api::Error;
use webxr_api::Event;
use webxr_api::EventBuffer;
use webxr_api::Floor;
use webxr_api::Frame;
use webxr_api::GLContexts;
use webxr_api::InputId;
use webxr_api::InputSource;
use webxr_api::LayerGrandManager;
use webxr_api::LayerId;
use webxr_api::LayerInit;
use webxr_api::LayerManager;
use webxr_api::LayerManagerAPI;
use webxr_api::LeftEye;
use webxr_api::Native;
use webxr_api::Quitter;
use webxr_api::RightEye;
use webxr_api::SelectKind;
use webxr_api::Sender;
use webxr_api::Session as WebXrSession;
use webxr_api::SessionBuilder;
use webxr_api::SessionInit;
use webxr_api::SessionMode;
use webxr_api::SubImage;
use webxr_api::SubImages;
use webxr_api::View;
use webxr_api::ViewerPose;
use webxr_api::Viewport;
use webxr_api::Viewports;
use webxr_api::Views;
use webxr_api::Visibility;
use winapi::shared::dxgi;
use winapi::shared::dxgiformat;
use winapi::shared::winerror::{DXGI_ERROR_NOT_FOUND, S_OK};
use winapi::um::d3d11::ID3D11Texture2D;
use winapi::Interface;
use wio::com::ComPtr;
mod input;
use input::OpenXRInput;
const HEIGHT: f32 = 1.4;
const IDENTITY_POSE: Posef = Posef {
orientation: Quaternionf {
x: 0.,
y: 0.,
z: 0.,
w: 1.,
},
position: Vector3f {
x: 0.,
y: 0.,
z: 0.,
},
};
const VIEW_INIT: openxr::View = openxr::View {
pose: IDENTITY_POSE,
fov: Fovf {
angle_left: 0.,
angle_right: 0.,
angle_up: 0.,
angle_down: 0.,
},
};
// How much to downscale the view capture by.
// This is used for performance reasons, to dedicate less texture memory to the camera.
// Note that on an HL2 this allocates enough texture memory for "low power" mode,
// not "high quality" (in the device portal under
// Views > Mixed Reality Capture > Photo and Video Settings).
const SECONDARY_VIEW_DOWNSCALE: i32 = 2;
/// Provides a way to spawn and interact with context menus
pub trait ContextMenuProvider: Send {
/// Open a context menu, return a way to poll for the result
fn open_context_menu(&self) -> Box<dyn ContextMenuFuture>;
/// Clone self as a trait object
fn clone_object(&self) -> Box<dyn ContextMenuProvider>;
}
/// A way to poll for the result of the context menu request
pub trait ContextMenuFuture {
fn poll(&self) -> ContextMenuResult;
}
/// The result of polling on a context menu request
pub enum ContextMenuResult {
/// Session should exit
ExitSession,
/// Dialog was dismissed
Dismissed,
/// User has not acted on dialog
Pending,
}
struct ViewInfo<Eye> {
view: openxr::View,
extent: Extent2Di,
cached_projection: Transform3D<f32, Eye, Display>,
}
impl<Eye> ViewInfo<Eye> {
fn set_view(&mut self, view: openxr::View, clip_planes: ClipPlanes) {
self.view.pose = view.pose;
if self.view.fov.angle_left != view.fov.angle_left
|| self.view.fov.angle_right != view.fov.angle_right
|| self.view.fov.angle_up != view.fov.angle_up
|| self.view.fov.angle_down != view.fov.angle_down
{
// It's fine if this happens occasionally, but if this happening very
// often we should stop caching
warn!("FOV changed, updating projection matrices");
self.view.fov = view.fov;
self.recompute_projection(clip_planes);
}
}
fn recompute_projection(&mut self, clip_planes: ClipPlanes) {
self.cached_projection = fov_to_projection_matrix(&self.view.fov, clip_planes);
}
fn view(&self) -> View<Eye> {
View {
transform: transform(&self.view.pose),
projection: self.cached_projection,
}
}
}
pub struct OpenXrDiscovery {
context_menu_provider: Option<Box<dyn ContextMenuProvider>>,
}
impl OpenXrDiscovery {
pub fn new(context_menu_provider: Option<Box<dyn ContextMenuProvider>>) -> Self {
Self {
context_menu_provider,
}
}
}
pub struct CreatedInstance {
instance: Instance,
supports_hands: bool,
supports_secondary: bool,
system: SystemId,
}
pub fn create_instance(
needs_hands: bool,
needs_secondary: bool,
) -> Result<CreatedInstance, String> {
let entry = unsafe { Entry::load().map_err(|e| format!("Entry::load {:?}", e))? };
let supported = entry
.enumerate_extensions()
.map_err(|e| format!("Entry::enumerate_extensions {:?}", e))?;
warn!("Available extensions:\n{:?}", supported);
let mut supports_hands = needs_hands && supported.ext_hand_tracking;
let supports_secondary = needs_secondary
&& supported.msft_secondary_view_configuration
&& supported.msft_first_person_observer;
let app_info = ApplicationInfo {
application_name: "firefox.reality",
application_version: 1,
engine_name: "servo",
engine_version: 1,
};
let mut exts = ExtensionSet::default();
exts.khr_d3d11_enable = true;
if supports_hands {
exts.ext_hand_tracking = true;
}
if supports_secondary {
exts.msft_secondary_view_configuration = true;
exts.msft_first_person_observer = true;
}
let instance = entry
.create_instance(&app_info, &exts, &[])
.map_err(|e| format!("Entry::create_instance {:?}", e))?;
let system = instance
.system(FormFactor::HEAD_MOUNTED_DISPLAY)
.map_err(|e| format!("Instance::system {:?}", e))?;
if supports_hands {
supports_hands |= instance
.supports_hand_tracking(system)
.map_err(|e| format!("Instance::supports_hand_tracking {:?}", e))?;
}
Ok(CreatedInstance {
instance,
supports_hands,
supports_secondary,
system,
})
}
fn get_matching_adapter(
requirements: &Requirements,
) -> Result<ComPtr<dxgi::IDXGIAdapter1>, String> {
unsafe {
let mut factory_ptr: *mut dxgi::IDXGIFactory1 = ptr::null_mut();
let result = dxgi::CreateDXGIFactory1(
&dxgi::IDXGIFactory1::uuidof(),
&mut factory_ptr as *mut _ as *mut _,
);
assert_eq!(result, S_OK);
let factory = ComPtr::from_raw(factory_ptr);
let index = 0;
loop {
let mut adapter_ptr = ptr::null_mut();
let result = factory.EnumAdapters1(index, &mut adapter_ptr);
if result == DXGI_ERROR_NOT_FOUND {
return Err("No matching adapter".to_owned());
}
assert_eq!(result, S_OK);
let adapter = ComPtr::from_raw(adapter_ptr);
let mut adapter_desc = mem::zeroed();
let result = adapter.GetDesc1(&mut adapter_desc);
assert_eq!(result, S_OK);
let adapter_luid = &adapter_desc.AdapterLuid;
if adapter_luid.LowPart == requirements.adapter_luid.LowPart
&& adapter_luid.HighPart == requirements.adapter_luid.HighPart
{
return Ok(adapter);
}
}
}
}
pub fn create_surfman_adapter() -> Option<SurfmanAdapter> {
let instance = create_instance(false, false).ok()?;
let system = instance
.instance
.system(FormFactor::HEAD_MOUNTED_DISPLAY)
.ok()?;
let requirements = D3D11::requirements(&instance.instance, system).ok()?;
let adapter = get_matching_adapter(&requirements).ok()?;
Some(SurfmanAdapter::from_dxgi_adapter(adapter.up()))
}
fn pick_format(formats: &[dxgiformat::DXGI_FORMAT]) -> dxgiformat::DXGI_FORMAT {
// TODO: extract the format from surfman's device and pick a matching
// valid format based on that. For now, assume that eglChooseConfig will
// gravitate to B8G8R8A8.
warn!("Available formats: {:?}", formats);
for format in formats {
match *format {
dxgiformat::DXGI_FORMAT_B8G8R8A8_UNORM => return *format,
//dxgiformat::DXGI_FORMAT_R8G8B8A8_UNORM => return *format,
f => {
warn!("Backend requested unsupported format {:?}", f);
}
}
}
panic!("No formats supported amongst {:?}", formats);
}
impl DiscoveryAPI<SurfmanGL> for OpenXrDiscovery {
fn request_session(
&mut self,
mode: SessionMode,
init: &SessionInit,
xr: SessionBuilder<SurfmanGL>,
) -> Result<WebXrSession, Error> {
if self.supports_session(mode) {
let needs_hands = init.feature_requested("hand-tracking");
let needs_secondary =
init.feature_requested("secondary-views") && init.first_person_observer_view;
let instance = create_instance(needs_hands, needs_secondary)
.map_err(|e| Error::BackendSpecific(e))?;
let mut supported_features = vec!["local-floor".into()];
if instance.supports_hands {
supported_features.push("hand-tracking".into());
}
if instance.supports_secondary && init.first_person_observer_view {
supported_features.push("secondary-views".into());
}
let granted_features = init.validate(mode, &supported_features)?;
let context_menu_provider = self.context_menu_provider.take();
xr.spawn(move |grand_manager| {
OpenXrDevice::new(
instance,
granted_features,
context_menu_provider,
grand_manager,
)
})
} else {
Err(Error::NoMatchingDevice)
}
}
fn supports_session(&self, mode: SessionMode) -> bool {
let mut supports = false;
// Determining AR support requires enumerating environment blend modes,
// but this requires an already created XrInstance and SystemId.
// We'll make a "default" instance here to check the blend modes,
// then a proper one in request_session with hands/secondary support if needed.
if let Ok(instance) = create_instance(false, false) {
if let Ok(blend_modes) = instance.instance.enumerate_environment_blend_modes(
instance.system,
ViewConfigurationType::PRIMARY_STEREO,
) {
if mode == SessionMode::ImmersiveAR {
supports = blend_modes.contains(&EnvironmentBlendMode::ADDITIVE)
|| blend_modes.contains(&EnvironmentBlendMode::ALPHA_BLEND);
} else if mode == SessionMode::ImmersiveVR {
// Immersive VR sessions are not precluded by non-opaque blending
supports = blend_modes.len() > 0;
}
}
}
supports
}
}
struct OpenXrDevice {
session: Arc<Session<D3D11>>,
instance: Instance,
events: EventBuffer,
frame_waiter: FrameWaiter,
layer_manager: LayerManager,
viewer_space: Space,
shared_data: Arc<Mutex<Option<SharedData>>>,
clip_planes: ClipPlanes,
supports_secondary: bool,
// input
action_set: ActionSet,
right_hand: OpenXRInput,
left_hand: OpenXRInput,
granted_features: Vec<String>,
context_menu_provider: Option<Box<dyn ContextMenuProvider>>,
context_menu_future: Option<Box<dyn ContextMenuFuture>>,
}
/// Data that is shared between the openxr thread and the
/// layer manager that runs in the webgl thread.
struct SharedData {
left: ViewInfo<LeftEye>,
right: ViewInfo<RightEye>,
secondary: Option<ViewInfo<Capture>>,
secondary_active: bool,
primary_blend_mode: EnvironmentBlendMode,
secondary_blend_mode: Option<EnvironmentBlendMode>,
frame_state: Option<FrameState>,
space: Space,
}
struct OpenXrLayerManager {
session: Arc<Session<D3D11>>,
shared_data: Arc<Mutex<Option<SharedData>>>,
frame_stream: FrameStream<D3D11>,
layers: Vec<(ContextId, LayerId)>,
openxr_layers: HashMap<LayerId, OpenXrLayer>,
clearer: GlClearer,
}
struct OpenXrLayer {
swapchain: Swapchain<D3D11>,
depth_stencil_texture: Option<GLuint>,
size: Size2D<i32, Viewport>,
images: Vec<<D3D11 as Graphics>::SwapchainImage>,
surface_textures: Vec<Option<SurfaceTexture>>,
waited: bool,
}
impl OpenXrLayerManager {
fn new(
session: Arc<Session<D3D11>>,
shared_data: Arc<Mutex<Option<SharedData>>>,
frame_stream: FrameStream<D3D11>,
) -> OpenXrLayerManager {
let layers = Vec::new();
let openxr_layers = HashMap::new();
let clearer = GlClearer::new();
OpenXrLayerManager {
session,
shared_data,
frame_stream,
layers,
openxr_layers,
clearer,
}
}
fn create_session(
device: &SurfmanDevice,
instance: &Instance,
system: SystemId,
) -> Result<(Session<D3D11>, FrameWaiter, FrameStream<D3D11>), Error> {
// Get the current surfman device and extract its D3D device. This will ensure
// that the OpenXR runtime's texture will be shareable with surfman's surfaces.
let native_device = device.native_device();
let d3d_device = native_device.d3d11_device;
// FIXME: we should be using these graphics requirements to drive the actual
// d3d device creation, rather than assuming the device that surfman
// already created is appropriate. OpenXR returns a validation error
// unless we call this method, so we call it and ignore the results
// in the short term.
let _requirements = D3D11::requirements(&instance, system)
.map_err(|e| Error::BackendSpecific(format!("D3D11::requirements {:?}", e)))?;
unsafe {
instance
.create_session::<D3D11>(system, &SessionCreateInfoD3D11 { device: d3d_device as *mut _ })
.map_err(|e| Error::BackendSpecific(format!("Instance::create_session {:?}", e)))
}
}
}
impl OpenXrLayer {
fn new(
swapchain: Swapchain<D3D11>,
depth_stencil_texture: Option<GLuint>,
size: Size2D<i32, Viewport>,
) -> Result<OpenXrLayer, Error> {
let images = swapchain
.enumerate_images()
.map_err(|e| Error::BackendSpecific(format!("Session::enumerate_images {:?}", e)))?;
let waited = false;
let mut surface_textures = Vec::new();
surface_textures.resize_with(images.len(), || None);
Ok(OpenXrLayer {
swapchain,
depth_stencil_texture,
size,
images,
surface_textures,
waited,
})
}
fn get_surface_texture(
&mut self,
device: &mut SurfmanDevice,
context: &mut SurfmanContext,
index: usize,
) -> Result<&SurfaceTexture, SurfmanError> {
let result = self
.surface_textures
.get_mut(index)
.ok_or(SurfmanError::Failed)?;
if let Some(result) = result {
return Ok(result);
}
unsafe {
let image = ComPtr::from_raw(self.images[index] as *mut ID3D11Texture2D);
image.AddRef();
let surface_texture = device.create_surface_texture_from_texture(
context,
&self.size.to_untyped(),
image,
)?;
*result = Some(surface_texture);
}
result.as_ref().ok_or(SurfmanError::Failed)
}
}
impl LayerManagerAPI<SurfmanGL> for OpenXrLayerManager {
fn create_layer(
&mut self,
device: &mut SurfmanDevice,
contexts: &mut dyn GLContexts<SurfmanGL>,
context_id: ContextId,
init: LayerInit,
) -> Result<LayerId, Error> {
let guard = self.shared_data.lock().unwrap();
let data = guard.as_ref().unwrap();
// XXXManishearth should we be doing this, or letting Servo set the format?
let formats = self.session.enumerate_swapchain_formats().map_err(|e| {
Error::BackendSpecific(format!("Session::enumerate_swapchain_formats {:?}", e))
})?;
let format = pick_format(&formats);
let texture_size = init.texture_size(&data.viewports());
let swapchain_create_info = SwapchainCreateInfo {
create_flags: SwapchainCreateFlags::EMPTY,
usage_flags: SwapchainUsageFlags::COLOR_ATTACHMENT | SwapchainUsageFlags::SAMPLED,
width: texture_size.width as u32,
height: texture_size.height as u32,
format,
sample_count: 1,
face_count: 1,
array_size: 1,
mip_count: 1,
};
let swapchain = self
.session
.create_swapchain(&swapchain_create_info)
.map_err(|e| Error::BackendSpecific(format!("Session::create_swapchain {:?}", e)))?;
// TODO: Treat depth and stencil separately?
// TODO: Use the openxr API for depth/stencil swap chains?
let has_depth_stencil = match init {
LayerInit::WebGLLayer { stencil, depth, .. } => stencil | depth,
LayerInit::ProjectionLayer { stencil, depth, .. } => stencil | depth,
};
let depth_stencil_texture = if has_depth_stencil {
let gl = contexts
.bindings(device, context_id)
.ok_or(Error::NoMatchingDevice)?;
let depth_stencil_texture = gl.gen_textures(1)[0];
gl.bind_texture(gl::TEXTURE_2D, depth_stencil_texture);
gl.tex_image_2d(
gl::TEXTURE_2D,
0,
gl::DEPTH24_STENCIL8 as _,
texture_size.width,
texture_size.height,
0,
gl::DEPTH_STENCIL,
gl::UNSIGNED_INT_24_8,
gl::TexImageSource::Pixels(None),
);
Some(depth_stencil_texture)
} else {
None
};
let layer_id = LayerId::new();
let openxr_layer = OpenXrLayer::new(swapchain, depth_stencil_texture, texture_size)?;
self.layers.push((context_id, layer_id));
self.openxr_layers.insert(layer_id, openxr_layer);
Ok(layer_id)
}
fn destroy_layer(
&mut self,
device: &mut SurfmanDevice,
contexts: &mut dyn GLContexts<SurfmanGL>,
context_id: ContextId,
layer_id: LayerId,
) {
self.clearer
.destroy_layer(device, contexts, context_id, layer_id);
self.layers.retain(|&ids| ids != (context_id, layer_id));
if let Some(mut layer) = self.openxr_layers.remove(&layer_id) {
if let Some(depth_stencil_texture) = layer.depth_stencil_texture {
let gl = contexts.bindings(device, context_id).unwrap();
gl.delete_textures(&[depth_stencil_texture]);
}
let mut context = contexts
.context(device, context_id)
.expect("missing GL context");
for surface_texture in mem::replace(&mut layer.surface_textures, vec![]) {
if let Some(surface_texture) = surface_texture {
let mut surface = device
.destroy_surface_texture(&mut context, surface_texture)
.unwrap();
device.destroy_surface(&mut context, &mut surface).unwrap();
}
}
}
}
fn layers(&self) -> &[(ContextId, LayerId)] {
&self.layers[..]
}
fn end_frame(
&mut self,
_device: &mut SurfmanDevice,
_contexts: &mut dyn GLContexts<SurfmanGL>,
layers: &[(ContextId, LayerId)],
) -> Result<(), Error> {
let guard = self.shared_data.lock().unwrap();
let data = guard.as_ref().unwrap();
// At this point the frame contents have been rendered, so we can release access to the texture
// in preparation for displaying it.
for (_, openxr_layer) in &mut self.openxr_layers {
if openxr_layer.waited {
openxr_layer.swapchain.release_image().map_err(|e| {
Error::BackendSpecific(format!("Session::release_image {:?}", e))
})?;
openxr_layer.waited = false;
}
}
let openxr_layers = &self.openxr_layers;
// Invert the up/down angles so that openxr flips the texture in the y axis.
let mut l_fov = data.left.view.fov;
let mut r_fov = data.right.view.fov;
std::mem::swap(&mut l_fov.angle_up, &mut l_fov.angle_down);
std::mem::swap(&mut r_fov.angle_up, &mut r_fov.angle_down);
let viewports = data.viewports();
let primary_views = layers
.iter()
.filter_map(|&(_, layer_id)| {
let openxr_layer = openxr_layers.get(&layer_id)?;
Some([
openxr::CompositionLayerProjectionView::new()
.pose(data.left.view.pose)
.fov(l_fov)
.sub_image(
openxr::SwapchainSubImage::new()
.swapchain(&openxr_layer.swapchain)
.image_array_index(0)
.image_rect(image_rect(viewports.viewports[0])),
),
openxr::CompositionLayerProjectionView::new()
.pose(data.right.view.pose)
.fov(r_fov)
.sub_image(
openxr::SwapchainSubImage::new()
.swapchain(&openxr_layer.swapchain)
.image_array_index(0)
.image_rect(image_rect(viewports.viewports[1])),
),
])
})
.collect::<Vec<_>>();
let primary_layers = primary_views
.iter()
.map(|views| {
CompositionLayerProjection::new()
.space(&data.space)
.layer_flags(CompositionLayerFlags::BLEND_TEXTURE_SOURCE_ALPHA)
.views(&views[..])
})
.collect::<Vec<_>>();
let primary_layers = primary_layers
.iter()
.map(|layer| layer.deref())
.collect::<Vec<_>>();
if let (Some(secondary), true) = (data.secondary.as_ref(), data.secondary_active) {
let mut s_fov = secondary.view.fov;
std::mem::swap(&mut s_fov.angle_up, &mut s_fov.angle_down);
let secondary_views = layers
.iter()
.filter_map(|&(_, layer_id)| {
let openxr_layer = openxr_layers.get(&layer_id)?;
Some([openxr::CompositionLayerProjectionView::new()
.pose(secondary.view.pose)
.fov(s_fov)
.sub_image(
openxr::SwapchainSubImage::new()
.swapchain(&openxr_layer.swapchain)
.image_array_index(0)
.image_rect(image_rect(viewports.viewports[2])),
)])
})
.collect::<Vec<_>>();
let secondary_layers = secondary_views
.iter()
.map(|views| {
CompositionLayerProjection::new()
.space(&data.space)
.layer_flags(CompositionLayerFlags::BLEND_TEXTURE_SOURCE_ALPHA)
.views(&views[..])
})
.collect::<Vec<_>>();
let secondary_layers = secondary_layers
.iter()
.map(|layer| layer.deref())
.collect::<Vec<_>>();
self.frame_stream
.end_secondary(
data.frame_state.as_ref().unwrap().predicted_display_time,
data.primary_blend_mode,
&primary_layers[..],
SecondaryEndInfo {
ty: ViewConfigurationType::SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT,
// XXXManishearth should we use the secondary layer's blend mode here, given
// that the content will be using the primary blend mode?
environment_blend_mode: data
.secondary_blend_mode
.unwrap_or(data.primary_blend_mode),
layers: &secondary_layers[..],
},
)
.map_err(|e| {
Error::BackendSpecific(format!("FrameStream::end_secondary {:?}", e))
})?;
} else {
self.frame_stream
.end(
data.frame_state.as_ref().unwrap().predicted_display_time,
data.primary_blend_mode,
&primary_layers[..],
)
.map_err(|e| Error::BackendSpecific(format!("FrameStream::end {:?}", e)))?;
}
Ok(())
}
fn begin_frame(
&mut self,
device: &mut SurfmanDevice,
contexts: &mut dyn GLContexts<SurfmanGL>,
layers: &[(ContextId, LayerId)],
) -> Result<Vec<SubImages>, Error> {
let data_guard = self.shared_data.lock().unwrap();
let data = data_guard.as_ref().unwrap();
let openxr_layers = &mut self.openxr_layers;
let clearer = &mut self.clearer;
self.frame_stream
.begin()
.map_err(|e| Error::BackendSpecific(format!("FrameStream::begin {:?}", e)))?;
layers
.iter()
.map(|&(context_id, layer_id)| {
let context = contexts
.context(device, context_id)
.ok_or(Error::NoMatchingDevice)?;
let openxr_layer = openxr_layers
.get_mut(&layer_id)
.ok_or(Error::NoMatchingDevice)?;
let image = openxr_layer.swapchain.acquire_image().map_err(|e| {
Error::BackendSpecific(format!("Swapchain::acquire_image {:?}", e))
})?;
openxr_layer
.swapchain
.wait_image(openxr::Duration::INFINITE)
.map_err(|e| {
Error::BackendSpecific(format!("Swapchain::wait_image {:?}", e))
})?;
openxr_layer.waited = true;
let color_surface_texture = openxr_layer
.get_surface_texture(device, context, image as usize)
.map_err(|e| {
Error::BackendSpecific(format!("Layer::get_surface_texture {:?}", e))
})?;
let color_texture = device.surface_texture_object(color_surface_texture);
let color_target = device.surface_gl_texture_target();
let depth_stencil_texture = openxr_layer.depth_stencil_texture;
let texture_array_index = None;
let origin = Point2D::new(0, 0);
let texture_size = openxr_layer.size;
let sub_image = Some(SubImage {
color_texture,
depth_stencil_texture,
texture_array_index,
viewport: Rect::new(origin, texture_size),
});
let view_sub_images = data
.viewports()
.viewports
.iter()
.map(|&viewport| SubImage {
color_texture,
depth_stencil_texture,
texture_array_index,
viewport,
})
.collect();
clearer.clear(
device,
contexts,
context_id,
layer_id,
color_texture,
color_target,
depth_stencil_texture,
);
Ok(SubImages {
layer_id,
sub_image,
view_sub_images,
})
})
.collect()
}
}
fn image_rect(viewport: Rect<i32, Viewport>) -> openxr::Rect2Di {
openxr::Rect2Di {
extent: openxr::Extent2Di {
height: viewport.size.height,
width: viewport.size.width,
},
offset: openxr::Offset2Di {
x: viewport.origin.x,
y: viewport.origin.y,
},
}
}
impl OpenXrDevice {
fn new(
instance: CreatedInstance,
granted_features: Vec<String>,
context_menu_provider: Option<Box<dyn ContextMenuProvider>>,
grand_manager: LayerGrandManager<SurfmanGL>,
) -> Result<OpenXrDevice, Error> {
let CreatedInstance {
instance,
supports_hands,
supports_secondary,
system,
} = instance;
let (init_tx, init_rx) = crossbeam_channel::unbounded();
let instance_clone = instance.clone();
let shared_data = Arc::new(Mutex::new(None));
let shared_data_clone = shared_data.clone();
let mut data = shared_data.lock().unwrap();
let layer_manager = grand_manager.create_layer_manager(move |device, _| {
let (session, frame_waiter, frame_stream) =
OpenXrLayerManager::create_session(device, &instance_clone, system)?;
let session = Arc::new(session);
init_tx
.send((session.clone(), frame_waiter))
.map_err(|_| Error::CommunicationError)?;
Ok(OpenXrLayerManager::new(
session,
shared_data_clone,
frame_stream,
))
})?;
let (session, frame_waiter) = init_rx.recv().map_err(|_| Error::CommunicationError)?;
// XXXPaul initialisation should happen on SessionStateChanged(Ready)?
if supports_secondary {
session
.begin_with_secondary(
ViewConfigurationType::PRIMARY_STEREO,
&[ViewConfigurationType::SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT],
)
.map_err(|e| {
Error::BackendSpecific(format!("Session::begin_with_secondary {:?}", e))
})?;
} else {
session
.begin(ViewConfigurationType::PRIMARY_STEREO)
.map_err(|e| Error::BackendSpecific(format!("Session::begin {:?}", e)))?;
}
let pose = Posef {
orientation: Quaternionf {
x: 0.,
y: 0.,
z: 0.,
w: 1.,
},
position: Vector3f {
x: 0.,
y: 0.,
z: 0.,
},
};
let space = session
.create_reference_space(ReferenceSpaceType::LOCAL, pose)
.map_err(|e| {
Error::BackendSpecific(format!("Session::create_reference_space {:?}", e))
})?;
let viewer_space = session
.create_reference_space(ReferenceSpaceType::VIEW, pose)
.map_err(|e| {
Error::BackendSpecific(format!("Session::create_reference_space {:?}", e))
})?;
let view_configuration_type = ViewConfigurationType::PRIMARY_STEREO;
let view_configurations = instance
.enumerate_view_configuration_views(system, view_configuration_type)
.map_err(|e| {
Error::BackendSpecific(format!(
"Session::enumerate_view_configuration_views {:?}",
e
))
})?;
let left_view_configuration = view_configurations[0];
let right_view_configuration = view_configurations[1];
let left_extent = Extent2Di {
width: left_view_configuration.recommended_image_rect_width as i32,
height: left_view_configuration.recommended_image_rect_height as i32,
};
let right_extent = Extent2Di {
width: right_view_configuration.recommended_image_rect_width as i32,
height: right_view_configuration.recommended_image_rect_height as i32,
};
assert_eq!(
left_view_configuration.recommended_image_rect_height,
right_view_configuration.recommended_image_rect_height,
);
let secondary_active = false;
let (secondary, secondary_blend_mode) = if supports_secondary {
let view_configuration = *instance
.enumerate_view_configuration_views(
system,
ViewConfigurationType::SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT,
)
.map_err(|e| {
Error::BackendSpecific(format!(
"Session::enumerate_view_configuration_views {:?}",
e
))
})?
.get(0)
.expect(
"Session::enumerate_view_configuration_views() returned no secondary views",
);
let secondary_blend_mode = instance
.enumerate_environment_blend_modes(
system,
ViewConfigurationType::SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT,
)
.map_err(|e| {
Error::BackendSpecific(format!(
"Instance::enumerate_environment_blend_modes {:?}",
e
))
})?[0];
let secondary_extent = Extent2Di {
width: view_configuration.recommended_image_rect_width as i32,
height: view_configuration.recommended_image_rect_height as i32,
};
let secondary = ViewInfo {
view: VIEW_INIT,
extent: secondary_extent,
cached_projection: Transform3D::identity(),
};
(Some(secondary), Some(secondary_blend_mode))
} else {
(None, None)
};
let primary_blend_mode = instance
.enumerate_environment_blend_modes(system, view_configuration_type)
.map_err(|e| {
Error::BackendSpecific(format!(
"Instance::enumerate_environment_blend_modes {:?}",
e
))