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
use std::{ffi::CString, marker::PhantomData, mem, ptr, sync::Arc};

use crate::*;

/// A rendering session using a particular graphics API `G`
pub struct Session<G: Graphics> {
    pub(crate) inner: Arc<SessionInner>,
    _marker: PhantomData<G>,
}

impl<G: Graphics> Session<G> {
    /// Take ownership of an existing session handle
    ///
    /// # Safety
    ///
    /// `handle` must be a valid session handle associated with `instance` which is not currently inside a frame.
    #[inline]
    pub unsafe fn from_raw(instance: Instance, handle: sys::Session) -> (Self, FrameStream<G>) {
        let session = Self {
            inner: Arc::new(SessionInner {
                instance: instance.clone(),
                handle,
            }),
            _marker: PhantomData,
        };
        (session.clone(), FrameStream::new(session))
    }

    /// Access the raw session handle
    #[inline]
    pub fn as_raw(&self) -> sys::Session {
        self.inner.handle
    }

    /// Access the `Instance` self is descended from
    #[inline]
    pub fn instance(&self) -> &Instance {
        &self.inner.instance
    }

    /// Set the debug name of this `Session`, if `XR_EXT_debug_utils` is loaded
    #[inline]
    pub fn set_name(&mut self, name: &str) -> Result<()> {
        if let Some(fp) = self.instance().exts().ext_debug_utils.as_ref() {
            let name = CString::new(name).unwrap();
            let info = sys::DebugUtilsObjectNameInfoEXT {
                ty: sys::DebugUtilsObjectNameInfoEXT::TYPE,
                next: ptr::null(),
                object_type: ObjectType::SESSION,
                object_handle: self.as_raw().into_raw(),
                object_name: name.as_ptr(),
            };
            unsafe {
                cvt((fp.set_debug_utils_object_name)(
                    self.instance().as_raw(),
                    &info,
                ))?;
            }
        }
        Ok(())
    }

    /// Request that the runtime show the application's rendered output to the user
    #[inline]
    pub fn begin(&self, ty: ViewConfigurationType) -> Result<sys::Result> {
        let info = sys::SessionBeginInfo {
            ty: sys::SessionBeginInfo::TYPE,
            next: ptr::null(),
            primary_view_configuration_type: ty,
        };
        unsafe { cvt((self.fp().begin_session)(self.as_raw(), &info)) }
    }

    /// Signal that the application no longer wishes to display rendered output, read input state,
    /// or control haptic events
    #[inline]
    pub fn end(&self) -> Result<sys::Result> {
        unsafe { cvt((self.fp().end_session)(self.as_raw())) }
    }

    #[inline]
    pub fn reference_space_bounds_rect(&self, ty: ReferenceSpaceType) -> Result<Option<Extent2Df>> {
        unsafe {
            let mut out = mem::uninitialized();
            let status = cvt((self.fp().get_reference_space_bounds_rect)(
                self.as_raw(),
                ty,
                &mut out,
            ))?;
            Ok(if status == sys::Result::SPACE_BOUNDS_UNAVAILABLE {
                None
            } else {
                Some(out)
            })
        }
    }

    /// Enumerate the set of reference space types supported for this session
    ///
    /// Constant for the lifetime of the session.
    #[inline]
    pub fn enumerate_reference_spaces(&self) -> Result<Vec<ReferenceSpaceType>> {
        get_arr(|cap, count, buf| unsafe {
            (self.fp().enumerate_reference_spaces)(self.as_raw(), cap, count, buf)
        })
    }

    /// Creates a `Space` based on a chosen reference space
    pub fn create_reference_space(
        &self,
        reference_space_type: ReferenceSpaceType,
        pose_in_reference_space: Posef,
    ) -> Result<Space> {
        let info = sys::ReferenceSpaceCreateInfo {
            ty: sys::ReferenceSpaceCreateInfo::TYPE,
            next: ptr::null(),
            reference_space_type,
            pose_in_reference_space,
        };
        let mut out = sys::Space::NULL;
        unsafe {
            cvt((self.fp().create_reference_space)(
                self.as_raw(),
                &info,
                &mut out,
            ))?;
            Ok(Space::reference_from_raw(self.clone(), out))
        }
    }

    /// Enumerate texture formats supported by the current session
    ///
    /// The type of formats returned is dependent on the graphics API for which the session was
    /// created.
    #[inline]
    pub fn enumerate_swapchain_formats(&self) -> Result<Vec<G::Format>> {
        let raw = get_arr(|capacity, count, buf| unsafe {
            (self.fp().enumerate_swapchain_formats)(self.as_raw(), capacity, count, buf)
        })?;
        Ok(raw.into_iter().map(G::raise_format).collect())
    }

    #[inline]
    pub fn create_swapchain(&self, info: &SwapchainCreateInfo<G>) -> Result<Swapchain<G>> {
        let mut out = sys::Swapchain::NULL;
        let info = sys::SwapchainCreateInfo {
            ty: sys::SwapchainCreateInfo::TYPE,
            next: ptr::null(),
            create_flags: info.create_flags,
            usage_flags: info.usage_flags,
            format: G::lower_format(info.format),
            sample_count: info.sample_count,
            width: info.width,
            height: info.height,
            face_count: info.face_count,
            array_size: info.array_size,
            mip_count: info.mip_count,
        };
        unsafe {
            cvt((self.fp().create_swapchain)(self.as_raw(), &info, &mut out))?;
            Ok(Swapchain::from_raw(self.clone(), out, info.create_flags))
        }
    }

    /// Get the view and projection info for a particular display time
    #[inline]
    pub fn locate_views(
        &self,
        display_time: Time,
        space: &Space,
    ) -> Result<(ViewStateFlags, Vec<View>)> {
        let info = sys::ViewLocateInfo {
            ty: sys::ViewLocateInfo::TYPE,
            next: ptr::null(),
            display_time,
            space: space.as_raw(),
        };
        let (flags, raw) = unsafe {
            let mut out = sys::ViewState {
                ty: sys::ViewState::TYPE,
                next: ptr::null_mut(),
                ..mem::uninitialized()
            };
            let raw = get_arr_init(
                sys::View {
                    ty: sys::View::TYPE,
                    next: ptr::null_mut(),
                    ..mem::uninitialized()
                },
                |cap, count, buf| {
                    (self.fp().locate_views)(self.as_raw(), &info, &mut out, cap, count, buf)
                },
            )?;
            (out.view_state_flags, raw)
        };
        Ok((
            flags,
            raw.into_iter()
                .map(|x| View {
                    pose: x.pose,
                    fov: x.fov,
                })
                .collect(),
        ))
    }

    /// Allocate a new [`ActionSet`]
    ///
    /// [`ActionSet`]: https://www.khronos.org/registry/OpenXR/specs/0.90/html/xrspec.html#input-action-creation
    #[inline]
    pub fn create_action_set(
        &self,
        name: &str,
        localized_name: &str,
        priority: u32,
    ) -> Result<ActionSet> {
        let info = builder::ActionSetCreateInfo::new()
            .action_set_name(name)
            .localized_action_set_name(localized_name)
            .priority(priority);
        unsafe {
            let mut out = sys::ActionSet::NULL;
            cvt((self.fp().create_action_set)(
                self.as_raw(),
                info.as_raw(),
                &mut out,
            ))?;
            Ok(ActionSet::from_raw(self.clone(), out))
        }
    }

    #[inline]
    pub fn set_interaction_profile_suggested_bindings(
        &self,
        interaction_profile: Path,
        bindings: &[Binding],
    ) -> Result<()> {
        let info = sys::InteractionProfileSuggestedBinding {
            ty: sys::InteractionProfileSuggestedBinding::TYPE,
            next: ptr::null(),
            interaction_profile,
            count_suggested_bindings: bindings.len() as u32,
            suggested_bindings: bindings.as_ptr() as *const _ as _,
        };
        unsafe {
            cvt((self.fp().set_interaction_profile_suggested_bindings)(
                self.as_raw(),
                &info,
            ))?;
        }
        Ok(())
    }

    /// Get the suggested interaction profile in use for a top level user path
    ///
    /// May be NULL.
    #[inline]
    pub fn current_interaction_profile(&self, top_level_user_path: Path) -> Result<Path> {
        unsafe {
            let mut out = sys::InteractionProfileInfo {
                ty: sys::InteractionProfileInfo::TYPE,
                next: ptr::null(),
                ..mem::uninitialized()
            };
            cvt((self.fp().get_current_interaction_profile)(
                self.as_raw(),
                top_level_user_path,
                &mut out,
            ))?;
            Ok(out.interaction_profile)
        }
    }

    /// Designate active input actions and update their states
    #[inline]
    pub fn sync_action_data(&self, action_sets: &[ActiveActionSet<'_>]) -> Result<()> {
        unsafe {
            cvt((self.fp().sync_action_data)(
                self.as_raw(),
                action_sets.len() as u32,
                action_sets.as_ptr() as _,
            ))?;
        }
        Ok(())
    }

    /// Get a name for the input source in the current system locale
    #[inline]
    pub fn input_source_localized_name(
        &self,
        source: Path,
        flags: InputSourceLocalizedNameFlags,
    ) -> Result<String> {
        get_str(|cap, count, buf| unsafe {
            (self.fp().get_input_source_localized_name)(
                self.as_raw(),
                source,
                flags,
                cap,
                count,
                buf,
            )
        })
    }

    // Private helper
    #[inline]
    fn fp(&self) -> &raw::Instance {
        self.inner.instance.fp()
    }

    pub(crate) fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            _marker: PhantomData,
        }
    }
}

impl<G: Graphics> Clone for Session<G> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            _marker: PhantomData,
        }
    }
}

pub(crate) struct SessionInner {
    pub(crate) instance: Instance,
    pub(crate) handle: sys::Session,
}

impl Drop for SessionInner {
    fn drop(&mut self) {
        unsafe {
            (self.instance.fp().destroy_session)(self.handle);
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub struct SwapchainCreateInfo<G: Graphics> {
    pub create_flags: SwapchainCreateFlags,
    pub usage_flags: SwapchainUsageFlags,
    pub format: G::Format,
    pub sample_count: u32,
    pub width: u32,
    pub height: u32,
    pub face_count: u32,
    pub array_size: u32,
    pub mip_count: u32,
}

#[derive(Copy, Clone)]
pub struct View {
    pub pose: Posef,
    pub fov: Fovf,
}

#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct Binding<'a> {
    _inner: sys::ActionSuggestedBinding,
    _marker: PhantomData<&'a ()>,
}

impl<'a> Binding<'a> {
    #[inline]
    pub fn new<T: ActionTy>(action: &'a Action<T>, binding: Path) -> Self {
        Self {
            _inner: sys::ActionSuggestedBinding {
                action: action.as_raw(),
                binding: binding,
            },
            _marker: PhantomData,
        }
    }
}

#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct ActiveActionSet<'a> {
    _inner: sys::ActiveActionSet,
    _marker: PhantomData<&'a ActionSet>,
}

impl<'a> ActiveActionSet<'a> {
    #[inline]
    pub fn new(action_set: &'a ActionSet) -> Self {
        Self::with_subaction(action_set, Path::NULL)
    }

    #[inline]
    pub fn with_subaction(action_set: &'a ActionSet, subaction_path: Path) -> Self {
        Self {
            _inner: sys::ActiveActionSet {
                ty: sys::ActiveActionSet::TYPE,
                next: ptr::null(),
                action_set: action_set.as_raw(),
                subaction_path,
            },
            _marker: PhantomData,
        }
    }
}

impl<'a> From<&'a ActionSet> for ActiveActionSet<'a> {
    fn from(x: &'a ActionSet) -> Self {
        Self::new(x)
    }
}