Last active
August 29, 2015 14:10
-
-
Save SeijiEmery/fbc28a0d16f582baddd7 to your computer and use it in GitHub Desktop.
Vec2 impl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef __math2d_Vec2_h__ | |
#define __math2d_Vec2_h__ | |
#include <cmath> | |
#include <ostream> | |
#define DEFN_IMM_VECTOR_OP(op) \ | |
friend Vec2 operator op (const Vec2 &a, const Vec2 &b) { \ | |
return { a.x op b.x, a.y op b.y }; \ | |
} | |
#define DEFN_IMM_SCALAR_OP(op) \ | |
friend Vec2 operator op (const Vec2 &a, float s) { \ | |
return { a.x op s, a.y op s }; \ | |
} | |
#define DEFN_MUT_VECTOR_OP(op) \ | |
Vec2 & operator op (const Vec2 &rhs) { \ | |
return (x op rhs.x), (y op rhs.y), *this; \ | |
} | |
#define DEFN_MUT_SCALAR_OP(op) \ | |
Vec2 & operator op (float s) { \ | |
return (x op s), (y op s), *this; \ | |
} | |
struct Vec2 { | |
float x = 0.0f; | |
float y = 0.0f; | |
Vec2 () {} | |
Vec2 (float x, float y) : x(x), y(y) {} | |
Vec2 (const Vec2 & v) : x(x), y(y) {} | |
DEFN_IMM_VECTOR_OP(+) | |
DEFN_IMM_VECTOR_OP(-) | |
DEFN_IMM_SCALAR_OP(*) | |
DEFN_IMM_SCALAR_OP(/) | |
DEFN_MUT_VECTOR_OP(=) | |
DEFN_MUT_VECTOR_OP(+=) | |
DEFN_MUT_VECTOR_OP(-=) | |
DEFN_MUT_SCALAR_OP(*=) | |
DEFN_MUT_SCALAR_OP(/=) | |
float dot (const Vec2 & other) const { | |
return x * other.x + y * other.y; | |
} | |
float magnitude () const { | |
return sqrt(this->dot(*this)); | |
} | |
float distance (const Vec2 & other) const { | |
return (*this - other).magnitude(); | |
} | |
float magnitudeSq () const { | |
return this->dot(*this); | |
} | |
float distanceSq (cosnt Vec2 & other) const { | |
return (*this - other).magnitudeSq(); | |
} | |
Vec2 & normalize () { | |
return *this /= magnitude(); | |
} | |
Vec2 normalized () const { | |
return *this / magnitude(); | |
} | |
bool isNormalized () const { | |
return magnitudeSq() == 1.0f; | |
} | |
friend std::ostream & (std::ostream & os, const Vec2 &v) { | |
return os << "Vec2 { " << v.x << ", " << v.y << " }", os; | |
} | |
}; | |
#undef DEFN_MUT_VECTOR_OP | |
#undef DEFN_MUT_SCALAR_OP | |
#undef DEFN_IMM_VECTOR_OP | |
#undef DEFN_IMM_SCALAR_OP | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment