ColladaParser.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. /** Implementation of the Collada parser helper*/
  2. /*
  3. ---------------------------------------------------------------------------
  4. Open Asset Import Library (ASSIMP)
  5. ---------------------------------------------------------------------------
  6. Copyright (c) 2006-2008, ASSIMP Development Team
  7. All rights reserved.
  8. Redistribution and use of this software in source and binary forms,
  9. with or without modification, are permitted provided that the following
  10. conditions are met:
  11. * Redistributions of source code must retain the above
  12. copyright notice, this list of conditions and the
  13. following disclaimer.
  14. * Redistributions in binary form must reproduce the above
  15. copyright notice, this list of conditions and the
  16. following disclaimer in the documentation and/or other
  17. materials provided with the distribution.
  18. * Neither the name of the ASSIMP team, nor the names of its
  19. contributors may be used to endorse or promote products
  20. derived from this software without specific prior
  21. written permission of the ASSIMP Development Team.
  22. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. ---------------------------------------------------------------------------
  34. */
  35. #include "AssimpPCH.h"
  36. #include "ColladaParser.h"
  37. #include "fast_atof.h"
  38. #include "ParsingUtils.h"
  39. using namespace Assimp;
  40. // ------------------------------------------------------------------------------------------------
  41. // Constructor to be privately used by Importer
  42. ColladaParser::ColladaParser( const std::string& pFile)
  43. : mFileName( pFile)
  44. {
  45. mRootNode = NULL;
  46. mUnitSize = 1.0f;
  47. mUpDirection = UP_Z;
  48. // generate a XML reader for it
  49. mReader = irr::io::createIrrXMLReader( pFile.c_str());
  50. if( !mReader)
  51. ThrowException( "Unable to open file.");
  52. // start reading
  53. ReadContents();
  54. }
  55. // ------------------------------------------------------------------------------------------------
  56. // Destructor, private as well
  57. ColladaParser::~ColladaParser()
  58. {
  59. delete mReader;
  60. for( NodeLibrary::iterator it = mNodeLibrary.begin(); it != mNodeLibrary.end(); ++it)
  61. delete it->second;
  62. for( MeshLibrary::iterator it = mMeshLibrary.begin(); it != mMeshLibrary.end(); ++it)
  63. delete it->second;
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. // Reads the contents of the file
  67. void ColladaParser::ReadContents()
  68. {
  69. while( mReader->read())
  70. {
  71. // handle the root element "COLLADA"
  72. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  73. {
  74. if( IsElement( "COLLADA"))
  75. {
  76. ReadStructure();
  77. } else
  78. {
  79. DefaultLogger::get()->debug( boost::str( boost::format( "Ignoring global element \"%s\".") % mReader->getNodeName()));
  80. SkipElement();
  81. }
  82. } else
  83. {
  84. // skip everything else silently
  85. }
  86. }
  87. }
  88. // ------------------------------------------------------------------------------------------------
  89. // Reads the structure of the file
  90. void ColladaParser::ReadStructure()
  91. {
  92. while( mReader->read())
  93. {
  94. // beginning of elements
  95. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  96. {
  97. if( IsElement( "asset"))
  98. ReadAssetInfo();
  99. else if( IsElement( "library_geometries"))
  100. ReadGeometryLibrary();
  101. else if( IsElement( "library_visual_scenes"))
  102. ReadSceneLibrary();
  103. else if( IsElement( "scene"))
  104. ReadScene();
  105. else
  106. SkipElement();
  107. }
  108. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  109. {
  110. break;
  111. }
  112. }
  113. }
  114. // ------------------------------------------------------------------------------------------------
  115. // Reads asset informations such as coordinate system informations and legal blah
  116. void ColladaParser::ReadAssetInfo()
  117. {
  118. while( mReader->read())
  119. {
  120. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  121. {
  122. if( IsElement( "unit"))
  123. {
  124. // read unit data from the element's attributes
  125. int attrIndex = GetAttribute( "meter");
  126. mUnitSize = mReader->getAttributeValueAsFloat( attrIndex);
  127. // consume the trailing stuff
  128. if( !mReader->isEmptyElement())
  129. SkipElement();
  130. }
  131. else if( IsElement( "up_axis"))
  132. {
  133. // read content, strip whitespace, compare
  134. const char* content = GetTextContent();
  135. if( strncmp( content, "X_UP", 4) == 0)
  136. mUpDirection = UP_X;
  137. else if( strncmp( content, "Y_UP", 4) == 0)
  138. mUpDirection = UP_Y;
  139. else
  140. mUpDirection = UP_Z;
  141. // check element end
  142. TestClosing( "up_axis");
  143. } else
  144. {
  145. SkipElement();
  146. }
  147. }
  148. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  149. {
  150. if( strcmp( mReader->getNodeName(), "asset") != 0)
  151. ThrowException( "Expected end of \"asset\" element.");
  152. break;
  153. }
  154. }
  155. }
  156. // ------------------------------------------------------------------------------------------------
  157. // Reads the geometry library contents
  158. void ColladaParser::ReadGeometryLibrary()
  159. {
  160. while( mReader->read())
  161. {
  162. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  163. {
  164. if( IsElement( "geometry"))
  165. {
  166. // read ID. Another entry which is "optional" by design but obligatory in reality
  167. int indexID = GetAttribute( "id");
  168. std::string id = mReader->getAttributeValue( indexID);
  169. // TODO: (thom) support SIDs
  170. assert( TestAttribute( "sid") == -1);
  171. // a <geometry> always contains a single <mesh> element inside, so we just skip that element in advance
  172. TestOpening( "mesh");
  173. // create a mesh and store it in the library under its ID
  174. Mesh* mesh = new Mesh;
  175. mMeshLibrary[id] = mesh;
  176. // read on from there
  177. ReadMesh( mesh);
  178. // check for the closing tag of the outer <geometry" element, the inner closing of <mesh> has been consumed by ReadMesh()
  179. TestClosing( "geometry");
  180. } else
  181. {
  182. // ignore the rest
  183. SkipElement();
  184. }
  185. }
  186. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  187. {
  188. if( strcmp( mReader->getNodeName(), "library_geometries") != 0)
  189. ThrowException( "Expected end of \"library_geometries\" element.");
  190. break;
  191. }
  192. }
  193. }
  194. // ------------------------------------------------------------------------------------------------
  195. // Reads a mesh from the geometry library
  196. void ColladaParser::ReadMesh( Mesh* pMesh)
  197. {
  198. // I'm doing a dirty state parsing here because I don't want to open another submethod for it.
  199. // There's a <source> tag defining the name for the accessor inside, and possible a <float_array>
  200. // with it's own ID. This string contains the current source's ID if parsing is inside a <source> element.
  201. std::string presentSourceID;
  202. while( mReader->read())
  203. {
  204. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  205. {
  206. if( IsElement( "source"))
  207. {
  208. // beginning of a source element - store ID for the inner elements
  209. int attrID = GetAttribute( "id");
  210. presentSourceID = mReader->getAttributeValue( attrID);
  211. }
  212. else if( IsElement( "float_array"))
  213. {
  214. ReadFloatArray();
  215. }
  216. else if( IsElement( "technique_common"))
  217. {
  218. // I don't fucking care for your profiles bullshit
  219. }
  220. else if( IsElement( "accessor"))
  221. {
  222. ReadAccessor( presentSourceID);
  223. }
  224. else if( IsElement( "vertices"))
  225. {
  226. // read per-vertex mesh data
  227. ReadVertexData( pMesh);
  228. }
  229. else if( IsElement( "polylist") || IsElement( "triangles"))
  230. {
  231. // read per-index mesh data and faces setup
  232. ReadIndexData( pMesh);
  233. } else
  234. {
  235. // ignore the rest
  236. SkipElement();
  237. }
  238. }
  239. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  240. {
  241. if( strcmp( mReader->getNodeName(), "source") == 0)
  242. {
  243. // end of <source> - reset present source ID
  244. presentSourceID.clear();
  245. }
  246. else if( strcmp( mReader->getNodeName(), "technique_common") == 0)
  247. {
  248. // end of another meaningless element - read over it
  249. }
  250. else if( strcmp( mReader->getNodeName(), "mesh") == 0)
  251. {
  252. // end of <mesh> element - we're done here
  253. break;
  254. } else
  255. {
  256. // everything else should be punished
  257. ThrowException( "Expected end of \"mesh\" element.");
  258. }
  259. }
  260. }
  261. }
  262. // ------------------------------------------------------------------------------------------------
  263. // Reads a data array holding a number of floats, and stores it in the global library
  264. void ColladaParser::ReadFloatArray()
  265. {
  266. // read attributes
  267. int indexID = GetAttribute( "id");
  268. std::string id = mReader->getAttributeValue( indexID);
  269. int indexCount = GetAttribute( "count");
  270. unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( indexCount);
  271. const char* content = GetTextContent();
  272. // read values and store inside an array in the data library
  273. mDataLibrary[id] = Data();
  274. Data& data = mDataLibrary[id];
  275. data.mValues.reserve( count);
  276. for( unsigned int a = 0; a < count; a++)
  277. {
  278. if( *content == 0)
  279. ThrowException( "Expected more values while reading float_array contents.");
  280. float value;
  281. // read a number
  282. content = fast_atof_move( content, value);
  283. data.mValues.push_back( value);
  284. // skip whitespace after it
  285. SkipSpacesAndLineEnd( &content);
  286. }
  287. // test for closing tag
  288. TestClosing( "float_array");
  289. }
  290. // ------------------------------------------------------------------------------------------------
  291. // Reads an accessor and stores it in the global library
  292. void ColladaParser::ReadAccessor( const std::string& pID)
  293. {
  294. // read accessor attributes
  295. int attrSource = GetAttribute( "source");
  296. const char* source = mReader->getAttributeValue( attrSource);
  297. if( source[0] != '#')
  298. ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\".") % source));
  299. int attrCount = GetAttribute( "count");
  300. unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( attrCount);
  301. int attrOffset = TestAttribute( "offset");
  302. unsigned int offset = 0;
  303. if( attrOffset > -1)
  304. offset = (unsigned int) mReader->getAttributeValueAsInt( attrOffset);
  305. int attrStride = TestAttribute( "stride");
  306. unsigned int stride = 1;
  307. if( attrStride > -1)
  308. stride = (unsigned int) mReader->getAttributeValueAsInt( attrStride);
  309. // store in the library under the given ID
  310. mAccessorLibrary[pID] = Accessor();
  311. Accessor& acc = mAccessorLibrary[pID];
  312. acc.mCount = count;
  313. acc.mOffset = offset;
  314. acc.mStride = stride;
  315. acc.mSource = source+1; // ignore the leading '#'
  316. // and read the components
  317. while( mReader->read())
  318. {
  319. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  320. {
  321. if( IsElement( "param"))
  322. {
  323. // read data param
  324. int attrName = TestAttribute( "name");
  325. std::string name;
  326. if( attrName > -1)
  327. {
  328. name = mReader->getAttributeValue( attrName);
  329. // analyse for common type components and store it's sub-offset in the corresponding field
  330. if( name == "X") acc.mSubOffset[0] = acc.mParams.size();
  331. else if( name == "Y") acc.mSubOffset[1] = acc.mParams.size();
  332. else if( name == "Z") acc.mSubOffset[2] = acc.mParams.size();
  333. else if( name == "R") acc.mSubOffset[0] = acc.mParams.size();
  334. else if( name == "G") acc.mSubOffset[1] = acc.mParams.size();
  335. else if( name == "B") acc.mSubOffset[2] = acc.mParams.size();
  336. else if( name == "A") acc.mSubOffset[3] = acc.mParams.size();
  337. else if( name == "S") acc.mSubOffset[0] = acc.mParams.size();
  338. else if( name == "T") acc.mSubOffset[1] = acc.mParams.size();
  339. else
  340. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown accessor parameter \"%s\". Ignoring data channel.") % name));
  341. }
  342. acc.mParams.push_back( name);
  343. // skip remaining stuff of this element, if any
  344. SkipElement();
  345. } else
  346. {
  347. ThrowException( "Unexpected sub element in tag \"accessor\".");
  348. }
  349. }
  350. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  351. {
  352. if( strcmp( mReader->getNodeName(), "accessor") != 0)
  353. ThrowException( "Expected end of \"accessor\" element.");
  354. break;
  355. }
  356. }
  357. }
  358. // ------------------------------------------------------------------------------------------------
  359. // Reads input declarations of per-vertex mesh data into the given mesh
  360. void ColladaParser::ReadVertexData( Mesh* pMesh)
  361. {
  362. // extract the ID of the <vertices> element. Not that we care, but to catch strange referencing schemes we should warn about
  363. int attrID= GetAttribute( "id");
  364. pMesh->mVertexID = mReader->getAttributeValue( attrID);
  365. // a number of <input> elements
  366. while( mReader->read())
  367. {
  368. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  369. {
  370. if( IsElement( "input"))
  371. {
  372. ReadInputChannel( pMesh->mPerVertexData);
  373. } else
  374. {
  375. ThrowException( "Unexpected sub element in tag \"vertices\".");
  376. }
  377. }
  378. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  379. {
  380. if( strcmp( mReader->getNodeName(), "vertices") != 0)
  381. ThrowException( "Expected end of \"vertices\" element.");
  382. break;
  383. }
  384. }
  385. }
  386. // ------------------------------------------------------------------------------------------------
  387. // Reads input declarations of per-index mesh data into the given mesh
  388. void ColladaParser::ReadIndexData( Mesh* pMesh)
  389. {
  390. std::vector<size_t> vcount;
  391. std::vector<InputChannel> perIndexData;
  392. // read primitive count from the attribute
  393. int attrCount = GetAttribute( "count");
  394. size_t numPrimitives = (size_t) mReader->getAttributeValueAsInt( attrCount);
  395. // distinguish between polys and triangles
  396. std::string elementName = mReader->getNodeName();
  397. bool isPolylist = IsElement( "polylist");
  398. // also a number of <input> elements, but in addition a <p> primitive collection and propably index counts for all primitives
  399. while( mReader->read())
  400. {
  401. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  402. {
  403. if( IsElement( "input"))
  404. {
  405. ReadInputChannel( perIndexData);
  406. }
  407. else if( IsElement( "vcount"))
  408. {
  409. // case <polylist> - specifies the number of indices for each polygon
  410. const char* content = GetTextContent();
  411. vcount.reserve( numPrimitives);
  412. for( unsigned int a = 0; a < numPrimitives; a++)
  413. {
  414. if( *content == 0)
  415. ThrowException( "Expected more values while reading vcount contents.");
  416. // read a number
  417. vcount.push_back( (size_t) strtol10( content, &content));
  418. // skip whitespace after it
  419. SkipSpacesAndLineEnd( &content);
  420. }
  421. TestClosing( "vcount");
  422. }
  423. else if( IsElement( "p"))
  424. {
  425. // now here the actual fun starts - these are the indices to construct the mesh data from
  426. ReadPrimitives( pMesh, perIndexData, numPrimitives, vcount, isPolylist);
  427. } else
  428. {
  429. ThrowException( "Unexpected sub element in tag \"vertices\".");
  430. }
  431. }
  432. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  433. {
  434. if( mReader->getNodeName() != elementName)
  435. ThrowException( boost::str( boost::format( "Expected end of \"%s\" element.") % elementName));
  436. break;
  437. }
  438. }
  439. }
  440. // ------------------------------------------------------------------------------------------------
  441. // Reads a single input channel element and stores it in the given array, if valid
  442. void ColladaParser::ReadInputChannel( std::vector<InputChannel>& poChannels)
  443. {
  444. InputChannel channel;
  445. // read semantic
  446. int attrSemantic = GetAttribute( "semantic");
  447. std::string semantic = mReader->getAttributeValue( attrSemantic);
  448. channel.mType = GetTypeForSemantic( semantic);
  449. // read source
  450. int attrSource = GetAttribute( "source");
  451. const char* source = mReader->getAttributeValue( attrSource);
  452. if( source[0] != '#')
  453. ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\".") % source));
  454. channel.mAccessor = source+1; // skipping the leading #, hopefully the remaining text is the accessor ID only
  455. // read index offset, if per-index <input>
  456. int attrOffset = TestAttribute( "offset");
  457. if( attrOffset > -1)
  458. channel.mOffset = mReader->getAttributeValueAsInt( attrOffset);
  459. // store, if valid type
  460. if( channel.mType != IT_Invalid)
  461. poChannels.push_back( channel);
  462. // skip remaining stuff of this element, if any
  463. SkipElement();
  464. }
  465. // ------------------------------------------------------------------------------------------------
  466. // Reads a <p> primitive index list and assembles the mesh data into the given mesh
  467. void ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pPerIndexChannels,
  468. size_t pNumPrimitives, const std::vector<size_t>& pVCount, bool pIsPolylist)
  469. {
  470. // determine number of indices coming per vertex
  471. // find the offset index for all per-vertex channels
  472. size_t numOffsets = 1;
  473. size_t perVertexOffset = -1; // invalid value
  474. BOOST_FOREACH( const InputChannel& channel, pPerIndexChannels)
  475. {
  476. numOffsets = std::max( numOffsets, channel.mOffset+1);
  477. if( channel.mType == IT_Vertex)
  478. perVertexOffset = channel.mOffset;
  479. }
  480. // determine the expected number of indices
  481. size_t expectedPointCount = 0;
  482. if( pIsPolylist)
  483. {
  484. BOOST_FOREACH( size_t i, pVCount)
  485. expectedPointCount += i;
  486. } else
  487. {
  488. // everything triangles
  489. expectedPointCount = 3 * pNumPrimitives;
  490. }
  491. // and read all indices into a temporary array
  492. std::vector<size_t> indices( expectedPointCount * numOffsets);
  493. const char* content = GetTextContent();
  494. BOOST_FOREACH( size_t& value, indices)
  495. {
  496. if( *content == 0)
  497. ThrowException( "Expected more values while reading primitive indices.");
  498. // read a value in place
  499. value = strtol10( content, &content);
  500. // skip whitespace after it
  501. SkipSpacesAndLineEnd( &content);
  502. }
  503. // find the data for all sources
  504. BOOST_FOREACH( InputChannel& input, pMesh->mPerVertexData)
  505. {
  506. // find accessor
  507. input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
  508. // resolve accessor's data pointer as well, if neccessary
  509. const Accessor* acc = input.mResolved;
  510. if( !acc->mData)
  511. acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
  512. }
  513. // and the same for the per-index channels
  514. BOOST_FOREACH( InputChannel& input, pPerIndexChannels)
  515. {
  516. // ignore vertex pointer, it doesn't refer to an accessor
  517. if( input.mType == IT_Vertex)
  518. {
  519. // warn if the vertex channel does not refer to the <vertices> element in the same mesh
  520. if( input.mAccessor != pMesh->mVertexID)
  521. ThrowException( "Unsupported vertex referencing scheme. I fucking hate Collada.");
  522. continue;
  523. }
  524. // find accessor
  525. input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
  526. // resolve accessor's data pointer as well, if neccessary
  527. const Accessor* acc = input.mResolved;
  528. if( !acc->mData)
  529. acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
  530. }
  531. // now assemble vertex data according to those indices
  532. std::vector<size_t>::const_iterator idx = indices.begin();
  533. for( size_t a = 0; a < pNumPrimitives; a++)
  534. {
  535. // determine number of points for this primitive
  536. size_t numPoints = 3;
  537. if( pIsPolylist)
  538. numPoints = pVCount[a];
  539. // store the face size to later reconstruct the face from
  540. pMesh->mFaceSize.push_back( numPoints);
  541. // gather that number of vertices
  542. for( size_t b = 0; b < numPoints; b++)
  543. {
  544. // read all indices for this vertex. Yes, in a hacky static array
  545. assert( numOffsets < 20);
  546. static size_t vindex[20];
  547. for( size_t offsets = 0; offsets < numOffsets; ++offsets)
  548. vindex[offsets] = *idx++;
  549. // extract per-vertex channels using the global per-vertex offset
  550. BOOST_FOREACH( const InputChannel& input, pMesh->mPerVertexData)
  551. ExtractDataObjectFromChannel( input, vindex[perVertexOffset], pMesh);
  552. // and extract per-index channels using there specified offset
  553. BOOST_FOREACH( const InputChannel& input, pPerIndexChannels)
  554. ExtractDataObjectFromChannel( input, vindex[input.mOffset], pMesh);
  555. }
  556. }
  557. // if I ever get my hands on that guy how invented this steaming pile of indirection...
  558. TestClosing( "p");
  559. }
  560. // ------------------------------------------------------------------------------------------------
  561. // Extracts a single object from an input channel and stores it in the appropriate mesh data array
  562. void ColladaParser::ExtractDataObjectFromChannel( const InputChannel& pInput, size_t pLocalIndex, Mesh* pMesh)
  563. {
  564. // ignore vertex referrer - we handle them that separate
  565. if( pInput.mType == IT_Vertex)
  566. return;
  567. const Accessor& acc = *pInput.mResolved;
  568. if( pLocalIndex >= acc.mCount)
  569. ThrowException( boost::str( boost::format( "Invalid data index (%d/%d) in primitive specification") % pLocalIndex % acc.mCount));
  570. // get a pointer to the start of the data object referred to by the accessor and the local index
  571. const float* dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex* acc.mStride;
  572. // assemble according to the accessors component sub-offset list. We don't care, yet, what kind of object exactly we're extracting here
  573. float obj[4];
  574. for( size_t c = 0; c < 4; ++c)
  575. obj[c] = dataObject[acc.mSubOffset[c]];
  576. // now we reinterpret it according to the type we're reading here
  577. switch( pInput.mType)
  578. {
  579. case IT_Position: // ignore all position streams except 0 - there can be only one position
  580. if( pInput.mIndex == 0)
  581. pMesh->mPositions.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  582. break;
  583. case IT_Normal: // ignore all normal streams except 0 - there can be only one normal
  584. if( pInput.mIndex == 0)
  585. pMesh->mNormals.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  586. break;
  587. case IT_Texcoord: // up to 4 texture coord sets are fine, ignore the others
  588. if( pInput.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS)
  589. pMesh->mTexCoords[pInput.mIndex].push_back( aiVector2D( obj[0], obj[1]));
  590. break;
  591. case IT_Color: // up to 4 color sets are fine, ignore the others
  592. if( pInput.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS)
  593. pMesh->mColors[pInput.mIndex].push_back( aiColor4D( obj[0], obj[1], obj[2], obj[3]));
  594. break;
  595. }
  596. }
  597. // ------------------------------------------------------------------------------------------------
  598. // Reads the library of node hierarchies and scene parts
  599. void ColladaParser::ReadSceneLibrary()
  600. {
  601. while( mReader->read())
  602. {
  603. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  604. {
  605. // a visual scene - generate root node under its ID and let ReadNode() do the recursive work
  606. if( IsElement( "visual_scene"))
  607. {
  608. // read ID. Is optional according to the spec, but how on earth should a scene_instance refer to it then?
  609. int indexID = GetAttribute( "id");
  610. const char* attrID = mReader->getAttributeValue( indexID);
  611. // read name if given.
  612. int indexName = TestAttribute( "name");
  613. const char* attrName = "unnamed";
  614. if( indexName > -1)
  615. attrName = mReader->getAttributeValue( indexName);
  616. // TODO: (thom) support SIDs
  617. assert( TestAttribute( "sid") == -1);
  618. // create a node and store it in the library under its ID
  619. Node* node = new Node;
  620. node->mID = attrID;
  621. node->mName = attrName;
  622. mNodeLibrary[node->mID] = node;
  623. ReadSceneNode( node);
  624. } else
  625. {
  626. // ignore the rest
  627. SkipElement();
  628. }
  629. }
  630. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  631. {
  632. if( strcmp( mReader->getNodeName(), "library_visual_scenes") != 0)
  633. ThrowException( "Expected end of \"library_visual_scenes\" element.");
  634. break;
  635. }
  636. }
  637. }
  638. // ------------------------------------------------------------------------------------------------
  639. // Reads a scene node's contents including children and stores it in the given node
  640. void ColladaParser::ReadSceneNode( Node* pNode)
  641. {
  642. // quit immediately on <bla/> elements
  643. if( mReader->isEmptyElement())
  644. return;
  645. while( mReader->read())
  646. {
  647. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  648. {
  649. if( IsElement( "lookat"))
  650. ReadNodeTransformation( pNode, TF_LOOKAT);
  651. else if( IsElement( "matrix"))
  652. ReadNodeTransformation( pNode, TF_MATRIX);
  653. else if( IsElement( "rotate"))
  654. ReadNodeTransformation( pNode, TF_ROTATE);
  655. else if( IsElement( "scale"))
  656. ReadNodeTransformation( pNode, TF_SCALE);
  657. else if( IsElement( "skew"))
  658. ReadNodeTransformation( pNode, TF_SKEW);
  659. else if( IsElement( "translate"))
  660. ReadNodeTransformation( pNode, TF_TRANSLATE);
  661. else if( IsElement( "node"))
  662. {
  663. Node* child = new Node;
  664. int attrID = TestAttribute( "id");
  665. if( attrID > -1)
  666. child->mID = mReader->getAttributeValue( attrID);
  667. int attrName = TestAttribute( "name");
  668. if( attrName > -1)
  669. child->mName = mReader->getAttributeValue( attrName);
  670. // TODO: (thom) support SIDs
  671. // assert( TestAttribute( "sid") == -1);
  672. pNode->mChildren.push_back( child);
  673. child->mParent = pNode;
  674. // read on recursively from there
  675. ReadSceneNode( child);
  676. } else if( IsElement( "instance_node"))
  677. {
  678. // test for it, in case we need to implement it
  679. assert( false);
  680. SkipElement();
  681. } else if( IsElement( "instance_geometry"))
  682. {
  683. // Reference to a mesh, we possible material associations
  684. ReadNodeGeometry( pNode);
  685. } else
  686. {
  687. // skip everything else for the moment
  688. SkipElement();
  689. }
  690. }
  691. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  692. {
  693. break;
  694. }
  695. }
  696. }
  697. // ------------------------------------------------------------------------------------------------
  698. // Reads a node transformation entry of the given type and adds it to the given node's transformation list.
  699. void ColladaParser::ReadNodeTransformation( Node* pNode, TransformType pType)
  700. {
  701. std::string tagName = mReader->getNodeName();
  702. // how many parameters to read per transformation type
  703. static const unsigned int sNumParameters[] = { 9, 4, 3, 3, 7, 16 };
  704. const char* content = GetTextContent();
  705. // read as many parameters and store in the transformation
  706. Transform tf;
  707. tf.mType = pType;
  708. for( unsigned int a = 0; a < sNumParameters[pType]; a++)
  709. {
  710. // read a number
  711. content = fast_atof_move( content, tf.f[a]);
  712. // skip whitespace after it
  713. SkipSpacesAndLineEnd( &content);
  714. }
  715. // place the transformation at the queue of the node
  716. pNode->mTransforms.push_back( tf);
  717. // and consum the closing tag
  718. TestClosing( tagName.c_str());
  719. }
  720. // ------------------------------------------------------------------------------------------------
  721. // Reads a mesh reference in a node and adds it to the node's mesh list
  722. void ColladaParser::ReadNodeGeometry( Node* pNode)
  723. {
  724. // referred mesh is given as an attribute of the <instance_geometry> element
  725. int attrUrl = GetAttribute( "url");
  726. const char* url = mReader->getAttributeValue( attrUrl);
  727. if( url[0] != '#')
  728. ThrowException( "Unknown reference format");
  729. // store the mesh ID
  730. pNode->mMeshes.push_back( std::string( url+1));
  731. // for the moment, skip the rest
  732. SkipElement();
  733. }
  734. // ------------------------------------------------------------------------------------------------
  735. // Reads the collada scene
  736. void ColladaParser::ReadScene()
  737. {
  738. while( mReader->read())
  739. {
  740. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  741. {
  742. if( IsElement( "instance_visual_scene"))
  743. {
  744. // should be the first and only occurence
  745. if( mRootNode)
  746. ThrowException( "Invalid scene containing multiple root nodes");
  747. // read the url of the scene to instance. Should be of format "#some_name"
  748. int urlIndex = GetAttribute( "url");
  749. const char* url = mReader->getAttributeValue( urlIndex);
  750. if( url[0] != '#')
  751. ThrowException( "Unknown reference format");
  752. // find the referred scene, skip the leading #
  753. NodeLibrary::const_iterator sit = mNodeLibrary.find( url+1);
  754. if( sit == mNodeLibrary.end())
  755. ThrowException( boost::str( boost::format( "Unable to resolve visual_scene reference \"%s\".") % url));
  756. mRootNode = sit->second;
  757. } else
  758. {
  759. SkipElement();
  760. }
  761. }
  762. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  763. {
  764. break;
  765. }
  766. }
  767. }
  768. // ------------------------------------------------------------------------------------------------
  769. // Aborts the file reading with an exception
  770. void ColladaParser::ThrowException( const std::string& pError) const
  771. {
  772. throw new ImportErrorException( boost::str( boost::format( "%s - %s") % mFileName % pError));
  773. }
  774. // ------------------------------------------------------------------------------------------------
  775. // Skips all data until the end node of the current element
  776. void ColladaParser::SkipElement()
  777. {
  778. // nothing to skip if it's an <element />
  779. if( mReader->isEmptyElement())
  780. return;
  781. // copy the current node's name because it'a pointer to the reader's internal buffer,
  782. // which is going to change with the upcoming parsing
  783. std::string element = mReader->getNodeName();
  784. while( mReader->read())
  785. {
  786. if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  787. if( mReader->getNodeName() == element)
  788. break;
  789. }
  790. }
  791. // ------------------------------------------------------------------------------------------------
  792. // Tests for an opening element of the given name, throws an exception if not found
  793. void ColladaParser::TestOpening( const char* pName)
  794. {
  795. // read element start
  796. if( !mReader->read())
  797. ThrowException( boost::str( boost::format( "Unexpected end of file while beginning of \"%s\" element.") % pName));
  798. // whitespace in front is ok, just read again if found
  799. if( mReader->getNodeType() == irr::io::EXN_TEXT)
  800. if( !mReader->read())
  801. ThrowException( boost::str( boost::format( "Unexpected end of file while reading beginning of \"%s\" element.") % pName));
  802. if( mReader->getNodeType() != irr::io::EXN_ELEMENT || strcmp( mReader->getNodeName(), pName) != 0)
  803. ThrowException( boost::str( boost::format( "Expected start of \"%s\" element.") % pName));
  804. }
  805. // ------------------------------------------------------------------------------------------------
  806. // Tests for the closing tag of the given element, throws an exception if not found
  807. void ColladaParser::TestClosing( const char* pName)
  808. {
  809. // read closing tag
  810. if( !mReader->read())
  811. ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of \"%s\" element.") % pName));
  812. // whitespace in front is ok, just read again if found
  813. if( mReader->getNodeType() == irr::io::EXN_TEXT)
  814. if( !mReader->read())
  815. ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of \"%s\" element.") % pName));
  816. if( mReader->getNodeType() != irr::io::EXN_ELEMENT_END || strcmp( mReader->getNodeName(), pName) != 0)
  817. ThrowException( boost::str( boost::format( "Expected end of \"%s\" element.") % pName));
  818. }
  819. // ------------------------------------------------------------------------------------------------
  820. // Returns the index of the named attribute or -1 if not found. Does not throw, therefore useful for optional attributes
  821. int ColladaParser::GetAttribute( const char* pAttr) const
  822. {
  823. int index = TestAttribute( pAttr);
  824. if( index != -1)
  825. return index;
  826. // attribute not found -> throw an exception
  827. ThrowException( boost::str( boost::format( "Expected attribute \"%s\" at element \"%s\".") % pAttr % mReader->getNodeName()));
  828. return -1;
  829. }
  830. // ------------------------------------------------------------------------------------------------
  831. // Tests the present element for the presence of one attribute, returns its index or throws an exception if not found
  832. int ColladaParser::TestAttribute( const char* pAttr) const
  833. {
  834. for( int a = 0; a < mReader->getAttributeCount(); a++)
  835. if( strcmp( mReader->getAttributeName( a), pAttr) == 0)
  836. return a;
  837. return -1;
  838. }
  839. // ------------------------------------------------------------------------------------------------
  840. // Reads the text contents of an element, throws an exception if not given. Skips leading whitespace.
  841. const char* ColladaParser::GetTextContent()
  842. {
  843. // present node should be the beginning of an element
  844. if( mReader->getNodeType() != irr::io::EXN_ELEMENT || mReader->isEmptyElement())
  845. ThrowException( "Expected opening element");
  846. // read contents of the element
  847. if( !mReader->read())
  848. ThrowException( "Unexpected end of file while reading asset up_axis element.");
  849. if( mReader->getNodeType() != irr::io::EXN_TEXT)
  850. ThrowException( "Invalid contents in element \"up_axis\".");
  851. // skip leading whitespace
  852. const char* text = mReader->getNodeData();
  853. SkipSpacesAndLineEnd( &text);
  854. return text;
  855. }
  856. // ------------------------------------------------------------------------------------------------
  857. // Calculates the resulting transformation fromm all the given transform steps
  858. aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector<Transform>& pTransforms) const
  859. {
  860. aiMatrix4x4 res;
  861. for( std::vector<Transform>::const_iterator it = pTransforms.begin(); it != pTransforms.end(); ++it)
  862. {
  863. const Transform& tf = *it;
  864. switch( tf.mType)
  865. {
  866. case TF_LOOKAT:
  867. // TODO: (thom)
  868. assert( false);
  869. break;
  870. case TF_ROTATE:
  871. {
  872. aiMatrix4x4 rot;
  873. aiMatrix4x4::Rotation( tf.f[3], aiVector3D( tf.f[0], tf.f[1], tf.f[2]), rot);
  874. res *= rot;
  875. break;
  876. }
  877. case TF_TRANSLATE:
  878. {
  879. aiMatrix4x4 trans;
  880. aiMatrix4x4::Translation( aiVector3D( tf.f[0], tf.f[1], tf.f[2]), trans);
  881. res *= trans;
  882. break;
  883. }
  884. case TF_SCALE:
  885. {
  886. aiMatrix4x4 scale( tf.f[0], 0.0f, 0.0f, 0.0f, 0.0f, tf.f[1], 0.0f, 0.0f, 0.0f, 0.0f, tf.f[2], 0.0f,
  887. 0.0f, 0.0f, 0.0f, 1.0f);
  888. res *= scale;
  889. break;
  890. }
  891. case TF_SKEW:
  892. // TODO: (thom)
  893. assert( false);
  894. break;
  895. case TF_MATRIX:
  896. {
  897. aiMatrix4x4 mat( tf.f[0], tf.f[1], tf.f[2], tf.f[3], tf.f[4], tf.f[5], tf.f[6], tf.f[7],
  898. tf.f[8], tf.f[9], tf.f[10], tf.f[11], tf.f[12], tf.f[13], tf.f[14], tf.f[15]);
  899. res *= mat;
  900. break;
  901. }
  902. default:
  903. assert( false);
  904. break;
  905. }
  906. }
  907. return res;
  908. }
  909. // ------------------------------------------------------------------------------------------------
  910. // Determines the input data type for the given semantic string
  911. ColladaParser::InputType ColladaParser::GetTypeForSemantic( const std::string& pSemantic)
  912. {
  913. if( pSemantic == "POSITION")
  914. return IT_Position;
  915. else if( pSemantic == "TEXCOORD")
  916. return IT_Texcoord;
  917. else if( pSemantic == "NORMAL")
  918. return IT_Normal;
  919. else if( pSemantic == "COLOR")
  920. return IT_Color;
  921. else if( pSemantic == "VERTEX")
  922. return IT_Vertex;
  923. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown vertex input type \"%s\". Ignoring.") % pSemantic));
  924. return IT_Invalid;
  925. }