#include "flyingCamera.h"

// ----------------------------------------------------------------------------------------------------------------------------

CCamera::CCamera()
{
	ViewMatrix = NULL;

	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	Position = vec3(0.0f, 1.75f, 0.0f);
}

void CCamera::rotateWithMouse(int cx, int cy)
{
	float Sensitivity = 0.25f;

	float deltaX = (float)cx * Sensitivity;
	float deltaY = (float)cy * Sensitivity;

	if(deltaX != 0.0f)
	{
		X = rotate(X, deltaX, vec3(0.0f, 1.0f, 0.0f));
		Y = rotate(Y, deltaX, vec3(0.0f, 1.0f, 0.0f));
		Z = rotate(Z, deltaX, vec3(0.0f, 1.0f, 0.0f));
	}

	if(deltaY != 0.0f)
	{
		Y = rotate(Y, deltaY, X);
		Z = rotate(Z, deltaY, X);

		if(Y.y < 0.0f)
		{
			Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
			Y = cross(Z, X);
		}
	}

	look();
}

void CCamera::update(float FrameTime)
{
	float Speed = 5.0f;

	if(GetKeyState(VK_SHIFT) & 0x80)
	{
		Speed *= 2.0f;
	}

	float Distance = Speed * FrameTime;

	vec3 Up(0.0f, 1.0f, 0.0f);
	vec3 Right = X;
	vec3 Forward = cross(Up, Right);

	Up *= Distance;
	Right *= Distance;
	Forward *= Distance;

	vec3 Movement;

	if(GetKeyState('W') & 0x80) Movement += Forward;
	if(GetKeyState('S') & 0x80) Movement -= Forward;
	if(GetKeyState('A') & 0x80) Movement -= Right;
	if(GetKeyState('D') & 0x80) Movement += Right;
	if(GetKeyState('R') & 0x80) Movement += Up;
	if(GetKeyState('F') & 0x80) Movement -= Up;

	if(Movement.x != 0.0f || Movement.y != 0.0f || Movement.z != 0.0f)
	{
		Position += Movement;

		look();
	}
}

void CCamera::look()
{
	if(ViewMatrix != NULL)
	{
		*ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
	}
}

void CCamera::SetViewMatrixPointer(mat4x4 *ViewMatrix)
{
	this->ViewMatrix = ViewMatrix;

	look();
}