1 /* gph-cmath - C graphics math library
2 * Copyright (C) 2018 John Tsiombikas <nuclear@member.fsf.org>
4 * This program is free software. Feel free to use, modify, and/or redistribute
5 * it under the terms of the MIT/X11 license. See LICENSE for details.
6 * If you intend to redistribute parts of the code without the LICENSE file
7 * replace this paragraph with the full contents of the LICENSE file.
9 static CGM_INLINE void cgm_qcons(cgm_quat *q, float x, float y, float z, float w)
18 static CGM_INLINE void cgm_qneg(cgm_quat *q)
26 static CGM_INLINE void cgm_qadd(cgm_quat *a, const cgm_quat *b)
34 static CGM_INLINE void cgm_qsub(cgm_quat *a, const cgm_quat *b)
42 static CGM_INLINE void cgm_qmul(cgm_quat *a, const cgm_quat *b)
47 dot = a->x * b->x + a->y * b->y + a->z * b->z;
48 cgm_vcross(&cross, (cgm_vec3*)a, (cgm_vec3*)b);
50 x = a->w * b->x + b->w * a->x + cross.x;
51 y = a->w * b->y + b->w * a->y + cross.y;
52 z = a->w * b->z + b->w * a->z + cross.z;
53 a->w = a->w * b->w - dot;
59 static CGM_INLINE float cgm_qlength(const cgm_quat *q)
61 return sqrt(q->x * q->x + q->y * q->y + q->z * q->z + q->w * q->w);
64 static CGM_INLINE float cgm_qlength_sq(const cgm_quat *q)
66 return q->x * q->x + q->y * q->y + q->z * q->z + q->w * q->w;
69 static CGM_INLINE void cgm_qnormalize(cgm_quat *q)
71 float len = cgm_qlength(q);
81 static CGM_INLINE void cgm_qconjugate(cgm_quat *q)
88 static CGM_INLINE void cgm_qinvert(cgm_quat *q)
90 float len_sq = cgm_qlength_sq(q);
93 float s = 1.0f / len_sq;
101 static CGM_INLINE void cgm_qrotation(cgm_quat *q, float angle, float x, float y, float z)
103 float hangle = angle * 0.5f;
104 float sin_ha = sin(hangle);
111 static CGM_INLINE void cgm_qrotate(cgm_quat *q, float angle, float x, float y, float z)
114 cgm_qrotation(&qrot, angle, x, y, z);
118 static CGM_INLINE void cgm_qslerp(cgm_quat *res, const cgm_quat *quat1, const cgm_quat *q2, float t)
120 float angle, dot, a, b, sin_angle;
121 cgm_quat q1 = *quat1;
123 dot = quat1->x * q2->x + quat1->y * q2->y + quat1->z * q2->z + quat1->w * q2->w;
125 /* make sure we inteprolate across the shortest arc */
130 /* clamp dot to [-1, 1] in order to avoid domain errors in acos due to
131 * floating point imprecisions
133 if(dot < -1.0f) dot = -1.0f;
134 if(dot > 1.0f) dot = 1.0f;
137 sin_angle = sin(angle);
138 if(sin_angle == 0.0f) {
139 /* use linear interpolation to avoid div/zero */
143 a = sin((1.0f - t) * angle) / sin_angle;
144 b = sin(t * angle) / sin_angle;
147 res->x = q1.x * a + q2->x * b;
148 res->y = q1.y * a + q2->y * b;
149 res->z = q1.z * a + q2->z * b;
150 res->w = q1.w * a + q2->w * b;
153 static CGM_INLINE void cgm_qlerp(cgm_quat *res, const cgm_quat *a, const cgm_quat *b, float t)
155 res->x = a->x + (b->x - a->x) * t;
156 res->y = a->y + (b->y - a->y) * t;
157 res->z = a->z + (b->z - a->z) * t;
158 res->w = a->w + (b->w - a->w) * t;