MD3Loader.cpp 16 KB

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