GenericCamera.cc 17.2 KB
Newer Older
1
2
3
4
5
6
7
/***********************************************************************
 * Copyright 2011-2013 Computer Graphics Group RWTH Aachen University. *
 * All rights reserved.                                                *
 * Distributed under the terms of the MIT License (see LICENSE.TXT).   *
 **********************************************************************/

#include <ACGL/Scene/GenericCamera.hh>
8
#include <ACGL/Utils/StringHelpers.hh>
9
10
11
12
13
14
15
16
17
18
19

#include <cassert>

#include <ACGL/Math/Math.hh>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/euler_angles.hpp>

using namespace ACGL;
using namespace ACGL::Math::Functions;
using namespace ACGL::Scene;
20
using namespace ACGL::Utils::StringHelpers;
21
22
23
24
25
26
27
28
29
using namespace std;

GenericCamera::GenericCamera() :
    mPosition(),
    mProjectionMode(PERSPECTIVE_PROJECTION),
    mStereoMode(MONO),
    mCurrentEye(EYE_LEFT),
    mHorizontalFieldOfView(75.0),
    mAspectRatio( 4.0/3.0 ),
30
    mInterpupillaryDistance( 0.064 ), // 0.064 m = 6.4 cm - mean human eye distance: 6.47cm (male), 6.23cm (female)
31
32
33
34
35
36
37
    mNearClippingPlane(0.1),     // 10 cm
    mFarClippingPlane(5000.0),   // 5000 meter
    mLookAtDistance(500.0)       // half a kilometer away of the screen
{
    setRotationMatrix( glm::mat3(1.0f) );
}

38
39
40
41
42
GenericCamera::GenericCamera( const std::string &_state )
{
    setStateFromString( _state );
}

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
void GenericCamera::FPSstyleLookAround( float _deltaX, float _deltaY )
{
    float yaw   = 0.0f;
    float pitch = 0.0f;
    glm::mat3 R = getRotationMatrix3();

    // get roll / pitch / yaw from the current rotation matrix:
    float yaw1 = asin(-R[2][0]);
    float yaw2 = M_PI - asin(-R[2][0]);

    float pitch1  = (cos(yaw1) > 0)? atan2(R[2][1], R[2][2]): atan2(-R[2][1], -R[2][2]);
    float pitch2  = (cos(yaw2) > 0)? atan2(R[2][1], R[2][2]): atan2(-R[2][1], -R[2][2]);

    float roll1   = (cos(yaw1) > 0)? atan2(R[1][0], R[0][0]): atan2(-R[1][0], -R[0][0]);
    float roll2   = (cos(yaw2) > 0)? atan2(R[1][0], R[0][0]): atan2(-R[1][0], -R[0][0]);

    // we assume no roll at all, in that case one of the roll variants will be 0.0
    // if not, use the smaller one -> minimize the camera "jump" as this will destroy
    // information
    if ( std::abs(roll1) <= std::abs(roll2) ) {
        yaw   = -yaw1;
        pitch = -pitch1;
    } else {
        yaw   = -yaw2;
        pitch = -pitch2;
    }

    // add rotation diffs given:
    yaw = yaw + _deltaX;
    pitch = glm::clamp( pitch + _deltaY, -0.5f * (float)M_PI, 0.5f*(float)M_PI );

    // create rotation matices, seperated so we have full control over the order:
    glm::mat4 newRotY = glm::yawPitchRoll( yaw, 0.0f, 0.0f );
    glm::mat4 newRotX = glm::yawPitchRoll( 0.0f, pitch, 0.0f );

    // multiplication order is important to prevent roll:
    setRotationMatrix( newRotX * newRotY );
}

void GenericCamera::setRotationMatrix(glm::mat3 _matrix)
{
    mRotationMatrix = _matrix;
    assert(isOrthonormalMatrix(mRotationMatrix));
}

void GenericCamera::setRotationMatrix(glm::mat4 _matrix)
{
    mRotationMatrix = glm::mat3(_matrix);
    assert(isOrthonormalMatrix(mRotationMatrix));
}

void GenericCamera::setLookAtMatrix(const glm::vec3 &_position, const glm::vec3 &_target, const glm::vec3 &_up)
{
    setPosition(_position);
    setTarget(_target, _up);
}

glm::mat4 GenericCamera::getTranslationMatrix4() const
{
    glm::mat4 trans;
    trans[3][0] = -mPosition.x;
    trans[3][1] = -mPosition.y;
    trans[3][2] = -mPosition.z;
    return trans;
}

glm::vec3 GenericCamera::getUpDirection     () const
{
    glm::vec3 up(mRotationMatrix[0][1], mRotationMatrix[1][1], mRotationMatrix[2][1]);
    assert(glm::distance(getInverseRotationMatrix3() * glm::vec3(0.0f, 1.0f, 0.0f), up) < .01);
    return up;
}
glm::vec3 GenericCamera::getRightDirection  () const
{
    glm::vec3 right(mRotationMatrix[0][0], mRotationMatrix[1][0], mRotationMatrix[2][0]);
    assert(glm::distance(getInverseRotationMatrix3() * glm::vec3(1.0f, 0.0f, 0.0f), right) < .01);
    return right;
}
glm::vec3 GenericCamera::getForwardDirection() const
{
    glm::vec3 forward(-mRotationMatrix[0][2], -mRotationMatrix[1][2], -mRotationMatrix[2][2]);
    assert(glm::distance(getInverseRotationMatrix3() * glm::vec3(0.0f, 0.0f, -1.0f), forward) < .01);
    return forward;
}

void GenericCamera::setTarget(const glm::vec3 &_target, const glm::vec3 &_up)
{
    glm::vec3 forwardVector = _target - mPosition;
    mLookAtDistance = glm::length( forwardVector );

    forwardVector         = forwardVector / (float)mLookAtDistance; // normalize
    glm::vec3 rightVector = glm::normalize(glm::cross( forwardVector, _up ));
    glm::vec3 upVector    = glm::cross( rightVector, forwardVector );

    glm::mat3 rotMatrix;
    rotMatrix[0][0] =  rightVector.x;
    rotMatrix[0][1] =  upVector.x;
    rotMatrix[0][2] = -forwardVector.x;
    rotMatrix[1][0] =  rightVector.y;
    rotMatrix[1][1] =  upVector.y;
    rotMatrix[1][2] = -forwardVector.y;
    rotMatrix[2][0] =  rightVector.z;
    rotMatrix[2][1] =  upVector.z;
    rotMatrix[2][2] = -forwardVector.z;

    setRotationMatrix( rotMatrix );
}

Robert Menzel's avatar
Robert Menzel committed
151
void GenericCamera::setHorizontalFieldOfView(float _fovh)
152
153
154
155
156
157
{
    assert( _fovh < 180.0f );
    assert( _fovh > 0.0f );
    mHorizontalFieldOfView = _fovh;
}

Robert Menzel's avatar
Robert Menzel committed
158
void GenericCamera::setVerticalFieldOfView(float _fovv)
159
160
161
162
163
164
165
{
    assert( _fovv < 180.0f );
    assert( _fovv > 0.0f );
	
    // we only save the aspectRatio and the horizontal FoV
	// so if we change the vertical FoV, we change the aspectRatio
	
Robert Menzel's avatar
Robert Menzel committed
166
167
168
169
    //mAspectRatio = tan( calcDegToRad(0.5f * mHorizontalFieldOfView) ) / tan( calcDegToRad(0.5f * _fovv) );

    float x = tan( calcDegToRad(0.5f * _fovv) ) * mAspectRatio;
    mHorizontalFieldOfView = calcRadToDeg( 2.0f * atan( x ) );
170
171
}

Robert Menzel's avatar
Robert Menzel committed
172
float GenericCamera::getVerticalFieldOfView() const
173
174
175
176
{
    return calcRadToDeg( atan( tan( calcDegToRad(0.5f*mHorizontalFieldOfView) ) / mAspectRatio ) *2.0f );
}
	
Robert Menzel's avatar
Robert Menzel committed
177
void GenericCamera::setNearClippingPlane(float _plane)
178
{
Robert Menzel's avatar
Robert Menzel committed
179
    assert (_plane > 0.0f);
180
181
182
    mNearClippingPlane = _plane;
}

Robert Menzel's avatar
Robert Menzel committed
183
void GenericCamera::setFarClippingPlane(float _plane)
184
{
Robert Menzel's avatar
Robert Menzel committed
185
    assert (_plane > 0.0f);
186
187
188
    mFarClippingPlane = _plane;
}

Robert Menzel's avatar
Robert Menzel committed
189
void GenericCamera::setLookAtDistance(float _distance)
190
{
Robert Menzel's avatar
Robert Menzel committed
191
    assert (_distance > 0.0f);
192
193
194
    mLookAtDistance = _distance;
}

195
glm::mat4 GenericCamera::getViewMatrix() const
196
{
197
198
199
200
201
202
    if (mStereoMode == MONO) {
        return getMonoViewMatrix();
    } else {
        // all kinds of stereo
        bool eyeIsLeftEye = (getEye() == EYE_LEFT);
        return getStereoViewMatrix( eyeIsLeftEye, mStereoMode );
203
204
205
    }
}

206
glm::mat4 GenericCamera::getStereoViewMatrix( bool _leftEye, StereoMode _stereoMode ) const
207
{
208
209
210
211
    // The view matrix is independent of the projection mode (isometric or perspective)
    // so only the stereo mode has to be checked.
    assert( _stereoMode != MONO && "mono is not a stereo mode!" );

212
    float cameraPositionShiftValue = (mInterpupillaryDistance*0.5f); // shift to the right
213
214
215
216
217
218
219
220
    if (_leftEye) cameraPositionShiftValue *= -1.0f;      // if left eye shift to the left

    if ( (_stereoMode == PARALLEL_SHIFT) || (_stereoMode == OFF_AXIS) ) {
        //
        // parallel shift and off-axis have the same view matrices:
        // just shift the camera position to the left/right by half the eye-distance
        //

Robert Menzel's avatar
Robert Menzel committed
221
        //ACGL::Utils::debug() << "WARNING: getStereoViewMatrix() is not tested yet" << std::endl; // remove after testing
222
223
224
225
226
227
228
229
230

        glm::mat3 inverseRotation = getInverseRotationMatrix3();
        glm::vec3 eyePosition = mPosition + (inverseRotation * glm::vec3(cameraPositionShiftValue,0.0f,0.0f) );

        glm::mat4 m(mRotationMatrix);
        m[3][0] = -(m[0][0] * eyePosition.x + m[1][0] * eyePosition.y + m[2][0] * eyePosition.z);
        m[3][1] = -(m[0][1] * eyePosition.x + m[1][1] * eyePosition.y + m[2][1] * eyePosition.z);
        m[3][2] = -(m[0][2] * eyePosition.x + m[1][2] * eyePosition.y + m[2][2] * eyePosition.z);
        return m;
231
    }
232
233
234
235
236
237
238
239
240
241

    // else it has to be toe-in:
    assert( _stereoMode == TOE_IN && "unsupported stereo mode!" );
    //
    // Toe-in: shift the camera position to the left/right by half the eye-distance and
    //         rotate a bit inwards so that the two cameras focus the same point
    //         at the look-at distance (focal point)

    assert(0 && "getStereoViewMatrix() for TOE_IN is not implemented yet!");
    return glm::mat4();
242
243
244
245
}

glm::mat4 GenericCamera::getInverseViewMatrix() const
{
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
    if (mStereoMode == MONO) {
        return getMonoInverseViewMatrix();
    }

    glm::mat4 viewMatrix = getViewMatrix();
    return glm::inverse( viewMatrix );
}

glm::mat4 GenericCamera::getProjectionMatrix() const
{
    if (mStereoMode == MONO) {
        return getMonoProjectionMatrix();
    } else {
        // all kinds of stereo
        bool eyeIsLeftEye = (getEye() == EYE_LEFT);
        return getStereoProjectionMatrix( eyeIsLeftEye, mStereoMode );
262
263
264
265
266
267
268
269
270
271
272
    }
}

glm::mat4 GenericCamera::getMonoProjectionMatrix() const
{
    glm::mat4 projectionMatrix; // identity matrix

    if ( getProjectionMode() == ISOMETRIC_PROJECTION )
    {
        // we don't set the left/right/top/bottom values explicitly, so we want that
        // all object at our focal distance appear the same in perspective and isometric view
Robert Menzel's avatar
Robert Menzel committed
273
274
275
276
        float right  = tan( calcDegToRad(getHorizontalFieldOfView() * 0.5f) ) * mLookAtDistance;
        float left   = -right;
        float top    = tan( calcDegToRad(getVerticalFieldOfView() * 0.5f) ) * mLookAtDistance;
        float bottom = -top;
277
278
279
280
281
282
283
284
285
286
287
288
289
290

        // we do the same here as a glOrtho call would do.
        projectionMatrix[ 0][0] =  2.0f / (right - left);
        projectionMatrix[ 1][1] =  2.0f / (top   - bottom);
        projectionMatrix[ 2][2] = -2.0f / (mFarClippingPlane - mNearClippingPlane);
        projectionMatrix[ 0][3] = -(right+left) / (right-left);
        projectionMatrix[ 1][3] = -(top+bottom) / (top-bottom);
        projectionMatrix[ 2][3] = -(mFarClippingPlane+mNearClippingPlane)/(mFarClippingPlane-mNearClippingPlane);
        projectionMatrix[ 3][3] =  1.0;
    }
    else if ( mProjectionMode == PERSPECTIVE_PROJECTION )
    {
        projectionMatrix = glm::perspective( (float)getHorizontalFieldOfView(), (float)getAspectRatio(), (float)mNearClippingPlane, (float)mFarClippingPlane );
    }
Robert Menzel's avatar
Robert Menzel committed
291
    else assert(0 && "unsupported projection mode");
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314

    return projectionMatrix;
}

void GenericCamera::move( const glm::vec3 &_vector )
{
    glm::mat3 inverseRotation = getInverseRotationMatrix3();
    mPosition += (inverseRotation * _vector);
}

glm::mat4 GenericCamera::getMonoViewMatrix() const
{
    glm::mat4 m(mRotationMatrix);
    m[3][0] = -(m[0][0] * mPosition.x + m[1][0] * mPosition.y + m[2][0] * mPosition.z);
    m[3][1] = -(m[0][1] * mPosition.x + m[1][1] * mPosition.y + m[2][1] * mPosition.z);
    m[3][2] = -(m[0][2] * mPosition.x + m[1][2] * mPosition.y + m[2][2] * mPosition.z);
    assert( isApproxEqual( getRotationMatrix4() * getTranslationMatrix4(), m ) );
    return m;
}

glm::mat4 GenericCamera::getMonoInverseViewMatrix() const
{
    glm::mat4 m(glm::transpose(mRotationMatrix));
315
316
317
    m[3][0] = mPosition.x;
    m[3][1] = mPosition.y;
    m[3][2] = mPosition.z;
318
319
320
    assert( isApproxEqual( glm::inverse(getViewMatrix()), m ) );
    return m;
}
321
322

glm::mat4 GenericCamera::getStereoProjectionMatrix( bool _leftEye, StereoMode _stereoMode ) const
323
{
324
325
326
327
328
329
330
    assert( _stereoMode != MONO && "mono is not a stereo mode!" );

    if ( getProjectionMode() == ISOMETRIC_PROJECTION )
    {
        // very unusual, prepare for headaches!
        return getMonoProjectionMatrix();
    }
331

332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
    if ((_stereoMode == PARALLEL_SHIFT) || (_stereoMode == TOE_IN))
    {
        // the view matrix changes but the projection matrix stays the same
        return getMonoProjectionMatrix();
    }

    // so off-axis it is!
    assert( _stereoMode == OFF_AXIS && "unknown projection mode!" );
    //
    // In this mode the camera positions (view matrix) is shifted to the left/right still looking
    // straight ahead. The projection is also looking ahead but the projection center is
    // off (hence off-axis).
    // There is one plane in front of the cameras where the view-frusta match.
    // This should be the distance to the physical screen from the users position.


    assert(0 && "getStereoViewMatrix() is not implemented for OFF_AXIS yet!");
349
    return glm::mat4();
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
/// Writes all internal state to one string
/// Elements are seperated by pipes ('|'), spaces can get ignored.
std::string GenericCamera::storeStateToString() const
{
    std::string state;

    state  = "ACGL_GenericCamera | "; // "magic number", for every version the same
    state += "1 | "; // version, always an integer

    state += toString( mPosition ) + " | ";
    state += toString( mRotationMatrix ) + " | ";
    if ( mProjectionMode == ISOMETRIC_PROJECTION )   state += "ISOMETRIC_PROJECTION | ";
    if ( mProjectionMode == PERSPECTIVE_PROJECTION ) state += "PERSPECTIVE_PROJECTION | ";
    if ( mStereoMode     == MONO)                    state += "MONO | ";
    if ( mStereoMode     == PARALLEL_SHIFT)          state += "PARALLEL_SHIFT | ";
    if ( mStereoMode     == OFF_AXIS)                state += "OFF_AXIS | ";
    if ( mStereoMode     == TOE_IN)                  state += "TOE_IN | ";
    if ( mCurrentEye     == EYE_LEFT)                state += "EYE_LEFT | ";
    if ( mCurrentEye     == EYE_RIGHT)               state += "EYE_RIGHT | ";
    state += toString( mHorizontalFieldOfView ) + " | ";
    state += toString( mAspectRatio ) + " | ";
375
    state += toString( mInterpupillaryDistance ) + " | ";
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
    state += toString( mNearClippingPlane ) + " | ";
    state += toString( mFarClippingPlane ) + " | ";
    state += toString( mLookAtDistance ) + " | ";
    state += toString( mViewportSize );

    return state;
}

/// Sets all internal state from a string
void GenericCamera::setStateFromString( const std::string &_state )
{
    vector< string > token = split( _state, '|' );
    for (size_t i = 0; i < token.size(); i++) {
        token[i] = stripOfWhiteSpaces( token[i] );
    }
    if ((token.size() < 14) || (token[0] != "ACGL_GenericCamera")) {
        ACGL::Utils::error() << "Generic camera state string is invalid: " << _state << std::endl;
        return;
    }
    if ( to<int>(token[1]) != 1) {
        ACGL::Utils::error() << "Generic camera state version not supported: " << to<int>(token[1]) << std::endl;
        return;
    }

    int pos = 2;
    mPosition       = toVec3( token[pos++] );
    mRotationMatrix = toMat3( token[pos++] );
    if ( token[pos] == "ISOMETRIC_PROJECTION" )   mProjectionMode = ISOMETRIC_PROJECTION;
    if ( token[pos] == "PERSPECTIVE_PROJECTION" ) mProjectionMode = PERSPECTIVE_PROJECTION;
    pos++;
    if ( token[pos]     == "MONO")                mStereoMode = MONO;
    if ( token[pos]     == "PARALLEL_SHIFT")      mStereoMode = PARALLEL_SHIFT;
    if ( token[pos]     == "OFF_AXIS")            mStereoMode = OFF_AXIS;
    if ( token[pos]     == "TOE_IN")              mStereoMode = TOE_IN;
    pos++;
    if ( token[pos]     == "EYE_LEFT")            mCurrentEye = EYE_LEFT;
    if ( token[pos]     == "EYE_RIGHT")           mCurrentEye = EYE_RIGHT;
    pos++;

415
416
417
418
419
420
421
    mHorizontalFieldOfView  = to<float>( token[pos++] );
    mAspectRatio            = to<float>( token[pos++] );
    mInterpupillaryDistance = to<float>( token[pos++] );
    mNearClippingPlane      = to<float>( token[pos++] );
    mFarClippingPlane       = to<float>( token[pos++] );
    mLookAtDistance         = to<float>( token[pos++] );
    mViewportSize           = toUvec2( token[pos++] );
422
423
}

424
float GenericCamera::getFocalLenghtInPixel() const
425
{
426
    return ( (float) mViewportSize.x ) / ( 2.0f * tan( calcDegToRad(0.5f * mHorizontalFieldOfView) ) );
427
428
}

429
void GenericCamera::setFocalLengthInPixel( float _focalLengthInPixel )
430
{
431
432
433
434
    float hFoVrad = 2.0f * atan( ( 0.5f * mViewportSize.x ) * (1.0f / _focalLengthInPixel ) );
    setHorizontalFieldOfView( calcRadToDeg( hFoVrad ) );
}

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

/////////////// TESTS /////////////

#define DISABLE_TESTING
#ifndef DISABLE_TESTING
#include <gtest/gtest.h>

TEST(GenericCamera, SimpleTest)
{
    GenericCamera cam;

    cam.setNearClippingPlane(.33f);
    cam.setFarClippingPlane(3333.33f);
    cam.setLookAtMatrix(glm::vec3(0,0,-10), glm::vec3(0,0,10), glm::vec3(0,1,0));

    ASSERT_TRUE(isApproxEqual(cam.getLookAtDistance(), 20.0f));
    ASSERT_TRUE(isApproxEqual(cam.getPosition(), glm::vec3(0,0,-10)));
    ASSERT_TRUE(isApproxEqual(cam.getTarget(), glm::vec3(0,0,10)));

    ASSERT_TRUE(isApproxEqual(cam.getUpDirection(), glm::vec3(0,1,0)));
    ASSERT_TRUE(isApproxEqual(cam.getForwardDirection(), glm::vec3(0,0,1)));
    ASSERT_TRUE(isApproxEqual(cam.getRightDirection(), glm::cross(cam.getForwardDirection(), cam.getUpDirection())));

    ASSERT_TRUE(isApproxEqual(cam.getNearClippingPlane(), .33f));
    ASSERT_TRUE(isApproxEqual(cam.getFarClippingPlane(), 3333.33f));

    ASSERT_TRUE(isApproxEqual(cam.getViewMatrix(), glm::lookAt(glm::vec3(0,0,-10), glm::vec3(0,0,10), glm::vec3(0,1,0))));

    cam.moveForward(5.0f);
    ASSERT_TRUE(isApproxEqual(cam.getPosition(), glm::vec3(0,0,-5)));
    ASSERT_TRUE(isApproxEqual(cam.getTarget(), glm::vec3(0,0,15)));

    cam.moveUp(5.0f);
    ASSERT_TRUE(isApproxEqual(cam.getPosition(), glm::vec3(0,5,-5)));
    ASSERT_TRUE(isApproxEqual(cam.getTarget(), glm::vec3(0,5,15)));

    cam.moveLeft(5.0f);
    ASSERT_TRUE(isApproxEqual(cam.getPosition(), glm::vec3(5,5,-5)));
    ASSERT_TRUE(isApproxEqual(cam.getTarget(), glm::vec3(5,5,15)));
}

#endif