#ifndef CVECTOR2F_H
#define CVECTOR2F_H
#include <cmath>
#include <algorithm>
class CVector2f
{
public:
//Variables//
float x, y;
//Constructors//
CVector2f( ): x( 0.0f ), y( 0.0f ) { }
CVector2f( float _x, float _y ): x( _x ), y( _y ) { }
//Functions//
//Magnitude of the vector, squared( faster than norm() )
float norm2( ) const
{
return x * x + y * y;
}
//Magnitude of the vector (slower than norm2() because of sqrt )
float norm( ) const
{
return sqrt( norm2( ) );
}
//returns a vector of the same direction as this*, but with a norm() of 1
//or the vector if its norm is 0
CVector2f normal( ) const
{
float n = norm( );
return n == 0 ? *this : CVector2f( x/n, y/n);
}
//Turns this vector into its normal
void normalize( )
{
float n = norm( );
if( n != 0 )
*this /= n;
}
inline static CVector2f vmin( const CVector2f &a, const CVector2f &b )
{
return CVector2f( std::min( a.x, b.x ), std::min( a.y, b.y ) );
}
inline static CVector2f vmax( const CVector2f &a, const CVector2f &b )
{
return CVector2f( std::max( a.x, b.x), std::min( a.y, b.y ) );
}
inline static float crossProduct( const CVector2f &a, const CVector2f &b )
{
return a.x * b.y - b.x * a.y;
}
inline static float dotProduct( const CVector2f &a, const CVector2f &b )
{
return a.x * b.x + a.y * b.y;
}
//Operator Overloading//
//+,-,*,/
inline CVector2f operator+( const CVector2f &other ) const
{
return CVector2f( x + other.x, y + other.y );
}
inline CVector2f operator-( const CVector2f &other ) const
{
return CVector2f( x - other.x, y - other.y );
}
inline CVector2f operator*( float factor ) const //scale
{
return CVector2f( x * factor, y * factor );
}
inline CVector2f operator/( float factor ) const
{
return CVector2f( x / factor, y / factor );
}
//+=,-=,/=,*=
inline CVector2f& operator+=( const CVector2f &other )
{
x += other.x;
y += other.y;
return *this;
}
inline CVector2f& operator-=( const CVector2f &other )
{
x -= other.x;
y -= other.y;
return *this;
}
inline CVector2f& operator*=( float factor )
{
x *= factor;
y *= factor;
return *this;
}
inline CVector2f& operator/=( float factor )
{
x /= factor;
y /= factor;
return *this;
}
//-,*
inline CVector2f operator-( ) const
{
return CVector2f( -x, -y );
}
//maybe confusing?
inline float operator*( const CVector2f &other ) const //dot product
{
return ( x * other.x + y * other.y );
}
//==,!=
inline bool operator==( const CVector2f &other ) const
{
return (x == other.x) && (y == other.y);
}
inline bool operator!=( const CVector2f &other ) const
{
return !(*this==other);
}
//other
inline float crossProduct( const CVector2f &other ) const
{
return x * other.y - y * other.x;
}
//friends
friend CVector2f operator*( float factor, const CVector2f &vector );
};
inline CVector2f operator*( float factor, const CVector2f &vector )
{
return vector * factor;
}
#endif
|