2021-11-25 15:00:20 +01:00
|
|
|
#include "IO.h"
|
|
|
|
#include <stdexcept>
|
|
|
|
using namespace std;
|
|
|
|
|
|
|
|
void MeshReconstruction::WriteObjFile(Mesh const& mesh, string const& fileName)
|
|
|
|
{
|
|
|
|
// FILE faster than streams.
|
|
|
|
|
2017-05-12 03:04:43 +02:00
|
|
|
FILE* file = fopen(fileName.c_str(), "w");
|
2021-11-25 15:00:20 +01:00
|
|
|
if (file == NULL)
|
|
|
|
{
|
|
|
|
throw runtime_error("Could not write obj file.");
|
|
|
|
}
|
|
|
|
|
|
|
|
// write stats
|
|
|
|
fprintf(file, "# %d vertices, %d triangles\n\n",
|
|
|
|
static_cast<int>(mesh.vertices.size()),
|
|
|
|
static_cast<int>(mesh.triangles.size()));
|
|
|
|
|
|
|
|
// vertices
|
2017-05-12 03:04:43 +02:00
|
|
|
for (size_t vi = 0; vi < mesh.vertices.size(); ++vi)
|
2021-11-25 15:00:20 +01:00
|
|
|
{
|
|
|
|
auto const& v = mesh.vertices.at(vi);
|
|
|
|
fprintf(file, "v %f %f %f\n", v.x, v.y, v.z);
|
|
|
|
}
|
|
|
|
|
|
|
|
// vertex normals
|
|
|
|
fprintf(file, "\n");
|
2017-05-12 03:04:43 +02:00
|
|
|
for (size_t ni = 0; ni < mesh.vertices.size(); ++ni)
|
2021-11-25 15:00:20 +01:00
|
|
|
{
|
|
|
|
auto const& vn = mesh.vertexNormals.at(ni);
|
|
|
|
fprintf(file, "vn %f %f %f\n", vn.x, vn.y, vn.z);
|
|
|
|
}
|
|
|
|
|
|
|
|
// triangles (1-based)
|
|
|
|
fprintf(file, "\n");
|
2017-05-12 03:04:43 +02:00
|
|
|
for (size_t ti = 0; ti < mesh.triangles.size(); ++ti)
|
2021-11-25 15:00:20 +01:00
|
|
|
{
|
|
|
|
auto const& t = mesh.triangles.at(ti);
|
|
|
|
fprintf(file, "f %d//%d %d//%d %d//%d\n",
|
|
|
|
t[0] + 1, t[0] + 1,
|
|
|
|
t[1] + 1, t[1] + 1,
|
|
|
|
t[2] + 1, t[2] + 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
fclose(file);
|
2017-05-12 03:04:43 +02:00
|
|
|
}
|