Showing posts with label vector. Show all posts
Showing posts with label vector. Show all posts

Thursday, March 29, 2012

vector class in c++

This is the header file for my vector class its the simplest form of a vector class in c++ and i save it as a vec3.h file

class vector3

{
/*
vector class and method defnition goes here
*/
public:

double x, y, z;

// Constructor
vector3() : x(0.0), y(0.0),z(0.0){};
vector3(double a_x,double a_y,double a_z) : x(a_x), y(a_y),z(a_z){};

// Methods
double magnitude();
double dotProduct(vector3 d_v);
vector3 crossProduct(vector3 c_v);
vector3 normalize();
vector3 add(vector3 a_v);
vector3 sub(vector3 s_v);
vector3 mult(vector3 m_v);
};

Below in the cpp file for the class

#include
#include "vec3.h"

/*
Vector class methods
*/
double vector3::magnitude()
{
return (double)sqrt((x * x) + (y * y) + (z * z));
}

double vector3::dotProduct(vector3 d_v)
{
return (x * d_v.x + y * d_v.y + z * d_v.z);
}

vector3 vector3::crossProduct(vector3 c_v)
{
return vector3((y * c_v.z) - (z * c_v.y), (z * c_v.x) - (x * c_v.z), (x * c_v.y) - (y * c_v.x));
}

vector3 vector3::normalize()
{
double mag = (1.0 / magnitude());
double i = x * mag;
double j = y * mag;
double k = z * mag;
return vector3(i,j,k);
}

vector3 vector3::add(vector3 a_v)
{
return vector3(x+a_v.x, y+a_v.y, z+a_v.z);
}

vector3 vector3::sub(vector3 s_v)
{
return vector3(x-s_v.x,y-s_v.y,z-s_v.z);
}

vector3 vector3::mult(vector3 m_v)
{
return vector3 (x*m_v.x,y*m_v.y,z*m_v.z);
}

Friday, March 23, 2012

What is a Ray ?

To talk about ray let me first talk about a line, a line is a parametric equation based on a point and a vector. It will have a point P which is the point @ which line starts and a direction V which is a vector as shown in image.


A point on line can be represented as where t is a scalar

Point(t) = P + t * V


Varying t will give you points on the line, Now let’s see what is the difference between a line and a Ray, a line extends to both direction whereas a Ray has a origin and one direction @ which it travels. Also for a ray t must be a non-negative value.