MD2Loader.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 "ByteSwap.h"
  38. #include "MD2NormalTable.h" // shouldn't be included by other units
  39. #include "../include/IOStream.h"
  40. #include "../include/IOSystem.h"
  41. #include "../include/aiMesh.h"
  42. #include "../include/aiScene.h"
  43. #include "../include/aiAssert.h"
  44. #include "../include/DefaultLogger.h"
  45. #include "../include/assimp.hpp"
  46. #include <boost/scoped_ptr.hpp>
  47. using namespace Assimp;
  48. using namespace Assimp::MD2;
  49. // helper macro to determine the size of an array
  50. #if (!defined ARRAYSIZE)
  51. # define ARRAYSIZE(_array) (int(sizeof(_array) / sizeof(_array[0])))
  52. #endif
  53. // ------------------------------------------------------------------------------------------------
  54. // Helper function to lookup a normal in Quake 2's precalculated table
  55. void MD2::LookupNormalIndex(uint8_t iNormalIndex,aiVector3D& vOut)
  56. {
  57. // make sure the normal index has a valid value
  58. if (iNormalIndex >= ARRAYSIZE(g_avNormals))
  59. {
  60. DefaultLogger::get()->warn("Index overflow in Quake II normal vector list (the "
  61. " LUT has only 162 entries). ");
  62. iNormalIndex = ARRAYSIZE(g_avNormals) - 1;
  63. }
  64. vOut = *((const aiVector3D*)(&g_avNormals[iNormalIndex]));
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. // Constructor to be privately used by Importer
  68. MD2Importer::MD2Importer()
  69. {
  70. }
  71. // ------------------------------------------------------------------------------------------------
  72. // Destructor, private as well
  73. MD2Importer::~MD2Importer()
  74. {
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Returns whether the class can handle the format of the given file.
  78. bool MD2Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  79. {
  80. // simple check of file extension is enough for the moment
  81. std::string::size_type pos = pFile.find_last_of('.');
  82. // no file extension - can't read
  83. if( pos == std::string::npos)
  84. return false;
  85. std::string extension = pFile.substr( pos);
  86. if (extension.length() < 4)return false;
  87. if (extension[0] != '.')return false;
  88. if (extension[1] != 'm' && extension[1] != 'M')return false;
  89. if (extension[2] != 'd' && extension[2] != 'D')return false;
  90. if (extension[3] != '2')return false;
  91. return true;
  92. }
  93. // ------------------------------------------------------------------------------------------------
  94. // Setup configuration properties
  95. void MD2Importer::SetupProperties(const Importer* pImp)
  96. {
  97. // The AI_CONFIG_IMPORT_MD2_KEYFRAME option overrides the
  98. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  99. if(0xffffffff == (this->configFrameID = pImp->GetProperty(
  100. AI_CONFIG_IMPORT_MD2_KEYFRAME,0xffffffff)))
  101. {
  102. this->configFrameID = pImp->GetProperty(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  103. }
  104. }
  105. // ------------------------------------------------------------------------------------------------
  106. // Validate the file header
  107. void MD2Importer::ValidateHeader( )
  108. {
  109. // check magic number
  110. if (this->m_pcHeader->magic != AI_MD2_MAGIC_NUMBER_BE &&
  111. this->m_pcHeader->magic != AI_MD2_MAGIC_NUMBER_LE)
  112. {
  113. char szBuffer[5];
  114. szBuffer[0] = ((char*)&this->m_pcHeader->magic)[0];
  115. szBuffer[1] = ((char*)&this->m_pcHeader->magic)[1];
  116. szBuffer[2] = ((char*)&this->m_pcHeader->magic)[2];
  117. szBuffer[3] = ((char*)&this->m_pcHeader->magic)[3];
  118. szBuffer[4] = '\0';
  119. throw new ImportErrorException("Invalid MD2 magic word: should be IDP2, the "
  120. "magic word found is " + std::string(szBuffer));
  121. }
  122. // check file format version
  123. if (this->m_pcHeader->version != 8)
  124. DefaultLogger::get()->warn( "Unsupported md2 file version. Continuing happily ...");
  125. // check some values whether they are valid
  126. if (0 == this->m_pcHeader->numFrames)
  127. throw new ImportErrorException( "Invalid md2 file: NUM_FRAMES is 0");
  128. if (this->m_pcHeader->offsetEnd > (int32_t)fileSize)
  129. throw new ImportErrorException( "Invalid md2 file: File is too small");
  130. if (this->m_pcHeader->offsetSkins + this->m_pcHeader->numSkins * sizeof (MD2::Skin) >= this->fileSize ||
  131. this->m_pcHeader->offsetTexCoords + this->m_pcHeader->numTexCoords * sizeof (MD2::TexCoord) >= this->fileSize ||
  132. this->m_pcHeader->offsetTriangles + this->m_pcHeader->numTriangles * sizeof (MD2::Triangle) >= this->fileSize ||
  133. this->m_pcHeader->offsetFrames + this->m_pcHeader->numFrames * sizeof (MD2::Frame) >= this->fileSize ||
  134. this->m_pcHeader->offsetEnd > this->fileSize)
  135. {
  136. throw new ImportErrorException("Invalid MD2 header: some offsets are outside the file");
  137. }
  138. if (this->m_pcHeader->numSkins > AI_MD2_MAX_SKINS)
  139. DefaultLogger::get()->warn("The model contains more skins than Quake 2 supports");
  140. if ( this->m_pcHeader->numFrames > AI_MD2_MAX_FRAMES)
  141. DefaultLogger::get()->warn("The model contains more frames than Quake 2 supports");
  142. if (this->m_pcHeader->numVertices > AI_MD2_MAX_VERTS)
  143. DefaultLogger::get()->warn("The model contains more vertices than Quake 2 supports");
  144. if (this->m_pcHeader->numFrames <= this->configFrameID )
  145. throw new ImportErrorException("The requested frame is not existing the file");
  146. }
  147. // ------------------------------------------------------------------------------------------------
  148. // Imports the given file into the given scene structure.
  149. void MD2Importer::InternReadFile( const std::string& pFile,
  150. aiScene* pScene, IOSystem* pIOHandler)
  151. {
  152. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  153. // Check whether we can read from the file
  154. if( file.get() == NULL)
  155. throw new ImportErrorException( "Failed to open MD2 file " + pFile + "");
  156. // check whether the md3 file is large enough to contain
  157. // at least the file header
  158. fileSize = (unsigned int)file->FileSize();
  159. if( fileSize < sizeof(MD2::Header))
  160. throw new ImportErrorException( "MD2 File is too small");
  161. try
  162. {
  163. // allocate storage and copy the contents of the file to a memory buffer
  164. this->mBuffer = new unsigned char[fileSize];
  165. file->Read( (void*)mBuffer, 1, fileSize);
  166. this->m_pcHeader = (const MD2::Header*)this->mBuffer;
  167. #ifdef AI_BUILD_BIG_ENDIAN
  168. ByteSwap::Swap4(&m_pcHeader->frameSize);
  169. ByteSwap::Swap4(&m_pcHeader->magic);
  170. ByteSwap::Swap4(&m_pcHeader->numFrames);
  171. ByteSwap::Swap4(&m_pcHeader->numGlCommands);
  172. ByteSwap::Swap4(&m_pcHeader->numSkins);
  173. ByteSwap::Swap4(&m_pcHeader->numTexCoords);
  174. ByteSwap::Swap4(&m_pcHeader->numTriangles);
  175. ByteSwap::Swap4(&m_pcHeader->numVertices);
  176. ByteSwap::Swap4(&m_pcHeader->offsetEnd);
  177. ByteSwap::Swap4(&m_pcHeader->offsetFrames);
  178. ByteSwap::Swap4(&m_pcHeader->offsetGlCommands);
  179. ByteSwap::Swap4(&m_pcHeader->offsetSkins);
  180. ByteSwap::Swap4(&m_pcHeader->offsetTexCoords);
  181. ByteSwap::Swap4(&m_pcHeader->offsetTriangles);
  182. ByteSwap::Swap4(&m_pcHeader->skinHeight);
  183. ByteSwap::Swap4(&m_pcHeader->skinWidth);
  184. ByteSwap::Swap4(&m_pcHeader->version);
  185. #endif
  186. this->ValidateHeader();
  187. // there won't be more than one mesh inside the file
  188. pScene->mNumMaterials = 1;
  189. pScene->mRootNode = new aiNode();
  190. pScene->mRootNode->mNumMeshes = 1;
  191. pScene->mRootNode->mMeshes = new unsigned int[1];
  192. pScene->mRootNode->mMeshes[0] = 0;
  193. pScene->mMaterials = new aiMaterial*[1];
  194. pScene->mMaterials[0] = new MaterialHelper();
  195. pScene->mNumMeshes = 1;
  196. pScene->mMeshes = new aiMesh*[1];
  197. aiMesh* pcMesh = pScene->mMeshes[0] = new aiMesh();
  198. // navigate to the begin of the frame data
  199. const MD2::Frame* pcFrame = (const MD2::Frame*) ((uint8_t*)
  200. this->m_pcHeader + this->m_pcHeader->offsetFrames);
  201. pcFrame += this->configFrameID;
  202. // navigate to the begin of the triangle data
  203. MD2::Triangle* pcTriangles = (MD2::Triangle*) ((uint8_t*)
  204. this->m_pcHeader + this->m_pcHeader->offsetTriangles);
  205. // navigate to the begin of the tex coords data
  206. const MD2::TexCoord* pcTexCoords = (const MD2::TexCoord*) ((uint8_t*)
  207. this->m_pcHeader + this->m_pcHeader->offsetTexCoords);
  208. // navigate to the begin of the vertex data
  209. const MD2::Vertex* pcVerts = (const MD2::Vertex*) (pcFrame->vertices);
  210. #ifdef AI_BUILD_BIG_ENDIAN
  211. for (uint32_t i = 0; i< m_pcHeader->numTriangles)
  212. {
  213. for (unsigned int p = 0; p < 3;++p)
  214. {
  215. ByteSwap::Swap2(& pcTriangles[i].textureIndices[p]);
  216. ByteSwap::Swap2(& pcTriangles[i].vertexIndices[p]);
  217. }
  218. }
  219. for (uint32_t i = 0; i < m_pcHeader->offsetTexCoords;++i)
  220. {
  221. ByteSwap::Swap2(& pcTexCoords[i].s);
  222. ByteSwap::Swap2(& pcTexCoords[i].t);
  223. }
  224. ByteSwap::Swap4( & pcFrame->scale[0] );
  225. ByteSwap::Swap4( & pcFrame->scale[1] );
  226. ByteSwap::Swap4( & pcFrame->scale[2] );
  227. ByteSwap::Swap4( & pcFrame->translate[0] );
  228. ByteSwap::Swap4( & pcFrame->translate[1] );
  229. ByteSwap::Swap4( & pcFrame->translate[2] );
  230. #endif
  231. pcMesh->mNumFaces = this->m_pcHeader->numTriangles;
  232. pcMesh->mFaces = new aiFace[this->m_pcHeader->numTriangles];
  233. // allocate output storage
  234. pcMesh->mNumVertices = (unsigned int)pcMesh->mNumFaces*3;
  235. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  236. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  237. // not sure whether there are MD2 files without texture coordinates
  238. // NOTE: texture coordinates can be there without a texture,
  239. // but a texture can't be there without a valid UV channel
  240. if (this->m_pcHeader->numTexCoords && this->m_pcHeader->numSkins)
  241. {
  242. // navigate to the first texture associated with the mesh
  243. const MD2::Skin* pcSkins = (const MD2::Skin*) ((unsigned char*)this->m_pcHeader +
  244. this->m_pcHeader->offsetSkins);
  245. const int iMode = (int)aiShadingMode_Gouraud;
  246. MaterialHelper* pcHelper = (MaterialHelper*)pScene->mMaterials[0];
  247. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  248. aiColor3D clr;
  249. clr.b = clr.g = clr.r = 1.0f;
  250. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  251. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  252. clr.b = clr.g = clr.r = 0.05f;
  253. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  254. if (pcSkins->name[0])
  255. {
  256. aiString szString;
  257. const size_t iLen = ::strlen(pcSkins->name);
  258. ::memcpy(szString.data,pcSkins->name,iLen);
  259. szString.data[iLen] = '\0';
  260. szString.length = iLen;
  261. pcHelper->AddProperty(&szString,AI_MATKEY_TEXTURE_DIFFUSE(0));
  262. }
  263. else
  264. {
  265. DefaultLogger::get()->warn("Texture file name has zero length. It will be skipped.");
  266. }
  267. }
  268. else
  269. {
  270. // apply a default material
  271. const int iMode = (int)aiShadingMode_Gouraud;
  272. MaterialHelper* pcHelper = (MaterialHelper*)pScene->mMaterials[0];
  273. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  274. aiColor3D clr;
  275. clr.b = clr.g = clr.r = 0.6f;
  276. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  277. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  278. clr.b = clr.g = clr.r = 0.05f;
  279. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  280. aiString szName;
  281. szName.Set(AI_DEFAULT_MATERIAL_NAME);
  282. pcHelper->AddProperty(&szName,AI_MATKEY_NAME);
  283. }
  284. // now read all triangles of the first frame, apply scaling and translation
  285. unsigned int iCurrent = 0;
  286. float fDivisorU,fDivisorV;
  287. if (this->m_pcHeader->numTexCoords)
  288. {
  289. // allocate storage for texture coordinates, too
  290. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  291. pcMesh->mNumUVComponents[0] = 2;
  292. // check whether the skin width or height are zero (this would
  293. // cause a division through zero)
  294. if (!this->m_pcHeader->skinWidth)
  295. {
  296. DefaultLogger::get()->error("Skin width is zero but there are "
  297. "valid absolute texture coordinates. Unable to compute "
  298. "relative texture coordinates ranging from 0 to 1");
  299. fDivisorU = 1.0f;
  300. }
  301. else fDivisorU = (float)this->m_pcHeader->skinWidth;
  302. if (!this->m_pcHeader->skinHeight)
  303. {
  304. DefaultLogger::get()->error("Skin height is zero but there are "
  305. "valid absolute texture coordinates. Unable to compute "
  306. "relative texture coordinates ranging from 0 to 1");
  307. fDivisorV = 1.0f;
  308. }
  309. else fDivisorV = (float)this->m_pcHeader->skinHeight;
  310. }
  311. for (unsigned int i = 0; i < (unsigned int)this->m_pcHeader->numTriangles;++i)
  312. {
  313. // allocate the face
  314. pScene->mMeshes[0]->mFaces[i].mIndices = new unsigned int[3];
  315. pScene->mMeshes[0]->mFaces[i].mNumIndices = 3;
  316. // copy texture coordinates
  317. // check whether they are different from the previous value at this index.
  318. // In this case, create a full separate set of vertices/normals/texcoords
  319. unsigned int iTemp = iCurrent;
  320. for (unsigned int c = 0; c < 3;++c,++iCurrent)
  321. {
  322. // validate vertex indices
  323. if (pcTriangles[i].vertexIndices[c] >= this->m_pcHeader->numVertices)
  324. {
  325. DefaultLogger::get()->error("Vertex index is outside the allowed range");
  326. pcTriangles[i].vertexIndices[c] = this->m_pcHeader->numVertices-1;
  327. }
  328. // copy face indices
  329. unsigned int iIndex = (unsigned int)pcTriangles[i].vertexIndices[c];
  330. // read x,y, and z component of the vertex
  331. aiVector3D& vec = pcMesh->mVertices[iCurrent];
  332. vec.x = (float)pcVerts[iIndex].vertex[0] * pcFrame->scale[0];
  333. vec.x += pcFrame->translate[0];
  334. // (flip z and y component)
  335. // FIX: no .... invert y instead
  336. vec.y = (float)pcVerts[iIndex].vertex[1] * pcFrame->scale[1];
  337. vec.y += pcFrame->translate[1];
  338. vec.y *= -1.0f;
  339. vec.z = (float)pcVerts[iIndex].vertex[2] * pcFrame->scale[2];
  340. vec.z += pcFrame->translate[2];
  341. // read the normal vector from the precalculated normal table
  342. aiVector3D& vNormal = pcMesh->mNormals[iCurrent];
  343. LookupNormalIndex(pcVerts[iIndex].lightNormalIndex,vNormal);
  344. vNormal.y *= -1.0f;
  345. if (this->m_pcHeader->numTexCoords)
  346. {
  347. // validate texture coordinates
  348. if (pcTriangles[iIndex].textureIndices[c] >= this->m_pcHeader->numTexCoords)
  349. {
  350. DefaultLogger::get()->error("UV index is outside the allowed range");
  351. pcTriangles[iIndex].textureIndices[c] = this->m_pcHeader->numTexCoords-1;
  352. }
  353. aiVector3D& pcOut = pcMesh->mTextureCoords[0][iCurrent];
  354. float u,v;
  355. // the texture coordinates are absolute values but we
  356. // need relative values between 0 and 1
  357. u = (float)pcTexCoords[pcTriangles[i].textureIndices[c]].s / fDivisorU;
  358. v = (float)pcTexCoords[pcTriangles[i].textureIndices[c]].t / fDivisorV;
  359. pcOut.x = u;
  360. pcOut.y = 1.0f - v; // FIXME: Is this correct for MD2?
  361. }
  362. }
  363. // FIX: flip the face order for use with OpenGL
  364. pScene->mMeshes[0]->mFaces[i].mIndices[0] = iTemp+2;
  365. pScene->mMeshes[0]->mFaces[i].mIndices[1] = iTemp+1;
  366. pScene->mMeshes[0]->mFaces[i].mIndices[2] = iTemp+0;
  367. }
  368. }
  369. catch (ImportErrorException* ex)
  370. {
  371. delete[] this->mBuffer; AI_DEBUG_INVALIDATE_PTR(this->mBuffer);
  372. throw ex;
  373. }
  374. delete[] this->mBuffer; AI_DEBUG_INVALIDATE_PTR(this->mBuffer);
  375. }