MD3Loader.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2017, 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. /** @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. #ifndef ASSIMP_BUILD_NO_MD3_IMPORTER
  43. #include "MD3Loader.h"
  44. #include <assimp/SceneCombiner.h>
  45. #include "GenericProperty.h"
  46. #include "RemoveComments.h"
  47. #include "ParsingUtils.h"
  48. #include "Importer.h"
  49. #include <assimp/DefaultLogger.hpp>
  50. #include <memory>
  51. #include <assimp/IOSystem.hpp>
  52. #include <assimp/material.h>
  53. #include <assimp/scene.h>
  54. #include <assimp/importerdesc.h>
  55. #include <cctype>
  56. using namespace Assimp;
  57. static const aiImporterDesc desc = {
  58. "Quake III Mesh Importer",
  59. "",
  60. "",
  61. "",
  62. aiImporterFlags_SupportBinaryFlavour,
  63. 0,
  64. 0,
  65. 0,
  66. 0,
  67. "md3"
  68. };
  69. // ------------------------------------------------------------------------------------------------
  70. // Convert a Q3 shader blend function to the appropriate enum value
  71. Q3Shader::BlendFunc StringToBlendFunc(const std::string& m)
  72. {
  73. if (m == "GL_ONE") {
  74. return Q3Shader::BLEND_GL_ONE;
  75. }
  76. if (m == "GL_ZERO") {
  77. return Q3Shader::BLEND_GL_ZERO;
  78. }
  79. if (m == "GL_SRC_ALPHA") {
  80. return Q3Shader::BLEND_GL_SRC_ALPHA;
  81. }
  82. if (m == "GL_ONE_MINUS_SRC_ALPHA") {
  83. return Q3Shader::BLEND_GL_ONE_MINUS_SRC_ALPHA;
  84. }
  85. if (m == "GL_ONE_MINUS_DST_COLOR") {
  86. return Q3Shader::BLEND_GL_ONE_MINUS_DST_COLOR;
  87. }
  88. DefaultLogger::get()->error("Q3Shader: Unknown blend function: " + m);
  89. return Q3Shader::BLEND_NONE;
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Load a Quake 3 shader
  93. bool Q3Shader::LoadShader(ShaderData& fill, const std::string& pFile,IOSystem* io)
  94. {
  95. std::unique_ptr<IOStream> file( io->Open( pFile, "rt"));
  96. if (!file.get())
  97. return false; // if we can't access the file, don't worry and return
  98. DefaultLogger::get()->info("Loading Quake3 shader file " + pFile);
  99. // read file in memory
  100. const size_t s = file->FileSize();
  101. std::vector<char> _buff(s+1);
  102. file->Read(&_buff[0],s,1);
  103. _buff[s] = 0;
  104. // remove comments from it (C++ style)
  105. CommentRemover::RemoveLineComments("//",&_buff[0]);
  106. const char* buff = &_buff[0];
  107. Q3Shader::ShaderDataBlock* curData = NULL;
  108. Q3Shader::ShaderMapBlock* curMap = NULL;
  109. // read line per line
  110. for (;SkipSpacesAndLineEnd(&buff);SkipLine(&buff)) {
  111. if (*buff == '{') {
  112. ++buff;
  113. // append to last section, if any
  114. if (!curData) {
  115. DefaultLogger::get()->error("Q3Shader: Unexpected shader section token \'{\'");
  116. return true; // still no failure, the file is there
  117. }
  118. // read this data section
  119. for (;SkipSpacesAndLineEnd(&buff);SkipLine(&buff)) {
  120. if (*buff == '{') {
  121. ++buff;
  122. // add new map section
  123. curData->maps.push_back(Q3Shader::ShaderMapBlock());
  124. curMap = &curData->maps.back();
  125. for (;SkipSpacesAndLineEnd(&buff);SkipLine(&buff)) {
  126. // 'map' - Specifies texture file name
  127. if (TokenMatchI(buff,"map",3) || TokenMatchI(buff,"clampmap",8)) {
  128. curMap->name = GetNextToken(buff);
  129. }
  130. // 'blendfunc' - Alpha blending mode
  131. else if (TokenMatchI(buff,"blendfunc",9)) {
  132. const std::string blend_src = GetNextToken(buff);
  133. if (blend_src == "add") {
  134. curMap->blend_src = Q3Shader::BLEND_GL_ONE;
  135. curMap->blend_dest = Q3Shader::BLEND_GL_ONE;
  136. }
  137. else if (blend_src == "filter") {
  138. curMap->blend_src = Q3Shader::BLEND_GL_DST_COLOR;
  139. curMap->blend_dest = Q3Shader::BLEND_GL_ZERO;
  140. }
  141. else if (blend_src == "blend") {
  142. curMap->blend_src = Q3Shader::BLEND_GL_SRC_ALPHA;
  143. curMap->blend_dest = Q3Shader::BLEND_GL_ONE_MINUS_SRC_ALPHA;
  144. }
  145. else {
  146. curMap->blend_src = StringToBlendFunc(blend_src);
  147. curMap->blend_dest = StringToBlendFunc(GetNextToken(buff));
  148. }
  149. }
  150. // 'alphafunc' - Alpha testing mode
  151. else if (TokenMatchI(buff,"alphafunc",9)) {
  152. const std::string at = GetNextToken(buff);
  153. if (at == "GT0") {
  154. curMap->alpha_test = Q3Shader::AT_GT0;
  155. }
  156. else if (at == "LT128") {
  157. curMap->alpha_test = Q3Shader::AT_LT128;
  158. }
  159. else if (at == "GE128") {
  160. curMap->alpha_test = Q3Shader::AT_GE128;
  161. }
  162. }
  163. else if (*buff == '}') {
  164. ++buff;
  165. // close this map section
  166. curMap = NULL;
  167. break;
  168. }
  169. }
  170. }
  171. else if (*buff == '}') {
  172. ++buff;
  173. curData = NULL;
  174. break;
  175. }
  176. // 'cull' specifies culling behaviour for the model
  177. else if (TokenMatchI(buff,"cull",4)) {
  178. SkipSpaces(&buff);
  179. if (!ASSIMP_strincmp(buff,"back",4)) {
  180. curData->cull = Q3Shader::CULL_CCW;
  181. }
  182. else if (!ASSIMP_strincmp(buff,"front",5)) {
  183. curData->cull = Q3Shader::CULL_CW;
  184. }
  185. else if (!ASSIMP_strincmp(buff,"none",4) || !ASSIMP_strincmp(buff,"disable",7)) {
  186. curData->cull = Q3Shader::CULL_NONE;
  187. }
  188. else DefaultLogger::get()->error("Q3Shader: Unrecognized cull mode");
  189. }
  190. }
  191. }
  192. else {
  193. // add new section
  194. fill.blocks.push_back(Q3Shader::ShaderDataBlock());
  195. curData = &fill.blocks.back();
  196. // get the name of this section
  197. curData->name = GetNextToken(buff);
  198. }
  199. }
  200. return true;
  201. }
  202. // ------------------------------------------------------------------------------------------------
  203. // Load a Quake 3 skin
  204. bool Q3Shader::LoadSkin(SkinData& fill, const std::string& pFile,IOSystem* io)
  205. {
  206. std::unique_ptr<IOStream> file( io->Open( pFile, "rt"));
  207. if (!file.get())
  208. return false; // if we can't access the file, don't worry and return
  209. DefaultLogger::get()->info("Loading Quake3 skin file " + pFile);
  210. // read file in memory
  211. const size_t s = file->FileSize();
  212. std::vector<char> _buff(s+1);const char* buff = &_buff[0];
  213. file->Read(&_buff[0],s,1);
  214. _buff[s] = 0;
  215. // remove commas
  216. std::replace(_buff.begin(),_buff.end(),',',' ');
  217. // read token by token and fill output table
  218. for (;*buff;) {
  219. SkipSpacesAndLineEnd(&buff);
  220. // get first identifier
  221. std::string ss = GetNextToken(buff);
  222. // ignore tokens starting with tag_
  223. if (!::strncmp(&ss[0],"tag_",std::min((size_t)4, ss.length())))
  224. continue;
  225. fill.textures.push_back(SkinData::TextureEntry());
  226. SkinData::TextureEntry& s = fill.textures.back();
  227. s.first = ss;
  228. s.second = GetNextToken(buff);
  229. }
  230. return true;
  231. }
  232. // ------------------------------------------------------------------------------------------------
  233. // Convert Q3Shader to material
  234. void Q3Shader::ConvertShaderToMaterial(aiMaterial* out, const ShaderDataBlock& shader)
  235. {
  236. ai_assert(NULL != out);
  237. /* IMPORTANT: This is not a real conversion. Actually we're just guessing and
  238. * hacking around to build an aiMaterial that looks nearly equal to the
  239. * original Quake 3 shader. We're missing some important features like
  240. * animatable material properties in our material system, but at least
  241. * multiple textures should be handled correctly.
  242. */
  243. // Two-sided material?
  244. if (shader.cull == Q3Shader::CULL_NONE) {
  245. const int twosided = 1;
  246. out->AddProperty(&twosided,1,AI_MATKEY_TWOSIDED);
  247. }
  248. unsigned int cur_emissive = 0, cur_diffuse = 0, cur_lm =0;
  249. // Iterate through all textures
  250. for (std::list< Q3Shader::ShaderMapBlock >::const_iterator it = shader.maps.begin(); it != shader.maps.end();++it) {
  251. // CONVERSION BEHAVIOUR:
  252. //
  253. //
  254. // If the texture is additive
  255. // - if it is the first texture, assume additive blending for the whole material
  256. // - otherwise register it as emissive texture.
  257. //
  258. // If the texture is using standard blend (or if the blend mode is unknown)
  259. // - if first texture: assume default blending for material
  260. // - in any case: set it as diffuse texture
  261. //
  262. // If the texture is using 'filter' blending
  263. // - take as lightmap
  264. //
  265. // Textures with alpha funcs
  266. // - aiTextureFlags_UseAlpha is set (otherwise aiTextureFlags_NoAlpha is explicitly set)
  267. aiString s((*it).name);
  268. aiTextureType type; unsigned int index;
  269. if ((*it).blend_src == Q3Shader::BLEND_GL_ONE && (*it).blend_dest == Q3Shader::BLEND_GL_ONE) {
  270. if (it == shader.maps.begin()) {
  271. const int additive = aiBlendMode_Additive;
  272. out->AddProperty(&additive,1,AI_MATKEY_BLEND_FUNC);
  273. index = cur_diffuse++;
  274. type = aiTextureType_DIFFUSE;
  275. }
  276. else {
  277. index = cur_emissive++;
  278. type = aiTextureType_EMISSIVE;
  279. }
  280. }
  281. else if ((*it).blend_src == Q3Shader::BLEND_GL_DST_COLOR && (*it).blend_dest == Q3Shader::BLEND_GL_ZERO) {
  282. index = cur_lm++;
  283. type = aiTextureType_LIGHTMAP;
  284. }
  285. else {
  286. const int blend = aiBlendMode_Default;
  287. out->AddProperty(&blend,1,AI_MATKEY_BLEND_FUNC);
  288. index = cur_diffuse++;
  289. type = aiTextureType_DIFFUSE;
  290. }
  291. // setup texture
  292. out->AddProperty(&s,AI_MATKEY_TEXTURE(type,index));
  293. // setup texture flags
  294. const int use_alpha = ((*it).alpha_test != Q3Shader::AT_NONE ? aiTextureFlags_UseAlpha : aiTextureFlags_IgnoreAlpha);
  295. out->AddProperty(&use_alpha,1,AI_MATKEY_TEXFLAGS(type,index));
  296. }
  297. // If at least one emissive texture was set, set the emissive base color to 1 to ensure
  298. // the texture is actually displayed.
  299. if (0 != cur_emissive) {
  300. aiColor3D one(1.f,1.f,1.f);
  301. out->AddProperty(&one,1,AI_MATKEY_COLOR_EMISSIVE);
  302. }
  303. }
  304. // ------------------------------------------------------------------------------------------------
  305. // Constructor to be privately used by Importer
  306. MD3Importer::MD3Importer()
  307. : configFrameID (0)
  308. , configHandleMP (true)
  309. , configSpeedFlag()
  310. , pcHeader()
  311. , mBuffer()
  312. , fileSize()
  313. , mScene()
  314. , mIOHandler()
  315. {}
  316. // ------------------------------------------------------------------------------------------------
  317. // Destructor, private as well
  318. MD3Importer::~MD3Importer()
  319. {}
  320. // ------------------------------------------------------------------------------------------------
  321. // Returns whether the class can handle the format of the given file.
  322. bool MD3Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  323. {
  324. const std::string extension = GetExtension(pFile);
  325. if (extension == "md3")
  326. return true;
  327. // if check for extension is not enough, check for the magic tokens
  328. if (!extension.length() || checkSig) {
  329. uint32_t tokens[1];
  330. tokens[0] = AI_MD3_MAGIC_NUMBER_LE;
  331. return CheckMagicToken(pIOHandler,pFile,tokens,1);
  332. }
  333. return false;
  334. }
  335. // ------------------------------------------------------------------------------------------------
  336. void MD3Importer::ValidateHeaderOffsets()
  337. {
  338. // Check magic number
  339. if (pcHeader->IDENT != AI_MD3_MAGIC_NUMBER_BE &&
  340. pcHeader->IDENT != AI_MD3_MAGIC_NUMBER_LE)
  341. throw DeadlyImportError( "Invalid MD3 file: Magic bytes not found");
  342. // Check file format version
  343. if (pcHeader->VERSION > 15)
  344. DefaultLogger::get()->warn( "Unsupported MD3 file version. Continuing happily ...");
  345. // Check some offset values whether they are valid
  346. if (!pcHeader->NUM_SURFACES)
  347. throw DeadlyImportError( "Invalid md3 file: NUM_SURFACES is 0");
  348. if (pcHeader->OFS_FRAMES >= fileSize || pcHeader->OFS_SURFACES >= fileSize ||
  349. pcHeader->OFS_EOF > fileSize) {
  350. throw DeadlyImportError("Invalid MD3 header: some offsets are outside the file");
  351. }
  352. if (pcHeader->NUM_SURFACES > AI_MAX_ALLOC(MD3::Surface)) {
  353. throw DeadlyImportError("Invalid MD3 header: too many surfaces, would overflow");
  354. }
  355. if (pcHeader->OFS_SURFACES + pcHeader->NUM_SURFACES * sizeof(MD3::Surface) >= fileSize) {
  356. throw DeadlyImportError("Invalid MD3 header: some surfaces are outside the file");
  357. }
  358. if (pcHeader->NUM_FRAMES <= configFrameID )
  359. throw DeadlyImportError("The requested frame is not existing the file");
  360. }
  361. // ------------------------------------------------------------------------------------------------
  362. void MD3Importer::ValidateSurfaceHeaderOffsets(const MD3::Surface* pcSurf)
  363. {
  364. // Calculate the relative offset of the surface
  365. const int32_t ofs = int32_t((const unsigned char*)pcSurf-this->mBuffer);
  366. // Check whether all data chunks are inside the valid range
  367. if (pcSurf->OFS_TRIANGLES + ofs + pcSurf->NUM_TRIANGLES * sizeof(MD3::Triangle) > fileSize ||
  368. pcSurf->OFS_SHADERS + ofs + pcSurf->NUM_SHADER * sizeof(MD3::Shader) > fileSize ||
  369. pcSurf->OFS_ST + ofs + pcSurf->NUM_VERTICES * sizeof(MD3::TexCoord) > fileSize ||
  370. pcSurf->OFS_XYZNORMAL + ofs + pcSurf->NUM_VERTICES * sizeof(MD3::Vertex) > fileSize) {
  371. throw DeadlyImportError("Invalid MD3 surface header: some offsets are outside the file");
  372. }
  373. // Check whether all requirements for Q3 files are met. We don't
  374. // care, but probably someone does.
  375. if (pcSurf->NUM_TRIANGLES > AI_MD3_MAX_TRIANGLES) {
  376. DefaultLogger::get()->warn("MD3: Quake III triangle limit exceeded");
  377. }
  378. if (pcSurf->NUM_SHADER > AI_MD3_MAX_SHADERS) {
  379. DefaultLogger::get()->warn("MD3: Quake III shader limit exceeded");
  380. }
  381. if (pcSurf->NUM_VERTICES > AI_MD3_MAX_VERTS) {
  382. DefaultLogger::get()->warn("MD3: Quake III vertex limit exceeded");
  383. }
  384. if (pcSurf->NUM_FRAMES > AI_MD3_MAX_FRAMES) {
  385. DefaultLogger::get()->warn("MD3: Quake III frame limit exceeded");
  386. }
  387. }
  388. // ------------------------------------------------------------------------------------------------
  389. const aiImporterDesc* MD3Importer::GetInfo () const
  390. {
  391. return &desc;
  392. }
  393. // ------------------------------------------------------------------------------------------------
  394. // Setup configuration properties
  395. void MD3Importer::SetupProperties(const Importer* pImp)
  396. {
  397. // The
  398. // AI_CONFIG_IMPORT_MD3_KEYFRAME option overrides the
  399. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  400. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD3_KEYFRAME,-1);
  401. if(static_cast<unsigned int>(-1) == configFrameID) {
  402. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  403. }
  404. // AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART
  405. configHandleMP = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART,1));
  406. // AI_CONFIG_IMPORT_MD3_SKIN_NAME
  407. configSkinFile = (pImp->GetPropertyString(AI_CONFIG_IMPORT_MD3_SKIN_NAME,"default"));
  408. // AI_CONFIG_IMPORT_MD3_SHADER_SRC
  409. configShaderFile = (pImp->GetPropertyString(AI_CONFIG_IMPORT_MD3_SHADER_SRC,""));
  410. // AI_CONFIG_FAVOUR_SPEED
  411. configSpeedFlag = (0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0));
  412. }
  413. // ------------------------------------------------------------------------------------------------
  414. // Try to read the skin for a MD3 file
  415. void MD3Importer::ReadSkin(Q3Shader::SkinData& fill) const
  416. {
  417. // skip any postfixes (e.g. lower_1.md3)
  418. std::string::size_type s = filename.find_last_of('_');
  419. if (s == std::string::npos) {
  420. s = filename.find_last_of('.');
  421. if (s == std::string::npos) {
  422. s = filename.size();
  423. }
  424. }
  425. ai_assert(s != std::string::npos);
  426. const std::string skin_file = path + filename.substr(0,s) + "_" + configSkinFile + ".skin";
  427. Q3Shader::LoadSkin(fill,skin_file,mIOHandler);
  428. }
  429. // ------------------------------------------------------------------------------------------------
  430. // Try to read the shader for a MD3 file
  431. void MD3Importer::ReadShader(Q3Shader::ShaderData& fill) const
  432. {
  433. // Determine Q3 model name from given path
  434. const std::string::size_type s = path.find_last_of("\\/",path.length()-2);
  435. const std::string model_file = path.substr(s+1,path.length()-(s+2));
  436. // If no specific dir or file is given, use our default search behaviour
  437. if (!configShaderFile.length()) {
  438. if(!Q3Shader::LoadShader(fill,path + "..\\..\\..\\scripts\\" + model_file + ".shader",mIOHandler)) {
  439. Q3Shader::LoadShader(fill,path + "..\\..\\..\\scripts\\" + filename + ".shader",mIOHandler);
  440. }
  441. }
  442. else {
  443. // If the given string specifies a file, load this file.
  444. // Otherwise it's a directory.
  445. const std::string::size_type st = configShaderFile.find_last_of('.');
  446. if (st == std::string::npos) {
  447. if(!Q3Shader::LoadShader(fill,configShaderFile + model_file + ".shader",mIOHandler)) {
  448. Q3Shader::LoadShader(fill,configShaderFile + filename + ".shader",mIOHandler);
  449. }
  450. }
  451. else {
  452. Q3Shader::LoadShader(fill,configShaderFile,mIOHandler);
  453. }
  454. }
  455. }
  456. // ------------------------------------------------------------------------------------------------
  457. // Tiny helper to remove a single node from its parent' list
  458. void RemoveSingleNodeFromList(aiNode* nd)
  459. {
  460. if (!nd || nd->mNumChildren || !nd->mParent)return;
  461. aiNode* par = nd->mParent;
  462. for (unsigned int i = 0; i < par->mNumChildren;++i) {
  463. if (par->mChildren[i] == nd) {
  464. --par->mNumChildren;
  465. for (;i < par->mNumChildren;++i) {
  466. par->mChildren[i] = par->mChildren[i+1];
  467. }
  468. delete nd;
  469. break;
  470. }
  471. }
  472. }
  473. // ------------------------------------------------------------------------------------------------
  474. // Read a multi-part Q3 player model
  475. bool MD3Importer::ReadMultipartFile()
  476. {
  477. // check whether the file name contains a common postfix, e.g lower_2.md3
  478. std::string::size_type s = filename.find_last_of('_'), t = filename.find_last_of('.');
  479. if (t == std::string::npos)
  480. t = filename.size();
  481. if (s == std::string::npos)
  482. s = t;
  483. const std::string mod_filename = filename.substr(0,s);
  484. const std::string suffix = filename.substr(s,t-s);
  485. if (mod_filename == "lower" || mod_filename == "upper" || mod_filename == "head"){
  486. const std::string lower = path + "lower" + suffix + ".md3";
  487. const std::string upper = path + "upper" + suffix + ".md3";
  488. const std::string head = path + "head" + suffix + ".md3";
  489. aiScene* scene_upper = NULL;
  490. aiScene* scene_lower = NULL;
  491. aiScene* scene_head = NULL;
  492. std::string failure;
  493. aiNode* tag_torso, *tag_head;
  494. std::vector<AttachmentInfo> attach;
  495. DefaultLogger::get()->info("Multi part MD3 player model: lower, upper and head parts are joined");
  496. // ensure we won't try to load ourselves recursively
  497. BatchLoader::PropertyMap props;
  498. SetGenericProperty( props.ints, AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART, 0);
  499. // now read these three files
  500. BatchLoader batch(mIOHandler);
  501. const unsigned int _lower = batch.AddLoadRequest(lower,0,&props);
  502. const unsigned int _upper = batch.AddLoadRequest(upper,0,&props);
  503. const unsigned int _head = batch.AddLoadRequest(head,0,&props);
  504. batch.LoadAll();
  505. // now construct a dummy scene to place these three parts in
  506. aiScene* master = new aiScene();
  507. aiNode* nd = master->mRootNode = new aiNode();
  508. nd->mName.Set("<MD3_Player>");
  509. // ... and get them. We need all of them.
  510. scene_lower = batch.GetImport(_lower);
  511. if (!scene_lower) {
  512. DefaultLogger::get()->error("M3D: Failed to read multi part model, lower.md3 fails to load");
  513. failure = "lower";
  514. goto error_cleanup;
  515. }
  516. scene_upper = batch.GetImport(_upper);
  517. if (!scene_upper) {
  518. DefaultLogger::get()->error("M3D: Failed to read multi part model, upper.md3 fails to load");
  519. failure = "upper";
  520. goto error_cleanup;
  521. }
  522. scene_head = batch.GetImport(_head);
  523. if (!scene_head) {
  524. DefaultLogger::get()->error("M3D: Failed to read multi part model, head.md3 fails to load");
  525. failure = "head";
  526. goto error_cleanup;
  527. }
  528. // build attachment infos. search for typical Q3 tags
  529. // original root
  530. scene_lower->mRootNode->mName.Set("lower");
  531. attach.push_back(AttachmentInfo(scene_lower, nd));
  532. // tag_torso
  533. tag_torso = scene_lower->mRootNode->FindNode("tag_torso");
  534. if (!tag_torso) {
  535. DefaultLogger::get()->error("M3D: Failed to find attachment tag for multi part model: tag_torso expected");
  536. goto error_cleanup;
  537. }
  538. scene_upper->mRootNode->mName.Set("upper");
  539. attach.push_back(AttachmentInfo(scene_upper,tag_torso));
  540. // tag_head
  541. tag_head = scene_upper->mRootNode->FindNode("tag_head");
  542. if (!tag_head) {
  543. DefaultLogger::get()->error("M3D: Failed to find attachment tag for multi part model: tag_head expected");
  544. goto error_cleanup;
  545. }
  546. scene_head->mRootNode->mName.Set("head");
  547. attach.push_back(AttachmentInfo(scene_head,tag_head));
  548. // Remove tag_head and tag_torso from all other model parts ...
  549. // this ensures (together with AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY)
  550. // that tag_torso/tag_head is also the name of the (unique) output node
  551. RemoveSingleNodeFromList (scene_upper->mRootNode->FindNode("tag_torso"));
  552. RemoveSingleNodeFromList (scene_head-> mRootNode->FindNode("tag_head" ));
  553. // Undo the rotations which we applied to the coordinate systems. We're
  554. // working in global Quake space here
  555. scene_head->mRootNode->mTransformation = aiMatrix4x4();
  556. scene_lower->mRootNode->mTransformation = aiMatrix4x4();
  557. scene_upper->mRootNode->mTransformation = aiMatrix4x4();
  558. // and merge the scenes
  559. SceneCombiner::MergeScenes(&mScene,master, attach,
  560. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES |
  561. AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES |
  562. AI_INT_MERGE_SCENE_RESOLVE_CROSS_ATTACHMENTS |
  563. (!configSpeedFlag ? AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY : 0));
  564. // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
  565. mScene->mRootNode->mTransformation = aiMatrix4x4(1.f,0.f,0.f,0.f,
  566. 0.f,0.f,1.f,0.f,0.f,-1.f,0.f,0.f,0.f,0.f,0.f,1.f);
  567. return true;
  568. error_cleanup:
  569. delete scene_upper;
  570. delete scene_lower;
  571. delete scene_head;
  572. delete master;
  573. if (failure == mod_filename) {
  574. throw DeadlyImportError("MD3: failure to read multipart host file");
  575. }
  576. }
  577. return false;
  578. }
  579. // ------------------------------------------------------------------------------------------------
  580. // Convert a MD3 path to a proper value
  581. void MD3Importer::ConvertPath(const char* texture_name, const char* header_name, std::string& out) const
  582. {
  583. // If the MD3's internal path itself and the given path are using
  584. // the same directory, remove it completely to get right output paths.
  585. const char* end1 = ::strrchr(header_name,'\\');
  586. if (!end1)end1 = ::strrchr(header_name,'/');
  587. const char* end2 = ::strrchr(texture_name,'\\');
  588. if (!end2)end2 = ::strrchr(texture_name,'/');
  589. // HACK: If the paths starts with "models", ignore the
  590. // next two hierarchy levels, it specifies just the model name.
  591. // Ignored by Q3, it might be not equal to the real model location.
  592. if (end2) {
  593. size_t len2;
  594. const size_t len1 = (size_t)(end1 - header_name);
  595. if (!ASSIMP_strincmp(texture_name,"models",6) && (texture_name[6] == '/' || texture_name[6] == '\\')) {
  596. len2 = 6; // ignore the seventh - could be slash or backslash
  597. if (!header_name[0]) {
  598. // Use the file name only
  599. out = end2+1;
  600. return;
  601. }
  602. }
  603. else len2 = std::min (len1, (size_t)(end2 - texture_name ));
  604. if (!ASSIMP_strincmp(texture_name,header_name,static_cast<unsigned int>(len2))) {
  605. // Use the file name only
  606. out = end2+1;
  607. return;
  608. }
  609. }
  610. // Use the full path
  611. out = texture_name;
  612. }
  613. // ------------------------------------------------------------------------------------------------
  614. // Imports the given file into the given scene structure.
  615. void MD3Importer::InternReadFile( const std::string& pFile,
  616. aiScene* pScene, IOSystem* pIOHandler)
  617. {
  618. mFile = pFile;
  619. mScene = pScene;
  620. mIOHandler = pIOHandler;
  621. // get base path and file name
  622. // todo ... move to PathConverter
  623. std::string::size_type s = mFile.find_last_of("/\\");
  624. if (s == std::string::npos) {
  625. s = 0;
  626. }
  627. else ++s;
  628. filename = mFile.substr(s), path = mFile.substr(0,s);
  629. for( std::string::iterator it = filename .begin(); it != filename.end(); ++it)
  630. *it = tolower( *it);
  631. // Load multi-part model file, if necessary
  632. if (configHandleMP) {
  633. if (ReadMultipartFile())
  634. return;
  635. }
  636. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  637. // Check whether we can read from the file
  638. if( file.get() == NULL)
  639. throw DeadlyImportError( "Failed to open MD3 file " + pFile + ".");
  640. // Check whether the md3 file is large enough to contain the header
  641. fileSize = (unsigned int)file->FileSize();
  642. if( fileSize < sizeof(MD3::Header))
  643. throw DeadlyImportError( "MD3 File is too small.");
  644. // Allocate storage and copy the contents of the file to a memory buffer
  645. std::vector<unsigned char> mBuffer2 (fileSize);
  646. file->Read( &mBuffer2[0], 1, fileSize);
  647. mBuffer = &mBuffer2[0];
  648. pcHeader = (BE_NCONST MD3::Header*)mBuffer;
  649. // Ensure correct endianness
  650. #ifdef AI_BUILD_BIG_ENDIAN
  651. AI_SWAP4(pcHeader->VERSION);
  652. AI_SWAP4(pcHeader->FLAGS);
  653. AI_SWAP4(pcHeader->IDENT);
  654. AI_SWAP4(pcHeader->NUM_FRAMES);
  655. AI_SWAP4(pcHeader->NUM_SKINS);
  656. AI_SWAP4(pcHeader->NUM_SURFACES);
  657. AI_SWAP4(pcHeader->NUM_TAGS);
  658. AI_SWAP4(pcHeader->OFS_EOF);
  659. AI_SWAP4(pcHeader->OFS_FRAMES);
  660. AI_SWAP4(pcHeader->OFS_SURFACES);
  661. AI_SWAP4(pcHeader->OFS_TAGS);
  662. #endif
  663. // Validate the file header
  664. ValidateHeaderOffsets();
  665. // Navigate to the list of surfaces
  666. BE_NCONST MD3::Surface* pcSurfaces = (BE_NCONST MD3::Surface*)(mBuffer + pcHeader->OFS_SURFACES);
  667. // Navigate to the list of tags
  668. BE_NCONST MD3::Tag* pcTags = (BE_NCONST MD3::Tag*)(mBuffer + pcHeader->OFS_TAGS);
  669. // Allocate output storage
  670. pScene->mNumMeshes = pcHeader->NUM_SURFACES;
  671. if (pcHeader->NUM_SURFACES == 0) {
  672. throw DeadlyImportError("MD3: No surfaces");
  673. } else if (pcHeader->NUM_SURFACES > AI_MAX_ALLOC(aiMesh)) {
  674. // We allocate pointers but check against the size of aiMesh
  675. // since those pointers will eventually have to point to real objects
  676. throw DeadlyImportError("MD3: Too many surfaces, would run out of memory");
  677. }
  678. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  679. pScene->mNumMaterials = pcHeader->NUM_SURFACES;
  680. pScene->mMaterials = new aiMaterial*[pScene->mNumMeshes];
  681. // Set arrays to zero to ensue proper destruction if an exception is raised
  682. ::memset(pScene->mMeshes,0,pScene->mNumMeshes*sizeof(aiMesh*));
  683. ::memset(pScene->mMaterials,0,pScene->mNumMaterials*sizeof(aiMaterial*));
  684. // Now read possible skins from .skin file
  685. Q3Shader::SkinData skins;
  686. ReadSkin(skins);
  687. // And check whether we can locate a shader file for this model
  688. Q3Shader::ShaderData shaders;
  689. ReadShader(shaders);
  690. // Adjust all texture paths in the shader
  691. const char* header_name = pcHeader->NAME;
  692. if (!shaders.blocks.empty()) {
  693. for (std::list< Q3Shader::ShaderDataBlock >::iterator dit = shaders.blocks.begin(); dit != shaders.blocks.end(); ++dit) {
  694. ConvertPath((*dit).name.c_str(),header_name,(*dit).name);
  695. for (std::list< Q3Shader::ShaderMapBlock >::iterator mit = (*dit).maps.begin(); mit != (*dit).maps.end(); ++mit) {
  696. ConvertPath((*mit).name.c_str(),header_name,(*mit).name);
  697. }
  698. }
  699. }
  700. // Read all surfaces from the file
  701. unsigned int iNum = pcHeader->NUM_SURFACES;
  702. unsigned int iNumMaterials = 0;
  703. while (iNum-- > 0) {
  704. // Ensure correct endianness
  705. #ifdef AI_BUILD_BIG_ENDIAN
  706. AI_SWAP4(pcSurfaces->FLAGS);
  707. AI_SWAP4(pcSurfaces->IDENT);
  708. AI_SWAP4(pcSurfaces->NUM_FRAMES);
  709. AI_SWAP4(pcSurfaces->NUM_SHADER);
  710. AI_SWAP4(pcSurfaces->NUM_TRIANGLES);
  711. AI_SWAP4(pcSurfaces->NUM_VERTICES);
  712. AI_SWAP4(pcSurfaces->OFS_END);
  713. AI_SWAP4(pcSurfaces->OFS_SHADERS);
  714. AI_SWAP4(pcSurfaces->OFS_ST);
  715. AI_SWAP4(pcSurfaces->OFS_TRIANGLES);
  716. AI_SWAP4(pcSurfaces->OFS_XYZNORMAL);
  717. #endif
  718. // Validate the surface header
  719. ValidateSurfaceHeaderOffsets(pcSurfaces);
  720. // Navigate to the vertex list of the surface
  721. BE_NCONST MD3::Vertex* pcVertices = (BE_NCONST MD3::Vertex*)
  722. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_XYZNORMAL);
  723. // Navigate to the triangle list of the surface
  724. BE_NCONST MD3::Triangle* pcTriangles = (BE_NCONST MD3::Triangle*)
  725. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_TRIANGLES);
  726. // Navigate to the texture coordinate list of the surface
  727. BE_NCONST MD3::TexCoord* pcUVs = (BE_NCONST MD3::TexCoord*)
  728. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_ST);
  729. // Navigate to the shader list of the surface
  730. BE_NCONST MD3::Shader* pcShaders = (BE_NCONST MD3::Shader*)
  731. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_SHADERS);
  732. // If the submesh is empty ignore it
  733. if (0 == pcSurfaces->NUM_VERTICES || 0 == pcSurfaces->NUM_TRIANGLES)
  734. {
  735. pcSurfaces = (BE_NCONST MD3::Surface*)(((uint8_t*)pcSurfaces) + pcSurfaces->OFS_END);
  736. pScene->mNumMeshes--;
  737. continue;
  738. }
  739. // Allocate output mesh
  740. pScene->mMeshes[iNum] = new aiMesh();
  741. aiMesh* pcMesh = pScene->mMeshes[iNum];
  742. std::string _texture_name;
  743. const char* texture_name = NULL;
  744. // Check whether we have a texture record for this surface in the .skin file
  745. std::list< Q3Shader::SkinData::TextureEntry >::iterator it = std::find(
  746. skins.textures.begin(), skins.textures.end(), pcSurfaces->NAME );
  747. if (it != skins.textures.end()) {
  748. texture_name = &*( _texture_name = (*it).second).begin();
  749. DefaultLogger::get()->debug("MD3: Assigning skin texture " + (*it).second + " to surface " + pcSurfaces->NAME);
  750. (*it).resolved = true; // mark entry as resolved
  751. }
  752. // Get the first shader (= texture?) assigned to the surface
  753. if (!texture_name && pcSurfaces->NUM_SHADER) {
  754. texture_name = pcShaders->NAME;
  755. }
  756. std::string convertedPath;
  757. if (texture_name) {
  758. ConvertPath(texture_name,header_name,convertedPath);
  759. }
  760. const Q3Shader::ShaderDataBlock* shader = NULL;
  761. // Now search the current shader for a record with this name (
  762. // excluding texture file extension)
  763. if (!shaders.blocks.empty()) {
  764. std::string::size_type s = convertedPath.find_last_of('.');
  765. if (s == std::string::npos)
  766. s = convertedPath.length();
  767. const std::string without_ext = convertedPath.substr(0,s);
  768. std::list< Q3Shader::ShaderDataBlock >::const_iterator dit = std::find(shaders.blocks.begin(),shaders.blocks.end(),without_ext);
  769. if (dit != shaders.blocks.end()) {
  770. // Hurra, wir haben einen. Tolle Sache.
  771. shader = &*dit;
  772. DefaultLogger::get()->info("Found shader record for " +without_ext );
  773. }
  774. else DefaultLogger::get()->warn("Unable to find shader record for " +without_ext );
  775. }
  776. aiMaterial* pcHelper = new aiMaterial();
  777. const int iMode = (int)aiShadingMode_Gouraud;
  778. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  779. // Add a small ambient color value - Quake 3 seems to have one
  780. aiColor3D clr;
  781. clr.b = clr.g = clr.r = 0.05f;
  782. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  783. clr.b = clr.g = clr.r = 1.0f;
  784. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  785. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  786. // use surface name + skin_name as material name
  787. aiString name;
  788. name.Set("MD3_[" + configSkinFile + "][" + pcSurfaces->NAME + "]");
  789. pcHelper->AddProperty(&name,AI_MATKEY_NAME);
  790. if (!shader) {
  791. // Setup dummy texture file name to ensure UV coordinates are kept during postprocessing
  792. aiString szString;
  793. if (convertedPath.length()) {
  794. szString.Set(convertedPath);
  795. }
  796. else {
  797. DefaultLogger::get()->warn("Texture file name has zero length. Using default name");
  798. szString.Set("dummy_texture.bmp");
  799. }
  800. pcHelper->AddProperty(&szString,AI_MATKEY_TEXTURE_DIFFUSE(0));
  801. // prevent transparency by default
  802. int no_alpha = aiTextureFlags_IgnoreAlpha;
  803. pcHelper->AddProperty(&no_alpha,1,AI_MATKEY_TEXFLAGS_DIFFUSE(0));
  804. }
  805. else {
  806. Q3Shader::ConvertShaderToMaterial(pcHelper,*shader);
  807. }
  808. pScene->mMaterials[iNumMaterials] = (aiMaterial*)pcHelper;
  809. pcMesh->mMaterialIndex = iNumMaterials++;
  810. // Ensure correct endianness
  811. #ifdef AI_BUILD_BIG_ENDIAN
  812. for (uint32_t i = 0; i < pcSurfaces->NUM_VERTICES;++i) {
  813. AI_SWAP2( pcVertices[i].NORMAL );
  814. AI_SWAP2( pcVertices[i].X );
  815. AI_SWAP2( pcVertices[i].Y );
  816. AI_SWAP2( pcVertices[i].Z );
  817. AI_SWAP4( pcUVs[i].U );
  818. AI_SWAP4( pcUVs[i].U );
  819. }
  820. for (uint32_t i = 0; i < pcSurfaces->NUM_TRIANGLES;++i) {
  821. AI_SWAP4(pcTriangles[i].INDEXES[0]);
  822. AI_SWAP4(pcTriangles[i].INDEXES[1]);
  823. AI_SWAP4(pcTriangles[i].INDEXES[2]);
  824. }
  825. #endif
  826. // Fill mesh information
  827. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  828. pcMesh->mNumVertices = pcSurfaces->NUM_TRIANGLES*3;
  829. pcMesh->mNumFaces = pcSurfaces->NUM_TRIANGLES;
  830. pcMesh->mFaces = new aiFace[pcSurfaces->NUM_TRIANGLES];
  831. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  832. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  833. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  834. pcMesh->mNumUVComponents[0] = 2;
  835. // Fill in all triangles
  836. unsigned int iCurrent = 0;
  837. for (unsigned int i = 0; i < (unsigned int)pcSurfaces->NUM_TRIANGLES;++i) {
  838. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  839. pcMesh->mFaces[i].mNumIndices = 3;
  840. //unsigned int iTemp = iCurrent;
  841. for (unsigned int c = 0; c < 3;++c,++iCurrent) {
  842. pcMesh->mFaces[i].mIndices[c] = iCurrent;
  843. // Read vertices
  844. aiVector3D& vec = pcMesh->mVertices[iCurrent];
  845. uint32_t index = pcTriangles->INDEXES[c];
  846. if (index >= pcSurfaces->NUM_VERTICES) {
  847. throw DeadlyImportError( "MD3: Invalid vertex index");
  848. }
  849. vec.x = pcVertices[index].X*AI_MD3_XYZ_SCALE;
  850. vec.y = pcVertices[index].Y*AI_MD3_XYZ_SCALE;
  851. vec.z = pcVertices[index].Z*AI_MD3_XYZ_SCALE;
  852. // Convert the normal vector to uncompressed float3 format
  853. aiVector3D& nor = pcMesh->mNormals[iCurrent];
  854. LatLngNormalToVec3(pcVertices[pcTriangles->INDEXES[c]].NORMAL,(ai_real*)&nor);
  855. // Read texture coordinates
  856. pcMesh->mTextureCoords[0][iCurrent].x = pcUVs[ pcTriangles->INDEXES[c]].U;
  857. pcMesh->mTextureCoords[0][iCurrent].y = 1.0f-pcUVs[ pcTriangles->INDEXES[c]].V;
  858. }
  859. // Flip face order if necessary
  860. if (!shader || shader->cull == Q3Shader::CULL_CW) {
  861. std::swap(pcMesh->mFaces[i].mIndices[2],pcMesh->mFaces[i].mIndices[1]);
  862. }
  863. pcTriangles++;
  864. }
  865. // Go to the next surface
  866. pcSurfaces = (BE_NCONST MD3::Surface*)(((unsigned char*)pcSurfaces) + pcSurfaces->OFS_END);
  867. }
  868. // For debugging purposes: check whether we found matches for all entries in the skins file
  869. if (!DefaultLogger::isNullLogger()) {
  870. for (std::list< Q3Shader::SkinData::TextureEntry>::const_iterator it = skins.textures.begin();it != skins.textures.end(); ++it) {
  871. if (!(*it).resolved) {
  872. DefaultLogger::get()->error("MD3: Failed to match skin " + (*it).first + " to surface " + (*it).second);
  873. }
  874. }
  875. }
  876. if (!pScene->mNumMeshes)
  877. throw DeadlyImportError( "MD3: File contains no valid mesh");
  878. pScene->mNumMaterials = iNumMaterials;
  879. // Now we need to generate an empty node graph
  880. pScene->mRootNode = new aiNode("<MD3Root>");
  881. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  882. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  883. // Attach tiny children for all tags
  884. if (pcHeader->NUM_TAGS) {
  885. pScene->mRootNode->mNumChildren = pcHeader->NUM_TAGS;
  886. pScene->mRootNode->mChildren = new aiNode*[pcHeader->NUM_TAGS];
  887. for (unsigned int i = 0; i < pcHeader->NUM_TAGS; ++i, ++pcTags) {
  888. aiNode* nd = pScene->mRootNode->mChildren[i] = new aiNode();
  889. nd->mName.Set((const char*)pcTags->NAME);
  890. nd->mParent = pScene->mRootNode;
  891. AI_SWAP4(pcTags->origin.x);
  892. AI_SWAP4(pcTags->origin.y);
  893. AI_SWAP4(pcTags->origin.z);
  894. // Copy local origin, again flip z,y
  895. nd->mTransformation.a4 = pcTags->origin.x;
  896. nd->mTransformation.b4 = pcTags->origin.y;
  897. nd->mTransformation.c4 = pcTags->origin.z;
  898. // Copy rest of transformation (need to transpose to match row-order matrix)
  899. for (unsigned int a = 0; a < 3;++a) {
  900. for (unsigned int m = 0; m < 3;++m) {
  901. nd->mTransformation[m][a] = pcTags->orientation[a][m];
  902. AI_SWAP4(nd->mTransformation[m][a]);
  903. }
  904. }
  905. }
  906. }
  907. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  908. pScene->mRootNode->mMeshes[i] = i;
  909. // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
  910. pScene->mRootNode->mTransformation = aiMatrix4x4(1.f,0.f,0.f,0.f,
  911. 0.f,0.f,1.f,0.f,0.f,-1.f,0.f,0.f,0.f,0.f,0.f,1.f);
  912. }
  913. #endif // !! ASSIMP_BUILD_NO_MD3_IMPORTER