review save method
[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 VG_STATIC void camera_lerp_angles( v3f a, v3f b, float t, v3f d )
27 {
28 d[0] = vg_alerpf( a[0], b[0], t );
29 d[1] = vg_lerpf( a[1], b[1], t );
30 d[2] = vg_lerpf( a[2], b[2], t );
31 }
32
33 VG_STATIC void camera_lerp( camera *a, camera *b, float t, camera *d )
34 {
35 v3_lerp( a->pos, b->pos, t, d->pos );
36 d->angles[0] = vg_alerpf( a->angles[0], b->angles[0], t );
37 d->angles[1] = vg_lerpf( a->angles[1], b->angles[1], t );
38 d->angles[2] = vg_lerpf( a->angles[2], b->angles[2], t );
39 d->fov = vg_lerpf( a->fov, b->fov, t );
40 }
41
42 /*
43 * 1) [angles, pos] -> transform
44 */
45 VG_STATIC void camera_update_transform( camera *cam )
46 {
47 v4f qyaw, qpitch, qcam;
48 q_axis_angle( qyaw, (v3f){ 0.0f, 1.0f, 0.0f }, -cam->angles[0] );
49 q_axis_angle( qpitch, (v3f){ 1.0f, 0.0f, 0.0f }, -cam->angles[1] );
50
51 q_mul( qyaw, qpitch, qcam );
52 q_m3x3( qcam, cam->transform );
53 v3_copy( cam->pos, cam->transform[3] );
54 }
55
56 /*
57 * 2) [transform] -> transform_inverse, view matrix
58 */
59 VG_STATIC void camera_update_view( camera *cam )
60 {
61 m4x4_copy( cam->mtx.v, cam->mtx_prev.v );
62 m4x3_invert_affine( cam->transform, cam->transform_inverse );
63 m4x3_expand( cam->transform_inverse, cam->mtx.v );
64 }
65
66 /*
67 * 3) [fov,nearz,farz] -> projection matrix
68 */
69 VG_STATIC void camera_update_projection( camera *cam )
70 {
71 m4x4_copy( cam->mtx.p, cam->mtx_prev.p );
72 m4x4_projection( cam->mtx.p, cam->fov,
73 (float)vg.window_x / (float)vg.window_y,
74 cam->nearz, cam->farz );
75 }
76
77 /*
78 * 4) [projection matrix, view matrix] -> previous pv, new pv
79 */
80 VG_STATIC void camera_finalize( camera *cam )
81 {
82 m4x4_copy( cam->mtx.pv, cam->mtx_prev.pv );
83 m4x4_mul( cam->mtx.p, cam->mtx.v, cam->mtx.pv );
84 }
85
86 /*
87 * http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
88 */
89 VG_STATIC void m4x4_clip_projection( m4x4f mat, v4f plane )
90 {
91 v4f c =
92 {
93 (vg_signf(plane[0]) + mat[2][0]) / mat[0][0],
94 (vg_signf(plane[1]) + mat[2][1]) / mat[1][1],
95 -1.0f,
96 (1.0f + mat[2][2]) / mat[3][2]
97 };
98
99 v4_muls( plane, 2.0f / v4_dot(plane,c), c );
100
101 mat[0][2] = c[0];
102 mat[1][2] = c[1];
103 mat[2][2] = c[2] + 1.0f;
104 mat[3][2] = c[3];
105 }
106
107 /*
108 * Undoes the above operation
109 */
110 VG_STATIC void m4x4_reset_clipping( m4x4f mat, float ffar, float fnear )
111 {
112 mat[0][2] = 0.0f;
113 mat[1][2] = 0.0f;
114 mat[2][2] = -(ffar + fnear) / (ffar - fnear);
115 mat[3][2] = -2.0f * ffar * fnear / (ffar - fnear);
116 }
117
118 #endif /* CAMERA_H */