| 1 | // ============================================================================= |
| 2 | // Derived from openxr-simple-example |
| 3 | // Copyright 2019-2021, Collabora, Ltd. |
| 4 | // Which was adapted from |
| 5 | // https://github.com/KhronosGroup/OpenXR-SDK-Source/blob/master/src/common/xr_linear.h |
| 6 | // Copyright (c) 2017 The Khronos Group Inc. |
| 7 | // Copyright (c) 2016 Oculus VR, LLC. |
| 8 | // SPDX-License-Identifier: Apache-2.0 |
| 9 | // ============================================================================= |
| 10 | |
| 11 | #include "projection.h" |
| 12 | |
| 13 | void osgXR::createProjectionFov(osg::Matrix& result, |
| 14 | const XrFovf& fov, |
| 15 | const float nearZ, |
| 16 | const float farZ) |
| 17 | { |
| 18 | const float tanAngleLeft = tanf(fov.angleLeft); |
| 19 | const float tanAngleRight = tanf(fov.angleRight); |
| 20 | |
| 21 | const float tanAngleDown = tanf(fov.angleDown); |
| 22 | const float tanAngleUp = tanf(fov.angleUp); |
| 23 | |
| 24 | const float tanAngleWidth = tanAngleRight - tanAngleLeft; |
| 25 | |
| 26 | // Set to tanAngleDown - tanAngleUp for a clip space with positive Y |
| 27 | // down (Vulkan). Set to tanAngleUp - tanAngleDown for a clip space with |
| 28 | // positive Y up (OpenGL / D3D / Metal). |
| 29 | const float tanAngleHeight = tanAngleUp - tanAngleDown; |
| 30 | |
| 31 | // Set to nearZ for a [-1,1] Z clip space (OpenGL / OpenGL ES). |
| 32 | // Set to zero for a [0,1] Z clip space (Vulkan / D3D / Metal). |
| 33 | const float offsetZ = nearZ; |
| 34 | |
| 35 | if (farZ <= nearZ) |
| 36 | { |
| 37 | // place the far plane at infinity |
| 38 | result(0, 0) = 2 / tanAngleWidth; |
| 39 | result(1, 0) = 0; |
| 40 | result(2, 0) = (tanAngleRight + tanAngleLeft) / tanAngleWidth; |
| 41 | result(3, 0) = 0; |
| 42 | |
| 43 | result(0, 1) = 0; |
| 44 | result(1, 1) = 2 / tanAngleHeight; |
| 45 | result(2, 1) = (tanAngleUp + tanAngleDown) / tanAngleHeight; |
| 46 | result(3, 1) = 0; |
| 47 | |
| 48 | result(0, 2) = 0; |
| 49 | result(1, 2) = 0; |
| 50 | result(2, 2) = -1; |
| 51 | result(3, 2) = -(nearZ + offsetZ); |
| 52 | |
| 53 | result(0, 3) = 0; |
| 54 | result(1, 3) = 0; |
| 55 | result(2, 3) = -1; |
| 56 | result(3, 3) = 0; |
| 57 | } else { |
| 58 | // normal projection |
| 59 | result(0, 0) = 2 / tanAngleWidth; |
| 60 | result(1, 0) = 0; |
| 61 | result(2, 0) = (tanAngleRight + tanAngleLeft) / tanAngleWidth; |
| 62 | result(3, 0) = 0; |
| 63 | |
| 64 | result(0, 1) = 0; |
| 65 | result(1, 1) = 2 / tanAngleHeight; |
| 66 | result(2, 1) = (tanAngleUp + tanAngleDown) / tanAngleHeight; |
| 67 | result(3, 1) = 0; |
| 68 | |
| 69 | result(0, 2) = 0; |
| 70 | result(1, 2) = 0; |
| 71 | result(2, 2) = -(farZ + offsetZ) / (farZ - nearZ); |
| 72 | result(3, 2) = -(farZ * (nearZ + offsetZ)) / (farZ - nearZ); |
| 73 | |
| 74 | result(0, 3) = 0; |
| 75 | result(1, 3) = 0; |
| 76 | result(2, 3) = -1; |
| 77 | result(3, 3) = 0; |
| 78 | } |
| 79 | } |