-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
1333 lines (1140 loc) · 60.3 KB
/
main.cpp
File metadata and controls
1333 lines (1140 loc) · 60.3 KB
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
// Copyright (c) 2017-2020 The Khronos Group Inc.
// Copyright (c) 2020 ReliaSolve LLC.
//
// SPDX-License-Identifier: Apache-2.0
#include <stdlib.h>
#include <string>
#include <iostream>
#include <array>
#include <map>
#include "pch.h"
#include "common.h"
#include "gfxwrapper_opengl.h"
#include "xr_linear.h"
// Include the file that describes the cubes we draw in this example.
#include "geometry.h"
unsigned g_verbosity = 1;
static void Usage(std::string name)
{
std::cout << "Usage: " << name << " [--verbosity V]" << std::endl;
std::cout << " --verbosity: Set V to 0 for silence, higher for more info (default " << g_verbosity << ")" << std::endl;
}
//============================================================================================
// Helper functions.
namespace Math {
namespace Pose {
XrPosef Identity() {
XrPosef t{};
t.orientation.w = 1;
return t;
}
XrPosef Translation(const XrVector3f& translation) {
XrPosef t = Identity();
t.position = translation;
return t;
}
XrPosef RotateCCWAboutYAxis(float radians, XrVector3f translation) {
XrPosef t = Identity();
t.orientation.x = 0.f;
t.orientation.y = std::sin(radians * 0.5f);
t.orientation.z = 0.f;
t.orientation.w = std::cos(radians * 0.5f);
t.position = translation;
return t;
}
} // namespace Pose
} // namespace Math
//============================================================================================
// Code to handle knowing which spaces things are rendered in.
/// @todo If you only want to render in world space, all of the space-choosing machinery
/// can be removed. Note that the hands are spaces in addition to the application-defined ones.
// Maps from the space back to its name so we can know what to render in each
std::map<XrSpace, std::string> g_spaceNames;
// Description of one of the spaces we want to render in, along with a scale factor to
// be applied in that space. In the original example, this is used to position, orient,
// and scale cubes to various spaces including hand space.
struct Space {
XrPosef Pose; ///< Pose of the space relative to g_appSpace
XrVector3f Scale; ///< Scale hint for the space
std::string Name; ///< An identifier so we can know what to render in each space
};
//============================================================================================
// OpenGL state and functions.
constexpr float DarkSlateGray[] = {0.184313729f, 0.309803933f, 0.309803933f, 1.0f};
#ifdef XR_USE_PLATFORM_WIN32
XrGraphicsBindingOpenGLWin32KHR g_graphicsBinding{XR_TYPE_GRAPHICS_BINDING_OPENGL_WIN32_KHR};
#elif defined(XR_USE_PLATFORM_XLIB)
XrGraphicsBindingOpenGLXlibKHR g_graphicsBinding{XR_TYPE_GRAPHICS_BINDING_OPENGL_XLIB_KHR};
#elif defined(XR_USE_PLATFORM_XCB)
XrGraphicsBindingOpenGLXcbKHR g_graphicsBinding{XR_TYPE_GRAPHICS_BINDING_OPENGL_XCB_KHR};
#elif defined(XR_USE_PLATFORM_WAYLAND)
XrGraphicsBindingOpenGLWaylandKHR g_graphicsBinding{XR_TYPE_GRAPHICS_BINDING_OPENGL_WAYLAND_KHR};
#endif
ksGpuWindow g_window{};
std::list<std::vector<XrSwapchainImageOpenGLKHR>> g_swapchainImageBuffers;
GLuint g_swapchainFramebuffer{0};
GLuint g_program{0};
GLint g_modelViewProjectionUniformLocation{0};
GLint g_vertexAttribCoords{0};
GLint g_vertexAttribColor{0};
GLuint g_vao{0};
GLuint g_cubeVertexBuffer{0};
GLuint g_cubeIndexBuffer{0};
// Map color buffer to associated depth buffer. This map is populated on demand.
std::map<uint32_t, uint32_t> g_colorToDepthMap;
static const char* VertexShaderGlsl = R"_(
#version 410
in vec3 VertexPos;
in vec3 VertexColor;
out vec3 PSVertexColor;
uniform mat4 ModelViewProjection;
void main() {
gl_Position = ModelViewProjection * vec4(VertexPos, 1.0);
PSVertexColor = VertexColor;
}
)_";
static const char* FragmentShaderGlsl = R"_(
#version 410
in vec3 PSVertexColor;
out vec4 FragColor;
void main() {
FragColor = vec4(PSVertexColor, 1);
}
)_";
void CheckShader(GLuint shader) {
GLint r = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &r);
if (r == GL_FALSE) {
GLchar msg[4096] = {};
GLsizei length;
glGetShaderInfoLog(shader, sizeof(msg), &length, msg);
THROW(Fmt("Compile shader failed: %s", msg));
}
}
void CheckProgram(GLuint prog) {
GLint r = 0;
glGetProgramiv(prog, GL_LINK_STATUS, &r);
if (r == GL_FALSE) {
GLchar msg[4096] = {};
GLsizei length;
glGetProgramInfoLog(prog, sizeof(msg), &length, msg);
THROW(Fmt("Link program failed: %s", msg));
}
}
static void OpenGLInitializeResources()
{
glGenFramebuffers(1, &g_swapchainFramebuffer);
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &VertexShaderGlsl, nullptr);
glCompileShader(vertexShader);
CheckShader(vertexShader);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &FragmentShaderGlsl, nullptr);
glCompileShader(fragmentShader);
CheckShader(fragmentShader);
g_program = glCreateProgram();
glAttachShader(g_program, vertexShader);
glAttachShader(g_program, fragmentShader);
glLinkProgram(g_program);
CheckProgram(g_program);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
g_modelViewProjectionUniformLocation = glGetUniformLocation(g_program, "ModelViewProjection");
g_vertexAttribCoords = glGetAttribLocation(g_program, "VertexPos");
g_vertexAttribColor = glGetAttribLocation(g_program, "VertexColor");
glGenBuffers(1, &g_cubeVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, g_cubeVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(Geometry::c_cubeVertices), Geometry::c_cubeVertices, GL_STATIC_DRAW);
glGenBuffers(1, &g_cubeIndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_cubeIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Geometry::c_cubeIndices), Geometry::c_cubeIndices, GL_STATIC_DRAW);
glGenVertexArrays(1, &g_vao);
glBindVertexArray(g_vao);
glEnableVertexAttribArray(g_vertexAttribCoords);
glEnableVertexAttribArray(g_vertexAttribColor);
glBindBuffer(GL_ARRAY_BUFFER, g_cubeVertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_cubeIndexBuffer);
glVertexAttribPointer(g_vertexAttribCoords, 3, GL_FLOAT, GL_FALSE, sizeof(Geometry::Vertex), nullptr);
glVertexAttribPointer(g_vertexAttribColor, 3, GL_FLOAT, GL_FALSE, sizeof(Geometry::Vertex),
reinterpret_cast<const void*>(sizeof(XrVector3f)));
}
static void OpenGLInitializeDevice(XrInstance instance, XrSystemId systemId)
{
// Extension function must be loaded by name
PFN_xrGetOpenGLGraphicsRequirementsKHR pfnGetOpenGLGraphicsRequirementsKHR = nullptr;
CHECK_XRCMD(xrGetInstanceProcAddr(instance, "xrGetOpenGLGraphicsRequirementsKHR",
reinterpret_cast<PFN_xrVoidFunction*>(&pfnGetOpenGLGraphicsRequirementsKHR)));
XrGraphicsRequirementsOpenGLKHR graphicsRequirements{XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_KHR};
CHECK_XRCMD(pfnGetOpenGLGraphicsRequirementsKHR(instance, systemId, &graphicsRequirements));
// Initialize the gl extensions. Note we have to open a window.
ksDriverInstance driverInstance{};
ksGpuQueueInfo queueInfo{};
ksGpuSurfaceColorFormat colorFormat{KS_GPU_SURFACE_COLOR_FORMAT_B8G8R8A8};
ksGpuSurfaceDepthFormat depthFormat{KS_GPU_SURFACE_DEPTH_FORMAT_D24};
ksGpuSampleCount sampleCount{KS_GPU_SAMPLE_COUNT_1};
if (!ksGpuWindow_Create(&g_window, &driverInstance, &queueInfo, 0, colorFormat, depthFormat, sampleCount, 640, 480, false)) {
THROW("Unable to create GL context");
}
GLint major = 0;
GLint minor = 0;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
const XrVersion desiredApiVersion = XR_MAKE_VERSION(major, minor, 0);
if (graphicsRequirements.minApiVersionSupported > desiredApiVersion) {
THROW("Runtime does not support desired Graphics API and/or version");
}
#ifdef XR_USE_PLATFORM_WIN32
g_graphicsBinding.hDC = g_window.context.hDC;
g_graphicsBinding.hGLRC = g_window.context.hGLRC;
#elif defined(XR_USE_PLATFORM_XLIB)
g_graphicsBinding.xDisplay = g_window.context.xDisplay;
g_graphicsBinding.visualid = g_window.context.visualid;
g_graphicsBinding.glxFBConfig = g_window.context.glxFBConfig;
g_graphicsBinding.glxDrawable = g_window.context.glxDrawable;
g_graphicsBinding.glxContext = g_window.context.glxContext;
#elif defined(XR_USE_PLATFORM_XCB)
// TODO: Still missing the platform adapter, and some items to make this usable.
g_graphicsBinding.connection = g_window.connection;
// g_graphicsBinding.screenNumber = g_window.context.screenNumber;
// g_graphicsBinding.fbconfigid = g_window.context.fbconfigid;
g_graphicsBinding.visualid = g_window.context.visualid;
g_graphicsBinding.glxDrawable = g_window.context.glxDrawable;
// g_graphicsBinding.glxContext = g_window.context.glxContext;
#elif defined(XR_USE_PLATFORM_WAYLAND)
// TODO: Just need something other than NULL here for now (for validation). Eventually need
// to correctly put in a valid pointer to an wl_display
g_graphicsBinding.display = reinterpret_cast<wl_display*>(0xFFFFFFFF);
#endif
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(
[](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message,
const void* userParam) {
std::cout << "GL Debug: " << std::string(message, 0, length) << std::endl;
},
nullptr);
OpenGLInitializeResources();
}
static int64_t OpenGLSelectColorSwapchainFormat(const std::vector<int64_t>& runtimeFormats)
{
// List of supported color swapchain formats.
constexpr int64_t SupportedColorSwapchainFormats[] = {
GL_RGB10_A2,
GL_RGBA16F,
// The two below should only be used as a fallback, as they are linear color formats without enough bits for color
// depth, thus leading to banding.
GL_RGBA8,
GL_RGBA8_SNORM,
};
auto swapchainFormatIt =
std::find_first_of(runtimeFormats.begin(), runtimeFormats.end(), std::begin(SupportedColorSwapchainFormats),
std::end(SupportedColorSwapchainFormats));
if (swapchainFormatIt == runtimeFormats.end()) {
THROW("No runtime swapchain format supported for color swapchain");
}
return *swapchainFormatIt;
}
static std::vector<XrSwapchainImageBaseHeader*> OpenGLAllocateSwapchainImageStructs(
uint32_t capacity, const XrSwapchainCreateInfo& /*swapchainCreateInfo*/)
{
// Allocate and initialize the buffer of image structs (must be sequential in memory for xrEnumerateSwapchainImages).
// Return back an array of pointers to each swapchain image struct so the consumer doesn't need to know the type/size.
std::vector<XrSwapchainImageOpenGLKHR> swapchainImageBuffer(capacity);
std::vector<XrSwapchainImageBaseHeader*> swapchainImageBase;
for (XrSwapchainImageOpenGLKHR& image : swapchainImageBuffer) {
image.type = XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_KHR;
swapchainImageBase.push_back(reinterpret_cast<XrSwapchainImageBaseHeader*>(&image));
}
// Keep the buffer alive by moving it into the list of buffers.
g_swapchainImageBuffers.push_back(std::move(swapchainImageBuffer));
return swapchainImageBase;
}
static uint32_t OpenGLGetDepthTexture(uint32_t colorTexture)
{
// If a depth-stencil view has already been created for this back-buffer, use it.
auto depthBufferIt = g_colorToDepthMap.find(colorTexture);
if (depthBufferIt != g_colorToDepthMap.end()) {
return depthBufferIt->second;
}
// This back-buffer has no corresponding depth-stencil texture, so create one with matching dimensions.
GLint width;
GLint height;
glBindTexture(GL_TEXTURE_2D, colorTexture);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height);
uint32_t depthTexture;
glGenTextures(1, &depthTexture);
glBindTexture(GL_TEXTURE_2D, depthTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
g_colorToDepthMap.insert(std::make_pair(colorTexture, depthTexture));
return depthTexture;
}
static void OpenGLRenderView(const XrCompositionLayerProjectionView& layerView, const XrSwapchainImageBaseHeader* swapchainImage,
int64_t swapchainFormat, const std::vector<Space>& spaces)
{
CHECK(layerView.subImage.imageArrayIndex == 0); // Texture arrays not supported.
UNUSED_PARM(swapchainFormat); // Not used in this function for now.
glBindFramebuffer(GL_FRAMEBUFFER, g_swapchainFramebuffer);
const uint32_t colorTexture = reinterpret_cast<const XrSwapchainImageOpenGLKHR*>(swapchainImage)->image;
glViewport(static_cast<GLint>(layerView.subImage.imageRect.offset.x),
static_cast<GLint>(layerView.subImage.imageRect.offset.y),
static_cast<GLsizei>(layerView.subImage.imageRect.extent.width),
static_cast<GLsizei>(layerView.subImage.imageRect.extent.height));
const uint32_t depthTexture = OpenGLGetDepthTexture(colorTexture);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTexture, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
// Disable back-face culling so we can see the inside of the world-space cube
glDisable(GL_CULL_FACE);
//glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
// Clear swapchain and depth buffer.
glClearColor(DarkSlateGray[0], DarkSlateGray[1], DarkSlateGray[2], DarkSlateGray[3]);
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// Set shaders and uniform variables.
glUseProgram(g_program);
// Set cube primitive data.
glBindVertexArray(g_vao);
const auto& pose = layerView.pose;
XrMatrix4x4f proj;
XrMatrix4x4f_CreateProjectionFov(&proj, GRAPHICS_OPENGL, layerView.fov, 0.05f, 100.0f);
XrMatrix4x4f toView;
XrVector3f scale{1.f, 1.f, 1.f};
XrMatrix4x4f_CreateTranslationRotationScale(&toView, &pose.position, &pose.orientation, &scale);
XrMatrix4x4f view;
XrMatrix4x4f_InvertRigidBody(&view, &toView);
XrMatrix4x4f vp;
XrMatrix4x4f_Multiply(&vp, &proj, &view);
// Things drawn here will appear in world space at the scale specified above (if scale = 1 then
// unit scale). The Model transform and scale will adjust where and how large they are.
// Here, we draw a cube that is 10 meters large located at the origin.
/// @todo Replace with the things you'd like to be drawn in the world.
{
XrPosef id = Math::Pose::Identity();
XrVector3f worldCubeScale{10.f, 10.f, 10.f};
// Compute the model-view-projection transform and set it..
XrMatrix4x4f model;
XrMatrix4x4f_CreateTranslationRotationScale(&model, &id.position, &id.orientation, &worldCubeScale);
XrMatrix4x4f mvp;
XrMatrix4x4f_Multiply(&mvp, &vp, &model);
glUniformMatrix4fv(g_modelViewProjectionUniformLocation, 1, GL_FALSE, reinterpret_cast<const GLfloat*>(&mvp));
// Draw the cube.
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(ArraySize(Geometry::c_cubeIndices)), GL_UNSIGNED_SHORT, nullptr);
}
// Render a cube within each of the spaces we've been asked to render, at the requested sizes. These show
// the centers of each of the spaces we defined.
/// @todo Use the name of each space to determine what to draw in it.
for (const Space& space : spaces) {
if (g_verbosity >= 10) {
std::cout << " Rendering " << space.Name << " space" << std::endl;
}
// Compute the model-view-projection transform and set it..
XrMatrix4x4f model;
XrMatrix4x4f_CreateTranslationRotationScale(&model, &space.Pose.position, &space.Pose.orientation, &space.Scale);
XrMatrix4x4f mvp;
XrMatrix4x4f_Multiply(&mvp, &vp, &model);
glUniformMatrix4fv(g_modelViewProjectionUniformLocation, 1, GL_FALSE, reinterpret_cast<const GLfloat*>(&mvp));
// Draw the cube.
glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(ArraySize(Geometry::c_cubeIndices)), GL_UNSIGNED_SHORT, nullptr);
}
glBindVertexArray(0);
glUseProgram(0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Swap our window every other eye for RenderDoc
// (This is not needed unless we're rendering into that window, but we leave it here.)
static int everyOther = 0;
if ((everyOther++ & 1) != 0) {
ksGpuWindow_SwapBuffers(&g_window);
}
}
static void OpenGLTearDown()
{
if (g_swapchainFramebuffer != 0) {
glDeleteFramebuffers(1, &g_swapchainFramebuffer);
}
if (g_program != 0) {
glDeleteProgram(g_program);
}
if (g_vao != 0) {
glDeleteVertexArrays(1, &g_vao);
}
if (g_cubeVertexBuffer != 0) {
glDeleteBuffers(1, &g_cubeVertexBuffer);
}
if (g_cubeIndexBuffer != 0) {
glDeleteBuffers(1, &g_cubeIndexBuffer);
}
for (auto& colorToDepth : g_colorToDepthMap) {
if (colorToDepth.second != 0) {
glDeleteTextures(1, &colorToDepth.second);
}
}
}
//============================================================================================
// OpenXR state and functions.
#if !defined(XR_USE_PLATFORM_WIN32)
#define strcpy_s(dest, source) strncpy((dest), (source), sizeof(dest))
#endif
namespace Side {
const int LEFT = 0;
const int RIGHT = 1;
const int COUNT = 2;
} // namespace Side
struct InputState {
XrActionSet actionSet{XR_NULL_HANDLE};
XrAction grabAction{XR_NULL_HANDLE};
XrAction poseAction{XR_NULL_HANDLE};
XrAction vibrateAction{XR_NULL_HANDLE};
XrAction quitAction{XR_NULL_HANDLE};
std::array<XrPath, Side::COUNT> handSubactionPath;
std::array<XrSpace, Side::COUNT> handSpace;
std::array<float, Side::COUNT> handScale = {{1.0f, 1.0f}};
std::array<XrBool32, Side::COUNT> handActive;
};
struct Swapchain {
XrSwapchain handle;
int32_t width;
int32_t height;
};
XrInstance g_instance{XR_NULL_HANDLE};
XrSession g_session{XR_NULL_HANDLE};
XrSpace g_appSpace{XR_NULL_HANDLE};
XrFormFactor g_formFactor{XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY};
XrViewConfigurationType g_viewConfigType{XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO};
XrEnvironmentBlendMode g_environmentBlendMode{XR_ENVIRONMENT_BLEND_MODE_OPAQUE};
XrSystemId g_systemId{XR_NULL_SYSTEM_ID};
std::vector<XrViewConfigurationView> g_configViews;
std::vector<Swapchain> g_swapchains;
std::map<XrSwapchain, std::vector<XrSwapchainImageBaseHeader*>> g_swapchainImages;
std::vector<XrView> g_views;
int64_t g_colorSwapchainFormat{-1};
std::vector<XrSpace> g_visualizedSpaces;
// Application's current lifecycle state according to the runtime
XrSessionState g_sessionState{XR_SESSION_STATE_UNKNOWN};
bool g_sessionRunning{false};
XrEventDataBuffer g_eventDataBuffer;
InputState g_input;
static void OpenXRCreateInstance()
{
#ifdef XR_USE_PLATFORM_WIN32
CHECK_HRCMD(CoInitializeEx(nullptr, COINIT_MULTITHREADED));
#endif
CHECK(g_instance == XR_NULL_HANDLE);
// Create union of extensions required by OpenGL.
std::vector<const char*> extensions = {XR_KHR_OPENGL_ENABLE_EXTENSION_NAME};
XrInstanceCreateInfo createInfo{XR_TYPE_INSTANCE_CREATE_INFO};
createInfo.next = nullptr; // Needs to be set on Android.
createInfo.enabledExtensionCount = (uint32_t)extensions.size();
createInfo.enabledExtensionNames = extensions.data();
/// @todo Change the application name here.
strcpy(createInfo.applicationInfo.applicationName, "OpenXR-OpenGL-Example");
createInfo.applicationInfo.apiVersion = XR_CURRENT_API_VERSION;
CHECK_XRCMD(xrCreateInstance(&createInfo, &g_instance));
}
static XrReferenceSpaceCreateInfo GetXrReferenceSpaceCreateInfo(const std::string& referenceSpaceTypeStr) {
XrReferenceSpaceCreateInfo referenceSpaceCreateInfo{XR_TYPE_REFERENCE_SPACE_CREATE_INFO};
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::Identity();
if (EqualsIgnoreCase(referenceSpaceTypeStr, "View")) {
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_VIEW;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "ViewFront")) {
// Render head-locked 2m in front of device.
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::Translation({0.f, 0.f, -2.f}),
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_VIEW;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "Local")) {
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "Stage")) {
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "StageLeft")) {
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::RotateCCWAboutYAxis(0.f, {-2.f, 0.f, -2.f});
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "StageRight")) {
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::RotateCCWAboutYAxis(0.f, {2.f, 0.f, -2.f});
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "StageLeftRotated")) {
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::RotateCCWAboutYAxis(3.14f / 3.f, {-2.f, 0.5f, -2.f});
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
} else if (EqualsIgnoreCase(referenceSpaceTypeStr, "StageRightRotated")) {
referenceSpaceCreateInfo.poseInReferenceSpace = Math::Pose::RotateCCWAboutYAxis(-3.14f / 3.f, {2.f, 0.5f, -2.f});
referenceSpaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
} else {
throw std::invalid_argument(Fmt("Unknown reference space type '%s'", referenceSpaceTypeStr.c_str()));
}
return referenceSpaceCreateInfo;
}
/// @todo Change these to match the desired behavior.
struct Options {
std::string GraphicsPlugin;
XrFormFactor FormFactor{XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY};
XrViewConfigurationType ViewConfiguration{XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO};
XrEnvironmentBlendMode EnvironmentBlendMode{XR_ENVIRONMENT_BLEND_MODE_OPAQUE};
std::string AppSpace{"Local"};
} g_options;
static void OpenXRInitializeSystem()
{
CHECK(g_instance != XR_NULL_HANDLE);
CHECK(g_systemId == XR_NULL_SYSTEM_ID);
g_formFactor = g_options.FormFactor;
g_viewConfigType = g_options.ViewConfiguration;
g_environmentBlendMode = g_options.EnvironmentBlendMode;
XrSystemGetInfo systemInfo{XR_TYPE_SYSTEM_GET_INFO};
systemInfo.formFactor = g_formFactor;
CHECK_XRCMD(xrGetSystem(g_instance, &systemInfo, &g_systemId));
if (g_verbosity >= 2) std::cout << "Using system " << g_systemId
<< " for form factor " << to_string(g_formFactor) << std::endl;
CHECK(g_instance != XR_NULL_HANDLE);
CHECK(g_systemId != XR_NULL_SYSTEM_ID);
/// @todo Print information about the system here in verbose mode.
// The graphics API can initialize the graphics device now that the systemId and instance
// handle are available.
OpenGLInitializeDevice(g_instance, g_systemId);
}
/// @todo Change the behaviors by modifying the action bindings.
void OpenXRInitializeActions() {
// Create an action set.
{
XrActionSetCreateInfo actionSetInfo{XR_TYPE_ACTION_SET_CREATE_INFO};
strcpy_s(actionSetInfo.actionSetName, "gameplay");
strcpy_s(actionSetInfo.localizedActionSetName, "Gameplay");
actionSetInfo.priority = 0;
CHECK_XRCMD(xrCreateActionSet(g_instance, &actionSetInfo, &g_input.actionSet));
}
// Get the XrPath for the left and right hands - we will use them as subaction paths.
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/left", &g_input.handSubactionPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/right", &g_input.handSubactionPath[Side::RIGHT]));
// Create actions.
{
// Create an input action for grabbing objects with the left and right hands.
XrActionCreateInfo actionInfo{XR_TYPE_ACTION_CREATE_INFO};
actionInfo.actionType = XR_ACTION_TYPE_FLOAT_INPUT;
strcpy_s(actionInfo.actionName, "grab_object");
strcpy_s(actionInfo.localizedActionName, "Grab Object");
actionInfo.countSubactionPaths = uint32_t(g_input.handSubactionPath.size());
actionInfo.subactionPaths = g_input.handSubactionPath.data();
CHECK_XRCMD(xrCreateAction(g_input.actionSet, &actionInfo, &g_input.grabAction));
// Create an input action getting the left and right hand poses.
actionInfo.actionType = XR_ACTION_TYPE_POSE_INPUT;
strcpy_s(actionInfo.actionName, "hand_pose");
strcpy_s(actionInfo.localizedActionName, "Hand Pose");
actionInfo.countSubactionPaths = uint32_t(g_input.handSubactionPath.size());
actionInfo.subactionPaths = g_input.handSubactionPath.data();
CHECK_XRCMD(xrCreateAction(g_input.actionSet, &actionInfo, &g_input.poseAction));
// Create output actions for vibrating the left and right controller.
actionInfo.actionType = XR_ACTION_TYPE_VIBRATION_OUTPUT;
strcpy_s(actionInfo.actionName, "vibrate_hand");
strcpy_s(actionInfo.localizedActionName, "Vibrate Hand");
actionInfo.countSubactionPaths = uint32_t(g_input.handSubactionPath.size());
actionInfo.subactionPaths = g_input.handSubactionPath.data();
CHECK_XRCMD(xrCreateAction(g_input.actionSet, &actionInfo, &g_input.vibrateAction));
// Create input actions for quitting the session using the left and right controller.
// Since it doesn't matter which hand did this, we do not specify subaction paths for it.
// We will just suggest bindings for both hands, where possible.
actionInfo.actionType = XR_ACTION_TYPE_BOOLEAN_INPUT;
strcpy_s(actionInfo.actionName, "quit_session");
strcpy_s(actionInfo.localizedActionName, "Quit Session");
actionInfo.countSubactionPaths = 0;
actionInfo.subactionPaths = nullptr;
CHECK_XRCMD(xrCreateAction(g_input.actionSet, &actionInfo, &g_input.quitAction));
}
std::array<XrPath, Side::COUNT> selectPath;
std::array<XrPath, Side::COUNT> squeezeValuePath;
std::array<XrPath, Side::COUNT> squeezeForcePath;
std::array<XrPath, Side::COUNT> squeezeClickPath;
std::array<XrPath, Side::COUNT> posePath;
std::array<XrPath, Side::COUNT> hapticPath;
std::array<XrPath, Side::COUNT> menuClickPath;
std::array<XrPath, Side::COUNT> bClickPath;
std::array<XrPath, Side::COUNT> triggerValuePath;
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/left/input/select/click", &selectPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/right/input/select/click", &selectPath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/left/input/squeeze/value", &squeezeValuePath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/right/input/squeeze/value", &squeezeValuePath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/left/input/squeeze/force", &squeezeForcePath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/right/input/squeeze/force", &squeezeForcePath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/left/input/squeeze/click", &squeezeClickPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/right/input/squeeze/click", &squeezeClickPath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/left/input/grip/pose", &posePath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/right/input/grip/pose", &posePath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/left/output/haptic", &hapticPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/right/output/haptic", &hapticPath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/left/input/menu/click", &menuClickPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/right/input/menu/click", &menuClickPath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/left/input/b/click", &bClickPath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/right/input/b/click", &bClickPath[Side::RIGHT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/left/input/trigger/value", &triggerValuePath[Side::LEFT]));
CHECK_XRCMD(xrStringToPath(g_instance, "/user/hand/right/input/trigger/value", &triggerValuePath[Side::RIGHT]));
// Suggest bindings for KHR Simple.
{
XrPath khrSimpleInteractionProfilePath;
CHECK_XRCMD(
xrStringToPath(g_instance, "/interaction_profiles/khr/simple_controller", &khrSimpleInteractionProfilePath));
std::vector<XrActionSuggestedBinding> bindings{{// Fall back to a click input for the grab action.
{g_input.grabAction, selectPath[Side::LEFT]},
{g_input.grabAction, selectPath[Side::RIGHT]},
{g_input.poseAction, posePath[Side::LEFT]},
{g_input.poseAction, posePath[Side::RIGHT]},
{g_input.quitAction, menuClickPath[Side::LEFT]},
{g_input.quitAction, menuClickPath[Side::RIGHT]},
{g_input.vibrateAction, hapticPath[Side::LEFT]},
{g_input.vibrateAction, hapticPath[Side::RIGHT]}}};
XrInteractionProfileSuggestedBinding suggestedBindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
suggestedBindings.interactionProfile = khrSimpleInteractionProfilePath;
suggestedBindings.suggestedBindings = bindings.data();
suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size();
CHECK_XRCMD(xrSuggestInteractionProfileBindings(g_instance, &suggestedBindings));
}
// Suggest bindings for the Oculus Touch.
{
XrPath oculusTouchInteractionProfilePath;
CHECK_XRCMD(
xrStringToPath(g_instance, "/interaction_profiles/oculus/touch_controller", &oculusTouchInteractionProfilePath));
std::vector<XrActionSuggestedBinding> bindings{{{g_input.grabAction, squeezeValuePath[Side::LEFT]},
{g_input.grabAction, squeezeValuePath[Side::RIGHT]},
{g_input.poseAction, posePath[Side::LEFT]},
{g_input.poseAction, posePath[Side::RIGHT]},
{g_input.quitAction, menuClickPath[Side::LEFT]},
{g_input.vibrateAction, hapticPath[Side::LEFT]},
{g_input.vibrateAction, hapticPath[Side::RIGHT]}}};
XrInteractionProfileSuggestedBinding suggestedBindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
suggestedBindings.interactionProfile = oculusTouchInteractionProfilePath;
suggestedBindings.suggestedBindings = bindings.data();
suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size();
CHECK_XRCMD(xrSuggestInteractionProfileBindings(g_instance, &suggestedBindings));
}
// Suggest bindings for the Vive Controller.
{
XrPath viveControllerInteractionProfilePath;
CHECK_XRCMD(
xrStringToPath(g_instance, "/interaction_profiles/htc/vive_controller", &viveControllerInteractionProfilePath));
std::vector<XrActionSuggestedBinding> bindings{{{g_input.grabAction, triggerValuePath[Side::LEFT]},
{g_input.grabAction, triggerValuePath[Side::RIGHT]},
{g_input.poseAction, posePath[Side::LEFT]},
{g_input.poseAction, posePath[Side::RIGHT]},
{g_input.quitAction, menuClickPath[Side::LEFT]},
{g_input.quitAction, menuClickPath[Side::RIGHT]},
{g_input.vibrateAction, hapticPath[Side::LEFT]},
{g_input.vibrateAction, hapticPath[Side::RIGHT]}}};
XrInteractionProfileSuggestedBinding suggestedBindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
suggestedBindings.interactionProfile = viveControllerInteractionProfilePath;
suggestedBindings.suggestedBindings = bindings.data();
suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size();
CHECK_XRCMD(xrSuggestInteractionProfileBindings(g_instance, &suggestedBindings));
}
// Suggest bindings for the Valve Index Controller.
{
XrPath indexControllerInteractionProfilePath;
CHECK_XRCMD(
xrStringToPath(g_instance, "/interaction_profiles/valve/index_controller", &indexControllerInteractionProfilePath));
std::vector<XrActionSuggestedBinding> bindings{{{g_input.grabAction, squeezeForcePath[Side::LEFT]},
{g_input.grabAction, squeezeForcePath[Side::RIGHT]},
{g_input.poseAction, posePath[Side::LEFT]},
{g_input.poseAction, posePath[Side::RIGHT]},
{g_input.quitAction, bClickPath[Side::LEFT]},
{g_input.quitAction, bClickPath[Side::RIGHT]},
{g_input.vibrateAction, hapticPath[Side::LEFT]},
{g_input.vibrateAction, hapticPath[Side::RIGHT]}}};
XrInteractionProfileSuggestedBinding suggestedBindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
suggestedBindings.interactionProfile = indexControllerInteractionProfilePath;
suggestedBindings.suggestedBindings = bindings.data();
suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size();
CHECK_XRCMD(xrSuggestInteractionProfileBindings(g_instance, &suggestedBindings));
}
// Suggest bindings for the Microsoft Mixed Reality Motion Controller.
{
XrPath microsoftMixedRealityInteractionProfilePath;
CHECK_XRCMD(xrStringToPath(g_instance, "/interaction_profiles/microsoft/motion_controller",
µsoftMixedRealityInteractionProfilePath));
std::vector<XrActionSuggestedBinding> bindings{{{g_input.grabAction, squeezeClickPath[Side::LEFT]},
{g_input.grabAction, squeezeClickPath[Side::RIGHT]},
{g_input.poseAction, posePath[Side::LEFT]},
{g_input.poseAction, posePath[Side::RIGHT]},
{g_input.quitAction, menuClickPath[Side::LEFT]},
{g_input.quitAction, menuClickPath[Side::RIGHT]},
{g_input.vibrateAction, hapticPath[Side::LEFT]},
{g_input.vibrateAction, hapticPath[Side::RIGHT]}}};
XrInteractionProfileSuggestedBinding suggestedBindings{XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING};
suggestedBindings.interactionProfile = microsoftMixedRealityInteractionProfilePath;
suggestedBindings.suggestedBindings = bindings.data();
suggestedBindings.countSuggestedBindings = (uint32_t)bindings.size();
CHECK_XRCMD(xrSuggestInteractionProfileBindings(g_instance, &suggestedBindings));
}
XrActionSpaceCreateInfo actionSpaceInfo{XR_TYPE_ACTION_SPACE_CREATE_INFO};
actionSpaceInfo.action = g_input.poseAction;
actionSpaceInfo.poseInActionSpace.orientation.w = 1.f;
actionSpaceInfo.subactionPath = g_input.handSubactionPath[Side::LEFT];
CHECK_XRCMD(xrCreateActionSpace(g_session, &actionSpaceInfo, &g_input.handSpace[Side::LEFT]));
actionSpaceInfo.subactionPath = g_input.handSubactionPath[Side::RIGHT];
CHECK_XRCMD(xrCreateActionSpace(g_session, &actionSpaceInfo, &g_input.handSpace[Side::RIGHT]));
XrSessionActionSetsAttachInfo attachInfo{XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO};
attachInfo.countActionSets = 1;
attachInfo.actionSets = &g_input.actionSet;
CHECK_XRCMD(xrAttachSessionActionSets(g_session, &attachInfo));
}
void OpenXRCreateVisualizedSpaces() {
CHECK(g_session != XR_NULL_HANDLE);
/// @todo Change this to modify the spaces that have things drawn in them. They can all be removed
/// if you draw things in world space. Removing these will not remove the cubes drawn for the hands.
std::string visualizedSpaces[] = {"ViewFront", "Local", "Stage", "StageLeft", "StageRight", "StageLeftRotated",
"StageRightRotated"};
for (const auto& visualizedSpace : visualizedSpaces) {
XrReferenceSpaceCreateInfo referenceSpaceCreateInfo = GetXrReferenceSpaceCreateInfo(visualizedSpace);
XrSpace space;
XrResult res = xrCreateReferenceSpace(g_session, &referenceSpaceCreateInfo, &space);
if (XR_SUCCEEDED(res)) {
g_visualizedSpaces.push_back(space);
g_spaceNames[space] = visualizedSpace;
} else {
if (g_verbosity >= 0) {
std::cerr << "Failed to create reference space " << visualizedSpace << " with error " << res
<< std::endl;
}
}
}
}
void OpenXRInitializeSession()
{
CHECK(g_instance != XR_NULL_HANDLE);
CHECK(g_session == XR_NULL_HANDLE);
{
if (g_verbosity >= 2) std::cout << Fmt("Creating session...") << std::endl;
XrSessionCreateInfo createInfo{XR_TYPE_SESSION_CREATE_INFO};
createInfo.next = reinterpret_cast<const XrBaseInStructure*>(&g_graphicsBinding);
createInfo.systemId = g_systemId;
CHECK_XRCMD(xrCreateSession(g_instance, &createInfo, &g_session));
}
/// @todo Print the reference spaces.
OpenXRInitializeActions();
OpenXRCreateVisualizedSpaces();
{
XrReferenceSpaceCreateInfo referenceSpaceCreateInfo = GetXrReferenceSpaceCreateInfo(g_options.AppSpace);
CHECK_XRCMD(xrCreateReferenceSpace(g_session, &referenceSpaceCreateInfo, &g_appSpace));
}
}
static void OpenXRCreateSwapchains()
{
CHECK(g_session != XR_NULL_HANDLE);
CHECK(g_swapchains.empty());
CHECK(g_configViews.empty());
// Read graphics properties for preferred swapchain length and logging.
XrSystemProperties systemProperties{XR_TYPE_SYSTEM_PROPERTIES};
CHECK_XRCMD(xrGetSystemProperties(g_instance, g_systemId, &systemProperties));
// Log system properties.
if (g_verbosity >= 1) {
std::cout <<
Fmt("System Properties: Name=%s VendorId=%d", systemProperties.systemName, systemProperties.vendorId)
<< std::endl;
std::cout << Fmt("System Graphics Properties: MaxWidth=%d MaxHeight=%d MaxLayers=%d",
systemProperties.graphicsProperties.maxSwapchainImageWidth,
systemProperties.graphicsProperties.maxSwapchainImageHeight,
systemProperties.graphicsProperties.maxLayerCount)
<< std::endl;
std::cout << Fmt("System Tracking Properties: OrientationTracking=%s PositionTracking=%s",
systemProperties.trackingProperties.orientationTracking == XR_TRUE ? "True" : "False",
systemProperties.trackingProperties.positionTracking == XR_TRUE ? "True" : "False")
<< std::endl;
}
// Note: No other view configurations exist at the time this code was written. If this
// condition is not met, the project will need to be audited to see how support should be
// added.
CHECK_MSG(g_viewConfigType == XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, "Unsupported view configuration type");
// Query and cache view configuration views.
uint32_t viewCount;
CHECK_XRCMD(xrEnumerateViewConfigurationViews(g_instance, g_systemId, g_viewConfigType, 0, &viewCount, nullptr));
g_configViews.resize(viewCount, {XR_TYPE_VIEW_CONFIGURATION_VIEW});
CHECK_XRCMD(xrEnumerateViewConfigurationViews(g_instance, g_systemId, g_viewConfigType, viewCount, &viewCount,
g_configViews.data()));
// Create and cache view buffer for xrLocateViews later.
g_views.resize(viewCount, {XR_TYPE_VIEW});
// Create the swapchain and get the images.
if (viewCount > 0) {
// Select a swapchain format.
uint32_t swapchainFormatCount;
CHECK_XRCMD(xrEnumerateSwapchainFormats(g_session, 0, &swapchainFormatCount, nullptr));
std::vector<int64_t> swapchainFormats(swapchainFormatCount);
CHECK_XRCMD(xrEnumerateSwapchainFormats(g_session, (uint32_t)swapchainFormats.size(), &swapchainFormatCount,
swapchainFormats.data()));
CHECK(swapchainFormatCount == swapchainFormats.size());
g_colorSwapchainFormat = OpenGLSelectColorSwapchainFormat(swapchainFormats);
// Print swapchain formats and the selected one.
{
std::string swapchainFormatsString;
for (int64_t format : swapchainFormats) {
const bool selected = format == g_colorSwapchainFormat;
swapchainFormatsString += " ";
if (selected) {
swapchainFormatsString += "[";
}
swapchainFormatsString += std::to_string(format);
if (selected) {
swapchainFormatsString += "]";
}
}
if (g_verbosity >= 1) std::cout << Fmt("Swapchain Formats: %s", swapchainFormatsString.c_str()) << std::endl;
}
// Create a swapchain for each view.
for (uint32_t i = 0; i < viewCount; i++) {
const XrViewConfigurationView& vp = g_configViews[i];
if (g_verbosity >= 1) {
std::cout <<
Fmt("Creating swapchain for view %d with dimensions Width=%d Height=%d SampleCount=%d", i,
vp.recommendedImageRectWidth, vp.recommendedImageRectHeight, vp.recommendedSwapchainSampleCount)
<< std::endl;
}
// Create the swapchain.
XrSwapchainCreateInfo swapchainCreateInfo{XR_TYPE_SWAPCHAIN_CREATE_INFO};
swapchainCreateInfo.arraySize = 1;
swapchainCreateInfo.format = g_colorSwapchainFormat;
swapchainCreateInfo.width = vp.recommendedImageRectWidth;
swapchainCreateInfo.height = vp.recommendedImageRectHeight;
swapchainCreateInfo.mipCount = 1;
swapchainCreateInfo.faceCount = 1;
swapchainCreateInfo.sampleCount = vp.recommendedSwapchainSampleCount;
swapchainCreateInfo.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT;
Swapchain swapchain;
swapchain.width = swapchainCreateInfo.width;
swapchain.height = swapchainCreateInfo.height;
CHECK_XRCMD(xrCreateSwapchain(g_session, &swapchainCreateInfo, &swapchain.handle));
g_swapchains.push_back(swapchain);
uint32_t imageCount;
CHECK_XRCMD(xrEnumerateSwapchainImages(swapchain.handle, 0, &imageCount, nullptr));
// XXX This should really just return XrSwapchainImageBaseHeader*
std::vector<XrSwapchainImageBaseHeader*> swapchainImages =
OpenGLAllocateSwapchainImageStructs(imageCount, swapchainCreateInfo);
CHECK_XRCMD(xrEnumerateSwapchainImages(swapchain.handle, imageCount, &imageCount, swapchainImages[0]));
g_swapchainImages.insert(std::make_pair(swapchain.handle, std::move(swapchainImages)));
}
}
}
// Return event if one is available, otherwise return null.
static XrEventDataBaseHeader* OpenXRTryReadNextEvent() {
// It is sufficient to clear the just the XrEventDataBuffer header to
// XR_TYPE_EVENT_DATA_BUFFER
XrEventDataBaseHeader* baseHeader = reinterpret_cast<XrEventDataBaseHeader*>(&g_eventDataBuffer);
*baseHeader = {XR_TYPE_EVENT_DATA_BUFFER};
const XrResult xr = xrPollEvent(g_instance, &g_eventDataBuffer);
if (xr == XR_SUCCESS) {
if (baseHeader->type == XR_TYPE_EVENT_DATA_EVENTS_LOST) {
const XrEventDataEventsLost* const eventsLost = reinterpret_cast<const XrEventDataEventsLost*>(baseHeader);
if (g_verbosity > 0) std::cerr << Fmt("%d events lost", eventsLost) << std::endl;
}
return baseHeader;
}
if (xr == XR_EVENT_UNAVAILABLE) {
return nullptr;
}
THROW_XR(xr, "xrPollEvent");
}
static void OpenXRHandleSessionStateChangedEvent(const XrEventDataSessionStateChanged& stateChangedEvent, bool* exitRenderLoop,
bool* requestRestart) {
const XrSessionState oldState = g_sessionState;
g_sessionState = stateChangedEvent.state;
if (g_verbosity >= 1) {
std::cout << Fmt("XrEventDataSessionStateChanged: state %s->%s session=%lld time=%lld", to_string(oldState),
to_string(g_sessionState), stateChangedEvent.session, stateChangedEvent.time)
<< std::endl;
}
if ((stateChangedEvent.session != XR_NULL_HANDLE) && (stateChangedEvent.session != g_session)) {
std::cerr << "XrEventDataSessionStateChanged for unknown session" << std::endl;
return;
}
switch (g_sessionState) {
case XR_SESSION_STATE_READY: {
CHECK(g_session != XR_NULL_HANDLE);
XrSessionBeginInfo sessionBeginInfo{XR_TYPE_SESSION_BEGIN_INFO};
sessionBeginInfo.primaryViewConfigurationType = g_viewConfigType;
CHECK_XRCMD(xrBeginSession(g_session, &sessionBeginInfo));
g_sessionRunning = true;
break;
}
case XR_SESSION_STATE_STOPPING: {
CHECK(g_session != XR_NULL_HANDLE);
g_sessionRunning = false;
CHECK_XRCMD(xrEndSession(g_session))