MD2Loader.cpp 14 KB

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