Add OBJ file loading

This commit is contained in:
austin committed 2020-07-01 17:42:44 -07:00
1 parent b024d821f5
commit c82f690943
6 files changed
+165 -3

No files matched your search

+13
View File
@@ -1,7 +1,20 @@
#include "engine.h"
#include "loader.h"
// GLOBALS
static Mesh mesh;
int Engine_Init(char *filename)
{
int result = LoadMesh(filename, mesh);
if (result < 0)
{
return -1;
}
return 0;
}
+93
View File
@@ -0,0 +1,93 @@
#include "loader.h"
#include <cctype>
#include <cstdio>
#include <cstring>
// STATIC PROTOTYPES
static char *GetLine(char *buffer, int maxLength, FILE *fp);
// PUBLIC FUNCTIONS
int LoadMesh(char *filename, Mesh &mesh)
{
FILE *fp;
char buffer[256];
char *token;
char garbage[5];
fp = fopen(filename, "r");
if (fp == NULL)
{
fprintf(stderr, "Error loading file: %s\n", filename);
return -1;
}
token = GetLine(buffer, sizeof(buffer), fp);
while (token != NULL)
{
if (token[0] == 'v')
{
Point v;
sscanf(
token, "%s %f %f %f",
garbage,
&v.x,
&v.y,
&v.z);
mesh.verts.push_back(v);
}
else if (token[0] == 'f')
{
Face f;
sscanf(token, "%s %d %d %d",
garbage,
&f.vertIndex[0],
&f.vertIndex[1],
&f.vertIndex[2]);
// Convert to 0-indexed
f.vertIndex[0] -= 1;
f.vertIndex[1] -= 1;
f.vertIndex[2] -= 1;
mesh.faces.push_back(f);
}
token = GetLine(buffer, sizeof(buffer), fp);
}
printf("OBJ: %s\n", filename);
printf("Verts: %lu\n", mesh.verts.size());
printf("Faces: %lu\n", mesh.faces.size());
fclose(fp);
return 0;
}
static char *GetLine(char *buffer, int maxLength, FILE *fp)
{
while(true)
{
if (!fgets(buffer, maxLength, fp))
{
return NULL;
}
// for (length = strlen(buffer), index = 0; isspace(buffer[index]); ++index);
if (buffer[0] != 'v' && buffer[0] != 'f')
{
continue;
}
return buffer;
}
}