demotool/camera.cc

81 lines
1.8 KiB
C++
Raw Normal View History

2017-10-02 10:12:27 +02:00
#include "externals.hh"
#include "camera.hh"
#include "c-utilities.hh"
2017-10-02 10:12:27 +02:00
#include <glm/gtc/matrix_access.hpp>
2017-10-02 10:12:27 +02:00
/*= T_Camera =================================================================*/
2017-11-19 23:47:26 +01:00
T_Camera::T_Camera( ) noexcept
{
cvtFov2Np( );
cvtAnglesToVectors( );
}
/*----------------------------------------------------------------------------*/
void T_Camera::camera(
glm::vec3 const& lookAt ,
glm::vec3 const& angles ,
const float distance ) noexcept
{
lookAt_ = lookAt;
angles_ = angles;
distance_ = distance;
cvtAnglesToVectors( );
}
void T_Camera::camera(
glm::vec3 const& lookAt ,
glm::vec3 const& position ,
glm::vec3 const& up ) noexcept
{
pos_ = position;
up_ = up;
lookAt_ = lookAt;
cvtVectorsToAngles( );
}
2017-11-19 23:47:26 +01:00
void T_Camera::cvtAnglesToVectors( ) noexcept
{
anglesToMatrix( &angles_.x , &rotMat_[ 0 ].x );
dir_ = glm::vec3( 0 , 0 , -distance_ ) * rotMat_;
up_ = glm::vec3( 0 , 1 , 0 ) * rotMat_;
pos_ = lookAt_ - dir_;
}
void T_Camera::cvtVectorsToAngles( ) noexcept
{
dir_ = lookAt_ - pos_;
const float distance{ length( dir_ ) };
if ( distance == 0 || length( up_ ) == 0 ) {
return;
}
distance_ = distance;
const glm::vec3 nDir{ - dir_ / distance_ };
const glm::vec3 nUp{ normalize( up_ ) };
if ( abs( dot( nUp , nDir ) ) == 1 ) {
return;
}
const glm::vec3 side{ normalize( cross( nUp , nDir ) ) };
const glm::vec3 up{ normalize( cross( nDir , side ) ) };
column( rotMat_ , 0 ) = side;
column( rotMat_ , 1 ) = up;
column( rotMat_ , 2 ) = nDir;
glm::vec3 nAngles;
nAngles.x = atan2f( nDir.y , nDir.z );
const float c2{ sqrtf( side.x * side.x + side.y * side.y ) };
nAngles.y = atan2f( -side.z , c2 );
const float s1{ sinf( nAngles.x ) } , c1{ cosf( nAngles.x ) };
nAngles.z = atan2f( s1 * nDir.x - c1 * up.x ,
c1 * up.y - s1 * nDir.y );
angles_ = nAngles * 180.f / float( M_PI );
2017-11-19 23:47:26 +01:00
}