MD5Parser.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, 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 MD5Parser.cpp
  35. * @brief Implementation of the MD5 parser class
  36. */
  37. // internal headers
  38. #include "AssetLib/MD5/MD5Loader.h"
  39. #include "Material/MaterialSystem.h"
  40. #include <assimp/ParsingUtils.h>
  41. #include <assimp/StringComparison.h>
  42. #include <assimp/fast_atof.h>
  43. #include <assimp/mesh.h>
  44. #include <assimp/DefaultLogger.hpp>
  45. using namespace Assimp;
  46. using namespace Assimp::MD5;
  47. // ------------------------------------------------------------------------------------------------
  48. // Parse the segment structure for an MD5 file
  49. MD5Parser::MD5Parser(char *_buffer, unsigned int _fileSize) : buffer(_buffer), bufferEnd(nullptr), fileSize(_fileSize), lineNumber(0) {
  50. ai_assert(nullptr != _buffer);
  51. ai_assert(0 != _fileSize);
  52. bufferEnd = buffer + fileSize;
  53. ASSIMP_LOG_DEBUG("MD5Parser begin");
  54. // parse the file header
  55. ParseHeader();
  56. // and read all sections until we're finished
  57. bool running = true;
  58. while (running) {
  59. mSections.emplace_back();
  60. Section &sec = mSections.back();
  61. if (!ParseSection(sec)) {
  62. break;
  63. }
  64. }
  65. if (!DefaultLogger::isNullLogger()) {
  66. char szBuffer[128]; // should be sufficiently large
  67. ::ai_snprintf(szBuffer, 128, "MD5Parser end. Parsed %i sections", (int)mSections.size());
  68. ASSIMP_LOG_DEBUG(szBuffer);
  69. }
  70. }
  71. // ------------------------------------------------------------------------------------------------
  72. // Report error to the log stream
  73. /*static*/ AI_WONT_RETURN void MD5Parser::ReportError(const char *error, unsigned int line) {
  74. char szBuffer[1024];
  75. ::ai_snprintf(szBuffer, 1024, "[MD5] Line %u: %s", line, error);
  76. throw DeadlyImportError(szBuffer);
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. // Report warning to the log stream
  80. /*static*/ void MD5Parser::ReportWarning(const char *warn, unsigned int line) {
  81. char szBuffer[1024];
  82. ::snprintf(szBuffer, sizeof(szBuffer), "[MD5] Line %u: %s", line, warn);
  83. ASSIMP_LOG_WARN(szBuffer);
  84. }
  85. // ------------------------------------------------------------------------------------------------
  86. // Parse and validate the MD5 header
  87. void MD5Parser::ParseHeader() {
  88. // parse and validate the file version
  89. SkipSpaces();
  90. if (!TokenMatch(buffer, "MD5Version", 10)) {
  91. ReportError("Invalid MD5 file: MD5Version tag has not been found");
  92. }
  93. SkipSpaces();
  94. unsigned int iVer = ::strtoul10(buffer, (const char **)&buffer);
  95. if (10 != iVer) {
  96. ReportError("MD5 version tag is unknown (10 is expected)");
  97. }
  98. SkipLine();
  99. if (buffer == bufferEnd) {
  100. return;
  101. }
  102. // print the command line options to the console
  103. // FIX: can break the log length limit, so we need to be careful
  104. char *sz = buffer;
  105. while (!IsLineEnd(*buffer++))
  106. ;
  107. ASSIMP_LOG_INFO(std::string(sz, std::min((uintptr_t)MAX_LOG_MESSAGE_LENGTH, (uintptr_t)(buffer - sz))));
  108. SkipSpacesAndLineEnd();
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. // Recursive MD5 parsing function
  112. bool MD5Parser::ParseSection(Section &out) {
  113. // store the current line number for use in error messages
  114. out.iLineNumber = lineNumber;
  115. // first parse the name of the section
  116. char *sz = buffer;
  117. while (!IsSpaceOrNewLine(*buffer)) {
  118. ++buffer;
  119. if (buffer == bufferEnd)
  120. return false;
  121. }
  122. out.mName = std::string(sz, (uintptr_t)(buffer - sz));
  123. while (IsSpace(*buffer)) {
  124. ++buffer;
  125. if (buffer == bufferEnd)
  126. return false;
  127. }
  128. bool running = true;
  129. while (running) {
  130. if ('{' == *buffer) {
  131. // it is a normal section so read all lines
  132. ++buffer;
  133. if (buffer == bufferEnd)
  134. return false;
  135. bool run = true;
  136. while (run) {
  137. while (IsSpaceOrNewLine(*buffer)) {
  138. ++buffer;
  139. if (buffer == bufferEnd)
  140. return false;
  141. }
  142. if ('\0' == *buffer) {
  143. return false; // seems this was the last section
  144. }
  145. if ('}' == *buffer) {
  146. ++buffer;
  147. break;
  148. }
  149. out.mElements.emplace_back();
  150. Element &elem = out.mElements.back();
  151. elem.iLineNumber = lineNumber;
  152. elem.szStart = buffer;
  153. // terminate the line with zero
  154. while (!IsLineEnd(*buffer)) {
  155. ++buffer;
  156. if (buffer == bufferEnd)
  157. return false;
  158. }
  159. if (*buffer) {
  160. ++lineNumber;
  161. *buffer++ = '\0';
  162. if (buffer == bufferEnd)
  163. return false;
  164. }
  165. }
  166. break;
  167. } else if (!IsSpaceOrNewLine(*buffer)) {
  168. // it is an element at global scope. Parse its value and go on
  169. sz = buffer;
  170. while (!IsSpaceOrNewLine(*buffer++)) {
  171. if (buffer == bufferEnd)
  172. return false;
  173. }
  174. out.mGlobalValue = std::string(sz, (uintptr_t)(buffer - sz));
  175. continue;
  176. }
  177. break;
  178. }
  179. if (buffer == bufferEnd)
  180. return false;
  181. while (IsSpaceOrNewLine(*buffer)) {
  182. ++buffer;
  183. if (buffer == bufferEnd)
  184. return false;
  185. }
  186. return '\0' != *buffer;
  187. }
  188. // ------------------------------------------------------------------------------------------------
  189. // Some dirty macros just because they're so funny and easy to debug
  190. // skip all spaces ... handle EOL correctly
  191. #define AI_MD5_SKIP_SPACES() \
  192. if (!SkipSpaces(&sz)) \
  193. MD5Parser::ReportWarning("Unexpected end of line", elem.iLineNumber);
  194. // read a triple float in brackets: (1.0 1.0 1.0)
  195. #define AI_MD5_READ_TRIPLE(vec) \
  196. AI_MD5_SKIP_SPACES(); \
  197. if ('(' != *sz++) \
  198. MD5Parser::ReportWarning("Unexpected token: ( was expected", elem.iLineNumber); \
  199. AI_MD5_SKIP_SPACES(); \
  200. sz = fast_atoreal_move<float>(sz, (float &)vec.x); \
  201. AI_MD5_SKIP_SPACES(); \
  202. sz = fast_atoreal_move<float>(sz, (float &)vec.y); \
  203. AI_MD5_SKIP_SPACES(); \
  204. sz = fast_atoreal_move<float>(sz, (float &)vec.z); \
  205. AI_MD5_SKIP_SPACES(); \
  206. if (')' != *sz++) \
  207. MD5Parser::ReportWarning("Unexpected token: ) was expected", elem.iLineNumber);
  208. // parse a string, enclosed in quotation marks or not
  209. #define AI_MD5_PARSE_STRING(out) \
  210. bool bQuota = (*sz == '\"'); \
  211. const char *szStart = sz; \
  212. while (!IsSpaceOrNewLine(*sz)) \
  213. ++sz; \
  214. const char *szEnd = sz; \
  215. if (bQuota) { \
  216. szStart++; \
  217. if ('\"' != *(szEnd -= 1)) { \
  218. MD5Parser::ReportWarning("Expected closing quotation marks in string", \
  219. elem.iLineNumber); \
  220. continue; \
  221. } \
  222. } \
  223. out.length = (size_t)(szEnd - szStart); \
  224. ::memcpy(out.data, szStart, out.length); \
  225. out.data[out.length] = '\0';
  226. // parse a string, enclosed in quotation marks
  227. #define AI_MD5_PARSE_STRING_IN_QUOTATION(out) \
  228. out.length = 0; \
  229. while ('\"' != *sz && '\0' != *sz) \
  230. ++sz; \
  231. if ('\0' != *sz) { \
  232. const char *szStart = ++sz; \
  233. while ('\"' != *sz && '\0' != *sz) \
  234. ++sz; \
  235. if ('\0' != *sz) { \
  236. const char *szEnd = (sz++); \
  237. out.length = (ai_uint32)(szEnd - szStart); \
  238. ::memcpy(out.data, szStart, out.length); \
  239. } \
  240. } \
  241. out.data[out.length] = '\0';
  242. // ------------------------------------------------------------------------------------------------
  243. // .MD5MESH parsing function
  244. MD5MeshParser::MD5MeshParser(SectionList &mSections) {
  245. ASSIMP_LOG_DEBUG("MD5MeshParser begin");
  246. // now parse all sections
  247. for (SectionList::const_iterator iter = mSections.begin(), iterEnd = mSections.end(); iter != iterEnd; ++iter) {
  248. if ((*iter).mName == "numMeshes") {
  249. mMeshes.reserve(::strtoul10((*iter).mGlobalValue.c_str()));
  250. } else if ((*iter).mName == "numJoints") {
  251. mJoints.reserve(::strtoul10((*iter).mGlobalValue.c_str()));
  252. } else if ((*iter).mName == "joints") {
  253. // "origin" -1 ( -0.000000 0.016430 -0.006044 ) ( 0.707107 0.000000 0.707107 )
  254. for (const auto &elem : (*iter).mElements) {
  255. mJoints.emplace_back();
  256. BoneDesc &desc = mJoints.back();
  257. const char *sz = elem.szStart;
  258. AI_MD5_PARSE_STRING_IN_QUOTATION(desc.mName);
  259. AI_MD5_SKIP_SPACES();
  260. // negative values, at least -1, is allowed here
  261. desc.mParentIndex = (int)strtol10(sz, &sz);
  262. AI_MD5_READ_TRIPLE(desc.mPositionXYZ);
  263. AI_MD5_READ_TRIPLE(desc.mRotationQuat); // normalized quaternion, so w is not there
  264. }
  265. } else if ((*iter).mName == "mesh") {
  266. mMeshes.emplace_back();
  267. MeshDesc &desc = mMeshes.back();
  268. for (const auto &elem : (*iter).mElements) {
  269. const char *sz = elem.szStart;
  270. // shader attribute
  271. if (TokenMatch(sz, "shader", 6)) {
  272. AI_MD5_SKIP_SPACES();
  273. AI_MD5_PARSE_STRING_IN_QUOTATION(desc.mShader);
  274. }
  275. // numverts attribute
  276. else if (TokenMatch(sz, "numverts", 8)) {
  277. AI_MD5_SKIP_SPACES();
  278. desc.mVertices.resize(strtoul10(sz));
  279. }
  280. // numtris attribute
  281. else if (TokenMatch(sz, "numtris", 7)) {
  282. AI_MD5_SKIP_SPACES();
  283. desc.mFaces.resize(strtoul10(sz));
  284. }
  285. // numweights attribute
  286. else if (TokenMatch(sz, "numweights", 10)) {
  287. AI_MD5_SKIP_SPACES();
  288. desc.mWeights.resize(strtoul10(sz));
  289. }
  290. // vert attribute
  291. // "vert 0 ( 0.394531 0.513672 ) 0 1"
  292. else if (TokenMatch(sz, "vert", 4)) {
  293. AI_MD5_SKIP_SPACES();
  294. const unsigned int idx = ::strtoul10(sz, &sz);
  295. AI_MD5_SKIP_SPACES();
  296. if (idx >= desc.mVertices.size())
  297. desc.mVertices.resize(idx + 1);
  298. VertexDesc &vert = desc.mVertices[idx];
  299. if ('(' != *sz++)
  300. MD5Parser::ReportWarning("Unexpected token: ( was expected", elem.iLineNumber);
  301. AI_MD5_SKIP_SPACES();
  302. sz = fast_atoreal_move<float>(sz, (float &)vert.mUV.x);
  303. AI_MD5_SKIP_SPACES();
  304. sz = fast_atoreal_move<float>(sz, (float &)vert.mUV.y);
  305. AI_MD5_SKIP_SPACES();
  306. if (')' != *sz++)
  307. MD5Parser::ReportWarning("Unexpected token: ) was expected", elem.iLineNumber);
  308. AI_MD5_SKIP_SPACES();
  309. vert.mFirstWeight = ::strtoul10(sz, &sz);
  310. AI_MD5_SKIP_SPACES();
  311. vert.mNumWeights = ::strtoul10(sz, &sz);
  312. }
  313. // tri attribute
  314. // "tri 0 15 13 12"
  315. else if (TokenMatch(sz, "tri", 3)) {
  316. AI_MD5_SKIP_SPACES();
  317. const unsigned int idx = strtoul10(sz, &sz);
  318. if (idx >= desc.mFaces.size())
  319. desc.mFaces.resize(idx + 1);
  320. aiFace &face = desc.mFaces[idx];
  321. face.mIndices = new unsigned int[face.mNumIndices = 3];
  322. for (unsigned int i = 0; i < 3; ++i) {
  323. AI_MD5_SKIP_SPACES();
  324. face.mIndices[i] = strtoul10(sz, &sz);
  325. }
  326. }
  327. // weight attribute
  328. // "weight 362 5 0.500000 ( -3.553583 11.893474 9.719339 )"
  329. else if (TokenMatch(sz, "weight", 6)) {
  330. AI_MD5_SKIP_SPACES();
  331. const unsigned int idx = strtoul10(sz, &sz);
  332. AI_MD5_SKIP_SPACES();
  333. if (idx >= desc.mWeights.size())
  334. desc.mWeights.resize(idx + 1);
  335. WeightDesc &weight = desc.mWeights[idx];
  336. weight.mBone = strtoul10(sz, &sz);
  337. AI_MD5_SKIP_SPACES();
  338. sz = fast_atoreal_move<float>(sz, weight.mWeight);
  339. AI_MD5_READ_TRIPLE(weight.vOffsetPosition);
  340. }
  341. }
  342. }
  343. }
  344. ASSIMP_LOG_DEBUG("MD5MeshParser end");
  345. }
  346. // ------------------------------------------------------------------------------------------------
  347. // .MD5ANIM parsing function
  348. MD5AnimParser::MD5AnimParser(SectionList &mSections) {
  349. ASSIMP_LOG_DEBUG("MD5AnimParser begin");
  350. fFrameRate = 24.0f;
  351. mNumAnimatedComponents = UINT_MAX;
  352. for (SectionList::const_iterator iter = mSections.begin(), iterEnd = mSections.end(); iter != iterEnd; ++iter) {
  353. if ((*iter).mName == "hierarchy") {
  354. // "sheath" 0 63 6
  355. for (const auto &elem : (*iter).mElements) {
  356. mAnimatedBones.emplace_back();
  357. AnimBoneDesc &desc = mAnimatedBones.back();
  358. const char *sz = elem.szStart;
  359. AI_MD5_PARSE_STRING_IN_QUOTATION(desc.mName);
  360. AI_MD5_SKIP_SPACES();
  361. // parent index - negative values are allowed (at least -1)
  362. desc.mParentIndex = ::strtol10(sz, &sz);
  363. // flags (highest is 2^6-1)
  364. AI_MD5_SKIP_SPACES();
  365. if (63 < (desc.iFlags = ::strtoul10(sz, &sz))) {
  366. MD5Parser::ReportWarning("Invalid flag combination in hierarchy section", elem.iLineNumber);
  367. }
  368. AI_MD5_SKIP_SPACES();
  369. // index of the first animation keyframe component for this joint
  370. desc.iFirstKeyIndex = ::strtoul10(sz, &sz);
  371. }
  372. } else if ((*iter).mName == "baseframe") {
  373. // ( -0.000000 0.016430 -0.006044 ) ( 0.707107 0.000242 0.707107 )
  374. for (const auto &elem : (*iter).mElements) {
  375. const char *sz = elem.szStart;
  376. mBaseFrames.emplace_back();
  377. BaseFrameDesc &desc = mBaseFrames.back();
  378. AI_MD5_READ_TRIPLE(desc.vPositionXYZ);
  379. AI_MD5_READ_TRIPLE(desc.vRotationQuat);
  380. }
  381. } else if ((*iter).mName == "frame") {
  382. if (!(*iter).mGlobalValue.length()) {
  383. MD5Parser::ReportWarning("A frame section must have a frame index", (*iter).iLineNumber);
  384. continue;
  385. }
  386. mFrames.emplace_back();
  387. FrameDesc &desc = mFrames.back();
  388. desc.iIndex = strtoul10((*iter).mGlobalValue.c_str());
  389. // we do already know how much storage we will presumably need
  390. if (UINT_MAX != mNumAnimatedComponents) {
  391. desc.mValues.reserve(mNumAnimatedComponents);
  392. }
  393. // now read all elements (continuous list of floats)
  394. for (const auto &elem : (*iter).mElements) {
  395. const char *sz = elem.szStart;
  396. while (SkipSpacesAndLineEnd(&sz)) {
  397. float f;
  398. sz = fast_atoreal_move<float>(sz, f);
  399. desc.mValues.push_back(f);
  400. }
  401. }
  402. } else if ((*iter).mName == "numFrames") {
  403. mFrames.reserve(strtoul10((*iter).mGlobalValue.c_str()));
  404. } else if ((*iter).mName == "numJoints") {
  405. const unsigned int num = strtoul10((*iter).mGlobalValue.c_str());
  406. mAnimatedBones.reserve(num);
  407. // try to guess the number of animated components if that element is not given
  408. if (UINT_MAX == mNumAnimatedComponents) {
  409. mNumAnimatedComponents = num * 6;
  410. }
  411. } else if ((*iter).mName == "numAnimatedComponents") {
  412. mAnimatedBones.reserve(strtoul10((*iter).mGlobalValue.c_str()));
  413. } else if ((*iter).mName == "frameRate") {
  414. fast_atoreal_move<float>((*iter).mGlobalValue.c_str(), fFrameRate);
  415. }
  416. }
  417. ASSIMP_LOG_DEBUG("MD5AnimParser end");
  418. }
  419. // ------------------------------------------------------------------------------------------------
  420. // .MD5CAMERA parsing function
  421. MD5CameraParser::MD5CameraParser(SectionList &mSections) {
  422. ASSIMP_LOG_DEBUG("MD5CameraParser begin");
  423. fFrameRate = 24.0f;
  424. for (SectionList::const_iterator iter = mSections.begin(), iterEnd = mSections.end(); iter != iterEnd; ++iter) {
  425. if ((*iter).mName == "numFrames") {
  426. frames.reserve(strtoul10((*iter).mGlobalValue.c_str()));
  427. } else if ((*iter).mName == "frameRate") {
  428. fFrameRate = fast_atof((*iter).mGlobalValue.c_str());
  429. } else if ((*iter).mName == "numCuts") {
  430. cuts.reserve(strtoul10((*iter).mGlobalValue.c_str()));
  431. } else if ((*iter).mName == "cuts") {
  432. for (const auto &elem : (*iter).mElements) {
  433. cuts.push_back(strtoul10(elem.szStart) + 1);
  434. }
  435. } else if ((*iter).mName == "camera") {
  436. for (const auto &elem : (*iter).mElements) {
  437. const char *sz = elem.szStart;
  438. frames.emplace_back();
  439. CameraAnimFrameDesc &cur = frames.back();
  440. AI_MD5_READ_TRIPLE(cur.vPositionXYZ);
  441. AI_MD5_READ_TRIPLE(cur.vRotationQuat);
  442. AI_MD5_SKIP_SPACES();
  443. cur.fFOV = fast_atof(sz);
  444. }
  445. }
  446. }
  447. ASSIMP_LOG_DEBUG("MD5CameraParser end");
  448. }