include/vector.h
author Radek Brich <radek.brich@devl.cz>
Sat, 08 Dec 2007 16:02:37 +0100
branchpyrit
changeset 30 33f95441790e
parent 28 ffe83ca074f3
child 34 28f6e8b9d5d1
permissions -rw-r--r--
pyrit_verbosity: new variable for controlling amount of output, see common.h fix Makefile dependencies for raytracer_module fix bad view in buddha.py caused by last commit

/*
 * C++ RayTracer
 * file: vector.h
 *
 * Radek Brich, 2006
 */

#ifndef VECTOR_H
#define VECTOR_H

#include <math.h>
#include <iostream>

using namespace std;

class Vector3
{
public:
	// data
	union {
		struct {
			Float x, y, z;
		};
		struct {
			Float r, g, b;
		};
		Float cell[3];
	};

	// constructors
	Vector3(): x(0.0f), y(0.0f), z(0.0f) {};
	Vector3(Float ax, Float ay, Float az): x(ax), y(ay), z(az) {};

	// index operator
	const Float &operator[](int index) const { return cell[index]; };

	bool operator==(Vector3 &v) const { return x==v.x && y==v.y && z==v.z; };

	// normalize
	Vector3 normalize()
	{
		Float f = 1.0f / mag();
		x *= f;
		y *= f;
		z *= f;
		return *this;
	}

	// get normalized copy
	Vector3 unit() const
	{
		Vector3 u(*this);
		return u.normalize();;
	}

	// square magnitude, magnitude
	Float mag2() const	{ return x * x + y * y + z * z; }
	Float mag() const	{ return sqrtf(mag2()); }

	// negative
	Vector3 operator-() const { return Vector3(-x, -y, -z); }

	// accumulate
	Vector3 operator+=(const Vector3 &v)
	{
		x += v.x;
		y += v.y;
		z += v.z;
		return *this;
	};

	// cut
	Vector3 operator/=(const Float &f)
	{
		x /= f;
		y /= f;
		z /= f;
		return *this;
	};

	// sum
	friend Vector3 operator+(const Vector3 &a, const Vector3 &b)
	{
		return Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
	};

	// difference
	friend Vector3 operator-(const Vector3 &a, const Vector3 &b)
	{
		return Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
	};

	// dot product
	friend Float dot(const Vector3 &a, const Vector3 &b)
	{
		return a.x * b.x + a.y * b.y + a.z * b.z;
	};

	// cross product
	friend Vector3 cross(const Vector3 &a, const Vector3 &b)
	{
		return Vector3(a.y * b.z - a.z * b.y,
			a.z * b.x - a.x * b.z,
			a.x * b.y - a.y * b.x);
	};

	// product of vector and scalar
	friend Vector3 operator*(const Vector3 &v, const Float &f)
	{
		return Vector3(f * v.x, f * v.y, f * v.z);
	}

	friend Vector3 operator*(const Float &f, const Vector3 &v)
	{
		return v * f;
	};

	// vector plus scalar
	friend Vector3 operator+(const Vector3 &v, const Float &f)
	{
		return Vector3(v.x + f, v.y + f, v.z + f);
	}

	// vector minus scalar
	friend Vector3 operator-(const Vector3 &v, const Float &f)
	{
		return Vector3(v.x - f, v.y - f, v.z - f);
	}

	// cell by cell product (only usable for colours)
	friend Vector3 operator*(const Vector3 &a,  const Vector3 &b)
	{
		return Vector3(a.x * b.x, a.y * b.y, a.z * b.z);
	};

	// print
	friend ostream & operator<<(ostream &st, const Vector3 &v)
	{
		return st << "(" << v.x << ", " << v.y  << ", " << v.z << ")";
	}
};

typedef Vector3 Colour;

#endif