MD3Loader.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 MD3 importer class */
  35. #include "MD3Loader.h"
  36. #include "MaterialSystem.h"
  37. #include "StringComparison.h"
  38. #include "ByteSwap.h"
  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. // ------------------------------------------------------------------------------------------------
  49. // Constructor to be privately used by Importer
  50. MD3Importer::MD3Importer()
  51. {
  52. }
  53. // ------------------------------------------------------------------------------------------------
  54. // Destructor, private as well
  55. MD3Importer::~MD3Importer()
  56. {
  57. }
  58. // ------------------------------------------------------------------------------------------------
  59. // Returns whether the class can handle the format of the given file.
  60. bool MD3Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  61. {
  62. // simple check of file extension is enough for the moment
  63. std::string::size_type pos = pFile.find_last_of('.');
  64. // no file extension - can't read
  65. if( pos == std::string::npos)
  66. return false;
  67. std::string extension = pFile.substr( pos);
  68. if (extension.length() < 4)return false;
  69. if (extension[0] != '.')return false;
  70. if (extension[1] != 'm' && extension[1] != 'M')return false;
  71. if (extension[2] != 'd' && extension[2] != 'D')return false;
  72. if (extension[3] != '3')return false;
  73. return true;
  74. }
  75. // ------------------------------------------------------------------------------------------------
  76. void MD3Importer::ValidateHeaderOffsets()
  77. {
  78. // check magic number
  79. if (pcHeader->IDENT != AI_MD3_MAGIC_NUMBER_BE &&
  80. pcHeader->IDENT != AI_MD3_MAGIC_NUMBER_LE)
  81. throw new ImportErrorException( "Invalid MD3 file: Magic bytes not found");
  82. // check file format version
  83. if (pcHeader->VERSION > 15)
  84. DefaultLogger::get()->warn( "Unsupported MD3 file version. Continuing happily ...");
  85. // check some values whether they are valid
  86. if (!pcHeader->NUM_SURFACES)
  87. throw new ImportErrorException( "Invalid md3 file: NUM_SURFACES is 0");
  88. if (pcHeader->OFS_FRAMES >= fileSize ||
  89. pcHeader->OFS_SURFACES >= fileSize ||
  90. pcHeader->OFS_EOF > fileSize)
  91. {
  92. throw new ImportErrorException("Invalid MD3 header: some offsets are outside the file");
  93. }
  94. if (pcHeader->NUM_FRAMES <= this->configFrameID )
  95. throw new ImportErrorException("The requested frame is not existing the file");
  96. }
  97. // ------------------------------------------------------------------------------------------------
  98. void MD3Importer::ValidateSurfaceHeaderOffsets(const MD3::Surface* pcSurf)
  99. {
  100. // calculate the relative offset of the surface
  101. int32_t ofs = int32_t((const unsigned char*)pcSurf-this->mBuffer);
  102. if (pcSurf->OFS_TRIANGLES + ofs + pcSurf->NUM_TRIANGLES * sizeof(MD3::Triangle) > fileSize ||
  103. pcSurf->OFS_SHADERS + ofs + pcSurf->NUM_SHADER * sizeof(MD3::Shader) > fileSize ||
  104. pcSurf->OFS_ST + ofs + pcSurf->NUM_VERTICES * sizeof(MD3::TexCoord) > fileSize ||
  105. pcSurf->OFS_XYZNORMAL + ofs + pcSurf->NUM_VERTICES * sizeof(MD3::Vertex) > fileSize)
  106. {
  107. throw new ImportErrorException("Invalid MD3 surface header: some offsets are outside the file");
  108. }
  109. if (pcSurf->NUM_TRIANGLES > AI_MD3_MAX_TRIANGLES)
  110. DefaultLogger::get()->warn("The model contains more triangles than Quake 3 supports");
  111. if (pcSurf->NUM_SHADER > AI_MD3_MAX_SHADERS)
  112. DefaultLogger::get()->warn("The model contains more shaders than Quake 3 supports");
  113. if (pcSurf->NUM_VERTICES > AI_MD3_MAX_VERTS)
  114. DefaultLogger::get()->warn("The model contains more vertices than Quake 3 supports");
  115. if (pcSurf->NUM_FRAMES > AI_MD3_MAX_FRAMES)
  116. DefaultLogger::get()->warn("The model contains more frames than Quake 3 supports");
  117. }
  118. // ------------------------------------------------------------------------------------------------
  119. // Setup configuration properties
  120. void MD3Importer::SetupProperties(const Importer* pImp)
  121. {
  122. // The AI_CONFIG_IMPORT_MD3_KEYFRAME option overrides the
  123. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  124. if(0xffffffff == (this->configFrameID = pImp->GetPropertyInteger(
  125. AI_CONFIG_IMPORT_MD3_KEYFRAME,0xffffffff)))
  126. {
  127. this->configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  128. }
  129. }
  130. // ------------------------------------------------------------------------------------------------
  131. // Imports the given file into the given scene structure.
  132. void MD3Importer::InternReadFile(
  133. const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  134. {
  135. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  136. // Check whether we can read from the file
  137. if( file.get() == NULL)
  138. throw new ImportErrorException( "Failed to open MD3 file " + pFile + ".");
  139. // check whether the md3 file is large enough to contain
  140. // at least the file header
  141. fileSize = (unsigned int)file->FileSize();
  142. if( fileSize < sizeof(MD3::Header))
  143. throw new ImportErrorException( "MD3 File is too small.");
  144. // allocate storage and copy the contents of the file to a memory buffer
  145. std::vector<unsigned char> mBuffer2 (fileSize);
  146. file->Read( &mBuffer2[0], 1, fileSize);
  147. mBuffer = &mBuffer2[0];
  148. pcHeader = (BE_NCONST MD3::Header*)mBuffer;
  149. #ifdef AI_BUILD_BIG_ENDIAN
  150. ByteSwap::Swap4(&pcHeader->VERSION);
  151. ByteSwap::Swap4(&pcHeader->FLAGS);
  152. ByteSwap::Swap4(&pcHeader->IDENT);
  153. ByteSwap::Swap4(&pcHeader->NUM_FRAMES);
  154. ByteSwap::Swap4(&pcHeader->NUM_SKINS);
  155. ByteSwap::Swap4(&pcHeader->NUM_SURFACES);
  156. ByteSwap::Swap4(&pcHeader->NUM_TAGS);
  157. ByteSwap::Swap4(&pcHeader->OFS_EOF);
  158. ByteSwap::Swap4(&pcHeader->OFS_FRAMES);
  159. ByteSwap::Swap4(&pcHeader->OFS_SURFACES);
  160. ByteSwap::Swap4(&pcHeader->OFS_TAGS);
  161. #endif
  162. // validate the header
  163. this->ValidateHeaderOffsets();
  164. // now navigate to the list of surfaces
  165. const MD3::Surface* pcSurfaces = (const MD3::Surface*)(mBuffer + pcHeader->OFS_SURFACES);
  166. // allocate output storage
  167. pScene->mNumMeshes = pcHeader->NUM_SURFACES;
  168. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  169. pScene->mNumMaterials = pcHeader->NUM_SURFACES;
  170. pScene->mMaterials = new aiMaterial*[pScene->mNumMeshes];
  171. // if an exception is thrown before the meshes are allocated ->
  172. // otherwise the pointer value would be invalid and delete would crash
  173. ::memset(pScene->mMeshes,0,pScene->mNumMeshes*sizeof(aiMesh*));
  174. ::memset(pScene->mMaterials,0,pScene->mNumMaterials*sizeof(aiMaterial*));
  175. unsigned int iNum = pcHeader->NUM_SURFACES;
  176. unsigned int iNumMaterials = 0;
  177. unsigned int iDefaultMatIndex = 0xFFFFFFFF;
  178. while (iNum-- > 0)
  179. {
  180. #ifdef AI_BUILD_BIG_ENDIAN
  181. ByteSwap::Swap4(pcSurfaces->FLAGS);
  182. ByteSwap::Swap4(pcSurfaces->IDENT);
  183. ByteSwap::Swap4(pcSurfaces->NUM_FRAMES);
  184. ByteSwap::Swap4(pcSurfaces->NUM_SHADER);
  185. ByteSwap::Swap4(pcSurfaces->NUM_TRIANGLES);
  186. ByteSwap::Swap4(pcSurfaces->NUM_VERTICES);
  187. ByteSwap::Swap4(pcSurfaces->OFS_END);
  188. ByteSwap::Swap4(pcSurfaces->OFS_SHADERS);
  189. ByteSwap::Swap4(pcSurfaces->OFS_ST);
  190. ByteSwap::Swap4(pcSurfaces->OFS_TRIANGLES);
  191. ByteSwap::Swap4(pcSurfaces->OFS_XYZNORMAL);
  192. #endif
  193. // validate the surface
  194. this->ValidateSurfaceHeaderOffsets(pcSurfaces);
  195. // navigate to the vertex list of the surface
  196. const MD3::Vertex* pcVertices = (const MD3::Vertex*)
  197. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_XYZNORMAL);
  198. // navigate to the triangle list of the surface
  199. const MD3::Triangle* pcTriangles = (const MD3::Triangle*)
  200. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_TRIANGLES);
  201. // navigate to the texture coordinate list of the surface
  202. const MD3::TexCoord* pcUVs = (const MD3::TexCoord*)
  203. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_ST);
  204. // navigate to the shader list of the surface
  205. const MD3::Shader* pcShaders = (const MD3::Shader*)
  206. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_SHADERS);
  207. // if the submesh is empty ignore it
  208. if (0 == pcSurfaces->NUM_VERTICES || 0 == pcSurfaces->NUM_TRIANGLES)
  209. {
  210. pcSurfaces = (const MD3::Surface*)(((uint8_t*)pcSurfaces) + pcSurfaces->OFS_END);
  211. pScene->mNumMeshes--;
  212. continue;
  213. }
  214. #ifdef AI_BUILD_BIG_ENDIAN
  215. for (uint32_t i = 0; i < pcSurfaces->NUM_VERTICES;++i)
  216. {
  217. ByteSwap::Swap2( & pcVertices[i].NORMAL );
  218. ByteSwap::Swap2( & pcVertices[i].X );
  219. ByteSwap::Swap2( & pcVertices[i].Y );
  220. ByteSwap::Swap2( & pcVertices[i].Z );
  221. ByteSwap::Swap4( & pcUVs[i].U );
  222. ByteSwap::Swap4( & pcUVs[i].U );
  223. }
  224. for (uint32_t i = 0; i < pcSurfaces->NUM_TRIANGLES;++i)
  225. {
  226. ByteSwap::Swap4(pcTriangles[i].INDEXES[0]);
  227. ByteSwap::Swap4(pcTriangles[i].INDEXES[1]);
  228. ByteSwap::Swap4(pcTriangles[i].INDEXES[2]);
  229. }
  230. #endif
  231. // allocate the output mesh
  232. pScene->mMeshes[iNum] = new aiMesh();
  233. aiMesh* pcMesh = pScene->mMeshes[iNum];
  234. pcMesh->mNumVertices = pcSurfaces->NUM_TRIANGLES*3;
  235. pcMesh->mNumFaces = pcSurfaces->NUM_TRIANGLES;
  236. pcMesh->mFaces = new aiFace[pcSurfaces->NUM_TRIANGLES];
  237. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  238. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  239. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  240. pcMesh->mNumUVComponents[0] = 2;
  241. // fill in all triangles
  242. unsigned int iCurrent = 0;
  243. for (unsigned int i = 0; i < (unsigned int)pcSurfaces->NUM_TRIANGLES;++i)
  244. {
  245. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  246. pcMesh->mFaces[i].mNumIndices = 3;
  247. unsigned int iTemp = iCurrent;
  248. for (unsigned int c = 0; c < 3;++c,++iCurrent)
  249. {
  250. // read vertices
  251. pcMesh->mVertices[iCurrent].x = pcVertices[ pcTriangles->INDEXES[c]].X*AI_MD3_XYZ_SCALE;
  252. pcMesh->mVertices[iCurrent].y = pcVertices[ pcTriangles->INDEXES[c]].Y*-1.0f*AI_MD3_XYZ_SCALE;
  253. pcMesh->mVertices[iCurrent].z = pcVertices[ pcTriangles->INDEXES[c]].Z*AI_MD3_XYZ_SCALE;
  254. // convert the normal vector to uncompressed float3 format
  255. LatLngNormalToVec3(pcVertices[pcTriangles->INDEXES[c]].NORMAL,
  256. (float*)&pcMesh->mNormals[iCurrent]);
  257. pcMesh->mNormals[iCurrent].y *= -1.0f;
  258. // read texture coordinates
  259. pcMesh->mTextureCoords[0][iCurrent].x = pcUVs[ pcTriangles->INDEXES[c]].U;
  260. pcMesh->mTextureCoords[0][iCurrent].y = 1.0f-pcUVs[ pcTriangles->INDEXES[c]].V;
  261. }
  262. // FIX: flip the face ordering for use with OpenGL
  263. pcMesh->mFaces[i].mIndices[0] = iTemp+2;
  264. pcMesh->mFaces[i].mIndices[1] = iTemp+1;
  265. pcMesh->mFaces[i].mIndices[2] = iTemp+0;
  266. pcTriangles++;
  267. }
  268. // get the first shader (= texture?) assigned to the surface
  269. if (pcSurfaces->NUM_SHADER)
  270. {
  271. // make a relative path.
  272. // if the MD3's internal path itself and the given path are using
  273. // the same directory remove it
  274. const char* szEndDir1 = ::strrchr((const char*)pcHeader->NAME,'\\');
  275. if (!szEndDir1)szEndDir1 = ::strrchr((const char*)pcHeader->NAME,'/');
  276. const char* szEndDir2 = ::strrchr((const char*)pcShaders->NAME,'\\');
  277. if (!szEndDir2)szEndDir2 = ::strrchr((const char*)pcShaders->NAME,'/');
  278. if (szEndDir1 && szEndDir2)
  279. {
  280. // both of them are valid
  281. const unsigned int iLen1 = (unsigned int)(szEndDir1 - (const char*)pcHeader->NAME);
  282. const unsigned int iLen2 = std::min (iLen1, (unsigned int)(szEndDir2 - (const char*)pcShaders->NAME) );
  283. bool bSuccess = true;
  284. for (unsigned int a = 0; a < iLen2;++a)
  285. {
  286. char sz = ::tolower ( pcShaders->NAME[a] );
  287. char sz2 = ::tolower ( pcHeader->NAME[a] );
  288. if (sz != sz2)
  289. {
  290. bSuccess = false;
  291. break;
  292. }
  293. }
  294. if (bSuccess)
  295. {
  296. // use the file name only
  297. szEndDir2++;
  298. }
  299. else
  300. {
  301. // use the full path
  302. szEndDir2 = (const char*)pcShaders->NAME;
  303. }
  304. }
  305. MaterialHelper* pcHelper = new MaterialHelper();
  306. if (szEndDir2)
  307. {
  308. if (szEndDir2[0])
  309. {
  310. aiString szString;
  311. const size_t iLen = ::strlen(szEndDir2);
  312. ::memcpy(szString.data,szEndDir2,iLen);
  313. szString.data[iLen] = '\0';
  314. szString.length = iLen;
  315. pcHelper->AddProperty(&szString,AI_MATKEY_TEXTURE_DIFFUSE(0));
  316. }
  317. else
  318. {
  319. DefaultLogger::get()->warn("Texture file name has zero length. "
  320. "It will be skipped.");
  321. }
  322. }
  323. int iMode = (int)aiShadingMode_Gouraud;
  324. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  325. // add a small ambient color value - Quake 3 seems to have one
  326. aiColor3D clr;
  327. clr.b = clr.g = clr.r = 0.05f;
  328. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  329. clr.b = clr.g = clr.r = 1.0f;
  330. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  331. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  332. aiString szName;
  333. szName.Set(AI_DEFAULT_MATERIAL_NAME);
  334. pcHelper->AddProperty(&szName,AI_MATKEY_NAME);
  335. pScene->mMaterials[iNumMaterials] = (aiMaterial*)pcHelper;
  336. pcMesh->mMaterialIndex = iNumMaterials++;
  337. }
  338. else
  339. {
  340. if (0xFFFFFFFF != iDefaultMatIndex)
  341. {
  342. pcMesh->mMaterialIndex = iDefaultMatIndex;
  343. }
  344. else
  345. {
  346. MaterialHelper* pcHelper = new MaterialHelper();
  347. // fill in a default material
  348. int iMode = (int)aiShadingMode_Gouraud;
  349. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  350. aiColor3D clr;
  351. clr.b = clr.g = clr.r = 0.6f;
  352. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  353. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  354. clr.b = clr.g = clr.r = 0.05f;
  355. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  356. pScene->mMaterials[iNumMaterials] = (aiMaterial*)pcHelper;
  357. iDefaultMatIndex = pcMesh->mMaterialIndex = iNumMaterials++;
  358. }
  359. }
  360. // go to the next surface
  361. pcSurfaces = (const MD3::Surface*)(((unsigned char*)pcSurfaces) + pcSurfaces->OFS_END);
  362. }
  363. if (!pScene->mNumMeshes)
  364. throw new ImportErrorException( "Invalid MD3 file: File contains no valid mesh");
  365. pScene->mNumMaterials = iNumMaterials;
  366. // now we need to generate an empty node graph
  367. pScene->mRootNode = new aiNode();
  368. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  369. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  370. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  371. pScene->mRootNode->mMeshes[i] = i;
  372. }