MDLLoader.cpp 87 KB

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