root/OpenSceneGraph/trunk/src/osgPlugins/obj/glm.cpp @ 3284

Revision 3284, 56.1 kB (checked in by robert, 10 years ago)

Fix to order of materials

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/*   
2 *  Wavefront .obj file format reader.
3 *
4 *  author: Nate Robins
5 *  email: ndr@pobox.com
6 *  www: http://www.pobox.com/~ndr
7 */
8
9
10/* includes */
11#include "glm.h"
12#include <math.h>
13#include <stdio.h>
14#include <string.h>
15#include <assert.h>
16#include <osg/Math>
17#include <stdlib.h>
18
19#include <osg/Math>
20
21
22/* defines */
23#define T(x) model->triangles[(x)]
24
25
26/* enums */
27enum { X, Y, Z, W };            /* elements of a vertex */
28
29
30/* typedefs */
31
32/* _GLMnode: general purpose node
33 */
34typedef struct _GLMnode {
35  unsigned int           index;
36  GLboolean        averaged;
37  struct _GLMnode* next;
38} GLMnode;
39
40
41/* private functions */
42
43/* _glmMax: returns the maximum of two floats */
44static GLfloat
45_glmMax(GLfloat a, GLfloat b)
46{
47  if (a > b)
48    return a;
49  return b;
50}
51
52/* _glmAbs: returns the absolute value of a float */
53static GLfloat
54_glmAbs(GLfloat f)
55{
56  if (f < 0)
57    return -f;
58  return f;
59}
60
61/* _glmDot: compute the dot product of two vectors
62 *
63 * u - array of 3 GLfloats (GLfloat u[3])
64 * v - array of 3 GLfloats (GLfloat v[3])
65 */
66static GLfloat
67_glmDot(GLfloat* u, GLfloat* v)
68{
69  assert(u);
70  assert(v);
71
72  /* compute the dot product */
73  return u[X] * v[X] + u[Y] * v[Y] + u[Z] * v[Z];
74}
75
76/* _glmCross: compute the cross product of two vectors
77 *
78 * u - array of 3 GLfloats (GLfloat u[3])
79 * v - array of 3 GLfloats (GLfloat v[3])
80 * n - array of 3 GLfloats (GLfloat n[3]) to return the cross product in
81 */
82static GLvoid
83_glmCross(GLfloat* u, GLfloat* v, GLfloat* n)
84{
85  assert(u);
86  assert(v);
87  assert(n);
88
89  /* compute the cross product (u x v for right-handed [ccw]) */
90  n[X] = u[Y] * v[Z] - u[Z] * v[Y];
91  n[Y] = u[Z] * v[X] - u[X] * v[Z];
92  n[Z] = u[X] * v[Y] - u[Y] * v[X];
93}
94
95/* _glmNormalize: normalize a vector
96 *
97 * n - array of 3 GLfloats (GLfloat n[3]) to be normalized
98 */
99static GLvoid
100_glmNormalize(GLfloat* n)
101{
102  GLfloat l;
103
104  assert(n);
105
106  /* normalize */
107  l = (GLfloat)sqrt(n[X] * n[X] + n[Y] * n[Y] + n[Z] * n[Z]);
108  n[0] /= l;
109  n[1] /= l;
110  n[2] /= l;
111}
112
113/* _glmEqual: compares two vectors and returns GL_TRUE if they are
114 * equal (within a certain threshold) or GL_FALSE if not. An epsilon
115 * that works fairly well is 0.000001.
116 *
117 * u - array of 3 GLfloats (GLfloat u[3])
118 * v - array of 3 GLfloats (GLfloat v[3])
119 */
120static GLboolean
121_glmEqual(GLfloat* u, GLfloat* v, GLfloat epsilon)
122{
123  if (_glmAbs(u[0] - v[0]) < epsilon &&
124      _glmAbs(u[1] - v[1]) < epsilon &&
125      _glmAbs(u[2] - v[2]) < epsilon)
126  {
127    return GL_TRUE;
128  }
129  return GL_FALSE;
130}
131
132/* _glmWeldVectors: eliminate (weld) vectors that are within an
133 * epsilon of each other.
134 *
135 * vectors    - array of GLfloat[3]'s to be welded
136 * numvectors - number of GLfloat[3]'s in vectors
137 * epsilon    - maximum difference between vectors
138 *
139 */
140GLfloat*
141_glmWeldVectors(GLfloat* vectors, unsigned int* numvectors, GLfloat epsilon)
142{
143  GLfloat* copies;
144  unsigned int   copied;
145  unsigned int   i, j;
146
147  copies = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (*numvectors + 1));
148  memcpy(copies, vectors, (sizeof(GLfloat) * 3 * (*numvectors + 1)));
149
150  copied = 1;
151  for (i = 1; i <= *numvectors; i++) {
152    for (j = 1; j <= copied; j++) {
153      if (_glmEqual(&vectors[3 * i], &copies[3 * j], epsilon)) {
154    goto duplicate;
155      }
156    }
157
158    /* must not be any duplicates -- add to the copies array */
159    copies[3 * copied + 0] = vectors[3 * i + 0];
160    copies[3 * copied + 1] = vectors[3 * i + 1];
161    copies[3 * copied + 2] = vectors[3 * i + 2];
162    j = copied;                /* pass this along for below */
163    copied++;
164
165  duplicate:
166    /* set the first component of this vector to point at the correct
167       index into the new copies array */
168    vectors[3 * i + 0] = (GLfloat)j;
169  }
170
171  *numvectors = copied-1;
172  return copies;
173}
174
175/* _glmFindGroup: Find a group in the model
176 */
177GLMgroup*
178_glmFindGroup(GLMmodel* model, char* name)
179{
180  GLMgroup* group;
181
182  assert(model);
183
184  group = model->groups;
185  while(group) {
186    if (!strcmp(name, group->name))
187      break;
188    group = group->next;
189  }
190
191  return group;
192}
193
194/* _glmAddGroup: Add a group to the model
195 */
196GLMgroup*
197_glmAddGroup(GLMmodel* model, char* name)
198{
199  GLMgroup* group;
200
201  group = _glmFindGroup(model, name);
202  if (!group) {
203    group = (GLMgroup*)malloc(sizeof(GLMgroup));
204    group->init();
205    group->name = strdup(name);
206    group->material = 0;
207    group->numtriangles = 0;
208    group->triangles = NULL;
209    group->hastexcoords = false;
210    group->next = model->groups;
211    model->groups = group;
212    model->numgroups++;
213  }
214
215  return group;
216}
217
218/* _glmFindGroup: Find a material in the model
219 */
220unsigned int
221_glmFindMaterial(GLMmodel* model, char* name)
222{
223  unsigned int i;
224
225  for (i = 0; i < model->nummaterials; i++) {
226    if (!strcmp(model->materials[i].name, name))
227      goto found;
228  }
229
230  /* didn't find the name, so set it as the default material */
231  fprintf(stderr,"_glmFindMaterial():  can't find material \"%s\".\n", name);
232  i = 0;
233
234found:
235  return i;
236}
237
238
239/* _glmDirName: return the directory given a path
240 *
241 * path - filesystem path
242 *
243 * The return value should be free'd.
244 */
245static char*
246_glmDirName(char* path)
247{
248  char* dir;
249  char* s;
250  char* s2;
251
252  dir = strdup(path);
253
254  s = strrchr(dir, '/');
255  s2 = strrchr(dir, '\\');    // also look for backslashes
256  if (s2 > s)                // take whichever is later
257      s = s2;
258
259  if (s)
260    s[1] = '\0';
261  else
262    dir[0] = '\0';
263
264  return dir;
265}
266
267
268/* _glmReadMTLTextureOptions: parses the given line for texture options
269 * and applies the options to the given model/material
270 *
271 * model         - properly initialized GLMmodel structure
272 * materialIndex - the material affected in the given model
273 * line          - white-space separated options
274 */
275GLvoid
276_glmReadMTLTextureOptions(GLMmodel* model, unsigned int materialIndex, char* line)
277{
278  char *token;
279  char seps[] = " \t\n\r\f\v";
280  token = ::strtok(line, seps);
281  while(NULL != token)
282  {
283    switch(token[0])
284    {
285      case '-':
286        switch(token[1])
287        {
288          // Scaling:  -s <uScale> <vScale>
289          case 's':
290            float uScale, vScale;
291            token = ::strtok(NULL, seps);
292            uScale = token ? (float)::atof(token) : 1.0f;
293
294            token = ::strtok(NULL, seps);
295            vScale = token ? (float)::atof(token) : 1.0f;
296
297            if ((0.0f != uScale) && (0.0f != vScale))
298            {
299              uScale = 1.0f / uScale;
300              vScale = 1.0f / vScale;
301              model->materials[materialIndex].textureUScale = uScale;
302              model->materials[materialIndex].textureVScale = vScale;
303            }
304            break;
305
306          // Offset:  -o <uOffset> <vOffset>
307          case 'o':
308            float uOffset, vOffset;
309            token = ::strtok(NULL, seps);
310            uOffset = token ? (float)::atof(token) : 0.0f;
311
312            token = ::strtok(NULL, seps);
313            vOffset = token ? (float)::atof(token) : 0.0f;
314
315            model->materials[materialIndex].textureUOffset = uOffset;
316            model->materials[materialIndex].textureVOffset = vOffset;
317            break;
318
319          // These options are not handled - so just advance to the next
320          // valid token
321          // ==================================================================
322          //
323
324          // Clamping:  -clamp <on|off>
325          case 'c':
326            token = ::strtok(NULL, seps);
327            break;
328
329          // Bias and gain:  -mm <bias> <gain>
330          case 'm':
331          // Turbulence/Noise:  -t <uNoise> <vNoise>
332          case 't':
333            token = ::strtok(NULL, seps);
334            token = ::strtok(NULL, seps);
335            break;
336
337          default:
338            break;
339        }
340        break;
341
342      // Image filename
343      default:
344        if (0 != strlen(token))
345        {
346          model->materials[materialIndex].textureName = strdup(token);
347        }
348    }
349
350    // Advance to the next token
351    token = ::strtok(NULL, seps);
352  }
353}
354
355
356/* _glmReadMTL: read a wavefront material library file
357 *
358 * model - properly initialized GLMmodel structure
359 * name  - name of the material library
360 */
361static GLvoid
362_glmReadMTL(GLMmodel* model, char* name)
363{
364  FILE* file;
365  char* dir;
366  char* filename;
367  char  buf[128];
368  unsigned int nummaterials, i;
369
370  dir = _glmDirName(model->pathname);
371  filename = (char*)malloc(sizeof(char) * (strlen(dir) + strlen(name) + 1));
372  strcpy(filename, dir);
373  strcat(filename, name);
374  free(dir);
375
376  /* open the file */
377  file = fopen(filename, "r");
378  if (!file) {
379    fprintf(stderr, "_glmReadMTL() failed: can't open material file \"%s\".\n",
380        filename);
381    return;
382  }
383  free(filename);
384
385  /* count the number of materials in the file */
386  nummaterials = 1;
387  while(fscanf(file, "%s", buf) != EOF) {
388    switch(buf[0]) {
389    case '#':                /* comment */
390      /* eat up rest of line */
391      fgets(buf, sizeof(buf), file);
392      break;
393    case 'n':                /* newmtl */
394      fgets(buf, sizeof(buf), file);
395      nummaterials++;
396      sscanf(buf, "%s %s", buf, buf);
397      break;
398    default:
399      /* eat up rest of line */
400      fgets(buf, sizeof(buf), file);
401      break;
402    }
403  }
404
405  rewind(file);
406
407  /* allocate memory for the materials */
408  model->materials = (GLMmaterial*)malloc(sizeof(GLMmaterial) * nummaterials);
409  model->nummaterials = nummaterials;
410
411  /* set the default material */
412  for (i = 0; i < nummaterials; i++) {
413    model->materials[i].init();
414    model->materials[i].name = NULL;
415    model->materials[i].shininess = 0.0f;
416    model->materials[i].diffuse[0] = 0.8f;
417    model->materials[i].diffuse[1] = 0.8f;
418    model->materials[i].diffuse[2] = 0.8f;
419    model->materials[i].diffuse[3] = 1.0f;
420    model->materials[i].ambient[0] = 0.2f;
421    model->materials[i].ambient[1] = 0.2f;
422    model->materials[i].ambient[2] = 0.2f;
423    model->materials[i].ambient[3] = 1.0f;
424    model->materials[i].specular[0] = 0.0f;
425    model->materials[i].specular[1] = 0.0f;
426    model->materials[i].specular[2] = 0.0f;
427    model->materials[i].textureName = NULL;
428    model->materials[i].textureReflection = false;
429    model->materials[i].textureUScale = 1.0f;
430    model->materials[i].textureVScale = 1.0f;
431    model->materials[i].textureUOffset = 0.0f;
432    model->materials[i].textureVOffset = 0.0f;
433    model->materials[i].alpha = 1.0f;
434  }
435  model->materials[0].name = strdup("default");
436
437  /* now, read in the data */
438  nummaterials = 0;
439  while(fscanf(file, "%s", buf) != EOF) {
440    switch(buf[0]) {
441    case '#':                /* comment */
442      /* eat up rest of line */
443      fgets(buf, sizeof(buf), file);
444      break;
445    case 'n':                /* newmtl */
446      fgets(buf, sizeof(buf), file);
447      sscanf(buf, "%s %s", buf, buf);
448      nummaterials++;
449      model->materials[nummaterials].name = strdup(buf);
450      break;
451    case 'N':
452      fscanf(file, "%f", &model->materials[nummaterials].shininess);
453      /* wavefront shininess is from [0, 1000], so scale for OpenGL */
454      model->materials[nummaterials].shininess /= 1000.0;
455      model->materials[nummaterials].shininess *= 128.0;
456      break;
457    case 'd':
458      fscanf(file, "%f", &model->materials[nummaterials].alpha);
459      break;
460    case 'K':
461      switch(buf[1]) {
462      case 'd':
463    fscanf(file, "%f %f %f",
464           &model->materials[nummaterials].diffuse[0],
465           &model->materials[nummaterials].diffuse[1],
466           &model->materials[nummaterials].diffuse[2]);
467    break;
468      case 's':
469    fscanf(file, "%f %f %f",
470           &model->materials[nummaterials].specular[0],
471           &model->materials[nummaterials].specular[1],
472           &model->materials[nummaterials].specular[2]);
473    break;
474      case 'a':
475    fscanf(file, "%f %f %f",
476           &model->materials[nummaterials].ambient[0],
477           &model->materials[nummaterials].ambient[1],
478           &model->materials[nummaterials].ambient[2]);
479    break;
480      default:
481    /* eat up rest of line */
482    fgets(buf, sizeof(buf), file);
483    break;
484      }
485      break;
486     
487    default:
488   
489      /* added by RO */
490      if (strcmp(buf,"map_Kd")==0)
491      {
492        fgets(buf, sizeof(buf), file);
493        _glmReadMTLTextureOptions(model, nummaterials, buf);
494      }
495      else if (strcmp(buf,"refl")==0)
496      {
497        model->materials[nummaterials].textureReflection = true;
498      }
499      else
500      {
501        /* eat up rest of line */
502        fgets(buf, sizeof(buf), file);
503      }
504      break;
505    }
506  }
507  fclose(file);
508}
509
510/* _glmWriteMTL: write a wavefront material library file
511 *
512 * model      - properly initialized GLMmodel structure
513 * modelpath  - pathname of the model being written
514 * mtllibname - name of the material library to be written
515 */
516static GLvoid
517_glmWriteMTL(GLMmodel* model, char* modelpath, char* mtllibname)
518{
519  FILE* file;
520  char* dir;
521  char* filename;
522  GLMmaterial* material;
523  unsigned int i;
524
525  dir = _glmDirName(modelpath);
526  filename = (char*)malloc(sizeof(char) * (strlen(dir) + strlen(mtllibname)));
527  strcpy(filename, dir);
528  strcat(filename, mtllibname);
529  free(dir);
530
531  /* open the file */
532  file = fopen(filename, "w");
533  if (!file) {
534    fprintf(stderr, "_glmWriteMTL() failed: can't open file \"%s\".\n",
535        filename);
536    return;
537  }
538  free(filename);
539
540  /* spit out a header */
541  fprintf(file, "#  \n");
542  fprintf(file, "#  Wavefront MTL generated by GLM library\n");
543  fprintf(file, "#  \n");
544  fprintf(file, "#  GLM library copyright (C) 1997 by Nate Robins\n");
545  fprintf(file, "#  email: ndr@pobox.com\n");
546  fprintf(file, "#  www:   http://www.pobox.com/~ndr\n");
547  fprintf(file, "#  \n\n");
548
549  for (i = 0; i < model->nummaterials; i++) {
550    material = &model->materials[i];
551    fprintf(file, "newmtl %s\n", material->name);
552    fprintf(file, "Ka %f %f %f\n",
553        material->ambient[0], material->ambient[1], material->ambient[2]);
554    fprintf(file, "Kd %f %f %f\n",
555        material->diffuse[0], material->diffuse[1], material->diffuse[2]);
556    fprintf(file, "Ks %f %f %f\n",
557        material->specular[0],material->specular[1],material->specular[2]);
558    fprintf(file, "Ns %f\n", material->shininess);
559    fprintf(file, "\n");
560  }
561}
562/* Create by RO to help handle g %s %s groups */
563static void createCompositeName(char* buf,char* compositeName)
564{
565    char *ptr_b = buf;
566    char *ptr_c = compositeName;
567
568    /* first skip over leading spaces */
569    while(*ptr_b!=0 && *ptr_b==' ') ++ptr_b;
570
571    /* copy over rest, changing spaces for underscores,
572     * to handle faces which are contained in several groups */
573    while(*ptr_b>=' ')
574    {
575      if (*ptr_b==' ') *ptr_c = '_';
576      else *ptr_c = *ptr_b;
577      ++ptr_c;
578      ++ptr_b;
579    }
580    *ptr_c = 0;
581}
582/* _glmFirstPass: first pass at a Wavefront OBJ file that gets all the
583 * statistics of the model (such as #vertices, #normals, etc)
584 *
585 * model - properly initialized GLMmodel structure
586 * file  - (fopen'd) file descriptor
587 */
588static GLvoid
589_glmFirstPass(GLMmodel* model, FILE* file)
590{
591  unsigned int    numvertices;        /* number of vertices in model */
592  unsigned int    numnormals;            /* number of normals in model */
593  unsigned int    numtexcoords;        /* number of texcoords in model */
594  unsigned int    numtriangles;        /* number of triangles in model */
595  GLMgroup* group;            /* current group */
596  unsigned  v, n, t;
597  char      buf[128];
598
599  /* make a default group */
600  group = _glmAddGroup(model, "default");
601
602  float x,y,z;
603  int r,g,b;
604
605  numvertices = numnormals = numtexcoords = numtriangles = 0;
606 
607  unsigned int numcolors = 0;
608 
609  while(fscanf(file, "%s", buf) != EOF) {
610    switch(buf[0]) {
611    case '#':                /* comment */
612      /* eat up rest of line */
613      fgets(buf, sizeof(buf), file);
614      break;
615    case 'v':                /* v, vn, vt */
616      switch(buf[1]) {
617      case '\0':            /* vertex */
618        {
619            /* eat up rest of line */
620            fgets(buf, sizeof(buf), file);
621
622            int noRead = sscanf(buf, "%f %f %f %d %d %d",
623                                &x, &y, &z, &r,&g,&b);
624
625            numvertices++;
626            if (noRead==6) numcolors++;
627
628
629            break;
630        }
631      case 'n':                /* normal */
632        /* eat up rest of line */
633        fgets(buf, sizeof(buf), file);
634        numnormals++;
635        break;
636      case 't':                /* texcoord */
637        /* eat up rest of line */
638        fgets(buf, sizeof(buf), file);
639        numtexcoords++;
640        break;
641      default:
642        printf("_glmFirstPass(): Unknown token \"%s\".\n", buf);
643        //exit(1);
644        return;
645      }
646      break;
647    case 'm':
648      fgets(buf, sizeof(buf), file);
649      sscanf(buf, "%s %s", buf, buf);
650      model->mtllibname = strdup(buf);
651      _glmReadMTL(model, buf);
652      break;
653    case 'u':
654      /* eat up rest of line */
655      fgets(buf, sizeof(buf), file);
656      break;
657    case 'o':                /* group */
658    case 's':                /* group */
659    case 'g':                /* group */
660      {
661        /* eat up rest of line */
662        fgets(buf, sizeof(buf), file);
663
664        char compositeName[128];
665        createCompositeName(buf,compositeName);
666
667        group = _glmAddGroup(model, compositeName);
668      }
669      break;
670    case 'f':                /* face */
671      v = n = t = 0;
672      fscanf(file, "%s", buf);
673      /* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
674      if (strstr(buf, "//")) {
675    /* v//n */
676    sscanf(buf, "%d//%d", &v, &n);
677    fscanf(file, "%d//%d", &v, &n);
678    fscanf(file, "%d//%d", &v, &n);
679    numtriangles++;
680    group->numtriangles++;
681    while(fscanf(file, "%d//%d", &v, &n) > 0) {
682      numtriangles++;
683      group->numtriangles++;
684    }
685      } else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) {
686    /* v/t/n */
687    fscanf(file, "%d/%d/%d", &v, &t, &n);
688    fscanf(file, "%d/%d/%d", &v, &t, &n);
689    numtriangles++;
690    group->numtriangles++;
691    while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
692      numtriangles++;
693      group->numtriangles++;
694    }
695      } else if (sscanf(buf, "%d/%d", &v, &t) == 2) {
696    /* v/t */
697    fscanf(file, "%d/%d", &v, &t);
698    fscanf(file, "%d/%d", &v, &t);
699    numtriangles++;
700    group->numtriangles++;
701    while(fscanf(file, "%d/%d", &v, &t) > 0) {
702      numtriangles++;
703      group->numtriangles++;
704    }
705      } else {
706    /* v */
707    fscanf(file, "%d", &v);
708    fscanf(file, "%d", &v);
709    numtriangles++;
710    group->numtriangles++;
711    while(fscanf(file, "%d", &v) > 0) {
712      numtriangles++;
713      group->numtriangles++;
714    }
715      }
716      break;
717
718    default:
719      /* eat up rest of line */
720      fgets(buf, sizeof(buf), file);
721      break;
722    }
723  }
724
725#if 0
726  /* announce the model statistics */
727  printf(" Vertices: %d\n", numvertices);
728  printf(" Normals: %d\n", numnormals);
729  printf(" Texcoords: %d\n", numtexcoords);
730  printf(" Triangles: %d\n", numtriangles);
731  printf(" Groups: %d\n", model->numgroups);
732#endif
733
734  /* set the stats in the model structure */
735  model->numvertices  = numvertices;
736  model->numnormals   = numnormals;
737  model->numtexcoords = numtexcoords;
738  model->numtriangles = numtriangles;
739
740  /* allocate memory for the triangles in each group */
741  group = model->groups;
742  while(group) {
743    group->triangles = (unsigned int*)malloc(sizeof(unsigned int) * group->numtriangles);
744    group->numtriangles = 0;
745    group = group->next;
746  }
747
748
749  // if all vertices have colours enables per vertex colors
750  if (numvertices==numcolors) model->useColors = true;
751
752}
753
754/* _glmSecondPass: second pass at a Wavefront OBJ file that gets all
755 * the data.
756 *
757 * model - properly initialized GLMmodel structure
758 * file  - (fopen'd) file descriptor
759 */
760static GLvoid
761_glmSecondPass(GLMmodel* model, FILE* file)
762{
763  unsigned int    numvertices;        /* number of vertices in model */
764  unsigned int    numnormals;            /* number of normals in model */
765  unsigned int    numtexcoords;        /* number of texcoords in model */
766  unsigned int    numtriangles;        /* number of triangles in model */
767  GLfloat*  vertices;            /* array of vertices  */
768  GLfloat*  normals;            /* array of normals */
769  GLfloat*  texcoords;            /* array of texture coordinates */
770  GLMgroup* group;            /* current group pointer */
771  unsigned int    material;            /* current material */
772  unsigned int    v, n, t;
773  char      buf[128];
774
775  /* set the pointer shortcuts */
776  vertices     = model->vertices;
777  normals      = model->normals;
778  texcoords    = model->texcoords;
779  group        = model->groups;
780
781  /* on the second pass through the file, read all the data into the
782     allocated arrays */
783  numvertices = numnormals = numtexcoords = 1;
784  numtriangles = 0;
785  material = 0;
786 
787  bool firstGroup = true;
788  bool previousLineWas_g = false;
789
790  int r,g,b;
791  while(fscanf(file, "%s", buf) != EOF) {
792    char c = buf[0];
793    switch(c) {
794    case '#':                /* comment */
795      /* eat up rest of line */
796      fgets(buf, sizeof(buf), file);
797      break;
798    case 'v':                /* v, vn, vt */
799      switch(buf[1]) {
800      case '\0':            /* vertex */
801        {
802            if (model->useColors)
803            {
804                fscanf(file, "%f %f %f %d %d %d",
805                             &vertices[3 * numvertices + X],
806                             &vertices[3 * numvertices + Y],
807                             &vertices[3 * numvertices + Z],
808                             &r,&g,&b);
809                model->colors[numvertices].set(r,g,b,255);
810
811                numvertices++;               
812            } else
813            {
814                fscanf(file, "%f %f %f",
815                             &vertices[3 * numvertices + X],
816                             &vertices[3 * numvertices + Y],
817                             &vertices[3 * numvertices + Z]);
818                numvertices++;               
819            }
820        }
821        break;
822      case 'n':                /* normal */
823        fscanf(file, "%f %f %f",
824               &normals[3 * numnormals + X],
825               &normals[3 * numnormals + Y],
826               &normals[3 * numnormals + Z]);
827        numnormals++;
828        break;
829      case 't':                /* texcoord */
830        fscanf(file, "%f %f",
831               &texcoords[2 * numtexcoords + X],
832               &texcoords[2 * numtexcoords + Y]);
833        numtexcoords++;
834        break;
835      }
836      break;
837    case 'u':
838      fgets(buf, sizeof(buf), file);
839      sscanf(buf, "%s %s", buf, buf);
840     
841      material = _glmFindMaterial(model, buf);
842     
843      group->material = material;
844
845      break;
846    case 'o':                /* group */
847    case 's':                /* group */
848    case 'g':                /* group */
849      /* eat up rest of line */
850      fgets(buf, sizeof(buf), file);
851      char compositeName[128];
852      createCompositeName(buf,compositeName);
853
854      group = _glmFindGroup(model, compositeName);
855      group->material = material;
856      firstGroup = false;
857      break;
858    case 'f':                /* face */
859      v = n = t = 0;
860      fscanf(file, "%s", buf);
861      /* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
862      if (strstr(buf, "//")) {
863        /* v//n */
864        sscanf(buf, "%d//%d", &v, &n);
865        T(numtriangles).vindices[0] = v;
866        T(numtriangles).nindices[0] = n;
867        fscanf(file, "%d//%d", &v, &n);
868        T(numtriangles).vindices[1] = v;
869        T(numtriangles).nindices[1] = n;
870        fscanf(file, "%d//%d", &v, &n);
871        T(numtriangles).vindices[2] = v;
872        T(numtriangles).nindices[2] = n;
873        group->triangles[group->numtriangles++] = numtriangles;
874        numtriangles++;
875        while(fscanf(file, "%d//%d", &v, &n) > 0) {
876          T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
877          T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
878          T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
879          T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
880          T(numtriangles).vindices[2] = v;
881          T(numtriangles).nindices[2] = n;
882          group->triangles[group->numtriangles++] = numtriangles;
883          numtriangles++;
884        }
885      } else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) {
886        /* v/t/n */
887        T(numtriangles).vindices[0] = v;
888        T(numtriangles).tindices[0] = t;
889        T(numtriangles).nindices[0] = n;
890        fscanf(file, "%d/%d/%d", &v, &t, &n);
891        T(numtriangles).vindices[1] = v;
892        T(numtriangles).tindices[1] = t;
893        T(numtriangles).nindices[1] = n;
894        fscanf(file, "%d/%d/%d", &v, &t, &n);
895        T(numtriangles).vindices[2] = v;
896        T(numtriangles).tindices[2] = t;
897        T(numtriangles).nindices[2] = n;
898        group->triangles[group->numtriangles++] = numtriangles;
899        group->hastexcoords = true;
900        numtriangles++;
901        while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
902          T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
903          T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
904          T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
905          T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
906          T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
907          T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
908          T(numtriangles).vindices[2] = v;
909          T(numtriangles).tindices[2] = t;
910          T(numtriangles).nindices[2] = n;
911          group->triangles[group->numtriangles++] = numtriangles;
912          numtriangles++;
913        }
914      } else if (sscanf(buf, "%d/%d", &v, &t) == 2) {
915        /* v/t */
916        T(numtriangles).vindices[0] = v;
917        T(numtriangles).tindices[0] = t;
918        fscanf(file, "%d/%d", &v, &t);
919        T(numtriangles).vindices[1] = v;
920        T(numtriangles).tindices[1] = t;
921        fscanf(file, "%d/%d", &v, &t);
922        T(numtriangles).vindices[2] = v;
923        T(numtriangles).tindices[2] = t;
924        group->triangles[group->numtriangles++] = numtriangles;
925        group->hastexcoords = true;
926        numtriangles++;
927        while(fscanf(file, "%d/%d", &v, &t) > 0) {
928          T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
929          T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
930          T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
931          T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
932          T(numtriangles).vindices[2] = v;
933          T(numtriangles).tindices[2] = t;
934          group->triangles[group->numtriangles++] = numtriangles;
935          numtriangles++;
936        }
937      } else {
938        /* v */
939        sscanf(buf, "%d", &v);
940        T(numtriangles).vindices[0] = v;
941        fscanf(file, "%d", &v);
942        T(numtriangles).vindices[1] = v;
943        fscanf(file, "%d", &v);
944        T(numtriangles).vindices[2] = v;
945        group->triangles[group->numtriangles++] = numtriangles;
946        numtriangles++;
947        while(fscanf(file, "%d", &v) > 0) {
948          T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
949          T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
950          T(numtriangles).vindices[2] = v;
951          group->triangles[group->numtriangles++] = numtriangles;
952          numtriangles++;
953        }
954      }
955      break;
956
957    default:
958      /* eat up rest of line */
959      fgets(buf, sizeof(buf), file);
960      break;
961    }
962   
963    // a hack by Robert Osfield to account for usemtl being infront
964    // or the group, or after - but only one line after.
965    previousLineWas_g = (c=='g');
966  }
967
968#if 0
969  /* announce the memory requirements */
970  printf(" Memory: %d bytes\n",
971     numvertices  * 3*sizeof(GLfloat) +
972     numnormals   * 3*sizeof(GLfloat) * (numnormals ? 1 : 0) +
973     numtexcoords * 3*sizeof(GLfloat) * (numtexcoords ? 1 : 0) +
974     numtriangles * sizeof(GLMtriangle));
975#endif
976}
977
978
979
980
981/* public functions */
982
983/* glmUnitize: "unitize" a model by translating it to the origin and
984 * scaling it to fit in a unit cube around the origin.  Returns the
985 * scalefactor used.
986 *
987 * model - properly initialized GLMmodel structure
988 */
989GLfloat
990glmUnitize(GLMmodel* model)
991{
992  unsigned int  i;
993  GLfloat maxx, minx, maxy, miny, maxz, minz;
994  GLfloat cx, cy, cz, w, h, d;
995  GLfloat scale;
996
997  assert(model);
998  assert(model->vertices);
999
1000  /* get the max/mins */
1001  maxx = minx = model->vertices[3 + X];
1002  maxy = miny = model->vertices[3 + Y];
1003  maxz = minz = model->vertices[3 + Z];
1004  for (i = 1; i <= model->numvertices; i++) {
1005    if (maxx < model->vertices[3 * i + X])
1006      maxx = model->vertices[3 * i + X];
1007    if (minx > model->vertices[3 * i + X])
1008      minx = model->vertices[3 * i + X];
1009
1010    if (maxy < model->vertices[3 * i + Y])
1011      maxy = model->vertices[3 * i + Y];
1012    if (miny > model->vertices[3 * i + Y])
1013      miny = model->vertices[3 * i + Y];
1014
1015    if (maxz < model->vertices[3 * i + Z])
1016      maxz = model->vertices[3 * i + Z];
1017    if (minz > model->vertices[3 * i + Z])
1018      minz = model->vertices[3 * i + Z];
1019  }
1020
1021  /* calculate model width, height, and depth */
1022  w = _glmAbs(maxx) + _glmAbs(minx);
1023  h = _glmAbs(maxy) + _glmAbs(miny);
1024  d = _glmAbs(maxz) + _glmAbs(minz);
1025
1026  /* calculate center of the model */
1027  cx = (maxx + minx) / 2.0f;
1028  cy = (maxy + miny) / 2.0f;
1029  cz = (maxz + minz) / 2.0f;
1030
1031  /* calculate unitizing scale factor */
1032  scale = 2.0f / _glmMax(_glmMax(w, h), d);
1033
1034  /* translate around center then scale */
1035  for (i = 1; i <= model->numvertices; i++) {
1036    model->vertices[3 * i + X] -= cx;
1037    model->vertices[3 * i + Y] -= cy;
1038    model->vertices[3 * i + Z] -= cz;
1039    model->vertices[3 * i + X] *= scale;
1040    model->vertices[3 * i + Y] *= scale;
1041    model->vertices[3 * i + Z] *= scale;
1042  }
1043
1044  return scale;
1045}
1046
1047/* glmDimensions: Calculates the dimensions (width, height, depth) of
1048 * a model.
1049 *
1050 * model      - initialized GLMmodel structure
1051 * dimensions - array of 3 GLfloats (GLfloat dimensions[3])
1052 */
1053GLvoid
1054glmDimensions(GLMmodel* model, GLfloat* dimensions)
1055{
1056  unsigned int i;
1057  GLfloat maxx, minx, maxy, miny, maxz, minz;
1058
1059  assert(model);
1060  assert(model->vertices);
1061  assert(dimensions);
1062
1063  /* get the max/mins */
1064  maxx = minx = model->vertices[3 + X];
1065  maxy = miny = model->vertices[3 + Y];
1066  maxz = minz = model->vertices[3 + Z];
1067  for (i = 1; i <= model->numvertices; i++) {
1068    if (maxx < model->vertices[3 * i + X])
1069      maxx = model->vertices[3 * i + X];
1070    if (minx > model->vertices[3 * i + X])
1071      minx = model->vertices[3 * i + X];
1072
1073    if (maxy < model->vertices[3 * i + Y])
1074      maxy = model->vertices[3 * i + Y];
1075    if (miny > model->vertices[3 * i + Y])
1076      miny = model->vertices[3 * i + Y];
1077
1078    if (maxz < model->vertices[3 * i + Z])
1079      maxz = model->vertices[3 * i + Z];
1080    if (minz > model->vertices[3 * i + Z])
1081      minz = model->vertices[3 * i + Z];
1082  }
1083
1084  /* calculate model width, height, and depth */
1085  dimensions[X] = _glmAbs(maxx) + _glmAbs(minx);
1086  dimensions[Y] = _glmAbs(maxy) + _glmAbs(miny);
1087  dimensions[Z] = _glmAbs(maxz) + _glmAbs(minz);
1088}
1089
1090/* glmScale: Scales a model by a given amount.
1091 *
1092 * model - properly initialized GLMmodel structure
1093 * scale - scalefactor (0.5 = half as large, 2.0 = twice as large)
1094 */
1095GLvoid
1096glmScale(GLMmodel* model, GLfloat scale)
1097{
1098  unsigned int i;
1099
1100  for (i = 1; i <= model->numvertices; i++) {
1101    model->vertices[3 * i + X] *= scale;
1102    model->vertices[3 * i + Y] *= scale;
1103    model->vertices[3 * i + Z] *= scale;
1104  }
1105}
1106
1107/* glmReverseWinding: Reverse the polygon winding for all polygons in
1108 * this model.  Default winding is counter-clockwise.  Also changes
1109 * the direction of the normals.
1110 *
1111 * model - properly initialized GLMmodel structure
1112 */
1113GLvoid
1114glmReverseWinding(GLMmodel* model)
1115{
1116  unsigned int i, swap;
1117
1118  assert(model);
1119
1120  for (i = 0; i < model->numtriangles; i++) {
1121    swap = T(i).vindices[0];
1122    T(i).vindices[0] = T(i).vindices[2];
1123    T(i).vindices[2] = swap;
1124
1125    if (model->numnormals) {
1126      swap = T(i).nindices[0];
1127      T(i).nindices[0] = T(i).nindices[2];
1128      T(i).nindices[2] = swap;
1129    }
1130
1131    if (model->numtexcoords) {
1132      swap = T(i).tindices[0];
1133      T(i).tindices[0] = T(i).tindices[2];
1134      T(i).tindices[2] = swap;
1135    }
1136  }
1137
1138  /* reverse facet normals */
1139  for (i = 1; i <= model->numfacetnorms; i++) {
1140    model->facetnorms[3 * i + X] = -model->facetnorms[3 * i + X];
1141    model->facetnorms[3 * i + Y] = -model->facetnorms[3 * i + Y];
1142    model->facetnorms[3 * i + Z] = -model->facetnorms[3 * i + Z];
1143  }
1144
1145  /* reverse vertex normals */
1146  for (i = 1; i <= model->numnormals; i++) {
1147    model->normals[3 * i + X] = -model->normals[3 * i + X];
1148    model->normals[3 * i + Y] = -model->normals[3 * i + Y];
1149    model->normals[3 * i + Z] = -model->normals[3 * i + Z];
1150  }
1151}
1152
1153/* glmFacetNormals: Generates facet normals for a model (by taking the
1154 * cross product of the two vectors derived from the sides of each
1155 * triangle).  Assumes a counter-clockwise winding.
1156 *
1157 * model - initialized GLMmodel structure
1158 */
1159GLvoid
1160glmFacetNormals(GLMmodel* model)
1161{
1162  unsigned int  i;
1163  GLfloat u[3];
1164  GLfloat v[3];
1165 
1166  assert(model);
1167  assert(model->vertices);
1168
1169  /* clobber any old facetnormals */
1170  if (model->facetnorms)
1171    free(model->facetnorms);
1172
1173  /* allocate memory for the new facet normals */
1174  model->numfacetnorms = model->numtriangles;
1175  model->facetnorms = (GLfloat*)malloc(sizeof(GLfloat) *
1176                       3 * (model->numfacetnorms + 1));
1177
1178  for (i = 0; i < model->numtriangles; i++) {
1179    model->triangles[i].findex = i+1;
1180
1181    u[X] = model->vertices[3 * T(i).vindices[1] + X] -
1182           model->vertices[3 * T(i).vindices[0] + X];
1183    u[Y] = model->vertices[3 * T(i).vindices[1] + Y] -
1184           model->vertices[3 * T(i).vindices[0] + Y];
1185    u[Z] = model->vertices[3 * T(i).vindices[1] + Z] -
1186           model->vertices[3 * T(i).vindices[0] + Z];
1187
1188    v[X] = model->vertices[3 * T(i).vindices[2] + X] -
1189           model->vertices[3 * T(i).vindices[0] + X];
1190    v[Y] = model->vertices[3 * T(i).vindices[2] + Y] -
1191           model->vertices[3 * T(i).vindices[0] + Y];
1192    v[Z] = model->vertices[3 * T(i).vindices[2] + Z] -
1193           model->vertices[3 * T(i).vindices[0] + Z];
1194
1195    _glmCross(u, v, &model->facetnorms[3 * (i+1)]);
1196    _glmNormalize(&model->facetnorms[3 * (i+1)]);
1197  }
1198}
1199
1200/* glmVertexNormals: Generates smooth vertex normals for a model.
1201 * First builds a list of all the triangles each vertex is in.  Then
1202 * loops through each vertex in the the list averaging all the facet
1203 * normals of the triangles each vertex is in.  Finally, sets the
1204 * normal index in the triangle for the vertex to the generated smooth
1205 * normal.  If the dot product of a facet normal and the facet normal
1206 * associated with the first triangle in the list of triangles the
1207 * current vertex is in is greater than the cosine of the angle
1208 * parameter to the function, that facet normal is not added into the
1209 * average normal calculation and the corresponding vertex is given
1210 * the facet normal.  This tends to preserve hard edges.  The angle to
1211 * use depends on the model, but 90 degrees is usually a good start.
1212 *
1213 * model - initialized GLMmodel structure
1214 * angle - maximum angle (in degrees) to smooth across
1215 */
1216GLvoid
1217glmVertexNormals(GLMmodel* model, GLfloat angle)
1218{
1219  GLMnode*  node;
1220  GLMnode*  tail;
1221  GLMnode** members;
1222  GLfloat*  normals;
1223  unsigned int    numnormals;
1224  GLfloat   average[3];
1225  GLfloat   dot, cos_angle;
1226  unsigned int    i, avg;
1227
1228  assert(model);
1229  assert(model->facetnorms);
1230
1231  /* calculate the cosine of the angle (in degrees) */
1232  cos_angle = (float)cos(osg::DegreesToRadians(angle));
1233
1234  /* nuke any previous normals */
1235  if (model->normals)
1236    free(model->normals);
1237
1238  /* allocate space for new normals */
1239  model->numnormals = model->numtriangles * 3; /* 3 normals per triangle */
1240  model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1));
1241
1242  /* allocate a structure that will hold a linked list of triangle
1243     indices for each vertex */
1244  members = (GLMnode**)malloc(sizeof(GLMnode*) * (model->numvertices + 1));
1245  for (i = 1; i <= model->numvertices; i++)
1246    members[i] = NULL;
1247 
1248  /* for every triangle, create a node for each vertex in it */
1249  for (i = 0; i < model->numtriangles; i++) {
1250    node = (GLMnode*)malloc(sizeof(GLMnode));
1251    node->index = i;
1252    node->next  = members[T(i).vindices[0]];
1253    members[T(i).vindices[0]] = node;
1254
1255    node = (GLMnode*)malloc(sizeof(GLMnode));
1256    node->index = i;
1257    node->next  = members[T(i).vindices[1]];
1258    members[T(i).vindices[1]] = node;
1259
1260    node = (GLMnode*)malloc(sizeof(GLMnode));
1261    node->index = i;
1262    node->next  = members[T(i).vindices[2]];
1263    members[T(i).vindices[2]] = node;
1264  }
1265
1266  /* calculate the average normal for each vertex */
1267  numnormals = 1;
1268  for (i = 1; i <= model->numvertices; i++) {
1269    /* calculate an average normal for this vertex by averaging the
1270       facet normal of every triangle this vertex is in */
1271    node = members[i];
1272    if (!node)
1273      fprintf(stderr, "glmVertexNormals(): vertex w/o a triangle\n");
1274    average[0] = 0.0; average[1] = 0.0; average[2] = 0.0;
1275    avg = 0;
1276    while (node) {
1277      /* only average if the dot product of the angle between the two
1278         facet normals is greater than the cosine of the threshold
1279         angle -- or, said another way, the angle between the two
1280         facet normals is less than (or equal to) the threshold angle */
1281      dot = _glmDot(&model->facetnorms[3 * T(node->index).findex],
1282             &model->facetnorms[3 * T(members[i]->index).findex]);
1283      if (dot > cos_angle) {
1284    node->averaged = GL_TRUE;
1285    average[0] += model->facetnorms[3 * T(node->index).findex + 0];
1286    average[1] += model->facetnorms[3 * T(node->index).findex + 1];
1287    average[2] += model->facetnorms[3 * T(node->index).findex + 2];
1288    avg = 1;            /* we averaged at least one normal! */
1289      } else {
1290    node->averaged = GL_FALSE;
1291      }
1292      node = node->next;
1293    }
1294
1295    if (avg) {
1296      /* normalize the averaged normal */
1297      _glmNormalize(average);
1298
1299      /* add the normal to the vertex normals list */
1300      model->normals[3 * numnormals + 0] = average[0];
1301      model->normals[3 * numnormals + 1] = average[1];
1302      model->normals[3 * numnormals + 2] = average[2];
1303      avg = numnormals;
1304      numnormals++;
1305    }
1306
1307    /* set the normal of this vertex in each triangle it is in */
1308    node = members[i];
1309    while (node) {
1310      if (node->averaged) {
1311    /* if this node was averaged, use the average normal */
1312    if (T(node->index).vindices[0] == i)
1313      T(node->index).nindices[0] = avg;
1314    else if (T(node->index).vindices[1] == i)
1315      T(node->index).nindices[1] = avg;
1316    else if (T(node->index).vindices[2] == i)
1317      T(node->index).nindices[2] = avg;
1318      } else {
1319    /* if this node wasn't averaged, use the facet normal */
1320    model->normals[3 * numnormals + 0] =
1321      model->facetnorms[3 * T(node->index).findex + 0];
1322    model->normals[3 * numnormals + 1] =
1323      model->facetnorms[3 * T(node->index).findex + 1];
1324    model->normals[3 * numnormals + 2] =
1325      model->facetnorms[3 * T(node->index).findex + 2];
1326    if (T(node->index).vindices[0] == i)
1327      T(node->index).nindices[0] = numnormals;
1328    else if (T(node->index).vindices[1] == i)
1329      T(node->index).nindices[1] = numnormals;
1330    else if (T(node->index).vindices[2] == i)
1331      T(node->index).nindices[2] = numnormals;
1332    numnormals++;
1333      }
1334      node = node->next;
1335    }
1336  }
1337 
1338  model->numnormals = numnormals - 1;
1339
1340  /* free the member information */
1341  for (i = 1; i <= model->numvertices; i++) {
1342    node = members[i];
1343    while (node) {
1344      tail = node;
1345      node = node->next;
1346      free(tail);
1347    }
1348  }
1349  free(members);
1350
1351  /* pack the normals array (we previously allocated the maximum
1352     number of normals that could possibly be created (numtriangles *
1353     3), so get rid of some of them (usually alot unless none of the
1354     facet normals were averaged)) */
1355  normals = model->normals;
1356  model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1));
1357  for (i = 1; i <= model->numnormals; i++) {
1358    model->normals[3 * i + 0] = normals[3 * i + 0];
1359    model->normals[3 * i + 1] = normals[3 * i + 1];
1360    model->normals[3 * i + 2] = normals[3 * i + 2];
1361  }
1362  free(normals);
1363
1364  printf("glmVertexNormals(): %d normals generated\n", model->numnormals);
1365}
1366
1367
1368/* glmLinearTexture: Generates texture coordinates according to a
1369 * linear projection of the texture map.  It generates these by
1370 * linearly mapping the vertices onto a square.
1371 *
1372 * model - pointer to initialized GLMmodel structure
1373 */
1374GLvoid
1375glmLinearTexture(GLMmodel* model)
1376{
1377  GLMgroup *group;
1378  GLfloat dimensions[3];
1379  GLfloat x, y, scalefactor;
1380  unsigned int i;
1381 
1382  assert(model);
1383
1384  if (model->texcoords)
1385    free(model->texcoords);
1386  model->numtexcoords = model->numvertices;
1387  model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1));
1388 
1389  glmDimensions(model, dimensions);
1390  scalefactor = 2.0f /
1391    _glmAbs(_glmMax(_glmMax(dimensions[0], dimensions[1]), dimensions[2]));
1392
1393  /* do the calculations */
1394  for(i = 1; i <= model->numvertices; i++) {
1395    x = model->vertices[3 * i + 0] * scalefactor;
1396    y = model->vertices[3 * i + 2] * scalefactor;
1397    model->texcoords[2 * i + 0] = (x + 1.0f) / 2.0f;
1398    model->texcoords[2 * i + 1] = (y + 1.0f) / 2.0f;
1399  }
1400 
1401  /* go through and put texture coordinate indices in all the triangles */
1402  group = model->groups;
1403  while(group) {
1404    for(i = 0; i < group->numtriangles; i++) {
1405      T(group->triangles[i]).tindices[0] = T(group->triangles[i]).vindices[0];
1406      T(group->triangles[i]).tindices[1] = T(group->triangles[i]).vindices[1];
1407      T(group->triangles[i]).tindices[2] = T(group->triangles[i]).vindices[2];
1408    }   
1409    group = group->next;
1410  }
1411
1412#if 0
1413  printf("glmLinearTexture(): generated %d linear texture coordinates\n",
1414      model->numtexcoords);
1415#endif
1416}
1417
1418/* glmSpheremapTexture: Generates texture coordinates according to a
1419 * spherical projection of the texture map.  Sometimes referred to as
1420 * spheremap, or reflection map texture coordinates.  It generates
1421 * these by using the normal to calculate where that vertex would map
1422 * onto a sphere.  Since it is impossible to map something flat
1423 * perfectly onto something spherical, there is distortion at the
1424 * poles.  This particular implementation causes the poles along the X
1425 * axis to be distorted.
1426 *
1427 * model - pointer to initialized GLMmodel structure
1428 */
1429GLvoid
1430glmSpheremapTexture(GLMmodel* model)
1431{
1432  GLMgroup* group;
1433  GLfloat theta, phi, rho, x, y, z, r;
1434  unsigned int i;
1435 
1436  assert(model);
1437  assert(model->normals);
1438
1439  if (model->texcoords)
1440    free(model->texcoords);
1441  model->numtexcoords = model->numnormals;
1442  model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1));
1443     
1444  /* do the calculations */
1445  for (i = 1; i <= model->numnormals; i++) {
1446    z = model->normals[3 * i + 0];    /* re-arrange for pole distortion */
1447    y = model->normals[3 * i + 1];
1448    x = model->normals[3 * i + 2];
1449    r = sqrtf((x * x) + (y * y));
1450    rho = sqrtf((r * r) + (z * z));
1451     
1452    if(r == 0.0f) {
1453    theta = 0.0f;
1454    phi = 0.0f;
1455    } else {
1456      if(z == 0.0)
1457    phi = 3.14159265f / 2.0f;
1458      else
1459    phi = acosf(z / rho);
1460     
1461#if WE_DONT_NEED_THIS_CODE
1462      if(x == 0.0)
1463    theta = 3.14159265f / 2.0f;    /* asin(y / r); */
1464      else
1465    theta = acos(x / r);
1466#endif
1467     
1468      if(y == 0.0)
1469    theta = 3.141592365f / 2.0f;    /* acos(x / r); */
1470      else
1471    theta = asinf(y / r) + 3.14159265f / 2.0f;
1472    }
1473   
1474    model->texcoords[2 * i + 0] = theta / 3.14159265f;
1475    model->texcoords[2 * i + 1] = phi / 3.14159265f;
1476  }
1477 
1478  /* go through and put texcoord indices in all the triangles */
1479  group = model->groups;
1480  while(group) {
1481    for (i = 0; i < group->numtriangles; i++) {
1482      T(group->triangles[i]).tindices[0] = T(group->triangles[i]).nindices[0];
1483      T(group->triangles[i]).tindices[1] = T(group->triangles[i]).nindices[1];
1484      T(group->triangles[i]).tindices[2] = T(group->triangles[i]).nindices[2];
1485    }
1486    group = group->next;
1487  }
1488
1489#if 0 
1490  printf("glmSpheremapTexture(): generated %d spheremap texture coordinates\n",
1491     model->numtexcoords);
1492#endif
1493}
1494
1495/* glmDelete: Deletes a GLMmodel structure.
1496 *
1497 * model - initialized GLMmodel structure
1498 */
1499GLvoid
1500glmDelete(GLMmodel* model)
1501{
1502  GLMgroup* group;
1503  unsigned int i;
1504
1505  assert(model);
1506
1507  if (model->pathname)   free(model->pathname);
1508  if (model->mtllibname) free(model->mtllibname);
1509  if (model->vertices)   free(model->vertices);
1510  if (model->colors)     free(model->colors);
1511  if (model->normals)    free(model->normals);
1512  if (model->texcoords)  free(model->texcoords);
1513  if (model->facetnorms) free(model->facetnorms);
1514  if (model->triangles)  free(model->triangles);
1515  if (model->materials) {
1516    for (i = 0; i < model->nummaterials; i++)
1517    {
1518      free(model->materials[i].name);
1519      free(model->materials[i].textureName);
1520    }
1521  }
1522  free(model->materials);
1523  while(model->groups) {
1524    group = model->groups;
1525    model->groups = model->groups->next;
1526    free(group->name);
1527    free(group->triangles);
1528    free(group);
1529  }
1530
1531  free(model);
1532}
1533
1534/* glmReadOBJ: Reads a model description from a Wavefront .OBJ file.
1535 * Returns a pointer to the created object which should be free'd with
1536 * glmDelete().
1537 *
1538 * filename - name of the file containing the Wavefront .OBJ format data. 
1539 */
1540GLMmodel*
1541glmReadOBJ(char* filename)
1542{
1543  GLMmodel* model;
1544  FILE*     file;
1545
1546  /* open the file */
1547  file = fopen(filename, "r");
1548  if (!file) {
1549    fprintf(stderr, "glmReadOBJ() failed: can't open data file \"%s\".\n",
1550        filename);
1551    //exit(1);
1552    return NULL;
1553  }
1554
1555#if 0
1556  /* announce the model name */
1557  printf("Model: %s\n", filename);
1558#endif
1559
1560  /* allocate a new model */
1561  model = (GLMmodel*)malloc(sizeof(GLMmodel));
1562  model->pathname      = strdup(filename);
1563  model->mtllibname    = NULL;
1564  model->numvertices   = 0;
1565  model->vertices      = NULL;
1566  model->useColors     = false;
1567  model->colors        = NULL;
1568  model->numnormals    = 0;
1569  model->normals       = NULL;
1570  model->numtexcoords  = 0;
1571  model->texcoords     = NULL;
1572  model->numfacetnorms = 0;
1573  model->facetnorms    = NULL;
1574  model->numtriangles  = 0;
1575  model->triangles     = NULL;
1576  model->nummaterials  = 0;
1577  model->materials     = NULL;
1578  model->numgroups     = 0;
1579  model->groups        = NULL;
1580  model->position[0]   = 0.0;
1581  model->position[1]   = 0.0;
1582  model->position[2]   = 0.0;
1583
1584  /* make a first pass through the file to get a count of the number
1585     of vertices, normals, texcoords & triangles */
1586  _glmFirstPass(model, file);
1587
1588  /* allocate memory */
1589  model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
1590                     3 * (model->numvertices + 1));
1591
1592  if (model->useColors)                     
1593      model->colors = (osg::UByte4*)malloc(sizeof(osg::UByte4)*(model->numvertices + 1));
1594 
1595  model->triangles = (GLMtriangle*)malloc(sizeof(GLMtriangle) *
1596                      model->numtriangles);
1597  if (model->numnormals) {
1598    model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
1599                      3 * (model->numnormals + 1));
1600  }
1601  if (model->numtexcoords) {
1602    model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
1603                    2 * (model->numtexcoords + 1));
1604  }
1605
1606  /* rewind to beginning of file and read in the data this pass */
1607  rewind(file);
1608
1609  _glmSecondPass(model, file);
1610
1611  /* close the file */
1612  fclose(file);
1613
1614  return model;
1615}
1616
1617/* glmWriteOBJ: Writes a model description in Wavefront .OBJ format to
1618 * a file.
1619 *
1620 * model    - initialized GLMmodel structure
1621 * filename - name of the file to write the Wavefront .OBJ format data to
1622 * mode     - a bitwise or of values describing what is written to the file
1623 *            GLM_NONE     -  render with only vertices
1624 *            GLM_FLAT     -  render with facet normals
1625 *            GLM_SMOOTH   -  render with vertex normals
1626 *            GLM_TEXTURE  -  render with texture coords
1627 *            GLM_COLOR    -  render with colors (color material)
1628 *            GLM_MATERIAL -  render with materials
1629 *            GLM_COLOR and GLM_MATERIAL should not both be specified. 
1630 *            GLM_FLAT and GLM_SMOOTH should not both be specified. 
1631 */
1632GLvoid
1633glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode)
1634{
1635  unsigned int    i;
1636  FILE*     file;
1637  GLMgroup* group;
1638
1639  assert(model);
1640
1641  /* do a bit of warning */
1642  if (mode & GLM_FLAT && !model->facetnorms) {
1643    printf("glmWriteOBJ() warning: flat normal output requested "
1644       "with no facet normals defined.\n");
1645    mode &= ~GLM_FLAT;
1646  }
1647  if (mode & GLM_SMOOTH && !model->normals) {
1648    printf("glmWriteOBJ() warning: smooth normal output requested "
1649       "with no normals defined.\n");
1650    mode &= ~GLM_SMOOTH;
1651  }
1652  if (mode & GLM_TEXTURE && !model->texcoords) {
1653    printf("glmWriteOBJ() warning: texture coordinate output requested "
1654       "with no texture coordinates defined.\n");
1655    mode &= ~GLM_TEXTURE;
1656  }
1657  if (mode & GLM_FLAT && mode & GLM_SMOOTH) {
1658    printf("glmWriteOBJ() warning: flat normal output requested "
1659       "and smooth normal output requested (using smooth).\n");
1660    mode &= ~GLM_FLAT;
1661  }
1662
1663  /* open the file */
1664  file = fopen(filename, "w");
1665  if (!file) {
1666    fprintf(stderr, "glmWriteOBJ() failed: can't open file \"%s\" to write.\n",
1667        filename);
1668    //exit(1);
1669    return;
1670  }
1671
1672  /* spit out a header */
1673  fprintf(file, "#  \n");
1674  fprintf(file, "#  Wavefront OBJ generated by GLM library\n");
1675  fprintf(file, "#  \n");
1676  fprintf(file, "#  GLM library copyright (C) 1997 by Nate Robins\n");
1677  fprintf(file, "#  email: ndr@pobox.com\n");
1678  fprintf(file, "#  www:   http://www.pobox.com/~ndr\n");
1679  fprintf(file, "#  \n");
1680
1681  if (mode & GLM_MATERIAL && model->mtllibname) {
1682    fprintf(file, "\nmtllib %s\n\n", model->mtllibname);
1683    _glmWriteMTL(model, filename, model->mtllibname);
1684  }
1685
1686  /* spit out the vertices */
1687  fprintf(file, "\n");
1688  fprintf(file, "# %d vertices\n", model->numvertices);
1689  for (i = 1; i <= model->numvertices; i++) {
1690    fprintf(file, "v %f %f %f\n",
1691        model->vertices[3 * i + 0],
1692        model->vertices[3 * i + 1],
1693        model->vertices[3 * i + 2]);
1694  }
1695
1696  /* spit out the smooth/flat normals */
1697  if (mode & GLM_SMOOTH) {
1698    fprintf(file, "\n");
1699    fprintf(file, "# %d normals\n", model->numnormals);
1700    for (i = 1; i <= model->numnormals; i++) {
1701      fprintf(file, "vn %f %f %f\n",
1702          model->normals[3 * i + 0],
1703          model->normals[3 * i + 1],
1704          model->normals[3 * i + 2]);
1705    }
1706  } else if (mode & GLM_FLAT) {
1707    fprintf(file, "\n");
1708    fprintf(file, "# %d normals\n", model->numfacetnorms);
1709    for (i = 1; i <= model->numnormals; i++) {
1710      fprintf(file, "vn %f %f %f\n",
1711          model->facetnorms[3 * i + 0],
1712          model->facetnorms[3 * i + 1],
1713          model->facetnorms[3 * i + 2]);
1714    }
1715  }
1716
1717  /* spit out the texture coordinates */
1718  if (mode & GLM_TEXTURE) {
1719    fprintf(file, "\n");
1720    fprintf(file, "# %d texcoords\n", model->numtexcoords);
1721    for (i = 1; i <= model->numtexcoords; i++) {
1722      fprintf(file, "vt %f %f\n",
1723          model->texcoords[2 * i + 0],
1724          model->texcoords[2 * i + 1]);
1725    }
1726  }
1727
1728  fprintf(file, "\n");
1729  fprintf(file, "# %d groups\n", model->numgroups);
1730  fprintf(file, "# %d faces (triangles)\n", model->numtriangles);
1731  fprintf(file, "\n");
1732
1733  group = model->groups;
1734  while(group) {
1735    fprintf(file, "g %s\n", group->name);
1736    if (mode & GLM_MATERIAL)
1737      fprintf(file, "usemtl %s\n", model->materials[group->material].name);
1738    for (i = 0; i < group->numtriangles; i++) {
1739      if (mode & GLM_SMOOTH && mode & GLM_TEXTURE) {
1740    fprintf(file, "f %d/%d/%d %d/%d/%d %d/%d/%d\n",
1741        T(group->triangles[i]).vindices[0],
1742        T(group->triangles[i]).nindices[0],
1743        T(group->triangles[i]).tindices[0],
1744        T(group->triangles[i]).vindices[1],
1745        T(group->triangles[i]).nindices[1],
1746        T(group->triangles[i]).tindices[1],
1747        T(group->triangles[i]).vindices[2],
1748        T(group->triangles[i]).nindices[2],
1749        T(group->triangles[i]).tindices[2]);
1750      } else if (mode & GLM_FLAT && mode & GLM_TEXTURE) {
1751    fprintf(file, "f %d/%d %d/%d %d/%d\n",
1752        T(group->triangles[i]).vindices[0],
1753        T(group->triangles[i]).findex,
1754        T(group->triangles[i]).vindices[1],
1755        T(group->triangles[i]).findex,
1756        T(group->triangles[i]).vindices[2],
1757        T(group->triangles[i]).findex);
1758      } else if (mode & GLM_TEXTURE) {
1759    fprintf(file, "f %d/%d %d/%d %d/%d\n",
1760        T(group->triangles[i]).vindices[0],
1761        T(group->triangles[i]).tindices[0],
1762        T(group->triangles[i]).vindices[1],
1763        T(group->triangles[i]).tindices[1],
1764        T(group->triangles[i]).vindices[2],
1765        T(group->triangles[i]).tindices[2]);
1766      } else if (mode & GLM_SMOOTH) {
1767    fprintf(file, "f %d//%d %d//%d %d//%d\n",
1768        T(group->triangles[i]).vindices[0],
1769        T(group->triangles[i]).nindices[0],
1770        T(group->triangles[i]).vindices[1],
1771        T(group->triangles[i]).nindices[1],
1772        T(group->triangles[i]).vindices[2],
1773        T(group->triangles[i]).nindices[2]);
1774      } else if (mode & GLM_FLAT) {
1775    fprintf(file, "f %d//%d %d//%d %d//%d\n",
1776        T(group->triangles[i]).vindices[0],
1777        T(group->triangles[i]).findex,
1778        T(group->triangles[i]).vindices[1],
1779        T(group->triangles[i]).findex,
1780        T(group->triangles[i]).vindices[2],
1781        T(group->triangles[i]).findex);
1782      } else {
1783    fprintf(file, "f %d %d %d\n",
1784        T(group->triangles[i]).vindices[0],
1785        T(group->triangles[i]).vindices[1],
1786        T(group->triangles[i]).vindices[2]);
1787      }
1788    }
1789    fprintf(file, "\n");
1790    group = group->next;
1791  }
1792
1793  fclose(file);
1794}
1795
1796/* glmWeld: eliminate (weld) vectors that are within an epsilon of
1797 * each other.
1798 *
1799 * model      - initialized GLMmodel structure
1800 * epsilon    - maximum difference between vertices
1801 *              ( 0.00001 is a good start for a unitized model)
1802 *
1803 */
1804GLvoid
1805glmWeld(GLMmodel* model, GLfloat epsilon)
1806{
1807  GLfloat* vectors;
1808  GLfloat* copies;
1809  unsigned int   numvectors;
1810  unsigned int   i;
1811
1812  /* vertices */
1813  numvectors = model->numvertices;
1814  vectors    = model->vertices;
1815  copies = _glmWeldVectors(vectors, &numvectors, epsilon);
1816
1817  printf("glmWeld(): %d redundant vertices.\n",
1818     model->numvertices - numvectors - 1);
1819
1820  for (i = 0; i < model->numtriangles; i++) {
1821    T(i).vindices[0] = (unsigned int)vectors[3 * T(i).vindices[0] + 0];
1822    T(i).vindices[1] = (unsigned int)vectors[3 * T(i).vindices[1] + 0];
1823    T(i).vindices[2] = (unsigned int)vectors[3 * T(i).vindices[2] + 0];
1824  }
1825
1826  /* free space for old vertices */
1827  free(vectors);
1828
1829  /* allocate space for the new vertices */
1830  model->numvertices = numvectors;
1831  model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
1832                     3 * (model->numvertices + 1));
1833
1834  /* copy the optimized vertices into the actual vertex list */
1835  for (i = 1; i <= model->numvertices; i++) {
1836    model->vertices[3 * i + 0] = copies[3 * i + 0];
1837    model->vertices[3 * i + 1] = copies[3 * i + 1];
1838    model->vertices[3 * i + 2] = copies[3 * i + 2];
1839  }
1840
1841  free(copies);
1842}
1843
1844
1845#if 0
1846  /* normals */
1847  if (model->numnormals) {
1848  numvectors = model->numnormals;
1849  vectors    = model->normals;
1850  copies = _glmOptimizeVectors(vectors, &numvectors);
1851
1852  printf("glmOptimize(): %d redundant normals.\n",
1853     model->numnormals - numvectors);
1854
1855  for (i = 0; i < model->numtriangles; i++) {
1856    T(i).nindices[0] = (unsigned int)vectors[3 * T(i).nindices[0] + 0];
1857    T(i).nindices[1] = (unsigned int)vectors[3 * T(i).nindices[1] + 0];
1858    T(i).nindices[2] = (unsigned int)vectors[3 * T(i).nindices[2] + 0];
1859  }
1860
1861  /* free space for old normals */
1862  free(vectors);
1863
1864  /* allocate space for the new normals */
1865  model->numnormals = numvectors;
1866  model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
1867                    3 * (model->numnormals + 1));
1868
1869  /* copy the optimized vertices into the actual vertex list */
1870  for (i = 1; i <= model->numnormals; i++) {
1871    model->normals[3 * i + 0] = copies[3 * i + 0];
1872    model->normals[3 * i + 1] = copies[3 * i + 1];
1873    model->normals[3 * i + 2] = copies[3 * i + 2];
1874  }
1875
1876  free(copies);
1877  }
1878
1879  /* texcoords */
1880  if (model->numtexcoords) {
1881  numvectors = model->numtexcoords;
1882  vectors    = model->texcoords;
1883  copies = _glmOptimizeVectors(vectors, &numvectors);
1884
1885  printf("glmOptimize(): %d redundant texcoords.\n",
1886     model->numtexcoords - numvectors);
1887
1888  for (i = 0; i < model->numtriangles; i++) {
1889    for (j = 0; j < 3; j++) {
1890      T(i).tindices[j] = (unsigned int)vectors[3 * T(i).tindices[j] + 0];
1891    }
1892  }
1893
1894  /* free space for old texcoords */
1895  free(vectors);
1896
1897  /* allocate space for the new texcoords */
1898  model->numtexcoords = numvectors;
1899  model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
1900                      2 * (model->numtexcoords + 1));
1901
1902  /* copy the optimized vertices into the actual vertex list */
1903  for (i = 1; i <= model->numtexcoords; i++) {
1904    model->texcoords[2 * i + 0] = copies[2 * i + 0];
1905    model->texcoords[2 * i + 1] = copies[2 * i + 1];
1906  }
1907
1908  free(copies);
1909  }
1910#endif
1911
1912#if 0
1913  /* look for unused vertices */
1914  /* look for unused normals */
1915  /* look for unused texcoords */
1916  for (i = 1; i <= model->numvertices; i++) {
1917    for (j = 0; j < model->numtriangles; i++) {
1918      if (T(j).vindices[0] == i ||
1919      T(j).vindices[1] == i ||
1920      T(j).vindices[1] == i)
1921    break;
1922    }
1923  }
1924#endif
Note: See TracBrowser for help on using the browser.