160 lines
1.9 KiB
C++
160 lines
1.9 KiB
C++
#pragma once
|
|
|
|
#include "Matrix.hpp"
|
|
#include <algorithm>
|
|
#include <cmath>
|
|
|
|
|
|
class Vector
|
|
{
|
|
public:
|
|
Vector()
|
|
: x(0), y(0), z(0), w(0)
|
|
{}
|
|
|
|
Vector(float x, float y, float z)
|
|
: x(x), y(y), z(z), w(0)
|
|
{}
|
|
|
|
Vector operator-() const
|
|
{
|
|
return Vector(
|
|
-x,
|
|
-y,
|
|
-z);
|
|
}
|
|
|
|
Vector operator-(Vector const& rhs) const
|
|
{
|
|
return Vector(
|
|
x - rhs.x,
|
|
y - rhs.y,
|
|
z - rhs.z);
|
|
}
|
|
|
|
Vector operator+(Vector const& rhs) const
|
|
{
|
|
return Vector(
|
|
x + rhs.x,
|
|
y + rhs.y,
|
|
z + rhs.z);
|
|
}
|
|
|
|
Vector& operator+=(Vector const& rhs)
|
|
{
|
|
x += rhs.x;
|
|
y += rhs.y;
|
|
z += rhs.z;
|
|
|
|
return *this;
|
|
}
|
|
|
|
Vector operator*(float rhs) const
|
|
{
|
|
return Vector(
|
|
x * rhs,
|
|
y * rhs,
|
|
z * rhs);
|
|
}
|
|
|
|
Vector operator*(Matrix const& rhs)
|
|
{
|
|
Vector result;
|
|
|
|
for (int col = 0; col < 4; ++col)
|
|
{
|
|
float sum = 0.0;
|
|
|
|
for (int row = 0; row < 4; ++row)
|
|
{
|
|
sum += e[row] * rhs.e[row][col];
|
|
}
|
|
|
|
result.e[col] = sum;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
Vector operator/(float rhs) const
|
|
{
|
|
float inverse = 1.0f / rhs;
|
|
|
|
return Vector(
|
|
x * inverse,
|
|
y * inverse,
|
|
z * inverse);
|
|
}
|
|
|
|
Vector& operator/=(float rhs)
|
|
{
|
|
x /= rhs;
|
|
y /= rhs;
|
|
z /= rhs;
|
|
|
|
return *this;
|
|
}
|
|
|
|
float Length()
|
|
{
|
|
float result = sqrtf(x * x + y * y + z * z);
|
|
|
|
if (result < 0.0f)
|
|
{
|
|
result = 0.0f;
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void Normalize()
|
|
{
|
|
float length = Length();
|
|
|
|
if (length == 0.0f)
|
|
{
|
|
x = 0.0f;
|
|
y = 0.0f;
|
|
z = 0.0f;
|
|
}
|
|
else
|
|
{
|
|
float lengthInv = 1.0f / length;
|
|
|
|
x *= lengthInv;
|
|
y *= lengthInv;
|
|
z *= lengthInv;
|
|
}
|
|
}
|
|
|
|
static Vector Cross(Vector& v1, Vector& v2)
|
|
{
|
|
Vector result;
|
|
|
|
result.x = (v1.y * v2.z) - (v1.z * v2.y);
|
|
result.y = (v1.z * v2.x) - (v1.x * v2.z);
|
|
result.z = (v1.x * v2.y) - (v1.y * v2.x);
|
|
|
|
return result;
|
|
}
|
|
|
|
static float Dot(Vector& v1, Vector& v2)
|
|
{
|
|
float result;
|
|
|
|
result = (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
|
|
|
|
return result;
|
|
}
|
|
|
|
union
|
|
{
|
|
float e[4];
|
|
|
|
struct
|
|
{
|
|
float x, y, z, w;
|
|
};
|
|
};
|
|
};
|