2
0

ColladaParser.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  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. using namespace Assimp::Collada;
  41. // ------------------------------------------------------------------------------------------------
  42. // Constructor to be privately used by Importer
  43. ColladaParser::ColladaParser( const std::string& pFile)
  44. : mFileName( pFile)
  45. {
  46. mRootNode = NULL;
  47. mUnitSize = 1.0f;
  48. mUpDirection = UP_Z;
  49. // generate a XML reader for it
  50. mReader = irr::io::createIrrXMLReader( pFile.c_str());
  51. if( !mReader)
  52. ThrowException( "Unable to open file.");
  53. // start reading
  54. ReadContents();
  55. }
  56. // ------------------------------------------------------------------------------------------------
  57. // Destructor, private as well
  58. ColladaParser::~ColladaParser()
  59. {
  60. delete mReader;
  61. for( NodeLibrary::iterator it = mNodeLibrary.begin(); it != mNodeLibrary.end(); ++it)
  62. delete it->second;
  63. for( MeshLibrary::iterator it = mMeshLibrary.begin(); it != mMeshLibrary.end(); ++it)
  64. delete it->second;
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. // Reads the contents of the file
  68. void ColladaParser::ReadContents()
  69. {
  70. while( mReader->read())
  71. {
  72. // handle the root element "COLLADA"
  73. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  74. {
  75. if( IsElement( "COLLADA"))
  76. {
  77. ReadStructure();
  78. } else
  79. {
  80. DefaultLogger::get()->debug( boost::str( boost::format( "Ignoring global element \"%s\".") % mReader->getNodeName()));
  81. SkipElement();
  82. }
  83. } else
  84. {
  85. // skip everything else silently
  86. }
  87. }
  88. }
  89. // ------------------------------------------------------------------------------------------------
  90. // Reads the structure of the file
  91. void ColladaParser::ReadStructure()
  92. {
  93. while( mReader->read())
  94. {
  95. // beginning of elements
  96. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  97. {
  98. if( IsElement( "asset"))
  99. ReadAssetInfo();
  100. else if( IsElement( "library_images"))
  101. ReadImageLibrary();
  102. else if( IsElement( "library_materials"))
  103. ReadMaterialLibrary();
  104. else if( IsElement( "library_effects"))
  105. ReadEffectLibrary();
  106. else if( IsElement( "library_geometries"))
  107. ReadGeometryLibrary();
  108. else if( IsElement( "library_visual_scenes"))
  109. ReadSceneLibrary();
  110. else if( IsElement( "scene"))
  111. ReadScene();
  112. else
  113. SkipElement();
  114. }
  115. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  116. {
  117. break;
  118. }
  119. }
  120. }
  121. // ------------------------------------------------------------------------------------------------
  122. // Reads asset informations such as coordinate system informations and legal blah
  123. void ColladaParser::ReadAssetInfo()
  124. {
  125. while( mReader->read())
  126. {
  127. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  128. {
  129. if( IsElement( "unit"))
  130. {
  131. // read unit data from the element's attributes
  132. int attrIndex = GetAttribute( "meter");
  133. mUnitSize = mReader->getAttributeValueAsFloat( attrIndex);
  134. // consume the trailing stuff
  135. if( !mReader->isEmptyElement())
  136. SkipElement();
  137. }
  138. else if( IsElement( "up_axis"))
  139. {
  140. // read content, strip whitespace, compare
  141. const char* content = GetTextContent();
  142. if( strncmp( content, "X_UP", 4) == 0)
  143. mUpDirection = UP_X;
  144. else if( strncmp( content, "Y_UP", 4) == 0)
  145. mUpDirection = UP_Y;
  146. else
  147. mUpDirection = UP_Z;
  148. // check element end
  149. TestClosing( "up_axis");
  150. } else
  151. {
  152. SkipElement();
  153. }
  154. }
  155. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  156. {
  157. if( strcmp( mReader->getNodeName(), "asset") != 0)
  158. ThrowException( "Expected end of \"asset\" element.");
  159. break;
  160. }
  161. }
  162. }
  163. // ------------------------------------------------------------------------------------------------
  164. // Reads the image library contents
  165. void ColladaParser::ReadImageLibrary()
  166. {
  167. while( mReader->read())
  168. {
  169. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  170. {
  171. if( IsElement( "image"))
  172. {
  173. // read ID. Another entry which is "optional" by design but obligatory in reality
  174. int attrID = GetAttribute( "id");
  175. std::string id = mReader->getAttributeValue( attrID);
  176. // create an entry and store it in the library under its ID
  177. mImageLibrary[id] = Image();
  178. // read on from there
  179. ReadImage( mImageLibrary[id]);
  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_images") != 0)
  189. ThrowException( "Expected end of \"library_images\" element.");
  190. break;
  191. }
  192. }
  193. }
  194. // ------------------------------------------------------------------------------------------------
  195. // Reads an image entry into the given image
  196. void ColladaParser::ReadImage( Collada::Image& pImage)
  197. {
  198. while( mReader->read())
  199. {
  200. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  201. {
  202. if( IsElement( "init_from"))
  203. {
  204. // element content is filename - hopefully
  205. const char* content = GetTextContent();
  206. pImage.mFileName = content;
  207. TestClosing( "init_from");
  208. } else
  209. {
  210. // ignore the rest
  211. SkipElement();
  212. }
  213. }
  214. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  215. {
  216. if( strcmp( mReader->getNodeName(), "image") != 0)
  217. ThrowException( "Expected end of \"image\" element.");
  218. break;
  219. }
  220. }
  221. }
  222. // ------------------------------------------------------------------------------------------------
  223. // Reads the material library
  224. void ColladaParser::ReadMaterialLibrary()
  225. {
  226. while( mReader->read())
  227. {
  228. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  229. {
  230. if( IsElement( "material"))
  231. {
  232. // read ID. By now you propably know my opinion about this "specification"
  233. int attrID = GetAttribute( "id");
  234. std::string id = mReader->getAttributeValue( attrID);
  235. // create an entry and store it in the library under its ID
  236. mMaterialLibrary[id] = Material();
  237. // read on from there
  238. ReadMaterial( mMaterialLibrary[id]);
  239. } else
  240. {
  241. // ignore the rest
  242. SkipElement();
  243. }
  244. }
  245. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  246. {
  247. if( strcmp( mReader->getNodeName(), "library_materials") != 0)
  248. ThrowException( "Expected end of \"library_materials\" element.");
  249. break;
  250. }
  251. }
  252. }
  253. // ------------------------------------------------------------------------------------------------
  254. // Reads a material entry into the given material
  255. void ColladaParser::ReadMaterial( Collada::Material& pMaterial)
  256. {
  257. while( mReader->read())
  258. {
  259. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  260. {
  261. if( IsElement( "instance_effect"))
  262. {
  263. // referred effect by URL
  264. int attrUrl = GetAttribute( "url");
  265. const char* url = mReader->getAttributeValue( attrUrl);
  266. if( url[0] != '#')
  267. ThrowException( "Unknown reference format");
  268. pMaterial.mEffect = url+1;
  269. SkipElement();
  270. } else
  271. {
  272. // ignore the rest
  273. SkipElement();
  274. }
  275. }
  276. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  277. {
  278. if( strcmp( mReader->getNodeName(), "material") != 0)
  279. ThrowException( "Expected end of \"image\" element.");
  280. break;
  281. }
  282. }
  283. }
  284. // ------------------------------------------------------------------------------------------------
  285. // Reads the effect library
  286. void ColladaParser::ReadEffectLibrary()
  287. {
  288. while( mReader->read())
  289. {
  290. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  291. {
  292. if( IsElement( "effect"))
  293. {
  294. // read ID. Do I have to repeat my ranting about "optional" attributes?
  295. int attrID = GetAttribute( "id");
  296. std::string id = mReader->getAttributeValue( attrID);
  297. // create an entry and store it in the library under its ID
  298. mEffectLibrary[id] = Effect();
  299. // read on from there
  300. ReadEffect( mEffectLibrary[id]);
  301. } else
  302. {
  303. // ignore the rest
  304. SkipElement();
  305. }
  306. }
  307. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  308. {
  309. if( strcmp( mReader->getNodeName(), "library_effects") != 0)
  310. ThrowException( "Expected end of \"library_effects\" element.");
  311. break;
  312. }
  313. }
  314. }
  315. // ------------------------------------------------------------------------------------------------
  316. // Reads an effect entry into the given effect
  317. void ColladaParser::ReadEffect( Collada::Effect& pEffect)
  318. {
  319. // for the moment we don't support any other type of effect.
  320. // TODO: (thom) Rewrite this so that it ignores the whole effect instead of bailing out
  321. TestOpening( "profile_COMMON");
  322. while( mReader->read())
  323. {
  324. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  325. {
  326. if( IsElement( "newparam"))
  327. {
  328. // save ID
  329. int attrSID = GetAttribute( "sid");
  330. std::string sid = mReader->getAttributeValue( attrSID);
  331. pEffect.mParams[sid] = EffectParam();
  332. ReadEffectParam( pEffect.mParams[sid]);
  333. }
  334. else if( IsElement( "technique"))
  335. {
  336. // just syntactic sugar
  337. }
  338. else if( IsElement( "phong"))
  339. pEffect.mShadeType = Shade_Phong;
  340. else if( IsElement( "constant"))
  341. pEffect.mShadeType = Shade_Constant;
  342. else if( IsElement( "lambert"))
  343. pEffect.mShadeType = Shade_Lambert;
  344. else if( IsElement( "blinn"))
  345. pEffect.mShadeType = Shade_Blinn;
  346. else if( IsElement( "emission"))
  347. ReadEffectColor( pEffect.mEmissive, pEffect.mTexEmissive);
  348. else if( IsElement( "ambient"))
  349. ReadEffectColor( pEffect.mAmbient, pEffect.mTexAmbient);
  350. else if( IsElement( "diffuse"))
  351. ReadEffectColor( pEffect.mDiffuse, pEffect.mTexDiffuse);
  352. else if( IsElement( "specular"))
  353. ReadEffectColor( pEffect.mSpecular, pEffect.mTexSpecular);
  354. else if( IsElement( "reflective")){
  355. std::string buf;
  356. ReadEffectColor( pEffect.mReflective, buf);
  357. }
  358. else if( IsElement( "transparent")){
  359. std::string buf;
  360. ReadEffectColor( pEffect.mRefractive,buf);
  361. }
  362. else if( IsElement( "shininess"))
  363. ReadEffectFloat( pEffect.mShininess);
  364. else if( IsElement( "reflectivity"))
  365. ReadEffectFloat( pEffect.mReflectivity);
  366. else if( IsElement( "transparency"))
  367. ReadEffectFloat( pEffect.mRefractivity);
  368. else if( IsElement( "index_of_refraction"))
  369. ReadEffectFloat( pEffect.mRefractIndex);
  370. else
  371. {
  372. // ignore the rest
  373. SkipElement();
  374. }
  375. }
  376. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  377. {
  378. if( strcmp( mReader->getNodeName(), "effect") == 0)
  379. break;
  380. }
  381. }
  382. }
  383. // ------------------------------------------------------------------------------------------------
  384. // Reads an effect entry containing a color or a texture defining that color
  385. void ColladaParser::ReadEffectColor( aiColor4D& pColor, std::string& pSampler)
  386. {
  387. while( mReader->read())
  388. {
  389. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  390. {
  391. if( IsElement( "color"))
  392. {
  393. // text content contains 4 floats
  394. const char* content = GetTextContent();
  395. float fBuf;
  396. content = fast_atof_move( content, fBuf);
  397. pColor.r = fBuf;
  398. SkipSpacesAndLineEnd( &content);
  399. content = fast_atof_move( content, fBuf);
  400. pColor.g = fBuf;
  401. SkipSpacesAndLineEnd( &content);
  402. content = fast_atof_move( content, fBuf);
  403. pColor.b = fBuf;
  404. SkipSpacesAndLineEnd( &content);
  405. content = fast_atof_move( content, fBuf);
  406. pColor.a = fBuf;
  407. SkipSpacesAndLineEnd( &content);
  408. TestClosing( "color");
  409. }
  410. else if( IsElement( "texture"))
  411. {
  412. int attrTex = GetAttribute( "texture");
  413. pSampler = mReader->getAttributeValue( attrTex);
  414. SkipElement();
  415. } else
  416. {
  417. // ignore the rest
  418. SkipElement();
  419. }
  420. }
  421. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  422. {
  423. break;
  424. }
  425. }
  426. }
  427. // ------------------------------------------------------------------------------------------------
  428. // Reads an effect entry containing a float
  429. void ColladaParser::ReadEffectFloat( float& pFloat)
  430. {
  431. while( mReader->read())
  432. {
  433. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  434. {
  435. if( IsElement( "float"))
  436. {
  437. // text content contains a single floats
  438. const char* content = GetTextContent();
  439. content = fast_atof_move( content, pFloat);
  440. SkipSpacesAndLineEnd( &content);
  441. TestClosing( "float");
  442. } else
  443. {
  444. // ignore the rest
  445. SkipElement();
  446. }
  447. }
  448. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  449. {
  450. break;
  451. }
  452. }
  453. }
  454. // ------------------------------------------------------------------------------------------------
  455. // Reads an effect parameter specification of any kind
  456. void ColladaParser::ReadEffectParam( Collada::EffectParam& pParam)
  457. {
  458. while( mReader->read())
  459. {
  460. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  461. {
  462. if( IsElement( "surface"))
  463. {
  464. // image ID given inside <init_from> tags
  465. TestOpening( "init_from");
  466. const char* content = GetTextContent();
  467. pParam.mType = Param_Surface;
  468. pParam.mReference = content;
  469. TestClosing( "init_from");
  470. // don't care for remaining stuff
  471. SkipElement( "surface");
  472. }
  473. else if( IsElement( "sampler2D"))
  474. {
  475. // surface ID is given inside <source> tags
  476. TestOpening( "source");
  477. const char* content = GetTextContent();
  478. pParam.mType = Param_Sampler;
  479. pParam.mReference = content;
  480. TestClosing( "source");
  481. // don't care for remaining stuff
  482. SkipElement( "sampler2D");
  483. } else
  484. {
  485. // ignore unknown element
  486. SkipElement();
  487. }
  488. }
  489. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  490. {
  491. break;
  492. }
  493. }
  494. }
  495. // ------------------------------------------------------------------------------------------------
  496. // Reads the geometry library contents
  497. void ColladaParser::ReadGeometryLibrary()
  498. {
  499. while( mReader->read())
  500. {
  501. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  502. {
  503. if( IsElement( "geometry"))
  504. {
  505. // read ID. Another entry which is "optional" by design but obligatory in reality
  506. int indexID = GetAttribute( "id");
  507. std::string id = mReader->getAttributeValue( indexID);
  508. // TODO: (thom) support SIDs
  509. assert( TestAttribute( "sid") == -1);
  510. // create a mesh and store it in the library under its ID
  511. Mesh* mesh = new Mesh;
  512. mMeshLibrary[id] = mesh;
  513. // read on from there
  514. ReadGeometry( mesh);
  515. } else
  516. {
  517. // ignore the rest
  518. SkipElement();
  519. }
  520. }
  521. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  522. {
  523. if( strcmp( mReader->getNodeName(), "library_geometries") != 0)
  524. ThrowException( "Expected end of \"library_geometries\" element.");
  525. break;
  526. }
  527. }
  528. }
  529. // ------------------------------------------------------------------------------------------------
  530. // Reads a geometry from the geometry library.
  531. void ColladaParser::ReadGeometry( Collada::Mesh* pMesh)
  532. {
  533. while( mReader->read())
  534. {
  535. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  536. {
  537. if( IsElement( "mesh"))
  538. {
  539. // read on from there
  540. ReadMesh( pMesh);
  541. } else
  542. {
  543. // ignore the rest
  544. SkipElement();
  545. }
  546. }
  547. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  548. {
  549. if( strcmp( mReader->getNodeName(), "geometry") != 0)
  550. ThrowException( "Expected end of \"geometry\" element.");
  551. break;
  552. }
  553. }
  554. }
  555. // ------------------------------------------------------------------------------------------------
  556. // Reads a mesh from the geometry library
  557. void ColladaParser::ReadMesh( Mesh* pMesh)
  558. {
  559. // I'm doing a dirty state parsing here because I don't want to open another submethod for it.
  560. // There's a <source> tag defining the name for the accessor inside, and possible a <float_array>
  561. // with it's own ID. This string contains the current source's ID if parsing is inside a <source> element.
  562. std::string presentSourceID;
  563. while( mReader->read())
  564. {
  565. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  566. {
  567. if( IsElement( "source"))
  568. {
  569. // beginning of a source element - store ID for the inner elements
  570. int attrID = GetAttribute( "id");
  571. presentSourceID = mReader->getAttributeValue( attrID);
  572. }
  573. else if( IsElement( "float_array"))
  574. {
  575. ReadFloatArray();
  576. }
  577. else if( IsElement( "technique_common"))
  578. {
  579. // I don't fucking care for your profiles bullshit
  580. }
  581. else if( IsElement( "accessor"))
  582. {
  583. ReadAccessor( presentSourceID);
  584. }
  585. else if( IsElement( "vertices"))
  586. {
  587. // read per-vertex mesh data
  588. ReadVertexData( pMesh);
  589. }
  590. else if( IsElement( "triangles") || IsElement( "lines") || IsElement( "linestrips")
  591. || IsElement( "polygons") || IsElement( "polylist") || IsElement( "trifans") || IsElement( "tristrips"))
  592. {
  593. // read per-index mesh data and faces setup
  594. ReadIndexData( pMesh);
  595. } else
  596. {
  597. // ignore the rest
  598. SkipElement();
  599. }
  600. }
  601. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  602. {
  603. if( strcmp( mReader->getNodeName(), "source") == 0)
  604. {
  605. // end of <source> - reset present source ID
  606. presentSourceID.clear();
  607. }
  608. else if( strcmp( mReader->getNodeName(), "technique_common") == 0)
  609. {
  610. // end of another meaningless element - read over it
  611. }
  612. else if( strcmp( mReader->getNodeName(), "mesh") == 0)
  613. {
  614. // end of <mesh> element - we're done here
  615. break;
  616. } else
  617. {
  618. // everything else should be punished
  619. ThrowException( "Expected end of \"mesh\" element.");
  620. }
  621. }
  622. }
  623. }
  624. // ------------------------------------------------------------------------------------------------
  625. // Reads a data array holding a number of floats, and stores it in the global library
  626. void ColladaParser::ReadFloatArray()
  627. {
  628. // read attributes
  629. int indexID = GetAttribute( "id");
  630. std::string id = mReader->getAttributeValue( indexID);
  631. int indexCount = GetAttribute( "count");
  632. unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( indexCount);
  633. const char* content = GetTextContent();
  634. // read values and store inside an array in the data library
  635. mDataLibrary[id] = Data();
  636. Data& data = mDataLibrary[id];
  637. data.mValues.reserve( count);
  638. for( unsigned int a = 0; a < count; a++)
  639. {
  640. if( *content == 0)
  641. ThrowException( "Expected more values while reading float_array contents.");
  642. float value;
  643. // read a number
  644. content = fast_atof_move( content, value);
  645. data.mValues.push_back( value);
  646. // skip whitespace after it
  647. SkipSpacesAndLineEnd( &content);
  648. }
  649. // test for closing tag
  650. TestClosing( "float_array");
  651. }
  652. // ------------------------------------------------------------------------------------------------
  653. // Reads an accessor and stores it in the global library
  654. void ColladaParser::ReadAccessor( const std::string& pID)
  655. {
  656. // read accessor attributes
  657. int attrSource = GetAttribute( "source");
  658. const char* source = mReader->getAttributeValue( attrSource);
  659. if( source[0] != '#')
  660. ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\".") % source));
  661. int attrCount = GetAttribute( "count");
  662. unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( attrCount);
  663. int attrOffset = TestAttribute( "offset");
  664. unsigned int offset = 0;
  665. if( attrOffset > -1)
  666. offset = (unsigned int) mReader->getAttributeValueAsInt( attrOffset);
  667. int attrStride = TestAttribute( "stride");
  668. unsigned int stride = 1;
  669. if( attrStride > -1)
  670. stride = (unsigned int) mReader->getAttributeValueAsInt( attrStride);
  671. // store in the library under the given ID
  672. mAccessorLibrary[pID] = Accessor();
  673. Accessor& acc = mAccessorLibrary[pID];
  674. acc.mCount = count;
  675. acc.mOffset = offset;
  676. acc.mStride = stride;
  677. acc.mSource = source+1; // ignore the leading '#'
  678. // and read the components
  679. while( mReader->read())
  680. {
  681. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  682. {
  683. if( IsElement( "param"))
  684. {
  685. // read data param
  686. int attrName = TestAttribute( "name");
  687. std::string name;
  688. if( attrName > -1)
  689. {
  690. name = mReader->getAttributeValue( attrName);
  691. // analyse for common type components and store it's sub-offset in the corresponding field
  692. if( name == "X") acc.mSubOffset[0] = acc.mParams.size();
  693. else if( name == "Y") acc.mSubOffset[1] = acc.mParams.size();
  694. else if( name == "Z") acc.mSubOffset[2] = acc.mParams.size();
  695. else if( name == "R") acc.mSubOffset[0] = acc.mParams.size();
  696. else if( name == "G") acc.mSubOffset[1] = acc.mParams.size();
  697. else if( name == "B") acc.mSubOffset[2] = acc.mParams.size();
  698. else if( name == "A") acc.mSubOffset[3] = acc.mParams.size();
  699. else if( name == "S") acc.mSubOffset[0] = acc.mParams.size();
  700. else if( name == "T") acc.mSubOffset[1] = acc.mParams.size();
  701. else
  702. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown accessor parameter \"%s\". Ignoring data channel.") % name));
  703. }
  704. acc.mParams.push_back( name);
  705. // skip remaining stuff of this element, if any
  706. SkipElement();
  707. } else
  708. {
  709. ThrowException( "Unexpected sub element in tag \"accessor\".");
  710. }
  711. }
  712. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  713. {
  714. if( strcmp( mReader->getNodeName(), "accessor") != 0)
  715. ThrowException( "Expected end of \"accessor\" element.");
  716. break;
  717. }
  718. }
  719. }
  720. // ------------------------------------------------------------------------------------------------
  721. // Reads input declarations of per-vertex mesh data into the given mesh
  722. void ColladaParser::ReadVertexData( Mesh* pMesh)
  723. {
  724. // extract the ID of the <vertices> element. Not that we care, but to catch strange referencing schemes we should warn about
  725. int attrID= GetAttribute( "id");
  726. pMesh->mVertexID = mReader->getAttributeValue( attrID);
  727. // a number of <input> elements
  728. while( mReader->read())
  729. {
  730. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  731. {
  732. if( IsElement( "input"))
  733. {
  734. ReadInputChannel( pMesh->mPerVertexData);
  735. } else
  736. {
  737. ThrowException( "Unexpected sub element in tag \"vertices\".");
  738. }
  739. }
  740. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  741. {
  742. if( strcmp( mReader->getNodeName(), "vertices") != 0)
  743. ThrowException( "Expected end of \"vertices\" element.");
  744. break;
  745. }
  746. }
  747. }
  748. // ------------------------------------------------------------------------------------------------
  749. // Reads input declarations of per-index mesh data into the given mesh
  750. void ColladaParser::ReadIndexData( Mesh* pMesh)
  751. {
  752. std::vector<size_t> vcount;
  753. std::vector<InputChannel> perIndexData;
  754. // read primitive count from the attribute
  755. int attrCount = GetAttribute( "count");
  756. size_t numPrimitives = (size_t) mReader->getAttributeValueAsInt( attrCount);
  757. // material subgroup
  758. int attrMaterial = TestAttribute( "material");
  759. SubMesh subgroup;
  760. if( attrMaterial > -1)
  761. subgroup.mMaterial = mReader->getAttributeValue( attrMaterial);
  762. subgroup.mNumFaces = numPrimitives;
  763. pMesh->mSubMeshes.push_back( subgroup);
  764. // distinguish between polys and triangles
  765. std::string elementName = mReader->getNodeName();
  766. PrimitiveType primType = Prim_Invalid;
  767. if( IsElement( "lines"))
  768. primType = Prim_Lines;
  769. else if( IsElement( "linestrips"))
  770. primType = Prim_LineStrip;
  771. else if( IsElement( "polygons"))
  772. primType = Prim_Polygon;
  773. else if( IsElement( "polylist"))
  774. primType = Prim_Polylist;
  775. else if( IsElement( "triangles"))
  776. primType = Prim_Triangles;
  777. else if( IsElement( "trifans"))
  778. primType = Prim_TriFans;
  779. else if( IsElement( "tristrips"))
  780. primType = Prim_TriStrips;
  781. assert( primType != Prim_Invalid);
  782. // also a number of <input> elements, but in addition a <p> primitive collection and propably index counts for all primitives
  783. while( mReader->read())
  784. {
  785. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  786. {
  787. if( IsElement( "input"))
  788. {
  789. ReadInputChannel( perIndexData);
  790. }
  791. else if( IsElement( "vcount"))
  792. {
  793. if( !mReader->isEmptyElement())
  794. {
  795. // case <polylist> - specifies the number of indices for each polygon
  796. const char* content = GetTextContent();
  797. vcount.reserve( numPrimitives);
  798. for( unsigned int a = 0; a < numPrimitives; a++)
  799. {
  800. if( *content == 0)
  801. ThrowException( "Expected more values while reading vcount contents.");
  802. // read a number
  803. vcount.push_back( (size_t) strtol10( content, &content));
  804. // skip whitespace after it
  805. SkipSpacesAndLineEnd( &content);
  806. }
  807. TestClosing( "vcount");
  808. }
  809. }
  810. else if( IsElement( "p"))
  811. {
  812. if( !mReader->isEmptyElement())
  813. {
  814. // now here the actual fun starts - these are the indices to construct the mesh data from
  815. ReadPrimitives( pMesh, perIndexData, numPrimitives, vcount, primType);
  816. }
  817. } else
  818. {
  819. ThrowException( "Unexpected sub element in tag \"vertices\".");
  820. }
  821. }
  822. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  823. {
  824. if( mReader->getNodeName() != elementName)
  825. ThrowException( boost::str( boost::format( "Expected end of \"%s\" element.") % elementName));
  826. break;
  827. }
  828. }
  829. }
  830. // ------------------------------------------------------------------------------------------------
  831. // Reads a single input channel element and stores it in the given array, if valid
  832. void ColladaParser::ReadInputChannel( std::vector<InputChannel>& poChannels)
  833. {
  834. InputChannel channel;
  835. // read semantic
  836. int attrSemantic = GetAttribute( "semantic");
  837. std::string semantic = mReader->getAttributeValue( attrSemantic);
  838. channel.mType = GetTypeForSemantic( semantic);
  839. // read source
  840. int attrSource = GetAttribute( "source");
  841. const char* source = mReader->getAttributeValue( attrSource);
  842. if( source[0] != '#')
  843. ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\".") % source));
  844. channel.mAccessor = source+1; // skipping the leading #, hopefully the remaining text is the accessor ID only
  845. // read index offset, if per-index <input>
  846. int attrOffset = TestAttribute( "offset");
  847. if( attrOffset > -1)
  848. channel.mOffset = mReader->getAttributeValueAsInt( attrOffset);
  849. // store, if valid type
  850. if( channel.mType != IT_Invalid)
  851. poChannels.push_back( channel);
  852. // skip remaining stuff of this element, if any
  853. SkipElement();
  854. }
  855. // ------------------------------------------------------------------------------------------------
  856. // Reads a <p> primitive index list and assembles the mesh data into the given mesh
  857. void ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pPerIndexChannels,
  858. size_t pNumPrimitives, const std::vector<size_t>& pVCount, PrimitiveType pPrimType)
  859. {
  860. // determine number of indices coming per vertex
  861. // find the offset index for all per-vertex channels
  862. size_t numOffsets = 1;
  863. size_t perVertexOffset = -1; // invalid value
  864. BOOST_FOREACH( const InputChannel& channel, pPerIndexChannels)
  865. {
  866. numOffsets = std::max( numOffsets, channel.mOffset+1);
  867. if( channel.mType == IT_Vertex)
  868. perVertexOffset = channel.mOffset;
  869. }
  870. // determine the expected number of indices
  871. size_t expectedPointCount = 0;
  872. switch( pPrimType)
  873. {
  874. case Prim_Polylist:
  875. {
  876. BOOST_FOREACH( size_t i, pVCount)
  877. expectedPointCount += i;
  878. break;
  879. }
  880. case Prim_Lines:
  881. expectedPointCount = 2 * pNumPrimitives;
  882. break;
  883. case Prim_Triangles:
  884. expectedPointCount = 3 * pNumPrimitives;
  885. break;
  886. default:
  887. // other primitive types don't state the index count upfront... we need to guess
  888. break;
  889. }
  890. // and read all indices into a temporary array
  891. std::vector<size_t> indices;
  892. if( expectedPointCount > 0)
  893. indices.reserve( expectedPointCount * numOffsets);
  894. const char* content = GetTextContent();
  895. while( *content != 0)
  896. {
  897. // read a value
  898. unsigned int value = strtol10( content, &content);
  899. indices.push_back( size_t( value));
  900. // skip whitespace after it
  901. SkipSpacesAndLineEnd( &content);
  902. }
  903. // complain if the index count doesn't fit
  904. if( expectedPointCount > 0 && indices.size() != expectedPointCount * numOffsets)
  905. ThrowException( "Expected different index count in <p> element.");
  906. else if( expectedPointCount == 0 && (indices.size() % numOffsets) != 0)
  907. ThrowException( "Expected different index count in <p> element.");
  908. // find the data for all sources
  909. BOOST_FOREACH( InputChannel& input, pMesh->mPerVertexData)
  910. {
  911. if( input.mResolved)
  912. continue;
  913. // find accessor
  914. input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
  915. // resolve accessor's data pointer as well, if neccessary
  916. const Accessor* acc = input.mResolved;
  917. if( !acc->mData)
  918. acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
  919. }
  920. // and the same for the per-index channels
  921. BOOST_FOREACH( InputChannel& input, pPerIndexChannels)
  922. {
  923. if( input.mResolved)
  924. continue;
  925. // ignore vertex pointer, it doesn't refer to an accessor
  926. if( input.mType == IT_Vertex)
  927. {
  928. // warn if the vertex channel does not refer to the <vertices> element in the same mesh
  929. if( input.mAccessor != pMesh->mVertexID)
  930. ThrowException( "Unsupported vertex referencing scheme. I fucking hate Collada.");
  931. continue;
  932. }
  933. // find accessor
  934. input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
  935. // resolve accessor's data pointer as well, if neccessary
  936. const Accessor* acc = input.mResolved;
  937. if( !acc->mData)
  938. acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
  939. }
  940. // now assemble vertex data according to those indices
  941. std::vector<size_t>::const_iterator idx = indices.begin();
  942. // For continued primitives, the given count does not come all in one <p>, but only one primitive per <p>
  943. size_t numPrimitives = pNumPrimitives;
  944. if( pPrimType == Prim_TriFans || pPrimType == Prim_Polygon)
  945. numPrimitives = 1;
  946. for( size_t a = 0; a < numPrimitives; a++)
  947. {
  948. // determine number of points for this primitive
  949. size_t numPoints = 0;
  950. switch( pPrimType)
  951. {
  952. case Prim_Lines: numPoints = 2; break;
  953. case Prim_Triangles: numPoints = 3; break;
  954. case Prim_Polylist: numPoints = pVCount[a]; break;
  955. case Prim_TriFans:
  956. case Prim_Polygon: numPoints = indices.size() / numOffsets; break;
  957. default:
  958. // LineStrip and TriStrip not supported due to expected index unmangling
  959. ThrowException( "Unsupported primitive type.");
  960. break;
  961. }
  962. // store the face size to later reconstruct the face from
  963. pMesh->mFaceSize.push_back( numPoints);
  964. // gather that number of vertices
  965. for( size_t b = 0; b < numPoints; b++)
  966. {
  967. // read all indices for this vertex. Yes, in a hacky static array
  968. assert( numOffsets < 20);
  969. static size_t vindex[20];
  970. for( size_t offsets = 0; offsets < numOffsets; ++offsets)
  971. vindex[offsets] = *idx++;
  972. // extract per-vertex channels using the global per-vertex offset
  973. BOOST_FOREACH( const InputChannel& input, pMesh->mPerVertexData)
  974. ExtractDataObjectFromChannel( input, vindex[perVertexOffset], pMesh);
  975. // and extract per-index channels using there specified offset
  976. BOOST_FOREACH( const InputChannel& input, pPerIndexChannels)
  977. ExtractDataObjectFromChannel( input, vindex[input.mOffset], pMesh);
  978. }
  979. }
  980. // if I ever get my hands on that guy who invented this steaming pile of indirection...
  981. TestClosing( "p");
  982. }
  983. // ------------------------------------------------------------------------------------------------
  984. // Extracts a single object from an input channel and stores it in the appropriate mesh data array
  985. void ColladaParser::ExtractDataObjectFromChannel( const InputChannel& pInput, size_t pLocalIndex, Mesh* pMesh)
  986. {
  987. // ignore vertex referrer - we handle them that separate
  988. if( pInput.mType == IT_Vertex)
  989. return;
  990. const Accessor& acc = *pInput.mResolved;
  991. if( pLocalIndex >= acc.mCount)
  992. ThrowException( boost::str( boost::format( "Invalid data index (%d/%d) in primitive specification") % pLocalIndex % acc.mCount));
  993. // get a pointer to the start of the data object referred to by the accessor and the local index
  994. const float* dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex* acc.mStride;
  995. // assemble according to the accessors component sub-offset list. We don't care, yet, what kind of object exactly we're extracting here
  996. float obj[4];
  997. for( size_t c = 0; c < 4; ++c)
  998. obj[c] = dataObject[acc.mSubOffset[c]];
  999. // now we reinterpret it according to the type we're reading here
  1000. switch( pInput.mType)
  1001. {
  1002. case IT_Position: // ignore all position streams except 0 - there can be only one position
  1003. if( pInput.mIndex == 0)
  1004. pMesh->mPositions.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1005. break;
  1006. case IT_Normal: // ignore all normal streams except 0 - there can be only one normal
  1007. if( pInput.mIndex == 0)
  1008. pMesh->mNormals.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1009. break;
  1010. case IT_Texcoord: // up to 4 texture coord sets are fine, ignore the others
  1011. if( pInput.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS)
  1012. pMesh->mTexCoords[pInput.mIndex].push_back( aiVector2D( obj[0], obj[1]));
  1013. break;
  1014. case IT_Color: // up to 4 color sets are fine, ignore the others
  1015. if( pInput.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS)
  1016. pMesh->mColors[pInput.mIndex].push_back( aiColor4D( obj[0], obj[1], obj[2], obj[3]));
  1017. break;
  1018. }
  1019. }
  1020. // ------------------------------------------------------------------------------------------------
  1021. // Reads the library of node hierarchies and scene parts
  1022. void ColladaParser::ReadSceneLibrary()
  1023. {
  1024. while( mReader->read())
  1025. {
  1026. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1027. {
  1028. // a visual scene - generate root node under its ID and let ReadNode() do the recursive work
  1029. if( IsElement( "visual_scene"))
  1030. {
  1031. // read ID. Is optional according to the spec, but how on earth should a scene_instance refer to it then?
  1032. int indexID = GetAttribute( "id");
  1033. const char* attrID = mReader->getAttributeValue( indexID);
  1034. // read name if given.
  1035. int indexName = TestAttribute( "name");
  1036. const char* attrName = "unnamed";
  1037. if( indexName > -1)
  1038. attrName = mReader->getAttributeValue( indexName);
  1039. // TODO: (thom) support SIDs
  1040. assert( TestAttribute( "sid") == -1);
  1041. // create a node and store it in the library under its ID
  1042. Node* node = new Node;
  1043. node->mID = attrID;
  1044. node->mName = attrName;
  1045. mNodeLibrary[node->mID] = node;
  1046. ReadSceneNode( node);
  1047. } else
  1048. {
  1049. // ignore the rest
  1050. SkipElement();
  1051. }
  1052. }
  1053. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1054. {
  1055. if( strcmp( mReader->getNodeName(), "library_visual_scenes") != 0)
  1056. ThrowException( "Expected end of \"library_visual_scenes\" element.");
  1057. break;
  1058. }
  1059. }
  1060. }
  1061. // ------------------------------------------------------------------------------------------------
  1062. // Reads a scene node's contents including children and stores it in the given node
  1063. void ColladaParser::ReadSceneNode( Node* pNode)
  1064. {
  1065. // quit immediately on <bla/> elements
  1066. if( mReader->isEmptyElement())
  1067. return;
  1068. while( mReader->read())
  1069. {
  1070. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1071. {
  1072. if( IsElement( "lookat"))
  1073. ReadNodeTransformation( pNode, TF_LOOKAT);
  1074. else if( IsElement( "matrix"))
  1075. ReadNodeTransformation( pNode, TF_MATRIX);
  1076. else if( IsElement( "rotate"))
  1077. ReadNodeTransformation( pNode, TF_ROTATE);
  1078. else if( IsElement( "scale"))
  1079. ReadNodeTransformation( pNode, TF_SCALE);
  1080. else if( IsElement( "skew"))
  1081. ReadNodeTransformation( pNode, TF_SKEW);
  1082. else if( IsElement( "translate"))
  1083. ReadNodeTransformation( pNode, TF_TRANSLATE);
  1084. else if( IsElement( "node"))
  1085. {
  1086. Node* child = new Node;
  1087. int attrID = TestAttribute( "id");
  1088. if( attrID > -1)
  1089. child->mID = mReader->getAttributeValue( attrID);
  1090. int attrName = TestAttribute( "name");
  1091. if( attrName > -1)
  1092. child->mName = mReader->getAttributeValue( attrName);
  1093. // TODO: (thom) support SIDs
  1094. // assert( TestAttribute( "sid") == -1);
  1095. pNode->mChildren.push_back( child);
  1096. child->mParent = pNode;
  1097. // read on recursively from there
  1098. ReadSceneNode( child);
  1099. } else if( IsElement( "instance_node"))
  1100. {
  1101. // test for it, in case we need to implement it
  1102. assert( false);
  1103. SkipElement();
  1104. } else if( IsElement( "instance_geometry"))
  1105. {
  1106. // Reference to a mesh, we possible material associations
  1107. ReadNodeGeometry( pNode);
  1108. } else
  1109. {
  1110. // skip everything else for the moment
  1111. SkipElement();
  1112. }
  1113. }
  1114. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1115. {
  1116. break;
  1117. }
  1118. }
  1119. }
  1120. // ------------------------------------------------------------------------------------------------
  1121. // Reads a node transformation entry of the given type and adds it to the given node's transformation list.
  1122. void ColladaParser::ReadNodeTransformation( Node* pNode, TransformType pType)
  1123. {
  1124. std::string tagName = mReader->getNodeName();
  1125. // how many parameters to read per transformation type
  1126. static const unsigned int sNumParameters[] = { 9, 4, 3, 3, 7, 16 };
  1127. const char* content = GetTextContent();
  1128. // read as many parameters and store in the transformation
  1129. Transform tf;
  1130. tf.mType = pType;
  1131. for( unsigned int a = 0; a < sNumParameters[pType]; a++)
  1132. {
  1133. // read a number
  1134. content = fast_atof_move( content, tf.f[a]);
  1135. // skip whitespace after it
  1136. SkipSpacesAndLineEnd( &content);
  1137. }
  1138. // place the transformation at the queue of the node
  1139. pNode->mTransforms.push_back( tf);
  1140. // and consum the closing tag
  1141. TestClosing( tagName.c_str());
  1142. }
  1143. // ------------------------------------------------------------------------------------------------
  1144. // Reads a mesh reference in a node and adds it to the node's mesh list
  1145. void ColladaParser::ReadNodeGeometry( Node* pNode)
  1146. {
  1147. // referred mesh is given as an attribute of the <instance_geometry> element
  1148. int attrUrl = GetAttribute( "url");
  1149. const char* url = mReader->getAttributeValue( attrUrl);
  1150. if( url[0] != '#')
  1151. ThrowException( "Unknown reference format");
  1152. Collada::MeshInstance instance;
  1153. instance.mMesh = url+1; // skipping the leading #
  1154. if( !mReader->isEmptyElement())
  1155. {
  1156. // read material associations. Ignore additional elements inbetween
  1157. while( mReader->read())
  1158. {
  1159. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1160. {
  1161. if( IsElement( "instance_material"))
  1162. {
  1163. // read ID of the geometry subgroup and the target material
  1164. int attrGroup = GetAttribute( "symbol");
  1165. std::string group = mReader->getAttributeValue( attrGroup);
  1166. int attrMaterial = GetAttribute( "target");
  1167. const char* urlMat = mReader->getAttributeValue( attrMaterial);
  1168. if( urlMat[0] != '#')
  1169. ThrowException( "Unknown reference format");
  1170. std::string mat = urlMat+1;
  1171. // store the association
  1172. instance.mMaterials[group] = mat;
  1173. }
  1174. }
  1175. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1176. {
  1177. if( strcmp( mReader->getNodeName(), "instance_geometry") == 0)
  1178. break;
  1179. }
  1180. }
  1181. }
  1182. // store it
  1183. pNode->mMeshes.push_back( instance);
  1184. }
  1185. // ------------------------------------------------------------------------------------------------
  1186. // Reads the collada scene
  1187. void ColladaParser::ReadScene()
  1188. {
  1189. while( mReader->read())
  1190. {
  1191. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1192. {
  1193. if( IsElement( "instance_visual_scene"))
  1194. {
  1195. // should be the first and only occurence
  1196. if( mRootNode)
  1197. ThrowException( "Invalid scene containing multiple root nodes");
  1198. // read the url of the scene to instance. Should be of format "#some_name"
  1199. int urlIndex = GetAttribute( "url");
  1200. const char* url = mReader->getAttributeValue( urlIndex);
  1201. if( url[0] != '#')
  1202. ThrowException( "Unknown reference format");
  1203. // find the referred scene, skip the leading #
  1204. NodeLibrary::const_iterator sit = mNodeLibrary.find( url+1);
  1205. if( sit == mNodeLibrary.end())
  1206. ThrowException( boost::str( boost::format( "Unable to resolve visual_scene reference \"%s\".") % url));
  1207. mRootNode = sit->second;
  1208. } else
  1209. {
  1210. SkipElement();
  1211. }
  1212. }
  1213. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1214. {
  1215. break;
  1216. }
  1217. }
  1218. }
  1219. // ------------------------------------------------------------------------------------------------
  1220. // Aborts the file reading with an exception
  1221. void ColladaParser::ThrowException( const std::string& pError) const
  1222. {
  1223. throw new ImportErrorException( boost::str( boost::format( "%s - %s") % mFileName % pError));
  1224. }
  1225. // ------------------------------------------------------------------------------------------------
  1226. // Skips all data until the end node of the current element
  1227. void ColladaParser::SkipElement()
  1228. {
  1229. // nothing to skip if it's an <element />
  1230. if( mReader->isEmptyElement())
  1231. return;
  1232. // reroute
  1233. SkipElement( mReader->getNodeName());
  1234. }
  1235. // ------------------------------------------------------------------------------------------------
  1236. // Skips all data until the end node of the given element
  1237. void ColladaParser::SkipElement( const char* pElement)
  1238. {
  1239. // copy the current node's name because it'a pointer to the reader's internal buffer,
  1240. // which is going to change with the upcoming parsing
  1241. std::string element = pElement;
  1242. while( mReader->read())
  1243. {
  1244. if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1245. if( mReader->getNodeName() == element)
  1246. break;
  1247. }
  1248. }
  1249. // ------------------------------------------------------------------------------------------------
  1250. // Tests for an opening element of the given name, throws an exception if not found
  1251. void ColladaParser::TestOpening( const char* pName)
  1252. {
  1253. // read element start
  1254. if( !mReader->read())
  1255. ThrowException( boost::str( boost::format( "Unexpected end of file while beginning of \"%s\" element.") % pName));
  1256. // whitespace in front is ok, just read again if found
  1257. if( mReader->getNodeType() == irr::io::EXN_TEXT)
  1258. if( !mReader->read())
  1259. ThrowException( boost::str( boost::format( "Unexpected end of file while reading beginning of \"%s\" element.") % pName));
  1260. if( mReader->getNodeType() != irr::io::EXN_ELEMENT || strcmp( mReader->getNodeName(), pName) != 0)
  1261. ThrowException( boost::str( boost::format( "Expected start of \"%s\" element.") % pName));
  1262. }
  1263. // ------------------------------------------------------------------------------------------------
  1264. // Tests for the closing tag of the given element, throws an exception if not found
  1265. void ColladaParser::TestClosing( const char* pName)
  1266. {
  1267. // read closing tag
  1268. if( !mReader->read())
  1269. ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of \"%s\" element.") % pName));
  1270. // whitespace in front is ok, just read again if found
  1271. if( mReader->getNodeType() == irr::io::EXN_TEXT)
  1272. if( !mReader->read())
  1273. ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of \"%s\" element.") % pName));
  1274. if( mReader->getNodeType() != irr::io::EXN_ELEMENT_END || strcmp( mReader->getNodeName(), pName) != 0)
  1275. ThrowException( boost::str( boost::format( "Expected end of \"%s\" element.") % pName));
  1276. }
  1277. // ------------------------------------------------------------------------------------------------
  1278. // Returns the index of the named attribute or -1 if not found. Does not throw, therefore useful for optional attributes
  1279. int ColladaParser::GetAttribute( const char* pAttr) const
  1280. {
  1281. int index = TestAttribute( pAttr);
  1282. if( index != -1)
  1283. return index;
  1284. // attribute not found -> throw an exception
  1285. ThrowException( boost::str( boost::format( "Expected attribute \"%s\" at element \"%s\".") % pAttr % mReader->getNodeName()));
  1286. return -1;
  1287. }
  1288. // ------------------------------------------------------------------------------------------------
  1289. // Tests the present element for the presence of one attribute, returns its index or throws an exception if not found
  1290. int ColladaParser::TestAttribute( const char* pAttr) const
  1291. {
  1292. for( int a = 0; a < mReader->getAttributeCount(); a++)
  1293. if( strcmp( mReader->getAttributeName( a), pAttr) == 0)
  1294. return a;
  1295. return -1;
  1296. }
  1297. // ------------------------------------------------------------------------------------------------
  1298. // Reads the text contents of an element, throws an exception if not given. Skips leading whitespace.
  1299. const char* ColladaParser::GetTextContent()
  1300. {
  1301. // present node should be the beginning of an element
  1302. if( mReader->getNodeType() != irr::io::EXN_ELEMENT || mReader->isEmptyElement())
  1303. ThrowException( "Expected opening element");
  1304. // read contents of the element
  1305. if( !mReader->read())
  1306. ThrowException( "Unexpected end of file while reading asset up_axis element.");
  1307. if( mReader->getNodeType() != irr::io::EXN_TEXT)
  1308. ThrowException( "Invalid contents in element \"up_axis\".");
  1309. // skip leading whitespace
  1310. const char* text = mReader->getNodeData();
  1311. SkipSpacesAndLineEnd( &text);
  1312. return text;
  1313. }
  1314. // ------------------------------------------------------------------------------------------------
  1315. // Calculates the resulting transformation fromm all the given transform steps
  1316. aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector<Transform>& pTransforms) const
  1317. {
  1318. aiMatrix4x4 res;
  1319. for( std::vector<Transform>::const_iterator it = pTransforms.begin(); it != pTransforms.end(); ++it)
  1320. {
  1321. const Transform& tf = *it;
  1322. switch( tf.mType)
  1323. {
  1324. case TF_LOOKAT:
  1325. // TODO: (thom)
  1326. assert( false);
  1327. break;
  1328. case TF_ROTATE:
  1329. {
  1330. aiMatrix4x4 rot;
  1331. float angle = tf.f[3] * float( AI_MATH_PI) / 180.0f;
  1332. aiVector3D axis( tf.f[0], tf.f[1], tf.f[2]);
  1333. aiMatrix4x4::Rotation( angle, axis, rot);
  1334. res *= rot;
  1335. break;
  1336. }
  1337. case TF_TRANSLATE:
  1338. {
  1339. aiMatrix4x4 trans;
  1340. aiMatrix4x4::Translation( aiVector3D( tf.f[0], tf.f[1], tf.f[2]), trans);
  1341. res *= trans;
  1342. break;
  1343. }
  1344. case TF_SCALE:
  1345. {
  1346. 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,
  1347. 0.0f, 0.0f, 0.0f, 1.0f);
  1348. res *= scale;
  1349. break;
  1350. }
  1351. case TF_SKEW:
  1352. // TODO: (thom)
  1353. assert( false);
  1354. break;
  1355. case TF_MATRIX:
  1356. {
  1357. 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],
  1358. tf.f[8], tf.f[9], tf.f[10], tf.f[11], tf.f[12], tf.f[13], tf.f[14], tf.f[15]);
  1359. res *= mat;
  1360. break;
  1361. }
  1362. default:
  1363. assert( false);
  1364. break;
  1365. }
  1366. }
  1367. return res;
  1368. }
  1369. // ------------------------------------------------------------------------------------------------
  1370. // Determines the input data type for the given semantic string
  1371. Collada::InputType ColladaParser::GetTypeForSemantic( const std::string& pSemantic)
  1372. {
  1373. if( pSemantic == "POSITION")
  1374. return IT_Position;
  1375. else if( pSemantic == "TEXCOORD")
  1376. return IT_Texcoord;
  1377. else if( pSemantic == "NORMAL")
  1378. return IT_Normal;
  1379. else if( pSemantic == "COLOR")
  1380. return IT_Color;
  1381. else if( pSemantic == "VERTEX")
  1382. return IT_Vertex;
  1383. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown vertex input type \"%s\". Ignoring.") % pSemantic));
  1384. return IT_Invalid;
  1385. }