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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::channel;
use crate::ContextId;
use crate::DeviceAPI;
use crate::Error;
use crate::Event;
use crate::Floor;
use crate::Frame;
use crate::FrameUpdateEvent;
use crate::HitTestId;
use crate::HitTestSource;
use crate::InputSource;
use crate::LayerGrandManager;
use crate::LayerId;
use crate::LayerInit;
use crate::Native;
use crate::Receiver;
use crate::Sender;
use crate::Viewport;
use crate::Viewports;

use euclid::Rect;
use euclid::RigidTransform3D;
use euclid::Size2D;

use log::warn;

use std::thread;
use std::time::Duration;

#[cfg(feature = "ipc")]
use serde::{Deserialize, Serialize};

// How long to wait for an rAF.
static TIMEOUT: Duration = Duration::from_millis(5);

/// https://www.w3.org/TR/webxr/#xrsessionmode-enum
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "ipc", derive(Serialize, Deserialize))]
pub enum SessionMode {
    Inline,
    ImmersiveVR,
    ImmersiveAR,
}

/// https://immersive-web.github.io/webxr/#dictdef-xrsessioninit
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "ipc", derive(Serialize, Deserialize))]
pub struct SessionInit {
    pub required_features: Vec<String>,
    pub optional_features: Vec<String>,
    /// Secondary views are enabled with the `secondary-view` feature
    /// but for performance reasons we also ask users to enable this pref
    /// for now.
    pub first_person_observer_view: bool,
}

impl SessionInit {
    /// Helper function for validating a list of requested features against
    /// a list of supported features for a given mode
    pub fn validate(&self, mode: SessionMode, supported: &[String]) -> Result<Vec<String>, Error> {
        for f in &self.required_features {
            // viewer and local in immersive are granted by default
            // https://immersive-web.github.io/webxr/#default-features
            if f == "viewer" || (f == "local" && mode != SessionMode::Inline) {
                continue;
            }

            if !supported.contains(f) {
                return Err(Error::UnsupportedFeature(f.into()));
            }
        }
        let mut granted = self.required_features.clone();
        for f in &self.optional_features {
            if f == "viewer"
                || (f == "local" && mode != SessionMode::Inline)
                || supported.contains(f)
            {
                granted.push(f.clone());
            }
        }

        Ok(granted)
    }

    pub fn feature_requested(&self, f: &str) -> bool {
        self.required_features
            .iter()
            .chain(self.optional_features.iter())
            .find(|x| *x == f)
            .is_some()
    }
}

#[cfg(feature = "profile")]
fn to_ms(ns: u64) -> f64 {
    ns as f64 / 1_000_000.
}

/// https://immersive-web.github.io/webxr-ar-module/#xrenvironmentblendmode-enum
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "ipc", derive(Serialize, Deserialize))]
pub enum EnvironmentBlendMode {
    Opaque,
    AlphaBlend,
    Additive,
}

// The messages that are sent from the content thread to the session thread.
#[derive(Debug)]
#[cfg_attr(feature = "ipc", derive(Serialize, Deserialize))]
enum SessionMsg {
    CreateLayer(ContextId, LayerInit, Sender<Result<LayerId, Error>>),
    DestroyLayer(ContextId, LayerId),
    SetLayers(Vec<(ContextId, LayerId)>),
    SetEventDest(Sender<Event>),
    UpdateClipPlanes(/* near */ f32, /* far */ f32),
    StartRenderLoop,
    RenderAnimationFrame(/* request time */ u64),
    RequestHitTest(HitTestSource),
    CancelHitTest(HitTestId),
    Quit,
}

#[cfg_attr(feature = "ipc", derive(Serialize, Deserialize))]
#[derive(Clone)]
pub struct Quitter {
    sender: Sender<SessionMsg>,
}

impl Quitter {
    pub fn quit(&self) {
        let _ = self.sender.send(SessionMsg::Quit);
    }
}

/// An object that represents an XR session.
/// This is owned by the content thread.
/// https://www.w3.org/TR/webxr/#xrsession-interface
#[cfg_attr(feature = "ipc", derive(Serialize, Deserialize))]
pub struct Session {
    floor_transform: Option<RigidTransform3D<f32, Native, Floor>>,
    viewports: Viewports,
    sender: Sender<SessionMsg>,
    environment_blend_mode: EnvironmentBlendMode,
    initial_inputs: Vec<InputSource>,
    granted_features: Vec<String>,
    id: SessionId,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "ipc", derive(Deserialize, Serialize))]
pub struct SessionId(pub(crate) u32);

impl Session {
    pub fn id(&self) -> SessionId {
        self.id
    }

    pub fn floor_transform(&self) -> Option<RigidTransform3D<f32, Native, Floor>> {
        self.floor_transform.clone()
    }

    pub fn initial_inputs(&self) -> &[InputSource] {
        &self.initial_inputs
    }

    pub fn environment_blend_mode(&self) -> EnvironmentBlendMode {
        self.environment_blend_mode
    }

    pub fn viewports(&self) -> &[Rect<i32, Viewport>] {
        &self.viewports.viewports
    }

    /// A resolution large enough to contain all the viewports.
    /// https://immersive-web.github.io/webxr/#recommended-webgl-framebuffer-resolution
    ///
    /// Returns None if the session is inline
    pub fn recommended_framebuffer_resolution(&self) -> Option<Size2D<i32, Viewport>> {
        self.viewports()
            .iter()
            .fold(None::<Rect<_, _>>, |acc, vp| {
                Some(acc.map(|a| a.union(vp)).unwrap_or(*vp))
            })
            .map(|rect| Size2D::new(rect.max_x(), rect.max_y()))
    }

    pub fn create_layer(&self, context_id: ContextId, init: LayerInit) -> Result<LayerId, Error> {
        let (sender, receiver) = channel().map_err(|_| Error::CommunicationError)?;
        let _ = self
            .sender
            .send(SessionMsg::CreateLayer(context_id, init, sender));
        receiver.recv().map_err(|_| Error::CommunicationError)?
    }

    /// Destroy a layer
    pub fn destroy_layer(&self, context_id: ContextId, layer_id: LayerId) {
        let _ = self
            .sender
            .send(SessionMsg::DestroyLayer(context_id, layer_id));
    }

    pub fn set_layers(&self, layers: Vec<(ContextId, LayerId)>) {
        let _ = self.sender.send(SessionMsg::SetLayers(layers));
    }

    pub fn start_render_loop(&mut self) {
        let _ = self.sender.send(SessionMsg::StartRenderLoop);
    }

    pub fn update_clip_planes(&mut self, near: f32, far: f32) {
        let _ = self.sender.send(SessionMsg::UpdateClipPlanes(near, far));
    }

    pub fn set_event_dest(&mut self, dest: Sender<Event>) {
        let _ = self.sender.send(SessionMsg::SetEventDest(dest));
    }

    pub fn render_animation_frame(&mut self) {
        #[allow(unused)]
        let mut time = 0;
        #[cfg(feature = "profile")]
        {
            time = time::precise_time_ns();
        }
        let _ = self.sender.send(SessionMsg::RenderAnimationFrame(time));
    }

    pub fn end_session(&mut self) {
        let _ = self.sender.send(SessionMsg::Quit);
    }

    pub fn apply_event(&mut self, event: FrameUpdateEvent) {
        match event {
            FrameUpdateEvent::UpdateFloorTransform(floor) => self.floor_transform = floor,
            FrameUpdateEvent::UpdateViewports(vp) => self.viewports = vp,
            FrameUpdateEvent::HitTestSourceAdded(_) => (),
        }
    }

    pub fn granted_features(&self) -> &[String] {
        &self.granted_features
    }

    pub fn request_hit_test(&self, source: HitTestSource) {
        let _ = self.sender.send(SessionMsg::RequestHitTest(source));
    }

    pub fn cancel_hit_test(&self, id: HitTestId) {
        let _ = self.sender.send(SessionMsg::CancelHitTest(id));
    }
}

#[derive(PartialEq)]
enum RenderState {
    NotInRenderLoop,
    InRenderLoop,
    PendingQuit,
}

/// For devices that want to do their own thread management, the `SessionThread` type is exposed.
pub struct SessionThread<Device> {
    receiver: Receiver<SessionMsg>,
    sender: Sender<SessionMsg>,
    layers: Vec<(ContextId, LayerId)>,
    pending_layers: Option<Vec<(ContextId, LayerId)>>,
    frame_count: u64,
    frame_sender: Sender<Frame>,
    running: bool,
    device: Device,
    id: SessionId,
    render_state: RenderState,
}

impl<Device> SessionThread<Device>
where
    Device: DeviceAPI,
{
    pub fn new(
        mut device: Device,
        frame_sender: Sender<Frame>,
        id: SessionId,
    ) -> Result<Self, Error> {
        let (sender, receiver) = crate::channel().or(Err(Error::CommunicationError))?;
        device.set_quitter(Quitter {
            sender: sender.clone(),
        });
        let frame_count = 0;
        let running = true;
        let layers = Vec::new();
        let pending_layers = None;
        Ok(SessionThread {
            sender,
            receiver,
            device,
            layers,
            pending_layers,
            frame_count,
            frame_sender,
            running,
            id,
            render_state: RenderState::NotInRenderLoop,
        })
    }

    pub fn new_session(&mut self) -> Session {
        let floor_transform = self.device.floor_transform();
        let viewports = self.device.viewports();
        let sender = self.sender.clone();
        let initial_inputs = self.device.initial_inputs();
        let environment_blend_mode = self.device.environment_blend_mode();
        let granted_features = self.device.granted_features().into();
        Session {
            floor_transform,
            viewports,
            sender,
            initial_inputs,
            environment_blend_mode,
            granted_features,
            id: self.id,
        }
    }

    pub fn run(&mut self) {
        loop {
            if let Ok(msg) = self.receiver.recv() {
                if !self.handle_msg(msg) {
                    self.running = false;
                    break;
                }
            } else {
                break;
            }
        }
    }

    fn handle_msg(&mut self, msg: SessionMsg) -> bool {
        log::debug!("processing {:?}", msg);
        match msg {
            SessionMsg::SetEventDest(dest) => {
                self.device.set_event_dest(dest);
            }
            SessionMsg::RequestHitTest(source) => {
                self.device.request_hit_test(source);
            }
            SessionMsg::CancelHitTest(id) => {
                self.device.cancel_hit_test(id);
            }
            SessionMsg::CreateLayer(context_id, layer_init, sender) => {
                let result = self.device.create_layer(context_id, layer_init);
                let _ = sender.send(result);
            }
            SessionMsg::DestroyLayer(context_id, layer_id) => {
                self.layers.retain(|&(_, other_id)| layer_id != other_id);
                self.device.destroy_layer(context_id, layer_id);
            }
            SessionMsg::SetLayers(layers) => {
                self.pending_layers = Some(layers);
            }
            SessionMsg::StartRenderLoop => {
                if let Some(layers) = self.pending_layers.take() {
                    self.layers = layers;
                }
                let frame = match self.device.begin_animation_frame(&self.layers[..]) {
                    Some(frame) => frame,
                    None => {
                        warn!("Device stopped providing frames, exiting");
                        return false;
                    }
                };
                self.render_state = RenderState::InRenderLoop;
                let _ = self.frame_sender.send(frame);
            }
            SessionMsg::UpdateClipPlanes(near, far) => self.device.update_clip_planes(near, far),
            SessionMsg::RenderAnimationFrame(_sent_time) => {
                self.frame_count += 1;
                #[cfg(feature = "profile")]
                let render_start = time::precise_time_ns();
                #[cfg(feature = "profile")]
                println!(
                    "WEBXR PROFILING [raf transmitted]:\t{}ms",
                    to_ms(render_start - _sent_time)
                );

                #[cfg(feature = "profile")]
                let end_frame = time::precise_time_ns();
                self.device.end_animation_frame(&self.layers[..]);

                if self.render_state == RenderState::PendingQuit {
                    self.quit();
                    return false;
                }

                #[cfg(feature = "profile")]
                let ended_frame = time::precise_time_ns();
                #[cfg(feature = "profile")]
                println!(
                    "WEBXR PROFILING [raf end frame]:\t{}ms",
                    to_ms(ended_frame - end_frame)
                );

                #[cfg(feature = "profile")]
                let begin_frame = time::precise_time_ns();
                if let Some(layers) = self.pending_layers.take() {
                    self.layers = layers;
                }
                #[allow(unused_mut)]
                let mut frame = match self.device.begin_animation_frame(&self.layers[..]) {
                    Some(frame) => frame,
                    None => {
                        warn!("Device stopped providing frames, exiting");
                        return false;
                    }
                };
                #[cfg(feature = "profile")]
                let begun_frame = time::precise_time_ns();
                #[cfg(feature = "profile")]
                {
                    println!(
                        "WEBXR PROFILING [raf begin frame]:\t{}ms",
                        to_ms(begun_frame - begin_frame)
                    );
                    frame.sent_time = begun_frame;
                }

                let _ = self.frame_sender.send(frame);
            }
            SessionMsg::Quit => {
                if self.render_state == RenderState::NotInRenderLoop {
                    self.quit();
                    return false;
                } else {
                    self.render_state = RenderState::PendingQuit;
                }
            }
        }
        true
    }

    fn quit(&mut self) {
        self.render_state = RenderState::NotInRenderLoop;
        self.device.quit();
    }
}

/// Devices that need to can run sessions on the main thread.
pub trait MainThreadSession: 'static {
    fn run_one_frame(&mut self);
    fn running(&self) -> bool;
}

impl<Device> MainThreadSession for SessionThread<Device>
where
    Device: DeviceAPI,
{
    fn run_one_frame(&mut self) {
        let frame_count = self.frame_count;
        #[cfg(feature = "profile")]
        let start_run = time::precise_time_ns();
        while frame_count == self.frame_count && self.running {
            if let Ok(msg) = crate::recv_timeout(&self.receiver, TIMEOUT) {
                self.running = self.handle_msg(msg);
            } else {
                break;
            }
        }
        #[cfg(feature = "profile")]
        {
            let end_run = time::precise_time_ns();
            println!(
                "WEBXR PROFILING [run_one_frame]:\t{}ms",
                to_ms(end_run - start_run)
            );
        }
    }

    fn running(&self) -> bool {
        self.running
    }
}

/// A type for building XR sessions
pub struct SessionBuilder<'a, GL> {
    sessions: &'a mut Vec<Box<dyn MainThreadSession>>,
    frame_sender: Sender<Frame>,
    layer_grand_manager: LayerGrandManager<GL>,
    id: SessionId,
}

impl<'a, GL: 'static> SessionBuilder<'a, GL> {
    pub fn id(&self) -> SessionId {
        self.id
    }

    pub(crate) fn new(
        sessions: &'a mut Vec<Box<dyn MainThreadSession>>,
        frame_sender: Sender<Frame>,
        layer_grand_manager: LayerGrandManager<GL>,
        id: SessionId,
    ) -> Self {
        SessionBuilder {
            sessions,
            frame_sender,
            layer_grand_manager,
            id,
        }
    }

    /// For devices which are happy to hand over thread management to webxr.
    pub fn spawn<Device, Factory>(self, factory: Factory) -> Result<Session, Error>
    where
        Factory: 'static + FnOnce(LayerGrandManager<GL>) -> Result<Device, Error> + Send,
        Device: DeviceAPI,
    {
        let (acks, ackr) = crate::channel().or(Err(Error::CommunicationError))?;
        let frame_sender = self.frame_sender;
        let layer_grand_manager = self.layer_grand_manager;
        let id = self.id;
        thread::spawn(move || {
            match factory(layer_grand_manager)
                .and_then(|device| SessionThread::new(device, frame_sender, id))
            {
                Ok(mut thread) => {
                    let session = thread.new_session();
                    let _ = acks.send(Ok(session));
                    thread.run();
                }
                Err(err) => {
                    let _ = acks.send(Err(err));
                }
            }
        });
        ackr.recv().unwrap_or(Err(Error::CommunicationError))
    }

    /// For devices that need to run on the main thread.
    pub fn run_on_main_thread<Device, Factory>(self, factory: Factory) -> Result<Session, Error>
    where
        Factory: 'static + FnOnce(LayerGrandManager<GL>) -> Result<Device, Error>,
        Device: DeviceAPI,
    {
        let device = factory(self.layer_grand_manager)?;
        let frame_sender = self.frame_sender;
        let mut session_thread = SessionThread::new(device, frame_sender, self.id)?;
        let session = session_thread.new_session();
        self.sessions.push(Box::new(session_thread));
        Ok(session)
    }
}