MD5Parser.cpp 18 KB

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