#include "stdafx.h"

#include "Scene.hxx"
#include "EyeLightShader.hxx"

//////////////////////////////////////////////////////////////////////////
//TASK: Extend scene.cxx to handle normals and texture coordinates
//////////////////////////////////////////////////////////////////////////

Vec3f vec3fFromStream(std::istream &aStream)
{
	float x, y, z;
	aStream >> x >> y >> z;
	return Vec3f(x, y, z);
}

struct FaceIdcs 
{
	int v[3];
	FaceIdcs()
	{ memset(this, -1, sizeof(*this)); }

	FaceIdcs(std::istream &aStream)
	{ 
		memset(this, -1, sizeof(*this));

		for(int i = 0; i < 3; i++)
		{
			aStream >> v[i] >> std::ws;

			std::string s;
			aStream >> s >> std::ws; //Skip the normal and texture data if present

		//////////////////////////////////////////////////////////////////////////
		//Hint: read eventual normal/texture indices here. Create a new array for the
		//	normal indices and for the texture ones as well.
		//////////////////////////////////////////////////////////////////////////
		}
	}
};


void Scene::ParseOBJ(char *fileName, PrimitiveFactory *aFactory)
{
	cout << "Parsing OBJFile : " << fileName << endl;

	std::ifstream ifile(fileName);

	std::vector<FaceIdcs> faces;
	std::vector<Vec3f> vert;

	while(!ifile.eof())
	{
		std::string curLine;
		std::getline(ifile, curLine);

		std::istringstream issLine(curLine);
		std::string lineType;
		issLine >> std::ws >> lineType;

		if(lineType == "v")
			vert.push_back(vec3fFromStream(issLine));
		else if (lineType == "f")
			faces.push_back(issLine);
		//////////////////////////////////////////////////////////////////////////
		//Hint: Add other types of entities here
		//////////////////////////////////////////////////////////////////////////
	}

	for(std::vector<FaceIdcs>::iterator itFace = faces.begin(); itFace != faces.end(); itFace++)
	{
		Vec3f v[3], vn[3], vt[3];
		for(int i = 0; i < 3; i++)
		{
			v[i] = vert[itFace->v[i] - 1];
			//////////////////////////////////////////////////////////////////////////
			//Hint: cinstruct vn[i] and vt[i] from the face (it)
			//////////////////////////////////////////////////////////////////////////
			vn[i] = Vec3f();
			vt[i] = Vec3f();
		}

		primitive.push_back(aFactory->createPrimitive(
			v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], vt[1], vt[2]
		));
	}

	cout << "Number of Vertices: " << (vert.size() / 3) << endl;
	cout << "Number of Triangles: " << primitive.size() << endl;

	cout << "Finished Parsing" << endl;
}
