ccdemos/common_ply.h
author Radek Brich <radek.brich@devl.cz>
Fri, 02 May 2008 13:27:47 +0200
branchpyrit
changeset 91 9d66d323c354
parent 80 907929fa9b59
child 92 9af5c039b678
permissions -rw-r--r--
packetize Phong shader new scons config options: simd=(yes|no) - allow/suppress explicit SSE force_flags=(yes|no) - force use of specified flags instead of autodetected profile=(yes|no) - enable gcc's profiling (-pg option) check for pthread.h header, don't try to build without it add fourth Vector3 component for better memory aligning rename Vector3 to Vector partialy SSE-ize Vector class (only fully vertical operations) build static lib and python module in distinctive directories to avoid collision of library file names on some platforms

#include <iostream>
#include <fstream>
#include <iomanip>

void load_ply(Raytracer &rt, const char *filename, Material *mat, Vector scale, Vector transp)
{
	vector<NormalVertex*> vertices;
	vector<Vector> normals;
	vector<int> vertex_face_num;
	ifstream f(filename);
	string token = "a";
	if (!f.is_open())
	{
		cout << "File not found: " << filename <<endl;
		exit(1);
	}
	// read header
	int vertex_num, face_num;
	while (token != "end_header")
	{
		f >> token;
		if (token == "element")
		{
			f >> token;
			if (token == "vertex")
				f >> vertex_num;
			if (token == "face")
				f >> face_num;
		}
		f.ignore(1000,'\n');
	}

	// read vertices
	Vector P;
	int num = vertex_num;
	while (num--)
	{
		f >> P.x >> P.y >> P.z;
		P.x = scale.x*P.x + transp.x;
		P.y = scale.y*P.y + transp.y;
		P.z = scale.z*P.z + transp.z;
		vertices.push_back(new NormalVertex(P));
		normals.push_back(Vector());
		vertex_face_num.push_back(0);
		f.ignore(1000,'\n');
	}

	// read faces
	Triangle *face;
	int v1, v2, v3;
	while (face_num--)
	{
		f >> num;
		if (num != 3)
		{
			printf("ply error: faces of %d vertices not supported", num);
			continue;
		}
		f >> v1 >> v2 >> v3;

		// check for invalid faces and ignore them
		if (vertices[v1]->P == vertices[v2]->P
		 || vertices[v1]->P == vertices[v3]->P
		 || vertices[v2]->P == vertices[v3]->P)
		{
			f.ignore(1000,'\n');
			continue;
		}

		face = new Triangle(vertices[v1], vertices[v3], vertices[v2], mat);
		rt.addShape(face);

		normals.at(v1) += face->getNormal();
		vertex_face_num.at(v1)++;
		normals.at(v2) += face->getNormal();
		vertex_face_num.at(v2)++;
		normals.at(v3) += face->getNormal();
		vertex_face_num.at(v3)++;
		f.ignore(1000,'\n');
	}

	for (int i = 0; i < vertex_num; i++)
		if (vertex_face_num.at(i))
		{
			normals.at(i) /= vertex_face_num.at(i);
			normals.at(i).normalize();
			vertices.at(i)->N = normals.at(i);
		}

	f.close();
}