3 This file is part of libmspgl
4 Copyright © 2010 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
25 void Camera::set_field_of_view(float f)
30 void Camera::set_aspect(float a)
35 void Camera::set_depth_clip(float n, float f)
41 void Camera::set_position(const Vector3 &p)
47 void Camera::set_up_direction(const Vector3 &u)
49 float len = sqrt(u.x*u.x+u.y*u.y+u.z*u.z);
58 void Camera::set_look_direction(const Vector3 &l)
60 float len = sqrt(l.x*l.x+l.y*l.y+l.z*l.z);
69 void Camera::look_at(const Vector3 &p)
71 set_look_direction(Vector3(p.x-position.x, p.y-position.y, p.z-position.z));
74 Vector3 Camera::project(const Vector4 &p) const
76 float frustum_h = tan(fov/2);
77 float frustum_w = frustum_h*aspect;
78 float z_range = clip_far-clip_near;
80 float eye_x = matrix[0]*p.x+matrix[4]*p.y+matrix[8]*p.z+matrix[12]*p.w;
81 float eye_y = matrix[1]*p.x+matrix[5]*p.y+matrix[9]*p.z+matrix[13]*p.w;
82 float eye_z = matrix[2]*p.x+matrix[6]*p.y+matrix[10]*p.z+matrix[14]*p.w;
84 return Vector3(eye_x/frustum_w/-eye_z, eye_y/frustum_h/-eye_z,
85 (clip_far+clip_near)/z_range+2*clip_far*clip_near/(eye_z*z_range));
88 Vector4 Camera::unproject(const Vector4 &p) const
90 float frustum_h = tan(fov/2);
91 float frustum_w = frustum_h*aspect;
92 float z_range = clip_far-clip_near;
94 float z = (2*clip_far*clip_near)/(p.z*z_range-(clip_far+clip_near))-matrix[14]*p.w;
95 float x = p.x*-z*frustum_w-matrix[12]*p.w;
96 float y = p.y*-z*frustum_h-matrix[13]*p.w;
98 return Vector4(matrix[0]*x+matrix[1]*y+matrix[2]*z,
99 matrix[4]*x+matrix[5]*y+matrix[6]*z,
100 matrix[8]*x+matrix[9]*y+matrix[10]*z,
104 void Camera::apply() const
106 MatrixStack::projection() = Matrix::perspective(fov, aspect, clip_near, clip_far);
107 MatrixStack::modelview() = matrix;
110 void Camera::compute_matrix()
112 float x = look_dir.y*up_dir.z-look_dir.z*up_dir.y;
113 float y = look_dir.z*up_dir.x-look_dir.x*up_dir.z;
114 float z = look_dir.x*up_dir.y-look_dir.y*up_dir.x;
115 float len = sqrt(x*x+y*y+z*z);
122 mdata[1] = mdata[4]*look_dir.z-mdata[8]*look_dir.y;
123 mdata[5] = mdata[8]*look_dir.x-mdata[0]*look_dir.z;
124 mdata[9] = mdata[0]*look_dir.y-mdata[4]*look_dir.x;
126 mdata[2] = -look_dir.x;
127 mdata[6] = -look_dir.y;
128 mdata[10] = -look_dir.z;
130 mdata[12] = -position.x*mdata[0]-position.y*mdata[4]-position.z*mdata[8];
131 mdata[13] = -position.x*mdata[1]-position.y*mdata[5]-position.z*mdata[9];
132 mdata[14] = -position.x*mdata[2]-position.y*mdata[6]-position.z*mdata[10];