-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIO_OBJ.cpp
346 lines (322 loc) · 14 KB
/
IO_OBJ.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#include "IO_OBJ.hpp"
#include "IO_core.hpp"
#include "GeometryUtils.hpp"
#include "Strings.hpp"
#include <CGAL/Polyhedron_incremental_builder_3.h>
#include <exception>
#include <stdexcept>
// OBJ File References:
// http://en.wikipedia.org/wiki/Wavefront_.obj_file
// http://www.martinreddy.net/gfx/3d/OBJ.spec
#ifdef _MSC_VER
#pragma region Writing OBJ Files
#endif
void write_obj_file(const char* filename, const std::map<std::string, Polyhedron3*>& P, bool as_objects, const std::string& matfile, const std::vector<std::string>& mtls)
{
std::ofstream f(filename);
f << "# OBJ File saved from geoEM" << std::endl << std::endl;
size_t off = 0;
write_obj_file(f, P, off, as_objects, matfile, mtls);
f.close();
}
void write_obj_file(std::ostream &out, const std::map<std::string, Polyhedron3*>& P, size_t& off, bool as_objects, const std::string& matfile, const std::vector<std::string>& mtls)
{
size_t i = 0;
if (matfile != "") { out << "mtllib " << matfile << std::endl << std::endl; }
// TODO: handle no-name and "default" polyhedrons (possibly not even necessary)
for (std::map<std::string, Polyhedron3*>::const_iterator itr = P.begin(), end = P.end(); itr != end; ++itr, ++i)
{
out << (as_objects ? "o " : "g ") << itr->first << std::endl;
if (mtls.size() > i) { out << "usemtl " << mtls[i] << std::endl; }
write_obj(out, itr->second, off);
}
}
void write_obj_file(const char* filename, const std::vector<Polyhedron3*>& P, bool as_objects, const std::string& matfile, const std::vector<std::string>& mtls)
{
std::ofstream f(filename);
f << "# OBJ File saved from geoEM" << std::endl << std::endl;
size_t off = 0;
write_obj_file(f, P, off, as_objects, matfile, mtls);
f.close();
}
void write_obj_file(std::ostream &out, const std::vector<Polyhedron3*>& P, size_t& off, bool as_objects, const std::string& matfile, const std::vector<std::string>& mtls)
{
size_t i = 0;
if (matfile != "") { out << "mtllib " << matfile << std::endl << std::endl; }
for (std::vector<Polyhedron3*>::const_iterator itr = P.begin(), end = P.end(); itr != end; ++itr, ++i)
{
out << (as_objects ? "o obj" : "g obj") << i << std::endl;
if (mtls.size() > i) { out << "usemtl " << mtls[i] << std::endl; }
write_obj(out, *itr, off);
}
}
void write_obj_file(const char* filename, const Polyhedron3* P)
{
size_t off = 0;
std::ofstream f(filename);
f << "# OBJ File saved from geoEM" << std::endl << std::endl;
write_obj(f, P, off);
f.close();
}
void write_obj(std::ostream &out, const Polyhedron3* P)
{
size_t off = 0;
write_obj(out, P, off);
}
void write_obj(std::ostream &out, const Polyhedron3* P, size_t& off)
{
// Write vertices
handle_map<Polyhedron3::Vertex_const_handle, size_t> verts(P->size_of_vertices());
for (Polyhedron3::Vertex_const_iterator V = P->vertices_begin(), Vend = P->vertices_end(); V != Vend; ++V)
{
const Point3& p = V->point();
out << "v " << p.x() << " " << p.y() << " " << p.z() << std::endl;
verts.insert(std::make_pair(V, off++));
}
// Write faces
for (Polyhedron3::Facet_const_iterator F = P->facets_begin(), Fend = P->facets_end(); F != Fend; ++F)
{
out << "f";
Polyhedron3::Halfedge_around_facet_const_circulator H = F->facet_begin(), Hstart = H;
do { out << " " << verts[H->vertex()] + 1; } while (++H != Hstart);
out << std::endl;
}
out << std::endl;
}
#ifdef _MSC_VER
#pragma endregion
#endif
#ifdef _MSC_VER
#pragma region Reading OBJ Files
#endif
class ObjFileDetail : public VertexReader, public CGAL::Modifier_base<Polyhedron3::HalfedgeDS>
{
private:
typedef Polyhedron3::HalfedgeDS HDS;
typedef HDS::Vertex Vertex;
typedef CGAL::Polyhedron_incremental_builder_3<HDS> Builder;
typedef std::vector<size_t> facet;
struct raw_mesh
{
std::string name;
std::vector<size_t> facets;
};
typedef std::list<raw_mesh> raw_meshes;
typedef std::map<std::string, raw_meshes::iterator> name_lookup;
inline static raw_meshes::iterator get_entry(const char *name, name_lookup &lookup, raw_meshes &meshes)
{
name_lookup::const_iterator i = lookup.find(name);
if (i != lookup.end()) { return i->second; }
raw_meshes::iterator x = meshes.insert(meshes.end(), raw_mesh());
lookup.insert(i, name_lookup::value_type(name, x));
return x;
}
std::vector<raw_meshes::iterator> g(char *params)
{
std::vector<raw_meshes::iterator> grps;
char *name = strtok(params, " \t\v");
while (name != nullptr)
{
grps.push_back(get_entry(name, this->grp_lookup, this->grps));
name = strtok(nullptr, " \t\v");
}
if (grps.size() == 0) { grps.push_back(get_entry("default", this->grp_lookup, this->grps)); }
return grps;
}
raw_meshes::iterator o(const char *params) { return get_entry(params, this->obj_lookup, this->objs); }
facet f_v(char *s, bool has_vt, bool has_vn)
{
facet f;
ssize_t v;
while (str_read_int(s, &s, &v) && // read "v"
((!has_vt && !has_vn) || *s++ == '/') &&
(!has_vt || str_skip_int(s, &s)) && // skip "vt"
(!has_vn || (*s == '/' && str_skip_int(s+1, &s))) && // skip "vn"
(!*s || isspace(*s)))
{
// Add vertex to facet
if (v == 0 || (size_t)CGAL::abs(v) > this->vertices.size()) { break; }
f.push_back((v > 0) ? v - 1 : v + this->vertices.size());
s = ltrim(s);
if (!*s) { if (f.size() < 3) { break; } return f; } // Finished
}
throw std::invalid_argument("Error: invalid OBJ file format");
}
facet f(char *params)
{
// At least 3 points
// Each point is of one of the following forms, and in a face all points have the same form
// v, v/vt, v//vn, v/vt/vn
// Call the proper function for the given form by parsing the first vertex
char *s = params;
if (str_skip_int(s, &s))
{
if (isspace(*s)) { return f_v(params, false, false); } // v
else if (*s++ == '/')
{
if (*s == '/' && str_skip_int(s+1, &s)) { return f_v(params, false, true); } // v//vn
else if (str_skip_int(s, &s))
{
if (isspace(*s)) { return f_v(params, true, false); } // v/vt
else if (*s == '/' && str_skip_int(s+1, &s) && isspace(*s)) { return f_v(params, true, true); } // v/vt/vn
}
}
}
throw std::invalid_argument("Error: invalid OBJ file format");
}
inline static bool o_matches(const char *params, const char* obj_name) { return strcmp(params, obj_name) == 0; }
inline static bool g_matches(char *params, const char* grp_name) { char *name = strtok(params, " "); while (name != nullptr) { if (strcmp(name, grp_name) == 0) { return true; } name = strtok(nullptr, " "); } return false; }
std::vector<facet> facets;
raw_meshes objs;
raw_meshes grps;
name_lookup obj_lookup;
name_lookup grp_lookup;
raw_meshes::iterator current;
struct Current
{
raw_meshes::iterator obj;
std::vector<raw_meshes::iterator> grps;
Current(raw_meshes::iterator o, raw_meshes::iterator g) : obj(o), grps(1, g) {}
};
virtual void parse_cmd(const char* cmd, char* params, void* extra)
{
Current* cur = (Current*)extra;
switch (tolower(cmd[0]))
{
// v and vn are already done, need to read the faces into each group/object and validate ignored commands
case 'o':
if (cmd[1] == '\0') { cur->obj = o(params); }
else { throw std::invalid_argument("Error: OBJ file contains unimplemented commands"); }
break;
case 'g':
if (cmd[1] == '\0') { cur->grps = g(params); }
else { throw std::invalid_argument("Error: OBJ file contains unimplemented commands"); }
break;
case 'f':
if (cmd[1] == '\0' || strieq(cmd+1, "o")) // TODO: validation
{
facet f = this->f(params);
size_t fi = this->facets.size();
this->facets.push_back(f);
cur->obj->facets.push_back(fi);
for (size_t i = 0, len = cur->grps.size(); i < len; ++i)
cur->grps[i]->facets.push_back(fi);
}
else { throw std::invalid_argument("Error: OBJ file contains unimplemented commands"); }
break;
default:
if (!strieq(cmd, "vt") && !strieq(cmd, "s") && !strieq(cmd, "p") && !strieq(cmd, "l") &&
!strieq(cmd, "mtllib") && !strieq(cmd, "usemtl") && !strieq(cmd, "maplib") && !strieq(cmd, "usemap") &&
!strieq(cmd, "bevel") && !strieq(cmd, "c_interp") && !strieq(cmd, "d_interp") && !strieq(cmd, "log") && !strieq(cmd, "shadow_obj") && !strieq(cmd, "trace_obj"))
{
throw std::invalid_argument("Error: OBJ file contains unimplemented commands");
}
// else they are purposely ignored commands (materials, rendering tips, etc)
}
}
void build(std::istream& in)
{
// Initialize
Current cur(get_entry("", this->obj_lookup, this->objs), get_entry("default", this->grp_lookup, this->grps));
this->init(in, &cur);
// Remove default names if they are empty
if (this->objs.front().facets.size() == 0) { this->objs.pop_front(); this->obj_lookup.erase(""); }
if (this->grps.front().facets.size() == 0) { this->grps.pop_front(); this->grp_lookup.erase("default"); }
// Remove excess allocated data
for (auto i = this->objs.begin(), end = this->objs.end(); i != end; ++i) { i->facets.shrink_to_fit(); }
for (auto i = this->grps.begin(), end = this->grps.end(); i != end; ++i) { i->facets.shrink_to_fit(); }
this->facets.shrink_to_fit();
}
public:
ObjFileDetail(const char *filename)
{
std::ifstream in(filename, std::ifstream::binary);
this->build(in);
}
ObjFileDetail(std::istream& in) { this->build(in); }
inline const size_t count_objects() const { return this->objs.size(); }
inline const size_t count_groups() const { return this->grps.size(); }
const std::vector<std::string> object_names() const
{
std::vector<std::string> names;
names.reserve(this->objs.size());
for (auto i = this->obj_lookup.begin(), end = this->obj_lookup.end(); i != end; ++i) { names.push_back(i->first); }
return names;
}
const std::vector<std::string> group_names() const
{
std::vector<std::string> names;
names.reserve(this->grps.size());
for (auto i = this->grp_lookup.begin(), end = this->grp_lookup.end(); i != end; ++i) { names.push_back(i->first); }
return names;
}
void set_current(size_t i, bool as_object)
{
raw_meshes& rm = as_object ? this->objs : this->grps;
if (i >= rm.size()) { std::invalid_argument("Error: index out of range in OBJ file"); }
raw_meshes::iterator x = rm.begin();
std::advance(x, i);
this->current = x;
}
void set_current(const std::string& name, bool as_object)
{
name_lookup& nl = as_object ? this->obj_lookup : this->grp_lookup;
name_lookup::iterator x = nl.find((name.empty() || name == "default") ? (as_object ? "" : "default") : name);
if (x == nl.end()) { throw std::invalid_argument("Error: name doesn't exist in OBJ file"); }
this->current = x->second;
}
void operator()(HDS& hds)
{
// Builds the polyhedron
// Setup basic variables
Builder b(hds, true);
size_t total_faces = this->current->facets.size(), total_vertices = 0;
// Calculate the vertices and their new indices
for (std::vector<size_t>::const_iterator i = this->current->facets.begin(), end = this->current->facets.end(); i != end; ++i)
{
total_vertices += this->facets[*i].size();
}
// Create the surface
// TODO: need to calculate the actual set of vertices we want to keep in the mesh and the new vertex offsets
b.begin_surface(total_vertices, total_faces);
for (size_t i = 0, len = this->vertices.size(); i < len; ++i)
{
b.add_vertex(this->vertices[i]);
}
for (std::vector<size_t>::const_iterator i = this->current->facets.begin(), end = this->current->facets.end(); i != end; ++i)
{
b.begin_facet();
facet& f = this->facets[*i];
for (size_t j = 0; j < f.size(); ++j) { b.add_vertex_to_facet(f[j]); }
b.end_facet();
}
b.end_surface();
#ifndef POLYHEDRON_USE_VECTOR
// Remove all the vertices we added that weren't part of faces
// This is going to be either 0 for single group files or massive for multiple-group files
assert(b.remove_unconnected_vertices());
#endif
}
};
ObjFile::ObjFile(const char *filename, bool as_objects) : _as_objects(as_objects), detail(new ObjFileDetail(filename)) { }
ObjFile::ObjFile(std::istream& in, bool as_objects) : _as_objects(as_objects), detail(new ObjFileDetail(in)) { }
ObjFile::~ObjFile() { if (this->detail) { delete this->detail; this->detail = nullptr; } }
const std::vector<std::string> ObjFile::names() const { return this->_as_objects ? this->detail->object_names() : this->detail->group_names(); }
size_t ObjFile::size() const { return this->_as_objects ? this->detail->count_objects() : this->detail->count_groups(); }
Polyhedron3* ObjFile::operator[](const std::string& name) const
{
this->detail->set_current(name, this->_as_objects);
Polyhedron3 *P = new Polyhedron3();
P->delegate(*this->detail);
return P;
}
Polyhedron3* ObjFile::operator[](size_t i) const
{
this->detail->set_current(i, this->_as_objects);
Polyhedron3 *P = new Polyhedron3();
P->delegate(*this->detail);
return P;
}
#ifdef _MSC_VER
#pragma endregion
#endif