Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/terrain.older/src/lib/graphics/importer/md2/md2Model.cc @ 10610

Last change on this file since 10610 was 9140, checked in by bensch, 18 years ago

merged back

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