goat3d

view libs/vmath/quat_c.c @ 37:d259a5094390

trying to figure out how to properly call C functions from the python plugin
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 06 Oct 2013 17:42:43 +0300
parents
children
line source
1 /*
2 libvmath - a vector math library
3 Copyright (C) 2004-2011 John Tsiombikas <nuclear@member.fsf.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published
7 by the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
20 #include <stdio.h>
21 #include <math.h>
22 #include "quat.h"
24 void quat_print(FILE *fp, quat_t q)
25 {
26 fprintf(fp, "([ %.4f %.4f %.4f ] %.4f)", q.x, q.y, q.z, q.w);
27 }
29 quat_t quat_rotate(quat_t q, scalar_t angle, scalar_t x, scalar_t y, scalar_t z)
30 {
31 quat_t rq;
32 scalar_t half_angle = angle * 0.5;
33 scalar_t sin_half = sin(half_angle);
35 rq.w = cos(half_angle);
36 rq.x = x * sin_half;
37 rq.y = y * sin_half;
38 rq.z = z * sin_half;
40 return quat_mul(q, rq);
41 }
43 quat_t quat_rotate_quat(quat_t q, quat_t rotq)
44 {
45 return quat_mul(quat_mul(rotq, q), quat_conjugate(rotq));
46 }
48 quat_t quat_slerp(quat_t q1, quat_t q2, scalar_t t)
49 {
50 quat_t res;
51 scalar_t a, b, angle, sin_angle, dot;
53 dot = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z;
54 if(dot < 0.0) {
55 /* make sure we interpolate across the shortest arc */
56 q1.x = -q1.x;
57 q1.y = -q1.y;
58 q1.z = -q1.z;
59 q1.w = -q1.w;
60 dot = -dot;
61 }
63 /* clamp dot to [-1, 1] in order to avoid domain errors in acos due to
64 * floating point imprecisions
65 */
66 if(dot < -1.0) dot = -1.0;
67 if(dot > 1.0) dot = 1.0;
69 angle = acos(dot);
70 sin_angle = sin(angle);
72 if(fabs(sin_angle) < SMALL_NUMBER) {
73 /* for very small angles or completely opposite orientations
74 * use linear interpolation to avoid div/zero (in the first case it makes sense,
75 * the second case is pretty much undefined anyway I guess ...
76 */
77 a = 1.0f - t;
78 b = t;
79 } else {
80 a = sin((1.0f - t) * angle) / sin_angle;
81 b = sin(t * angle) / sin_angle;
82 }
84 res.x = q1.x * a + q2.x * b;
85 res.y = q1.y * a + q2.y * b;
86 res.z = q1.z * a + q2.z * b;
87 res.w = q1.w * a + q2.w * b;
88 return res;
89 }