aboutsummaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/Vision/Vision_Common.h
blob: 0610adbf01544d451f8305d0e925ff53bdbf87f0 (plain)
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
/************************************************************************************

Filename    :   OVR_Vision_Common.h
Content     :   Common data structures that are used in multiple vision files
Created     :   November 25, 2014
Authors     :   Max Katsev

Copyright   :   Copyright 2014 Oculus VR, LLC All Rights reserved.

Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.

You may obtain a copy of the License at

http://www.oculusvr.com/licenses/LICENSE-3.2

Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*************************************************************************************/

#ifndef OVR_Vision_Common_h
#define OVR_Vision_Common_h

#include "Kernel/OVR_RefCount.h"
#include "Extras/OVR_Math.h"
#include "Kernel/OVR_Array.h"
#include "Kernel/OVR_Log.h"
#include "Sensors/OVR_DeviceConstants.h"

// Compatible types (these are declared in global namespace)
typedef struct ovrPoseStatef_ ovrPoseStatef;
typedef struct ovrPoseStated_ ovrPoseStated;

namespace OVR { namespace Vision {
    
// Global "calibration mode" used by calibration tools to change
// the behavior of the SDK for calibration/experimentation purposes.
// This flag is set at system startup by calibration tools, and never changed.

extern int BundleCalibrationMode;

// Vision <-> OVR transform functions
//
// These transforms are required across the interface to many of the
// matching and reconstruction functions.
//
// OVR system is x+ right, y+ up, z+ back.
// Vision system is x+ right, y+ down, z+ forward.
// This is a 180 degree rotation about X axis.
//
template<typename T> inline Vector3<T> VisionFromOvr(const Vector3<T>& ovr)       { return Vector3<T>(ovr.x, -ovr.y, -ovr.z); }
template<typename T> inline Vector3<T> OvrFromVision(const Vector3<T>& vision)    { return Vector3<T>(vision.x, -vision.y, -vision.z); }
    
template<typename T> inline Quat<T> VisionFromOvr(const Quat<T>& ovr)       { return Quat<T>(ovr.x, -ovr.y, -ovr.z, ovr.w); }
template<typename T> inline Quat<T> OvrFromVision(const Quat<T>& vision)    { return Quat<T>(vision.x, -vision.y, -vision.z, vision.w); }

template<typename T> inline Pose<T> VisionFromOvr(const Pose<T>& ovr)       { return Pose<T>(VisionFromOvr(ovr.Rotation), VisionFromOvr(ovr.Translation)); }
template<typename T> inline Pose<T> OvrFromVision(const Pose<T>& vision)    { return Pose<T>(OvrFromVision(vision.Rotation), OvrFromVision(vision.Translation)); }

struct ImuSample
{
    double Time;

    Vector3d Accelerometer;
    Vector3d Gyro;
    Vector3d Magnetometer;
    double Temperature;

    ImuSample() : Time(-1), 
                  Temperature(-1) {}

    ImuSample(const SensorDataType& data) : Time(data.AbsoluteTimeSeconds),
                                            Accelerometer(data.Acceleration),
                                            Gyro(data.RotationRate),
                                            Magnetometer(data.MagneticField),
                                            Temperature(data.Temperature) {}
};

struct PoseSample
{
    double Time;
    Posed ThePose;
    Vector3d LinearVelocity, AngularVelocity;

    // stats for LED tracking
    int LedsCount;
    double ObjectSpaceError;
    // stats for sphere tracking
    int ContourCount;
    double CircleRadius;

    bool HasOrientation, HasPosition, HasVelocities;
    // true => ThePose == WorldFromImu, false => ThePose == CameraFromImu
    bool IsInWorldFrame;

    void ApplyWorldFromCamera(const Posed& worldFromCamera)
    {
        OVR_ASSERT(!IsInWorldFrame);

        IsInWorldFrame = true;
        ThePose = worldFromCamera * ThePose;
        if (HasVelocities)
        {
            LinearVelocity = worldFromCamera.Rotate(LinearVelocity);
            AngularVelocity = worldFromCamera.Rotate(AngularVelocity);
    }
    }

    friend PoseSample operator*(const PoseSample& sample, const Posed& trans)
    {
        PoseSample result = sample;
        result.ThePose = sample.ThePose * trans;
        // if we don't have orientation, the result will be useless - this is probably not expected to happen
        OVR_ASSERT(sample.HasOrientation); 
        result.HasPosition = sample.HasPosition && sample.HasOrientation;
        return result;
    }

    PoseSample(double time = -1) : Time(time),
                   LedsCount(-1),
                   ObjectSpaceError(-1),
                   ContourCount(-1),
                   CircleRadius(-1),
                   HasOrientation(false),
                   HasPosition(false),
                   HasVelocities(false),
                   IsInWorldFrame(false) {}
};

struct PoseEstimate
{
    Posed WorldFromImu, CameraFromWorld;

    bool HasPosition, HasOrientation, HasUp;

    Posed CameraFromImu() const
    {
        return CameraFromWorld * WorldFromImu;
    }

    friend PoseEstimate operator*(const PoseEstimate& estimate, const Posed& trans)
{
    PoseEstimate result = estimate;
    result.WorldFromImu = estimate.WorldFromImu * trans;
    // if we don't have orientation, the result will be useless - this is probably not expected to happen
    OVR_ASSERT(estimate.HasOrientation);
    result.HasPosition = estimate.HasPosition && estimate.HasOrientation;
    return result;
    }

    PoseEstimate(const Posed& worldFromCamera) :
        CameraFromWorld(worldFromCamera.Inverted()),
        HasPosition(false),
        HasOrientation(false),
        HasUp(false) {}
};

} // namespace OVR::Vision

// PoseState describes the complete pose, or a rigid body configuration, at a
// point in time, including first and second derivatives. It is used to specify
// instantaneous location and movement of the headset.
// SensorState is returned as a part of the sensor state.

template<class T>
class PoseState
{
public:
	typedef typename CompatibleTypes<Pose<T> >::Type CompatibleType;

	PoseState() : TimeInSeconds(0.0) { }

	// float <-> double conversion constructor.
	explicit PoseState(const PoseState<typename Math<T>::OtherFloatType> &src)
		: ThePose(src.ThePose),
		AngularVelocity(src.AngularVelocity), LinearVelocity(src.LinearVelocity),
		AngularAcceleration(src.AngularAcceleration), LinearAcceleration(src.LinearAcceleration),
		TimeInSeconds(src.TimeInSeconds)
	{ }

	// C-interop support: PoseStatef <-> ovrPoseStatef
	PoseState(const typename CompatibleTypes<PoseState<T> >::Type& src)
		: ThePose(src.ThePose),
		AngularVelocity(src.AngularVelocity), LinearVelocity(src.LinearVelocity),
		AngularAcceleration(src.AngularAcceleration), LinearAcceleration(src.LinearAcceleration),
		TimeInSeconds(src.TimeInSeconds)
	{ }

	operator typename CompatibleTypes<PoseState<T> >::Type() const
	{
		typename CompatibleTypes<PoseState<T> >::Type result;
		result.ThePose = ThePose;
		result.AngularVelocity = AngularVelocity;
		result.LinearVelocity = LinearVelocity;
		result.AngularAcceleration = AngularAcceleration;
		result.LinearAcceleration = LinearAcceleration;
		result.TimeInSeconds = TimeInSeconds;
		return result;
	}

	Pose<T> ThePose;
	Vector3<T>  AngularVelocity;
	Vector3<T>  LinearVelocity;
	Vector3<T>  AngularAcceleration;
	Vector3<T>  LinearAcceleration;
	// Absolute time of this state sample; always a double measured in seconds.
	double      TimeInSeconds;

	// ***** Helpers for Pose integration

    // Stores and integrates gyro angular velocity reading for a given time step.
    void StoreAndIntegrateGyro(Vector3d angVel, double dt)
    {
        AngularVelocity = angVel;
        ThePose.Rotation *= Quatd::FromRotationVector(angVel * dt);
    }

    void StoreAndIntegrateAccelerometer(Vector3d linearAccel, double dt)
    {
        LinearAcceleration = linearAccel;
        ThePose.Translation += LinearVelocity * dt + LinearAcceleration * (dt * dt * 0.5);
        LinearVelocity += LinearAcceleration * dt;
    }

    friend PoseState operator*(const Pose<T>& trans, const PoseState& poseState)
{
        PoseState result;
	result.ThePose             = trans * poseState.ThePose;
	result.LinearVelocity      = trans.Rotate(poseState.LinearVelocity);
	result.LinearAcceleration  = trans.Rotate(poseState.LinearAcceleration);
	result.AngularVelocity     = trans.Rotate(poseState.AngularVelocity);
	result.AngularAcceleration = trans.Rotate(poseState.AngularAcceleration);
	return result;
}
};

// External API returns pose as float, but uses doubles internally for quaternion precision.
typedef PoseState<float>  PoseStatef;
typedef PoseState<double> PoseStated;

// Compatible types
template<> struct CompatibleTypes<PoseState<float> > { typedef ovrPoseStatef Type; };
template<> struct CompatibleTypes<PoseState<double> > { typedef ovrPoseStated Type; };

// Handy debug output functions
template<typename T>
void Dump(const char* label, const Pose<T>& pose)
{
    auto t = pose.Translation * 1000;
    auto r = pose.Rotation.ToRotationVector();
    double angle = RadToDegree(r.Length());
    if (r.LengthSq() > 0)
        r.Normalize();
    LogText("%s: %.2f, %.2f, %.2f mm, %.2f deg %.2f, %.2f, %.2f\n",
            label, t.x, t.y, t.z, angle, r.x, r.y, r.z);
}

template<typename T>
void Dump(const char* label, const Vector3<T>& v)
{
    LogText("%s %.5g, %.5g, %.5g (%.5g)\n", label, v.x, v.y, v.z, v.Length());
}

template<typename T>
void Dump(const char* label, const Quat<T>& q)
{
    auto r = q.ToRotationVector();
    auto axis = r.Normalized();
    auto angle = RadToDegree(r.Length());
    LogText("%s %.2f (%.2f, %.2f, %.2f)\n", label, angle, axis.x, axis.y, axis.z);
}

template<typename T>
void Dump(const char* label, double time, const Pose<T>& p)
{
    LogText("%.4f: ", time);
    Dump(label, p);
}

static_assert((sizeof(PoseState<double>) == sizeof(Pose<double>) + 4 * sizeof(Vector3<double>) + sizeof(double)), "sizeof(PoseState<double>) failure");
#ifdef OVR_CPU_X86_64
static_assert((sizeof(PoseState<float>) == sizeof(Pose<float>) + 4 * sizeof(Vector3<float>) + sizeof(uint32_t)+sizeof(double)), "sizeof(PoseState<float>) failure"); //TODO: Manually pad template.
#elif defined(OVR_OS_WIN32) // The Windows 32 bit ABI aligns 64 bit values on 64 bit boundaries
static_assert((sizeof(PoseState<float>) == sizeof(Pose<float>) + 4 * sizeof(Vector3<float>) + sizeof(uint32_t)+sizeof(double)), "sizeof(PoseState<float>) failure");
#elif defined(OVR_CPU_ARM) // ARM aligns 64 bit values to 64 bit boundaries: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0472k/chr1359125009502.html
static_assert((sizeof(PoseState<float>) == sizeof(Pose<float>) + 4 * sizeof(Vector3<float>) + sizeof(uint32_t)+sizeof(double)), "sizeof(PoseState<float>) failure");
#else // Else Unix/Apple 32 bit ABI, which aligns 64 bit values on 32 bit boundaries.
static_assert((sizeof(PoseState<float>) == sizeof(Pose<float>) + 4 * sizeof(Vector3<float>) + sizeof(double)), "sizeof(PoseState<float>) failure:");
#endif

} // namespace OVR

#endif // OVR_Vision_Common_h