MD2Loader.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development Team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the ASSIMP team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the ASSIMP Development Team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the MD2 importer class */
  35. #include "MD2Loader.h"
  36. #include "MaterialSystem.h"
  37. #include "MD2NormalTable.h"
  38. #include "../include/IOStream.h"
  39. #include "../include/IOSystem.h"
  40. #include "../include/aiMesh.h"
  41. #include "../include/aiScene.h"
  42. #include "../include/aiAssert.h"
  43. #include <boost/scoped_ptr.hpp>
  44. using namespace Assimp;
  45. // ------------------------------------------------------------------------------------------------
  46. inline bool is_qnan(float p_fIn)
  47. {
  48. // NOTE: Comparison against qnan is generally problematic
  49. // because qnan == qnan is false AFAIK
  50. union FTOINT
  51. {
  52. float fFloat;
  53. int32_t iInt;
  54. } one, two;
  55. one.fFloat = std::numeric_limits<float>::quiet_NaN();
  56. two.fFloat = p_fIn;
  57. return (one.iInt == two.iInt);
  58. }
  59. // ------------------------------------------------------------------------------------------------
  60. inline bool is_not_qnan(float p_fIn)
  61. {
  62. return !is_qnan(p_fIn);
  63. }
  64. // ------------------------------------------------------------------------------------------------
  65. // Constructor to be privately used by Importer
  66. MD2Importer::MD2Importer()
  67. {
  68. }
  69. // ------------------------------------------------------------------------------------------------
  70. // Destructor, private as well
  71. MD2Importer::~MD2Importer()
  72. {
  73. }
  74. // ------------------------------------------------------------------------------------------------
  75. // Returns whether the class can handle the format of the given file.
  76. bool MD2Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  77. {
  78. // simple check of file extension is enough for the moment
  79. std::string::size_type pos = pFile.find_last_of('.');
  80. // no file extension - can't read
  81. if( pos == std::string::npos)
  82. return false;
  83. std::string extension = pFile.substr( pos);
  84. // not brilliant but working ;-)
  85. if( extension == ".md2" || extension == ".MD2" ||
  86. extension == ".mD2" || extension == ".Md2")
  87. return true;
  88. return false;
  89. }
  90. // ------------------------------------------------------------------------------------------------
  91. // Imports the given file into the given scene structure.
  92. void MD2Importer::InternReadFile(
  93. const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  94. {
  95. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  96. // Check whether we can read from the file
  97. if( file.get() == NULL)
  98. {
  99. throw new ImportErrorException( "Failed to open md2 file " + pFile + ".");
  100. }
  101. // check whether the md3 file is large enough to contain
  102. // at least the file header
  103. size_t fileSize = file->FileSize();
  104. if( fileSize < sizeof(MD2::Header))
  105. {
  106. throw new ImportErrorException( ".md2 File is too small.");
  107. }
  108. // allocate storage and copy the contents of the file to a memory buffer
  109. this->mBuffer = new unsigned char[fileSize];
  110. file->Read( (void*)mBuffer, 1, fileSize);
  111. this->m_pcHeader = (const MD2::Header*)this->mBuffer;
  112. // check magic number
  113. if (this->m_pcHeader->magic != AI_MD2_MAGIC_NUMBER_BE &&
  114. this->m_pcHeader->magic != AI_MD2_MAGIC_NUMBER_LE)
  115. {
  116. throw new ImportErrorException( "Invalid md2 file: Magic bytes not found");
  117. }
  118. // check file format version
  119. if (this->m_pcHeader->version != 8)
  120. {
  121. throw new ImportErrorException( "Unsupported md3 file version");
  122. }
  123. // check some values whether they are valid
  124. if (0 == this->m_pcHeader->numFrames)
  125. {
  126. throw new ImportErrorException( "Invalid md2 file: NUM_FRAMES is 0");
  127. }
  128. if (this->m_pcHeader->offsetEnd > (int32_t)fileSize)
  129. {
  130. throw new ImportErrorException( "Invalid md2 file: File is too small");
  131. }
  132. // there won't be more than one mesh inside the file
  133. pScene->mNumMaterials = 1;
  134. pScene->mRootNode = new aiNode();
  135. pScene->mRootNode->mNumMeshes = 1;
  136. pScene->mRootNode->mMeshes = new unsigned int[1];
  137. pScene->mRootNode->mMeshes[0] = 0;
  138. pScene->mMaterials = new aiMaterial*[1];
  139. pScene->mMaterials[0] = new MaterialHelper();
  140. pScene->mNumMeshes = 1;
  141. pScene->mMeshes = new aiMesh*[1];
  142. pScene->mMeshes[0] = new aiMesh();
  143. // navigate to the begin of the frame data
  144. const MD2::Frame* pcFrame = (const MD2::Frame*) ((unsigned char*)this->m_pcHeader +
  145. this->m_pcHeader->offsetFrames);
  146. // navigate to the begin of the triangle data
  147. MD2::Triangle* pcTriangles = (MD2::Triangle*) ((unsigned char*)this->m_pcHeader +
  148. this->m_pcHeader->offsetTriangles);
  149. // navigate to the begin of the tex coords data
  150. const MD2::TexCoord* pcTexCoords = (const MD2::TexCoord*) ((unsigned char*)this->m_pcHeader +
  151. this->m_pcHeader->offsetTexCoords);
  152. // navigate to the begin of the vertex data
  153. const MD2::Vertex* pcVerts = (const MD2::Vertex*) (pcFrame->vertices);
  154. pScene->mMeshes[0]->mNumFaces = this->m_pcHeader->numTriangles;
  155. pScene->mMeshes[0]->mFaces = new aiFace[this->m_pcHeader->numTriangles];
  156. // temporary vectors for position/texture coordinates/normals
  157. std::vector<aiVector3D> vPositions;
  158. std::vector<aiVector3D> vTexCoords;
  159. std::vector<aiVector3D> vNormals;
  160. vPositions.resize(pScene->mMeshes[0]->mNumFaces*3,aiVector3D());
  161. vTexCoords.resize(pScene->mMeshes[0]->mNumFaces*3,aiVector3D(
  162. std::numeric_limits<float>::quiet_NaN(),
  163. std::numeric_limits<float>::quiet_NaN(),0.0f));
  164. vNormals.resize(pScene->mMeshes[0]->mNumFaces*3,aiVector3D());
  165. // not sure whether there are MD2 files without texture coordinates
  166. if (0 != this->m_pcHeader->numTexCoords && 0 != this->m_pcHeader->numSkins)
  167. {
  168. // navigate to the first texture associated with the mesh
  169. const MD2::Skin* pcSkins = (const MD2::Skin*) ((unsigned char*)this->m_pcHeader +
  170. this->m_pcHeader->offsetSkins);
  171. const int iMode = (int)aiShadingMode_Gouraud;
  172. MaterialHelper* pcHelper = (MaterialHelper*)pScene->mMaterials[0];
  173. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  174. aiColor3D clr;
  175. clr.b = clr.g = clr.r = 1.0f;
  176. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  177. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  178. clr.b = clr.g = clr.r = 0.05f;
  179. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  180. aiString szString;
  181. const size_t iLen = strlen(pcSkins->name);
  182. memcpy(szString.data,pcSkins->name,iLen+1);
  183. szString.length = iLen-1;
  184. pcHelper->AddProperty(&szString,AI_MATKEY_TEXTURE_DIFFUSE(0));
  185. }
  186. else
  187. {
  188. // apply a default material
  189. const int iMode = (int)aiShadingMode_Gouraud;
  190. MaterialHelper* pcHelper = (MaterialHelper*)pScene->mMaterials[0];
  191. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  192. aiColor3D clr;
  193. clr.b = clr.g = clr.r = 0.6f;
  194. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  195. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  196. clr.b = clr.g = clr.r = 0.05f;
  197. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  198. }
  199. // now read all triangles of the first frame, apply scaling and translation
  200. unsigned int iCurrent = 0;
  201. if (0 != this->m_pcHeader->numTexCoords)
  202. {
  203. for (unsigned int i = 0; i < (unsigned int)this->m_pcHeader->numTriangles;++i)
  204. {
  205. // allocate the face
  206. pScene->mMeshes[0]->mFaces[i].mIndices = new unsigned int[3];
  207. pScene->mMeshes[0]->mFaces[i].mNumIndices = 3;
  208. // copy texture coordinates
  209. // check whether they are different from the previous value at this index.
  210. // In this case, create a full separate set of vertices/normals/texcoords
  211. unsigned int iTemp = iCurrent;
  212. for (unsigned int c = 0; c < 3;++c,++iCurrent)
  213. {
  214. // validate vertex indices
  215. if (pcTriangles[i].vertexIndices[c] >= this->m_pcHeader->numVertices)
  216. pcTriangles[i].vertexIndices[c] = this->m_pcHeader->numVertices-1;
  217. // copy face indices
  218. unsigned int iIndex = (unsigned int)pcTriangles[i].vertexIndices[c];
  219. // read x,y, and z component of the vertex
  220. aiVector3D& vec = vPositions[iCurrent];
  221. vec.x = (float)pcVerts[iIndex].vertex[0] * pcFrame->scale[0];
  222. vec.x += pcFrame->translate[0];
  223. // (flip z and y component)
  224. vec.z = (float)pcVerts[iIndex].vertex[1] * pcFrame->scale[1];
  225. vec.z += pcFrame->translate[1];
  226. vec.y = (float)pcVerts[iIndex].vertex[2] * pcFrame->scale[2];
  227. vec.y += pcFrame->translate[2];
  228. // read the normal vector from the precalculated normal table
  229. vNormals[iCurrent] = *((const aiVector3D*)(&g_avNormals[std::min(
  230. int(pcVerts[iIndex].lightNormalIndex),
  231. int(sizeof(g_avNormals) / sizeof(g_avNormals[0]))-1)]));
  232. std::swap ( vNormals[iCurrent].y,vNormals[iCurrent].z );
  233. // validate texture coordinates
  234. if (pcTriangles[iIndex].textureIndices[c] >= this->m_pcHeader->numTexCoords)
  235. pcTriangles[iIndex].textureIndices[c] = this->m_pcHeader->numTexCoords-1;
  236. aiVector3D* pcOut = &vTexCoords[iCurrent];
  237. float u,v;
  238. u = (float)pcTexCoords[pcTriangles[i].textureIndices[c]].s / this->m_pcHeader->skinWidth;
  239. v = (float)pcTexCoords[pcTriangles[i].textureIndices[c]].t / this->m_pcHeader->skinHeight;
  240. pcOut->x = u;
  241. pcOut->y = v;
  242. }
  243. pScene->mMeshes[0]->mFaces[i].mIndices[0] = iTemp+2;
  244. pScene->mMeshes[0]->mFaces[i].mIndices[1] = iTemp+1;
  245. pScene->mMeshes[0]->mFaces[i].mIndices[2] = iTemp+0;
  246. }
  247. }
  248. else
  249. {
  250. for (unsigned int i = 0; i < (unsigned int)this->m_pcHeader->numTriangles;++i)
  251. {
  252. // allocate the face
  253. pScene->mMeshes[0]->mFaces[i].mIndices = new unsigned int[3];
  254. pScene->mMeshes[0]->mFaces[i].mNumIndices = 3;
  255. // copy texture coordinates
  256. // check whether they are different from the previous value at this index.
  257. // In this case, create a full separate set of vertices/normals/texcoords
  258. unsigned int iTemp = iCurrent;
  259. for (unsigned int c = 0; c < 3;++c,++iCurrent)
  260. {
  261. // validate vertex indices
  262. if (pcTriangles[i].vertexIndices[c] >= this->m_pcHeader->numVertices)
  263. pcTriangles[i].vertexIndices[c] = this->m_pcHeader->numVertices-1;
  264. // copy face indices
  265. unsigned int iIndex = (unsigned int)pcTriangles[i].vertexIndices[c];
  266. // read x,y, and z component of the vertex
  267. aiVector3D& vec = vPositions[iCurrent];
  268. vec.x = (float)pcVerts[iIndex].vertex[0] * pcFrame->scale[0];
  269. vec.x += pcFrame->translate[0];
  270. // (flip z and y component)
  271. vec.z = (float)pcVerts[iIndex].vertex[1] * pcFrame->scale[1];
  272. vec.z += pcFrame->translate[1];
  273. vec.y = (float)pcVerts[iIndex].vertex[2] * pcFrame->scale[2];
  274. vec.y += pcFrame->translate[2];
  275. // read the normal vector from the precalculated normal table
  276. vNormals[iCurrent] = *((const aiVector3D*)(&g_avNormals[std::min(
  277. int(pcVerts[iIndex].lightNormalIndex),
  278. int(sizeof(g_avNormals) / sizeof(g_avNormals[0]))-1)]));
  279. std::swap ( vNormals[iCurrent].y,vNormals[iCurrent].z );
  280. aiVector3D* pcOut = &vTexCoords[iCurrent];
  281. pcOut->x = (float)pcTexCoords[pcTriangles[i].textureIndices[c]].s / this->m_pcHeader->skinWidth;
  282. pcOut->y = (float)pcTexCoords[pcTriangles[i].textureIndices[c]].t / this->m_pcHeader->skinHeight;
  283. }
  284. pScene->mMeshes[0]->mFaces[i].mIndices[0] = iTemp+2;
  285. pScene->mMeshes[0]->mFaces[i].mIndices[1] = iTemp+1;
  286. pScene->mMeshes[0]->mFaces[i].mIndices[2] = iTemp+0;
  287. }
  288. }
  289. // allocate output storage
  290. pScene->mMeshes[0]->mNumVertices = vPositions.size();
  291. pScene->mMeshes[0]->mVertices = new aiVector3D[vPositions.size()];
  292. pScene->mMeshes[0]->mNormals = new aiVector3D[vPositions.size()];
  293. pScene->mMeshes[0]->mTextureCoords[0] = new aiVector3D[vPositions.size()];
  294. // memcpy() the data to the c-syle arrays
  295. memcpy(pScene->mMeshes[0]->mVertices, &vPositions[0],
  296. vPositions.size() * sizeof(aiVector3D));
  297. memcpy(pScene->mMeshes[0]->mNormals, &vNormals[0],
  298. vPositions.size() * sizeof(aiVector3D));
  299. if (0 != this->m_pcHeader->numTexCoords)
  300. {
  301. memcpy(pScene->mMeshes[0]->mTextureCoords[0], &vTexCoords[0],
  302. vPositions.size() * sizeof(aiVector3D));
  303. }
  304. return;
  305. }