writing obj loader
[dosdemo] / src / vmath.h
1 #ifndef VMATH_H_
2 #define VMATH_H_
3
4 #include <math.h>
5
6 #ifdef __GNUC__
7 #define INLINE __inline
8
9 #elif defined(__WATCOMC__)
10 #define INLINE __inline
11
12 #else
13 #define INLINE
14 #endif
15
16 typedef struct { float x, y; } vec2_t;
17 typedef struct { float x, y, z; } vec3_t;
18 typedef struct { float x, y, z, w; } vec4_t;
19
20 typedef vec4_t quat_t;
21
22 /* vector functions */
23 static INLINE vec3_t v3_cons(float x, float y, float z)
24 {
25         vec3_t res;
26         res.x = x;
27         res.y = y;
28         res.z = z;
29         return res;
30 }
31
32 static INLINE float v3_dot(vec3_t v1, vec3_t v2)
33 {
34         return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
35 }
36
37 /* quaternion functions */
38 static INLINE quat_t quat_cons(float s, float x, float y, float z)
39 {
40         quat_t q;
41         q.x = x;
42         q.y = y;
43         q.z = z;
44         q.w = s;
45         return q;
46 }
47
48 static INLINE vec3_t quat_vec(quat_t q)
49 {
50         vec3_t v;
51         v.x = q.x;
52         v.y = q.y;
53         v.z = q.z;
54         return v;
55 }
56
57 static INLINE quat_t quat_mul(quat_t q1, quat_t q2)
58 {
59         quat_t res;
60         vec3_t v1 = quat_vec(q1);
61         vec3_t v2 = quat_vec(q2);
62
63         res.w = q1.w * q2.w - v3_dot(v1, v2);
64         res.x = v2.x * q1.w + v1.x * q2.w + (v1.y * v2.z - v1.z * v2.y);
65         res.y = v2.y * q1.w + v1.y * q2.w + (v1.z * v2.x - v1.x * v2.z);
66         res.z = v2.z * q1.w + v1.z * q2.w + (v1.x * v2.y - v1.y * v2.x);
67         return res;
68 }
69
70 static INLINE void quat_to_mat(float *res, quat_t q)
71 {
72         res[0] = 1.0f - 2.0f * q.y*q.y - 2.0f * q.z*q.z;
73         res[1] = 2.0f * q.x * q.y - 2.0f * q.w * q.z;
74         res[2] = 2.0f * q.z * q.x + 2.0f * q.w * q.y;
75         res[3] = 0.0f;
76         res[4] = 2.0f * q.x * q.y + 2.0f * q.w * q.z;
77         res[5] = 1.0f - 2.0f * q.x*q.x - 2.0f * q.z*q.z;
78         res[6] = 2.0f * q.y * q.z - 2.0f * q.w * q.x;
79         res[7] = 0.0f;
80         res[8] = 2.0f * q.z * q.x - 2.0f * q.w * q.y;
81         res[9] = 2.0f * q.y * q.z + 2.0f * q.w * q.x;
82         res[10] = 1.0f - 2.0f * q.x*q.x - 2.0f * q.y*q.y;
83         res[11] = 0.0f;
84         res[12] = res[13] = res[14] = 0.0f;
85         res[15] = 1.0f;
86 }
87
88 static INLINE quat_t quat_rotate(quat_t q, float angle, float x, float y, float z)
89 {
90         quat_t rq;
91         float half_angle = angle * 0.5;
92         float sin_half = sin(half_angle);
93
94         rq.w = cos(half_angle);
95         rq.x = x * sin_half;
96         rq.y = y * sin_half;
97         rq.z = z * sin_half;
98
99         return quat_mul(q, rq);
100 }
101
102 #endif  /* VMATH_H_ */