Add normalize_vector() function

This commit is contained in:
hasufell 2014-05-10 18:35:22 +02:00
parent 1df3195f37
commit 8f8f5ad0a2
No known key found for this signature in database
GPG Key ID: 220CD1C5BDEED020
2 changed files with 35 additions and 0 deletions

View File

@ -20,6 +20,9 @@
#include "types.h"
#include "vec_math.h"
#include <errno.h>
#include <fenv.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>
@ -51,6 +54,37 @@ bool vector_product(vector *a, vector *b, vector *c)
return true;
}
/**
* Normalize a vector into a unit vector
* of length 1. This function is aliasing safe.
*
* @param a vector
* @param b vector
* @return true/false for success/failure
*/
bool normalize_vector(vector *a, vector *b)
{
if (!a || !b)
return false;
vector a_tmp;
float vector_length;
copy_vector(a, &a_tmp);
vector_length = sqrt((a_tmp.x * a_tmp.x) +
(a_tmp.y * a_tmp.y) + (a_tmp.z * a_tmp.z));
if (errno == EDOM)
return false;
b->x = a_tmp.x / vector_length;
b->y = a_tmp.y / vector_length;
b->z = a_tmp.z / vector_length;
return true;
}
/**
* Copy coordinates from vector a to vector b.
*

View File

@ -26,6 +26,7 @@
bool vector_product(vector *a, vector *b, vector *c);
bool normalize_vector(vector *a, vector *b);
bool copy_vector(vector *a, vector *b);