MD3Loader.cpp 42 KB

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