2
0

MD3Loader.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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 MD3Loader.cpp
  35. * @brief Implementation of the MD3 importer class
  36. *
  37. * Sources:
  38. * http://www.gamers.org/dEngine/quake3/UQ3S
  39. * http://linux.ucla.edu/~phaethon/q3/formats/md3format.html
  40. * http://www.heppler.com/shader/shader/
  41. */
  42. #include "AssimpPCH.h"
  43. #ifndef ASSIMP_BUILD_NO_MD3_IMPORTER
  44. #include "MD3Loader.h"
  45. #include "ByteSwap.h"
  46. #include "SceneCombiner.h"
  47. #include "GenericProperty.h"
  48. #include "RemoveComments.h"
  49. #include "ParsingUtils.h"
  50. using namespace Assimp;
  51. // ------------------------------------------------------------------------------------------------
  52. // Load a Quake 3 shader
  53. void Q3Shader::LoadShader(ShaderData& fill, const std::string& pFile,IOSystem* io)
  54. {
  55. boost::scoped_ptr<IOStream> file( io->Open( pFile, "rt"));
  56. if (!file.get())
  57. return; // if we can't access the file, don't worry and return
  58. DefaultLogger::get()->info("Loading Quake3 shader file " + pFile);
  59. // read file in memory
  60. const size_t s = file->FileSize();
  61. std::vector<char> _buff(s+1);
  62. file->Read(&_buff[0],s,1);
  63. _buff[s] = 0;
  64. // remove comments from it (C++ style)
  65. CommentRemover::RemoveLineComments("//",&_buff[0]);
  66. const char* buff = &_buff[0];
  67. Q3Shader::ShaderDataBlock* curData = NULL;
  68. Q3Shader::ShaderMapBlock* curMap = NULL;
  69. // read line per line
  70. for (;;SkipLine(&buff)) {
  71. if(!SkipSpacesAndLineEnd(&buff))
  72. break;
  73. if (*buff == '{') {
  74. // append to last section, if any
  75. if (!curData) {
  76. DefaultLogger::get()->error("Q3Shader: Unexpected shader section token \'{\'");
  77. return;
  78. }
  79. // read this map section
  80. for (;;SkipLine(&buff)) {
  81. if(!SkipSpacesAndLineEnd(&buff))
  82. break;
  83. if (*buff == '{') {
  84. // add new map section
  85. curData->maps.push_back(Q3Shader::ShaderMapBlock());
  86. curMap = &curData->maps.back();
  87. }
  88. else if (*buff == '}') {
  89. // close this map section
  90. if (curMap)
  91. curMap = NULL;
  92. else {
  93. curData = NULL;
  94. break;
  95. }
  96. }
  97. // 'map' - Specifies texture file name
  98. else if (TokenMatchI(buff,"map",3) || TokenMatchI(buff,"clampmap",8)) {
  99. curMap->name = GetNextToken(buff);
  100. }
  101. // 'blendfunc' - Alpha blending mode
  102. else if (TokenMatchI(buff,"blendfunc",9)) {
  103. // fixme
  104. }
  105. }
  106. }
  107. // 'cull' specifies culling behaviour for the model
  108. else if (TokenMatch(buff,"cull",4)) {
  109. SkipSpaces(&buff);
  110. if (!ASSIMP_strincmp(buff,"back",4)) {
  111. curData->cull = Q3Shader::CULL_CCW;
  112. }
  113. else if (!ASSIMP_strincmp(buff,"front",5)) {
  114. curData->cull = Q3Shader::CULL_CW;
  115. }
  116. //else curData->cull = Q3Shader::CULL_NONE;
  117. }
  118. else {
  119. // add new section
  120. fill.blocks.push_back(Q3Shader::ShaderDataBlock());
  121. curData = &fill.blocks.back();
  122. // get the name of this section
  123. curData->name = GetNextToken(buff);
  124. }
  125. }
  126. }
  127. // ------------------------------------------------------------------------------------------------
  128. // Load a Quake 3 skin
  129. void Q3Shader::LoadSkin(SkinData& fill, const std::string& pFile,IOSystem* io)
  130. {
  131. boost::scoped_ptr<IOStream> file( io->Open( pFile, "rt"));
  132. if (!file.get())
  133. return; // if we can't access the file, don't worry and return
  134. DefaultLogger::get()->info("Loading Quake3 skin file " + pFile);
  135. // read file in memory
  136. const size_t s = file->FileSize();
  137. std::vector<char> _buff(s+1);const char* buff = &_buff[0];
  138. file->Read(&_buff[0],s,1);
  139. _buff[s] = 0;
  140. // remove commas
  141. std::replace(_buff.begin(),_buff.end(),',',' ');
  142. // read token by token and fill output table
  143. for (;*buff;) {
  144. SkipSpacesAndLineEnd(&buff);
  145. // get first identifier
  146. std::string ss = GetNextToken(buff);
  147. // ignore tokens starting with tag_
  148. if (!::strncmp(&ss[0],"_tag",std::min((size_t)4, ss.length())))
  149. continue;
  150. fill.textures.push_back(SkinData::TextureEntry());
  151. SkinData::TextureEntry& s = fill.textures.back();
  152. s.first = ss;
  153. s.second = GetNextToken(buff);
  154. }
  155. }
  156. // ------------------------------------------------------------------------------------------------
  157. // Constructor to be privately used by Importer
  158. MD3Importer::MD3Importer()
  159. : configFrameID (0)
  160. , configHandleMP (true)
  161. {}
  162. // ------------------------------------------------------------------------------------------------
  163. // Destructor, private as well
  164. MD3Importer::~MD3Importer()
  165. {}
  166. // ------------------------------------------------------------------------------------------------
  167. // Returns whether the class can handle the format of the given file.
  168. bool MD3Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  169. {
  170. // simple check of file extension is enough for the moment
  171. std::string::size_type pos = pFile.find_last_of('.');
  172. // no file extension - can't read
  173. if( pos == std::string::npos)
  174. return false;
  175. std::string extension = pFile.substr( pos);
  176. for( std::string::iterator it = extension.begin(); it != extension.end(); ++it)
  177. *it = tolower( *it);
  178. return ( extension == ".md3");
  179. }
  180. // ------------------------------------------------------------------------------------------------
  181. void MD3Importer::ValidateHeaderOffsets()
  182. {
  183. // Check magic number
  184. if (pcHeader->IDENT != AI_MD3_MAGIC_NUMBER_BE &&
  185. pcHeader->IDENT != AI_MD3_MAGIC_NUMBER_LE)
  186. throw new ImportErrorException( "Invalid MD3 file: Magic bytes not found");
  187. // Check file format version
  188. if (pcHeader->VERSION > 15)
  189. DefaultLogger::get()->warn( "Unsupported MD3 file version. Continuing happily ...");
  190. // Check some offset values whether they are valid
  191. if (!pcHeader->NUM_SURFACES)
  192. throw new ImportErrorException( "Invalid md3 file: NUM_SURFACES is 0");
  193. if (pcHeader->OFS_FRAMES >= fileSize || pcHeader->OFS_SURFACES >= fileSize ||
  194. pcHeader->OFS_EOF > fileSize) {
  195. throw new ImportErrorException("Invalid MD3 header: some offsets are outside the file");
  196. }
  197. if (pcHeader->NUM_FRAMES <= configFrameID )
  198. throw new ImportErrorException("The requested frame is not existing the file");
  199. }
  200. // ------------------------------------------------------------------------------------------------
  201. void MD3Importer::ValidateSurfaceHeaderOffsets(const MD3::Surface* pcSurf)
  202. {
  203. // Calculate the relative offset of the surface
  204. const int32_t ofs = int32_t((const unsigned char*)pcSurf-this->mBuffer);
  205. // Check whether all data chunks are inside the valid range
  206. if (pcSurf->OFS_TRIANGLES + ofs + pcSurf->NUM_TRIANGLES * sizeof(MD3::Triangle) > fileSize ||
  207. pcSurf->OFS_SHADERS + ofs + pcSurf->NUM_SHADER * sizeof(MD3::Shader) > fileSize ||
  208. pcSurf->OFS_ST + ofs + pcSurf->NUM_VERTICES * sizeof(MD3::TexCoord) > fileSize ||
  209. pcSurf->OFS_XYZNORMAL + ofs + pcSurf->NUM_VERTICES * sizeof(MD3::Vertex) > fileSize) {
  210. throw new ImportErrorException("Invalid MD3 surface header: some offsets are outside the file");
  211. }
  212. // Check whether all requirements for Q3 files are met. We don't
  213. // care, but probably someone does.
  214. if (pcSurf->NUM_TRIANGLES > AI_MD3_MAX_TRIANGLES)
  215. DefaultLogger::get()->warn("MD3: Quake III triangle limit exceeded");
  216. if (pcSurf->NUM_SHADER > AI_MD3_MAX_SHADERS)
  217. DefaultLogger::get()->warn("MD3: Quake III shader limit exceeded");
  218. if (pcSurf->NUM_VERTICES > AI_MD3_MAX_VERTS)
  219. DefaultLogger::get()->warn("MD3: Quake III vertex limit exceeded");
  220. if (pcSurf->NUM_FRAMES > AI_MD3_MAX_FRAMES)
  221. DefaultLogger::get()->warn("MD3: Quake III frame limit exceeded");
  222. }
  223. // ------------------------------------------------------------------------------------------------
  224. void MD3Importer::GetExtensionList(std::string& append)
  225. {
  226. append.append("*.md3");
  227. }
  228. // ------------------------------------------------------------------------------------------------
  229. // Setup configuration properties
  230. void MD3Importer::SetupProperties(const Importer* pImp)
  231. {
  232. // The
  233. // AI_CONFIG_IMPORT_MD3_KEYFRAME option overrides the
  234. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  235. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD3_KEYFRAME,0xffffffff);
  236. if(0xffffffff == configFrameID) {
  237. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  238. }
  239. // AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART
  240. configHandleMP = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART,1));
  241. // AI_CONFIG_IMPORT_MD3_SKIN_NAME
  242. configSkinFile = (pImp->GetPropertyString(AI_CONFIG_IMPORT_MD3_SKIN_NAME,"default"));
  243. }
  244. // ------------------------------------------------------------------------------------------------
  245. // Try to read the skin for a MD3 file
  246. void MD3Importer::ReadSkin(Q3Shader::SkinData& fill)
  247. {
  248. // skip any postfixes (e.g. lower_1.md3)
  249. std::string::size_type s = filename.find_last_of('_');
  250. if (s == std::string::npos) {
  251. s = filename.find_last_of('.');
  252. }
  253. ai_assert(s != std::string::npos);
  254. const std::string skin_file = path + filename.substr(0,s) + "_" + configSkinFile + ".skin";
  255. Q3Shader::LoadSkin(fill,skin_file,mIOHandler);
  256. }
  257. // ------------------------------------------------------------------------------------------------
  258. // Read a multi-part Q3 player model
  259. bool MD3Importer::ReadMultipartFile()
  260. {
  261. // check whether the file name contains a common postfix, e.g lower_2.md3
  262. std::string::size_type s = filename.find_last_of('_'), t = filename.find_last_of('.');
  263. ai_assert(t != std::string::npos);
  264. if (s == std::string::npos)
  265. s = t;
  266. const std::string mod_filename = filename.substr(0,s);
  267. const std::string suffix = filename.substr(s,t-s);
  268. if (mod_filename == "lower" || mod_filename == "upper" || mod_filename == "head"){
  269. const std::string lower = path + "lower" + suffix + ".md3";
  270. const std::string upper = path + "upper" + suffix + ".md3";
  271. const std::string head = path + "head" + suffix + ".md3";
  272. aiScene* scene_upper = NULL;
  273. aiScene* scene_lower = NULL;
  274. aiScene* scene_head = NULL;
  275. std::string failure;
  276. aiNode* tag_torso, *tag_head;
  277. std::vector<AttachmentInfo> attach;
  278. DefaultLogger::get()->info("Multi-part MD3 player model: lower, upper and head parts are joined");
  279. // ensure we won't try to load ourselves recursively
  280. BatchLoader::PropertyMap props;
  281. SetGenericProperty( props.ints, AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART, 0, NULL);
  282. // now read these three files
  283. BatchLoader batch(mIOHandler);
  284. batch.AddLoadRequest(lower,0,&props);
  285. batch.AddLoadRequest(upper,0,&props);
  286. batch.AddLoadRequest(head,0,&props);
  287. batch.LoadAll();
  288. // now construct a dummy scene to place these three parts in
  289. aiScene* master = new aiScene();
  290. aiNode* nd = master->mRootNode = new aiNode();
  291. nd->mName.Set("<M3D_Player>");
  292. // ... and get them. We need all of them.
  293. scene_lower = batch.GetImport(lower);
  294. if (!scene_lower) {
  295. DefaultLogger::get()->error("M3D: Failed to read multipart model, lower.md3 fails to load");
  296. failure = "lower";
  297. goto error_cleanup;
  298. }
  299. scene_upper = batch.GetImport(upper);
  300. if (!scene_upper) {
  301. DefaultLogger::get()->error("M3D: Failed to read multipart model, upper.md3 fails to load");
  302. failure = "upper";
  303. goto error_cleanup;
  304. }
  305. scene_head = batch.GetImport(head);
  306. if (!scene_head) {
  307. DefaultLogger::get()->error("M3D: Failed to read multipart model, head.md3 fails to load");
  308. failure = "head";
  309. goto error_cleanup;
  310. }
  311. // build attachment infos. search for typical Q3 tags
  312. // original root
  313. attach.push_back(AttachmentInfo(scene_lower, nd));
  314. // tag_torso
  315. tag_torso = scene_lower->mRootNode->FindNode("tag_torso");
  316. if (!tag_torso) {
  317. DefaultLogger::get()->error("M3D: Failed to find attachment tag for multipart model: tag_torso expected");
  318. goto error_cleanup;
  319. }
  320. attach.push_back(AttachmentInfo(scene_upper,tag_torso));
  321. // tag_head
  322. tag_head = scene_upper->mRootNode->FindNode("tag_head");
  323. if (!tag_head) {
  324. DefaultLogger::get()->error("M3D: Failed to find attachment tag for multipart model: tag_head expected");
  325. goto error_cleanup;
  326. }
  327. attach.push_back(AttachmentInfo(scene_head,tag_head));
  328. // and merge the scenes
  329. SceneCombiner::MergeScenes(&mScene,master, attach,
  330. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES |
  331. AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES |
  332. AI_INT_MERGE_SCENE_RESOLVE_CROSS_ATTACHMENTS);
  333. return true;
  334. error_cleanup:
  335. delete scene_upper;
  336. delete scene_lower;
  337. delete scene_head;
  338. delete master;
  339. if (failure == mod_filename) {
  340. throw new ImportErrorException("MD3: failure to read multipart host file");
  341. }
  342. }
  343. return false;
  344. }
  345. // ------------------------------------------------------------------------------------------------
  346. // Imports the given file into the given scene structure.
  347. void MD3Importer::InternReadFile( const std::string& pFile,
  348. aiScene* pScene, IOSystem* pIOHandler)
  349. {
  350. mFile = pFile;
  351. mScene = pScene;
  352. mIOHandler = pIOHandler;
  353. // get base path and file name
  354. // todo ... move to PathConverter
  355. std::string::size_type s = mFile.find_last_of('/');
  356. if (s == std::string::npos) {
  357. s = mFile.find_last_of('\\');
  358. }
  359. if (s == std::string::npos) {
  360. s = 0;
  361. }
  362. else ++s;
  363. filename = mFile.substr(s), path = mFile.substr(0,s);
  364. for( std::string::iterator it = filename .begin(); it != filename.end(); ++it)
  365. *it = tolower( *it);
  366. // Load multi-part model file, if necessary
  367. if (configHandleMP) {
  368. if (ReadMultipartFile())
  369. return;
  370. }
  371. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  372. // Check whether we can read from the file
  373. if( file.get() == NULL)
  374. throw new ImportErrorException( "Failed to open MD3 file " + pFile + ".");
  375. // Check whether the md3 file is large enough to contain the header
  376. fileSize = (unsigned int)file->FileSize();
  377. if( fileSize < sizeof(MD3::Header))
  378. throw new ImportErrorException( "MD3 File is too small.");
  379. // Allocate storage and copy the contents of the file to a memory buffer
  380. std::vector<unsigned char> mBuffer2 (fileSize);
  381. file->Read( &mBuffer2[0], 1, fileSize);
  382. mBuffer = &mBuffer2[0];
  383. pcHeader = (BE_NCONST MD3::Header*)mBuffer;
  384. // Ensure correct endianess
  385. #ifdef AI_BUILD_BIG_ENDIAN
  386. AI_SWAP4(pcHeader->VERSION);
  387. AI_SWAP4(pcHeader->FLAGS);
  388. AI_SWAP4(pcHeader->IDENT);
  389. AI_SWAP4(pcHeader->NUM_FRAMES);
  390. AI_SWAP4(pcHeader->NUM_SKINS);
  391. AI_SWAP4(pcHeader->NUM_SURFACES);
  392. AI_SWAP4(pcHeader->NUM_TAGS);
  393. AI_SWAP4(pcHeader->OFS_EOF);
  394. AI_SWAP4(pcHeader->OFS_FRAMES);
  395. AI_SWAP4(pcHeader->OFS_SURFACES);
  396. AI_SWAP4(pcHeader->OFS_TAGS);
  397. #endif
  398. // Validate the file header
  399. ValidateHeaderOffsets();
  400. // Navigate to the list of surfaces
  401. BE_NCONST MD3::Surface* pcSurfaces = (BE_NCONST MD3::Surface*)(mBuffer + pcHeader->OFS_SURFACES);
  402. // Navigate to the list of tags
  403. BE_NCONST MD3::Tag* pcTags = (BE_NCONST MD3::Tag*)(mBuffer + pcHeader->OFS_TAGS);
  404. // Allocate output storage
  405. pScene->mNumMeshes = pcHeader->NUM_SURFACES;
  406. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  407. pScene->mNumMaterials = pcHeader->NUM_SURFACES;
  408. pScene->mMaterials = new aiMaterial*[pScene->mNumMeshes];
  409. // Set arrays to zero to ensue proper destruction if an exception is raised
  410. ::memset(pScene->mMeshes,0,pScene->mNumMeshes*sizeof(aiMesh*));
  411. ::memset(pScene->mMaterials,0,pScene->mNumMaterials*sizeof(aiMaterial*));
  412. // Now read possible skins from .skin file
  413. Q3Shader::SkinData skins;
  414. ReadSkin(skins);
  415. // Read all surfaces from the file
  416. unsigned int iNum = pcHeader->NUM_SURFACES;
  417. unsigned int iNumMaterials = 0;
  418. unsigned int iDefaultMatIndex = 0xFFFFFFFF;
  419. while (iNum-- > 0)
  420. {
  421. // Ensure correct endianess
  422. #ifdef AI_BUILD_BIG_ENDIAN
  423. AI_SWAP4(pcSurfaces->FLAGS);
  424. AI_SWAP4(pcSurfaces->IDENT);
  425. AI_SWAP4(pcSurfaces->NUM_FRAMES);
  426. AI_SWAP4(pcSurfaces->NUM_SHADER);
  427. AI_SWAP4(pcSurfaces->NUM_TRIANGLES);
  428. AI_SWAP4(pcSurfaces->NUM_VERTICES);
  429. AI_SWAP4(pcSurfaces->OFS_END);
  430. AI_SWAP4(pcSurfaces->OFS_SHADERS);
  431. AI_SWAP4(pcSurfaces->OFS_ST);
  432. AI_SWAP4(pcSurfaces->OFS_TRIANGLES);
  433. AI_SWAP4(pcSurfaces->OFS_XYZNORMAL);
  434. #endif
  435. // Validate the surface header
  436. ValidateSurfaceHeaderOffsets(pcSurfaces);
  437. // Navigate to the vertex list of the surface
  438. BE_NCONST MD3::Vertex* pcVertices = (BE_NCONST MD3::Vertex*)
  439. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_XYZNORMAL);
  440. // Navigate to the triangle list of the surface
  441. BE_NCONST MD3::Triangle* pcTriangles = (BE_NCONST MD3::Triangle*)
  442. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_TRIANGLES);
  443. // Navigate to the texture coordinate list of the surface
  444. BE_NCONST MD3::TexCoord* pcUVs = (BE_NCONST MD3::TexCoord*)
  445. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_ST);
  446. // Navigate to the shader list of the surface
  447. BE_NCONST MD3::Shader* pcShaders = (BE_NCONST MD3::Shader*)
  448. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_SHADERS);
  449. // If the submesh is empty ignore it
  450. if (0 == pcSurfaces->NUM_VERTICES || 0 == pcSurfaces->NUM_TRIANGLES)
  451. {
  452. pcSurfaces = (BE_NCONST MD3::Surface*)(((uint8_t*)pcSurfaces) + pcSurfaces->OFS_END);
  453. pScene->mNumMeshes--;
  454. continue;
  455. }
  456. // Ensure correct endianess
  457. #ifdef AI_BUILD_BIG_ENDIAN
  458. for (uint32_t i = 0; i < pcSurfaces->NUM_VERTICES;++i)
  459. {
  460. AI_SWAP2( pcVertices[i].NORMAL );
  461. AI_SWAP2( pcVertices[i].X );
  462. AI_SWAP2( pcVertices[i].Y );
  463. AI_SWAP2( pcVertices[i].Z );
  464. AI_SWAP4( pcUVs[i].U );
  465. AI_SWAP4( pcUVs[i].U );
  466. }
  467. for (uint32_t i = 0; i < pcSurfaces->NUM_TRIANGLES;++i)
  468. {
  469. AI_SWAP4(pcTriangles[i].INDEXES[0]);
  470. AI_SWAP4(pcTriangles[i].INDEXES[1]);
  471. AI_SWAP4(pcTriangles[i].INDEXES[2]);
  472. }
  473. #endif
  474. // Allocate the output mesh
  475. pScene->mMeshes[iNum] = new aiMesh();
  476. aiMesh* pcMesh = pScene->mMeshes[iNum];
  477. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  478. pcMesh->mNumVertices = pcSurfaces->NUM_TRIANGLES*3;
  479. pcMesh->mNumFaces = pcSurfaces->NUM_TRIANGLES;
  480. pcMesh->mFaces = new aiFace[pcSurfaces->NUM_TRIANGLES];
  481. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  482. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  483. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  484. pcMesh->mNumUVComponents[0] = 2;
  485. // Fill in all triangles
  486. unsigned int iCurrent = 0;
  487. for (unsigned int i = 0; i < (unsigned int)pcSurfaces->NUM_TRIANGLES;++i)
  488. {
  489. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  490. pcMesh->mFaces[i].mNumIndices = 3;
  491. unsigned int iTemp = iCurrent;
  492. for (unsigned int c = 0; c < 3;++c,++iCurrent)
  493. {
  494. // Read vertices
  495. pcMesh->mVertices[iCurrent].x = pcVertices[ pcTriangles->INDEXES[c]].X*AI_MD3_XYZ_SCALE;
  496. pcMesh->mVertices[iCurrent].y = pcVertices[ pcTriangles->INDEXES[c]].Y*AI_MD3_XYZ_SCALE;
  497. pcMesh->mVertices[iCurrent].z = pcVertices[ pcTriangles->INDEXES[c]].Z*AI_MD3_XYZ_SCALE;
  498. // Convert the normal vector to uncompressed float3 format
  499. LatLngNormalToVec3(pcVertices[pcTriangles->INDEXES[c]].NORMAL,
  500. (float*)&pcMesh->mNormals[iCurrent]);
  501. // Read texture coordinates
  502. pcMesh->mTextureCoords[0][iCurrent].x = pcUVs[ pcTriangles->INDEXES[c]].U;
  503. pcMesh->mTextureCoords[0][iCurrent].y = 1.0f-pcUVs[ pcTriangles->INDEXES[c]].V;
  504. }
  505. // FIX: flip the face ordering for use with OpenGL
  506. pcMesh->mFaces[i].mIndices[0] = iTemp+2;
  507. pcMesh->mFaces[i].mIndices[1] = iTemp+1;
  508. pcMesh->mFaces[i].mIndices[2] = iTemp+0;
  509. pcTriangles++;
  510. }
  511. std::string _texture_name;
  512. const char* texture_name = NULL, *header_name = pcHeader->NAME;
  513. // Check whether we have a texture record for this surface in the .skin file
  514. std::list< Q3Shader::SkinData::TextureEntry >::iterator it = std::find(
  515. skins.textures.begin(), skins.textures.end(), pcSurfaces->NAME );
  516. if (it != skins.textures.end()) {
  517. texture_name = &*( _texture_name = (*it).second).begin();
  518. DefaultLogger::get()->debug("MD3: Assigning skin texture " + (*it).second + " to surface " + pcSurfaces->NAME);
  519. (*it).resolved = true; // mark entry as resolved
  520. }
  521. // Get the first shader (= texture?) assigned to the surface
  522. if (!texture_name && pcSurfaces->NUM_SHADER) {
  523. texture_name = pcShaders->NAME;
  524. }
  525. const char* end2 = NULL;
  526. if (texture_name) {
  527. // If the MD3's internal path itself and the given path are using
  528. // the same directory, remove it completely to get right output paths.
  529. const char* end1 = ::strrchr(header_name,'\\');
  530. if (!end1)end1 = ::strrchr(header_name,'/');
  531. end2 = ::strrchr(texture_name,'\\');
  532. if (!end2)end2 = ::strrchr(texture_name,'/');
  533. // HACK: If the paths starts with "models/players", ignore the
  534. // next hierarchy level, it specifies just the model name.
  535. // Ignored by Q3, it might be not equal to the real model location.
  536. if (end1 && end2) {
  537. size_t len2;
  538. const size_t len1 = (size_t)(end1 - header_name);
  539. if (!ASSIMP_strincmp(header_name,"models/players/",15)) {
  540. len2 = 15;
  541. }
  542. else len2 = std::min (len1, (size_t)(end2 - texture_name ));
  543. if (!ASSIMP_strincmp(texture_name,header_name,len2)) {
  544. // Use the file name only
  545. end2++;
  546. }
  547. else {
  548. // Use the full path
  549. end2 = (const char*)texture_name;
  550. }
  551. }
  552. }
  553. MaterialHelper* pcHelper = new MaterialHelper();
  554. // Setup dummy texture file name to ensure UV coordinates are kept during postprocessing
  555. aiString szString;
  556. if (end2 && end2[0]) {
  557. const size_t iLen = ::strlen(end2);
  558. ::memcpy(szString.data,end2,iLen);
  559. szString.data[iLen] = '\0';
  560. szString.length = iLen;
  561. }
  562. else {
  563. DefaultLogger::get()->warn("Texture file name has zero length. Using default name");
  564. szString.Set("dummy_texture.bmp");
  565. }
  566. pcHelper->AddProperty(&szString,AI_MATKEY_TEXTURE_DIFFUSE(0));
  567. const int iMode = (int)aiShadingMode_Gouraud;
  568. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  569. // Add a small ambient color value - Quake 3 seems to have one
  570. aiColor3D clr;
  571. clr.b = clr.g = clr.r = 0.05f;
  572. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  573. clr.b = clr.g = clr.r = 1.0f;
  574. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  575. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  576. // use surface name + skin_name as material name
  577. aiString name;
  578. name.Set("MD3_[" + configSkinFile + "][" + pcSurfaces->NAME + "]");
  579. pcHelper->AddProperty(&name,AI_MATKEY_NAME);
  580. pScene->mMaterials[iNumMaterials] = (aiMaterial*)pcHelper;
  581. pcMesh->mMaterialIndex = iNumMaterials++;
  582. // Go to the next surface
  583. pcSurfaces = (BE_NCONST MD3::Surface*)(((unsigned char*)pcSurfaces) + pcSurfaces->OFS_END);
  584. }
  585. // For debugging purposes: check whether we found matches for all entries in the skins file
  586. if (!DefaultLogger::isNullLogger()) {
  587. for (std::list< Q3Shader::SkinData::TextureEntry>::const_iterator it = skins.textures.begin();it != skins.textures.end(); ++it) {
  588. if (!(*it).resolved) {
  589. DefaultLogger::get()->error("MD3: Failed to match skin " + (*it).first + " to surface " + (*it).second);
  590. }
  591. }
  592. }
  593. if (!pScene->mNumMeshes)
  594. throw new ImportErrorException( "MD3: File contains no valid mesh");
  595. pScene->mNumMaterials = iNumMaterials;
  596. // Now we need to generate an empty node graph
  597. pScene->mRootNode = new aiNode("<MD3Root>");
  598. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  599. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  600. // Attach tiny children for all tags
  601. if (pcHeader->NUM_TAGS) {
  602. pScene->mRootNode->mNumChildren = pcHeader->NUM_TAGS;
  603. pScene->mRootNode->mChildren = new aiNode*[pcHeader->NUM_TAGS];
  604. for (unsigned int i = 0; i < pcHeader->NUM_TAGS; ++i, ++pcTags) {
  605. aiNode* nd = pScene->mRootNode->mChildren[i] = new aiNode();
  606. nd->mName.Set((const char*)pcTags->NAME);
  607. nd->mParent = pScene->mRootNode;
  608. AI_SWAP4(pcTags->origin.x);
  609. AI_SWAP4(pcTags->origin.y);
  610. AI_SWAP4(pcTags->origin.z);
  611. // Copy local origin
  612. nd->mTransformation.a4 = pcTags->origin.x;
  613. nd->mTransformation.b4 = pcTags->origin.y;
  614. nd->mTransformation.c4 = pcTags->origin.z;
  615. // Copy rest of transformation (need to transpose to match row-order matrix)
  616. for (unsigned int a = 0; a < 3;++a) {
  617. for (unsigned int m = 0; m < 3;++m) {
  618. nd->mTransformation[m][a] = pcTags->orientation[a][m];
  619. AI_SWAP4(nd->mTransformation[m][a]);
  620. }
  621. }
  622. }
  623. }
  624. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  625. pScene->mRootNode->mMeshes[i] = i;
  626. }
  627. #endif // !! ASSIMP_BUILD_NO_MD3_IMPORTER