graphics updates
[voxelands-alt.git] / src / lib / math_vector.c
blob782c36da71c23bde148ae82f8a98969f0153115c
1 /************************************************************************
2 * math_vector.c
3 * voxelands - 3d voxel world sandbox game
4 * Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 * See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>
18 ************************************************************************/
20 #include "common.h"
22 #include <math.h>
24 /* get a vector from start/end points */
25 void vect_create(v3_t *start, v3_t *end, v3_t *v)
27 v->x = end->x - start->x;
28 v->y = end->y - start->y;
29 v->z = end->z - start->z;
30 vect_normalise(v);
33 /* get the length of a vector */
34 float vect_length(v3_t *v)
36 return sqrtf(v->x*v->x + v->y*v->y + v->z*v->z);
39 /* normalise a vector */
40 void vect_normalise(v3_t *v)
42 float l;
43 l= vect_length(v);
44 if (l==0)
45 l = 1;
47 v->x/=l;
48 v->y/=l;
49 v->z/=l;
52 /* get the scalar product of vectors */
53 float vect_scalarproduct(v3_t *v1, v3_t *v2)
55 return (v1->x*v2->x + v1->y*v2->y + v1->z*v2->z);
58 /* get the cross product of vectors */
59 void vect_crossproduct(v3_t *v1, v3_t *v2, v3_t *v3)
61 v3->x=(v1->y*v2->z)-(v1->z*v2->y);
62 v3->y=(v1->z*v2->x)-(v1->x*v2->z);
63 v3->z=(v1->x*v2->y)-(v1->y*v2->x);
66 /* get the dot product of vectors */
67 void vect_dotproduct(v3_t *v1, v3_t *v2, v3_t *v3)
69 v3->x=(v1->y*v2->z)+(v1->z*v2->y);
70 v3->y=(v1->z*v2->x)+(v1->x*v2->z);
71 v3->z=(v1->x*v2->y)+(v1->y*v2->x);
74 /* subtract a vector from a vector */
75 void vect_subtract(v3_t *v1, v3_t *v2, v3_t *v3)
77 v3->x = (v1->x-v2->x);
78 v3->y = (v1->y-v2->y);
79 v3->z = (v1->z-v2->z);
82 /* get the diameter of a vector */
83 float vect_diameter(v3_t *v)
85 return sqrtf(vect_scalarproduct(v,v));
88 /* get the dot product of vectors */
89 float math_dotproduct(v3_t *v1, v3_t *v2)
91 return (v1->x*v2->x + v1->y*v2->y + v1->z*v2->z);
94 /* get the distance between two points */
95 float math_distance(v3_t *v1, v3_t *v2)
97 float xd = v2->x-v1->x;
98 float yd = v2->y-v1->y;
99 float zd = v2->z-v1->z;
101 if (xd < 0.0)
102 xd *= -1.0;
103 if (yd < 0.0)
104 yd *= -1.0;
105 if (zd < 0.0)
106 zd *= -1.0;
108 return sqrtf(xd*xd + yd*yd + zd*zd);