You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

427 line
15 KiB

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