Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 10620 was 10488, checked in by patrick, 18 years ago

less md2 debug pls

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