FBXParser.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file FBXParser.cpp
  34. * @brief Implementation of the FBX parser and the rudimentary DOM that we use
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
  38. #ifdef ASSIMP_BUILD_NO_OWN_ZLIB
  39. # include <zlib.h>
  40. #else
  41. # include "../contrib/zlib/zlib.h"
  42. #endif
  43. #include "FBXTokenizer.h"
  44. #include "FBXParser.h"
  45. #include "FBXUtil.h"
  46. #include "ParsingUtils.h"
  47. #include "fast_atof.h"
  48. using namespace Assimp;
  49. using namespace Assimp::FBX;
  50. namespace {
  51. // ------------------------------------------------------------------------------------------------
  52. // signal parse error, this is always unrecoverable. Throws DeadlyImportError.
  53. void ParseError(const std::string& message, const Token& token)
  54. {
  55. throw DeadlyImportError(Util::AddTokenText("FBX-Parser",message,&token));
  56. }
  57. // ------------------------------------------------------------------------------------------------
  58. void ParseError(const std::string& message, const Element* element = NULL)
  59. {
  60. if(element) {
  61. ParseError(message,element->KeyToken());
  62. }
  63. throw DeadlyImportError("FBX-Parser " + message);
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. // print warning, do return
  67. void ParseWarning(const std::string& message, const Token& token)
  68. {
  69. if(DefaultLogger::get()) {
  70. DefaultLogger::get()->warn(Util::AddTokenText("FBX-Parser",message,&token));
  71. }
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. void ParseWarning(const std::string& message, const Element* element = NULL)
  75. {
  76. if(element) {
  77. ParseWarning(message,element->KeyToken());
  78. return;
  79. }
  80. if(DefaultLogger::get()) {
  81. DefaultLogger::get()->warn("FBX-Parser: " + message);
  82. }
  83. }
  84. // ------------------------------------------------------------------------------------------------
  85. void ParseError(const std::string& message, TokenPtr token)
  86. {
  87. if(token) {
  88. ParseError(message, *token);
  89. }
  90. ParseError(message);
  91. }
  92. }
  93. namespace Assimp {
  94. namespace FBX {
  95. // ------------------------------------------------------------------------------------------------
  96. Element::Element(const Token& key_token, Parser& parser)
  97. : key_token(key_token)
  98. {
  99. TokenPtr n = NULL;
  100. do {
  101. n = parser.AdvanceToNextToken();
  102. if(!n) {
  103. ParseError("unexpected end of file, expected closing bracket",parser.LastToken());
  104. }
  105. if (n->Type() == TokenType_DATA) {
  106. tokens.push_back(n);
  107. n = parser.AdvanceToNextToken();
  108. if(!n) {
  109. ParseError("unexpected end of file, expected bracket, comma or key",parser.LastToken());
  110. }
  111. const TokenType ty = n->Type();
  112. if (ty != TokenType_OPEN_BRACKET && ty != TokenType_CLOSE_BRACKET && ty != TokenType_COMMA && ty != TokenType_KEY) {
  113. ParseError("unexpected token; expected bracket, comma or key",n);
  114. }
  115. }
  116. if (n->Type() == TokenType_OPEN_BRACKET) {
  117. compound.reset(new Scope(parser));
  118. // current token should be a TOK_CLOSE_BRACKET
  119. n = parser.CurrentToken();
  120. ai_assert(n);
  121. if (n->Type() != TokenType_CLOSE_BRACKET) {
  122. ParseError("expected closing bracket",n);
  123. }
  124. parser.AdvanceToNextToken();
  125. return;
  126. }
  127. }
  128. while(n->Type() != TokenType_KEY && n->Type() != TokenType_CLOSE_BRACKET);
  129. }
  130. // ------------------------------------------------------------------------------------------------
  131. Element::~Element()
  132. {
  133. // no need to delete tokens, they are owned by the parser
  134. }
  135. // ------------------------------------------------------------------------------------------------
  136. Scope::Scope(Parser& parser,bool topLevel)
  137. {
  138. if(!topLevel) {
  139. TokenPtr t = parser.CurrentToken();
  140. if (t->Type() != TokenType_OPEN_BRACKET) {
  141. ParseError("expected open bracket",t);
  142. }
  143. }
  144. TokenPtr n = parser.AdvanceToNextToken();
  145. if(n == NULL) {
  146. ParseError("unexpected end of file");
  147. }
  148. // note: empty scopes are allowed
  149. while(n->Type() != TokenType_CLOSE_BRACKET) {
  150. if (n->Type() != TokenType_KEY) {
  151. ParseError("unexpected token, expected TOK_KEY",n);
  152. }
  153. const std::string& str = n->StringContents();
  154. elements.insert(ElementMap::value_type(str,new_Element(*n,parser)));
  155. // Element() should stop at the next Key token (or right after a Close token)
  156. n = parser.CurrentToken();
  157. if(n == NULL) {
  158. if (topLevel) {
  159. return;
  160. }
  161. ParseError("unexpected end of file",parser.LastToken());
  162. }
  163. }
  164. }
  165. // ------------------------------------------------------------------------------------------------
  166. Scope::~Scope()
  167. {
  168. BOOST_FOREACH(ElementMap::value_type& v, elements) {
  169. delete v.second;
  170. }
  171. }
  172. // ------------------------------------------------------------------------------------------------
  173. Parser::Parser (const TokenList& tokens, bool is_binary)
  174. : tokens(tokens)
  175. , last()
  176. , current()
  177. , cursor(tokens.begin())
  178. , is_binary(is_binary)
  179. {
  180. root.reset(new Scope(*this,true));
  181. }
  182. // ------------------------------------------------------------------------------------------------
  183. Parser::~Parser()
  184. {
  185. }
  186. // ------------------------------------------------------------------------------------------------
  187. TokenPtr Parser::AdvanceToNextToken()
  188. {
  189. last = current;
  190. if (cursor == tokens.end()) {
  191. current = NULL;
  192. }
  193. else {
  194. current = *cursor++;
  195. }
  196. return current;
  197. }
  198. // ------------------------------------------------------------------------------------------------
  199. TokenPtr Parser::CurrentToken() const
  200. {
  201. return current;
  202. }
  203. // ------------------------------------------------------------------------------------------------
  204. TokenPtr Parser::LastToken() const
  205. {
  206. return last;
  207. }
  208. // ------------------------------------------------------------------------------------------------
  209. uint64_t ParseTokenAsID(const Token& t, const char*& err_out)
  210. {
  211. err_out = NULL;
  212. if (t.Type() != TokenType_DATA) {
  213. err_out = "expected TOK_DATA token";
  214. return 0L;
  215. }
  216. if(t.IsBinary())
  217. {
  218. const char* data = t.begin();
  219. if (data[0] != 'L') {
  220. err_out = "failed to parse ID, unexpected data type, expected L(ong) (binary)";
  221. return 0L;
  222. }
  223. ai_assert(t.end() - data == 9);
  224. BE_NCONST uint64_t id = *reinterpret_cast<const uint64_t*>(data+1);
  225. AI_SWAP8(id);
  226. return id;
  227. }
  228. // XXX: should use size_t here
  229. unsigned int length = static_cast<unsigned int>(t.end() - t.begin());
  230. ai_assert(length > 0);
  231. const char* out;
  232. const uint64_t id = strtoul10_64(t.begin(),&out,&length);
  233. if (out > t.end()) {
  234. err_out = "failed to parse ID (text)";
  235. return 0L;
  236. }
  237. return id;
  238. }
  239. // ------------------------------------------------------------------------------------------------
  240. size_t ParseTokenAsDim(const Token& t, const char*& err_out)
  241. {
  242. // same as ID parsing, except there is a trailing asterisk
  243. err_out = NULL;
  244. if (t.Type() != TokenType_DATA) {
  245. err_out = "expected TOK_DATA token";
  246. return 0;
  247. }
  248. if(t.IsBinary())
  249. {
  250. const char* data = t.begin();
  251. if (data[0] != 'L') {
  252. err_out = "failed to parse ID, unexpected data type, expected L(ong) (binary)";
  253. return 0;
  254. }
  255. ai_assert(t.end() - data == 9);
  256. BE_NCONST uint64_t id = *reinterpret_cast<const uint64_t*>(data+1);
  257. AI_SWAP8(id);
  258. return static_cast<size_t>(id);
  259. }
  260. if(*t.begin() != '*') {
  261. err_out = "expected asterisk before array dimension";
  262. return 0;
  263. }
  264. // XXX: should use size_t here
  265. unsigned int length = static_cast<unsigned int>(t.end() - t.begin());
  266. if(length == 0) {
  267. err_out = "expected valid integer number after asterisk";
  268. return 0;
  269. }
  270. const char* out;
  271. const size_t id = static_cast<size_t>(strtoul10_64(t.begin() + 1,&out,&length));
  272. if (out > t.end()) {
  273. err_out = "failed to parse ID";
  274. return 0;
  275. }
  276. return id;
  277. }
  278. // ------------------------------------------------------------------------------------------------
  279. float ParseTokenAsFloat(const Token& t, const char*& err_out)
  280. {
  281. err_out = NULL;
  282. if (t.Type() != TokenType_DATA) {
  283. err_out = "expected TOK_DATA token";
  284. return 0.0f;
  285. }
  286. if(t.IsBinary())
  287. {
  288. const char* data = t.begin();
  289. if (data[0] != 'F' && data[0] != 'D') {
  290. err_out = "failed to parse F(loat) or D(ouble), unexpected data type (binary)";
  291. return 0.0f;
  292. }
  293. if (data[0] == 'F') {
  294. ai_assert(t.end() - data == 5);
  295. // no byte swapping needed for ieee floats
  296. return *reinterpret_cast<const float*>(data+1);
  297. }
  298. else {
  299. ai_assert(t.end() - data == 9);
  300. // no byte swapping needed for ieee floats
  301. return static_cast<float>(*reinterpret_cast<const double*>(data+1));
  302. }
  303. }
  304. // need to copy the input string to a temporary buffer
  305. // first - next in the fbx token stream comes ',',
  306. // which fast_atof could interpret as decimal point.
  307. #define MAX_FLOAT_LENGTH 31
  308. char temp[MAX_FLOAT_LENGTH + 1];
  309. const size_t length = static_cast<size_t>(t.end()-t.begin());
  310. std::copy(t.begin(),t.end(),temp);
  311. temp[std::min(static_cast<size_t>(MAX_FLOAT_LENGTH),length)] = '\0';
  312. return fast_atof(temp);
  313. }
  314. // ------------------------------------------------------------------------------------------------
  315. int ParseTokenAsInt(const Token& t, const char*& err_out)
  316. {
  317. err_out = NULL;
  318. if (t.Type() != TokenType_DATA) {
  319. err_out = "expected TOK_DATA token";
  320. return 0;
  321. }
  322. if(t.IsBinary())
  323. {
  324. const char* data = t.begin();
  325. if (data[0] != 'I') {
  326. err_out = "failed to parse I(nt), unexpected data type (binary)";
  327. return 0;
  328. }
  329. ai_assert(t.end() - data == 5);
  330. BE_NCONST int32_t ival = *reinterpret_cast<const int32_t*>(data+1);
  331. AI_SWAP4(ival);
  332. return static_cast<int>(ival);
  333. }
  334. ai_assert(static_cast<size_t>(t.end() - t.begin()) > 0);
  335. const char* out;
  336. const int intval = strtol10(t.begin(),&out);
  337. if (out != t.end()) {
  338. err_out = "failed to parse ID";
  339. return 0;
  340. }
  341. return intval;
  342. }
  343. // ------------------------------------------------------------------------------------------------
  344. std::string ParseTokenAsString(const Token& t, const char*& err_out)
  345. {
  346. err_out = NULL;
  347. if (t.Type() != TokenType_DATA) {
  348. err_out = "expected TOK_DATA token";
  349. return "";
  350. }
  351. if(t.IsBinary())
  352. {
  353. const char* data = t.begin();
  354. if (data[0] != 'S') {
  355. err_out = "failed to parse S(tring), unexpected data type (binary)";
  356. return "";
  357. }
  358. ai_assert(t.end() - data >= 5);
  359. // read string length
  360. BE_NCONST int32_t len = *reinterpret_cast<const int32_t*>(data+1);
  361. AI_SWAP4(len);
  362. ai_assert(t.end() - data == 5 + len);
  363. return std::string(data + 5, len);
  364. }
  365. const size_t length = static_cast<size_t>(t.end() - t.begin());
  366. if(length < 2) {
  367. err_out = "token is too short to hold a string";
  368. return "";
  369. }
  370. const char* s = t.begin(), *e = t.end() - 1;
  371. if (*s != '\"' || *e != '\"') {
  372. err_out = "expected double quoted string";
  373. return "";
  374. }
  375. return std::string(s+1,length-2);
  376. }
  377. namespace {
  378. // ------------------------------------------------------------------------------------------------
  379. // read the type code and element count of a binary data array and stop there
  380. void ReadBinaryDataArrayHead(const char*& data, const char* end, char& type, uint32_t& count,
  381. const Element& el)
  382. {
  383. if (static_cast<size_t>(end-data) < 5) {
  384. ParseError("binary data array is too short, need five (5) bytes for type signature and element count",&el);
  385. }
  386. // data type
  387. type = *data;
  388. // read number of elements
  389. BE_NCONST uint32_t len = *reinterpret_cast<const uint32_t*>(data+1);
  390. AI_SWAP4(len);
  391. count = len;
  392. data += 5;
  393. }
  394. // ------------------------------------------------------------------------------------------------
  395. // read binary data array, assume cursor points to the 'compression mode' field (i.e. behind the header)
  396. void ReadBinaryDataArray(char type, uint32_t count, const char*& data, const char* end,
  397. std::vector<char>& buff,
  398. const Element& el)
  399. {
  400. ai_assert(static_cast<size_t>(end-data) >= 4); // runtime check for this happens at tokenization stage
  401. BE_NCONST uint32_t encmode = *reinterpret_cast<const uint32_t*>(data);
  402. AI_SWAP4(encmode);
  403. data += 4;
  404. // next comes the compressed length
  405. BE_NCONST uint32_t comp_len = *reinterpret_cast<const uint32_t*>(data);
  406. AI_SWAP4(comp_len);
  407. data += 4;
  408. ai_assert(data + comp_len == end);
  409. // determine the length of the uncompressed data by looking at the type signature
  410. uint32_t stride;
  411. switch(type)
  412. {
  413. case 'f':
  414. case 'i':
  415. stride = 4;
  416. break;
  417. case 'd':
  418. case 'l':
  419. stride = 8;
  420. break;
  421. default:
  422. ai_assert(false);
  423. };
  424. const uint32_t full_length = stride * count;
  425. buff.resize(full_length);
  426. if(encmode == 0) {
  427. ai_assert(full_length == comp_len);
  428. // plain data, no compression
  429. std::copy(data, end, buff.begin());
  430. }
  431. else if(encmode == 1) {
  432. // zlib/deflate, next comes ZIP head (0x78 0x01)
  433. // see http://www.ietf.org/rfc/rfc1950.txt
  434. z_stream zstream;
  435. zstream.opaque = Z_NULL;
  436. zstream.zalloc = Z_NULL;
  437. zstream.zfree = Z_NULL;
  438. zstream.data_type = Z_BINARY;
  439. // http://hewgill.com/journal/entries/349-how-to-decompress-gzip-stream-with-zlib
  440. inflateInit(&zstream);
  441. zstream.next_in = reinterpret_cast<Bytef*>( const_cast<char*>(data) );
  442. zstream.avail_in = comp_len;
  443. zstream.avail_out = buff.size();
  444. zstream.next_out = reinterpret_cast<Bytef*>(&*buff.begin());
  445. const int ret = inflate(&zstream, Z_FINISH);
  446. if (ret != Z_STREAM_END && ret != Z_OK) {
  447. ParseError("failure decompressing compressed data section");
  448. }
  449. // terminate zlib
  450. inflateEnd(&zstream);
  451. }
  452. #ifdef _DEBUG
  453. else {
  454. // runtime check for this happens at tokenization stage
  455. ai_assert(false);
  456. }
  457. #endif
  458. data += comp_len;
  459. ai_assert(data == end);
  460. }
  461. } // !anon
  462. // ------------------------------------------------------------------------------------------------
  463. // read an array of float3 tuples
  464. void ParseVectorDataArray(std::vector<aiVector3D>& out, const Element& el)
  465. {
  466. out.clear();
  467. const TokenList& tok = el.Tokens();
  468. if(tok.empty()) {
  469. ParseError("unexpected empty element",&el);
  470. }
  471. if(tok[0]->IsBinary()) {
  472. const char* data = tok[0]->begin(), *end = tok[0]->end();
  473. char type;
  474. uint32_t count;
  475. ReadBinaryDataArrayHead(data, end, type, count, el);
  476. if(count % 3 != 0) {
  477. ParseError("number of floats is not a multiple of three (3) (binary)",&el);
  478. }
  479. if(!count) {
  480. return;
  481. }
  482. if (type != 'd' && type != 'f') {
  483. ParseError("expected float or double array (binary)",&el);
  484. }
  485. std::vector<char> buff;
  486. ReadBinaryDataArray(type, count, data, end, buff, el);
  487. ai_assert(data == end);
  488. ai_assert(buff.size() == count * (type == 'd' ? 8 : 4));
  489. const uint32_t count3 = count / 3;
  490. out.reserve(count3);
  491. if (type == 'd') {
  492. const double* d = reinterpret_cast<const double*>(&buff[0]);
  493. for (unsigned int i = 0; i < count3; ++i, d += 3) {
  494. out.push_back(aiVector3D(static_cast<float>(d[0]),
  495. static_cast<float>(d[1]),
  496. static_cast<float>(d[2])));
  497. }
  498. }
  499. else if (type == 'f') {
  500. const float* f = reinterpret_cast<const float*>(&buff[0]);
  501. for (unsigned int i = 0; i < count3; ++i, f += 3) {
  502. out.push_back(aiVector3D(f[0],f[1],f[2]));
  503. }
  504. }
  505. return;
  506. }
  507. const size_t dim = ParseTokenAsDim(*tok[0]);
  508. // may throw bad_alloc if the input is rubbish, but this need
  509. // not to be prevented - importing would fail but we wouldn't
  510. // crash since assimp handles this case properly.
  511. out.reserve(dim);
  512. const Scope& scope = GetRequiredScope(el);
  513. const Element& a = GetRequiredElement(scope,"a",&el);
  514. if (a.Tokens().size() % 3 != 0) {
  515. ParseError("number of floats is not a multiple of three (3)",&el);
  516. }
  517. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  518. aiVector3D v;
  519. v.x = ParseTokenAsFloat(**it++);
  520. v.y = ParseTokenAsFloat(**it++);
  521. v.z = ParseTokenAsFloat(**it++);
  522. out.push_back(v);
  523. }
  524. }
  525. // ------------------------------------------------------------------------------------------------
  526. // read an array of color4 tuples
  527. void ParseVectorDataArray(std::vector<aiColor4D>& out, const Element& el)
  528. {
  529. out.clear();
  530. const TokenList& tok = el.Tokens();
  531. if(tok.empty()) {
  532. ParseError("unexpected empty element",&el);
  533. }
  534. if(tok[0]->IsBinary()) {
  535. const char* data = tok[0]->begin(), *end = tok[0]->end();
  536. char type;
  537. uint32_t count;
  538. ReadBinaryDataArrayHead(data, end, type, count, el);
  539. if(count % 4 != 0) {
  540. ParseError("number of floats is not a multiple of four (4) (binary)",&el);
  541. }
  542. if(!count) {
  543. return;
  544. }
  545. if (type != 'd' && type != 'f') {
  546. ParseError("expected float or double array (binary)",&el);
  547. }
  548. std::vector<char> buff;
  549. ReadBinaryDataArray(type, count, data, end, buff, el);
  550. ai_assert(data == end);
  551. ai_assert(buff.size() == count * (type == 'd' ? 8 : 4));
  552. const uint32_t count4 = count / 4;
  553. out.reserve(count4);
  554. if (type == 'd') {
  555. const double* d = reinterpret_cast<const double*>(&buff[0]);
  556. for (unsigned int i = 0; i < count4; ++i, d += 4) {
  557. out.push_back(aiColor4D(static_cast<float>(d[0]),
  558. static_cast<float>(d[1]),
  559. static_cast<float>(d[2]),
  560. static_cast<float>(d[3])));
  561. }
  562. }
  563. else if (type == 'f') {
  564. const float* f = reinterpret_cast<const float*>(&buff[0]);
  565. for (unsigned int i = 0; i < count4; ++i, f += 4) {
  566. out.push_back(aiColor4D(f[0],f[1],f[2],f[3]));
  567. }
  568. }
  569. return;
  570. }
  571. const size_t dim = ParseTokenAsDim(*tok[0]);
  572. // see notes in ParseVectorDataArray() above
  573. out.reserve(dim);
  574. const Scope& scope = GetRequiredScope(el);
  575. const Element& a = GetRequiredElement(scope,"a",&el);
  576. if (a.Tokens().size() % 4 != 0) {
  577. ParseError("number of floats is not a multiple of four (4)",&el);
  578. }
  579. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  580. aiColor4D v;
  581. v.r = ParseTokenAsFloat(**it++);
  582. v.g = ParseTokenAsFloat(**it++);
  583. v.b = ParseTokenAsFloat(**it++);
  584. v.a = ParseTokenAsFloat(**it++);
  585. out.push_back(v);
  586. }
  587. }
  588. // ------------------------------------------------------------------------------------------------
  589. // read an array of float2 tuples
  590. void ParseVectorDataArray(std::vector<aiVector2D>& out, const Element& el)
  591. {
  592. out.clear();
  593. const TokenList& tok = el.Tokens();
  594. if(tok.empty()) {
  595. ParseError("unexpected empty element",&el);
  596. }
  597. if(tok[0]->IsBinary()) {
  598. const char* data = tok[0]->begin(), *end = tok[0]->end();
  599. char type;
  600. uint32_t count;
  601. ReadBinaryDataArrayHead(data, end, type, count, el);
  602. if(count % 2 != 0) {
  603. ParseError("number of floats is not a multiple of two (2) (binary)",&el);
  604. }
  605. if(!count) {
  606. return;
  607. }
  608. if (type != 'd' && type != 'f') {
  609. ParseError("expected float or double array (binary)",&el);
  610. }
  611. std::vector<char> buff;
  612. ReadBinaryDataArray(type, count, data, end, buff, el);
  613. ai_assert(data == end);
  614. ai_assert(buff.size() == count * (type == 'd' ? 8 : 4));
  615. const uint32_t count2 = count / 2;
  616. out.reserve(count2);
  617. if (type == 'd') {
  618. const double* d = reinterpret_cast<const double*>(&buff[0]);
  619. for (unsigned int i = 0; i < count2; ++i, d += 2) {
  620. out.push_back(aiVector2D(static_cast<float>(d[0]),
  621. static_cast<float>(d[1])));
  622. }
  623. }
  624. else if (type == 'f') {
  625. const float* f = reinterpret_cast<const float*>(&buff[0]);
  626. for (unsigned int i = 0; i < count2; ++i, f += 2) {
  627. out.push_back(aiVector2D(f[0],f[1]));
  628. }
  629. }
  630. return;
  631. }
  632. const size_t dim = ParseTokenAsDim(*tok[0]);
  633. // see notes in ParseVectorDataArray() above
  634. out.reserve(dim);
  635. const Scope& scope = GetRequiredScope(el);
  636. const Element& a = GetRequiredElement(scope,"a",&el);
  637. if (a.Tokens().size() % 2 != 0) {
  638. ParseError("number of floats is not a multiple of two (2)",&el);
  639. }
  640. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  641. aiVector2D v;
  642. v.x = ParseTokenAsFloat(**it++);
  643. v.y = ParseTokenAsFloat(**it++);
  644. out.push_back(v);
  645. }
  646. }
  647. // ------------------------------------------------------------------------------------------------
  648. // read an array of ints
  649. void ParseVectorDataArray(std::vector<int>& out, const Element& el)
  650. {
  651. out.clear();
  652. const TokenList& tok = el.Tokens();
  653. if(tok.empty()) {
  654. ParseError("unexpected empty element",&el);
  655. }
  656. if(tok[0]->IsBinary()) {
  657. const char* data = tok[0]->begin(), *end = tok[0]->end();
  658. char type;
  659. uint32_t count;
  660. ReadBinaryDataArrayHead(data, end, type, count, el);
  661. if(!count) {
  662. return;
  663. }
  664. if (type != 'i') {
  665. ParseError("expected int array (binary)",&el);
  666. }
  667. std::vector<char> buff;
  668. ReadBinaryDataArray(type, count, data, end, buff, el);
  669. ai_assert(data == end);
  670. ai_assert(buff.size() == count * 4);
  671. out.reserve(count);
  672. const int32_t* ip = reinterpret_cast<const int32_t*>(&buff[0]);
  673. for (unsigned int i = 0; i < count; ++i, ++ip) {
  674. BE_NCONST int32_t val = *ip;
  675. AI_SWAP4(val);
  676. out.push_back(val);
  677. }
  678. return;
  679. }
  680. const size_t dim = ParseTokenAsDim(*tok[0]);
  681. // see notes in ParseVectorDataArray()
  682. out.reserve(dim);
  683. const Scope& scope = GetRequiredScope(el);
  684. const Element& a = GetRequiredElement(scope,"a",&el);
  685. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  686. const int ival = ParseTokenAsInt(**it++);
  687. out.push_back(ival);
  688. }
  689. }
  690. // ------------------------------------------------------------------------------------------------
  691. // read an array of floats
  692. void ParseVectorDataArray(std::vector<float>& out, const Element& el)
  693. {
  694. out.clear();
  695. const TokenList& tok = el.Tokens();
  696. if(tok.empty()) {
  697. ParseError("unexpected empty element",&el);
  698. }
  699. if(tok[0]->IsBinary()) {
  700. const char* data = tok[0]->begin(), *end = tok[0]->end();
  701. char type;
  702. uint32_t count;
  703. ReadBinaryDataArrayHead(data, end, type, count, el);
  704. if(!count) {
  705. return;
  706. }
  707. if (type != 'd' && type != 'f') {
  708. ParseError("expected float or double array (binary)",&el);
  709. }
  710. std::vector<char> buff;
  711. ReadBinaryDataArray(type, count, data, end, buff, el);
  712. ai_assert(data == end);
  713. ai_assert(buff.size() == count * (type == 'd' ? 8 : 4));
  714. if (type == 'd') {
  715. const double* d = reinterpret_cast<const double*>(&buff[0]);
  716. for (unsigned int i = 0; i < count; ++i, ++d) {
  717. out.push_back(static_cast<float>(*d));
  718. }
  719. }
  720. else if (type == 'f') {
  721. const float* f = reinterpret_cast<const float*>(&buff[0]);
  722. for (unsigned int i = 0; i < count; ++i, ++f) {
  723. out.push_back(*f);
  724. }
  725. }
  726. return;
  727. }
  728. const size_t dim = ParseTokenAsDim(*tok[0]);
  729. // see notes in ParseVectorDataArray()
  730. out.reserve(dim);
  731. const Scope& scope = GetRequiredScope(el);
  732. const Element& a = GetRequiredElement(scope,"a",&el);
  733. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  734. const float ival = ParseTokenAsFloat(**it++);
  735. out.push_back(ival);
  736. }
  737. }
  738. // ------------------------------------------------------------------------------------------------
  739. // read an array of uints
  740. void ParseVectorDataArray(std::vector<unsigned int>& out, const Element& el)
  741. {
  742. out.clear();
  743. const TokenList& tok = el.Tokens();
  744. if(tok.empty()) {
  745. ParseError("unexpected empty element",&el);
  746. }
  747. if(tok[0]->IsBinary()) {
  748. const char* data = tok[0]->begin(), *end = tok[0]->end();
  749. char type;
  750. uint32_t count;
  751. ReadBinaryDataArrayHead(data, end, type, count, el);
  752. if(!count) {
  753. return;
  754. }
  755. if (type != 'i') {
  756. ParseError("expected (u)int array (binary)",&el);
  757. }
  758. std::vector<char> buff;
  759. ReadBinaryDataArray(type, count, data, end, buff, el);
  760. ai_assert(data == end);
  761. ai_assert(buff.size() == count * 4);
  762. out.reserve(count);
  763. const int32_t* ip = reinterpret_cast<const int32_t*>(&buff[0]);
  764. for (unsigned int i = 0; i < count; ++i, ++ip) {
  765. BE_NCONST int32_t val = *ip;
  766. if(val < 0) {
  767. ParseError("encountered negative integer index (binary)");
  768. }
  769. AI_SWAP4(val);
  770. out.push_back(val);
  771. }
  772. return;
  773. }
  774. const size_t dim = ParseTokenAsDim(*tok[0]);
  775. // see notes in ParseVectorDataArray()
  776. out.reserve(dim);
  777. const Scope& scope = GetRequiredScope(el);
  778. const Element& a = GetRequiredElement(scope,"a",&el);
  779. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  780. const int ival = ParseTokenAsInt(**it++);
  781. if(ival < 0) {
  782. ParseError("encountered negative integer index");
  783. }
  784. out.push_back(static_cast<unsigned int>(ival));
  785. }
  786. }
  787. // ------------------------------------------------------------------------------------------------
  788. // read an array of uint64_ts
  789. void ParseVectorDataArray(std::vector<uint64_t>& out, const Element& el)
  790. {
  791. out.clear();
  792. const TokenList& tok = el.Tokens();
  793. if(tok.empty()) {
  794. ParseError("unexpected empty element",&el);
  795. }
  796. if(tok[0]->IsBinary()) {
  797. const char* data = tok[0]->begin(), *end = tok[0]->end();
  798. char type;
  799. uint32_t count;
  800. ReadBinaryDataArrayHead(data, end, type, count, el);
  801. if(!count) {
  802. return;
  803. }
  804. if (type != 'l') {
  805. ParseError("expected long array (binary)",&el);
  806. }
  807. std::vector<char> buff;
  808. ReadBinaryDataArray(type, count, data, end, buff, el);
  809. ai_assert(data == end);
  810. ai_assert(buff.size() == count * 8);
  811. out.reserve(count);
  812. const uint64_t* ip = reinterpret_cast<const uint64_t*>(&buff[0]);
  813. for (unsigned int i = 0; i < count; ++i, ++ip) {
  814. BE_NCONST uint64_t val = *ip;
  815. AI_SWAP8(val);
  816. out.push_back(val);
  817. }
  818. return;
  819. }
  820. const size_t dim = ParseTokenAsDim(*tok[0]);
  821. // see notes in ParseVectorDataArray()
  822. out.reserve(dim);
  823. const Scope& scope = GetRequiredScope(el);
  824. const Element& a = GetRequiredElement(scope,"a",&el);
  825. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  826. const uint64_t ival = ParseTokenAsID(**it++);
  827. out.push_back(ival);
  828. }
  829. }
  830. // ------------------------------------------------------------------------------------------------
  831. aiMatrix4x4 ReadMatrix(const Element& element)
  832. {
  833. std::vector<float> values;
  834. ParseVectorDataArray(values,element);
  835. if(values.size() != 16) {
  836. ParseError("expected 16 matrix elements");
  837. }
  838. aiMatrix4x4 result;
  839. result.a1 = values[0];
  840. result.a2 = values[1];
  841. result.a3 = values[2];
  842. result.a4 = values[3];
  843. result.b1 = values[4];
  844. result.b2 = values[5];
  845. result.b3 = values[6];
  846. result.b4 = values[7];
  847. result.c1 = values[8];
  848. result.c2 = values[9];
  849. result.c3 = values[10];
  850. result.c4 = values[11];
  851. result.d1 = values[12];
  852. result.d2 = values[13];
  853. result.d3 = values[14];
  854. result.d4 = values[15];
  855. result.Transpose();
  856. return result;
  857. }
  858. // ------------------------------------------------------------------------------------------------
  859. // wrapper around ParseTokenAsString() with ParseError handling
  860. std::string ParseTokenAsString(const Token& t)
  861. {
  862. const char* err;
  863. const std::string& i = ParseTokenAsString(t,err);
  864. if(err) {
  865. ParseError(err,t);
  866. }
  867. return i;
  868. }
  869. // ------------------------------------------------------------------------------------------------
  870. // extract a required element from a scope, abort if the element cannot be found
  871. const Element& GetRequiredElement(const Scope& sc, const std::string& index, const Element* element /*= NULL*/)
  872. {
  873. const Element* el = sc[index];
  874. if(!el) {
  875. ParseError("did not find required element \"" + index + "\"",element);
  876. }
  877. return *el;
  878. }
  879. // ------------------------------------------------------------------------------------------------
  880. // extract required compound scope
  881. const Scope& GetRequiredScope(const Element& el)
  882. {
  883. const Scope* const s = el.Compound();
  884. if(!s) {
  885. ParseError("expected compound scope",&el);
  886. }
  887. return *s;
  888. }
  889. // ------------------------------------------------------------------------------------------------
  890. // get token at a particular index
  891. const Token& GetRequiredToken(const Element& el, unsigned int index)
  892. {
  893. const TokenList& t = el.Tokens();
  894. if(index >= t.size()) {
  895. ParseError(Formatter::format( "missing token at index " ) << index,&el);
  896. }
  897. return *t[index];
  898. }
  899. // ------------------------------------------------------------------------------------------------
  900. // wrapper around ParseTokenAsID() with ParseError handling
  901. uint64_t ParseTokenAsID(const Token& t)
  902. {
  903. const char* err;
  904. const uint64_t i = ParseTokenAsID(t,err);
  905. if(err) {
  906. ParseError(err,t);
  907. }
  908. return i;
  909. }
  910. // ------------------------------------------------------------------------------------------------
  911. // wrapper around ParseTokenAsDim() with ParseError handling
  912. size_t ParseTokenAsDim(const Token& t)
  913. {
  914. const char* err;
  915. const size_t i = ParseTokenAsDim(t,err);
  916. if(err) {
  917. ParseError(err,t);
  918. }
  919. return i;
  920. }
  921. // ------------------------------------------------------------------------------------------------
  922. // wrapper around ParseTokenAsFloat() with ParseError handling
  923. float ParseTokenAsFloat(const Token& t)
  924. {
  925. const char* err;
  926. const float i = ParseTokenAsFloat(t,err);
  927. if(err) {
  928. ParseError(err,t);
  929. }
  930. return i;
  931. }
  932. // ------------------------------------------------------------------------------------------------
  933. // wrapper around ParseTokenAsInt() with ParseError handling
  934. int ParseTokenAsInt(const Token& t)
  935. {
  936. const char* err;
  937. const int i = ParseTokenAsInt(t,err);
  938. if(err) {
  939. ParseError(err,t);
  940. }
  941. return i;
  942. }
  943. } // !FBX
  944. } // !Assimp
  945. #endif