# include <math.h>
# include <stdio.h>
# include <iostream>
# include <fstream>
# include "app_window.h"
# include "texture.h"
# include <sys/types.h>
# include <sys/timeb.h>

const double pi = 3.14159265;

//function to load texture from bitmap image 
GLuint loadTexture(char* file) {
	std::ifstream File(file, std::ios::in | std::ios::binary);
	if (File.is_open()) {
		GLuint texture = 0;
		unsigned int fileSize = 0;
		unsigned int size = 0;
		unsigned int width = 0;
		unsigned int height = 0;
		//read positions of file
		File.seekg(2);
		File.read((char *)&fileSize, 4);
		File.seekg(18);
		File.read((char *)&width, 4);
		File.read((char *)&height, 4);
		File.seekg(54);
		size = fileSize - 54;
		//load pixel data into array
		unsigned char* data = new unsigned char[size];
		File.read((char*)data, size);
		File.close();
		unsigned char* data1; 
		data1 = new unsigned char[size];
		for (int i = 0; i < size; i += 3) {
			data1[i + 2] = data[i];
			data1[i + 1] = data[i + 1];
			data1[i] = data[i + 2];
		}
		glGenTextures(1, &texture);
		glBindTexture(GL_TEXTURE_2D, texture);
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);																
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, data1);
		delete[] data1;
		delete[] data;
		return texture;
	}
	//could not read file
	std::cout << "ERROR\n";
	return 0;
}
//this function return the time using sys/timeb.h and sys/types.h
double getTime() {
	_timeb timer;
	_ftime_s(&timer);
	double time = 0.001*(double)timer.millitm + (double)timer.time;
	return time;

}
//sets the color of a material using R G B, and alpha
void setColor(float r, float g, float b, float a) {
	float color[4];
	color[0] = r;
	color[1] = g;
	color[2] = b;
	color[3] = a;
	glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color);
}