diff options
-rw-r--r-- | common/math_util.c | 27 | ||||
-rw-r--r-- | include/math_util.h | 18 |
2 files changed, 41 insertions, 4 deletions
diff --git a/common/math_util.c b/common/math_util.c index d0b5887199..22f5872267 100644 --- a/common/math_util.c +++ b/common/math_util.c @@ -135,6 +135,28 @@ int vector_magnitude(const intv3_t v) return int_sqrtf(sum); } +/* cross_product only works if the vectors magnitudes are around 1<<16. */ +void cross_product(const intv3_t v1, const intv3_t v2, intv3_t v) +{ + v[X] = (fp_inter_t)v1[Y] * v2[Z] - (fp_inter_t)v1[Z] * v2[Y]; + v[Y] = (fp_inter_t)v1[Z] * v2[X] - (fp_inter_t)v1[X] * v2[Z]; + v[Z] = (fp_inter_t)v1[X] * v2[Y] - (fp_inter_t)v1[Y] * v2[X]; +} + +fp_inter_t dot_product(const intv3_t v1, const intv3_t v2) +{ + return (fp_inter_t)v1[X] * v2[X] + + (fp_inter_t)v1[Y] * v2[Y] + + (fp_inter_t)v1[Z] * v2[Z]; +} + +void vector_scale(intv3_t v, fp_t s) +{ + v[X] = fp_mul(v[X], s); + v[Y] = fp_mul(v[Y], s); + v[Z] = fp_mul(v[Z], s); +} + fp_t cosine_of_angle_diff(const intv3_t v1, const intv3_t v2) { fp_inter_t dotproduct; @@ -144,10 +166,7 @@ fp_t cosine_of_angle_diff(const intv3_t v1, const intv3_t v2) * Angle between two vectors is acos(A dot B / |A|*|B|). To return * cosine of angle between vectors, then don't do acos operation. */ - - dotproduct = (fp_inter_t)v1[0] * v2[0] + - (fp_inter_t)v1[1] * v2[1] + - (fp_inter_t)v1[2] * v2[2]; + dotproduct = dot_product(v1, v2); denominator = (fp_inter_t)vector_magnitude(v1) * vector_magnitude(v2); diff --git a/include/math_util.h b/include/math_util.h index 1bcff13525..a536a0235a 100644 --- a/include/math_util.h +++ b/include/math_util.h @@ -122,6 +122,24 @@ enum { fp_t arc_cos(fp_t x); /** + * Calculate the dot product of 2 vectors. + */ +fp_inter_t dot_product(const intv3_t v1, const intv3_t v2); + +/* + * Calculate the dot product of 2 vectors, + * + * Assume the result vector components fits in 32bit. + */ +void cross_product(const intv3_t v1, const intv3_t v2, intv3_t v); + +/** + * Scale a vector by fixed point constant. + */ +void vector_scale(intv3_t v, fp_t s); + + +/** * Find the cosine of the angle between two vectors. * * The implementation assumes no vector component is greater than |