MD2Loader.cpp 15 KB

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