This class should have been posted long ago.  So, seeing how popular my C++ Vector2 class page has been, I've decided to finally post this for your needs.  This version is similar to the "improvements" on the Vector2 class, supposedly helping encapsulation; frankly, that's up for you to decide.

 

Remember, you can hover over the source area and click the "<>" looking image (top right) to pop the source code into a new window to more easily view and copy the code.

Vector3.h

/*  __      __   ___     _____    ____
 *  \ \    / /  / _ \   |  __ \  |    |
 *   \ \/\/ /  / / \ \  | | / /  |  __|
 *    \_/\_/  /_/   \_\ |_| \_\  |_|
 *      Take it to the next Level
 *
 *  Copyright (c) 2009 Brian Ernst.
 */

#ifndef w_Vector3
#define w_Vector3

#include <cmath>

namespace _Warp
{
	typedef float	Scalar;
	typedef int		Bool;

	class Vector3
	{
	public:
		Scalar X;
		Scalar Y;
		Scalar Z;

		Vector3();
		Vector3(Scalar x, Scalar y, Scalar z);

		Vector3		operator+(const Vector3&amp; vector) const;
		Vector3		operator-(const Vector3&amp; vector) const;
		Vector3		operator-() const;
		Vector3		operator*(Scalar num) const;
		Vector3		operator/(Scalar num) const;

		Vector3&amp;	operator+=(const Vector3&amp; vector);
		Vector3&amp;	operator-=(const Vector3&amp; vector);
		Vector3&amp;	operator*=(Scalar num);
		Vector3&amp;	operator/=(Scalar num);

		Bool		operator==(const Vector3&amp; vector) const;
		Bool		operator!=(const Vector3&amp; vector) const;

		static const Vector3 Zero;
		static const Scalar	Epsilon;
	};

	inline Bool Vector3::operator==(const Vector3&amp; vector) const
	{
		return X == vector.X &amp;&amp; Y == vector.Y &amp;&amp; Z == vector.Z;
	}

	inline Bool Vector3::operator!=(const Vector3&amp; vector) const
	{
		return X != vector.X || Y != vector.Y || Z != vector.Z;
	}

	inline Vector3 Vector3::operator+(const Vector3&amp; vector) const
	{
		return Vector3(X + vector.X, Y + vector.Y, Z + vector.Z);
	}

	inline Vector3 Vector3::operator-(const Vector3&amp; vector) const
	{
		return Vector3(X - vector.X, Y - vector.Y, Z - vector.Z);
	}

	inline Vector3 Vector3::operator-() const
	{
		return Vector3(-X,-Y,-Z);
	}

	inline Vector3 Vector3::operator*(Scalar num) const
	{
		return Vector3(X * num, Y * num, Z * num);
	}

	inline Vector3 Vector3::operator/(Scalar num) const
	{
		return Vector3(X / num, Y / num, Z / num);
	}
}
#endif

Vector3.cpp:

#include "Vector3.h"

#include <limits>

namespace _Warp
{
	const Vector3 Vector3::Zero = Vector3(0,0,0);
	const Scalar Vector3::Epsilon = std::numeric_limits::epsilon();

	Vector3::Vector3()
	{
	}

	Vector3::Vector3(Scalar x, Scalar y, Scalar z)
		: X( x )
		, Y( y )
		, Z( z )
	{
	}

	Vector3& Vector3::operator+=(const Vector3& vector)
	{
		X += vector.X;
		Y += vector.Y;
		Z += vector.Z;
		return *this;
	}

	Vector3& Vector3::operator-=(const Vector3& vector)
	{
		X -= vector.X;
		Y -= vector.Y;
		Z -= vector.Z;
		return *this;
	}

	Vector3& Vector3::operator*=(Scalar num)
	{
		X *= num;
		Y *= num;
		Z *= num;
		return *this;
	}

	Vector3& Vector3::operator/=(Scalar num)
	{
		this-&gt;X /= num;
		this-&gt;Y /= num;
		this-&gt;Z /= num;
		return *this;
	}
}

Vector3Util.h

/*  __      __   ___     _____    ____
 *  \ \    / /  / _ \   |  __ \  |    |
 *   \ \/\/ /  / / \ \  | | / /  |  __|
 *    \_/\_/  /_/   \_\ |_| \_\  |_|
 *      Take it to the next Level
 *
 *  Copyright (c) 2009 Brian Ernst.
 */

#ifndef w_Vector3Util
#define w_Vector3Util

#include "Vector3.h"

// These two files are not detailed out in this blog post.
#include "Quaternion.h"
#include "TMatrixUtil.h"

namespace _Warp
{
	Scalar len(const Vector3& vect);
	Scalar len2(const Vector3& vect);

	void Clamp(Vector3& vect,Scalar length);
	void Normalize(Vector3& vect);
	void Normalize_s(Vector3& vect);
	void SetLength(Vector3& vect, Scalar length);
	void SetLength_s(Vector3& vect, Scalar length);

	Scalar	Dot(const Vector3& vec1, const Vector3& vec2);
	Scalar	GetAngle(Vector3 vec1, Vector3 vec2);

	Vector3	ToNormalized(const Vector3& vect);
	Vector3	ToNormalized_s(const Vector3& vect);
	Vector3	ToPolar(Scalar x, Scalar y, Scalar z);
	Vector3	ToCartesian(Scalar radius, Scalar angle, Scalar z);
	Vector3	Cross(const Vector3& vec1, const Vector3& vec2);
	Vector3	Rotate(const Vector3& vec1, Scalar angle, const Vector3& axis);

	Vector3 ToEuler(Vector3 axis, Scalar angle);

	inline Scalar len(const Vector3& vect)
	{
		return sqrt(vect.X * vect.X + vect.Y * vect.Y + vect.Z * vect.Z);
	}

	inline Scalar len2(const Vector3& vect)
	{
		return vect.X * vect.X + vect.Y * vect.Y + vect.Z * vect.Z;
	}

	inline void Normalize(Vector3& vect)
	{
		vect /= len(vect);
	}

	inline void SetLength(Vector3& vect, Scalar length)
	{
		vect *= length / len(vect);
	}

	inline Scalar	Dot(const Vector3& vec1, const Vector3& vec2)
	{
		return vec1.X * vec2.X + vec1.Y * vec2.Y + vec1.Z * vec2.Z;
	}

	inline Vector3 ToNormalized(const Vector3& vect)
	{
		return vect / len(vect);
	}

	// This uses a Quaternion combined with the Matrix Utility, neither of which are detailed out in this post.
	inline Vector3	Rotate(const Vector3& vec1, Scalar angle, const Vector3&amp; axis)
	{
		return TransformCoord(Quaternion::FromAxis(axis.X,axis.Y,axis.Z,angle).Get_RotationMatrix(),vec1);
	}

	inline Vector3	ToPolar(Scalar x, Scalar y, Scalar z)
	{
		return Vector3(
			atan2(y,x),
			sqrt(x * x + y * y),
			z);
	}

	inline Vector3	ToCartesian(Scalar radius, Scalar angle, Scalar z)
	{
		return Vector3(
			radius * cos(angle),
			radius * sin(angle),
			z);
	}

	inline Vector3	Cross(const Vector3& vec1, const Vector3& vec2)
	{
		return Vector3(
			vec1.Y * vec2.Z - vec1.Z * vec2.Y,
			vec1.Z * vec2.X - vec1.X * vec2.Z,
			vec1.X * vec2.Y - vec1.Y * vec2.X);
	}
}

#endif

Vector3Util.cpp

#include "Vector3Util.h"

#include "../Constants.h"

namespace _Warp
{
	void Clamp(Vector3& vect,Scalar length)
	{
		Scalar vecLength = len2(vect);

		if(vecLength &lt;= length * length)
		{
			return;
		}

		vect *= length / sqrt(vecLength);
	}

	void Normalize_s(Vector3& vect)
	{
		Scalar vecLength = len2(vect);

		if(vecLength == 0)
		{
			return;
		}

		vect /= sqrt(vecLength);
	}

	void SetLength_s(Vector3& vect, Scalar length)
	{
		Scalar vecLength = len2(vect);

		if(vecLength == 0)
		{
			return;
		}

		vect *= length / sqrt(vecLength);
	}

	inline Scalar	GetAngle(Vector3 vec1, Vector3 vec2)
	{
		if(vec1 == vec2)
		{
			return 0.0f;
		}

		Normalize_s(vec1);
		Normalize_s(vec2);

		Scalar dot = Dot(vec1, vec2) / (len(vec1) * len(vec2));

		dot = dot > 1.0f ? 1.0f : ( dot < -1.0f ? -1.0f : dot );

		return std::acos(dot);
	}

	Vector3 ToNormalized_s(const Vector3& vect)
	{
		Scalar vecLength = len2(vect);

		if(vecLength == 0)
		{
			return vect;
		}

		vecLength = sqrt(vecLength);

		return Vector3(vect.X / vecLength, vect.Y / vecLength, vect.Z / vecLength);
	}

	// Thanks to Martin Baker for this solution
	// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToEuler/index.htm
	Vector3 ToEuler(Vector3 axis, Scalar angle)
	{
		Vector3 out = Vector3();

		Scalar s = sin(angle);
		Scalar c = cos(angle);
		Scalar t = (Scalar)1.0 - c;

		if ((axis.X * axis.Y * t + axis.Z * s) > (Scalar)0.998)// north pole singularity detected
		{
			out.Y = 2 * atan2(axis.X * sin(angle/2), cos(angle/2));
			out.Z = static_cast<Scalar>(W_PI_2);
			out.X = 0;
			return out;
		}
		if ((axis.X * axis.Y * t + axis.Z * s) < (Scalar)-0.998)// south pole singularity detected
		{
			out.Y = (Scalar)-2.0 * atan2(axis.X * sin(angle / (Scalar)2.0), cos(angle / (Scalar)2.0));
			out.Z = -static_cast<Scalar>(W_PI_2);;
			out.X = 0;
			return out;
		}
		out.Y = atan2(axis.Y * s - axis.X * axis.Z * t , 1 - (axis.Y * axis.Y + axis.Z * axis.Z ) * t);
		out.Z = asin(axis.X * axis.Y * t + axis.Z * s) ;
		out.X = atan2(axis.X * s - axis.Y * axis.Z * t , 1 - (axis.X * axis.X + axis.Z * axis.Z) * t);
		return out;
	}
}

You'll notice in the Vector3Util I have some functions ending with "_s", like "Noramlize_s"; this is a notation I'm trying to mean, in this case, a safe normalize function call (won't result in a divide by zero error).  So, if you know the vector you're using can't possibly be zero, use the standard Normalize function, if not, then feel free to use Normalize_s.  Please let me know if you have a comment on the notation!

Anyway, this Vector3 class and utility are code I use in my personal game development, and in other school projects that I may have, and have used it and my personal math libs in a ray tracer.  Concerning the util, I'm still tweaking it, making decisions on how to wrap it in a namespace (like it's own _Math namespace, which was taken out for this post), or perhaps on whether I feel I really need a separate util instead of having them as member functions, which would be more convenient with intellisense at hand. If you're wondering what I'm talking about, check out this article at Dr Dobbs on encapsulation.  I personally have to give it another read and determine if I agree with it or not and really want to stick with that methodology.

 

Please leave your thoughts and suggestions!
[I'll be uploading the upgraded version of this Vector3 class sometime soon, I realize there are parts of this version that may be a little rough/unfinished, and after that I'll include the source files for you to download]

[Disclaimer : All benchmarks were done in debug mode on an i7 920 system with no compiler optimizations]

After browsing some cool C++ util functions today on StackOverflow, one of the cool util functions was for trimming strings, so I became intrigued and decided to compare them against my own, as they used some cool C++ std library tricks that I've never seen before. After doing benchmark tests, I was excited to find my own implementation appeared to blow his out of the water. After 1,000,000 tests, his averaged about 27 microseconds, while mine at first averaged less than 5 microseconds. After tweaking mine a bit, my trim_trailingWhitespace function averaged close to 4 microseconds after averaging 1,000,000 samples. Also to note, his function works directly on the original string, while mine returns a new copy; so it's even more impressive.

Here's another benchmark using 1,000,000 samples.
Using the following string: "          "
His: 37.88 microseconds
Mine: 4.03 microseconds

Benchmark 3 using the same # of samples as before.
Using the following string: "  The world ends with you!   "
His: 30.37 microseconds
Mine: 6.26 microseconds

The reason for this post, is because I was excited to find out my implementation is extremely fast, and I felt like sharing it with the world to see if it's possible to do even better! I'm still thinking of ways to improve my functions, but please let me know if you can best me in any way, I'm here to learn!


The only header you should need is the following, with the proper using statements too of course:

#include <iostream>

using std::basic_string;

This is the trim function used by my trim_trailingWhitespace

template<typename CharType>
static basic_string<CharType> trim(const basic_string<CharType>& str, size_t index, size_t len)
{
	size_t length = str.size();
	if(index >= length)
	{
		return basic_string<CharType>();
	}

	length -= index;
	length = length > len ? len : length;

	return str.substr(index, length);
}

And this is my function to trim the whitespace at the end of the string:

template<typename CharType>
static basic_string<CharType> trim_trailingWhitespace(const basic_string<CharType>& str)
{
	size_t length = str.size();
	if(length == 0)
	{
		return str;
	}

	register size_t index = length - 1;

	while(' ' == str[index])
	{
		if(index != 0)
		{
			--index;
		}
		else
		{
			return basic_string<CharType>();
		}
	}

	return trim(str, 0, ++index);
}

You'll notice I'm using some funky template stuff here, and basic_string; this will allow you to use whatever kind of string encoding you want, 1Byte ASCII characters (string), or 2Byte unicode characters (wstring), or whatever. And the beauty of it is, if you pass in the proper string type, like string or wstring, you don't need to define the template parameters; your compiler will automatically fill them in for you so you only just need to call the function name without worrying about the template details!

I haven't gotten a chance to rewrite my trim_leadingWhitespace function, so that will be coming soon; and yes, I will rename these once I decide upon a better name.


After doing some further research I stumbled across this implementation.  I realized my above comparison to the first algorithm wasn't entirely fair as the implementation wasn't even competitive, even though it worked in-place.  So, here's the source for an actually efficient implementation of rear trimming white space:

void rtrim(string& str, const locale& loc)
{
  string::size_type pos = str.size();
  while (pos > 0 && isspace(str[pos - 1], loc)) pos--;
  str.erase(pos);
}

By replacing the isspace with ' ' == you can make this function much faster, though obviously this works with our locale, and may be different across other languages. Another possible reason this isn't as fast as it could be is because of the str[pos - 1], he's doing an extra calculation per loop besides the pos--. His solution gets around the problem of using an unsigned int (size_t) that mine originally had, but lucky for me my rewrite made mine even more efficient because of this trick he had to do.

And here's the details on isspace. I think my check works fine for both string and wstring and the like; if not, please let me know.  [Edit] You could pass the locale space/seperator in as a parameter to the function if that's an issue.

As the above solution works in place, I decided to tweak my original function to work in place on a string, and am excited to say that it beats out this obviously improved implementation.  Here's my new in-place implementation:

template<typename CharType>
static void trim_trailingWhitespace(basic_string<CharType>& str)
{
	size_t length = str.size();
	if(length == 0)
	{
		return;
	}

	register size_t index = length - 1;

	while(' ' == str[index])
	{
		if(index != 0)
		{
			--index;
		}
		else
		{
			str.clear();
			return;
		}
	}
	str.erase(++index);
}

So, my implementation provides shortcuts for an empty string, and for the case the entire string contains spaces (where you see str.clear()). It also provides an interesting way to loop through the string compared to the other implementation, allowing mine to be a bit quicker, probably because I only have to use str[index] (besides the above mentioned shortcuts).

Benchmark 1:
String: "      "
His: 2.97 microseconds
His + my tweak: 2.68 microseconds
Mine:2.54 microseconds

Benchmark 2:
String: "  The world ends with you!   "
His: 3.93 microseconds
His + my tweak: 3.68 microseconds
Mine: 3.65 microseconds

As noted at the header, the above tests were done in debug mode with no optimizations.  If you turn on optimizations you'll notice the two algorithms at the bottom here are neck and neck, it doesn't really matter what you use.  Heck, if you look at the algorithm from StackOverflow that's not nearly as efficient in debug, suddenly becomes nearly comparable.  Though, it's still nice to have a code that runs fast in debug too; but it does raise the question whether it was worth the time to do this research; as they say, don't optimize until you have to.  It's been a nice educational endeavor so far, so I don't really care if it might be considered wasted time, as I've learned more than a thing or two.  Thoughts?

And here's the link to the StackOverflow page of useful C++ utilities: Most Useful C++ Utils.

Looking to do Multithreaded programming? In order to do that you're going to need a Mutex to prevent threads from accessing data at the same time! There are different techniques of preventing threads from accessing the same data, but they can't guarantee problems won't happen, it has to be implemented on the hardware side and exposed through the OS or what have you. Luckily, we can do this using some code from the Windows header files, using what's called Critical Section Objects, which works between threads on the same process, and is apparently a, "slightly faster, more efficient mechanism for mutual-exclusion synchronization." Sweeet!

Mutex_win32.h:

#ifndef w_Mutex_win32
#define w_Mutex_win32

#include <windows.h>

#include "../Definitions.h"

namespace _Warp
{
	class Mutex_win32
	{
	protected:
		CRITICAL_SECTION _critSection;

	public:
		Mutex_win32()
		{
			InitializeCriticalSection (&_critSection);
		}

		~Mutex_win32()
		{
			DeleteCriticalSection (&_critSection);
		}

		void Lock()
		{
			EnterCriticalSection (&_critSection);
		}
		void Unlock()
		{
			LeaveCriticalSection (&_critSection);
		}

		Bool TryLock()
		{
			return (Bool)TryEnterCriticalSection(& _critSection);
		}
	};
}
#endif

Now, threading problems can be hard to track down and debug, especially if you forget to Unlock the Mutex. So a Lock object is a way to help you clean up and unlock the Mutex when you're done. A Lock is created on the Stack in a local block of code, so when the program leaves the block of code the Lock gets deleted, the destructor gets called, and in the process the Mutex is automatically unlocked in the Lock destructor.

Lock.h:

#ifndef w_Lock
#define w_Lock

#include "../Data/Uncopyable.h"

#include "Mutex_win32.h"

namespace _Warp
{
	class Lock
		: private Uncopyable
	{
	protected:
		Mutex_win32* _pMutex;

	public:
		explicit Lock(Mutex_win32* pMutex);
		~Lock();
	};

	inline Lock::Lock(Mutex_win32* pMutex)
		: _pMutex( pMutex )
	{
		if(_pMutex != NULL)
		{
			_pMutex->Lock();
		}
	}

	inline Lock::~Lock()
	{
		if(_pMutex != NULL)
		{
			_pMutex->Unlock();
		}
	}
};
#endif

Here's an example of how to use a Lock and Mutex:

Mutex_win32* _pMessageListMutex = new Mutex_win32();//a mutex might typically exist in the header as a member variable
list<string> _messages = list<string>();// this 

void function()
{
	Lock lock = Lock(_pMessageListMutex);
	/* do stuff to the list */
}// when the program reaches here, the lock gets cleaned up and the _pMessageListMutex gets freed so another thread can access the _messages list without worrying about another thread accessing it at the same time

In case you didn't notice, the Lock class inherits from an "Uncopyable" class that doesn't allow the Lock to be copied or to be constructed from another Lock.  This helps prevent errors from happening, besides the fact a lock shouldn't be copied anyway; so this class ensures it can't be.  The Uncopyable class was inspired by the Boost Uncopyable class, though it wasn't the first site I ran across that showed something very similar.

Uncopyable.h:

#ifndef w_Uncopyable
#define w_Uncopyable

namespace _Warp
{
	// Inherit from this if you want a class to be unable to be copy-constructed.
	class Uncopyable
	{
	private:
		Uncopyable(const Uncopyable&);
		Uncopyable& operator=(const Uncopyable&);

	protected:
		Uncopyable(){}
		virtual ~Uncopyable(){}
	};
};
#endif

For those of you who don't know, the virtual destructor is required if any class inherits from Uncopyable, if you want it to properly be deleted. This should only be a problem if you store an object as an Uncopyable object, instead of it's own object type, and you try to delete it, the child's destructor will be properly called before the parent's destructor. Also, because the Copy constructor and copy operator aren't defined (besides the fact that they're private), you'll get a compiler error preventing you from doing anything you shouldn't be!

Both the Lock and Mutex class are pretty simple, so there isn't really much variation to them; I don't remember exactly which sites I used to lookup the Windows functions, otherwise I'd credit them for their help.  Either way, if you had trouble finding C++ Mutex and Lock classes, I hope you find these useful for your purposes!

You can download the project files here: Mutex, Lock, and necessary class files.

This is an improved Vector2 class I'm working on with suggestions from Leander Hasting, though I haven't touched upon all of them yet.  Beyond that, some of the critiques seem subjective to a point, and other professionals he pointed me to, make the same argument; and that is the argument of the use 0f non-member functions.  With intellisense working, I find using member functions to be the easiest way of doing things, as I think it is easier for other people to work with; as someone who's trying to write an engine, I understand the importance of including extra functions in a separate header file, though I think that can get messy.  So, with what is proposed you could do VectorUtil::len(vector), though having the VectorUtilthere is ugly, though without it there, how do you know that function even exists or where it's coming from?  So for starters, it's more useful to split the vector up like this, because everything doesn't need access to these functions, and it helps build times.  Though, in the end, when this engine is done, all of the information is most likely going to be included anyway;  lets say I want to add scripting support with my own version of intellisense, I want to make it as easy as possible for someone not used to my engine to be able to interactively see what they can do with a Vector by simply using "vector." and everything they have available to them pop up.  So, because the functions are accessing public members, they have no need to be member functions; so while some may claim using member functions breaks encapsulation, I think it makes it easier to open up a class to the user and what it can do.  Though it's interesting that intellisense in Visual Studio also shows private and protected functions you don't have access to...

Anyway, what I would like to do with my code is make it as easy as possible for anyone to use, I'm not worried that much about technicalities and hardcore programmers squirming over things I don't care about.  Though that makes me wonder, should I care about that, and perhaps just take it with a grain of salt?

Anyway, here's my Vector2 class in it's improved glory.

Vector2.h:

/*  __      __   ___     _____    ____
 *  \ \    / /  / _ \   |  __ \  |    |
 *   \ \/\/ /  / / \ \  | | / /  |  __|
 *    \_/\_/  /_/   \_\ |_| \_\  |_|
 *      Take it to the next Level
 *
 *  Copyright (c) 2009 Brian Ernst.
 */
#ifndef w_Vector2
#define w_Vector2

#ifndef FALSE
#define FALSE 0
#endif

#ifndef TRUE
#define TRUE 1
#endif

namespace _Warp
{
	typedef float Scalar;
	typedef int Bool;

	class Vector2
	{
	public:
		Scalar X;
		Scalar Y;

		Vector2();
		Vector2(Scalar x, Scalar y);

		Vector2& operator+=(const Vector2& pVector);
		Vector2& operator-=(const Vector2& pVector);
		Vector2& operator*=(Scalar num);
		Vector2& operator/=(Scalar num);

		Bool operator!=(const Vector2& vect) const;
		Bool operator==(const Vector2&; vect) const;

		friend Vector2 operator-(Vector2& vect);
		friend Vector2 operator+(const Vector2& vect1,const Vector2& vect2);
		friend Vector2 operator-(const Vector2& vect1,const Vector2& vect2);
		friend Vector2 operator*(const Vector2& vect1, Scalar value);
		friend Vector2 operator/(const Vector2& vect1, Scalar value);
		friend Vector2 operator*(const Vector2& vect1,const Vector2& vect2);
		friend Vector2 operator/(const Vector2& vect1,const Vector2& vect2);
	};

	inline Vector2::Vector2()
	{
	}

	inline Vector2::Vector2(Scalar x,Scalar y)
		: X( x )
		, Y( y )
	{
	}

	inline Bool Vector2::operator!=(const Vector2& vector) const
	{
		return X != vector.X || Y != vector.Y;
	}

	inline Bool Vector2::operator==(const Vector2& vect) const
	{
		return (*this != vect) == FALSE;
	}

	inline Vector2& Vector2::operator+=(const Vector2& pVector)
	{
		X += pVector.X;
		Y += pVector.Y;
		return *this;
	}

	inline Vector2& Vector2::operator-=(const Vector2& pVector)
	{
		X -= pVector.X;
		Y -= pVector.Y;
		return *this;
	}

	inline Vector2& Vector2::operator*=(Scalar num)
	{
		X *= num;
		Y *= num;
		return *this;
	}

	inline Vector2& Vector2::operator/=(Scalar num)
	{
		X /= num;
		Y /= num;
		return *this;
	}

	inline Vector2 operator+(const Vector2& vect1,const Vector2& vect2)
	{
		return Vector2(vect1.X + vect2.X,vect1.Y + vect2.Y);
	}

	inline Vector2 operator-(const Vector2& vect1,const Vector2& vect2)
	{
		return Vector2(vect1.X - vect2.X,vect1.Y - vect2.Y);
	}

	inline Vector2 operator-(Vector2& vect)
	{
		return vect * -1;
	}

	inline Vector2 operator*(const Vector2& vect1, Scalar value)
	{
		return Vector2(vect1.X * value,vect1.Y * value);
	}

	inline Vector2 operator/(const Vector2& vect1, Scalar value)
	{
		return Vector2(vect1.X / value,vect1.Y / value);
	}

	inline Vector2 operator*(const Vector2& vect1,const Vector2& vect2)
	{
		return Vector2(vect1.X * vect2.X,vect1.Y * vect2.Y);
	}

	inline Vector2 operator/(const Vector2& vect1,const Vector2& vect2)
	{
		return Vector2(vect1.X / vect2.X,vect1.Y / vect2.Y);
	}
}

#endif

VectorUtil.h

/*  __      __   ___     _____    ____
 *  \ \    / /  / _ \   |  __ \  |    |
 *   \ \/\/ /  / / \ \  | | / /  |  __|
 *    \_/\_/  /_/   \_\ |_| \_\  |_|
 *      Take it to the next Level
 *
 *  Copyright (c) 2009 Brian Ernst.
 */

#ifndef w_VectorUtil
#define w_VectorUtil

#include <cmath>

using std::sin;
using std::cos;
using std::sqrt;
using std::atan2;

#include "Vector2.h"

namespace _Warp
{
	class Vector2Util
	{
		static Scalar 	len(const Vector2& vect);
		static Scalar 	len2(const Vector2& vect);

		static Vector2& invert(Vector2& vect);
		static Vector2& normalize(Vector2& vect);
		static Vector2& clamp(Vector2& vect, Scalar value);
		static Vector2& setLength(Vector2& vect, Scalar value);

		static Vector2	polar		(Scalar x, Scalar y);
		static Vector2 	cartesian	(Scalar radius,	Scalar angle);
		static Scalar 	dot			(const Vector2& pVec1, const Vector2& pVec2);
		static Vector2 	rotate		(const Vector2& pVec, Scalar angle);
	};

	inline Scalar len(const Vector2& vect)
	{
		return sqrt(vect.X * vect.X + vect.Y * vect.Y);
	}

	inline Scalar len2(const Vector2& vect)
	{
		return vect.X * vect.X + vect.Y * vect.Y;
	}

	inline Vector2& invert(Vector2& vect)
	{
		return vect *= -1;
	}

	inline Vector2& normalize(Vector2& vect)
	{
		if(vect.X == 0 &amp;&amp; vect.Y == 0)
		{
			return vect;
		}

		Scalar length = len(vect);

		vect.X /= length;
		vect.Y /= length;
		return vect;
	}

	inline Vector2& clamp(Vector2& vect,Scalar value)
	{
		Scalar length = len2(vect);
		if(length &lt;= value * value)
		{
			return vect;
		}

		length = sqrt(length);

		vect.X *= value / length;
		vect.Y *= value / length;

		return vect;
	}

	inline Vector2& setLength(Vector2& vect, Scalar value)
	{
		if(vect.X == 0 &amp;&amp; vect.Y == 0)
		{
			return vect;
		}

		Scalar length = len(vect);

		vect.X *= value / length;
		vect.Y *= value / length;

		return vect;
	}

	inline Vector2 cartesian(Scalar radius,Scalar angle)
	{
		return Vector2(radius * cos(angle),radius * sin(angle));
	}

	inline Vector2 polar(Scalar x,Scalar y)
	{
		return Vector2(atan2(y,x),sqrt(x * x + y * y));
	}

	inline Scalar dot(const Vector2& pVec1,const Vector2& pVec2)
	{
		return pVec1.X * pVec2.X + pVec1.Y * pVec2.Y;
	}

	inline Vector2 rotate(const Vector2& pVec,Scalar angle)
	{
		Scalar cosResult = cos(angle);
		Scalar sinResult = sin(angle);

		//Essentially, apply a 2x2 rotation matrix to the vector
		Scalar newX = pVec.X * cosResult - pVec.Y * sinResult;
		Scalar newY = pVec.X * sinResult + pVec.Y * cosResult;

		return Vector2(newX,newY);
	}
}

#endif

Notes:

With this class, you can't do this:

Vector2 vect = 2;

This was possible with my old Vector2 class, and frankly should be an error.  If you are going to initialize the vars of a Vector2 at a later time, you can do this:

Vector2 vect = Vector2(Vector2::Uninitialized())

The reason for this is, doing this:

Vector2 vect = Vector2();

...creates a Vector2(0,0) by default. I could setup a default constructor and not use default values, however that could result in bugs from coders not properly initializing Vector2 objects. So, it is this reason the Uninitialized class is being used.

Feel free to use this improved Vector2 class, and if the c-style functions in VectorUtil bug you, feel free to make them member functions again in Vector2.

Download the Vector2 improved here: Vector2 class files.

[Update: As of 5/11/10 I noticed a typo, which I fixed, however I need to update the source files. I've also realized there are also a couple other utility functions I could "add", so will do so sometime soon; I got the idea from looking at another blog, however I realized he just named the functions to something easily understandable. For example, the dot and cross product; their names don't say anything about what the function really does, what the data represents. So, it seems useful to package up those functions to make it easier for programmers using this utility, and of course leaving the original functions in-tact (perhaps?) so other programmers looking for them won't be confused when they think they can't find them. So, more cool things to come! :) ]

It's a very simple class, but I wrote what I'm calling a Timer, it has similar functionality to a stop watch. The Basic timer class relies on the Windows QueryPerformanceFrequency, so here's the function necessary for my Timer class:

Time.h

#ifndef w_Time
#define w_Time

#include "../Definitions.h"

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>

namespace _Warp
{
	class Time
	{
	public:

		static Real64 HiResTime()
		{
			u64 ticks;
			u64 ticksPerSecond;
			Bool result = QueryPerformanceFrequency((LARGE_INTEGER*) &ticksPerSecond);
			if(result == 0)
			{
				return -1;
			}
			result = QueryPerformanceCounter((LARGE_INTEGER*) &ticks);
			if(result == 0)
			{
				return -1;
			}
			return (Real64) ticks / ticksPerSecond;
		}
	};
};

#endif

Timer.h

#ifndef w_Timer
#define w_Timer

#include "../Definitions.h"

namespace _Warp
{
	class Timer
	{
	protected:
		Real64 _start;

		Bool _running;

	public:
		Timer();

		void Start();
		void Stop();
		void Reset();

		Real64 Get_Microseconds() const;
		Real64 Get_Milliseconds() const;
		Real64 Get_Seconds() const;

		Bool IsRunning() const;
	};
};

#endif

Timer.cpp

#include "Timer.h"

#include "Time.h"

namespace _Warp
{
	Timer::Timer()
		: _start( 0 )
		, _running( FALSE )
	{
	}

	void Timer::Start()
	{
		// this allows the timer to continue from where it left off
		_start = Time::HiResTime() - _start;
		_running = TRUE;
	}

	void Timer::Stop()
	{
		if(_running == TRUE)
		{
			_start = Time::HiResTime() - _start;
			_running = FALSE;
		}
	}

	void Timer::Reset()
	{
		if(_running == TRUE)
		{
			_start = Time::HiResTime();
		}
		else
		{
			_start = 0;
		}
	}

	Real64 Timer::Get_Microseconds() const
	{
		if(_running == TRUE)
		{
			return (Time::HiResTime() - _start) * 1000000.0;
		}
		return _start * 1000000.0;
	}

	Real64 Timer::Get_Milliseconds() const
	{
		if(_running == TRUE)
		{
			return (Time::HiResTime() - _start) * 1000.0;
		}
		return _start * 1000.0;
	}

	Real64 Timer::Get_Seconds() const
	{
		if(_running == TRUE)
		{
			return Time::HiResTime() - _start;
		}
		return _start;
	}

	Bool Timer::IsRunning() const
	{
		return _running;
	}
};

Here is a sample of how to use my timer class:

Timer timer = Timer();
timer.Start();
/* do stuff here */
timer.Stop();
Real64 seconds = timer.Get_Seconds();
timer.Reset();//reset the timer so it's total count is back to zero seconds.

timer.Start();
/* time something else */
timer.Stop();
/* do something */
timer.Start();//continue the count from where the timer left off
/* time something again*/
timer.Stop();
seconds = timer.Get_Seconds();// this is the total count of seconds from the last two timing sessions since Reset wasn't called

You can find the blog on the Definition.h file here.

Or download all of the above files and Definition.h here: Timer project files.

Archive