Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/graphics/importer/md2Model.cc @ 8314

Last change on this file since 8314 was 8309, checked in by bensch, 19 years ago

trunk: better texture-sequence

File size: 17.6 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Patrick Boenzli
13*/
14
15#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_IMPORTER
16#include "config.h"
17#ifdef HAVE_SDL_SDL_H
18#include <SDL/SDL.h>
19#include <SDL/SDL_endian.h>
20#else
21#include <SDL.h>
22#include <SDL_endian.h>
23#endif
24#include "md2Model.h"
25#include "material.h"
26
27#include "debug.h"
28#include "util/loading/resource_manager.h"
29
30using namespace std;
31
32//! the model anorms
33sVec3D MD2Model::anorms[NUM_VERTEX_NORMALS] = {
34 #include "anorms.h"
35};
36
37//! anormal dots, no idea of how this shall work, but it does
38float MD2Model::anormsDots[SHADEDOT_QUANT][256] = {
39  #include "anormtab.h"
40};
41
42
43//! the angle under which the model is viewd, used internaly
44float md2Angle = 0.0f;
45
46
47//! list of all different animations a std md2model supports
48sAnim MD2Model::animationList[21] =
49  {
50 // begin, end, fps, interruptable
51    {   0,  39,  9, 1 },   //!< STAND
52    {  40,  45, 10, 1 },   //!< RUN
53    {  46,  53, 10, 0 },   //!< ATTACK
54    {  54,  57,  7, 1 },   //!< PAIN_A
55    {  58,  61,  7, 1 },   //!< PAIN_B
56    {  62,  65,  7, 1 },   //!< PAIN_C
57    {  66,  71,  7, 0 },   //!< JUMP
58    {  72,  83,  7, 1 },   //!< FLIP
59    {  84,  94,  7, 1 },   //!< SALUTE
60    {  95, 111, 10, 1 },   //!< FALLBACK
61    { 112, 122,  7, 1 },   //!< WAVE
62    { 123, 134,  6, 1 },   //!< POINTT
63    { 135, 153, 10, 1 },   //!< CROUCH_STAND
64    { 154, 159,  7, 1 },   //!< CROUCH_WALK
65    { 160, 168, 10, 1 },   //!< CROUCH_ATTACK
66    { 196, 172,  7, 1 },   //!< CROUCH_PAIN
67    { 173, 177,  5, 0 },   //!< CROUCH_DEATH
68    { 178, 183,  10, 0 },   //!< DEATH_FALLBACK
69    { 184, 189,  10, 0 },   //!< DEATH_FALLFORWARD
70    { 190, 197,  10, 0 },   //!< DEATH_FALLBACKSLOW
71    { 198, 198,  5, 1 },   //!< BOOM
72  };
73
74
75#ifdef SDL_LIL_ENDIAN
76#define BULK_CONV( _ptr, _num ) do { \
77        int  _cnt = _num;\
78        int* _iptr = (int*)_ptr;\
79        for( int _l = 0; _l<_cnt; ++_l )\
80                _iptr[_l] = SDL_SwapLE32( _iptr[_l] );\
81} while( 0 )
82#define BULK_CONV16( _ptr, _num ) do { \
83        short  _cnt = _num;\
84        short* _iptr = (short*)_ptr;\
85        for( int _l = 0; _l<_cnt; ++_l )\
86                _iptr[_l] = SDL_SwapLE16( _iptr[_l] );\
87} while( 0 )
88#else
89#define BULK_CONV( _ptr, _num )
90#define BULK_CONV16( _ptr, _num )
91#endif
92
93/********************************************************************************
94 *   MD2Model                                                                   *
95 ********************************************************************************/
96
97/**
98  \brief simple constructor initializing all variables
99*/
100MD2Model::MD2Model(const std::string& modelFileName, const std::string& skinFileName, float scale)
101{
102  this->setClassID(CL_MD2_MODEL, "MD2Model");
103  /* this creates the data container via ressource manager */
104  if (!modelFileName.empty())
105    this->data = (MD2Data*)ResourceManager::getInstance()->load(
106                        modelFileName, MD2, RP_GAME, skinFileName, scale);
107
108        //When arriving here it is assumed that everything is in the correct byte order.
109  if( unlikely(this->data == NULL))
110    PRINTF(0)("The model was not found, MD2Model Loader finished abnormaly. Update the data-repos\n");
111
112  this->scaleFactor = scale;
113
114  shadeDots = MD2Model::anormsDots[0];
115  /* set the animation stat mannualy */
116  this->animationState.type = STAND;
117  this->animationState.numPlays = 1;
118  this->setAnim(STAND);
119
120  //this->debug();
121
122    //write the modelinfo information
123  this->pModelInfo.numVertices = this->data->numVertices;
124  this->pModelInfo.numTriangles = this->data->numTriangles;
125  this->pModelInfo.numNormals = 0;
126  this->pModelInfo.numTexCoor = this->data->numTexCoor;
127
128  this->pModelInfo.pVertices = (float*)this->data->pVertices;
129
130  this->pModelInfo.pNormals = NULL;
131
132  this->pModelInfo.pTexCoor = (float*)this->data->pTexCoor;
133
134  // triangle conversion
135  this->pModelInfo.pTriangles = new sTriangleExt[this->data->numTriangles];
136  for( int i = 0; i < this->data->numTriangles; i++)
137  {
138    this->pModelInfo.pTriangles[i].indexToVertices[0] = this->data->pTriangles[i].indexToVertices[0];
139    this->pModelInfo.pTriangles[i].indexToVertices[1] = this->data->pTriangles[i].indexToVertices[1];
140    this->pModelInfo.pTriangles[i].indexToVertices[2] = this->data->pTriangles[i].indexToVertices[2];
141
142    this->pModelInfo.pTriangles[i].indexToTexCoor[0] = this->data->pTriangles[i].indexToTexCoor[0];
143    this->pModelInfo.pTriangles[i].indexToTexCoor[1] = this->data->pTriangles[i].indexToTexCoor[1];
144    this->pModelInfo.pTriangles[i].indexToTexCoor[2] = this->data->pTriangles[i].indexToTexCoor[2];
145  }
146}
147
148
149/**
150  \brief simple destructor, dereferencing all variables
151
152  this is where the ressource manager is cleaning the stuff
153*/
154MD2Model::~MD2Model()
155{
156  this->pModelInfo.pVertices = NULL;
157  this->pModelInfo.pNormals = NULL;
158  this->pModelInfo.pTexCoor = NULL;
159  this->pModelInfo.pTriangles = NULL;
160
161  ResourceManager::getInstance()->unload(this->data);
162}
163
164
165/**
166 *  initializes an array of vert with the current frame scaled vertices
167 * @param this->verticesList: the list of vertices to interpolate between
168
169   we won't use the pVertices array directly, since its much easier and we need
170   saving of data anyway
171*/
172void MD2Model::interpolate(/*sVec3D* this->verticesList*/)
173{
174  sVec3D* currVec;
175  sVec3D* nextVec;
176
177  currVec = &this->data->pVertices[this->data->numVertices * this->animationState.currentFrame];
178  nextVec = &this->data->pVertices[this->data->numVertices * this->animationState.nextFrame];
179
180  for( int i = 0; i < this->data->numVertices; ++i)
181    {
182      this->verticesList[i][0] = currVec[i][0] + this->animationState.interpolationState * (nextVec[i][0] - currVec[i][0]);
183      this->verticesList[i][1] = currVec[i][1] + this->animationState.interpolationState * (nextVec[i][1] - currVec[i][1]);
184      this->verticesList[i][2] = currVec[i][2] + this->animationState.interpolationState * (nextVec[i][2] - currVec[i][2]);
185    }
186}
187
188
189/**
190  \brief sets the animation type
191* @param type: animation type
192
193  the animation types can be looked up in the animationType table
194*/
195void MD2Model::setAnim(int type, int animPlayback)
196{
197  if( (type < 0) || (type > MAX_ANIMATIONS) )
198    type = STAND;
199
200  if( MD2Model::animationList[this->animationState.type].bStoppable == 0)
201  {
202    if( this->animationState.numPlays == 0 )
203      return;
204  }
205
206  this->animationState.startFrame = animationList[type].firstFrame;
207  this->animationState.endFrame = animationList[type].lastFrame;
208  this->animationState.nextFrame = animationList[type].firstFrame + 1;
209  this->animationState.fps = animationList[type].fps;
210  this->animationState.type = type;
211  this->animationState.numPlays = 0;
212  this->animationState.animPlaybackMode = animPlayback;
213
214  this->animationState.interpolationState = 0.0f;
215  this->animationState.localTime = 0.0f;
216  this->animationState.lastTime = 0.0f;
217  this->animationState.currentFrame = animationList[type].firstFrame;
218}
219
220
221/**
222  \brief sets the time in seconds passed since the last tick
223* @param time: in sec
224*/
225void MD2Model::tick(float time)
226{
227  this->animate(time);
228  this->processLighting();
229  this->interpolate(/*this->verticesList*/);
230}
231
232
233/**
234 * @brief draws the model: interface for all other classes out in the world
235 * @todo make it const and virtual
236 * FIXME
237 */
238void MD2Model::draw() const
239{
240  glPushMatrix();
241  this->renderFrame();
242  // renderFrameTriangles();
243  glPopMatrix();
244}
245
246
247/**
248  \brief this is an internal function to render this special frame selected by animate()
249*/
250void MD2Model::renderFrame() const
251{
252  int* pCommands = this->data->pGLCommands;
253
254  /* some face culling stuff */
255  glPushAttrib(GL_POLYGON_BIT);
256  glFrontFace(GL_CW);
257  glEnable(GL_CULL_FACE);
258  glCullFace(GL_BACK);
259
260  this->data->material.select();
261
262  /* draw the triangles */
263  while( int i = *(pCommands++)) /* strange looking while loop for maximum performance */
264    {
265      if( i < 0)
266        {
267          glBegin(GL_TRIANGLE_FAN);
268          i = -i;
269        }
270      else
271        {
272          glBegin(GL_TRIANGLE_STRIP);
273        }
274
275      for(; i > 0; i--, pCommands += 3) /* down counting for loop, next 3 gl commands */
276        {
277          glTexCoord2f( ((float *)pCommands)[0], ((float *)pCommands)[1] );
278          glNormal3fv(anorms[this->data->pLightNormals[pCommands[2]]]);
279          glVertex3fv(this->verticesList[pCommands[2]]);
280        }
281      glEnd();
282
283    }
284  glDisable(GL_CULL_FACE);
285  glPopAttrib();
286}
287
288
289void MD2Model::renderFrameTriangles() const
290{
291  //static sVec3D this->verticesList[MD2_MAX_VERTICES]; /* performance: created only once in a lifetime */
292  int* pCommands = this->data->pGLCommands;
293  /* some face culling stuff */
294//   glPushAttrib(GL_POLYGON_BIT);
295//   glFrontFace(GL_CW);
296//   glEnable(GL_CULL_FACE);
297//   glCullFace(GL_BACK);
298//
299//   this->processLighting();
300//   this->interpolate(/*this->verticesList*/);
301  this->data->material.select();
302
303  /* draw the triangles */
304  glBegin(GL_TRIANGLES);
305
306  for( int i = 0, k = 0; i < this->data->numTriangles; ++i, k += 3)
307  {
308    float* v = this->data->pVertices[this->data->pTriangles[i].indexToVertices[0]];
309
310    printf("triangle: %i\n", i);
311    printf("     v0: (%f, %f, %f)\n", v[0], v[1], v[2]);
312    v = this->data->pVertices[this->data->pTriangles[i].indexToVertices[1]];
313    printf("     v1: (%f, %f, %f)\n", v[0], v[1], v[2]);
314    v = this->data->pVertices[this->data->pTriangles[i].indexToVertices[2]];
315    printf("     v2: (%f, %f, %f)\n", v[0], v[1], v[2]);
316
317
318    glNormal3f(anorms[i][0], anorms[i][1], anorms[i][2]);
319    glVertex3fv(this->data->pVertices[this->data->pTriangles[i].indexToVertices[0]]);
320
321    glNormal3f(anorms[i][0], anorms[i][1], anorms[i][2]);
322    glVertex3fv(this->data->pVertices[this->data->pTriangles[i].indexToVertices[1]]);
323
324    glNormal3f(anorms[i][0], anorms[i][1], anorms[i][2]);
325    glVertex3fv(this->data->pVertices[this->data->pTriangles[i].indexToVertices[2]]);
326  }
327
328  glEnd();
329}
330
331
332/**
333  \brief animates the current model
334
335  depending on the time passed (tick function), the player will select another model
336*/
337void MD2Model::animate(float time)
338{
339  this->animationState.localTime += time;
340
341  if( this->animationState.localTime - this->animationState.lastTime > (1.0f / this->animationState.fps))
342    {
343      this->animationState.currentFrame = this->animationState.nextFrame;
344      this->animationState.nextFrame++;
345
346      if( this->animationState.nextFrame > this->animationState.endFrame )
347      {
348        if( this->animationState.animPlaybackMode == MD2_ANIM_LOOP)
349        {
350          this->animationState.nextFrame = this->animationState.startFrame;
351          this->animationState.numPlays++;
352        }
353        else
354        {
355          this->animationState.nextFrame = this->animationState.endFrame;
356        }
357      }
358      this->animationState.lastTime = this->animationState.localTime;
359    }
360
361//     if( this->animationState.currentFrame > (this->data->numFrames - 1) )
362//       this->animationState.currentFrame = 0;
363
364//     if( (this->animationState.nextFrame > (this->data->numFrames - 1)) && this->animationState.animPlaybackMode == MD2_ANIM_LOOP)
365//     this->animationState.nextFrame = 0;
366
367  this->animationState.interpolationState = this->animationState.fps *
368    (this->animationState.localTime - this->animationState.lastTime);
369}
370
371
372/**
373  \brief this is how id is precessing their lightning
374
375  the details of how the whole lighting process is beeing handled - i have no idea... :)
376*/
377void MD2Model::processLighting()
378{
379  shadeDots = anormsDots[((int)(md2Angle*(SHADEDOT_QUANT / 360.0)))&(SHADEDOT_QUANT - 1)];
380}
381
382
383/**
384  \brief prints out debug informations
385*/
386void MD2Model::debug()
387{
388  //PRINTF(0)("\n==========================| MD2Model::debug() |===\n");
389  PRINTF(0)("=  Model FileName:\t%s\n", this->data->fileName.c_str());
390  PRINTF(0)("=  Skin FileName:\t%s\n",
391                this->data->skinFileName.c_str());
392  PRINTF(0)("=  Size in Memory:\t%i Bytes\n",
393                this->data->header->frameSize * this->data->header->numFrames + 64); // 64bytes is the header size
394  PRINTF(0)("=  Number of Vertices:\t%i\n", this->data->header->numVertices);
395  PRINTF(0)("=  Number of Frames: \t%i\n", this->data->header->numFrames);
396  PRINTF(0)("=  Height, Width:\t%i, %i\n", this->data->header->skinHeight, this->data->header->skinWidth);
397  PRINTF(0)("=  Pointer to the data object: %p\n", this->data);
398  //PRINTF(0)("===================================================\n\n");
399}
400
401
402/********************************************************************************
403 *   MD2Data                                                                    *
404 ********************************************************************************/
405
406/**
407  \brief simple constructor
408*/
409MD2Data::MD2Data(const std::string& modelFileName, const std::string& skinFileName, float scale)
410{
411  scale *= 0.1f;
412
413  this->pVertices = NULL;
414  this->pGLCommands = NULL;
415  this->pLightNormals = NULL;
416  this->pTexCoor = NULL;
417
418  this->numFrames = 0;
419  this->numVertices = 0;
420  this->numGLCommands = 0;
421  this->numTexCoor = 0;
422
423//   this->scaleFactor = 1.0f;
424  this->scaleFactor = scale;
425
426  this->fileName = "";
427  this->skinFileName = "";
428  this->loadModel(modelFileName);
429  this->loadSkin(skinFileName);
430}
431
432
433/**
434  \brief simple destructor
435
436  this will clean out all the necessary data for a specific md2model
437*/
438MD2Data::~MD2Data()
439{
440/*  delete this->header;
441
442  delete [] this->pVertices;
443  delete [] this->pGLCommands;
444  delete [] this->pLightNormals;
445  delete [] this->pTexCoor;*/
446}
447
448
449
450/**
451  \brief this will load the whole model data (vertices, opengl command list, ...)
452* @param fileName: the name of the model file
453  \return true if success
454*/
455bool MD2Data::loadModel(const std::string& fileName)
456{
457  FILE *pFile;                            //file stream
458  char* buffer;                           //buffer for frame data
459  sFrame* frame;                          //temp frame
460  sVec3D *pVertex;
461  int* pNormals;
462
463  //! @todo this chek should include deleting a loaded model (eventually)
464  if (fileName.empty())
465    return false;
466
467  pFile = fopen(fileName.c_str(), "rb");
468  if( unlikely(!pFile))
469    {
470      PRINTF(1)("Couldn't open the MD2 File for loading. Exiting.\n");
471      return false;
472    }
473  this->header = new MD2Header;
474  fread(this->header, 1, sizeof(MD2Header), pFile);
475        BULK_CONV( this->header, sizeof(MD2Header)/4 );
476  /* check for the header version: make sure its a md2 file :) */
477  if( unlikely( this->header->version != MD2_VERSION) && unlikely( this->header->ident != MD2_IDENT))
478    {
479      PRINTF(1)("Couldn't load file %s: invalid file format: stop loading\n", fileName.c_str());
480      return false;
481    }
482
483  this->fileName = fileName;
484  /* got the data: map it to locals */
485  this->numFrames = this->header->numFrames;
486  this->numVertices = this->header->numVertices;
487  this->numTriangles = this->header->numTriangles;
488  this->numGLCommands = this->header->numGlCommands;
489  this->numTexCoor = this->header->numTexCoords;
490  /* allocate memory for the data storage */
491  this->pVertices = new sVec3D[this->numVertices * this->numFrames];
492  this->pGLCommands = new int[this->numGLCommands];
493  this->pLightNormals = new int[this->numVertices * this->numFrames];
494  this->pTriangles = new sTriangle[this->numTriangles];
495  this->pTexCoor = new sTexCoor[this->numTexCoor];
496  buffer = new char[this->numFrames * this->header->frameSize];
497
498
499  /* read frame data from the file to a temp buffer */
500  fseek(pFile, this->header->offsetFrames, SEEK_SET);
501  fread(buffer, this->header->frameSize, this->numFrames, pFile);
502        //BULK_CONV( buffer, this->header->frameSize*this->numFrames*sizeof(char)/4 );
503  /* read opengl commands */
504  fseek(pFile, this->header->offsetGlCommands, SEEK_SET);
505
506  fread(this->pGLCommands, sizeof(int), this->numGLCommands, pFile);
507        BULK_CONV( this->pGLCommands, this->numGLCommands );
508  /* triangle list */
509  fseek(pFile, this->header->offsetTriangles, SEEK_SET);
510  fread(this->pTriangles, sizeof(sTriangle), this->numTriangles, pFile);
511        BULK_CONV16( this->pTriangles, this->numTriangles*sizeof(sTriangle)/2 );
512
513  /*  read in texture coordinates */
514  fseek(pFile, this->header->offsetTexCoords, SEEK_SET);
515  fread(this->pTexCoor, sizeof(sTexCoor), this->numTexCoor, pFile);
516        BULK_CONV16( this->pTexCoor, this->numTexCoor*sizeof(sTexCoor)/2 );
517
518  for(int i = 0; i < this->numFrames; ++i)
519    {
520      frame = (sFrame*)(buffer + this->header->frameSize * i);
521                        //Convert the translate and scale Vec3D if needed.
522                        BULK_CONV( frame, 6 );
523                        BULK_CONV( frame->pVertices, 3 );
524      pVertex = this->pVertices + this->numVertices  * i;
525      pNormals = this->pLightNormals + this->numVertices * i;
526
527      for(int j = 0; j < this->numVertices; ++j)
528        {
529          /* SPEEDUP: *(pVerts + i + 0) = (*(frame->pVertices + i + 0)...  */
530           pVertex[j][0] = ((frame->pVertices[j].v[0] * frame->scale[0] ) + frame->translate[0] )* this->scaleFactor;
531           pVertex[j][1] = ((frame->pVertices[j].v[2] * frame->scale[2]) + frame->translate[2]) * this->scaleFactor;
532           pVertex[j][2] = (-1.0 * (frame->pVertices[j].v[1] * frame->scale[1] + frame->translate[1])) * this->scaleFactor;
533
534          //printf("vertex %i/%i: (%f, %f, %f)\n", j, this->numVertices, pVertex[j][0], pVertex[j][1], pVertex[j][2]);
535
536          pNormals[j] = frame->pVertices[j].lightNormalIndex;
537        }
538    }
539    PRINTF(4)("Finished loading the md2 file\n");
540
541  delete [] buffer;
542  fclose(pFile);
543}
544
545
546/**
547  \brief loads the skin/material stuff
548* @param fileName: name of the skin file
549  \return true if success
550*/
551bool MD2Data::loadSkin(const std::string& fileName)
552{
553  if( fileName.empty())
554    {
555      this->skinFileName = "";
556      return false;
557    }
558
559  this->skinFileName = fileName;
560
561  this->material.setName("md2ModelMaterial");
562  this->material.setDiffuseMap(fileName);
563  this->material.setIllum(3);
564  this->material.setAmbient(1.0, 1.0, 1.0);
565}
Note: See TracBrowser for help on using the repository browser.