XFileParser.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development 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 Development 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 Implementation of the XFile parser helper class */
  35. #include "XFileParser.h"
  36. #include "XFileHelper.h"
  37. #include "BaseImporter.h"
  38. #include "fast_atof.h"
  39. #include <boost/format.hpp>
  40. using namespace Assimp;
  41. using namespace Assimp::XFile;
  42. // ------------------------------------------------------------------------------------------------
  43. // Constructor. Creates a data structure out of the XFile given in the memory block.
  44. XFileParser::XFileParser( const std::vector<char>& pBuffer)
  45. {
  46. mMajorVersion = mMinorVersion = 0;
  47. mIsBinaryFormat = false;
  48. mBinaryNumCount = 0;
  49. P = End = NULL;
  50. mLineNumber = 0;
  51. mScene = NULL;
  52. // set up memory pointers
  53. P = &pBuffer.front();
  54. End = P + pBuffer.size();
  55. // check header
  56. if( strncmp( P, "xof ", 4) != 0)
  57. throw new ImportErrorException( "Header mismatch, file is not an XFile.");
  58. // read version. It comes in a four byte format such as "0302"
  59. mMajorVersion = (unsigned int)(P[4] - 48) * 10 + (unsigned int)(P[5] - 48);
  60. mMinorVersion = (unsigned int)(P[6] - 48) * 10 + (unsigned int)(P[7] - 48);
  61. // read format
  62. if( strncmp( P + 8, "txt ", 4) == 0)
  63. mIsBinaryFormat = false;
  64. else if( strncmp( P + 8, "bin ", 4) == 0)
  65. mIsBinaryFormat = true;
  66. else
  67. ThrowException( "Unsupported xfile format");
  68. // float size
  69. mBinaryFloatSize = (unsigned int)(P[12] - 48) * 1000
  70. + (unsigned int)(P[13] - 48) * 100
  71. + (unsigned int)(P[14] - 48) * 10
  72. + (unsigned int)(P[15] - 48);
  73. if( mBinaryFloatSize != 32 && mBinaryFloatSize != 64)
  74. ThrowException( boost::str( boost::format( "Unknown float size %1% specified in xfile header.") % mBinaryFloatSize));
  75. // start reading here
  76. P += 16;
  77. ReadUntilEndOfLine();
  78. mScene = new Scene;
  79. ParseFile();
  80. // filter the imported hierarchy for some degenerated cases
  81. if( mScene->mRootNode)
  82. FilterHierarchy( mScene->mRootNode);
  83. }
  84. // ------------------------------------------------------------------------------------------------
  85. // Destructor. Destroys all imported data along with it
  86. XFileParser::~XFileParser()
  87. {
  88. // kill everything we created
  89. delete mScene;
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. void XFileParser::ParseFile()
  93. {
  94. while( 1)
  95. {
  96. // read name of next object
  97. std::string objectName = GetNextToken();
  98. if (objectName.length() == 0)
  99. break;
  100. // parse specific object
  101. if( objectName == "template")
  102. ParseDataObjectTemplate();
  103. else
  104. if( objectName == "Frame")
  105. ParseDataObjectFrame( NULL);
  106. else
  107. if( objectName == "Mesh")
  108. {
  109. // some meshes have no frames at all
  110. Mesh* mesh = new Mesh;
  111. ParseDataObjectMesh( mesh);
  112. mScene->mGlobalMeshes.push_back( mesh);
  113. } else
  114. if( objectName == "AnimTicksPerSecond")
  115. ParseDataObjectAnimTicksPerSecond();
  116. else
  117. if( objectName == "AnimationSet")
  118. ParseDataObjectAnimationSet();
  119. else
  120. if( objectName == "Material")
  121. {
  122. // Material outside of a mesh or node
  123. Material material;
  124. ParseDataObjectMaterial( &material);
  125. mScene->mGlobalMaterials.push_back( material);
  126. } else
  127. if( objectName == "}")
  128. {
  129. // whatever?
  130. // os::Printer::log("} found in dataObject", ELL_WARNING);
  131. } else
  132. {
  133. // unknown format
  134. //os::Printer::log("Unknown data object in animation of .x file", objectName.c_str(), ELL_WARNING);
  135. ParseUnknownDataObject();
  136. }
  137. }
  138. }
  139. // ------------------------------------------------------------------------------------------------
  140. void XFileParser::ParseDataObjectTemplate()
  141. {
  142. // parse a template data object. Currently not stored.
  143. std::string name;
  144. readHeadOfDataObject( &name);
  145. // read GUID
  146. std::string guid = GetNextToken();
  147. // read and ignore data members
  148. while(true)
  149. {
  150. std::string s = GetNextToken();
  151. if( s == "}")
  152. break;
  153. if( s.length() == 0)
  154. ThrowException( "Unexpected end of file reached while parsing template definition");
  155. }
  156. }
  157. // ------------------------------------------------------------------------------------------------
  158. void XFileParser::ParseDataObjectFrame( Node* pParent)
  159. {
  160. // A coordinate frame, or "frame of reference." The Frame template
  161. // is open and can contain any object. The Direct3D extensions (D3DX)
  162. // mesh-loading functions recognize Mesh, FrameTransformMatrix, and
  163. // Frame template instances as child objects when loading a Frame
  164. // instance.
  165. std::string name;
  166. readHeadOfDataObject(&name);
  167. // create a named node and place it at its parent, if given
  168. Node* node = new Node( pParent);
  169. node->mName = name;
  170. if( pParent)
  171. {
  172. pParent->mChildren.push_back( node);
  173. } else
  174. {
  175. // there might be multiple root nodes
  176. if( mScene->mRootNode != NULL)
  177. {
  178. // place a dummy root if not there
  179. if( mScene->mRootNode->mName != "$dummy_root")
  180. {
  181. Node* exroot = mScene->mRootNode;
  182. mScene->mRootNode = new Node( NULL);
  183. mScene->mRootNode->mName = "$dummy_root";
  184. mScene->mRootNode->mChildren.push_back( exroot);
  185. exroot->mParent = mScene->mRootNode;
  186. }
  187. // put the new node as its child instead
  188. mScene->mRootNode->mChildren.push_back( node);
  189. node->mParent = mScene->mRootNode;
  190. } else
  191. {
  192. // it's the first node imported. place it as root
  193. mScene->mRootNode = node;
  194. }
  195. }
  196. // Now inside a frame.
  197. // read tokens until closing brace is reached.
  198. while(true)
  199. {
  200. std::string objectName = GetNextToken();
  201. if (objectName.size() == 0)
  202. ThrowException( "Unexpected end of file reached while parsing frame");
  203. if( objectName == "}")
  204. break; // frame finished
  205. else
  206. if( objectName == "Frame")
  207. ParseDataObjectFrame( node); // child frame
  208. else
  209. if( objectName == "FrameTransformMatrix")
  210. ParseDataObjectTransformationMatrix( node->mTrafoMatrix);
  211. else
  212. if( objectName == "Mesh")
  213. {
  214. Mesh* mesh = new Mesh;
  215. node->mMeshes.push_back( mesh);
  216. ParseDataObjectMesh( mesh);
  217. } else
  218. {
  219. // os::Printer::log("Unknown data object in frame in x file", objectName.c_str(), ELL_WARNING);
  220. ParseUnknownDataObject();
  221. }
  222. }
  223. }
  224. // ------------------------------------------------------------------------------------------------
  225. void XFileParser::ParseDataObjectTransformationMatrix( aiMatrix4x4& pMatrix)
  226. {
  227. // read header, we're not interested if it has a name
  228. readHeadOfDataObject();
  229. // read its components
  230. pMatrix.a1 = ReadFloat(); pMatrix.b1 = ReadFloat();
  231. pMatrix.c1 = ReadFloat(); pMatrix.d1 = ReadFloat();
  232. pMatrix.a2 = ReadFloat(); pMatrix.b2 = ReadFloat();
  233. pMatrix.c2 = ReadFloat(); pMatrix.d2 = ReadFloat();
  234. pMatrix.a3 = ReadFloat(); pMatrix.b3 = ReadFloat();
  235. pMatrix.c3 = ReadFloat(); pMatrix.d3 = ReadFloat();
  236. pMatrix.a4 = ReadFloat(); pMatrix.b4 = ReadFloat();
  237. pMatrix.c4 = ReadFloat(); pMatrix.d4 = ReadFloat();
  238. // trailing symbols
  239. CheckForSemicolon();
  240. CheckForClosingBrace();
  241. }
  242. // ------------------------------------------------------------------------------------------------
  243. void XFileParser::ParseDataObjectMesh( Mesh* pMesh)
  244. {
  245. std::string name;
  246. readHeadOfDataObject( &name);
  247. // read vertex count
  248. unsigned int numVertices = ReadInt();
  249. pMesh->mPositions.resize( numVertices);
  250. // read vertices
  251. for( unsigned int a = 0; a < numVertices; a++)
  252. pMesh->mPositions[a] = ReadVector3();
  253. // read position faces
  254. unsigned int numPosFaces = ReadInt();
  255. pMesh->mPosFaces.resize( numPosFaces);
  256. for( unsigned int a = 0; a < numPosFaces; a++)
  257. {
  258. unsigned int numIndices = ReadInt();
  259. if( numIndices < 3)
  260. ThrowException( boost::str( boost::format( "Invalid index count %1% for face %2%.") % numIndices % a));
  261. // read indices
  262. Face& face = pMesh->mPosFaces[a];
  263. for( unsigned int b = 0; b < numIndices; b++)
  264. face.mIndices.push_back( ReadInt());
  265. CheckForSeparator();
  266. }
  267. // here, other data objects may follow
  268. while(true)
  269. {
  270. std::string objectName = GetNextToken();
  271. if( objectName.size() == 0)
  272. ThrowException( "Unexpected end of file while parsing mesh structure");
  273. else
  274. if( objectName == "}")
  275. break; // mesh finished
  276. else
  277. if( objectName == "MeshNormals")
  278. ParseDataObjectMeshNormals( pMesh);
  279. else
  280. if( objectName == "MeshTextureCoords")
  281. ParseDataObjectMeshTextureCoords( pMesh);
  282. else
  283. if( objectName == "MeshVertexColors")
  284. ParseDataObjectMeshVertexColors( pMesh);
  285. else
  286. if( objectName == "MeshMaterialList")
  287. ParseDataObjectMeshMaterialList( pMesh);
  288. else
  289. if( objectName == "VertexDuplicationIndices")
  290. ParseUnknownDataObject(); // we'll ignore vertex duplication indices
  291. else
  292. if( objectName == "XSkinMeshHeader")
  293. ParseDataObjectSkinMeshHeader( pMesh);
  294. else
  295. if( objectName == "SkinWeights")
  296. ParseDataObjectSkinWeights( pMesh);
  297. else
  298. {
  299. //os::Printer::log("Unknown data object in mesh in x file", objectName.c_str(), ELL_WARNING);
  300. ParseUnknownDataObject();
  301. }
  302. }
  303. }
  304. // ------------------------------------------------------------------------------------------------
  305. void XFileParser::ParseDataObjectSkinWeights( Mesh *pMesh)
  306. {
  307. readHeadOfDataObject();
  308. std::string transformNodeName;
  309. GetNextTokenAsString( transformNodeName);
  310. pMesh->mBones.push_back( Bone());
  311. Bone& bone = pMesh->mBones.back();
  312. bone.mName = transformNodeName;
  313. // read vertex weights
  314. unsigned int numWeights = ReadInt();
  315. bone.mWeights.reserve( numWeights);
  316. for( unsigned int a = 0; a < numWeights; a++)
  317. {
  318. BoneWeight weight;
  319. weight.mVertex = ReadInt();
  320. bone.mWeights.push_back( weight);
  321. }
  322. // read vertex weights
  323. for( unsigned int a = 0; a < numWeights; a++)
  324. bone.mWeights[a].mWeight = ReadFloat();
  325. // read matrix offset
  326. bone.mOffsetMatrix.a1 = ReadFloat(); bone.mOffsetMatrix.b1 = ReadFloat();
  327. bone.mOffsetMatrix.c1 = ReadFloat(); bone.mOffsetMatrix.d1 = ReadFloat();
  328. bone.mOffsetMatrix.a2 = ReadFloat(); bone.mOffsetMatrix.b2 = ReadFloat();
  329. bone.mOffsetMatrix.c2 = ReadFloat(); bone.mOffsetMatrix.d2 = ReadFloat();
  330. bone.mOffsetMatrix.a3 = ReadFloat(); bone.mOffsetMatrix.b3 = ReadFloat();
  331. bone.mOffsetMatrix.c3 = ReadFloat(); bone.mOffsetMatrix.d3 = ReadFloat();
  332. bone.mOffsetMatrix.a4 = ReadFloat(); bone.mOffsetMatrix.b4 = ReadFloat();
  333. bone.mOffsetMatrix.c4 = ReadFloat(); bone.mOffsetMatrix.d4 = ReadFloat();
  334. CheckForSemicolon();
  335. CheckForClosingBrace();
  336. }
  337. // ------------------------------------------------------------------------------------------------
  338. void XFileParser::ParseDataObjectSkinMeshHeader( Mesh* pMesh)
  339. {
  340. readHeadOfDataObject();
  341. unsigned int maxSkinWeightsPerVertex = ReadInt();
  342. unsigned int maxSkinWeightsPerFace = ReadInt();
  343. unsigned int numBonesInMesh = ReadInt();
  344. CheckForClosingBrace();
  345. }
  346. // ------------------------------------------------------------------------------------------------
  347. void XFileParser::ParseDataObjectMeshNormals( Mesh* pMesh)
  348. {
  349. readHeadOfDataObject();
  350. // read count
  351. unsigned int numNormals = ReadInt();
  352. pMesh->mNormals.resize( numNormals);
  353. // read normal vectors
  354. for( unsigned int a = 0; a < numNormals; a++)
  355. pMesh->mNormals[a] = ReadVector3();
  356. // read normal indices
  357. unsigned int numFaces = ReadInt();
  358. if( numFaces != pMesh->mPosFaces.size())
  359. ThrowException( "Normal face count does not match vertex face count.");
  360. for( unsigned int a = 0; a < numFaces; a++)
  361. {
  362. unsigned int numIndices = ReadInt();
  363. pMesh->mNormFaces.push_back( Face());
  364. Face& face = pMesh->mNormFaces.back();
  365. for( unsigned int b = 0; b < numIndices; b++)
  366. face.mIndices.push_back( ReadInt());
  367. CheckForSeparator();
  368. }
  369. CheckForClosingBrace();
  370. }
  371. // ------------------------------------------------------------------------------------------------
  372. void XFileParser::ParseDataObjectMeshTextureCoords( Mesh* pMesh)
  373. {
  374. readHeadOfDataObject();
  375. std::vector<aiVector2D>& coords = pMesh->mTexCoords[pMesh->mNumTextures++];
  376. unsigned int numCoords = ReadInt();
  377. if( numCoords != pMesh->mPositions.size())
  378. ThrowException( "Texture coord count does not match vertex count");
  379. coords.resize( numCoords);
  380. for( unsigned int a = 0; a < numCoords; a++)
  381. coords[a] = ReadVector2();
  382. CheckForClosingBrace();
  383. }
  384. // ------------------------------------------------------------------------------------------------
  385. void XFileParser::ParseDataObjectMeshVertexColors( Mesh* pMesh)
  386. {
  387. readHeadOfDataObject();
  388. std::vector<aiColor4D>& colors = pMesh->mColors[pMesh->mNumColorSets++];
  389. unsigned int numColors = ReadInt();
  390. if( numColors != pMesh->mPositions.size())
  391. ThrowException( "Vertex color count does not match vertex count");
  392. colors.resize( numColors, aiColor4D( 0, 0, 0, 1));
  393. for( unsigned int a = 0; a < numColors; a++)
  394. {
  395. unsigned int index = ReadInt();
  396. if( index >= pMesh->mPositions.size())
  397. ThrowException( "Vertex color index out of bounds");
  398. colors[index] = ReadRGBA();
  399. }
  400. CheckForSemicolon();
  401. CheckForClosingBrace();
  402. }
  403. // ------------------------------------------------------------------------------------------------
  404. void XFileParser::ParseDataObjectMeshMaterialList( Mesh* pMesh)
  405. {
  406. readHeadOfDataObject();
  407. // read material count
  408. unsigned int numMaterials = ReadInt();
  409. // read non triangulated face material index count
  410. unsigned int numMatIndices = ReadInt();
  411. // some models have a material index count of 1... to be able to read them we
  412. // replicate this single material index on every face
  413. if( numMatIndices != pMesh->mPosFaces.size() && numMatIndices != 1)
  414. ThrowException( "Per-Face material index count does not match face count.");
  415. // read per-face material indices
  416. for( unsigned int a = 0; a < numMatIndices; a++)
  417. pMesh->mFaceMaterials.push_back( ReadInt());
  418. // in version 03.02, the face indices end with two semicolons.
  419. // commented out version check, as version 03.03 exported from blender also has 2 semicolons
  420. if( !mIsBinaryFormat) // && MajorVersion == 3 && MinorVersion <= 2)
  421. {
  422. if( *P == ';')
  423. ++P;
  424. }
  425. // if there was only a single material index, replicate it on all faces
  426. while( pMesh->mFaceMaterials.size() < pMesh->mPosFaces.size())
  427. pMesh->mFaceMaterials.push_back( pMesh->mFaceMaterials.front());
  428. // read following data objects
  429. while(true)
  430. {
  431. std::string objectName = GetNextToken();
  432. if( objectName.size() == 0)
  433. ThrowException( "Unexpected end of file while parsing mesh material list.");
  434. else
  435. if( objectName == "}")
  436. break; // material list finished
  437. else
  438. if( objectName == "{")
  439. {
  440. // template materials
  441. std::string matName = GetNextToken();
  442. Material material;
  443. material.mIsReference = true;
  444. material.mName = matName;
  445. pMesh->mMaterials.push_back( material);
  446. CheckForClosingBrace(); // skip }
  447. } else
  448. if( objectName == "Material")
  449. {
  450. pMesh->mMaterials.push_back( Material());
  451. ParseDataObjectMaterial( &pMesh->mMaterials.back());
  452. } else
  453. if( objectName == ";")
  454. {
  455. // ignore
  456. } else
  457. {
  458. // os::Printer::log("Unknown data object in material list in x file", objectName.c_str(), ELL_WARNING);
  459. ParseUnknownDataObject();
  460. }
  461. }
  462. }
  463. // ------------------------------------------------------------------------------------------------
  464. void XFileParser::ParseDataObjectMaterial( Material* pMaterial)
  465. {
  466. std::string matName;
  467. readHeadOfDataObject( &matName);
  468. pMaterial->mName = matName;
  469. pMaterial->mIsReference = false;
  470. // read material values
  471. pMaterial->mDiffuse = ReadRGBA();
  472. pMaterial->mSpecularExponent = ReadFloat();
  473. pMaterial->mSpecular = ReadRGB();
  474. pMaterial->mEmissive = ReadRGB();
  475. // read other data objects
  476. while(true)
  477. {
  478. std::string objectName = GetNextToken();
  479. if( objectName.size() == 0)
  480. ThrowException( "Unexpected end of file while parsing mesh material");
  481. else
  482. if( objectName == "}")
  483. break; // material finished
  484. else
  485. if( objectName == "TextureFilename" || objectName == "TextureFileName")
  486. {
  487. // some exporters write "TextureFileName" instead.
  488. std::string texname;
  489. ParseDataObjectTextureFilename( texname);
  490. pMaterial->mTextures.push_back( texname);
  491. } else
  492. {
  493. // os::Printer::log("Unknown data object in material in .x file", objectName.c_str(), ELL_WARNING);
  494. ParseUnknownDataObject();
  495. }
  496. }
  497. }
  498. // ------------------------------------------------------------------------------------------------
  499. void XFileParser::ParseDataObjectAnimTicksPerSecond()
  500. {
  501. readHeadOfDataObject();
  502. mScene->mAnimTicksPerSecond = ReadInt();
  503. CheckForClosingBrace();
  504. }
  505. // ------------------------------------------------------------------------------------------------
  506. void XFileParser::ParseDataObjectAnimationSet()
  507. {
  508. std::string animName;
  509. readHeadOfDataObject( &animName);
  510. Animation* anim = new Animation;
  511. mScene->mAnims.push_back( anim);
  512. anim->mName = animName;
  513. while(true)
  514. {
  515. std::string objectName = GetNextToken();
  516. if( objectName.length() == 0)
  517. ThrowException( "Unexpected end of file while parsing animation set.");
  518. else
  519. if( objectName == "}")
  520. break; // animation set finished
  521. else
  522. if( objectName == "Animation")
  523. ParseDataObjectAnimation( anim);
  524. else
  525. {
  526. // os::Printer::log("Unknown data object in animation set in x file", objectName.c_str(), ELL_WARNING);
  527. ParseUnknownDataObject();
  528. }
  529. }
  530. }
  531. // ------------------------------------------------------------------------------------------------
  532. void XFileParser::ParseDataObjectAnimation( Animation* pAnim)
  533. {
  534. readHeadOfDataObject();
  535. AnimBone* banim = new AnimBone;
  536. pAnim->mAnims.push_back( banim);
  537. while(true)
  538. {
  539. std::string objectName = GetNextToken();
  540. if( objectName.length() == 0)
  541. ThrowException( "Unexpected end of file while parsing animation.");
  542. else
  543. if( objectName == "}")
  544. break; // animation finished
  545. else
  546. if( objectName == "AnimationKey")
  547. ParseDataObjectAnimationKey( banim);
  548. else
  549. if( objectName == "AnimationOptions")
  550. ParseUnknownDataObject(); // not interested
  551. else
  552. if( objectName == "{")
  553. {
  554. // read frame name
  555. banim->mBoneName = GetNextToken();
  556. CheckForClosingBrace();
  557. } else
  558. {
  559. //os::Printer::log("Unknown data object in animation in x file", objectName.c_str(), ELL_WARNING);
  560. ParseUnknownDataObject();
  561. }
  562. }
  563. }
  564. // ------------------------------------------------------------------------------------------------
  565. void XFileParser::ParseDataObjectAnimationKey( AnimBone* pAnimBone)
  566. {
  567. readHeadOfDataObject();
  568. // read key type
  569. unsigned int keyType = ReadInt();
  570. // read number of keys
  571. unsigned int numKeys = ReadInt();
  572. for( unsigned int a = 0; a < numKeys; a++)
  573. {
  574. // read time
  575. unsigned int time = ReadInt();
  576. // read keys
  577. switch( keyType)
  578. {
  579. case 0: // rotation quaternion
  580. {
  581. // read count
  582. if( ReadInt() != 4)
  583. ThrowException( "Invalid number of arguments for quaternion key in animation");
  584. aiQuatKey key;
  585. key.mTime = double( time);
  586. key.mValue.w = ReadFloat();
  587. key.mValue.x = ReadFloat();
  588. key.mValue.y = ReadFloat();
  589. key.mValue.z = ReadFloat();
  590. pAnimBone->mRotKeys.push_back( key);
  591. CheckForSemicolon();
  592. break;
  593. }
  594. case 1: // scale vector
  595. case 2: // position vector
  596. {
  597. // read count
  598. if( ReadInt() != 3)
  599. ThrowException( "Invalid number of arguments for vector key in animation");
  600. aiVectorKey key;
  601. key.mTime = double( time);
  602. key.mValue = ReadVector3();
  603. if( keyType == 2)
  604. pAnimBone->mPosKeys.push_back( key);
  605. else
  606. pAnimBone->mScaleKeys.push_back( key);
  607. break;
  608. }
  609. case 3: // combined transformation matrix
  610. case 4: // denoted both as 3 or as 4
  611. {
  612. // read count
  613. if( ReadInt() != 16)
  614. ThrowException( "Invalid number of arguments for matrix key in animation");
  615. // read matrix
  616. MatrixKey key;
  617. key.mTime = double( time);
  618. key.mMatrix.a1 = ReadFloat(); key.mMatrix.b1 = ReadFloat();
  619. key.mMatrix.c1 = ReadFloat(); key.mMatrix.d1 = ReadFloat();
  620. key.mMatrix.a2 = ReadFloat(); key.mMatrix.b2 = ReadFloat();
  621. key.mMatrix.c2 = ReadFloat(); key.mMatrix.d2 = ReadFloat();
  622. key.mMatrix.a3 = ReadFloat(); key.mMatrix.b3 = ReadFloat();
  623. key.mMatrix.c3 = ReadFloat(); key.mMatrix.d3 = ReadFloat();
  624. key.mMatrix.a4 = ReadFloat(); key.mMatrix.b4 = ReadFloat();
  625. key.mMatrix.c4 = ReadFloat(); key.mMatrix.d4 = ReadFloat();
  626. pAnimBone->mTrafoKeys.push_back( key);
  627. CheckForSemicolon();
  628. break;
  629. }
  630. default:
  631. ThrowException( boost::str( boost::format( "Unknown key type %1% in animation.") % keyType));
  632. break;
  633. } // end switch
  634. // key separator
  635. CheckForSeparator();
  636. }
  637. CheckForClosingBrace();
  638. }
  639. // ------------------------------------------------------------------------------------------------
  640. void XFileParser::ParseDataObjectTextureFilename( std::string& pName)
  641. {
  642. readHeadOfDataObject();
  643. GetNextTokenAsString( pName);
  644. CheckForClosingBrace();
  645. }
  646. // ------------------------------------------------------------------------------------------------
  647. void XFileParser::ParseUnknownDataObject()
  648. {
  649. // find opening delimiter
  650. while( true)
  651. {
  652. std::string t = GetNextToken();
  653. if( t.length() == 0)
  654. ThrowException( "Unexpected end of file while parsing unknown segment.");
  655. if( t == "{")
  656. break;
  657. }
  658. unsigned int counter = 1;
  659. // parse until closing delimiter
  660. while( counter > 0)
  661. {
  662. std::string t = GetNextToken();
  663. if( t.length() == 0)
  664. ThrowException( "Unexpected end of file while parsing unknown segment.");
  665. if( t == "{")
  666. ++counter;
  667. else
  668. if( t == "}")
  669. --counter;
  670. }
  671. }
  672. // ------------------------------------------------------------------------------------------------
  673. //! checks for closing curly brace
  674. void XFileParser::CheckForClosingBrace()
  675. {
  676. if( GetNextToken() != "}")
  677. ThrowException( "Closing brace expected.");
  678. }
  679. // ------------------------------------------------------------------------------------------------
  680. //! checks for one following semicolon
  681. void XFileParser::CheckForSemicolon()
  682. {
  683. if( mIsBinaryFormat)
  684. return;
  685. if( GetNextToken() != ";")
  686. ThrowException( "Semicolon expected.");
  687. }
  688. // ------------------------------------------------------------------------------------------------
  689. //! checks for a separator char, either a ',' or a ';'
  690. void XFileParser::CheckForSeparator()
  691. {
  692. if( mIsBinaryFormat)
  693. return;
  694. std::string token = GetNextToken();
  695. if( token != "," && token != ";")
  696. ThrowException( "Separator character (';' or ',') expected.");
  697. }
  698. // ------------------------------------------------------------------------------------------------
  699. void XFileParser::readHeadOfDataObject( std::string* poName)
  700. {
  701. std::string nameOrBrace = GetNextToken();
  702. if( nameOrBrace != "{")
  703. {
  704. if( poName)
  705. *poName = nameOrBrace;
  706. if( GetNextToken() != "{")
  707. ThrowException( "Opening brace expected.");
  708. }
  709. }
  710. // ------------------------------------------------------------------------------------------------
  711. std::string XFileParser::GetNextToken()
  712. {
  713. std::string s;
  714. // process binary-formatted file
  715. if( mIsBinaryFormat)
  716. {
  717. // in binary mode it will only return NAME and STRING token
  718. // and (correctly) skip over other tokens.
  719. unsigned int tok = ReadBinWord();
  720. unsigned int len;
  721. // standalone tokens
  722. switch( tok)
  723. {
  724. case 1:
  725. // name token
  726. len = ReadBinDWord();
  727. s = std::string(P, len);
  728. P += len;
  729. return s;
  730. case 2:
  731. // string token
  732. len = ReadBinDWord();
  733. s = std::string(P, len);
  734. P += (len + 2);
  735. return s;
  736. case 3:
  737. // integer token
  738. P += 4;
  739. return "<integer>";
  740. case 5:
  741. // GUID token
  742. P += 16;
  743. return "<guid>";
  744. case 6:
  745. len = ReadBinDWord();
  746. P += (len * 4);
  747. return "<int_list>";
  748. case 7:
  749. len = ReadBinDWord();
  750. P += (len * mBinaryFloatSize);
  751. return "<flt_list>";
  752. case 0x0a:
  753. return "{";
  754. case 0x0b:
  755. return "}";
  756. case 0x0c:
  757. return "(";
  758. case 0x0d:
  759. return ")";
  760. case 0x0e:
  761. return "[";
  762. case 0x0f:
  763. return "]";
  764. case 0x10:
  765. return "<";
  766. case 0x11:
  767. return ">";
  768. case 0x12:
  769. return ".";
  770. case 0x13:
  771. return ",";
  772. case 0x14:
  773. return ";";
  774. case 0x1f:
  775. return "template";
  776. case 0x28:
  777. return "WORD";
  778. case 0x29:
  779. return "DWORD";
  780. case 0x2a:
  781. return "FLOAT";
  782. case 0x2b:
  783. return "DOUBLE";
  784. case 0x2c:
  785. return "CHAR";
  786. case 0x2d:
  787. return "UCHAR";
  788. case 0x2e:
  789. return "SWORD";
  790. case 0x2f:
  791. return "SDWORD";
  792. case 0x30:
  793. return "void";
  794. case 0x31:
  795. return "string";
  796. case 0x32:
  797. return "unicode";
  798. case 0x33:
  799. return "cstring";
  800. case 0x34:
  801. return "array";
  802. }
  803. }
  804. // process text-formatted file
  805. else
  806. {
  807. FindNextNoneWhiteSpace();
  808. if( P >= End)
  809. return s;
  810. while( (P < End) && !isspace( (unsigned char) *P))
  811. {
  812. // either keep token delimiters when already holding a token, or return if first valid char
  813. if( *P == ';' || *P == '}' || *P == '{' || *P == ',')
  814. {
  815. if( !s.size())
  816. s.append( P++, 1);
  817. break; // stop for delimiter
  818. }
  819. s.append( P++, 1);
  820. }
  821. }
  822. return s;
  823. }
  824. // ------------------------------------------------------------------------------------------------
  825. void XFileParser::FindNextNoneWhiteSpace()
  826. {
  827. if( mIsBinaryFormat)
  828. return;
  829. while( true)
  830. {
  831. while( P < End && isspace( (unsigned char) *P))
  832. {
  833. if( *P == '\n')
  834. mLineNumber++;
  835. ++P;
  836. }
  837. if( P >= End)
  838. return;
  839. // check if this is a comment
  840. if( (P[0] == '/' && P[1] == '/') || P[0] == '#')
  841. ReadUntilEndOfLine();
  842. else
  843. break;
  844. }
  845. }
  846. // ------------------------------------------------------------------------------------------------
  847. void XFileParser::GetNextTokenAsString( std::string& poString)
  848. {
  849. if( mIsBinaryFormat)
  850. {
  851. poString = GetNextToken();
  852. return;
  853. }
  854. FindNextNoneWhiteSpace();
  855. if( P >= End)
  856. ThrowException( "Unexpected end of file while parsing string");
  857. if( *P != '"')
  858. ThrowException( "Expected quotation mark.");
  859. ++P;
  860. while( P < End && *P != '"')
  861. poString.append( P++, 1);
  862. if( P >= End-1)
  863. ThrowException( "Unexpected end of file while parsing string");
  864. if( P[1] != ';' || P[0] != '"')
  865. ThrowException( "Expected quotation mark and semicolon at the end of a string.");
  866. P+=2;
  867. }
  868. // ------------------------------------------------------------------------------------------------
  869. void XFileParser::ReadUntilEndOfLine()
  870. {
  871. if( mIsBinaryFormat)
  872. return;
  873. while( P < End)
  874. {
  875. if( *P == '\n' || *P == '\r')
  876. {
  877. ++P; mLineNumber++;
  878. return;
  879. }
  880. ++P;
  881. }
  882. }
  883. // ------------------------------------------------------------------------------------------------
  884. unsigned short XFileParser::ReadBinWord()
  885. {
  886. const unsigned char* q = (const unsigned char*) P;
  887. unsigned short tmp = q[0] | (q[1] << 8);
  888. P += 2;
  889. return tmp;
  890. }
  891. // ------------------------------------------------------------------------------------------------
  892. unsigned int XFileParser::ReadBinDWord()
  893. {
  894. const unsigned char* q = (const unsigned char*) P;
  895. unsigned int tmp = q[0] | (q[1] << 8) | (q[2] << 16) | (q[3] << 24);
  896. P += 4;
  897. return tmp;
  898. }
  899. // ------------------------------------------------------------------------------------------------
  900. unsigned int XFileParser::ReadInt()
  901. {
  902. if( mIsBinaryFormat)
  903. {
  904. if( mBinaryNumCount == 0)
  905. {
  906. unsigned short tmp = ReadBinWord(); // 0x06 or 0x03
  907. if( tmp == 0x06) // array of ints follows
  908. mBinaryNumCount = ReadBinDWord();
  909. else // single int follows
  910. mBinaryNumCount = 1;
  911. }
  912. --mBinaryNumCount;
  913. return ReadBinDWord();
  914. } else
  915. {
  916. FindNextNoneWhiteSpace();
  917. // check preceeding minus sign
  918. bool isNegative = false;
  919. if( *P == '-')
  920. {
  921. isNegative = true;
  922. P++;
  923. }
  924. // at least one digit expected
  925. if( !isdigit( *P))
  926. ThrowException( "Number expected.");
  927. // read digits
  928. unsigned int number = 0;
  929. while( P < End)
  930. {
  931. if( !isdigit( *P))
  932. break;
  933. number = number * 10 + (*P - 48);
  934. P++;
  935. }
  936. CheckForSeparator();
  937. return isNegative ? ((unsigned int) -int( number)) : number;
  938. }
  939. }
  940. // ------------------------------------------------------------------------------------------------
  941. float XFileParser::ReadFloat()
  942. {
  943. if( mIsBinaryFormat)
  944. {
  945. if( mBinaryNumCount == 0)
  946. {
  947. unsigned short tmp = ReadBinWord(); // 0x07 or 0x42
  948. if( tmp == 0x07) // array of floats following
  949. mBinaryNumCount = ReadBinDWord();
  950. else // single float following
  951. mBinaryNumCount = 1;
  952. }
  953. --mBinaryNumCount;
  954. if( mBinaryFloatSize == 8)
  955. {
  956. float result = (float) (*(double*) P);
  957. P += 8;
  958. return result;
  959. } else
  960. {
  961. float result = *(float*) P;
  962. P += 4;
  963. return result;
  964. }
  965. }
  966. // text version
  967. FindNextNoneWhiteSpace();
  968. // check for various special strings to allow reading files from faulty exporters
  969. // I mean you, Blender!
  970. if( strncmp( P, "-1.#IND00", 9) == 0)
  971. {
  972. P += 9;
  973. CheckForSeparator();
  974. return 0.0f;
  975. } else
  976. if( strncmp( P, "1.#QNAN0", 8) == 0)
  977. {
  978. P += 8;
  979. CheckForSeparator();
  980. return 0.0f;
  981. }
  982. float result = 0.0f;
  983. P = fast_atof_move( P, result);
  984. CheckForSeparator();
  985. return result;
  986. }
  987. // ------------------------------------------------------------------------------------------------
  988. aiVector2D XFileParser::ReadVector2()
  989. {
  990. aiVector2D vector;
  991. vector.x = ReadFloat();
  992. vector.y = ReadFloat();
  993. CheckForSeparator();
  994. return vector;
  995. }
  996. // ------------------------------------------------------------------------------------------------
  997. aiVector3D XFileParser::ReadVector3()
  998. {
  999. aiVector3D vector;
  1000. vector.x = ReadFloat();
  1001. vector.y = ReadFloat();
  1002. vector.z = ReadFloat();
  1003. CheckForSeparator();
  1004. return vector;
  1005. }
  1006. // ------------------------------------------------------------------------------------------------
  1007. aiColor4D XFileParser::ReadRGBA()
  1008. {
  1009. aiColor4D color;
  1010. color.r = ReadFloat();
  1011. color.g = ReadFloat();
  1012. color.b = ReadFloat();
  1013. color.a = ReadFloat();
  1014. CheckForSeparator();
  1015. return color;
  1016. }
  1017. // ------------------------------------------------------------------------------------------------
  1018. aiColor3D XFileParser::ReadRGB()
  1019. {
  1020. aiColor3D color;
  1021. color.r = ReadFloat();
  1022. color.g = ReadFloat();
  1023. color.b = ReadFloat();
  1024. CheckForSeparator();
  1025. return color;
  1026. }
  1027. // Throws an exception with a line number and the given text.
  1028. void XFileParser::ThrowException( const std::string& pText)
  1029. {
  1030. if( mIsBinaryFormat)
  1031. throw new ImportErrorException( pText);
  1032. else
  1033. throw new ImportErrorException( boost::str( boost::format( "Line %d: %s") % mLineNumber % pText));
  1034. }
  1035. // ------------------------------------------------------------------------------------------------
  1036. // Filters the imported hierarchy for some degenerated cases that some exporters produce.
  1037. void XFileParser::FilterHierarchy( XFile::Node* pNode)
  1038. {
  1039. // if the node has just a single unnamed child containing a mesh, remove
  1040. // the anonymous node inbetween. The 3DSMax kwXport plugin seems to produce this
  1041. // mess in some cases
  1042. if( pNode->mChildren.size() == 1)
  1043. {
  1044. XFile::Node* child = pNode->mChildren.front();
  1045. if( child->mName.length() == 0 && child->mMeshes.size() > 0)
  1046. {
  1047. // transfer its meshes to us
  1048. for( unsigned int a = 0; a < child->mMeshes.size(); a++)
  1049. pNode->mMeshes.push_back( child->mMeshes[a]);
  1050. child->mMeshes.clear();
  1051. // then kill it
  1052. delete child;
  1053. pNode->mChildren.clear();
  1054. }
  1055. }
  1056. // recurse
  1057. for( unsigned int a = 0; a < pNode->mChildren.size(); a++)
  1058. FilterHierarchy( pNode->mChildren[a]);
  1059. }