MD3Loader.cpp 42 KB

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