/***************************************************************************
 *   Copyright (C) 2007 by A.J. Tavakoli                                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#ifndef MD5MODEL_H
#define MD5MODEL_H

#include <string>
#include <stdexcept>
#include <vector>
#include <map>
#include <fstream>
#include "Math3D/Vector2.h"
#include "Math3D/Vector3.h"
#include "Math3D/Quat.h"
#include "Video.h"


class MD5Model {
public:
  class Exception : public std::runtime_error {
  public:
    Exception(const std::string &msg): std::runtime_error(msg) { }
  };

  class Tri {
  public:
    unsigned int v[3]; // vertex indices
  };

  class VertexInfo {
  public:
    int weightIndex;
    int weightCount;
  };

  class Weight {
  public:
    int joint;
    float w;
    float pos[3];
  };

  class Mesh {
  public:
    Mesh();

    int texID;
    int nmID;
    std::vector<VertexInfo> vertsInfo;
    std::vector<Video::Vertex> verts;
    std::vector<Tri> tris;
    std::vector<Weight> weights;
  };

  MD5Model();
  ~MD5Model();

  void clear();
  void loadMesh(const char *filename);
  int  loadAnim(const char *filename);
  void setAnim(int animIndex, int frameIndex = 0, float t=0.0f);
  void setFrame(int frameIndex);
  void animate(float dt);

  void removeRootTranslation();

  inline int                  getNumAnims()  const { return int(anims.size());  }
  inline int                  getNumMeshes() const { return int(meshes.size()); }
  inline const Mesh*          getMesh(int i) const { return meshes[i];          }

  int getNumAnimFrames(int animIndex) const;
  int getAnimFrameRate(int animIndex) const;
  void getBoundingBox(float *min, float *max) const;
  AABB getBoundingBox() const;
protected:
  enum TOKEN { TOKEN_KEYWORD,
               TOKEN_INT,
               TOKEN_FLOAT,
               TOKEN_STRING,
               TOKEN_LBRACE,
               TOKEN_RBRACE,
               TOKEN_LPAREN,
               TOKEN_RPAREN,
               TOKEN_INVALID };

  class Joint {
  public:
    std::string name;
    float pos[3];
    Math3D::Quat<float> quat;
    int parent;
    std::vector<int> children;
  };

  class Frame {
  public:
    std::vector<float> animatedComponents;
    std::vector<Joint> joints;
    float min[3]; // min point of bounding box
    float max[3]; // max point of bounding box
  };

  class JointInfo {
  public:
    std::string name;
    int parentIndex;
    int flags;
    int startIndex;
  };

  // stores data from an anim file
  class Anim {
  public:
    Anim();
    int numFrames;
    int frameRate;
    int numAnimatedComponents;
    std::vector<Frame> frames;
    std::vector<Joint> baseJoints;
    std::vector<JointInfo> jointInfo;
  };

  // methods for parser
  void  readElements(std::ifstream &fin);
  void  readAnimElements(std::ifstream &fin, Anim &anim);
  void  readCommandLineEl(std::ifstream &fin);
  void  readNumMeshesEl(std::ifstream &fin);
  void  readNumJointsEl(std::ifstream &fin);
  void  readNumFramesEl(std::ifstream &fin, Anim &anim);
  void  readFrameRateEl(std::ifstream &fin, Anim &anim);
  void  readNumAnimatedComponentsEl(std::ifstream &fin, Anim &anim);
  void  readJointsEl(std::ifstream &fin);
  void  readMeshEl(std::ifstream &fin);
  void  readHierarchyEl(std::ifstream &fin, Anim &anim);
  void  readBoundsEl(std::ifstream &fin, Anim &anim);
  void  readBaseframeEl(std::ifstream &fin, Anim &anim);
  void  readFrameEl(std::ifstream &fin, Anim &anim);
  int   readInt(std::ifstream &fin);
  float readFloat(std::ifstream &fin);
  void  readVec(std::ifstream &fin, float *v, int n);

  // methods for lexer
  void readString(std::ifstream &fin, std::string &str);
  void skipComments(std::ifstream &fin);
  void skipWhitespace(std::ifstream &fin);
  TOKEN getNextToken(std::ifstream &fin, std::string *tokStr=NULL);

  // utility method to compute w component of a normalized quaternion
  Math3D::Quat<float> buildQuat(float x, float y, float z) const;

  void buildVerts();
  void buildVerts(Frame &frame);
  void buildTBN();
  void buildFrames(Anim &anim);

  int numJoints;
  int numMeshes;
  int currAnim;
  int currFrame;
  float animTime;
  Frame interpFrame; // used to interpolate between frames

  typedef std::map< std::string, std::pair<int, int> > TexIDMap;
  TexIDMap texIDs; // maps texture names to IDs
                   // (texture ID, normal map ID)

  std::vector<Mesh*> meshes;
  std::vector<Joint> joints;
  std::vector<Anim*> anims;

  std::vector<VertexInfo> vertsInfo;
};


#endif
