-
Notifications
You must be signed in to change notification settings - Fork 8
/
mesh.cpp
84 lines (68 loc) · 2.29 KB
/
mesh.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "mesh.h"
#include <iostream>
#include <fstream>
#include <QFileInfo>
#include <QString>
#define TINYOBJLOADER_IMPLEMENTATION
#include "util/tiny_obj_loader.h"
using namespace Eigen;
using namespace std;
void Mesh::initFromVectors(const vector<Vector3f> &vertices,
const vector<Vector3i> &faces)
{
// Copy vertices and faces into internal vector
_vertices = vertices;
_faces = faces;
}
void Mesh::loadFromFile(const string &filePath)
{
tinyobj::attrib_t attrib;
vector<tinyobj::shape_t> shapes;
vector<tinyobj::material_t> materials;
QFileInfo info(QString(filePath.c_str()));
string err;
bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err,
info.absoluteFilePath().toStdString().c_str(), (info.absolutePath().toStdString() + "/").c_str(), true);
if (!err.empty()) {
cerr << err << endl;
}
if (!ret) {
cerr << "Failed to load/parse .obj file" << endl;
return;
}
for (size_t s = 0; s < shapes.size(); s++) {
size_t index_offset = 0;
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
unsigned int fv = shapes[s].mesh.num_face_vertices[f];
Vector3i face;
for (size_t v = 0; v < fv; v++) {
tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
face[v] = idx.vertex_index;
}
_faces.push_back(face);
index_offset += fv;
}
}
for (size_t i = 0; i < attrib.vertices.size(); i += 3) {
_vertices.emplace_back(attrib.vertices[i], attrib.vertices[i + 1], attrib.vertices[i + 2]);
}
cout << "Loaded " << _faces.size() << " faces and " << _vertices.size() << " vertices" << endl;
}
void Mesh::saveToFile(const string &filePath)
{
ofstream outfile;
outfile.open(filePath);
// Write vertices
for (size_t i = 0; i < _vertices.size(); i++)
{
const Vector3f &v = _vertices[i];
outfile << "v " << v[0] << " " << v[1] << " " << v[2] << endl;
}
// Write faces
for (size_t i = 0; i < _faces.size(); i++)
{
const Vector3i &f = _faces[i];
outfile << "f " << (f[0]+1) << " " << (f[1]+1) << " " << (f[2]+1) << endl;
}
outfile.close();
}