fdbc00c44fafbc4d75697970dc1bb4f8ba124bfe
[carveJwlIkooP6JGAAIwe30JlM.git] / camera.h
1 #ifndef CAMERA_H
2 #define CAMERA_H
3
4 #include "skaterift.h"
5
6 typedef struct camera camera;
7 struct camera{
8 /* Input */
9 v3f angles;
10 v3f pos;
11 float fov, nearz, farz;
12
13 /* Output */
14 m4x3f transform,
15 transform_inverse;
16
17 struct camera_mtx{
18 m4x4f p,
19 v,
20 pv;
21 }
22 mtx,
23 mtx_prev;
24 };
25
26 static void camera_lerp_angles( v3f a, v3f b, float t, v3f d ){
27 d[0] = vg_alerpf( a[0], b[0], t );
28 d[1] = vg_lerpf( a[1], b[1], t );
29 d[2] = vg_lerpf( a[2], b[2], t );
30 }
31
32 /* lerp position, fov, and angles */
33 static void camera_lerp( camera *a, camera *b, float t, camera *d ){
34 v3_lerp( a->pos, b->pos, t, d->pos );
35 camera_lerp_angles( a->angles, b->angles, t, d->angles );
36 d->fov = vg_lerpf( a->fov, b->fov, t );
37 }
38
39 static void camera_copy( camera *a, camera *d ){
40 v3_copy( a->pos, d->pos );
41 v3_copy( a->angles, d->angles );
42 d->fov = a->fov;
43 }
44
45 static void m4x3_transform_camera( m4x3f m, camera *cam ){
46 m4x3_mulv( m, cam->pos, cam->pos );
47
48 v3f v0;
49 v3_angles_vector( cam->angles, v0 );
50 m3x3_mulv( m, v0, v0 );
51 v3_normalize( v0 );
52 v3_angles( v0, cam->angles );
53 }
54
55 /*
56 * 1) [angles, pos] -> transform
57 */
58 static void camera_update_transform( camera *cam )
59 {
60 v4f qyaw, qpitch, qcam;
61 q_axis_angle( qyaw, (v3f){ 0.0f, 1.0f, 0.0f }, -cam->angles[0] );
62 q_axis_angle( qpitch, (v3f){ 1.0f, 0.0f, 0.0f }, -cam->angles[1] );
63
64 q_mul( qyaw, qpitch, qcam );
65 q_m3x3( qcam, cam->transform );
66 v3_copy( cam->pos, cam->transform[3] );
67 }
68
69 /*
70 * 2) [transform] -> transform_inverse, view matrix
71 */
72 static void camera_update_view( camera *cam )
73 {
74 m4x4_copy( cam->mtx.v, cam->mtx_prev.v );
75 m4x3_invert_affine( cam->transform, cam->transform_inverse );
76 m4x3_expand( cam->transform_inverse, cam->mtx.v );
77 }
78
79 /*
80 * 3) [fov,nearz,farz] -> projection matrix
81 */
82 static void camera_update_projection( camera *cam )
83 {
84 m4x4_copy( cam->mtx.p, cam->mtx_prev.p );
85 m4x4_projection( cam->mtx.p, cam->fov,
86 (float)vg.window_x / (float)vg.window_y,
87 cam->nearz, cam->farz );
88 }
89
90 /*
91 * 4) [projection matrix, view matrix] -> previous pv, new pv
92 */
93 static void camera_finalize( camera *cam )
94 {
95 m4x4_copy( cam->mtx.pv, cam->mtx_prev.pv );
96 m4x4_mul( cam->mtx.p, cam->mtx.v, cam->mtx.pv );
97 }
98
99 #endif /* CAMERA_H */