c++ - Opengl obj object loader with textures -


i using object loader load obj model exported blender. can load model none of textures loaded , don't know why. should loaded when render model in main class or need load textures rendering model?

objloader.cpp

/************************************************************ *loads obj file - limited vertices, faces, normals, texture maps *loads object structure defined in .h file ************************************************************/  #include <stdio.h> #include <iostream> #include <io.h> #include <stdlib.h> #include "glut.h"  #include "objloader.h"  using namespace std;  void object_type::render() {     glbegin(gl_triangles); // glbegin , glend delimit vertices define primitive (in our case triangles)      (int j=0;j<polygons_qty;j++)     {         //----------------- first vertex -----------------         //normal coordinates of first vertex         glnormal3f( normcoord[ polygon[j].n[0] - 1 ].i,                 normcoord[ polygon[j].n[0] - 1 ].j,                 normcoord[ polygon[j].n[0] - 1 ].k);         // texture coordinates of first vertex             gltexcoord2f( mapcoord[ polygon[j].t[0] - 1 ].u,                   mapcoord[ polygon[j].t[0] - 1 ].v);         // coordinates of first vertex         glvertex3f( vertex[ polygon[j].v[0] - 1].x,                 vertex[ polygon[j].v[0] - 1].y,                 vertex[ polygon[j].v[0] - 1].z);          //----------------- second vertex -----------------         //normal coordinates of first vertex         glnormal3f( normcoord[ polygon[j].n[1] - 1 ].i,                 normcoord[ polygon[j].n[1] - 1 ].j,                 normcoord[ polygon[j].n[1] - 1 ].k);         // texture coordinates of first vertex         gltexcoord2f( mapcoord[ polygon[j].t[1] - 1 ].u,                   mapcoord[ polygon[j].t[1] - 1 ].v);         // coordinates of first vertex         glvertex3f( vertex[ polygon[j].v[1] - 1].x,                 vertex[ polygon[j].v[1] - 1].y,                 vertex[ polygon[j].v[1] - 1].z);          //----------------- third vertex -----------------         //normal coordinates of first vertex         glnormal3f( normcoord[ polygon[j].n[2] - 1 ].i,                 normcoord[ polygon[j].n[2] - 1 ].j,                 normcoord[ polygon[j].n[2] - 1 ].k);         // texture coordinates of first vertex         gltexcoord2f( mapcoord[ polygon[j].t[2] - 1 ].u,                   mapcoord[ polygon[j].t[2] - 1 ].v);         // coordinates of first vertex         glvertex3f( vertex[ polygon[j].v[2] - 1].x,                 vertex[ polygon[j].v[2] - 1].y,                 vertex[ polygon[j].v[2] - 1].z);     }     glend(); }   /* vertex_type vertex[max_vertices];  mapcoord_type mapcoord[max_vertices]; normcoord_type normcoord[max_normals]; polygon_type polygon[max_polygons]; int id_texture */   int object_type::objdatadisplay() {    int i;    printf("vertices: %d\n",vertices_qty);  (i =0;i<vertices_qty;i++)  {      printf("%f %f %f\n",vertex[i].x,vertex[i].y,vertex[i].z);  }     printf("normals: %d\n",normcoord_qty);  (i =0;i<normcoord_qty;i++) {      printf("%f %f %f\n",normcoord[i].i,normcoord[i].j,normcoord[i].k); }    printf("map coords: %d\n",mapcoord_qty); (i =0;i<mapcoord_qty;i++) {      printf("%f %f\n",mapcoord[i].u,mapcoord[i].v); }    printf("polygons: %d\n",polygons_qty);  (i=0;i<polygons_qty;i++) //for each vertex of polygon (triangle) {     (int j = 0;j<3;j++)     {                 printf("%d::%d/%d/%d\n",i,polygon[i].v[j],polygon[i].t[j],polygon[i].n[j]);     } } return 1; }   int object_type::objloader(char *p_filename) {     int ivertex=0; //index variable     int inormal =0;     int ipolygon=0;     int imap=0;     char string[256]; file *l_file; //file pointer  char l_char; //char variable  unsigned short l_face_flags; //flag stores face information  if ((l_file=fopen (p_filename, "rt"))== null) return 0; //open file   while (!feof(l_file)) //loop scan whole file  {     fscanf(l_file,"%c",&l_char);     if(l_char=='\n')//read char if'/n' -skip next , read            fscanf(l_file,"%c",&l_char);     switch (l_char) //parse     {        default: fgets(string,256,l_file);         break;     case 'v':   //a vertex or normal or text co-ord         fscanf(l_file,"%c",&l_char);         switch (l_char)           {         case ' ':   //a vertex -expect , read 3 floats next               fscanf(l_file,"%f %f %f",&vertex[ivertex].x, &vertex[ivertex].y,&vertex[ivertex].z);                 ivertex++;               break;         case 'n': //a normal -expect , read 3 floats next               fscanf(l_file,"%f %f %f",&normcoord[inormal].i, &normcoord[inormal].j,&normcoord[inormal].k);               inormal++;               break;         case 't': //a texture map coord-expect , read 2 floats next               fscanf(l_file,"%f %f",&mapcoord[imap].u, &mapcoord[imap].v);               imap++;               break;         }  //end switch         break;     case 'f': //a face read next assume format -> f 1/1/1 2/2/2 3/3/3         (int i=0;i<3;i++) //for each vertex of polygon (triangle)         {              fscanf(l_file,"%c",&l_char); //read space char - ignore              fscanf(l_file,"%d",&polygon[ipolygon].v[i]); //read vertex.              fscanf(l_file,"%c",&l_char); //read space char - ignore              fscanf(l_file,"%d",&polygon[ipolygon].t[i]); //read text coord.              fscanf(l_file,"%c",&l_char); //read space char - ignore              fscanf(l_file,"%d",&polygon[ipolygon].n[i]); //read normal.         }         ipolygon++;         break;      } //end switch }  fclose (l_file); // closes file stream vertices_qty = ivertex; polygons_qty = ipolygon; mapcoord_qty = imap; normcoord_qty = inormal;  return 1;  //if successful     } 

objloader.h

#ifndef objload #define objload  /************************************************ *loads obj file - limited vertices, faces, normals, texture maps *loads object structure defined in .h file ****************************************************/   #define max_vertices 8000 // max number of vertices (for each object) #define max_polygons 8000 // max number of polygons (for each object) #define max_normals 8000 // max number of polygons (for each object)  // our vertex type typedef struct{ float x,y,z; }vertex_type;  // our normal type typedef struct{ float i,j,k; }normcoord_type;  // polygon (triangle), 3 numbers aim 3 vertices typedef struct{ int v[3],t[3],n[3]; }polygon_type;  // mapcoord type, 2 texture coordinates each vertex typedef struct{ float u,v; }mapcoord_type;  // object type class object_type{ public: int id_texture;  object_type(){} ~object_type(){} int objloader(char *p_filename);  int objdatadisplay(); void render();  private: char name[20]; int vertices_qty; int polygons_qty; int mapcoord_qty; int normcoord_qty;  vertex_type vertex[max_vertices];  mapcoord_type mapcoord[max_vertices]; normcoord_type normcoord[max_normals]; polygon_type polygon[max_polygons];  }; #endif 

main.cpp

#include "objloader.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gl/glew.h>  #ifdef __win32__ #include <windows.h> #endif  #include "glut.h"  //glut has ogl relevant .h files included   int screen_width=800; int screen_height=600;  //angle of rotation float xpos = 0, ypos = 0, zpos = 0, xrot = 0, yrot = 0, angle=0.0;  float cradius = 10.0f; // our radius distance our character  float lastx, lasty;  object_type *objarray[2];  //objects container our world. used throughout global  //lights settings glfloat light_ambient[]= { 0.1f, 0.1f, 0.1f, 0.1f }; glfloat light_diffuse[]= { 1.0f, 1.0f, 1.0f, 0.0f }; glfloat light_specular[]= { 1.0f, 1.0f, 1.0f, 0.0f }; glfloat light_position[]= { 100.0f, 0.0f, -10.0f, 1.0f };  //materials settings glfloat mat_ambient[]= { 0.5f, 0.5f, 0.0f, 0.0f }; glfloat mat_diffuse[]= { 0.5f, 0.5f, 0.0f, 0.0f }; glfloat mat_specular[]= { 1.0f, 1.0f, 1.0f, 0.0f }; glfloat mat_shininess[]= { 1.0f };   /************************************  *  * subroutine init(void)  *  * used initialize opengl , setup our world  * ************************************/  void init(void) {     glclearcolor(0.0, 0.0, 0.0, 0.0); // clear background color black      // viewport transformation     glviewport(0,0,screen_width,screen_height);        // projection transformation     glmatrixmode(gl_projection); // specifies matrix stack target matrix operations      glloadidentity(); // initialize projection matrix identity     gluperspective(45.0f,(glfloat)screen_width/(glfloat)screen_height,5.0f,10000.0f);        //lights initialization , activation     gllightfv (gl_light1, gl_ambient, light_ambient);     gllightfv (gl_light1, gl_diffuse, light_diffuse);     gllightfv (gl_light1, gl_diffuse, light_specular);     gllightfv (gl_light1, gl_position, light_position);         glenable (gl_light1);     glenable (gl_lighting);      //materials initialization , activation glmaterialfv (gl_front, gl_ambient, mat_ambient);     glmaterialfv (gl_front, gl_diffuse, mat_diffuse);     glmaterialfv (gl_front, gl_diffuse, mat_specular);     glmaterialfv (gl_front, gl_position, mat_shininess);      //other initializations     glshademodel(gl_smooth); // type of shading polygons glhint (gl_perspective_correction_hint, gl_nicest); // texture mapping perspective correction     glenable(gl_texture_2d); // texture mapping on     glpolygonmode (gl_front_and_back, gl_fill); // polygon rasterization mode (polygon filled) glenable(gl_cull_face); // enable face culling     glenable(gl_depth_test); // enable depth test   gltranslatef(0.0f, 0.0f, -cradius);     glrotatef(xrot,1.0,0.0,0.0);  angle++; //increase angle  (int i=0;i<2;i++) { printf("*************\n");     objarray[i] = new (object_type);     objarray[i]->objloader("c:/3dmodels/museum.obj");     objarray[i]->objdatadisplay();       }  }   /**********************************************************  *  * subroutine resize(int p_width, int p_height)  *  * routine must called everytime resize our window.  *  * input parameters: p_width = width in pixels of our viewport  *                   p_height = height in pixels of our viewport  *   *********************************************************/  void resize (int p_width, int p_height) { if (screen_width==0 && screen_height==0) exit(0);     screen_width=p_width; // obtain new screen width values , store     screen_height=p_height; // height value      glclear (gl_color_buffer_bit | gl_depth_buffer_bit); // clear both color , depth buffer draw next frame     glviewport(0,0,screen_width,screen_height); // viewport transformation      glmatrixmode(gl_projection); // projection transformation     glloadidentity(); // initialize projection matrix identity     gluperspective(45.0f,(glfloat)screen_width/(glfloat)screen_height,5.0f,10000.0f);      glutpostredisplay (); // command redraw scene (it calls same routine of glutdisplayfunc) }  /**********************************************************  *  * subroutine keyboard(void)  *  * subroutine handle keyboard input  *   *********************************************************/   void keyboard (unsigned char key, int x, int y) {     if (key=='q')     {     xrot += 1;     if (xrot >360) xrot -= 360;     }      if (key=='z')     {     xrot -= 1;  if (xrot < -360) xrot += 360;     }      if (key=='w')     {     float xrotrad, yrotrad;     yrotrad = (yrot / 180 * 3.141592654f);     xrotrad = (xrot / 180 * 3.141592654f);      xpos += float(sin(yrotrad));     zpos -= float(cos(yrotrad));     ypos -= float(sin(xrotrad));     }      if (key=='s')     {     float xrotrad, yrotrad;     yrotrad = (yrot / 180 * 3.141592654f);     xrotrad = (xrot / 180 * 3.141592654f);      xpos -= float(sin(yrotrad));     zpos += float(cos(yrotrad));     ypos += float(sin(xrotrad));     }      if (key=='d')     {     float yrotrad;     yrotrad = (yrot / 180 * 3.141592654f);     xpos += float(cos(yrotrad)) * 0.2;     zpos += float(sin(yrotrad)) * 0.2;     }      if (key=='a')     {     float yrotrad;     yrotrad = (yrot / 180 * 3.141592654f);     xpos -= float(cos(yrotrad)) * 0.2;     zpos -= float(sin(yrotrad)) * 0.2;     }      if (key==27)     {     exit(0);     } }  /**********************************************************  *  * subroutine mousemovement(void)  *  * subroutine handle mouse input  *   *********************************************************/  void mousemovement(int x, int y) { int diffx=x-lastx; //check difference between current x , last x position int diffy=y-lasty; //check difference between current y , last y position lastx=x; //set lastx current x position lasty=y; //set lasty current y position xrot += (float) diffy; //set xrot xrot addition of difference in y position yrot += (float) diffx;    //set xrot yrot addition of difference in x position }   /**********************************************************  *  * subroutine display(void)  *  * our main rendering subroutine, called each frame  *   *********************************************************/  void display(void) {      glclear(gl_color_buffer_bit | gl_depth_buffer_bit); // clear background color dark blue     glmatrixmode(gl_modelview); // modeling transformation     glpushmatrix(); glloadidentity(); // initialize model matrix identity      gltranslatef(0.0f, 0.0f, -cradius); // move object forward (the model matrix multiplied translation matrix)     glrotatef(xrot,1.0,0.0,0.0); // rotations of object (the model matrix multiplied rotation matrices)      glrotatef(yrot,0.0,1.0,0.0);  gltranslated(-xpos,0.0f,-zpos); //translate screen position of our camera   if (objarray[0]->id_texture!=-1)  {     glbindtexture(gl_texture_2d, objarray[0]->id_texture); // set active texture      glenable(gl_texture_2d); // texture mapping on     printf("txt map on"); } else     gldisable(gl_texture_2d); // texture mapping off   objarray[0]->render(); glpopmatrix(); glpushmatrix(); gltranslatef(5.0,0.0,-20.0); glflush(); // force execution of opengl commands glutswapbuffers(); // in double buffered mode invert positions of visible buffer , writing buffer }    /**********************************************************  *  * main routine  *   *********************************************************/   int main(int argc, char **argv) {     // use glut utility initialize window, handle input , interact windows system     glutinit(&argc, argv);         glutinitdisplaymode(glut_double | glut_rgb | glut_depth);     glutinitwindowsize(screen_width,screen_height);     glutinitwindowposition(0,0);     glutcreatewindow("demo 1: exit press esc");         glutdisplayfunc(display);     glutidlefunc(display);     glutreshapefunc (resize);  glutpassivemotionfunc(mousemovement); //check mouse movement glutkeyboardfunc (keyboard);   init();     glutmainloop();      return(0);     } 

example obj blender, cube.obj:

# blender v2.66 (sub 1) obj file: 'cube.blend' # www.blender.org mtllib cube.mtl g cube v 1.000000 0.665869 -1.000000 v 1.000000 0.665869 1.000000 v -1.000000 0.665869 1.000000 v -1.000000 0.665869 -1.000000 v 1.000000 2.665869 -0.999999 v 0.999999 2.665869 1.000001 v -1.000000 2.665869 1.000000 v -1.000000 2.665869 -1.000000 vt 0.000000 0.334353 vt 0.332314 0.333333 vt 0.333333 0.665647 vt 1.000000 0.001019 vt 0.998981 0.333333 vt 0.666667 0.332314 vt 1.000000 0.665647 vt 0.667686 0.666667 vt 0.334353 0.666667 vt 0.333333 0.334353 vt 0.666667 0.665647 vt 0.333333 0.332314 vt 0.001020 0.333333 vt 0.332314 0.000000 vt 0.333333 0.001019 vt 0.665647 0.000000 vt 0.001019 0.666667 vt 0.667686 0.000000 vt 0.666667 0.334353 vt 0.665647 0.333333 vt 0.000000 0.001020 vt 0.334353 0.333333 vn 0.000000 -1.000000 0.000000 vn -0.000000 1.000000 0.000000 vn 1.000000 -0.000000 0.000001 vn -0.000000 -0.000000 1.000000 vn -1.000000 -0.000000 -0.000000 vn 0.000000 0.000000 -1.000000 vn 1.000000 0.000000 -0.000000 usemtl material s off f 1/1/1 2/2/1 3/3/1 f 5/4/2 8/5/2 7/6/2 f 1/5/3 5/7/3 6/8/3 f 2/9/4 6/10/4 3/11/4 f 3/12/5 7/13/5 4/14/5 f 5/15/6 1/16/6 4/6/6 f 4/17/1 1/1/1 3/3/1 f 6/18/2 5/4/2 7/6/2 f 2/19/7 1/5/7 6/8/7 f 6/10/4 7/20/4 3/11/4 f 7/13/5 8/21/5 4/14/5 f 8/22/6 5/15/6 4/6/6 

your obj loader doesn't attempt parse mtl files.

you'll have add mtl handling yourself.

you'll want support map_kd.

good luck.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -