add motion vectors to all shaders
[carveJwlIkooP6JGAAIwe30JlM.git] / camera.h
1 #ifndef CAMERA_H
2 #define CAMERA_H
3
4 #include "common.h"
5
6 typedef struct camera camera;
7
8 struct camera
9 {
10 /* Input */
11 v2f angles;
12 v3f pos;
13 float fov, nearz, farz;
14
15 /* Output */
16 m4x3f transform,
17 transform_inverse;
18
19 struct camera_mtx
20 {
21 m4x4f p,
22 v,
23 pv;
24 }
25 mtx,
26 mtx_prev;
27 }
28 VG_STATIC main_camera;
29
30 /*
31 * 1) [angles, pos] -> transform
32 */
33 VG_STATIC void camera_update_transform( camera *cam )
34 {
35 v4f qyaw, qpitch, qcam;
36 q_axis_angle( qyaw, (v3f){ 0.0f, 1.0f, 0.0f }, -cam->angles[0] );
37 q_axis_angle( qpitch, (v3f){ 1.0f, 0.0f, 0.0f }, -cam->angles[1] );
38
39 q_mul( qyaw, qpitch, qcam );
40 q_m3x3( qcam, cam->transform );
41 v3_copy( cam->pos, cam->transform[3] );
42 }
43
44 /*
45 * 2) [transform] -> transform_inverse, view matrix
46 */
47 VG_STATIC void camera_update_view( camera *cam )
48 {
49 m4x4_copy( cam->mtx.v, cam->mtx_prev.v );
50 m4x3_invert_affine( cam->transform, cam->transform_inverse );
51 m4x3_expand( cam->transform_inverse, cam->mtx.v );
52 }
53
54 /*
55 * 3) [fov,nearz,farz] -> projection matrix
56 */
57 VG_STATIC void camera_update_projection( camera *cam )
58 {
59 m4x4_copy( cam->mtx.p, cam->mtx_prev.p );
60 m4x4_projection( cam->mtx.p, cam->fov,
61 (float)vg.window_x / (float)vg.window_y,
62 cam->nearz, cam->farz );
63 }
64
65 /*
66 * 4) [projection matrix, view matrix] -> previous pv, new pv
67 */
68 VG_STATIC void camera_finalize( camera *cam )
69 {
70 m4x4_copy( cam->mtx.pv, cam->mtx_prev.pv );
71 m4x4_mul( cam->mtx.p, cam->mtx.v, cam->mtx.pv );
72 }
73
74 /*
75 * http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
76 */
77 VG_STATIC void m4x4_clip_projection( m4x4f mat, v4f plane )
78 {
79 v4f c =
80 {
81 (vg_signf(plane[0]) + mat[2][0]) / mat[0][0],
82 (vg_signf(plane[1]) + mat[2][1]) / mat[1][1],
83 -1.0f,
84 (1.0f + mat[2][2]) / mat[3][2]
85 };
86
87 v4_muls( plane, 2.0f / v4_dot(plane,c), c );
88
89 mat[0][2] = c[0];
90 mat[1][2] = c[1];
91 mat[2][2] = c[2] + 1.0f;
92 mat[3][2] = c[3];
93 }
94
95 /*
96 * Undoes the above operation
97 */
98 VG_STATIC void m4x4_reset_clipping( m4x4f mat, float ffar, float fnear )
99 {
100 mat[0][2] = 0.0f;
101 mat[1][2] = 0.0f;
102 mat[2][2] = -(ffar + fnear) / (ffar - fnear);
103 mat[3][2] = -2.0f * ffar * fnear / (ffar - fnear);
104 }
105
106 #endif /* CAMERA_H */