labyrinth

diff src/mesh.c @ 0:8ba79034e8a6

labyrinth example initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 15 Jan 2015 14:59:38 +0200
parents
children 45b91185b298
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/mesh.c	Thu Jan 15 14:59:38 2015 +0200
     1.3 @@ -0,0 +1,76 @@
     1.4 +#ifdef __APPLE__
     1.5 +#include <GLUT/glut.h>
     1.6 +#elif defined(WIN32)
     1.7 +#include <glut.h>
     1.8 +#else
     1.9 +#include <GL/glut.h>
    1.10 +#endif
    1.11 +
    1.12 +#include "mesh.h"
    1.13 +#include "objfile.h"
    1.14 +
    1.15 +/* use objfile to load mesh data (vertices, normals, and texcoords)
    1.16 + * from a wavefront|OBJ file.
    1.17 + */
    1.18 +struct mesh *load_mesh(const char *fname)
    1.19 +{
    1.20 +	int i;
    1.21 +	struct mesh *m;
    1.22 +	struct objfile *obj;
    1.23 +
    1.24 +	if(!(obj = objf_load(fname))) {
    1.25 +		return 0;
    1.26 +	}
    1.27 +	m = malloc(sizeof *m);
    1.28 +	m->num_verts = objf_vertex_count(obj);
    1.29 +
    1.30 +	m->vert = malloc(m->num_verts * sizeof *m->vert);
    1.31 +	m->norm = malloc(m->num_verts * sizeof *m->norm);
    1.32 +	m->tc = malloc(m->num_verts * sizeof *m->tc);
    1.33 +
    1.34 +	for(i=0; i<m->num_verts; i++) {
    1.35 +		float *v = objf_vertex(obj, i);
    1.36 +		float *n = objf_normal(obj, i);
    1.37 +		float *t = objf_texcoord(obj, i);
    1.38 +
    1.39 +		m->vert[i].x = v[0];
    1.40 +		m->vert[i].y = v[1];
    1.41 +		m->vert[i].z = v[2];
    1.42 +
    1.43 +		m->norm[i].x = n[0];
    1.44 +		m->norm[i].y = n[1];
    1.45 +		m->norm[i].z = n[2];
    1.46 +
    1.47 +		m->tc[i].x = t[0];
    1.48 +		m->tc[i].y = t[1];
    1.49 +	}
    1.50 +	objf_free(obj);
    1.51 +	return m;
    1.52 +}
    1.53 +
    1.54 +void free_mesh(struct mesh *m)
    1.55 +{
    1.56 +	if(m) {
    1.57 +		free(m->vert);
    1.58 +		free(m->norm);
    1.59 +		free(m->tc);
    1.60 +		free(m);
    1.61 +	}
    1.62 +}
    1.63 +
    1.64 +void render_mesh(struct mesh *m)
    1.65 +{
    1.66 +	glEnableClientState(GL_VERTEX_ARRAY);
    1.67 +	glEnableClientState(GL_NORMAL_ARRAY);
    1.68 +	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    1.69 +
    1.70 +	glVertexPointer(3, GL_FLOAT, 0, m->vert);
    1.71 +	glNormalPointer(GL_FLOAT, 0, m->norm);
    1.72 +	glTexCoordPointer(2, GL_FLOAT, 0, m->tc);
    1.73 +
    1.74 +	glDrawArrays(GL_TRIANGLES, 0, m->num_verts);
    1.75 +
    1.76 +	glDisableClientState(GL_VERTEX_ARRAY);
    1.77 +	glDisableClientState(GL_NORMAL_ARRAY);
    1.78 +	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    1.79 +}