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
#[cfg(feature = "loaded")]
use libloading::Library;
use std::{
ffi::{CStr, CString},
mem, ptr,
sync::Arc,
};
#[cfg(feature = "loaded")]
use std::{fmt, path::Path};
use crate::*;
#[derive(Clone)]
pub struct Entry {
inner: Arc<Inner>,
}
impl Entry {
#[cfg(feature = "linked")]
pub fn linked() -> Self {
Self {
inner: Arc::new(Inner {
raw: RawEntry {
get_instance_proc_addr: sys::get_instance_proc_addr,
create_instance: sys::create_instance,
enumerate_instance_extension_properties:
sys::enumerate_instance_extension_properties,
enumerate_api_layer_properties: sys::enumerate_api_layer_properties,
},
#[cfg(feature = "loaded")]
_lib_guard: None,
}),
}
}
#[cfg(feature = "loaded")]
pub fn load() -> std::result::Result<Self, LoadError> {
#[cfg(target_os = "windows")]
const PATH: &str = "openxr_loader.dll";
#[cfg(target_os = "macos")]
const PATH: &str = "libopenxr_loader.dylib";
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
const PATH: &str = "libopenxr_loader.so";
Self::load_from(Path::new(PATH))
}
#[cfg(feature = "loaded")]
pub fn load_from(path: &Path) -> std::result::Result<Self, LoadError> {
let lib = unsafe { Library::new(path).map_err(LoadError)? };
Ok(Self {
inner: Arc::new(Inner {
raw: unsafe {
RawEntry {
get_instance_proc_addr: *lib
.get(b"xrGetInstanceProcAddr\0")
.map_err(LoadError)?,
create_instance: *lib.get(b"xrCreateInstance\0").map_err(LoadError)?,
enumerate_instance_extension_properties: *lib
.get(b"xrEnumerateInstanceExtensionProperties\0")
.map_err(LoadError)?,
enumerate_api_layer_properties: *lib
.get(b"xrEnumerateApiLayerProperties\0")
.map_err(LoadError)?,
}
},
_lib_guard: Some(lib),
}),
})
}
#[inline]
pub fn fp(&self) -> &RawEntry {
&self.inner.raw
}
#[inline]
pub(crate) unsafe fn get_instance_proc_addr(
&self,
instance: sys::Instance,
name: &CStr,
) -> Result<unsafe extern "system" fn()> {
let mut f = None;
cvt((self.fp().get_instance_proc_addr)(
instance,
name.as_ptr(),
&mut f,
))?;
Ok(f.unwrap())
}
pub fn create_instance(
&self,
app_info: &ApplicationInfo,
required_extensions: &ExtensionSet,
layers: &[&str],
) -> Result<Instance> {
assert!(
app_info.application_name.len() < sys::MAX_APPLICATION_NAME_SIZE,
"application names are limited to {} bytes",
sys::MAX_APPLICATION_NAME_SIZE
);
assert!(
app_info.engine_name.len() < sys::MAX_ENGINE_NAME_SIZE,
"engine names are limited to {} bytes",
sys::MAX_ENGINE_NAME_SIZE
);
let ext_names = required_extensions.names();
let ext_ptrs = ext_names
.iter()
.map(|x| x.as_ptr() as *const _)
.collect::<Vec<_>>();
let layer_names = layers
.iter()
.filter_map(|&x| CString::new(x).ok())
.collect::<Vec<_>>();
let layer_ptrs = layer_names
.iter()
.map(|x| x.as_ptr() as *const _)
.collect::<Vec<_>>();
let mut info = sys::InstanceCreateInfo {
ty: sys::InstanceCreateInfo::TYPE,
next: ptr::null(),
create_flags: Default::default(),
application_info: sys::ApplicationInfo {
application_name: [0; sys::MAX_APPLICATION_NAME_SIZE],
application_version: app_info.application_version,
engine_name: [0; sys::MAX_ENGINE_NAME_SIZE],
engine_version: app_info.engine_version,
api_version: CURRENT_API_VERSION,
},
enabled_api_layer_count: layer_ptrs.len() as _,
enabled_api_layer_names: layer_ptrs.as_ptr(),
enabled_extension_count: ext_ptrs.len() as _,
enabled_extension_names: ext_ptrs.as_ptr(),
};
place_cstr(
&mut info.application_info.application_name,
&app_info.application_name,
);
place_cstr(
&mut info.application_info.engine_name,
&app_info.engine_name,
);
unsafe {
let mut handle = sys::Instance::NULL;
cvt((self.fp().create_instance)(&info, &mut handle))?;
let exts = InstanceExtensions::load(self, handle, required_extensions)?;
Instance::from_raw(self.clone(), handle, exts)
}
}
pub fn enumerate_extensions(&self) -> Result<ExtensionSet> {
unsafe {
let exts = get_arr_init(
sys::ExtensionProperties::out(ptr::null_mut()),
|cap, count, buf| {
(self.fp().enumerate_instance_extension_properties)(
ptr::null(),
cap,
count,
buf as _,
)
},
)?;
Ok(ExtensionSet::from_properties(mem::transmute(&exts[..])))
}
}
pub fn enumerate_layers(&self) -> Result<Vec<ApiLayerProperties>> {
unsafe {
let layers = get_arr_init(
sys::ApiLayerProperties::out(ptr::null_mut()),
|cap, count, buf| (self.fp().enumerate_api_layer_properties)(cap, count, buf as _),
)?;
Ok(layers
.into_iter()
.map(|x| {
let x = x.assume_init();
ApiLayerProperties {
layer_name: fixed_str(&x.layer_name).into(),
spec_version: x.spec_version,
layer_version: x.layer_version,
description: fixed_str(&x.description).into(),
}
})
.collect())
}
}
}
struct Inner {
raw: RawEntry,
#[cfg(feature = "loaded")]
_lib_guard: Option<Library>,
}
pub struct RawEntry {
pub get_instance_proc_addr: sys::pfn::GetInstanceProcAddr,
pub create_instance: sys::pfn::CreateInstance,
pub enumerate_instance_extension_properties: sys::pfn::EnumerateInstanceExtensionProperties,
pub enumerate_api_layer_properties: sys::pfn::EnumerateApiLayerProperties,
}
#[cfg(feature = "loaded")]
pub struct LoadError(libloading::Error);
#[cfg(feature = "loaded")]
impl fmt::Debug for LoadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
#[cfg(feature = "loaded")]
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
#[cfg(feature = "loaded")]
impl std::error::Error for LoadError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.0.source()
}
}
#[derive(Debug, Copy, Clone, Default)]
pub struct ApplicationInfo<'a> {
pub application_name: &'a str,
pub application_version: u32,
pub engine_name: &'a str,
pub engine_version: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[doc = "See [XrApiLayerProperties](https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrApiLayerProperties)"]
pub struct ApiLayerProperties {
pub layer_name: String,
pub spec_version: Version,
pub layer_version: u32,
pub description: String,
}