2
0

XFileParser.cpp 34 KB

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