/***************************************************************************
 *            vector.c
 *
 *  Thu Jan 27 02:23:51 2005
 *  Copyright  2005  Peter Baldwin
 *  pgbaldwi@uwaterloo.ca
 ****************************************************************************/

#include "vector.h"

#include <math.h>

//constants
vector VZERO  = {  0,  0 };

vector vAdd(vector v1, vector v2) {
	vector v = { v1.x+v2.x, v1.y+v2.y };
	return v;
}

vector vSubtract(vector v1, vector v2) {
	vector v = { v1.x-v2.x, v1.y-v2.y };
	return v;
}

double vDot(vector v1, vector v2) {
	return v1.x*v2.x + v1.y*v2.y;
}
double vMagnitude(vector v) {
	return sqrt(vDot(v,v));
}
// Returns a unit vector with the same direction
vector vUnit(vector v) {
	double length = vMagnitude(v);
	return length == 0 ? VZERO : vScale(v, 1/length);
}	
vector vScale(vector v, double factor) {
	vector result = { v.x*factor, v.y*factor };
	return result;
}

//scales the vector only in the direction of the normal
vector vScaleNormal(vector v, vector normal, double factor) {
	const vector v_normal = vScale(normal, vDot(v,normal));
	const vector v_perpendicular = vSubtract(v,v_normal);
	const vector result = vAdd(vScale(v_normal,factor),v_perpendicular);
	return result;
}

double vDistance(vector v1, vector v2) {
	//TODO why was this dot-product?
	return vMagnitude(vSubtract(v1,v2));
}

bool vEqual(vector v1, vector v2) {
	return v1.x == v2.x && v1.y == v2.y;
}

vector vNew(double x, double y) {
	vector v = {x, y};
	return v;
}
