Repository navigation
Expand file tree
/
Copy pathHelloOpenXRSession.cpp
More file actions
429 lines (369 loc) · 14.5 KB
/
Copy pathHelloOpenXRSession.cpp
File metadata and controls
429 lines (369 loc) · 14.5 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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @fb-only
#include <shell/renderSessions/HelloOpenXRSession.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <glm/detail/qualifier.hpp>
#include <IGLU/shaderCross/ShaderCross.h>
#include <IGLU/shaderCross/ShaderCrossUniformBuffer.h>
#include <shell/shared/renderSession/ShellParams.h>
#include <igl/Device.h>
#include <igl/NameHandle.h>
#include <igl/RenderCommandEncoder.h>
#include <igl/ShaderCreator.h>
namespace igl::shell {
namespace {
struct VertexPosUvw {
glm::vec3 position;
glm::vec3 uvw;
};
const float kHalf = 1.0f;
const VertexPosUvw kVertexData0[] = {
{.position = {-kHalf, kHalf, -kHalf}, .uvw = {0.0, 1.0, 0.0}},
{.position = {kHalf, kHalf, -kHalf}, .uvw = {1.0, 1.0, 0.0}},
{.position = {-kHalf, -kHalf, -kHalf}, .uvw = {0.0, 0.0, 0.0}},
{.position = {kHalf, -kHalf, -kHalf}, .uvw = {1.0, 0.0, 0.0}},
{.position = {kHalf, kHalf, kHalf}, .uvw = {1.0, 1.0, 1.0}},
{.position = {-kHalf, kHalf, kHalf}, .uvw = {0.0, 1.0, 1.0}},
{.position = {kHalf, -kHalf, kHalf}, .uvw = {1.0, 0.0, 1.0}},
{.position = {-kHalf, -kHalf, kHalf}, .uvw = {0.0, 0.0, 1.0}},
};
constexpr uint16_t kIndexData[] = {0, 1, 2, 1, 3, 2, 1, 4, 3, 4, 6, 3, 4, 5, 6, 5, 7, 6,
5, 0, 7, 0, 2, 7, 5, 4, 0, 4, 1, 0, 2, 3, 7, 3, 6, 7};
[[nodiscard]] const char* getVulkanFragmentShaderSource() {
return R"(#version 450
precision highp float;
precision highp sampler2D;
layout(location = 0) in vec3 uvw;
layout(location = 1) in vec3 color;
layout(set = 0, binding = 0) uniform sampler2D inputImage;
layout(location = 0) out vec4 fragmentColor;
void main() {
fragmentColor = texture(inputImage, uvw.xy) * vec4(color, 1.0);
})";
}
[[nodiscard]] std::string getVertexShaderProlog(bool stereoRendering) {
return stereoRendering ? R"(#version 450
#extension GL_OVR_multiview2 : require
layout(num_views = 2) in;
precision highp float;
#define VIEW_ID int(gl_ViewID_OVR)
)"
: R"(#version 450
precision highp float;
#define VIEW_ID perFrame.viewId
)";
}
[[nodiscard]] std::string getVulkanVertexShaderSource(bool stereoRendering) {
return getVertexShaderProlog(stereoRendering) + R"(
layout (set = 1, binding = 1, std140) uniform PerFrame {
mat4 modelMatrix;
mat4 viewProjectionMatrix[2];
float scaleZ;
int viewId;
} perFrame;
layout(location = 0) in vec3 position;
layout(location = 1) in vec3 uvw_in;
layout(location = 0) out vec3 uvw;
layout(location = 1) out vec3 color;
void main() {
mat4 mvpMatrix = perFrame.viewProjectionMatrix[VIEW_ID] * perFrame.modelMatrix;
gl_Position = mvpMatrix * vec4(position, 1.0);
uvw = vec3(uvw_in.x, uvw_in.y, (uvw_in.z - 0.5) * perFrame.scaleZ + 0.5);
color = vec3(1.0, 1.0, 0.0);
})";
}
[[nodiscard]] std::unique_ptr<IShaderStages> getShaderStagesForBackend(
IDevice& device,
const iglu::ShaderCross& shaderCross,
bool stereoRendering) noexcept {
// NOLINTNEXTLINE(clang-diagnostic-switch-enum)
switch (device.getBackendType()) {
case igl::BackendType::Metal:
IGL_DEBUG_ABORT("Metal is not supported");
return nullptr;
// @fb-only
// @fb-only
// @fb-only
case igl::BackendType::Vulkan:
return igl::ShaderStagesCreator::fromModuleStringInput(
device,
getVulkanVertexShaderSource(stereoRendering).c_str(),
"main",
"",
getVulkanFragmentShaderSource(),
"main",
"",
nullptr);
case igl::BackendType::OpenGL: {
Result res;
const auto vs = shaderCross.crossCompileFromVulkanSource(
getVulkanVertexShaderSource(stereoRendering).c_str(), igl::ShaderStage::Vertex, &res);
IGL_DEBUG_ASSERT(res.isOk(), res.message.c_str());
const auto fs = shaderCross.crossCompileFromVulkanSource(
getVulkanFragmentShaderSource(), igl::ShaderStage::Fragment, &res);
IGL_DEBUG_ASSERT(res.isOk(), res.message.c_str());
return igl::ShaderStagesCreator::fromModuleStringInput(
device,
vs.c_str(),
shaderCross.entryPointName(igl::ShaderStage::Vertex),
"",
fs.c_str(),
shaderCross.entryPointName(igl::ShaderStage::Fragment),
"",
nullptr);
}
default:
IGL_DEBUG_ASSERT_NOT_REACHED();
return nullptr;
}
}
[[nodiscard]] bool isDeviceCompatible(IDevice& device) noexcept {
return device.hasFeature(DeviceFeatures::Multiview);
}
[[nodiscard]] glm::mat4 perspectiveAsymmetricFovRH(const Fov& fov,
float nearZ,
float farZ) noexcept {
glm::mat4 mat;
const float tanLeft = std::tan(fov.angleLeft);
const float tanRight = std::tan(fov.angleRight);
const float tanDown = std::tan(fov.angleDown);
const float tanUp = std::tan(fov.angleUp);
const float tanWidth = tanRight - tanLeft;
const float tanHeight = tanUp - tanDown;
mat[0][0] = 2.0f / tanWidth;
mat[1][0] = 0.0f;
mat[2][0] = (tanRight + tanLeft) / tanWidth;
mat[3][0] = 0.0f;
mat[0][1] = 0.0f;
mat[1][1] = 2.0f / tanHeight;
mat[2][1] = (tanUp + tanDown) / tanHeight;
mat[3][1] = 0.0f;
mat[0][2] = 0.0f;
mat[1][2] = 0.0f;
mat[2][2] = -(farZ + nearZ) / (farZ - nearZ);
mat[3][2] = -2.0f * farZ * nearZ / (farZ - nearZ);
mat[0][3] = 0.0f;
mat[1][3] = 0.0f;
mat[2][3] = -1.0f;
mat[3][3] = 0.0f;
return mat;
}
} // namespace
void HelloOpenXRSession::createSamplerAndTextures(const IDevice& device) {
// Sampler & Texture
samp0_ = device.createSamplerState(
SamplerStateDesc{
.minFilter = SamplerMinMagFilter::Linear,
.magFilter = SamplerMinMagFilter::Linear,
.addressModeU = SamplerAddressMode::MirrorRepeat,
.addressModeV = SamplerAddressMode::MirrorRepeat,
.addressModeW = SamplerAddressMode::MirrorRepeat,
},
nullptr);
tex0_ = getPlatform().loadTexture("macbeth.png");
}
// NOLINTNEXTLINE(bugprone-exception-escape)
void HelloOpenXRSession::initialize() noexcept {
auto& device = getPlatform().getDevice();
if (!isDeviceCompatible(device)) {
return;
}
// Vertex buffer, Index buffer and Vertex Input
const BufferDesc vb0Desc{.type = BufferDesc::BufferTypeBits::Vertex,
.data = kVertexData0,
.length = sizeof(kVertexData0)};
vb0_ = device.createBuffer(vb0Desc, nullptr);
const BufferDesc ibDesc{
.type = BufferDesc::BufferTypeBits::Index, .data = kIndexData, .length = sizeof(kIndexData)};
ib0_ = device.createBuffer(ibDesc, nullptr);
const VertexInputStateDesc inputDesc = {
.numAttributes = 2,
.attributes =
{
{.bufferIndex = 0,
.format = VertexAttributeFormat::Float3,
.offset = offsetof(VertexPosUvw, position),
.name = "position",
.location = 0},
{.bufferIndex = 0,
.format = VertexAttributeFormat::Float3,
.offset = offsetof(VertexPosUvw, uvw),
.name = "uvw_in",
.location = 1},
},
.numInputBindings = 1,
.inputBindings = {{.stride = sizeof(VertexPosUvw)}},
};
vertexInput0_ = device.createVertexInputState(inputDesc, nullptr);
const bool stereoRendering = shellParams().viewParams.size() > 1;
createSamplerAndTextures(device);
const iglu::ShaderCross shaderCross(device);
shaderStages_ = getShaderStagesForBackend(device, shaderCross, stereoRendering);
// Command queue: backed by different types of GPU HW queues
commandQueue_ = device.createCommandQueue({}, nullptr);
// Set up vertex uniform data
ub_.scaleZ = 1.0f;
renderPass_ = {
.colorAttachments =
{
{
.loadAction = LoadAction::Clear,
.storeAction = StoreAction::Store,
#if defined(IGL_OPENXR_MR_MODE)
.clearColor = {0.0, 0.0, 1.0, 0.0f},
#else
.clearColor = {0.0, 0.0, 1.0, 1.0f},
#endif
},
},
.depthAttachment = {.loadAction = LoadAction::Clear, .clearDepth = 1.0},
};
}
void HelloOpenXRSession::updateUniformBlock() {
// rotating animation
static float angle = 0.0f, scaleZ = 1.0f, ss = 0.005f;
angle += 0.005f;
scaleZ += ss;
scaleZ = scaleZ < 0.0f ? 0.0f : (scaleZ > 1.0 ? 1.0f : scaleZ);
if (scaleZ <= 0.05f || scaleZ >= 1.0f) {
ss *= -1.0f;
}
const glm::mat4 rotMat = glm::rotate(glm::mat4(1.0f), angle, glm::vec3(0.0f, 1.0f, 0.0f)) *
glm::rotate(glm::mat4(1.0f), -0.2f, glm::vec3(1.0f, 0.0f, 0.0f));
ub_.modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.f, -8.0f)) * rotMat *
glm::scale(glm::mat4(1.0f), glm::vec3(1.0f, 1.0f, scaleZ));
for (size_t i = 0; i < std::min(shellParams().viewParams.size(), static_cast<size_t>(2)); ++i) {
const auto viewIndex = shellParams().viewParams[i].viewIndex;
ub_.viewProjectionMatrix[viewIndex] =
perspectiveAsymmetricFovRH(shellParams().viewParams[i].fov, 0.1f, 100.0f) *
shellParams().viewParams[i].viewMatrix;
ub_.viewId = viewIndex;
}
ub_.scaleZ = scaleZ;
}
// NOLINTNEXTLINE(bugprone-exception-escape)
void HelloOpenXRSession::update(SurfaceTextures surfaceTextures) noexcept {
// Per IGL guidelines, surfaceTextures.color may be null on some platforms
// before the surface is ready (e.g., during window resize on Android/iOS).
if (!surfaceTextures.color) {
return;
}
auto& device = getPlatform().getDevice();
if (!isDeviceCompatible(device)) {
return;
}
updateUniformBlock();
IGL_DEBUG_ASSERT(!shellParams().viewParams.empty());
const auto viewIndex = shellParams().viewParams[0].viewIndex;
Result ret;
if (framebuffer_[viewIndex] == nullptr) {
const FramebufferMode mode = surfaceTextures.color->getNumLayers() > 1 ? FramebufferMode::Stereo
: FramebufferMode::Mono;
framebuffer_[viewIndex] = getPlatform().getDevice().createFramebuffer(
FramebufferDesc{
.colorAttachments = {{.texture = surfaceTextures.color}},
.depthAttachment = {.texture = surfaceTextures.depth},
.mode = mode,
},
&ret);
IGL_DEBUG_ASSERT(ret.isOk());
IGL_DEBUG_ASSERT(framebuffer_[viewIndex] != nullptr);
} else {
framebuffer_[viewIndex]->updateDrawable(surfaceTextures.color);
}
constexpr uint32_t textureUnit = 0;
if (pipelineState_ == nullptr) {
// Graphics pipeline: state batch that fully configures GPU for rendering
pipelineState_ = getPlatform().getDevice().createRenderPipeline(
RenderPipelineDesc{
.vertexInputState = vertexInput0_,
.shaderStages = shaderStages_,
.targetDesc =
{
.colorAttachments =
{
{
.textureFormat = framebuffer_[viewIndex]
->getColorAttachment(0)
->getProperties()
.format,
},
},
.depthAttachmentFormat =
framebuffer_[viewIndex]->getDepthAttachment()->getProperties().format,
},
.cullMode = igl::CullMode::Back,
.frontFaceWinding = igl::WindingMode::CounterClockwise,
.fragmentUnitSamplerMap = {{textureUnit, IGL_NAMEHANDLE("inputImage")}},
},
nullptr);
}
// Command buffers (1-N per thread): create, submit and forget
const auto buffer = commandQueue_->createCommandBuffer({}, nullptr);
const std::shared_ptr<IRenderCommandEncoder> commands =
buffer->createRenderCommandEncoder(renderPass_, framebuffer_[viewIndex]);
commands->pushDebugGroupLabel("HelloOpenXRSession Commands", Color(0.0f, 1.0f, 0.0f));
commands->bindVertexBuffer(0, *vb0_);
const iglu::ManagedUniformBufferInfo info = {
.index = 1,
.length = sizeof(UniformBlock),
.uniforms =
{
{
.name = "modelMatrix",
.location = -1,
.type = igl::UniformType::Mat4x4,
.numElements = 1,
.offset = offsetof(UniformBlock, modelMatrix),
.elementStride = 0,
},
{
.name = "viewProjectionMatrix",
.location = -1,
.type = igl::UniformType::Mat4x4,
.numElements = 2,
.offset = offsetof(UniformBlock, viewProjectionMatrix),
.elementStride = sizeof(glm::mat4),
},
{
.name = "scaleZ",
.location = -1,
.type = igl::UniformType::Float,
.numElements = 1,
.offset = offsetof(UniformBlock, scaleZ),
.elementStride = 0,
},
{
.name = "viewId",
.location = -1,
.type = igl::UniformType::Int,
.numElements = 1,
.offset = offsetof(UniformBlock, viewId),
.elementStride = 0,
},
},
};
const auto ubo = std::make_shared<iglu::ShaderCrossUniformBuffer>(device, "perFrame", info);
IGL_DEBUG_ASSERT(ubo->result.isOk());
*static_cast<UniformBlock*>(ubo->getData()) = ub_;
ubo->bind(device, *pipelineState_, *commands);
commands->bindTexture(textureUnit, BindTarget::kFragment, tex0_.get());
commands->bindSamplerState(textureUnit, BindTarget::kFragment, samp0_.get());
commands->bindRenderPipelineState(pipelineState_);
commands->bindIndexBuffer(*ib0_, IndexFormat::UInt16);
commands->drawIndexed(static_cast<size_t>(3u * 6u * 2u));
commands->popDebugGroupLabel();
commands->endEncoding();
if (shellParams().shouldPresent) {
buffer->present(framebuffer_[viewIndex]->getColorAttachment(0));
}
commandQueue_->submit(*buffer); // Guarantees ordering between command buffers
}
} // namespace igl::shell