MDLLoader.cpp 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, 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 MDLLoader.cpp
  35. * @brief Implementation of the main parts of the MDL importer class
  36. * *TODO* Cleanup and further testing of some parts necessary
  37. */
  38. // internal headers
  39. #ifndef ASSIMP_BUILD_NO_MDL_IMPORTER
  40. #include "AssetLib/MDL/MDLLoader.h"
  41. #include "AssetLib/MD2/MD2FileData.h"
  42. #include "AssetLib/MDL/HalfLife/HL1MDLLoader.h"
  43. #include "AssetLib/MDL/MDLDefaultColorMap.h"
  44. #include <assimp/StringUtils.h>
  45. #include <assimp/importerdesc.h>
  46. #include <assimp/qnan.h>
  47. #include <assimp/scene.h>
  48. #include <assimp/DefaultLogger.hpp>
  49. #include <assimp/IOSystem.hpp>
  50. #include <assimp/Importer.hpp>
  51. #include <memory>
  52. using namespace Assimp;
  53. static const aiImporterDesc desc = {
  54. "Quake Mesh / 3D GameStudio Mesh Importer",
  55. "",
  56. "",
  57. "",
  58. aiImporterFlags_SupportBinaryFlavour,
  59. 0,
  60. 0,
  61. 7,
  62. 0,
  63. "mdl"
  64. };
  65. // ------------------------------------------------------------------------------------------------
  66. // Ugly stuff ... nevermind
  67. #define _AI_MDL7_ACCESS(_data, _index, _limit, _type) \
  68. (*((const _type *)(((const char *)_data) + _index * _limit)))
  69. #define _AI_MDL7_ACCESS_PTR(_data, _index, _limit, _type) \
  70. ((BE_NCONST _type *)(((const char *)_data) + _index * _limit))
  71. #define _AI_MDL7_ACCESS_VERT(_data, _index, _limit) \
  72. _AI_MDL7_ACCESS(_data, _index, _limit, MDL::Vertex_MDL7)
  73. // ------------------------------------------------------------------------------------------------
  74. // Constructor to be privately used by Importer
  75. MDLImporter::MDLImporter() :
  76. configFrameID(), mBuffer(), iGSFileVersion(), mIOHandler(nullptr), pScene(), iFileSize() {
  77. // empty
  78. }
  79. // ------------------------------------------------------------------------------------------------
  80. // Destructor, private as well
  81. MDLImporter::~MDLImporter() {
  82. // empty
  83. }
  84. // ------------------------------------------------------------------------------------------------
  85. // Returns whether the class can handle the format of the given file.
  86. bool MDLImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const {
  87. const std::string extension = GetExtension(pFile);
  88. // if check for extension is not enough, check for the magic tokens
  89. if (extension == "mdl" || !extension.length() || checkSig) {
  90. uint32_t tokens[8];
  91. tokens[0] = AI_MDL_MAGIC_NUMBER_LE_HL2a;
  92. tokens[1] = AI_MDL_MAGIC_NUMBER_LE_HL2b;
  93. tokens[2] = AI_MDL_MAGIC_NUMBER_LE_GS7;
  94. tokens[3] = AI_MDL_MAGIC_NUMBER_LE_GS5b;
  95. tokens[4] = AI_MDL_MAGIC_NUMBER_LE_GS5a;
  96. tokens[5] = AI_MDL_MAGIC_NUMBER_LE_GS4;
  97. tokens[6] = AI_MDL_MAGIC_NUMBER_LE_GS3;
  98. tokens[7] = AI_MDL_MAGIC_NUMBER_LE;
  99. return CheckMagicToken(pIOHandler, pFile, tokens, 8, 0);
  100. }
  101. return false;
  102. }
  103. // ------------------------------------------------------------------------------------------------
  104. // Setup configuration properties
  105. void MDLImporter::SetupProperties(const Importer *pImp) {
  106. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MDL_KEYFRAME, -1);
  107. // The
  108. // AI_CONFIG_IMPORT_MDL_KEYFRAME option overrides the
  109. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  110. if (static_cast<unsigned int>(-1) == configFrameID) {
  111. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME, 0);
  112. }
  113. // AI_CONFIG_IMPORT_MDL_COLORMAP - palette file
  114. configPalette = pImp->GetPropertyString(AI_CONFIG_IMPORT_MDL_COLORMAP, "colormap.lmp");
  115. // Read configuration specific to MDL (Half-Life 1).
  116. mHL1ImportSettings.read_animations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_ANIMATIONS, true);
  117. if (mHL1ImportSettings.read_animations) {
  118. mHL1ImportSettings.read_animation_events = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_ANIMATION_EVENTS, true);
  119. mHL1ImportSettings.read_blend_controllers = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_BLEND_CONTROLLERS, true);
  120. mHL1ImportSettings.read_sequence_transitions = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_SEQUENCE_TRANSITIONS, true);
  121. }
  122. mHL1ImportSettings.read_attachments = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_ATTACHMENTS, true);
  123. mHL1ImportSettings.read_bone_controllers = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_BONE_CONTROLLERS, true);
  124. mHL1ImportSettings.read_hitboxes = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_HITBOXES, true);
  125. mHL1ImportSettings.read_misc_global_info = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_MISC_GLOBAL_INFO, true);
  126. }
  127. // ------------------------------------------------------------------------------------------------
  128. // Get a list of all supported extensions
  129. const aiImporterDesc *MDLImporter::GetInfo() const {
  130. return &desc;
  131. }
  132. // ------------------------------------------------------------------------------------------------
  133. // Imports the given file into the given scene structure.
  134. void MDLImporter::InternReadFile(const std::string &pFile,
  135. aiScene *_pScene, IOSystem *pIOHandler) {
  136. pScene = _pScene;
  137. mIOHandler = pIOHandler;
  138. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile));
  139. // Check whether we can read from the file
  140. if (file.get() == nullptr) {
  141. throw DeadlyImportError("Failed to open MDL file ", pFile, ".");
  142. }
  143. // This should work for all other types of MDL files, too ...
  144. // the HL1 sequence group header is one of the smallest, afaik
  145. iFileSize = (unsigned int)file->FileSize();
  146. if (iFileSize < sizeof(MDL::HalfLife::SequenceHeader_HL1)) {
  147. throw DeadlyImportError("MDL File is too small.");
  148. }
  149. // delete the file buffer and cleanup.
  150. auto DeleteBufferAndCleanup = [&]() {
  151. if (mBuffer) {
  152. delete[] mBuffer;
  153. mBuffer = nullptr;
  154. }
  155. AI_DEBUG_INVALIDATE_PTR(mIOHandler);
  156. AI_DEBUG_INVALIDATE_PTR(pScene);
  157. };
  158. try {
  159. // Allocate storage and copy the contents of the file to a memory buffer
  160. mBuffer = new unsigned char[iFileSize + 1];
  161. file->Read((void *)mBuffer, 1, iFileSize);
  162. // Append a binary zero to the end of the buffer.
  163. // this is just for safety that string parsing routines
  164. // find the end of the buffer ...
  165. mBuffer[iFileSize] = '\0';
  166. const uint32_t iMagicWord = *((uint32_t *)mBuffer);
  167. // Determine the file subtype and call the appropriate member function
  168. // Original Quake1 format
  169. if (AI_MDL_MAGIC_NUMBER_BE == iMagicWord || AI_MDL_MAGIC_NUMBER_LE == iMagicWord) {
  170. ASSIMP_LOG_DEBUG("MDL subtype: Quake 1, magic word is IDPO");
  171. iGSFileVersion = 0;
  172. InternReadFile_Quake1();
  173. }
  174. // GameStudio A<old> MDL2 format - used by some test models that come with 3DGS
  175. else if (AI_MDL_MAGIC_NUMBER_BE_GS3 == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_GS3 == iMagicWord) {
  176. ASSIMP_LOG_DEBUG("MDL subtype: 3D GameStudio A2, magic word is MDL2");
  177. iGSFileVersion = 2;
  178. InternReadFile_Quake1();
  179. }
  180. // GameStudio A4 MDL3 format
  181. else if (AI_MDL_MAGIC_NUMBER_BE_GS4 == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_GS4 == iMagicWord) {
  182. ASSIMP_LOG_DEBUG("MDL subtype: 3D GameStudio A4, magic word is MDL3");
  183. iGSFileVersion = 3;
  184. InternReadFile_3DGS_MDL345();
  185. }
  186. // GameStudio A5+ MDL4 format
  187. else if (AI_MDL_MAGIC_NUMBER_BE_GS5a == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_GS5a == iMagicWord) {
  188. ASSIMP_LOG_DEBUG("MDL subtype: 3D GameStudio A4, magic word is MDL4");
  189. iGSFileVersion = 4;
  190. InternReadFile_3DGS_MDL345();
  191. }
  192. // GameStudio A5+ MDL5 format
  193. else if (AI_MDL_MAGIC_NUMBER_BE_GS5b == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_GS5b == iMagicWord) {
  194. ASSIMP_LOG_DEBUG("MDL subtype: 3D GameStudio A5, magic word is MDL5");
  195. iGSFileVersion = 5;
  196. InternReadFile_3DGS_MDL345();
  197. }
  198. // GameStudio A7 MDL7 format
  199. else if (AI_MDL_MAGIC_NUMBER_BE_GS7 == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_GS7 == iMagicWord) {
  200. ASSIMP_LOG_DEBUG("MDL subtype: 3D GameStudio A7, magic word is MDL7");
  201. iGSFileVersion = 7;
  202. InternReadFile_3DGS_MDL7();
  203. }
  204. // IDST/IDSQ Format (CS:S/HL^2, etc ...)
  205. else if (AI_MDL_MAGIC_NUMBER_BE_HL2a == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_HL2a == iMagicWord ||
  206. AI_MDL_MAGIC_NUMBER_BE_HL2b == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_HL2b == iMagicWord) {
  207. iGSFileVersion = 0;
  208. HalfLife::HalfLifeMDLBaseHeader *pHeader = (HalfLife::HalfLifeMDLBaseHeader *)mBuffer;
  209. if (pHeader->version == AI_MDL_HL1_VERSION) {
  210. ASSIMP_LOG_DEBUG("MDL subtype: Half-Life 1/Goldsrc Engine, magic word is IDST/IDSQ");
  211. InternReadFile_HL1(pFile, iMagicWord);
  212. } else {
  213. ASSIMP_LOG_DEBUG("MDL subtype: Source(tm) Engine, magic word is IDST/IDSQ");
  214. InternReadFile_HL2();
  215. }
  216. } else {
  217. // print the magic word to the log file
  218. throw DeadlyImportError("Unknown MDL subformat ", pFile,
  219. ". Magic word (", std::string((char *)&iMagicWord, 4), ") is not known");
  220. }
  221. // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
  222. pScene->mRootNode->mTransformation = aiMatrix4x4(1.f, 0.f, 0.f, 0.f,
  223. 0.f, 0.f, 1.f, 0.f, 0.f, -1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f);
  224. DeleteBufferAndCleanup();
  225. } catch (...) {
  226. DeleteBufferAndCleanup();
  227. throw;
  228. }
  229. }
  230. // ------------------------------------------------------------------------------------------------
  231. // Check whether we're still inside the valid file range
  232. void MDLImporter::SizeCheck(const void *szPos) {
  233. if (!szPos || (const unsigned char *)szPos > this->mBuffer + this->iFileSize) {
  234. throw DeadlyImportError("Invalid MDL file. The file is too small "
  235. "or contains invalid data.");
  236. }
  237. }
  238. // ------------------------------------------------------------------------------------------------
  239. // Just for debugging purposes
  240. void MDLImporter::SizeCheck(const void *szPos, const char *szFile, unsigned int iLine) {
  241. ai_assert(nullptr != szFile);
  242. if (!szPos || (const unsigned char *)szPos > mBuffer + iFileSize) {
  243. // remove a directory if there is one
  244. const char *szFilePtr = ::strrchr(szFile, '\\');
  245. if (!szFilePtr) {
  246. szFilePtr = ::strrchr(szFile, '/');
  247. if (nullptr == szFilePtr) {
  248. szFilePtr = szFile;
  249. }
  250. }
  251. if (szFilePtr) {
  252. ++szFilePtr;
  253. }
  254. char szBuffer[1024];
  255. ::sprintf(szBuffer, "Invalid MDL file. The file is too small "
  256. "or contains invalid data (File: %s Line: %u)",
  257. szFilePtr, iLine);
  258. throw DeadlyImportError(szBuffer);
  259. }
  260. }
  261. // ------------------------------------------------------------------------------------------------
  262. // Validate a quake file header
  263. void MDLImporter::ValidateHeader_Quake1(const MDL::Header *pcHeader) {
  264. // some values may not be nullptr
  265. if (!pcHeader->num_frames)
  266. throw DeadlyImportError("[Quake 1 MDL] There are no frames in the file");
  267. if (!pcHeader->num_verts)
  268. throw DeadlyImportError("[Quake 1 MDL] There are no vertices in the file");
  269. if (!pcHeader->num_tris)
  270. throw DeadlyImportError("[Quake 1 MDL] There are no triangles in the file");
  271. // check whether the maxima are exceeded ...however, this applies for Quake 1 MDLs only
  272. if (!this->iGSFileVersion) {
  273. if (pcHeader->num_verts > AI_MDL_MAX_VERTS)
  274. ASSIMP_LOG_WARN("Quake 1 MDL model has more than AI_MDL_MAX_VERTS vertices");
  275. if (pcHeader->num_tris > AI_MDL_MAX_TRIANGLES)
  276. ASSIMP_LOG_WARN("Quake 1 MDL model has more than AI_MDL_MAX_TRIANGLES triangles");
  277. if (pcHeader->num_frames > AI_MDL_MAX_FRAMES)
  278. ASSIMP_LOG_WARN("Quake 1 MDL model has more than AI_MDL_MAX_FRAMES frames");
  279. // (this does not apply for 3DGS MDLs)
  280. if (!this->iGSFileVersion && pcHeader->version != AI_MDL_VERSION)
  281. ASSIMP_LOG_WARN("Quake 1 MDL model has an unknown version: AI_MDL_VERSION (=6) is "
  282. "the expected file format version");
  283. if (pcHeader->num_skins && (!pcHeader->skinwidth || !pcHeader->skinheight))
  284. ASSIMP_LOG_WARN("Skin width or height are 0");
  285. }
  286. }
  287. #ifdef AI_BUILD_BIG_ENDIAN
  288. // ------------------------------------------------------------------------------------------------
  289. void FlipQuakeHeader(BE_NCONST MDL::Header *pcHeader) {
  290. AI_SWAP4(pcHeader->ident);
  291. AI_SWAP4(pcHeader->version);
  292. AI_SWAP4(pcHeader->boundingradius);
  293. AI_SWAP4(pcHeader->flags);
  294. AI_SWAP4(pcHeader->num_frames);
  295. AI_SWAP4(pcHeader->num_skins);
  296. AI_SWAP4(pcHeader->num_tris);
  297. AI_SWAP4(pcHeader->num_verts);
  298. for (unsigned int i = 0; i < 3; ++i) {
  299. AI_SWAP4(pcHeader->scale[i]);
  300. AI_SWAP4(pcHeader->translate[i]);
  301. }
  302. AI_SWAP4(pcHeader->size);
  303. AI_SWAP4(pcHeader->skinheight);
  304. AI_SWAP4(pcHeader->skinwidth);
  305. AI_SWAP4(pcHeader->synctype);
  306. }
  307. #endif
  308. // ------------------------------------------------------------------------------------------------
  309. // Read a Quake 1 file
  310. void MDLImporter::InternReadFile_Quake1() {
  311. ai_assert(nullptr != pScene);
  312. BE_NCONST MDL::Header *pcHeader = (BE_NCONST MDL::Header *)this->mBuffer;
  313. #ifdef AI_BUILD_BIG_ENDIAN
  314. FlipQuakeHeader(pcHeader);
  315. #endif
  316. ValidateHeader_Quake1(pcHeader);
  317. // current cursor position in the file
  318. const unsigned char *szCurrent = (const unsigned char *)(pcHeader + 1);
  319. // need to read all textures
  320. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_skins; ++i) {
  321. union {
  322. BE_NCONST MDL::Skin *pcSkin;
  323. BE_NCONST MDL::GroupSkin *pcGroupSkin;
  324. };
  325. if (szCurrent + sizeof(MDL::Skin) > this->mBuffer + this->iFileSize) {
  326. throw DeadlyImportError("[Quake 1 MDL] Unexpected EOF");
  327. }
  328. pcSkin = (BE_NCONST MDL::Skin *)szCurrent;
  329. AI_SWAP4(pcSkin->group);
  330. // Quake 1 group-skins
  331. if (1 == pcSkin->group) {
  332. AI_SWAP4(pcGroupSkin->nb);
  333. // need to skip multiple images
  334. const unsigned int iNumImages = (unsigned int)pcGroupSkin->nb;
  335. szCurrent += sizeof(uint32_t) * 2;
  336. if (0 != iNumImages) {
  337. if (!i) {
  338. // however, create only one output image (the first)
  339. this->CreateTextureARGB8_3DGS_MDL3(szCurrent + iNumImages * sizeof(float));
  340. }
  341. // go to the end of the skin section / the beginning of the next skin
  342. szCurrent += pcHeader->skinheight * pcHeader->skinwidth +
  343. sizeof(float) * iNumImages;
  344. }
  345. } else {
  346. szCurrent += sizeof(uint32_t);
  347. unsigned int iSkip = i ? UINT_MAX : 0;
  348. CreateTexture_3DGS_MDL4(szCurrent, pcSkin->group, &iSkip);
  349. szCurrent += iSkip;
  350. }
  351. }
  352. // get a pointer to the texture coordinates
  353. BE_NCONST MDL::TexCoord *pcTexCoords = (BE_NCONST MDL::TexCoord *)szCurrent;
  354. szCurrent += sizeof(MDL::TexCoord) * pcHeader->num_verts;
  355. // get a pointer to the triangles
  356. BE_NCONST MDL::Triangle *pcTriangles = (BE_NCONST MDL::Triangle *)szCurrent;
  357. szCurrent += sizeof(MDL::Triangle) * pcHeader->num_tris;
  358. VALIDATE_FILE_SIZE(szCurrent);
  359. // now get a pointer to the first frame in the file
  360. BE_NCONST MDL::Frame *pcFrames = (BE_NCONST MDL::Frame *)szCurrent;
  361. MDL::SimpleFrame *pcFirstFrame;
  362. if (0 == pcFrames->type) {
  363. // get address of single frame
  364. pcFirstFrame = (MDL::SimpleFrame *)&pcFrames->frame;
  365. } else {
  366. // get the first frame in the group
  367. BE_NCONST MDL::GroupFrame *pcFrames2 = (BE_NCONST MDL::GroupFrame *)pcFrames;
  368. pcFirstFrame = &(pcFrames2->frames[0]);
  369. }
  370. BE_NCONST MDL::Vertex *pcVertices = (BE_NCONST MDL::Vertex *)((pcFirstFrame->name) + sizeof(pcFirstFrame->name));
  371. VALIDATE_FILE_SIZE((const unsigned char *)(pcVertices + pcHeader->num_verts));
  372. #ifdef AI_BUILD_BIG_ENDIAN
  373. for (int i = 0; i < pcHeader->num_verts; ++i) {
  374. AI_SWAP4(pcTexCoords[i].onseam);
  375. AI_SWAP4(pcTexCoords[i].s);
  376. AI_SWAP4(pcTexCoords[i].t);
  377. }
  378. for (int i = 0; i < pcHeader->num_tris; ++i) {
  379. AI_SWAP4(pcTriangles[i].facesfront);
  380. AI_SWAP4(pcTriangles[i].vertex[0]);
  381. AI_SWAP4(pcTriangles[i].vertex[1]);
  382. AI_SWAP4(pcTriangles[i].vertex[2]);
  383. }
  384. #endif
  385. // setup materials
  386. SetupMaterialProperties_3DGS_MDL5_Quake1();
  387. // allocate enough storage to hold all vertices and triangles
  388. aiMesh *pcMesh = new aiMesh();
  389. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  390. pcMesh->mNumVertices = pcHeader->num_tris * 3;
  391. pcMesh->mNumFaces = pcHeader->num_tris;
  392. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  393. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  394. pcMesh->mFaces = new aiFace[pcMesh->mNumFaces];
  395. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  396. pcMesh->mNumUVComponents[0] = 2;
  397. // there won't be more than one mesh inside the file
  398. pScene->mRootNode = new aiNode();
  399. pScene->mRootNode->mNumMeshes = 1;
  400. pScene->mRootNode->mMeshes = new unsigned int[1];
  401. pScene->mRootNode->mMeshes[0] = 0;
  402. pScene->mNumMeshes = 1;
  403. pScene->mMeshes = new aiMesh *[1];
  404. pScene->mMeshes[0] = pcMesh;
  405. // now iterate through all triangles
  406. unsigned int iCurrent = 0;
  407. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_tris; ++i) {
  408. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  409. pcMesh->mFaces[i].mNumIndices = 3;
  410. unsigned int iTemp = iCurrent;
  411. for (unsigned int c = 0; c < 3; ++c, ++iCurrent) {
  412. pcMesh->mFaces[i].mIndices[c] = iCurrent;
  413. // read vertices
  414. unsigned int iIndex = pcTriangles->vertex[c];
  415. if (iIndex >= (unsigned int)pcHeader->num_verts) {
  416. iIndex = pcHeader->num_verts - 1;
  417. ASSIMP_LOG_WARN("Index overflow in Q1-MDL vertex list.");
  418. }
  419. aiVector3D &vec = pcMesh->mVertices[iCurrent];
  420. vec.x = (float)pcVertices[iIndex].v[0] * pcHeader->scale[0];
  421. vec.x += pcHeader->translate[0];
  422. vec.y = (float)pcVertices[iIndex].v[1] * pcHeader->scale[1];
  423. vec.y += pcHeader->translate[1];
  424. //vec.y *= -1.0f;
  425. vec.z = (float)pcVertices[iIndex].v[2] * pcHeader->scale[2];
  426. vec.z += pcHeader->translate[2];
  427. // read the normal vector from the precalculated normal table
  428. MD2::LookupNormalIndex(pcVertices[iIndex].normalIndex, pcMesh->mNormals[iCurrent]);
  429. //pcMesh->mNormals[iCurrent].y *= -1.0f;
  430. // read texture coordinates
  431. float s = (float)pcTexCoords[iIndex].s;
  432. float t = (float)pcTexCoords[iIndex].t;
  433. // translate texture coordinates
  434. if (0 == pcTriangles->facesfront && 0 != pcTexCoords[iIndex].onseam) {
  435. s += pcHeader->skinwidth * 0.5f;
  436. }
  437. // Scale s and t to range from 0.0 to 1.0
  438. pcMesh->mTextureCoords[0][iCurrent].x = (s + 0.5f) / pcHeader->skinwidth;
  439. pcMesh->mTextureCoords[0][iCurrent].y = 1.0f - (t + 0.5f) / pcHeader->skinheight;
  440. }
  441. pcMesh->mFaces[i].mIndices[0] = iTemp + 2;
  442. pcMesh->mFaces[i].mIndices[1] = iTemp + 1;
  443. pcMesh->mFaces[i].mIndices[2] = iTemp + 0;
  444. pcTriangles++;
  445. }
  446. return;
  447. }
  448. // ------------------------------------------------------------------------------------------------
  449. // Setup material properties for Quake and older GameStudio files
  450. void MDLImporter::SetupMaterialProperties_3DGS_MDL5_Quake1() {
  451. const MDL::Header *const pcHeader = (const MDL::Header *)this->mBuffer;
  452. // allocate ONE material
  453. pScene->mMaterials = new aiMaterial *[1];
  454. pScene->mMaterials[0] = new aiMaterial();
  455. pScene->mNumMaterials = 1;
  456. // setup the material's properties
  457. const int iMode = (int)aiShadingMode_Gouraud;
  458. aiMaterial *const pcHelper = (aiMaterial *)pScene->mMaterials[0];
  459. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  460. aiColor4D clr;
  461. if (0 != pcHeader->num_skins && pScene->mNumTextures) {
  462. // can we replace the texture with a single color?
  463. clr = this->ReplaceTextureWithColor(pScene->mTextures[0]);
  464. if (is_not_qnan(clr.r)) {
  465. delete pScene->mTextures[0];
  466. delete[] pScene->mTextures;
  467. pScene->mTextures = nullptr;
  468. pScene->mNumTextures = 0;
  469. } else {
  470. clr.b = clr.a = clr.g = clr.r = 1.0f;
  471. aiString szString;
  472. ::memcpy(szString.data, AI_MAKE_EMBEDDED_TEXNAME(0), 3);
  473. szString.length = 2;
  474. pcHelper->AddProperty(&szString, AI_MATKEY_TEXTURE_DIFFUSE(0));
  475. }
  476. }
  477. pcHelper->AddProperty<aiColor4D>(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  478. pcHelper->AddProperty<aiColor4D>(&clr, 1, AI_MATKEY_COLOR_SPECULAR);
  479. clr.r *= 0.05f;
  480. clr.g *= 0.05f;
  481. clr.b *= 0.05f;
  482. clr.a = 1.0f;
  483. pcHelper->AddProperty<aiColor4D>(&clr, 1, AI_MATKEY_COLOR_AMBIENT);
  484. }
  485. // ------------------------------------------------------------------------------------------------
  486. // Read a MDL 3,4,5 file
  487. void MDLImporter::InternReadFile_3DGS_MDL345() {
  488. ai_assert(nullptr != pScene);
  489. // the header of MDL 3/4/5 is nearly identical to the original Quake1 header
  490. BE_NCONST MDL::Header *pcHeader = (BE_NCONST MDL::Header *)this->mBuffer;
  491. #ifdef AI_BUILD_BIG_ENDIAN
  492. FlipQuakeHeader(pcHeader);
  493. #endif
  494. ValidateHeader_Quake1(pcHeader);
  495. // current cursor position in the file
  496. const unsigned char *szCurrent = (const unsigned char *)(pcHeader + 1);
  497. const unsigned char *szEnd = mBuffer + iFileSize;
  498. // need to read all textures
  499. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_skins; ++i) {
  500. if (szCurrent >= szEnd) {
  501. throw DeadlyImportError("Texture data past end of file.");
  502. }
  503. BE_NCONST MDL::Skin *pcSkin;
  504. pcSkin = (BE_NCONST MDL::Skin *)szCurrent;
  505. AI_SWAP4(pcSkin->group);
  506. // create one output image
  507. unsigned int iSkip = i ? UINT_MAX : 0;
  508. if (5 <= iGSFileVersion) {
  509. // MDL5 format could contain MIPmaps
  510. CreateTexture_3DGS_MDL5((unsigned char *)pcSkin + sizeof(uint32_t),
  511. pcSkin->group, &iSkip);
  512. } else {
  513. CreateTexture_3DGS_MDL4((unsigned char *)pcSkin + sizeof(uint32_t),
  514. pcSkin->group, &iSkip);
  515. }
  516. // need to skip one image
  517. szCurrent += iSkip + sizeof(uint32_t);
  518. }
  519. // get a pointer to the texture coordinates
  520. BE_NCONST MDL::TexCoord_MDL3 *pcTexCoords = (BE_NCONST MDL::TexCoord_MDL3 *)szCurrent;
  521. szCurrent += sizeof(MDL::TexCoord_MDL3) * pcHeader->synctype;
  522. // NOTE: for MDLn formats "synctype" corresponds to the number of UV coords
  523. // get a pointer to the triangles
  524. BE_NCONST MDL::Triangle_MDL3 *pcTriangles = (BE_NCONST MDL::Triangle_MDL3 *)szCurrent;
  525. szCurrent += sizeof(MDL::Triangle_MDL3) * pcHeader->num_tris;
  526. #ifdef AI_BUILD_BIG_ENDIAN
  527. for (int i = 0; i < pcHeader->synctype; ++i) {
  528. AI_SWAP2(pcTexCoords[i].u);
  529. AI_SWAP2(pcTexCoords[i].v);
  530. }
  531. for (int i = 0; i < pcHeader->num_tris; ++i) {
  532. AI_SWAP2(pcTriangles[i].index_xyz[0]);
  533. AI_SWAP2(pcTriangles[i].index_xyz[1]);
  534. AI_SWAP2(pcTriangles[i].index_xyz[2]);
  535. AI_SWAP2(pcTriangles[i].index_uv[0]);
  536. AI_SWAP2(pcTriangles[i].index_uv[1]);
  537. AI_SWAP2(pcTriangles[i].index_uv[2]);
  538. }
  539. #endif
  540. VALIDATE_FILE_SIZE(szCurrent);
  541. // setup materials
  542. SetupMaterialProperties_3DGS_MDL5_Quake1();
  543. // allocate enough storage to hold all vertices and triangles
  544. aiMesh *pcMesh = new aiMesh();
  545. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  546. pcMesh->mNumVertices = pcHeader->num_tris * 3;
  547. pcMesh->mNumFaces = pcHeader->num_tris;
  548. pcMesh->mFaces = new aiFace[pcMesh->mNumFaces];
  549. // there won't be more than one mesh inside the file
  550. pScene->mRootNode = new aiNode();
  551. pScene->mRootNode->mNumMeshes = 1;
  552. pScene->mRootNode->mMeshes = new unsigned int[1];
  553. pScene->mRootNode->mMeshes[0] = 0;
  554. pScene->mNumMeshes = 1;
  555. pScene->mMeshes = new aiMesh *[1];
  556. pScene->mMeshes[0] = pcMesh;
  557. // allocate output storage
  558. pcMesh->mNumVertices = (unsigned int)pcHeader->num_tris * 3;
  559. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  560. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  561. if (pcHeader->synctype) {
  562. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  563. pcMesh->mNumUVComponents[0] = 2;
  564. }
  565. // now get a pointer to the first frame in the file
  566. BE_NCONST MDL::Frame *pcFrames = (BE_NCONST MDL::Frame *)szCurrent;
  567. AI_SWAP4(pcFrames->type);
  568. // byte packed vertices
  569. // FIXME: these two snippets below are almost identical ... join them?
  570. /////////////////////////////////////////////////////////////////////////////////////
  571. if (0 == pcFrames->type || 3 >= this->iGSFileVersion) {
  572. const MDL::SimpleFrame *pcFirstFrame = (const MDL::SimpleFrame *)(szCurrent + sizeof(uint32_t));
  573. const MDL::Vertex *pcVertices = (const MDL::Vertex *)((pcFirstFrame->name) + sizeof(pcFirstFrame->name));
  574. VALIDATE_FILE_SIZE(pcVertices + pcHeader->num_verts);
  575. // now iterate through all triangles
  576. unsigned int iCurrent = 0;
  577. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_tris; ++i) {
  578. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  579. pcMesh->mFaces[i].mNumIndices = 3;
  580. unsigned int iTemp = iCurrent;
  581. for (unsigned int c = 0; c < 3; ++c, ++iCurrent) {
  582. // read vertices
  583. unsigned int iIndex = pcTriangles->index_xyz[c];
  584. if (iIndex >= (unsigned int)pcHeader->num_verts) {
  585. iIndex = pcHeader->num_verts - 1;
  586. ASSIMP_LOG_WARN("Index overflow in MDLn vertex list");
  587. }
  588. aiVector3D &vec = pcMesh->mVertices[iCurrent];
  589. vec.x = (float)pcVertices[iIndex].v[0] * pcHeader->scale[0];
  590. vec.x += pcHeader->translate[0];
  591. vec.y = (float)pcVertices[iIndex].v[1] * pcHeader->scale[1];
  592. vec.y += pcHeader->translate[1];
  593. // vec.y *= -1.0f;
  594. vec.z = (float)pcVertices[iIndex].v[2] * pcHeader->scale[2];
  595. vec.z += pcHeader->translate[2];
  596. // read the normal vector from the precalculated normal table
  597. MD2::LookupNormalIndex(pcVertices[iIndex].normalIndex, pcMesh->mNormals[iCurrent]);
  598. // pcMesh->mNormals[iCurrent].y *= -1.0f;
  599. // read texture coordinates
  600. if (pcHeader->synctype) {
  601. ImportUVCoordinate_3DGS_MDL345(pcMesh->mTextureCoords[0][iCurrent],
  602. pcTexCoords, pcTriangles->index_uv[c]);
  603. }
  604. }
  605. pcMesh->mFaces[i].mIndices[0] = iTemp + 2;
  606. pcMesh->mFaces[i].mIndices[1] = iTemp + 1;
  607. pcMesh->mFaces[i].mIndices[2] = iTemp + 0;
  608. pcTriangles++;
  609. }
  610. }
  611. // short packed vertices
  612. /////////////////////////////////////////////////////////////////////////////////////
  613. else {
  614. // now get a pointer to the first frame in the file
  615. const MDL::SimpleFrame_MDLn_SP *pcFirstFrame = (const MDL::SimpleFrame_MDLn_SP *)(szCurrent + sizeof(uint32_t));
  616. // get a pointer to the vertices
  617. const MDL::Vertex_MDL4 *pcVertices = (const MDL::Vertex_MDL4 *)((pcFirstFrame->name) +
  618. sizeof(pcFirstFrame->name));
  619. VALIDATE_FILE_SIZE(pcVertices + pcHeader->num_verts);
  620. // now iterate through all triangles
  621. unsigned int iCurrent = 0;
  622. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_tris; ++i) {
  623. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  624. pcMesh->mFaces[i].mNumIndices = 3;
  625. unsigned int iTemp = iCurrent;
  626. for (unsigned int c = 0; c < 3; ++c, ++iCurrent) {
  627. // read vertices
  628. unsigned int iIndex = pcTriangles->index_xyz[c];
  629. if (iIndex >= (unsigned int)pcHeader->num_verts) {
  630. iIndex = pcHeader->num_verts - 1;
  631. ASSIMP_LOG_WARN("Index overflow in MDLn vertex list");
  632. }
  633. aiVector3D &vec = pcMesh->mVertices[iCurrent];
  634. vec.x = (float)pcVertices[iIndex].v[0] * pcHeader->scale[0];
  635. vec.x += pcHeader->translate[0];
  636. vec.y = (float)pcVertices[iIndex].v[1] * pcHeader->scale[1];
  637. vec.y += pcHeader->translate[1];
  638. // vec.y *= -1.0f;
  639. vec.z = (float)pcVertices[iIndex].v[2] * pcHeader->scale[2];
  640. vec.z += pcHeader->translate[2];
  641. // read the normal vector from the precalculated normal table
  642. MD2::LookupNormalIndex(pcVertices[iIndex].normalIndex, pcMesh->mNormals[iCurrent]);
  643. // pcMesh->mNormals[iCurrent].y *= -1.0f;
  644. // read texture coordinates
  645. if (pcHeader->synctype) {
  646. ImportUVCoordinate_3DGS_MDL345(pcMesh->mTextureCoords[0][iCurrent],
  647. pcTexCoords, pcTriangles->index_uv[c]);
  648. }
  649. }
  650. pcMesh->mFaces[i].mIndices[0] = iTemp + 2;
  651. pcMesh->mFaces[i].mIndices[1] = iTemp + 1;
  652. pcMesh->mFaces[i].mIndices[2] = iTemp + 0;
  653. pcTriangles++;
  654. }
  655. }
  656. // For MDL5 we will need to build valid texture coordinates
  657. // basing upon the file loaded (only support one file as skin)
  658. if (0x5 == iGSFileVersion)
  659. CalculateUVCoordinates_MDL5();
  660. return;
  661. }
  662. // ------------------------------------------------------------------------------------------------
  663. // Get a single UV coordinate for Quake and older GameStudio files
  664. void MDLImporter::ImportUVCoordinate_3DGS_MDL345(
  665. aiVector3D &vOut,
  666. const MDL::TexCoord_MDL3 *pcSrc,
  667. unsigned int iIndex) {
  668. ai_assert(nullptr != pcSrc);
  669. const MDL::Header *const pcHeader = (const MDL::Header *)this->mBuffer;
  670. // validate UV indices
  671. if (iIndex >= (unsigned int)pcHeader->synctype) {
  672. iIndex = pcHeader->synctype - 1;
  673. ASSIMP_LOG_WARN("Index overflow in MDLn UV coord list");
  674. }
  675. float s = (float)pcSrc[iIndex].u;
  676. float t = (float)pcSrc[iIndex].v;
  677. // Scale s and t to range from 0.0 to 1.0
  678. if (0x5 != iGSFileVersion) {
  679. s = (s + 0.5f) / pcHeader->skinwidth;
  680. t = 1.0f - (t + 0.5f) / pcHeader->skinheight;
  681. }
  682. vOut.x = s;
  683. vOut.y = t;
  684. vOut.z = 0.0f;
  685. }
  686. // ------------------------------------------------------------------------------------------------
  687. // Compute UV coordinates for a MDL5 file
  688. void MDLImporter::CalculateUVCoordinates_MDL5() {
  689. const MDL::Header *const pcHeader = (const MDL::Header *)this->mBuffer;
  690. if (pcHeader->num_skins && this->pScene->mNumTextures) {
  691. const aiTexture *pcTex = this->pScene->mTextures[0];
  692. // if the file is loaded in DDS format: get the size of the
  693. // texture from the header of the DDS file
  694. // skip three DWORDs and read first height, then the width
  695. unsigned int iWidth, iHeight;
  696. if (!pcTex->mHeight) {
  697. const uint32_t *piPtr = (uint32_t *)pcTex->pcData;
  698. piPtr += 3;
  699. iHeight = (unsigned int)*piPtr++;
  700. iWidth = (unsigned int)*piPtr;
  701. if (!iHeight || !iWidth) {
  702. ASSIMP_LOG_WARN("Either the width or the height of the "
  703. "embedded DDS texture is zero. Unable to compute final texture "
  704. "coordinates. The texture coordinates remain in their original "
  705. "0-x/0-y (x,y = texture size) range.");
  706. iWidth = 1;
  707. iHeight = 1;
  708. }
  709. } else {
  710. iWidth = pcTex->mWidth;
  711. iHeight = pcTex->mHeight;
  712. }
  713. if (1 != iWidth || 1 != iHeight) {
  714. const float fWidth = (float)iWidth;
  715. const float fHeight = (float)iHeight;
  716. aiMesh *pcMesh = this->pScene->mMeshes[0];
  717. for (unsigned int i = 0; i < pcMesh->mNumVertices; ++i) {
  718. pcMesh->mTextureCoords[0][i].x /= fWidth;
  719. pcMesh->mTextureCoords[0][i].y /= fHeight;
  720. pcMesh->mTextureCoords[0][i].y = 1.0f - pcMesh->mTextureCoords[0][i].y; // DX to OGL
  721. }
  722. }
  723. }
  724. }
  725. // ------------------------------------------------------------------------------------------------
  726. // Validate the header of a MDL7 file
  727. void MDLImporter::ValidateHeader_3DGS_MDL7(const MDL::Header_MDL7 *pcHeader) {
  728. ai_assert(nullptr != pcHeader);
  729. // There are some fixed sizes ...
  730. if (sizeof(MDL::ColorValue_MDL7) != pcHeader->colorvalue_stc_size) {
  731. throw DeadlyImportError(
  732. "[3DGS MDL7] sizeof(MDL::ColorValue_MDL7) != pcHeader->colorvalue_stc_size");
  733. }
  734. if (sizeof(MDL::TexCoord_MDL7) != pcHeader->skinpoint_stc_size) {
  735. throw DeadlyImportError(
  736. "[3DGS MDL7] sizeof(MDL::TexCoord_MDL7) != pcHeader->skinpoint_stc_size");
  737. }
  738. if (sizeof(MDL::Skin_MDL7) != pcHeader->skin_stc_size) {
  739. throw DeadlyImportError(
  740. "sizeof(MDL::Skin_MDL7) != pcHeader->skin_stc_size");
  741. }
  742. // if there are no groups ... how should we load such a file?
  743. if (!pcHeader->groups_num) {
  744. throw DeadlyImportError("[3DGS MDL7] No frames found");
  745. }
  746. }
  747. // ------------------------------------------------------------------------------------------------
  748. // resolve bone animation matrices
  749. void MDLImporter::CalcAbsBoneMatrices_3DGS_MDL7(MDL::IntBone_MDL7 **apcOutBones) {
  750. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  751. const MDL::Bone_MDL7 *pcBones = (const MDL::Bone_MDL7 *)(pcHeader + 1);
  752. ai_assert(nullptr != apcOutBones);
  753. // first find the bone that has NO parent, calculate the
  754. // animation matrix for it, then go on and search for the next parent
  755. // index (0) and so on until we can't find a new node.
  756. uint16_t iParent = 0xffff;
  757. uint32_t iIterations = 0;
  758. while (iIterations++ < pcHeader->bones_num) {
  759. for (uint32_t iBone = 0; iBone < pcHeader->bones_num; ++iBone) {
  760. BE_NCONST MDL::Bone_MDL7 *pcBone = _AI_MDL7_ACCESS_PTR(pcBones, iBone,
  761. pcHeader->bone_stc_size, MDL::Bone_MDL7);
  762. AI_SWAP2(pcBone->parent_index);
  763. AI_SWAP4(pcBone->x);
  764. AI_SWAP4(pcBone->y);
  765. AI_SWAP4(pcBone->z);
  766. if (iParent == pcBone->parent_index) {
  767. // MDL7 readme
  768. ////////////////////////////////////////////////////////////////
  769. /*
  770. The animation matrix is then calculated the following way:
  771. vector3 bPos = <absolute bone position>
  772. matrix44 laM; // local animation matrix
  773. sphrvector key_rotate = <bone rotation>
  774. matrix44 m1,m2;
  775. create_trans_matrix(m1, -bPos.x, -bPos.y, -bPos.z);
  776. create_trans_matrix(m2, -bPos.x, -bPos.y, -bPos.z);
  777. create_rotation_matrix(laM,key_rotate);
  778. laM = sm1 * laM;
  779. laM = laM * sm2;
  780. */
  781. /////////////////////////////////////////////////////////////////
  782. MDL::IntBone_MDL7 *const pcOutBone = apcOutBones[iBone];
  783. // store the parent index of the bone
  784. pcOutBone->iParent = pcBone->parent_index;
  785. if (0xffff != iParent) {
  786. const MDL::IntBone_MDL7 *pcParentBone = apcOutBones[iParent];
  787. pcOutBone->mOffsetMatrix.a4 = -pcParentBone->vPosition.x;
  788. pcOutBone->mOffsetMatrix.b4 = -pcParentBone->vPosition.y;
  789. pcOutBone->mOffsetMatrix.c4 = -pcParentBone->vPosition.z;
  790. }
  791. pcOutBone->vPosition.x = pcBone->x;
  792. pcOutBone->vPosition.y = pcBone->y;
  793. pcOutBone->vPosition.z = pcBone->z;
  794. pcOutBone->mOffsetMatrix.a4 -= pcBone->x;
  795. pcOutBone->mOffsetMatrix.b4 -= pcBone->y;
  796. pcOutBone->mOffsetMatrix.c4 -= pcBone->z;
  797. if (AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_NOT_THERE == pcHeader->bone_stc_size) {
  798. // no real name for our poor bone is specified :-(
  799. pcOutBone->mName.length = ai_snprintf(pcOutBone->mName.data, MAXLEN,
  800. "UnnamedBone_%i", iBone);
  801. } else {
  802. // Make sure we won't run over the buffer's end if there is no
  803. // terminal 0 character (however the documentation says there
  804. // should be one)
  805. uint32_t iMaxLen = pcHeader->bone_stc_size - 16;
  806. for (uint32_t qq = 0; qq < iMaxLen; ++qq) {
  807. if (!pcBone->name[qq]) {
  808. iMaxLen = qq;
  809. break;
  810. }
  811. }
  812. // store the name of the bone
  813. pcOutBone->mName.length = (size_t)iMaxLen;
  814. ::memcpy(pcOutBone->mName.data, pcBone->name, pcOutBone->mName.length);
  815. pcOutBone->mName.data[pcOutBone->mName.length] = '\0';
  816. }
  817. }
  818. }
  819. ++iParent;
  820. }
  821. }
  822. // ------------------------------------------------------------------------------------------------
  823. // read bones from a MDL7 file
  824. MDL::IntBone_MDL7 **MDLImporter::LoadBones_3DGS_MDL7() {
  825. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  826. if (pcHeader->bones_num) {
  827. // validate the size of the bone data structure in the file
  828. if (AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_20_CHARS != pcHeader->bone_stc_size &&
  829. AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_32_CHARS != pcHeader->bone_stc_size &&
  830. AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_NOT_THERE != pcHeader->bone_stc_size) {
  831. ASSIMP_LOG_WARN("Unknown size of bone data structure");
  832. return nullptr;
  833. }
  834. MDL::IntBone_MDL7 **apcBonesOut = new MDL::IntBone_MDL7 *[pcHeader->bones_num];
  835. for (uint32_t crank = 0; crank < pcHeader->bones_num; ++crank)
  836. apcBonesOut[crank] = new MDL::IntBone_MDL7();
  837. // and calculate absolute bone offset matrices ...
  838. CalcAbsBoneMatrices_3DGS_MDL7(apcBonesOut);
  839. return apcBonesOut;
  840. }
  841. return nullptr;
  842. }
  843. // ------------------------------------------------------------------------------------------------
  844. // read faces from a MDL7 file
  845. void MDLImporter::ReadFaces_3DGS_MDL7(const MDL::IntGroupInfo_MDL7 &groupInfo,
  846. MDL::IntGroupData_MDL7 &groupData) {
  847. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  848. MDL::Triangle_MDL7 *pcGroupTris = groupInfo.pcGroupTris;
  849. // iterate through all triangles and build valid display lists
  850. unsigned int iOutIndex = 0;
  851. for (unsigned int iTriangle = 0; iTriangle < (unsigned int)groupInfo.pcGroup->numtris; ++iTriangle) {
  852. AI_SWAP2(pcGroupTris->v_index[0]);
  853. AI_SWAP2(pcGroupTris->v_index[1]);
  854. AI_SWAP2(pcGroupTris->v_index[2]);
  855. // iterate through all indices of the current triangle
  856. for (unsigned int c = 0; c < 3; ++c, ++iOutIndex) {
  857. // validate the vertex index
  858. unsigned int iIndex = pcGroupTris->v_index[c];
  859. if (iIndex > (unsigned int)groupInfo.pcGroup->numverts) {
  860. // (we might need to read this section a second time - to process frame vertices correctly)
  861. pcGroupTris->v_index[c] = (uint16_t)(iIndex = groupInfo.pcGroup->numverts - 1);
  862. ASSIMP_LOG_WARN("Index overflow in MDL7 vertex list");
  863. }
  864. // write the output face index
  865. groupData.pcFaces[iTriangle].mIndices[2 - c] = iOutIndex;
  866. aiVector3D &vPosition = groupData.vPositions[iOutIndex];
  867. vPosition.x = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).x;
  868. vPosition.y = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).y;
  869. vPosition.z = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).z;
  870. // if we have bones, save the index
  871. if (!groupData.aiBones.empty()) {
  872. groupData.aiBones[iOutIndex] = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts,
  873. iIndex, pcHeader->mainvertex_stc_size)
  874. .vertindex;
  875. }
  876. // now read the normal vector
  877. if (AI_MDL7_FRAMEVERTEX030305_STCSIZE <= pcHeader->mainvertex_stc_size) {
  878. // read the full normal vector
  879. aiVector3D &vNormal = groupData.vNormals[iOutIndex];
  880. vNormal.x = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).norm[0];
  881. AI_SWAP4(vNormal.x);
  882. vNormal.y = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).norm[1];
  883. AI_SWAP4(vNormal.y);
  884. vNormal.z = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).norm[2];
  885. AI_SWAP4(vNormal.z);
  886. } else if (AI_MDL7_FRAMEVERTEX120503_STCSIZE <= pcHeader->mainvertex_stc_size) {
  887. // read the normal vector from Quake2's smart table
  888. aiVector3D &vNormal = groupData.vNormals[iOutIndex];
  889. MD2::LookupNormalIndex(_AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex,
  890. pcHeader->mainvertex_stc_size)
  891. .norm162index,
  892. vNormal);
  893. }
  894. // validate and process the first uv coordinate set
  895. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_ONE_UV) {
  896. if (groupInfo.pcGroup->num_stpts) {
  897. AI_SWAP2(pcGroupTris->skinsets[0].st_index[0]);
  898. AI_SWAP2(pcGroupTris->skinsets[0].st_index[1]);
  899. AI_SWAP2(pcGroupTris->skinsets[0].st_index[2]);
  900. iIndex = pcGroupTris->skinsets[0].st_index[c];
  901. if (iIndex > (unsigned int)groupInfo.pcGroup->num_stpts) {
  902. iIndex = groupInfo.pcGroup->num_stpts - 1;
  903. ASSIMP_LOG_WARN("Index overflow in MDL7 UV coordinate list (#1)");
  904. }
  905. float u = groupInfo.pcGroupUVs[iIndex].u;
  906. float v = 1.0f - groupInfo.pcGroupUVs[iIndex].v; // DX to OGL
  907. groupData.vTextureCoords1[iOutIndex].x = u;
  908. groupData.vTextureCoords1[iOutIndex].y = v;
  909. }
  910. // assign the material index, but only if it is existing
  911. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_ONE_UV_WITH_MATINDEX) {
  912. AI_SWAP4(pcGroupTris->skinsets[0].material);
  913. groupData.pcFaces[iTriangle].iMatIndex[0] = pcGroupTris->skinsets[0].material;
  914. }
  915. }
  916. // validate and process the second uv coordinate set
  917. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_TWO_UV) {
  918. if (groupInfo.pcGroup->num_stpts) {
  919. AI_SWAP2(pcGroupTris->skinsets[1].st_index[0]);
  920. AI_SWAP2(pcGroupTris->skinsets[1].st_index[1]);
  921. AI_SWAP2(pcGroupTris->skinsets[1].st_index[2]);
  922. AI_SWAP4(pcGroupTris->skinsets[1].material);
  923. iIndex = pcGroupTris->skinsets[1].st_index[c];
  924. if (iIndex > (unsigned int)groupInfo.pcGroup->num_stpts) {
  925. iIndex = groupInfo.pcGroup->num_stpts - 1;
  926. ASSIMP_LOG_WARN("Index overflow in MDL7 UV coordinate list (#2)");
  927. }
  928. float u = groupInfo.pcGroupUVs[iIndex].u;
  929. float v = 1.0f - groupInfo.pcGroupUVs[iIndex].v;
  930. groupData.vTextureCoords2[iOutIndex].x = u;
  931. groupData.vTextureCoords2[iOutIndex].y = v; // DX to OGL
  932. // check whether we do really need the second texture
  933. // coordinate set ... wastes memory and loading time
  934. if (0 != iIndex && (u != groupData.vTextureCoords1[iOutIndex].x ||
  935. v != groupData.vTextureCoords1[iOutIndex].y))
  936. groupData.bNeed2UV = true;
  937. // if the material differs, we need a second skin, too
  938. if (pcGroupTris->skinsets[1].material != pcGroupTris->skinsets[0].material)
  939. groupData.bNeed2UV = true;
  940. }
  941. // assign the material index
  942. groupData.pcFaces[iTriangle].iMatIndex[1] = pcGroupTris->skinsets[1].material;
  943. }
  944. }
  945. // get the next triangle in the list
  946. pcGroupTris = (MDL::Triangle_MDL7 *)((const char *)pcGroupTris + pcHeader->triangle_stc_size);
  947. }
  948. }
  949. // ------------------------------------------------------------------------------------------------
  950. // handle frames in a MDL7 file
  951. bool MDLImporter::ProcessFrames_3DGS_MDL7(const MDL::IntGroupInfo_MDL7 &groupInfo,
  952. MDL::IntGroupData_MDL7 &groupData,
  953. MDL::IntSharedData_MDL7 &shared,
  954. const unsigned char *szCurrent,
  955. const unsigned char **szCurrentOut) {
  956. ai_assert(nullptr != szCurrent);
  957. ai_assert(nullptr != szCurrentOut);
  958. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)mBuffer;
  959. // if we have no bones we can simply skip all frames,
  960. // otherwise we'll need to process them.
  961. // FIX: If we need another frame than the first we must apply frame vertex replacements ...
  962. for (unsigned int iFrame = 0; iFrame < (unsigned int)groupInfo.pcGroup->numframes; ++iFrame) {
  963. MDL::IntFrameInfo_MDL7 frame((BE_NCONST MDL::Frame_MDL7 *)szCurrent, iFrame);
  964. AI_SWAP4(frame.pcFrame->vertices_count);
  965. AI_SWAP4(frame.pcFrame->transmatrix_count);
  966. const unsigned int iAdd = pcHeader->frame_stc_size +
  967. frame.pcFrame->vertices_count * pcHeader->framevertex_stc_size +
  968. frame.pcFrame->transmatrix_count * pcHeader->bonetrans_stc_size;
  969. if (((const char *)szCurrent - (const char *)pcHeader) + iAdd > (unsigned int)pcHeader->data_size) {
  970. ASSIMP_LOG_WARN("Index overflow in frame area. "
  971. "Ignoring all frames and all further mesh groups, too.");
  972. // don't parse more groups if we can't even read one
  973. // FIXME: sometimes this seems to occur even for valid files ...
  974. *szCurrentOut = szCurrent;
  975. return false;
  976. }
  977. // our output frame?
  978. if (configFrameID == iFrame) {
  979. BE_NCONST MDL::Vertex_MDL7 *pcFrameVertices = (BE_NCONST MDL::Vertex_MDL7 *)(szCurrent + pcHeader->frame_stc_size);
  980. for (unsigned int qq = 0; qq < frame.pcFrame->vertices_count; ++qq) {
  981. // I assume this are simple replacements for normal vertices, the bone index serving
  982. // as the index of the vertex to be replaced.
  983. uint16_t iIndex = _AI_MDL7_ACCESS(pcFrameVertices, qq, pcHeader->framevertex_stc_size, MDL::Vertex_MDL7).vertindex;
  984. AI_SWAP2(iIndex);
  985. if (iIndex >= groupInfo.pcGroup->numverts) {
  986. ASSIMP_LOG_WARN("Invalid vertex index in frame vertex section");
  987. continue;
  988. }
  989. aiVector3D vPosition, vNormal;
  990. vPosition.x = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).x;
  991. AI_SWAP4(vPosition.x);
  992. vPosition.y = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).y;
  993. AI_SWAP4(vPosition.y);
  994. vPosition.z = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).z;
  995. AI_SWAP4(vPosition.z);
  996. // now read the normal vector
  997. if (AI_MDL7_FRAMEVERTEX030305_STCSIZE <= pcHeader->mainvertex_stc_size) {
  998. // read the full normal vector
  999. vNormal.x = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).norm[0];
  1000. AI_SWAP4(vNormal.x);
  1001. vNormal.y = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).norm[1];
  1002. AI_SWAP4(vNormal.y);
  1003. vNormal.z = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).norm[2];
  1004. AI_SWAP4(vNormal.z);
  1005. } else if (AI_MDL7_FRAMEVERTEX120503_STCSIZE <= pcHeader->mainvertex_stc_size) {
  1006. // read the normal vector from Quake2's smart table
  1007. MD2::LookupNormalIndex(_AI_MDL7_ACCESS_VERT(pcFrameVertices, qq,
  1008. pcHeader->framevertex_stc_size)
  1009. .norm162index,
  1010. vNormal);
  1011. }
  1012. // FIXME: O(n^2) at the moment ...
  1013. BE_NCONST MDL::Triangle_MDL7 *pcGroupTris = groupInfo.pcGroupTris;
  1014. unsigned int iOutIndex = 0;
  1015. for (unsigned int iTriangle = 0; iTriangle < (unsigned int)groupInfo.pcGroup->numtris; ++iTriangle) {
  1016. // iterate through all indices of the current triangle
  1017. for (unsigned int c = 0; c < 3; ++c, ++iOutIndex) {
  1018. // replace the vertex with the new data
  1019. const unsigned int iCurIndex = pcGroupTris->v_index[c];
  1020. if (iCurIndex == iIndex) {
  1021. groupData.vPositions[iOutIndex] = vPosition;
  1022. groupData.vNormals[iOutIndex] = vNormal;
  1023. }
  1024. }
  1025. // get the next triangle in the list
  1026. pcGroupTris = (BE_NCONST MDL::Triangle_MDL7 *)((const char *)
  1027. pcGroupTris +
  1028. pcHeader->triangle_stc_size);
  1029. }
  1030. }
  1031. }
  1032. // parse bone trafo matrix keys (only if there are bones ...)
  1033. if (shared.apcOutBones) {
  1034. ParseBoneTrafoKeys_3DGS_MDL7(groupInfo, frame, shared);
  1035. }
  1036. szCurrent += iAdd;
  1037. }
  1038. *szCurrentOut = szCurrent;
  1039. return true;
  1040. }
  1041. // ------------------------------------------------------------------------------------------------
  1042. // Sort faces by material, handle multiple UVs correctly
  1043. void MDLImporter::SortByMaterials_3DGS_MDL7(
  1044. const MDL::IntGroupInfo_MDL7 &groupInfo,
  1045. MDL::IntGroupData_MDL7 &groupData,
  1046. MDL::IntSplitGroupData_MDL7 &splitGroupData) {
  1047. const unsigned int iNumMaterials = (unsigned int)splitGroupData.shared.pcMats.size();
  1048. if (!groupData.bNeed2UV) {
  1049. // if we don't need a second set of texture coordinates there is no reason to keep it in memory ...
  1050. groupData.vTextureCoords2.clear();
  1051. // allocate the array
  1052. splitGroupData.aiSplit = new std::vector<unsigned int> *[iNumMaterials];
  1053. for (unsigned int m = 0; m < iNumMaterials; ++m)
  1054. splitGroupData.aiSplit[m] = new std::vector<unsigned int>();
  1055. // iterate through all faces and sort by material
  1056. for (unsigned int iFace = 0; iFace < (unsigned int)groupInfo.pcGroup->numtris; ++iFace) {
  1057. // check range
  1058. if (groupData.pcFaces[iFace].iMatIndex[0] >= iNumMaterials) {
  1059. // use the last material instead
  1060. splitGroupData.aiSplit[iNumMaterials - 1]->push_back(iFace);
  1061. // sometimes MED writes -1, but normally only if there is only
  1062. // one skin assigned. No warning in this case
  1063. if (0xFFFFFFFF != groupData.pcFaces[iFace].iMatIndex[0])
  1064. ASSIMP_LOG_WARN("Index overflow in MDL7 material list [#0]");
  1065. } else
  1066. splitGroupData.aiSplit[groupData.pcFaces[iFace].iMatIndex[0]]->push_back(iFace);
  1067. }
  1068. } else {
  1069. // we need to build combined materials for each combination of
  1070. std::vector<MDL::IntMaterial_MDL7> avMats;
  1071. avMats.reserve(iNumMaterials * 2);
  1072. // fixme: why on the heap?
  1073. std::vector<std::vector<unsigned int> *> aiTempSplit(iNumMaterials * 2);
  1074. for (unsigned int m = 0; m < iNumMaterials; ++m)
  1075. aiTempSplit[m] = new std::vector<unsigned int>();
  1076. // iterate through all faces and sort by material
  1077. for (unsigned int iFace = 0; iFace < (unsigned int)groupInfo.pcGroup->numtris; ++iFace) {
  1078. // check range
  1079. unsigned int iMatIndex = groupData.pcFaces[iFace].iMatIndex[0];
  1080. if (iMatIndex >= iNumMaterials) {
  1081. // sometimes MED writes -1, but normally only if there is only
  1082. // one skin assigned. No warning in this case
  1083. if (UINT_MAX != iMatIndex)
  1084. ASSIMP_LOG_WARN("Index overflow in MDL7 material list [#1]");
  1085. iMatIndex = iNumMaterials - 1;
  1086. }
  1087. unsigned int iMatIndex2 = groupData.pcFaces[iFace].iMatIndex[1];
  1088. unsigned int iNum = iMatIndex;
  1089. if (UINT_MAX != iMatIndex2 && iMatIndex != iMatIndex2) {
  1090. if (iMatIndex2 >= iNumMaterials) {
  1091. // sometimes MED writes -1, but normally only if there is only
  1092. // one skin assigned. No warning in this case
  1093. ASSIMP_LOG_WARN("Index overflow in MDL7 material list [#2]");
  1094. iMatIndex2 = iNumMaterials - 1;
  1095. }
  1096. // do a slow search in the list ...
  1097. iNum = 0;
  1098. bool bFound = false;
  1099. for (std::vector<MDL::IntMaterial_MDL7>::iterator i = avMats.begin(); i != avMats.end(); ++i, ++iNum) {
  1100. if ((*i).iOldMatIndices[0] == iMatIndex && (*i).iOldMatIndices[1] == iMatIndex2) {
  1101. // reuse this material
  1102. bFound = true;
  1103. break;
  1104. }
  1105. }
  1106. if (!bFound) {
  1107. // build a new material ...
  1108. MDL::IntMaterial_MDL7 sHelper;
  1109. sHelper.pcMat = new aiMaterial();
  1110. sHelper.iOldMatIndices[0] = iMatIndex;
  1111. sHelper.iOldMatIndices[1] = iMatIndex2;
  1112. JoinSkins_3DGS_MDL7(splitGroupData.shared.pcMats[iMatIndex],
  1113. splitGroupData.shared.pcMats[iMatIndex2], sHelper.pcMat);
  1114. // and add it to the list
  1115. avMats.push_back(sHelper);
  1116. iNum = (unsigned int)avMats.size() - 1;
  1117. }
  1118. // adjust the size of the file array
  1119. if (iNum == aiTempSplit.size()) {
  1120. aiTempSplit.push_back(new std::vector<unsigned int>());
  1121. }
  1122. }
  1123. aiTempSplit[iNum]->push_back(iFace);
  1124. }
  1125. // now add the newly created materials to the old list
  1126. if (0 == groupInfo.iIndex) {
  1127. splitGroupData.shared.pcMats.resize(avMats.size());
  1128. for (unsigned int o = 0; o < avMats.size(); ++o)
  1129. splitGroupData.shared.pcMats[o] = avMats[o].pcMat;
  1130. } else {
  1131. // This might result in redundant materials ...
  1132. splitGroupData.shared.pcMats.resize(iNumMaterials + avMats.size());
  1133. for (unsigned int o = iNumMaterials; o < avMats.size(); ++o)
  1134. splitGroupData.shared.pcMats[o] = avMats[o].pcMat;
  1135. }
  1136. // and build the final face-to-material array
  1137. splitGroupData.aiSplit = new std::vector<unsigned int> *[aiTempSplit.size()];
  1138. for (unsigned int m = 0; m < iNumMaterials; ++m)
  1139. splitGroupData.aiSplit[m] = aiTempSplit[m];
  1140. }
  1141. }
  1142. // ------------------------------------------------------------------------------------------------
  1143. // Read a MDL7 file
  1144. void MDLImporter::InternReadFile_3DGS_MDL7() {
  1145. ai_assert(nullptr != pScene);
  1146. MDL::IntSharedData_MDL7 sharedData;
  1147. // current cursor position in the file
  1148. BE_NCONST MDL::Header_MDL7 *pcHeader = (BE_NCONST MDL::Header_MDL7 *)this->mBuffer;
  1149. const unsigned char *szCurrent = (const unsigned char *)(pcHeader + 1);
  1150. AI_SWAP4(pcHeader->version);
  1151. AI_SWAP4(pcHeader->bones_num);
  1152. AI_SWAP4(pcHeader->groups_num);
  1153. AI_SWAP4(pcHeader->data_size);
  1154. AI_SWAP4(pcHeader->entlump_size);
  1155. AI_SWAP4(pcHeader->medlump_size);
  1156. AI_SWAP2(pcHeader->bone_stc_size);
  1157. AI_SWAP2(pcHeader->skin_stc_size);
  1158. AI_SWAP2(pcHeader->colorvalue_stc_size);
  1159. AI_SWAP2(pcHeader->material_stc_size);
  1160. AI_SWAP2(pcHeader->skinpoint_stc_size);
  1161. AI_SWAP2(pcHeader->triangle_stc_size);
  1162. AI_SWAP2(pcHeader->mainvertex_stc_size);
  1163. AI_SWAP2(pcHeader->framevertex_stc_size);
  1164. AI_SWAP2(pcHeader->bonetrans_stc_size);
  1165. AI_SWAP2(pcHeader->frame_stc_size);
  1166. // validate the header of the file. There are some structure
  1167. // sizes that are expected by the loader to be constant
  1168. this->ValidateHeader_3DGS_MDL7(pcHeader);
  1169. // load all bones (they are shared by all groups, so
  1170. // we'll need to add them to all groups/meshes later)
  1171. // apcBonesOut is a list of all bones or nullptr if they could not been loaded
  1172. szCurrent += pcHeader->bones_num * pcHeader->bone_stc_size;
  1173. sharedData.apcOutBones = this->LoadBones_3DGS_MDL7();
  1174. // vector to held all created meshes
  1175. std::vector<aiMesh *> *avOutList;
  1176. // 3 meshes per group - that should be OK for most models
  1177. avOutList = new std::vector<aiMesh *>[pcHeader->groups_num];
  1178. for (uint32_t i = 0; i < pcHeader->groups_num; ++i)
  1179. avOutList[i].reserve(3);
  1180. // buffer to held the names of all groups in the file
  1181. const size_t buffersize(AI_MDL7_MAX_GROUPNAMESIZE * pcHeader->groups_num);
  1182. char *aszGroupNameBuffer = new char[buffersize];
  1183. // read all groups
  1184. for (unsigned int iGroup = 0; iGroup < (unsigned int)pcHeader->groups_num; ++iGroup) {
  1185. MDL::IntGroupInfo_MDL7 groupInfo((BE_NCONST MDL::Group_MDL7 *)szCurrent, iGroup);
  1186. szCurrent = (const unsigned char *)(groupInfo.pcGroup + 1);
  1187. VALIDATE_FILE_SIZE(szCurrent);
  1188. AI_SWAP4(groupInfo.pcGroup->groupdata_size);
  1189. AI_SWAP4(groupInfo.pcGroup->numskins);
  1190. AI_SWAP4(groupInfo.pcGroup->num_stpts);
  1191. AI_SWAP4(groupInfo.pcGroup->numtris);
  1192. AI_SWAP4(groupInfo.pcGroup->numverts);
  1193. AI_SWAP4(groupInfo.pcGroup->numframes);
  1194. if (1 != groupInfo.pcGroup->typ) {
  1195. // Not a triangle-based mesh
  1196. ASSIMP_LOG_WARN("[3DGS MDL7] Not a triangle mesh group. Continuing happily");
  1197. }
  1198. // store the name of the group
  1199. const unsigned int ofs = iGroup * AI_MDL7_MAX_GROUPNAMESIZE;
  1200. ::memcpy(&aszGroupNameBuffer[ofs],
  1201. groupInfo.pcGroup->name, AI_MDL7_MAX_GROUPNAMESIZE);
  1202. // make sure '\0' is at the end
  1203. aszGroupNameBuffer[ofs + AI_MDL7_MAX_GROUPNAMESIZE - 1] = '\0';
  1204. // read all skins
  1205. sharedData.pcMats.reserve(sharedData.pcMats.size() + groupInfo.pcGroup->numskins);
  1206. sharedData.abNeedMaterials.resize(sharedData.abNeedMaterials.size() +
  1207. groupInfo.pcGroup->numskins,
  1208. false);
  1209. for (unsigned int iSkin = 0; iSkin < (unsigned int)groupInfo.pcGroup->numskins; ++iSkin) {
  1210. ParseSkinLump_3DGS_MDL7(szCurrent, &szCurrent, sharedData.pcMats);
  1211. }
  1212. // if we have absolutely no skin loaded we need to generate a default material
  1213. if (sharedData.pcMats.empty()) {
  1214. const int iMode = (int)aiShadingMode_Gouraud;
  1215. sharedData.pcMats.push_back(new aiMaterial());
  1216. aiMaterial *pcHelper = (aiMaterial *)sharedData.pcMats[0];
  1217. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  1218. aiColor3D clr;
  1219. clr.b = clr.g = clr.r = 0.6f;
  1220. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  1221. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_SPECULAR);
  1222. clr.b = clr.g = clr.r = 0.05f;
  1223. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_AMBIENT);
  1224. aiString szName;
  1225. szName.Set(AI_DEFAULT_MATERIAL_NAME);
  1226. pcHelper->AddProperty(&szName, AI_MATKEY_NAME);
  1227. sharedData.abNeedMaterials.resize(1, false);
  1228. }
  1229. // now get a pointer to all texture coords in the group
  1230. groupInfo.pcGroupUVs = (BE_NCONST MDL::TexCoord_MDL7 *)szCurrent;
  1231. for (int i = 0; i < groupInfo.pcGroup->num_stpts; ++i) {
  1232. AI_SWAP4(groupInfo.pcGroupUVs[i].u);
  1233. AI_SWAP4(groupInfo.pcGroupUVs[i].v);
  1234. }
  1235. szCurrent += pcHeader->skinpoint_stc_size * groupInfo.pcGroup->num_stpts;
  1236. // now get a pointer to all triangle in the group
  1237. groupInfo.pcGroupTris = (Triangle_MDL7 *)szCurrent;
  1238. szCurrent += pcHeader->triangle_stc_size * groupInfo.pcGroup->numtris;
  1239. // now get a pointer to all vertices in the group
  1240. groupInfo.pcGroupVerts = (BE_NCONST MDL::Vertex_MDL7 *)szCurrent;
  1241. for (int i = 0; i < groupInfo.pcGroup->numverts; ++i) {
  1242. AI_SWAP4(groupInfo.pcGroupVerts[i].x);
  1243. AI_SWAP4(groupInfo.pcGroupVerts[i].y);
  1244. AI_SWAP4(groupInfo.pcGroupVerts[i].z);
  1245. AI_SWAP2(groupInfo.pcGroupVerts[i].vertindex);
  1246. //We can not swap the normal information now as we don't know which of the two kinds it is
  1247. }
  1248. szCurrent += pcHeader->mainvertex_stc_size * groupInfo.pcGroup->numverts;
  1249. VALIDATE_FILE_SIZE(szCurrent);
  1250. MDL::IntSplitGroupData_MDL7 splitGroupData(sharedData, avOutList[iGroup]);
  1251. MDL::IntGroupData_MDL7 groupData;
  1252. if (groupInfo.pcGroup->numtris && groupInfo.pcGroup->numverts) {
  1253. // build output vectors
  1254. const unsigned int iNumVertices = groupInfo.pcGroup->numtris * 3;
  1255. groupData.vPositions.resize(iNumVertices);
  1256. groupData.vNormals.resize(iNumVertices);
  1257. if (sharedData.apcOutBones) groupData.aiBones.resize(iNumVertices, UINT_MAX);
  1258. // it is also possible that there are 0 UV coordinate sets
  1259. if (groupInfo.pcGroup->num_stpts) {
  1260. groupData.vTextureCoords1.resize(iNumVertices, aiVector3D());
  1261. // check whether the triangle data structure is large enough
  1262. // to contain a second UV coordinate set
  1263. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_TWO_UV) {
  1264. groupData.vTextureCoords2.resize(iNumVertices, aiVector3D());
  1265. groupData.bNeed2UV = true;
  1266. }
  1267. }
  1268. groupData.pcFaces.resize(groupInfo.pcGroup->numtris);
  1269. // read all faces into the preallocated arrays
  1270. ReadFaces_3DGS_MDL7(groupInfo, groupData);
  1271. // sort by materials
  1272. SortByMaterials_3DGS_MDL7(groupInfo, groupData,
  1273. splitGroupData);
  1274. for (unsigned int qq = 0; qq < sharedData.pcMats.size(); ++qq) {
  1275. if (!splitGroupData.aiSplit[qq]->empty())
  1276. sharedData.abNeedMaterials[qq] = true;
  1277. }
  1278. } else
  1279. ASSIMP_LOG_WARN("[3DGS MDL7] Mesh group consists of 0 "
  1280. "vertices or faces. It will be skipped.");
  1281. // process all frames and generate output meshes
  1282. ProcessFrames_3DGS_MDL7(groupInfo, groupData, sharedData, szCurrent, &szCurrent);
  1283. GenerateOutputMeshes_3DGS_MDL7(groupData, splitGroupData);
  1284. }
  1285. // generate a nodegraph and subnodes for each group
  1286. pScene->mRootNode = new aiNode();
  1287. // now we need to build a final mesh list
  1288. for (uint32_t i = 0; i < pcHeader->groups_num; ++i)
  1289. pScene->mNumMeshes += (unsigned int)avOutList[i].size();
  1290. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  1291. {
  1292. unsigned int p = 0, q = 0;
  1293. for (uint32_t i = 0; i < pcHeader->groups_num; ++i) {
  1294. for (unsigned int a = 0; a < avOutList[i].size(); ++a) {
  1295. pScene->mMeshes[p++] = avOutList[i][a];
  1296. }
  1297. if (!avOutList[i].empty()) ++pScene->mRootNode->mNumChildren;
  1298. }
  1299. // we will later need an extra node to serve as parent for all bones
  1300. if (sharedData.apcOutBones) ++pScene->mRootNode->mNumChildren;
  1301. this->pScene->mRootNode->mChildren = new aiNode *[pScene->mRootNode->mNumChildren];
  1302. p = 0;
  1303. for (uint32_t i = 0; i < pcHeader->groups_num; ++i) {
  1304. if (avOutList[i].empty()) continue;
  1305. aiNode *const pcNode = pScene->mRootNode->mChildren[p] = new aiNode();
  1306. pcNode->mNumMeshes = (unsigned int)avOutList[i].size();
  1307. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  1308. pcNode->mParent = this->pScene->mRootNode;
  1309. for (unsigned int a = 0; a < pcNode->mNumMeshes; ++a)
  1310. pcNode->mMeshes[a] = q + a;
  1311. q += (unsigned int)avOutList[i].size();
  1312. // setup the name of the node
  1313. char *const szBuffer = &aszGroupNameBuffer[i * AI_MDL7_MAX_GROUPNAMESIZE];
  1314. if ('\0' == *szBuffer) {
  1315. const size_t maxSize(buffersize - (i * AI_MDL7_MAX_GROUPNAMESIZE));
  1316. pcNode->mName.length = ai_snprintf(szBuffer, maxSize, "Group_%u", p);
  1317. } else {
  1318. pcNode->mName.length = (ai_uint32)::strlen(szBuffer);
  1319. }
  1320. ::strncpy(pcNode->mName.data, szBuffer, MAXLEN - 1);
  1321. ++p;
  1322. }
  1323. }
  1324. // if there is only one root node with a single child we can optimize it a bit ...
  1325. if (1 == pScene->mRootNode->mNumChildren && !sharedData.apcOutBones) {
  1326. aiNode *pcOldRoot = this->pScene->mRootNode;
  1327. pScene->mRootNode = pcOldRoot->mChildren[0];
  1328. pcOldRoot->mChildren[0] = nullptr;
  1329. delete pcOldRoot;
  1330. pScene->mRootNode->mParent = nullptr;
  1331. } else
  1332. pScene->mRootNode->mName.Set("<mesh_root>");
  1333. delete[] avOutList;
  1334. delete[] aszGroupNameBuffer;
  1335. AI_DEBUG_INVALIDATE_PTR(avOutList);
  1336. AI_DEBUG_INVALIDATE_PTR(aszGroupNameBuffer);
  1337. // build a final material list.
  1338. CopyMaterials_3DGS_MDL7(sharedData);
  1339. HandleMaterialReferences_3DGS_MDL7();
  1340. // generate output bone animations and add all bones to the scenegraph
  1341. if (sharedData.apcOutBones) {
  1342. // this step adds empty dummy bones to the nodegraph
  1343. // insert another dummy node to avoid name conflicts
  1344. aiNode *const pc = pScene->mRootNode->mChildren[pScene->mRootNode->mNumChildren - 1] = new aiNode();
  1345. pc->mName.Set("<skeleton_root>");
  1346. // add bones to the nodegraph
  1347. AddBonesToNodeGraph_3DGS_MDL7((const Assimp::MDL::IntBone_MDL7 **)
  1348. sharedData.apcOutBones,
  1349. pc, 0xffff);
  1350. // this steps build a valid output animation
  1351. BuildOutputAnims_3DGS_MDL7((const Assimp::MDL::IntBone_MDL7 **)
  1352. sharedData.apcOutBones);
  1353. }
  1354. }
  1355. // ------------------------------------------------------------------------------------------------
  1356. // Copy materials
  1357. void MDLImporter::CopyMaterials_3DGS_MDL7(MDL::IntSharedData_MDL7 &shared) {
  1358. pScene->mNumMaterials = (unsigned int)shared.pcMats.size();
  1359. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  1360. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i)
  1361. pScene->mMaterials[i] = shared.pcMats[i];
  1362. }
  1363. // ------------------------------------------------------------------------------------------------
  1364. // Process material references
  1365. void MDLImporter::HandleMaterialReferences_3DGS_MDL7() {
  1366. // search for referrer materials
  1367. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
  1368. int iIndex = 0;
  1369. if (AI_SUCCESS == aiGetMaterialInteger(pScene->mMaterials[i], AI_MDL7_REFERRER_MATERIAL, &iIndex)) {
  1370. for (unsigned int a = 0; a < pScene->mNumMeshes; ++a) {
  1371. aiMesh *const pcMesh = pScene->mMeshes[a];
  1372. if (i == pcMesh->mMaterialIndex) {
  1373. pcMesh->mMaterialIndex = iIndex;
  1374. }
  1375. }
  1376. // collapse the rest of the array
  1377. delete pScene->mMaterials[i];
  1378. for (unsigned int pp = i; pp < pScene->mNumMaterials - 1; ++pp) {
  1379. pScene->mMaterials[pp] = pScene->mMaterials[pp + 1];
  1380. for (unsigned int a = 0; a < pScene->mNumMeshes; ++a) {
  1381. aiMesh *const pcMesh = pScene->mMeshes[a];
  1382. if (pcMesh->mMaterialIndex > i) --pcMesh->mMaterialIndex;
  1383. }
  1384. }
  1385. --pScene->mNumMaterials;
  1386. }
  1387. }
  1388. }
  1389. // ------------------------------------------------------------------------------------------------
  1390. // Read bone transformation keys
  1391. void MDLImporter::ParseBoneTrafoKeys_3DGS_MDL7(
  1392. const MDL::IntGroupInfo_MDL7 &groupInfo,
  1393. IntFrameInfo_MDL7 &frame,
  1394. MDL::IntSharedData_MDL7 &shared) {
  1395. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  1396. // only the first group contains bone animation keys
  1397. if (frame.pcFrame->transmatrix_count) {
  1398. if (!groupInfo.iIndex) {
  1399. // skip all frames vertices. We can't support them
  1400. const MDL::BoneTransform_MDL7 *pcBoneTransforms = (const MDL::BoneTransform_MDL7 *)(((const char *)frame.pcFrame) + pcHeader->frame_stc_size +
  1401. frame.pcFrame->vertices_count * pcHeader->framevertex_stc_size);
  1402. // read all transformation matrices
  1403. for (unsigned int iTrafo = 0; iTrafo < frame.pcFrame->transmatrix_count; ++iTrafo) {
  1404. if (pcBoneTransforms->bone_index >= pcHeader->bones_num) {
  1405. ASSIMP_LOG_WARN("Index overflow in frame area. "
  1406. "Unable to parse this bone transformation");
  1407. } else {
  1408. AddAnimationBoneTrafoKey_3DGS_MDL7(frame.iIndex,
  1409. pcBoneTransforms, shared.apcOutBones);
  1410. }
  1411. pcBoneTransforms = (const MDL::BoneTransform_MDL7 *)((const char *)pcBoneTransforms + pcHeader->bonetrans_stc_size);
  1412. }
  1413. } else {
  1414. ASSIMP_LOG_WARN("Ignoring animation keyframes in groups != 0");
  1415. }
  1416. }
  1417. }
  1418. // ------------------------------------------------------------------------------------------------
  1419. // Attach bones to the output nodegraph
  1420. void MDLImporter::AddBonesToNodeGraph_3DGS_MDL7(const MDL::IntBone_MDL7 **apcBones,
  1421. aiNode *pcParent, uint16_t iParentIndex) {
  1422. ai_assert(nullptr != apcBones);
  1423. ai_assert(nullptr != pcParent);
  1424. // get a pointer to the header ...
  1425. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  1426. const MDL::IntBone_MDL7 **apcBones2 = apcBones;
  1427. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1428. const MDL::IntBone_MDL7 *const pcBone = *apcBones2++;
  1429. if (pcBone->iParent == iParentIndex) {
  1430. ++pcParent->mNumChildren;
  1431. }
  1432. }
  1433. pcParent->mChildren = new aiNode *[pcParent->mNumChildren];
  1434. unsigned int qq = 0;
  1435. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1436. const MDL::IntBone_MDL7 *const pcBone = *apcBones++;
  1437. if (pcBone->iParent != iParentIndex) continue;
  1438. aiNode *pcNode = pcParent->mChildren[qq++] = new aiNode();
  1439. pcNode->mName = aiString(pcBone->mName);
  1440. AddBonesToNodeGraph_3DGS_MDL7(apcBones, pcNode, (uint16_t)i);
  1441. }
  1442. }
  1443. // ------------------------------------------------------------------------------------------------
  1444. // Build output animations
  1445. void MDLImporter::BuildOutputAnims_3DGS_MDL7(
  1446. const MDL::IntBone_MDL7 **apcBonesOut) {
  1447. ai_assert(nullptr != apcBonesOut);
  1448. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)mBuffer;
  1449. // one animation ...
  1450. aiAnimation *pcAnim = new aiAnimation();
  1451. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1452. if (!apcBonesOut[i]->pkeyPositions.empty()) {
  1453. // get the last frame ... (needn't be equal to pcHeader->frames_num)
  1454. for (size_t qq = 0; qq < apcBonesOut[i]->pkeyPositions.size(); ++qq) {
  1455. pcAnim->mDuration = std::max(pcAnim->mDuration, (double)
  1456. apcBonesOut[i]
  1457. ->pkeyPositions[qq]
  1458. .mTime);
  1459. }
  1460. ++pcAnim->mNumChannels;
  1461. }
  1462. }
  1463. if (pcAnim->mDuration) {
  1464. pcAnim->mChannels = new aiNodeAnim *[pcAnim->mNumChannels];
  1465. unsigned int iCnt = 0;
  1466. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1467. if (!apcBonesOut[i]->pkeyPositions.empty()) {
  1468. const MDL::IntBone_MDL7 *const intBone = apcBonesOut[i];
  1469. aiNodeAnim *const pcNodeAnim = pcAnim->mChannels[iCnt++] = new aiNodeAnim();
  1470. pcNodeAnim->mNodeName = aiString(intBone->mName);
  1471. // allocate enough storage for all keys
  1472. pcNodeAnim->mNumPositionKeys = (unsigned int)intBone->pkeyPositions.size();
  1473. pcNodeAnim->mNumScalingKeys = (unsigned int)intBone->pkeyPositions.size();
  1474. pcNodeAnim->mNumRotationKeys = (unsigned int)intBone->pkeyPositions.size();
  1475. pcNodeAnim->mPositionKeys = new aiVectorKey[pcNodeAnim->mNumPositionKeys];
  1476. pcNodeAnim->mScalingKeys = new aiVectorKey[pcNodeAnim->mNumPositionKeys];
  1477. pcNodeAnim->mRotationKeys = new aiQuatKey[pcNodeAnim->mNumPositionKeys];
  1478. // copy all keys
  1479. for (unsigned int qq = 0; qq < pcNodeAnim->mNumPositionKeys; ++qq) {
  1480. pcNodeAnim->mPositionKeys[qq] = intBone->pkeyPositions[qq];
  1481. pcNodeAnim->mScalingKeys[qq] = intBone->pkeyScalings[qq];
  1482. pcNodeAnim->mRotationKeys[qq] = intBone->pkeyRotations[qq];
  1483. }
  1484. }
  1485. }
  1486. // store the output animation
  1487. pScene->mNumAnimations = 1;
  1488. pScene->mAnimations = new aiAnimation *[1];
  1489. pScene->mAnimations[0] = pcAnim;
  1490. } else
  1491. delete pcAnim;
  1492. }
  1493. // ------------------------------------------------------------------------------------------------
  1494. void MDLImporter::AddAnimationBoneTrafoKey_3DGS_MDL7(unsigned int iTrafo,
  1495. const MDL::BoneTransform_MDL7 *pcBoneTransforms,
  1496. MDL::IntBone_MDL7 **apcBonesOut) {
  1497. ai_assert(nullptr != pcBoneTransforms);
  1498. ai_assert(nullptr != apcBonesOut);
  1499. // first .. get the transformation matrix
  1500. aiMatrix4x4 mTransform;
  1501. mTransform.a1 = pcBoneTransforms->m[0];
  1502. mTransform.b1 = pcBoneTransforms->m[1];
  1503. mTransform.c1 = pcBoneTransforms->m[2];
  1504. mTransform.d1 = pcBoneTransforms->m[3];
  1505. mTransform.a2 = pcBoneTransforms->m[4];
  1506. mTransform.b2 = pcBoneTransforms->m[5];
  1507. mTransform.c2 = pcBoneTransforms->m[6];
  1508. mTransform.d2 = pcBoneTransforms->m[7];
  1509. mTransform.a3 = pcBoneTransforms->m[8];
  1510. mTransform.b3 = pcBoneTransforms->m[9];
  1511. mTransform.c3 = pcBoneTransforms->m[10];
  1512. mTransform.d3 = pcBoneTransforms->m[11];
  1513. // now decompose the transformation matrix into separate
  1514. // scaling, rotation and translation
  1515. aiVectorKey vScaling, vPosition;
  1516. aiQuatKey qRotation;
  1517. // FIXME: Decompose will assert in debug builds if the matrix is invalid ...
  1518. mTransform.Decompose(vScaling.mValue, qRotation.mValue, vPosition.mValue);
  1519. // now generate keys
  1520. vScaling.mTime = qRotation.mTime = vPosition.mTime = (double)iTrafo;
  1521. // add the keys to the bone
  1522. MDL::IntBone_MDL7 *const pcBoneOut = apcBonesOut[pcBoneTransforms->bone_index];
  1523. pcBoneOut->pkeyPositions.push_back(vPosition);
  1524. pcBoneOut->pkeyScalings.push_back(vScaling);
  1525. pcBoneOut->pkeyRotations.push_back(qRotation);
  1526. }
  1527. // ------------------------------------------------------------------------------------------------
  1528. // Construct output meshes
  1529. void MDLImporter::GenerateOutputMeshes_3DGS_MDL7(
  1530. MDL::IntGroupData_MDL7 &groupData,
  1531. MDL::IntSplitGroupData_MDL7 &splitGroupData) {
  1532. const MDL::IntSharedData_MDL7 &shared = splitGroupData.shared;
  1533. // get a pointer to the header ...
  1534. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  1535. const unsigned int iNumOutBones = pcHeader->bones_num;
  1536. for (std::vector<aiMaterial *>::size_type i = 0; i < shared.pcMats.size(); ++i) {
  1537. if (!splitGroupData.aiSplit[i]->empty()) {
  1538. // allocate the output mesh
  1539. aiMesh *pcMesh = new aiMesh();
  1540. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  1541. pcMesh->mMaterialIndex = (unsigned int)i;
  1542. // allocate output storage
  1543. pcMesh->mNumFaces = (unsigned int)splitGroupData.aiSplit[i]->size();
  1544. pcMesh->mFaces = new aiFace[pcMesh->mNumFaces];
  1545. pcMesh->mNumVertices = pcMesh->mNumFaces * 3;
  1546. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  1547. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  1548. if (!groupData.vTextureCoords1.empty()) {
  1549. pcMesh->mNumUVComponents[0] = 2;
  1550. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  1551. if (!groupData.vTextureCoords2.empty()) {
  1552. pcMesh->mNumUVComponents[1] = 2;
  1553. pcMesh->mTextureCoords[1] = new aiVector3D[pcMesh->mNumVertices];
  1554. }
  1555. }
  1556. // iterate through all faces and build an unique set of vertices
  1557. unsigned int iCurrent = 0;
  1558. for (unsigned int iFace = 0; iFace < pcMesh->mNumFaces; ++iFace) {
  1559. pcMesh->mFaces[iFace].mNumIndices = 3;
  1560. pcMesh->mFaces[iFace].mIndices = new unsigned int[3];
  1561. unsigned int iSrcFace = splitGroupData.aiSplit[i]->operator[](iFace);
  1562. const MDL::IntFace_MDL7 &oldFace = groupData.pcFaces[iSrcFace];
  1563. // iterate through all face indices
  1564. for (unsigned int c = 0; c < 3; ++c) {
  1565. const uint32_t iIndex = oldFace.mIndices[c];
  1566. pcMesh->mVertices[iCurrent] = groupData.vPositions[iIndex];
  1567. pcMesh->mNormals[iCurrent] = groupData.vNormals[iIndex];
  1568. if (!groupData.vTextureCoords1.empty()) {
  1569. pcMesh->mTextureCoords[0][iCurrent] = groupData.vTextureCoords1[iIndex];
  1570. if (!groupData.vTextureCoords2.empty()) {
  1571. pcMesh->mTextureCoords[1][iCurrent] = groupData.vTextureCoords2[iIndex];
  1572. }
  1573. }
  1574. pcMesh->mFaces[iFace].mIndices[c] = iCurrent++;
  1575. }
  1576. }
  1577. // if we have bones in the mesh we'll need to generate
  1578. // proper vertex weights for them
  1579. if (!groupData.aiBones.empty()) {
  1580. std::vector<std::vector<unsigned int>> aaiVWeightList;
  1581. aaiVWeightList.resize(iNumOutBones);
  1582. int iCurrentWeight = 0;
  1583. for (unsigned int iFace = 0; iFace < pcMesh->mNumFaces; ++iFace) {
  1584. unsigned int iSrcFace = splitGroupData.aiSplit[i]->operator[](iFace);
  1585. const MDL::IntFace_MDL7 &oldFace = groupData.pcFaces[iSrcFace];
  1586. // iterate through all face indices
  1587. for (unsigned int c = 0; c < 3; ++c) {
  1588. unsigned int iBone = groupData.aiBones[oldFace.mIndices[c]];
  1589. if (UINT_MAX != iBone) {
  1590. if (iBone >= iNumOutBones) {
  1591. ASSIMP_LOG_ERROR("Bone index overflow. "
  1592. "The bone index of a vertex exceeds the allowed range. ");
  1593. iBone = iNumOutBones - 1;
  1594. }
  1595. aaiVWeightList[iBone].push_back(iCurrentWeight);
  1596. }
  1597. ++iCurrentWeight;
  1598. }
  1599. }
  1600. // now check which bones are required ...
  1601. for (std::vector<std::vector<unsigned int>>::const_iterator k = aaiVWeightList.begin(); k != aaiVWeightList.end(); ++k) {
  1602. if (!(*k).empty()) {
  1603. ++pcMesh->mNumBones;
  1604. }
  1605. }
  1606. pcMesh->mBones = new aiBone *[pcMesh->mNumBones];
  1607. iCurrent = 0;
  1608. for (std::vector<std::vector<unsigned int>>::const_iterator k = aaiVWeightList.begin(); k != aaiVWeightList.end(); ++k, ++iCurrent) {
  1609. if ((*k).empty())
  1610. continue;
  1611. // seems we'll need this node
  1612. aiBone *pcBone = pcMesh->mBones[iCurrent] = new aiBone();
  1613. pcBone->mName = aiString(shared.apcOutBones[iCurrent]->mName);
  1614. pcBone->mOffsetMatrix = shared.apcOutBones[iCurrent]->mOffsetMatrix;
  1615. // setup vertex weights
  1616. pcBone->mNumWeights = (unsigned int)(*k).size();
  1617. pcBone->mWeights = new aiVertexWeight[pcBone->mNumWeights];
  1618. for (unsigned int weight = 0; weight < pcBone->mNumWeights; ++weight) {
  1619. pcBone->mWeights[weight].mVertexId = (*k)[weight];
  1620. pcBone->mWeights[weight].mWeight = 1.0f;
  1621. }
  1622. }
  1623. }
  1624. // add the mesh to the list of output meshes
  1625. splitGroupData.avOutList.push_back(pcMesh);
  1626. }
  1627. }
  1628. }
  1629. // ------------------------------------------------------------------------------------------------
  1630. // Join to materials
  1631. void MDLImporter::JoinSkins_3DGS_MDL7(
  1632. aiMaterial *pcMat1,
  1633. aiMaterial *pcMat2,
  1634. aiMaterial *pcMatOut) {
  1635. ai_assert(nullptr != pcMat1);
  1636. ai_assert(nullptr != pcMat2);
  1637. ai_assert(nullptr != pcMatOut);
  1638. // first create a full copy of the first skin property set
  1639. // and assign it to the output material
  1640. aiMaterial::CopyPropertyList(pcMatOut, pcMat1);
  1641. int iVal = 0;
  1642. pcMatOut->AddProperty<int>(&iVal, 1, AI_MATKEY_UVWSRC_DIFFUSE(0));
  1643. // then extract the diffuse texture from the second skin,
  1644. // setup 1 as UV source and we have it
  1645. aiString sString;
  1646. if (AI_SUCCESS == aiGetMaterialString(pcMat2, AI_MATKEY_TEXTURE_DIFFUSE(0), &sString)) {
  1647. iVal = 1;
  1648. pcMatOut->AddProperty<int>(&iVal, 1, AI_MATKEY_UVWSRC_DIFFUSE(1));
  1649. pcMatOut->AddProperty(&sString, AI_MATKEY_TEXTURE_DIFFUSE(1));
  1650. }
  1651. }
  1652. // ------------------------------------------------------------------------------------------------
  1653. // Read a Half-life 1 MDL
  1654. void MDLImporter::InternReadFile_HL1(const std::string &pFile, const uint32_t iMagicWord) {
  1655. // We can't correctly load an MDL from a MDL "sequence" file.
  1656. if (iMagicWord == AI_MDL_MAGIC_NUMBER_BE_HL2b || iMagicWord == AI_MDL_MAGIC_NUMBER_LE_HL2b)
  1657. throw DeadlyImportError("Impossible to properly load a model from an MDL sequence file.");
  1658. // Read the MDL file.
  1659. HalfLife::HL1MDLLoader loader(
  1660. pScene,
  1661. mIOHandler,
  1662. mBuffer,
  1663. pFile,
  1664. mHL1ImportSettings);
  1665. }
  1666. // ------------------------------------------------------------------------------------------------
  1667. // Read a half-life 2 MDL
  1668. void MDLImporter::InternReadFile_HL2() {
  1669. //const MDL::Header_HL2* pcHeader = (const MDL::Header_HL2*)this->mBuffer;
  1670. throw DeadlyImportError("HL2 MDLs are not implemented");
  1671. }
  1672. #endif // !! ASSIMP_BUILD_NO_MDL_IMPORTER