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