1/*
2 * Copyright (C) 2018 Igalia, S.L. All right reserved.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
13 *
14 * You should have received a copy of the GNU Library General Public License
15 * along with this library; see the file COPYING.LIB. If not, write to
16 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
18 *
19 */
20
21#include "config.h"
22#include "VRPlatformDisplayOpenVR.h"
23
24#if USE(OPENVR)
25
26#include <wtf/text/StringBuilder.h>
27
28namespace WebCore {
29
30uint32_t VRPlatformDisplayOpenVR::s_displayIdentifier = 0;
31
32VRPlatformDisplayOpenVR::VRPlatformDisplayOpenVR(vr::IVRSystem* system, vr::IVRChaperone* chaperone, vr::IVRCompositor* compositor)
33 : m_system(system)
34 , m_chaperone(chaperone)
35 , m_compositor(compositor)
36{
37 m_displayInfo.setDisplayIdentifier(++s_displayIdentifier);
38 m_displayInfo.setIsConnected(m_system->IsTrackedDeviceConnected(vr::k_unTrackedDeviceIndex_Hmd));
39
40 StringBuilder stringBuilder;
41 stringBuilder.appendLiteral("OpenVR HMD");
42 char HMDName[128];
43 if (auto length = m_system->GetStringTrackedDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_ManufacturerName_String, HMDName, 128)) {
44 stringBuilder.append(" (");
45 stringBuilder.append(HMDName, length);
46 stringBuilder.append(')');
47 }
48 m_displayInfo.setDisplayName(stringBuilder.toString());
49 m_displayInfo.setIsMounted(false);
50 // FIXME: We're assuming an HTC Vive HMD here. Get this info from OpenVR?.
51 m_displayInfo.setCapabilityFlags(VRDisplayCapabilityFlagNone | VRDisplayCapabilityFlagPosition | VRDisplayCapabilityFlagOrientation | VRDisplayCapabilityFlagExternalDisplay | VRDisplayCapabilityFlagPresent);
52
53 m_compositor->SetTrackingSpace(vr::TrackingUniverseSeated);
54
55 updateEyeParameters();
56 updateStageParameters();
57}
58
59VRPlatformDisplayInfo::FieldOfView VRPlatformDisplayOpenVR::computeFieldOfView(vr::Hmd_Eye eye)
60{
61 float left, right, top, bottom;
62 // OpenVR returns the tangents of the half-angles from the center view axis.
63 m_system->GetProjectionRaw(static_cast<vr::Hmd_Eye>(eye), &left, &right, &top, &bottom);
64 return { -rad2deg(atanf(top)), rad2deg(atanf(bottom)), -rad2deg(atanf(left)), rad2deg(atanf(right)) };
65}
66
67void VRPlatformDisplayOpenVR::updateEyeParameters()
68{
69 for (unsigned eye = 0; eye < VRPlatformDisplayInfo::NumEyes; ++eye) {
70 auto platformEye = static_cast<VRPlatformDisplayInfo::Eye>(eye);
71 m_displayInfo.setEyeFieldOfView(platformEye, computeFieldOfView(static_cast<vr::Hmd_Eye>(eye)));
72
73 vr::HmdMatrix34_t eyeToHead = m_system->GetEyeToHeadTransform(static_cast<vr::Hmd_Eye>(eye));
74 m_displayInfo.setEyeTranslation(platformEye, { eyeToHead.m[0][3], eyeToHead.m[1][3], eyeToHead.m[2][3] });
75 }
76
77 uint32_t width;
78 uint32_t height;
79 m_system->GetRecommendedRenderTargetSize(&width, &height);
80 m_displayInfo.setRenderSize({ width, height });
81}
82
83void VRPlatformDisplayOpenVR::updateStageParameters()
84{
85 float playAreaWidth = 1;
86 float playAreaDepth = 1;
87 if (!m_chaperone->GetPlayAreaSize(&playAreaWidth, &playAreaDepth)) {
88 // Fallback to sensible values, 1mx1m play area and 0.75m high seated position. We do as
89 // Firefox does.
90 TransformationMatrix matrix;
91 matrix.setM42(0.75);
92 m_displayInfo.setSittingToStandingTransform(WTFMove(matrix));
93 } else {
94 vr::HmdMatrix34_t transformMatrix = m_system->GetSeatedZeroPoseToStandingAbsoluteTrackingPose();
95 auto matrix = TransformationMatrix(transformMatrix.m[0][0], transformMatrix.m[1][0], transformMatrix.m[2][0], 0,
96 transformMatrix.m[0][1], transformMatrix.m[1][1], transformMatrix.m[2][1], 0,
97 transformMatrix.m[0][2], transformMatrix.m[1][2], transformMatrix.m[2][2], 0,
98 transformMatrix.m[0][3], transformMatrix.m[1][3], transformMatrix.m[2][3], 1);
99 m_displayInfo.setSittingToStandingTransform(WTFMove(matrix));
100 }
101 m_displayInfo.setPlayAreaBounds(FloatSize(playAreaWidth, playAreaDepth));
102}
103
104// FIXME: we might want to generalize this function for other backends.
105static VRPlatformTrackingInfo::Quaternion rotationMatrixToQuaternion(const float (&matrix)[3][4])
106{
107 // See https://d3cw3dd2w32x2b.cloudfront.net/wp-content/uploads/2015/01/matrix-to-quat.pdf.
108 VRPlatformTrackingInfo::Quaternion quaternion;
109 float trace;
110 if (matrix[2][2] < 0) {
111 if (matrix[0][0] > matrix[1][1]) {
112 trace = 1 + matrix[0][0] - matrix[1][1] - matrix[2][2];
113 quaternion = { trace, matrix[0][1]+matrix[1][0], matrix[2][0]+matrix[0][2], matrix[1][2] - matrix[2][1] };
114 } else {
115 trace = 1 - matrix[0][0] + matrix[1][1] - matrix[2][2];
116 quaternion = { matrix[0][1]+matrix[1][0], trace, matrix[1][2]+matrix[2][1], matrix[2][0] - matrix[0][2] };
117 }
118 } else {
119 if (matrix[0][0] < -matrix[1][1]) {
120 trace = 1 - matrix[0][0] - matrix[1][1] + matrix[2][2];
121 quaternion = { matrix[2][0]+matrix[0][2], matrix[1][2]+matrix[2][1], trace , matrix[0][1] - matrix[1][0] };
122 } else {
123 trace = 1 + matrix[0][0] + matrix[1][1] + matrix[2][2];
124 quaternion = { matrix[1][2] - matrix[2][1], matrix[2][0] - matrix[0][2], matrix[0][1] - matrix[1][0], trace };
125 }
126 }
127 return quaternion * (0.5 / sqrt(trace));
128}
129
130VRPlatformTrackingInfo VRPlatformDisplayOpenVR::getTrackingInfo()
131{
132 vr::TrackedDevicePose_t poses[vr::k_unMaxTrackedDeviceCount];
133
134 m_compositor->WaitGetPoses(nullptr, 0, poses, vr::k_unMaxTrackedDeviceCount);
135
136 m_trackingInfo.clear();
137
138 vr::Compositor_FrameTiming timing;
139 timing.m_nSize = sizeof(vr::Compositor_FrameTiming);
140 m_compositor->GetFrameTiming(&timing);
141 m_trackingInfo.timestamp = timing.m_flSystemTimeInSeconds;
142
143 if (!poses[vr::k_unTrackedDeviceIndex_Hmd].bDeviceIsConnected
144 || !poses[vr::k_unTrackedDeviceIndex_Hmd].bPoseIsValid
145 || poses[vr::k_unTrackedDeviceIndex_Hmd].eTrackingResult != vr::TrackingResult_Running_OK) {
146 // FIXME: Init some data maybe???.
147 return m_trackingInfo;
148 }
149
150 const auto& HMDPose = poses[vr::k_unTrackedDeviceIndex_Hmd];
151 const auto& transform = HMDPose.mDeviceToAbsoluteTracking;
152 m_trackingInfo.orientation = rotationMatrixToQuaternion(transform.m);
153 m_trackingInfo.orientation->conjugate();
154 m_trackingInfo.position = FloatPoint3D(transform.m[0][3], transform.m[1][3], transform.m[2][3]);
155 m_trackingInfo.angularVelocity = VRPlatformTrackingInfo::Float3(HMDPose.vAngularVelocity.v[0], HMDPose.vAngularVelocity.v[1], HMDPose.vAngularVelocity.v[2]);
156 m_trackingInfo.linearVelocity = VRPlatformTrackingInfo::Float3(HMDPose.vVelocity.v[0], HMDPose.vVelocity.v[1], HMDPose.vVelocity.v[2]);
157
158 return m_trackingInfo;
159}
160
161void VRPlatformDisplayOpenVR::updateDisplayInfo()
162{
163 if (!vr::VR_IsHmdPresent())
164 return;
165
166 vr::VREvent_t event;
167 while (m_system && m_system->PollNextEvent(&event, sizeof(event))) {
168 switch (event.eventType) {
169 case vr::VREvent_TrackedDeviceUserInteractionStarted:
170 case vr::VREvent_TrackedDeviceUserInteractionEnded:
171 if (event.trackedDeviceIndex == vr::k_unTrackedDeviceIndex_Hmd)
172 m_displayInfo.setIsMounted(event.eventType == vr::VREvent_TrackedDeviceUserInteractionStarted ? true : false);
173 break;
174 case vr::EVREventType::VREvent_TrackedDeviceActivated:
175 case vr::EVREventType::VREvent_TrackedDeviceDeactivated:
176 if (event.trackedDeviceIndex == vr::k_unTrackedDeviceIndex_Hmd)
177 m_displayInfo.setIsConnected(event.eventType == vr::VREvent_TrackedDeviceActivated ? true : false);
178 break;
179 case vr::EVREventType::VREvent_DriverRequestedQuit:
180 case vr::EVREventType::VREvent_Quit:
181 case vr::EVREventType::VREvent_ProcessQuit:
182 case vr::EVREventType::VREvent_QuitAcknowledged:
183 case vr::EVREventType::VREvent_QuitAborted_UserPrompt:
184 // FIXME: should we notify the platform manager about this and call VR_Shutdown().
185 default:
186 break;
187 }
188 }
189}
190
191}; // namespace WebCore
192
193#endif // USE(OPENVR)
194