-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjloader.cpp
More file actions
432 lines (364 loc) · 12.8 KB
/
objloader.cpp
File metadata and controls
432 lines (364 loc) · 12.8 KB
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*
Original code from Tutorials - 7
Modified to add helper function getTextureNameFromObj
*/
#include <vector>
#include <stdio.h>
#include <string>
#include <cstring>
#include <glm/glm.hpp>
#include <objloader.hpp>
#include <mesh.hpp>
// Include AssImp
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <iostream>
// Very, VERY simple OBJ loader.
bool loadOBJ(
const char* path,
std::vector<glm::vec3>& out_vertices,
std::vector<glm::vec2>& out_uvs,
std::vector<glm::vec3>& out_normals
) {
printf("Loading OBJ file %s...\n", path);
std::vector<unsigned int> vertexIndices, uvIndices, normalIndices;
std::vector<glm::vec3> temp_vertices;
std::vector<glm::vec2> temp_uvs;
std::vector<glm::vec3> temp_normals;
FILE* file;
fopen_s(&file, path, "r");
if (file == NULL) {
printf("Impossible to open the file ! Are you in the right path ?\n");
getchar();
return false;
}
while (1) {
char lineHeader[128];
int res = fscanf(file, "%s", lineHeader);
if (res == EOF)
break; // EOF = End Of File. Quit the loop.
if (strcmp(lineHeader, "v") == 0) {
glm::vec3 vertex;
fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
temp_vertices.push_back(vertex);
}
else if (strcmp(lineHeader, "vt") == 0) {
glm::vec2 uv;
fscanf(file, "%f %f\n", &uv.x, &uv.y);
uv.y = 1.0f - uv.y;
// uv.y = -uv.y; // We'll handle this in the texture loader or shader
temp_uvs.push_back(uv);
}
else if (strcmp(lineHeader, "vn") == 0) {
glm::vec3 normal;
fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z);
temp_normals.push_back(normal);
}
else if (strcmp(lineHeader, "f") == 0) {
std::string vertex1, vertex2, vertex3;
unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);
if (matches != 9) {
// Try a different format (without normals)
matches = fscanf(file, "%d/%d %d/%d %d/%d\n", &vertexIndex[0], &uvIndex[0], &vertexIndex[1], &uvIndex[1], &vertexIndex[2], &uvIndex[2]);
if (matches != 6) {
// Try a different format (without uvs)
matches = fscanf(file, "%d//%d %d//%d %d//%d\n", &vertexIndex[0], &normalIndex[0], &vertexIndex[1], &normalIndex[1], &vertexIndex[2], &normalIndex[2]);
if (matches != 6) {
printf("File can't be read by our simple parser :-( Try exporting with other options\n");
fclose(file);
return false;
}
// No UVs provided, add dummy UVs
uvIndex[0] = uvIndex[1] = uvIndex[2] = 0;
}
else {
// No normals provided, add dummy normals
normalIndex[0] = normalIndex[1] = normalIndex[2] = 0;
}
}
vertexIndices.push_back(vertexIndex[0]);
vertexIndices.push_back(vertexIndex[1]);
vertexIndices.push_back(vertexIndex[2]);
uvIndices.push_back(uvIndex[0]);
uvIndices.push_back(uvIndex[1]);
uvIndices.push_back(uvIndex[2]);
normalIndices.push_back(normalIndex[0]);
normalIndices.push_back(normalIndex[1]);
normalIndices.push_back(normalIndex[2]);
}
else {
// Probably a comment, eat up the rest of the line
char stupidBuffer[1000];
fgets(stupidBuffer, 1000, file);
}
}
// For each vertex of each triangle
for (unsigned int i = 0; i < vertexIndices.size(); i++) {
// Get the indices of its attributes
unsigned int vertexIndex = vertexIndices[i];
unsigned int uvIndex = uvIndices[i];
unsigned int normalIndex = normalIndices[i];
// Get the attributes thanks to the index
// Note: We check for 0 index (dummy)
glm::vec3 vertex = (vertexIndex == 0) ? glm::vec3(0, 0, 0) : temp_vertices[vertexIndex - 1];
glm::vec2 uv = (uvIndex == 0) ? glm::vec2(0, 0) : temp_uvs[uvIndex - 1];
glm::vec3 normal = (normalIndex == 0) ? glm::vec3(0, 0, 1) : temp_normals[normalIndex - 1];
// Put the attributes in buffers
out_vertices.push_back(vertex);
out_uvs.push_back(uv);
out_normals.push_back(normal);
}
fclose(file);
return true;
}
// ********************************************************************
// * NEW HELPER FUNCTION IMPLEMENTATION
// ********************************************************************
std::string getTextureNameFromObj(const char* obj_path) {
std::string mtl_filename = "";
// --- 1. Open the .OBJ file to find the .MTL file ---
FILE* obj_file;
fopen_s(&obj_file, obj_path, "r");
if (obj_file == NULL) {
printf("Impossible to open the .obj file!\n");
return "";
}
printf("Parsing .obj file to find .mtl...\n");
while (1) {
char lineHeader[128];
int res = fscanf(obj_file, "%s", lineHeader);
if (res == EOF)
break;
if (strcmp(lineHeader, "mtllib") == 0) {
char mtl_buffer[128];
fscanf(obj_file, "%s\n", mtl_buffer);
mtl_filename = std::string(mtl_buffer);
break; // Found it
}
else {
// Eat up the rest of the line
char stupidBuffer[1000];
fgets(stupidBuffer, 1000, obj_file);
}
}
fclose(obj_file);
if (mtl_filename == "") {
printf("No 'mtllib' line found in .obj file.\n");
return "";
}
printf("Found material file: %s\n", mtl_filename.c_str());
// --- 2. Open the .MTL file to find the texture ---
// This assumes the .mtl file is in the same directory as the .obj
// A more robust solution would handle file paths
FILE* mtl_file;
fopen_s(&mtl_file, mtl_filename.c_str(), "r");
if (mtl_file == NULL) {
printf("Impossible to open the .mtl file!\n");
return "";
}
printf("Parsing .mtl file to find 'map_Kd'...\n");
std::string texture_filename = "";
while (1) {
char lineHeader[128];
int res = fscanf(mtl_file, "%s", lineHeader);
if (res == EOF)
break;
if (strcmp(lineHeader, "map_Kd") == 0) {
// 'map_Kd' is the diffuse texture
char tex_buffer[128];
fscanf(mtl_file, "%s\n", tex_buffer);
texture_filename = std::string(tex_buffer);
break; // Found it
}
else {
// Eat up the rest of the line
char stupidBuffer[1000];
fgets(stupidBuffer, 1000, mtl_file);
}
}
fclose(mtl_file);
if (texture_filename == "") {
printf("No 'map_Kd' line found in .mtl file.\n");
return "";
}
printf("Found texture file: %s\n", texture_filename.c_str());
return texture_filename;
}
#ifdef USE_ASSIMP
// don't use this #define, it's only for me (it AssImp fails to compile on your machine, at least all the other tutorials still work)
// Include AssImp
#include <assimp/Importer.hpp> // C++ importer interface
#include <assimp/scene.h> // Output data structure
#include <assimp/postprocess.h> // Post processing flags
bool loadAssImp(
const char* path,
std::vector<unsigned short>& indices,
std::vector<glm::vec3>& vertices,
std::vector<glm::vec2>& uvs,
std::vector<glm::vec3>& normals
) {
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path, 0/*aiProcess_JoinIdenticalVertices | aiProcess_SortByPType*/);
if (!scene) {
fprintf(stderr, importer.GetErrorString());
getchar();
return false;
}
const aiMesh* mesh = scene->mMeshes[0]; // In this simple example code we always use the 1rst mesh (in OBJ files there is often only one anyway)
// Fill vertices positions
vertices.reserve(mesh->mNumVertices);
for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
aiVector3D pos = mesh->mVertices[i];
vertices.push_back(glm::vec3(pos.x, pos.y, pos.z));
}
// Fill vertices texture coordinates
uvs.reserve(mesh->mNumVertices);
// ************* FIX WAS HERE *************
// The loop should start from 0, not an uninitialized variable.
for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
if (mesh->HasTextureCoords(0)) { // Check if texture coordinates exist
aiVector3D UVW = mesh->mTextureCoords[0][i]; // Assume only 1 set of UV coords; AssImp supports 8 UV sets.
uvs.push_back(glm::vec2(UVW.x, UVW.y));
}
else {
uvs.push_back(glm::vec2(0.0f, 0.0f)); // Add dummy UVs if none exist
}
}
// Fill vertices normals
normals.reserve(mesh->mNumVertices);
for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
if (mesh->HasNormals()) {
aiVector3D n = mesh->mNormals[i];
normals.push_back(glm::vec3(n.x, n.y, n.z));
}
else {
normals.push_back(glm::vec3(0.0f, 0.0f, 1.0f)); // Add dummy normals if none exist
}
}
// Fill face indices
indices.reserve(3 * mesh->mNumFaces);
for (unsigned int i = 0; i < mesh->mNumFaces; i++) {
// Assume the model has only triangles.
indices.push_back(mesh->mFaces[i].mIndices[0]);
indices.push_back(mesh->mFaces[i].mIndices[1]);
indices.push_back(mesh->mFaces[i].mIndices[2]);
}
// The "scene" pointer will be deleted automatically by "importer"
return true;
}
#endif
extern GLuint loadBMP_custom(const char* path);
// This will process one 'aiMesh' and create one 'GameObject'
static GameObject* processMesh(aiMesh* mesh, const aiScene* scene, const std::string& directory) {
std::vector<glm::vec3> vertices;
std::vector<glm::vec2> uvs;
std::vector<glm::vec3> normals;
std::vector<glm::vec3> tangents;
std::vector<glm::vec3> bitangents;
GLuint textureID = 0; // Default no texture
glm::vec3 objCenter = glm::vec3(0.0f);
// 1. Process Vertices, Normals, and UVs
for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
vertices.push_back(glm::vec3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z));
objCenter += vertices.back();
if (mesh->HasNormals()) {
normals.push_back(glm::vec3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z));
}
else {
normals.push_back(glm::vec3(0.0f, 0.0f, 0.0f));
}
if (mesh->mTextureCoords[0]) {
uvs.push_back(glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y));
}
else {
uvs.push_back(glm::vec2(0.0f, 0.0f));
}
if (mesh->HasTangentsAndBitangents()) {
tangents.push_back(glm::vec3(mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z));
bitangents.push_back(glm::vec3(mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z));
}
else {
tangents.push_back(glm::vec3(0.0f));
bitangents.push_back(glm::vec3(0.0f));
}
}
// 2. Process Indices (we need to flatten them for glDrawArrays)
std::vector<glm::vec3> final_vertices;
std::vector<glm::vec2> final_uvs;
std::vector<glm::vec3> final_normals;
std::vector<glm::vec3> final_tangents;
std::vector<glm::vec3> final_bitangents;
for (unsigned int i = 0; i < mesh->mNumFaces; i++) {
aiFace face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; j++) {
unsigned int index = face.mIndices[j];
final_vertices.push_back(vertices[index]);
final_uvs.push_back(uvs[index]);
final_normals.push_back(normals[index]);
final_tangents.push_back(tangents[index]);
final_bitangents.push_back(bitangents[index]);
}
}
// 3. Process Textures
if (mesh->mMaterialIndex >= 0) {
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
// Just load the first diffuse texture
if (material->GetTextureCount(aiTextureType_DIFFUSE) > 0) {
aiString str;
material->GetTexture(aiTextureType_DIFFUSE, 0, &str);
std::string filename = std::string(str.C_Str());
//std::string full_path = directory + '/' + filename;
std::string full_path = filename;
printf("Loading texture for mesh: %s\n", full_path.c_str());
textureID = loadBMP_custom(full_path.c_str());
printf("Texture ID: %d\n", textureID);
}
}
objCenter /= (float)mesh->mNumVertices;
//printf("Object center: (%f, %f, %f)\n", objCenter.x, objCenter.y, objCenter.z);
string meshName = mesh->mName.C_Str();
// only for walls
GLuint normalMapId = 0;
if(meshName.rfind("walls") == 0) {
normalMapId = loadBMP_custom("textures/normal.png");
}
// 4. Create the GameObject using our NEW constructor
GameObject* obj = new GameObject(
final_vertices, final_uvs, final_normals,
final_tangents, final_bitangents,
textureID, normalMapId, objCenter
);
// 5. set the light id
if(meshName.rfind("light.") == 0) {
int id = -1;
if(sscanf(meshName.c_str(), "light.%d", &id) == 1) {
obj->lightID = id;
}
}
return obj;
}
// loads a scene using AssImp and returns a vector of GameObjects from single .obj file
std::vector<GameObject*> loadScene(const std::string& path) {
std::vector<GameObject*> objectsInScene;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path,
aiProcess_Triangulate |
aiProcess_FlipUVs |
aiProcess_CalcTangentSpace
);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
std::cerr << "ASSIMP ERROR: " << importer.GetErrorString() << std::endl;
return objectsInScene;
}
// Get the directory of the file (for textures)
std::string directory = path.substr(0, path.find_last_of('/'));
// Loop through ALL meshes in the scene
for (unsigned int i = 0; i < scene->mNumMeshes; i++) {
aiMesh* ai_mesh = scene->mMeshes[i];
// Create a GameObject for each mesh
objectsInScene.push_back(processMesh(ai_mesh, scene, directory));
}
return objectsInScene;
}