forked from jakogut/tinyflock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.c
146 lines (116 loc) · 2.23 KB
/
vector.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include "config.h"
#include <stdlib.h>
#include "vector.h"
vector* create_vector(float x, float y, float z)
{
vector* v = malloc(sizeof(vector));
v->x = x;
v->y = y;
v->z = z;
return v;
}
vector* create_randomized_vector(float min, float max)
{
vector* v = malloc(sizeof(vector));
float range = max - min;
v->x = (rand() / (float)RAND_MAX) * range;
v->x += min;
v->y = (rand() / (float)RAND_MAX) * range;
v->y += min;
v->z = (rand() / (float)RAND_MAX) * range;
v->z += min;
return v;
}
vector* copy_vector(vector* init)
{
vector* v = malloc(sizeof(vector));
v->x = init->x;
v->y = init->y;
v->z = init->z;
return v;
}
void destroy_vector(vector* v)
{
free(v);
}
void vector_init(vector* v, int init)
{
v->x = init;
v->y = init;
v->z = init;
}
void vector_add(vector* a, vector* b)
{
a->x += b->x;
a->y += b->y;
a->z += b->z;
}
void vector_sub(vector* a, vector* b)
{
a->x -= b->x;
a->y -= b->y;
a->z -= b->z;
}
void vector_mul(vector* a, vector* b)
{
a->x *= b->x;
a->y *= b->y;
a->z *= b->z;
}
void vector_mul_scalar(vector* a, float b)
{
a->x *= b;
a->y *= b;
a->z *= b;
}
void vector_div(vector* a, vector* b)
{
a->x /= b->x;
a->y /= b->y;
a->z /= b->z;
}
void vector_div_scalar(vector* v, float divisor)
{
v->x /= divisor;
v->y /= divisor;
v->z /= divisor;
}
float vector_distance(vector* a, vector* b)
{
register float xd = b->x - a->x;
register float yd = b->y - a->y;
register float zd = b->z - a->z;
return sqrt(xd * xd + yd * yd + zd * zd);
}
float vector_magnitude(vector* v)
{
return sqrt((v->x * v->x) + (v->y * v->y) + (v->z * v->z));
}
void vector_normalize(vector* v)
{
float magnitude = vector_magnitude(v);
if(magnitude > 0)
{
v->x /= magnitude;
v->y /= magnitude;
v->z /= magnitude;
}
}
void vector_clamp(vector* v, vector* min, vector* max)
{
if(v->x < min->x) v->x = min->x;
if(v->y < min->y) v->y = min->y;
if(v->z < min->z) v->z = min->z;
if(v->x > max->x) v->x = max->x;
if(v->y > max->y) v->y = max->y;
if(v->z > max->z) v->z = max->z;
}
void vector_clamp_scalar(vector* v, float min, float max)
{
if(v->x < min) v->x = min;
if(v->y < min) v->y = min;
if(v->z < min) v->z = min;
if(v->x > max) v->x = max;
if(v->y > max) v->y = max;
if(v->z > max) v->z = max;
}