-
Notifications
You must be signed in to change notification settings - Fork 0
/
rlobj.c
620 lines (516 loc) · 19.7 KB
/
rlobj.c
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// rlobj (c) Nikolas Wipper 2021
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0, with exemptions for Ramon Santamaria and the
* raylib contributors who may, at their discretion, instead license
* any of the Covered Software under the zlib license. If a copy of
* the MPL was not distributed with this file, You can obtain one
* at https://mozilla.org/MPL/2.0/. */
#include "rlobj.h"
#include <rlgl.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
typedef struct Edge { int vertex; int texcoord; int normal; } Edge;
typedef struct Face { Edge edges[3]; } Face;
typedef struct OBJMesh {
Mesh mesh;
unsigned long mat_hash;
} OBJMesh;
typedef struct OBJMat {
char *base;
Vector3 ambient, diffuse, specular;
float opacity;
char *ambient_map, *diffuse_map, *specular_map, *highlight_map, *alpha_map, *bump_map, *displacement_map, *decal_map, *reflection_map;
unsigned long name_hash;
} OBJMat;
typedef struct ValidFloat { float f; bool valid; } ValidFloat;
typedef struct ValidInt { int i; bool valid; } ValidInt;
typedef struct ValidEdge { Edge e; bool valid; } ValidEdge;
typedef struct ValidVec3 { Vector3 v; bool valid; } ValidVec3;
typedef struct GenericFile {
char *data;
} GenericFile;
typedef struct OBJFile {
char *base;
GenericFile data;
Vector3 *vertices, *normals;
Vector2 *texcoords;
Face *faces;
int vertex_count;
int texcoord_count;
int normal_count;
int face_count;
bool triangulation_warning;
OBJMat *mats;
int mat_count;
} OBJFile;
unsigned long hash(unsigned char *str) {
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
char *PutStringOnHeap(const char *string) {
size_t string_len = strlen(string);
if (string_len == 0) return NULL;
char *res = RL_CALLOC(strlen(string) + 1, sizeof(string));
strcpy(res, string);
return res;
}
char *AddBase(char *path, const char *base) {
if (path[0] == '/') return path;
size_t path_len = strlen(path), base_len = strlen(base);
path = RL_REALLOC(path, sizeof(char) * (path_len + base_len + 2));
memmove(path + base_len + 1, path, path_len + 1);
memcpy(path, base, base_len);
path[base_len] = '/';
return path;
}
// Generic reader functions
void IgnoreLine(GenericFile *file) {
for (; *file->data != '\n' && *file->data != '\0'; file->data++);
file->data++;
}
// Clears all whitespaces
// Returns false if the line ended
// This helps prevent reading two lines as one statement
bool ClearWhitespace(GenericFile *file) {
for (; *file->data == '\n' || isspace(*file->data);) {
if (*file->data == '\n') { // Don't read over unexpected line break, this prevents invalidation of the next line
return false;
}
file->data++;
}
return true;
}
char *ReadName(GenericFile *file) {
ClearWhitespace(file);
char *data_cpy = file->data;
for (; *data_cpy != '\n' && *data_cpy != '\0'; data_cpy++);
char *name = RL_CALLOC(data_cpy - file->data + 1, sizeof(char));
int i;
for (i = 0; !isspace(file->data[i]) && file->data[i] != '\0'; i++) {
name[i] = file->data[i];
}
file->data += i;
return name;
}
float ReadFloat(GenericFile *file) {
float res = 0.f, fact = 1.f;
bool point_seen = false;
if (*file->data == '-') {
file->data++;
fact = -1;
}
for (; *file->data; file->data++) {
if (*file->data == '.') {
point_seen = true;
continue;
}
unsigned char c = *file->data - '0';
if (c > 9) break; // same as isdigit(*file->data), but faster because we can use c later
if (point_seen) fact /= 10.f;
res = res * 10.f + (float) c;
}
return res * fact;
}
ValidFloat ReadValidFloat(GenericFile *file) {
if (!ClearWhitespace(file))
return (ValidFloat) {.f = 0.f, .valid = false};
float vX = ReadFloat(file);
return (ValidFloat) {.f = vX, .valid = true};
}
float ReadFloatDefault(GenericFile *file, float def) {
if (ClearWhitespace(file) && isdigit(*file->data)) {
def = ReadFloat(file);
}
return def;
}
int ReadInt(GenericFile *file) {
int res = 0;
for (; *file->data; file->data++) {
unsigned char c = *file->data - '0';
if (c > 9) break; // same as isdigit(*file->data), but faster because we can use c later
res = res * 10 + c;
}
return res;
}
ValidInt ReadValidInt(GenericFile *file) {
if (!ClearWhitespace(file))
return (ValidInt) {.i = 0, .valid = false};
int i = ReadInt(file);
return (ValidInt) {.i = i, .valid = true};
}
int ReadIntDefault(GenericFile *file, int def) {
if (ClearWhitespace(file) && isdigit(*file->data)) {
def = ReadInt(file);
}
return def;
}
ValidVec3 ReadColor(GenericFile *file) {
ValidFloat r = ReadValidFloat(file);
ValidFloat g = ReadValidFloat(file);
ValidFloat b = ReadValidFloat(file);
if (r.valid && g.valid && b.valid)
return (ValidVec3) {.v = {.x = r.f, .y = g.f, .z = b.f}, .valid = true};
return (ValidVec3) {.v = {0}, .valid = false};
}
OBJMat LoadMtlMat(GenericFile *file) {
bool seen_newmtl = false;
OBJMat mat = {0};
mat.opacity = 1.f;
while (*file->data) {
if (*file->data == 'K') {
file->data++;
if (*file->data == 'a') {
file->data++;
ValidVec3 a = ReadColor(file);
if (a.valid) mat.ambient = a.v;
} else if (*file->data == 'd') {
file->data++;
ValidVec3 d = ReadColor(file);
if (d.valid) mat.diffuse = d.v;
} else if (*file->data == 's') {
file->data++;
ValidVec3 s = ReadColor(file);
if (s.valid) mat.specular = s.v;
}
} else if (*file->data == 'd') {
file->data++;
ValidFloat o = ReadValidFloat(file);
if (o.valid) mat.opacity = o.f;
if (mat.opacity > 1) mat.opacity = 1;
} else if (strncmp(file->data, "newmtl", 6) == 0) {
if (seen_newmtl) break;
seen_newmtl = true;
file->data += 6;
char *name = ReadName(file);
mat.name_hash = hash((unsigned char *) name);
RL_FREE(name);
} else if (strncmp(file->data, "map_", 4) == 0) {
file->data += 4;
if (*file->data == 'K') {
file->data++;
if (*file->data == 'a') {
file->data++;
RL_FREE(mat.ambient_map);
mat.ambient_map = ReadName(file);
} else if (*file->data == 'd') {
file->data++;
RL_FREE(mat.diffuse_map);
mat.diffuse_map = ReadName(file);
} else if (*file->data == 's') {
file->data++;
RL_FREE(mat.specular_map);
mat.specular_map = ReadName(file);
}
} else if (*file->data == 'd') {
file->data++;
RL_FREE(mat.alpha_map);
mat.alpha_map = ReadName(file);
} else if (strncmp(file->data, "Ns", 2) == 0) {
file->data += 2;
RL_FREE(mat.highlight_map);
mat.highlight_map = ReadName(file);
} else if (strncmp(file->data, "bump", 4) == 0 || strncmp(file->data, "Bump", 4) == 0) { // Somewhat bad practice, but acceptable for now
file->data += 4;
RL_FREE(mat.bump_map);
mat.bump_map = ReadName(file);
}
} else if (strncmp(file->data, "bump", 4) == 0) {
file->data += 4;
RL_FREE(mat.bump_map);
mat.bump_map = ReadName(file);
} else if (strncmp(file->data, "disp", 4) == 0) {
file->data += 4;
RL_FREE(mat.displacement_map);
mat.displacement_map = ReadName(file);
} else if (strncmp(file->data, "decal", 5) == 0) {
file->data += 5;
RL_FREE(mat.decal_map);
mat.decal_map = ReadName(file);
} else if (strncmp(file->data, "refl", 4) == 0) {
file->data += 4;
RL_FREE(mat.reflection_map);
mat.reflection_map = ReadName(file);
}
IgnoreLine(file);
}
return mat;
}
char *ReadMtl(OBJFile *file, char *filename) {
if (file->base) filename = AddBase(filename, file->base);
char *data = LoadFileText(filename);
if (!data) { return filename; }
GenericFile mtl = (GenericFile) {.data = data};
const char *base = GetPrevDirectoryPath(filename);
while (*mtl.data) {
file->mats = (OBJMat *) RL_REALLOC(file->mats, sizeof(OBJMat) * ++file->mat_count);
file->mats[file->mat_count - 1] = LoadMtlMat(&mtl);
file->mats[file->mat_count - 1].base = PutStringOnHeap(base);
}
UnloadFileText(data);
return filename;
}
// OBJ specific reader functions
void ReadVertex(OBJFile *file) {
ValidFloat vX = ReadValidFloat(&file->data);
ValidFloat vY = ReadValidFloat(&file->data);
ValidFloat vZ = ReadValidFloat(&file->data);
if (!(vX.valid && vY.valid && vZ.valid)) { return; }
ReadFloatDefault(&file->data, 1.f); // value ignored
file->vertices = (Vector3 *) RL_REALLOC(file->vertices, sizeof(Vector3) * ++file->vertex_count);
int vc = file->vertex_count - 1;
file->vertices[vc].x = vX.f;
file->vertices[vc].y = vY.f;
file->vertices[vc].z = vZ.f;
}
void ReadTextureCoord(OBJFile *file) {
ValidFloat tU = ReadValidFloat(&file->data);
float tV = ReadFloatDefault(&file->data, 0.f);
ReadFloatDefault(&file->data, 0.f); // value ignored
if (!tU.valid) { return; }
file->texcoords = (Vector2 *) RL_REALLOC(file->texcoords, sizeof(Vector2) * ++file->texcoord_count);
int tc = file->texcoord_count - 1;
file->texcoords[tc].x = tU.f;
file->texcoords[tc].y = tV;
}
void ReadNormal(OBJFile *file) {
ValidFloat nX = ReadValidFloat(&file->data);
ValidFloat nY = ReadValidFloat(&file->data);
ValidFloat nZ = ReadValidFloat(&file->data);
if (!(nX.valid && nY.valid && nZ.valid)) { return; }
file->normals = (Vector3 *) RL_REALLOC(file->normals, sizeof(Vector3) * ++file->normal_count);
int nc = file->normal_count - 1;
file->normals[nc].x = nX.f;
file->normals[nc].y = nY.f;
file->normals[nc].z = nZ.f;
}
#define InvalidEdge (ValidEdge){(Edge){0,0,0}, false}
ValidEdge ReadEdge(GenericFile *file) {
Edge e = {0};
ValidInt v = ReadValidInt(file);
if (!v.valid) { return InvalidEdge; }
e.vertex = v.i;
if (*file->data == '/') {
file->data++;
int vt = ReadIntDefault(file, 0);
if (*file->data == '/') {
file->data++;
ValidInt vn = ReadValidInt(file);
if (!vn.valid) {
return InvalidEdge;
}
e.texcoord = vt == 0 ? 1 : vt; // a 0 index isn't valid, but not setting the value is
e.normal = vn.i;
} else {
if (vt == 0) { // a 0 index isn't valid and a single '/' without a value isn't either
return InvalidEdge;
}
e.texcoord = 1;
e.normal = vt;
}
}
return (ValidEdge) {e, true};
}
void ReadFace(OBJFile *file) {
Face f;
for (int i = 0; i < 3; i++) {
ValidEdge vE = ReadEdge(&file->data);
if (vE.valid)
f.edges[i] = vE.e;
else return;
}
file->faces = (Face *) RL_REALLOC(file->faces, sizeof(Face) * ++file->face_count);
int fc = file->face_count - 1;
file->faces[fc] = f;
ClearWhitespace(&file->data);
// Naïve triangulation
while (isdigit(*file->data.data)) {
if (!file->triangulation_warning) {
TraceLog(LOG_WARNING, "MESH: Triangulation is only very basic. Try doing that in your modeling software.");
file->triangulation_warning = true;
}
file->faces = (Face *) RL_REALLOC(file->faces, sizeof(Face) * ++file->face_count);
f.edges[1] = f.edges[2];
ValidEdge vE = ReadEdge(&file->data);
if (vE.valid) {
f.edges[2] = vE.e;
f.edges[2] = vE.e;
file->faces[++fc] = f;
} else return;
ClearWhitespace(&file->data);
}
}
OBJMesh LoadObjMesh(OBJFile *file) {
unsigned long mat_hash;
bool seen_o = false;
while (*file->data.data) {
if (*file->data.data == 'v') {
if (isspace(*(++file->data.data))) {
file->data.data++;
ReadVertex(file);
} else if (*file->data.data == 't') {
file->data.data++;
ReadTextureCoord(file);
} else if (*file->data.data == 'n') {
file->data.data++;
ReadNormal(file);
}
} else if (*file->data.data == 'f') {
file->data.data++;
ReadFace(file);
} else if (*file->data.data == 'o') {
if (seen_o) break;
seen_o = true;
} else if (strncmp(file->data.data, "usemtl", 6) == 0) {
file->data.data += 6;
char *name = ReadName(&file->data);
mat_hash = hash((unsigned char *) name);
RL_FREE(name);
} else if (strncmp(file->data.data, "mtllib", 6) == 0) {
file->data.data += 6;
char *name = ReadName(&file->data);
RL_FREE(ReadMtl(file, name));
}
IgnoreLine(&file->data);
}
Mesh m = (Mesh) {0};
if (file->vertex_count != 0) {
if (!file->texcoord_count || !file->texcoords) {
file->texcoords = (Vector2 *) RL_CALLOC(file->vertex_count, sizeof(Vector2)); // all texcoords will be 0,0
}
if (!file->normal_count || !file->normals) {
file->normals = (Vector3 *) RL_CALLOC(file->vertex_count, sizeof(Vector3)); // all normals will be 0,0,0
}
m.vertexCount = file->face_count * 3;
m.triangleCount = (int) file->face_count;
m.vertices = (float *) RL_CALLOC(m.vertexCount * 3, sizeof(float));
m.texcoords = (float *) RL_CALLOC(m.vertexCount * 2, sizeof(float));
m.normals = (float *) RL_CALLOC(m.vertexCount * 3, sizeof(float));
// Sort vertices, texcoords and normals
for (int i = 0; i < file->face_count; i++) {
for (int j = 0; j < 3; j++) {
int vIn = file->faces[i].edges[j].vertex - 1;
int tIn = file->faces[i].edges[j].texcoord - 1;
int nIn = file->faces[i].edges[j].normal - 1;
// Three vertices per face, three floats per vertex
m.vertices[i * 9 + j * 3] = file->vertices[vIn].x;
m.vertices[i * 9 + j * 3 + 1] = file->vertices[vIn].y;
m.vertices[i * 9 + j * 3 + 2] = file->vertices[vIn].z;
// Three coords per face, two floats per coords
m.texcoords[i * 6 + j * 2] = file->texcoords[tIn].x;
m.texcoords[i * 6 + j * 2 + 1] = 1.f - file->texcoords[tIn].y; // raylib flips textures upside down
// Three normals per face, three floats per normal
m.normals[i * 9 + j * 3] = file->normals[nIn].x;
m.normals[i * 9 + j * 3 + 1] = file->normals[nIn].y;
m.normals[i * 9 + j * 3 + 2] = file->normals[nIn].z;
}
}
}
return (OBJMesh) {.mesh = m, .mat_hash = mat_hash};
}
Color Vector3ToColor(Vector3 vec, float opacity) {
return (Color) {
.r = (char) roundf(vec.x * 255.f), .g = (char) roundf(vec.y * 255.f), .b = (char) roundf(vec.z * 255.f), .a = (char) roundf(opacity * 255.f)
};
}
Texture LoadTextureBase(char *filename, char *base) {
Texture res;
if (base) filename = AddBase(filename, base);
res = LoadTexture(filename);
RL_FREE(filename);
return res;
}
// Wrapper around read LoadObjMesh and LoadMtlMat
// Loads model without uploading meshes
Model LoadObjDry(const char *filename) {
char *data = LoadFileText(filename);
if (!data) return (Model) {0};
OBJMesh *meshes = NULL;
int mesh_count = 0;
OBJFile file = (OBJFile) {0};
file.data.data = data;
file.base = PutStringOnHeap(GetPrevDirectoryPath(filename));
while (*file.data.data) {
meshes = (OBJMesh *) RL_REALLOC(meshes, sizeof(OBJMesh) * ++mesh_count);
meshes[mesh_count - 1] = LoadObjMesh(&file);
file.face_count = 0;
RL_FREE(file.faces);
file.faces = NULL;
}
UnloadFileText(data);
RL_FREE(file.vertices);
RL_FREE(file.texcoords);
RL_FREE(file.normals);
Model model = {0};
model.transform = (Matrix) {
1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f
};
model.meshes = (Mesh *) RL_CALLOC(mesh_count, sizeof(Mesh));
model.meshCount = mesh_count;
model.materialCount = file.mat_count;
model.materials = RL_CALLOC(file.mat_count, sizeof(Material));
model.meshMaterial = RL_CALLOC(mesh_count, sizeof(int));
for (int i = 0; i < file.mat_count; i++) {
Material m = LoadMaterialDefault();
OBJMat names = file.mats[i];
m.maps[MATERIAL_MAP_ALBEDO].color = Vector3ToColor(names.diffuse, names.opacity);
m.maps[MATERIAL_MAP_METALNESS].color = Vector3ToColor(names.specular, names.opacity);
// if-check here, to prevent replacing default textures
// These are used to display .color values even if no image is present
if (names.diffuse_map) m.maps[MATERIAL_MAP_ALBEDO].texture = LoadTextureBase(names.diffuse_map, names.base);
else
RL_FREE(names.diffuse_map);
// NOTE: I'm not totally sure which one is right, but for raylib specular is the same as "metalness" so that's what
// we are using if both are defined
if (names.reflection_map) m.maps[MATERIAL_MAP_METALNESS].texture = LoadTextureBase(names.reflection_map, names.base);
else
RL_FREE(names.reflection_map);
if (names.specular_map) {
if (rlGetTextureIdDefault() != m.maps[MATERIAL_MAP_METALNESS].texture.id)
UnloadTexture(m.maps[MATERIAL_MAP_METALNESS].texture);
m.maps[MATERIAL_MAP_METALNESS].texture = LoadTextureBase(names.specular_map, names.base);
} else
RL_FREE(names.specular_map);
if (names.highlight_map) m.maps[MATERIAL_MAP_ROUGHNESS].texture = LoadTextureBase(names.highlight_map, names.base);
else
RL_FREE(names.highlight_map);
if (names.bump_map) m.maps[MATERIAL_MAP_NORMAL].texture = LoadTextureBase(names.bump_map, names.base);
else
RL_FREE(names.bump_map);
// Free unused maps (used ones are freed in LoadTextureBase because of reallocates)
RL_FREE(names.alpha_map);
RL_FREE(names.ambient_map);
RL_FREE(names.decal_map);
RL_FREE(names.displacement_map);
model.materials[i] = m;
}
for (int i = 0; i < mesh_count; i++) {
for (int j = 0; j < file.mat_count; j++) {
if (file.mats[j].name_hash == meshes[i].mat_hash)
model.meshMaterial[i] = j;
}
model.meshes[i] = meshes[i].mesh;
}
RL_FREE(meshes);
RL_FREE(file.mats);
RL_FREE(file.base);
return model;
}
// Wrapper around LoadObjDry
// This basically does the same job as LoadMaterial does for LoadOBJ
Model LoadObj(const char *filename) {
Model obj = LoadObjDry(filename);
if (obj.materialCount == 0) {
obj.materialCount = 1;
obj.materials = RL_CALLOC(1, sizeof(Material));
obj.materials[0] = LoadMaterialDefault();
}
for (int i = 0; i < obj.meshCount; i++) {
UploadMesh(&obj.meshes[i], false);
}
return obj;
}