ColladaParser.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development Team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the ASSIMP team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the ASSIMP Development Team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file ColladaParser.cpp
  35. * @brief Implementation of the Collada parser helper
  36. */
  37. #include "AssimpPCH.h"
  38. #ifndef ASSIMP_BUILD_NO_DAE_IMPORTER
  39. #include "ColladaParser.h"
  40. #include "fast_atof.h"
  41. #include "ParsingUtils.h"
  42. using namespace Assimp;
  43. using namespace Assimp::Collada;
  44. // ------------------------------------------------------------------------------------------------
  45. // Constructor to be privately used by Importer
  46. ColladaParser::ColladaParser( IOSystem* pIOHandler, const std::string& pFile)
  47. : mFileName( pFile)
  48. {
  49. mRootNode = NULL;
  50. mUnitSize = 1.0f;
  51. mUpDirection = UP_Z;
  52. // We assume the newest file format by default
  53. mFormat = FV_1_5_n;
  54. // open the file
  55. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  56. if( file.get() == NULL)
  57. throw new ImportErrorException( "Failed to open file " + pFile + ".");
  58. // generate a XML reader for it
  59. boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper( new CIrrXML_IOStreamReader( file.get()));
  60. mReader = irr::io::createIrrXMLReader( mIOWrapper.get());
  61. if( !mReader)
  62. ThrowException( "Collada: Unable to open file.");
  63. // start reading
  64. ReadContents();
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. // Destructor, private as well
  68. ColladaParser::~ColladaParser()
  69. {
  70. delete mReader;
  71. for( NodeLibrary::iterator it = mNodeLibrary.begin(); it != mNodeLibrary.end(); ++it)
  72. delete it->second;
  73. for( MeshLibrary::iterator it = mMeshLibrary.begin(); it != mMeshLibrary.end(); ++it)
  74. delete it->second;
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Read bool from text contents of current element
  78. bool ColladaParser::ReadBoolFromTextContent()
  79. {
  80. const char* cur = GetTextContent();
  81. return (!ASSIMP_strincmp(cur,"true",4) || '0' != *cur);
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. // Read float from text contents of current element
  85. float ColladaParser::ReadFloatFromTextContent()
  86. {
  87. const char* cur = GetTextContent();
  88. return fast_atof(cur);
  89. }
  90. // ------------------------------------------------------------------------------------------------
  91. // Reads the contents of the file
  92. void ColladaParser::ReadContents()
  93. {
  94. while( mReader->read())
  95. {
  96. // handle the root element "COLLADA"
  97. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  98. {
  99. if( IsElement( "COLLADA"))
  100. {
  101. // check for 'version' attribute
  102. const int attrib = TestAttribute("version");
  103. if (attrib != -1) {
  104. const char* version = mReader->getAttributeValue(attrib);
  105. if (!::strncmp(version,"1.5",3)) {
  106. mFormat = FV_1_5_n;
  107. DefaultLogger::get()->debug("Collada schema version is 1.5.n");
  108. }
  109. else if (!::strncmp(version,"1.4",3)) {
  110. mFormat = FV_1_4_n;
  111. DefaultLogger::get()->debug("Collada schema version is 1.4.n");
  112. }
  113. else if (!::strncmp(version,"1.3",3)) {
  114. mFormat = FV_1_3_n;
  115. DefaultLogger::get()->debug("Collada schema version is 1.3.n");
  116. }
  117. }
  118. ReadStructure();
  119. } else
  120. {
  121. DefaultLogger::get()->debug( boost::str( boost::format( "Ignoring global element \"%s\".") % mReader->getNodeName()));
  122. SkipElement();
  123. }
  124. } else
  125. {
  126. // skip everything else silently
  127. }
  128. }
  129. }
  130. // ------------------------------------------------------------------------------------------------
  131. // Reads the structure of the file
  132. void ColladaParser::ReadStructure()
  133. {
  134. while( mReader->read())
  135. {
  136. // beginning of elements
  137. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  138. if( IsElement( "asset"))
  139. ReadAssetInfo();
  140. else if( IsElement( "library_images"))
  141. ReadImageLibrary();
  142. else if( IsElement( "library_materials"))
  143. ReadMaterialLibrary();
  144. else if( IsElement( "library_effects"))
  145. ReadEffectLibrary();
  146. else if( IsElement( "library_geometries"))
  147. ReadGeometryLibrary();
  148. else if( IsElement( "library_visual_scenes"))
  149. ReadSceneLibrary();
  150. else if( IsElement( "library_lights"))
  151. ReadLightLibrary();
  152. else if( IsElement( "library_cameras"))
  153. ReadCameraLibrary();
  154. else if( IsElement( "library_nodes"))
  155. ReadSceneNode(NULL); /* some hacking to reuse this piece of code */
  156. else if( IsElement( "scene"))
  157. ReadScene();
  158. else
  159. SkipElement();
  160. }
  161. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  162. break;
  163. }
  164. }
  165. }
  166. // ------------------------------------------------------------------------------------------------
  167. // Reads asset informations such as coordinate system informations and legal blah
  168. void ColladaParser::ReadAssetInfo()
  169. {
  170. while( mReader->read())
  171. {
  172. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  173. {
  174. if( IsElement( "unit"))
  175. {
  176. // read unit data from the element's attributes
  177. int attrIndex = GetAttribute( "meter");
  178. mUnitSize = mReader->getAttributeValueAsFloat( attrIndex);
  179. // consume the trailing stuff
  180. if( !mReader->isEmptyElement())
  181. SkipElement();
  182. }
  183. else if( IsElement( "up_axis"))
  184. {
  185. // read content, strip whitespace, compare
  186. const char* content = GetTextContent();
  187. if( strncmp( content, "X_UP", 4) == 0)
  188. mUpDirection = UP_X;
  189. else if( strncmp( content, "Y_UP", 4) == 0)
  190. mUpDirection = UP_Y;
  191. else
  192. mUpDirection = UP_Z;
  193. // check element end
  194. TestClosing( "up_axis");
  195. } else
  196. {
  197. SkipElement();
  198. }
  199. }
  200. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  201. {
  202. if( strcmp( mReader->getNodeName(), "asset") != 0)
  203. ThrowException( "Expected end of \"asset\" element.");
  204. break;
  205. }
  206. }
  207. }
  208. // ------------------------------------------------------------------------------------------------
  209. // Reads the image library contents
  210. void ColladaParser::ReadImageLibrary()
  211. {
  212. while( mReader->read())
  213. {
  214. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  215. if( IsElement( "image"))
  216. {
  217. // read ID. Another entry which is "optional" by design but obligatory in reality
  218. int attrID = GetAttribute( "id");
  219. std::string id = mReader->getAttributeValue( attrID);
  220. // create an entry and store it in the library under its ID
  221. mImageLibrary[id] = Image();
  222. // read on from there
  223. ReadImage( mImageLibrary[id]);
  224. } else
  225. {
  226. // ignore the rest
  227. SkipElement();
  228. }
  229. }
  230. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  231. if( strcmp( mReader->getNodeName(), "library_images") != 0)
  232. ThrowException( "Expected end of \"library_images\" element.");
  233. break;
  234. }
  235. }
  236. }
  237. // ------------------------------------------------------------------------------------------------
  238. // Reads an image entry into the given image
  239. void ColladaParser::ReadImage( Collada::Image& pImage)
  240. {
  241. while( mReader->read())
  242. {
  243. if( mReader->getNodeType() == irr::io::EXN_ELEMENT){
  244. // Need to run different code paths here, depending on the Collada XSD version
  245. if( IsElement( "init_from"))
  246. {
  247. if (mFormat == FV_1_4_n) {
  248. // element content is filename - hopefully
  249. const char* sz = TestTextContent();
  250. if (sz)pImage.mFileName = sz;
  251. TestClosing( "init_from");
  252. }
  253. else if (mFormat == FV_1_5_n) {
  254. // make sure we skip over mip and array initializations, which
  255. // we don't support, but which could confuse the loader if
  256. // they're not skipped.
  257. int attrib = TestAttribute("array_index");
  258. if (attrib != -1 && mReader->getAttributeValueAsInt(attrib) > 0) {
  259. DefaultLogger::get()->warn("Collada: Ignoring texture array index");
  260. continue;
  261. }
  262. attrib = TestAttribute("mip_index");
  263. if (attrib != -1 && mReader->getAttributeValueAsInt(attrib) > 0) {
  264. DefaultLogger::get()->warn("Collada: Ignoring MIP map layer");
  265. continue;
  266. }
  267. // TODO: correctly jump over cube and volume maps?
  268. }
  269. }
  270. else if (mFormat == FV_1_5_n) {
  271. if( IsElement( "ref"))
  272. {
  273. // element content is filename - hopefully
  274. const char* sz = TestTextContent();
  275. if (sz)pImage.mFileName = sz;
  276. TestClosing( "ref");
  277. }
  278. else if( IsElement( "hex") && !pImage.mFileName.length())
  279. {
  280. // embedded image. get format
  281. const int attrib = TestAttribute("format");
  282. if (-1 == attrib)
  283. DefaultLogger::get()->warn("Collada: Unknown image file format");
  284. else pImage.mEmbeddedFormat = mReader->getAttributeValue(attrib);
  285. const char* data = GetTextContent();
  286. // hexadecimal-encoded binary octets. First of all, find the
  287. // required buffer size to reserve enough storage.
  288. const char* cur = data;
  289. while (!IsSpaceOrNewLine(*cur)) cur++;
  290. const unsigned int size = (unsigned int)(cur-data) * 2;
  291. pImage.mImageData.resize(size);
  292. for (unsigned int i = 0; i < size;++i) {
  293. pImage.mImageData[i] = HexOctetToDecimal(data+(i<<1));
  294. }
  295. TestClosing( "hex");
  296. }
  297. }
  298. else {
  299. // ignore the rest
  300. SkipElement();
  301. }
  302. }
  303. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  304. if( strcmp( mReader->getNodeName(), "image") == 0)
  305. break;
  306. }
  307. }
  308. }
  309. // ------------------------------------------------------------------------------------------------
  310. // Reads the material library
  311. void ColladaParser::ReadMaterialLibrary()
  312. {
  313. while( mReader->read())
  314. {
  315. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  316. if( IsElement( "material"))
  317. {
  318. // read ID. By now you propably know my opinion about this "specification"
  319. int attrID = GetAttribute( "id");
  320. std::string id = mReader->getAttributeValue( attrID);
  321. // create an entry and store it in the library under its ID
  322. ReadMaterial(mMaterialLibrary[id] = Material());
  323. } else
  324. {
  325. // ignore the rest
  326. SkipElement();
  327. }
  328. }
  329. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  330. if( strcmp( mReader->getNodeName(), "library_materials") != 0)
  331. ThrowException( "Expected end of \"library_materials\" element.");
  332. break;
  333. }
  334. }
  335. }
  336. // ------------------------------------------------------------------------------------------------
  337. // Reads the light library
  338. void ColladaParser::ReadLightLibrary()
  339. {
  340. while( mReader->read())
  341. {
  342. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  343. if( IsElement( "light"))
  344. {
  345. // read ID. By now you propably know my opinion about this "specification"
  346. int attrID = GetAttribute( "id");
  347. std::string id = mReader->getAttributeValue( attrID);
  348. // create an entry and store it in the library under its ID
  349. ReadLight(mLightLibrary[id] = Light());
  350. } else
  351. {
  352. // ignore the rest
  353. SkipElement();
  354. }
  355. }
  356. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  357. if( strcmp( mReader->getNodeName(), "library_lights") != 0)
  358. ThrowException( "Expected end of \"library_lights\" element.");
  359. break;
  360. }
  361. }
  362. }
  363. // ------------------------------------------------------------------------------------------------
  364. // Reads the camera library
  365. void ColladaParser::ReadCameraLibrary()
  366. {
  367. while( mReader->read())
  368. {
  369. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  370. if( IsElement( "camera"))
  371. {
  372. // read ID. By now you propably know my opinion about this "specification"
  373. int attrID = GetAttribute( "id");
  374. std::string id = mReader->getAttributeValue( attrID);
  375. // create an entry and store it in the library under its ID
  376. Camera& cam = mCameraLibrary[id];
  377. attrID = TestAttribute( "name");
  378. if (attrID != -1)
  379. cam.mName = mReader->getAttributeValue( attrID);
  380. ReadCamera(cam);
  381. } else
  382. {
  383. // ignore the rest
  384. SkipElement();
  385. }
  386. }
  387. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  388. if( strcmp( mReader->getNodeName(), "library_cameras") != 0)
  389. ThrowException( "Expected end of \"library_cameras\" element.");
  390. break;
  391. }
  392. }
  393. }
  394. // ------------------------------------------------------------------------------------------------
  395. // Reads a material entry into the given material
  396. void ColladaParser::ReadMaterial( Collada::Material& pMaterial)
  397. {
  398. while( mReader->read())
  399. {
  400. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  401. if( IsElement( "instance_effect"))
  402. {
  403. // referred effect by URL
  404. int attrUrl = GetAttribute( "url");
  405. const char* url = mReader->getAttributeValue( attrUrl);
  406. if( url[0] != '#')
  407. ThrowException( "Unknown reference format");
  408. pMaterial.mEffect = url+1;
  409. SkipElement();
  410. } else
  411. {
  412. // ignore the rest
  413. SkipElement();
  414. }
  415. }
  416. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  417. if( strcmp( mReader->getNodeName(), "material") != 0)
  418. ThrowException( "Expected end of \"material\" element.");
  419. break;
  420. }
  421. }
  422. }
  423. // ------------------------------------------------------------------------------------------------
  424. // Reads a light entry into the given light
  425. void ColladaParser::ReadLight( Collada::Light& pLight)
  426. {
  427. while( mReader->read())
  428. {
  429. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  430. if (IsElement("spot")) {
  431. pLight.mType = aiLightSource_SPOT;
  432. }
  433. else if (IsElement("ambient")) {
  434. pLight.mType = aiLightSource_AMBIENT;
  435. }
  436. else if (IsElement("directional")) {
  437. pLight.mType = aiLightSource_DIRECTIONAL;
  438. }
  439. else if (IsElement("point")) {
  440. pLight.mType = aiLightSource_POINT;
  441. }
  442. else if (IsElement("color")) {
  443. // text content contains 3 floats
  444. const char* content = GetTextContent();
  445. content = fast_atof_move( content, (float&)pLight.mColor.r);
  446. SkipSpacesAndLineEnd( &content);
  447. content = fast_atof_move( content, (float&)pLight.mColor.g);
  448. SkipSpacesAndLineEnd( &content);
  449. content = fast_atof_move( content, (float&)pLight.mColor.b);
  450. SkipSpacesAndLineEnd( &content);
  451. TestClosing( "color");
  452. }
  453. else if (IsElement("constant_attenuation")) {
  454. pLight.mAttConstant = ReadFloatFromTextContent();
  455. TestClosing("constant_attenuation");
  456. }
  457. else if (IsElement("linear_attenuation")) {
  458. pLight.mAttLinear = ReadFloatFromTextContent();
  459. TestClosing("linear_attenuation");
  460. }
  461. else if (IsElement("quadratic_attenuation")) {
  462. pLight.mAttQuadratic = ReadFloatFromTextContent();
  463. TestClosing("quadratic_attenuation");
  464. }
  465. else if (IsElement("falloff_angle")) {
  466. pLight.mFalloffAngle = ReadFloatFromTextContent();
  467. TestClosing("falloff_angle");
  468. }
  469. else if (IsElement("falloff_exponent")) {
  470. pLight.mFalloffExponent = ReadFloatFromTextContent();
  471. TestClosing("falloff_exponent");
  472. }
  473. // FCOLLADA extensions
  474. // -------------------------------------------------------
  475. else if (IsElement("outer_cone")) {
  476. pLight.mOuterAngle = ReadFloatFromTextContent();
  477. TestClosing("outer_cone");
  478. }
  479. // ... and this one is even deprecated
  480. else if (IsElement("penumbra_angle")) {
  481. pLight.mPenumbraAngle = ReadFloatFromTextContent();
  482. TestClosing("penumbra_angle");
  483. }
  484. else if (IsElement("intensity")) {
  485. pLight.mIntensity = ReadFloatFromTextContent();
  486. TestClosing("intensity");
  487. }
  488. }
  489. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  490. if( strcmp( mReader->getNodeName(), "light") == 0)
  491. break;
  492. }
  493. }
  494. }
  495. // ------------------------------------------------------------------------------------------------
  496. // Reads a camera entry into the given light
  497. void ColladaParser::ReadCamera( Collada::Camera& pCamera)
  498. {
  499. while( mReader->read())
  500. {
  501. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  502. if (IsElement("orthographic")) {
  503. pCamera.mOrtho = true;
  504. }
  505. else if (IsElement("xfov") || IsElement("xmag")) {
  506. pCamera.mHorFov = ReadFloatFromTextContent();
  507. TestClosing((pCamera.mOrtho ? "xmag" : "xfov"));
  508. }
  509. else if (IsElement("yfov") || IsElement("ymag")) {
  510. pCamera.mVerFov = ReadFloatFromTextContent();
  511. TestClosing((pCamera.mOrtho ? "ymag" : "yfov"));
  512. }
  513. else if (IsElement("aspect_ratio")) {
  514. pCamera.mAspect = ReadFloatFromTextContent();
  515. TestClosing("aspect_ratio");
  516. }
  517. else if (IsElement("znear")) {
  518. pCamera.mZNear = ReadFloatFromTextContent();
  519. TestClosing("znear");
  520. }
  521. else if (IsElement("zfar")) {
  522. pCamera.mZFar = ReadFloatFromTextContent();
  523. TestClosing("zfar");
  524. }
  525. }
  526. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  527. if( strcmp( mReader->getNodeName(), "camera") == 0)
  528. break;
  529. }
  530. }
  531. }
  532. // ------------------------------------------------------------------------------------------------
  533. // Reads the effect library
  534. void ColladaParser::ReadEffectLibrary()
  535. {
  536. while( mReader->read())
  537. {
  538. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  539. if( IsElement( "effect"))
  540. {
  541. // read ID. Do I have to repeat my ranting about "optional" attributes?
  542. // Alex: .... no, not necessary. Please shut up and leave more space for
  543. // me to complain about the fucking Collada spec with its fucking
  544. // 'optional' attributes ...
  545. int attrID = GetAttribute( "id");
  546. std::string id = mReader->getAttributeValue( attrID);
  547. // create an entry and store it in the library under its ID
  548. mEffectLibrary[id] = Effect();
  549. // read on from there
  550. ReadEffect( mEffectLibrary[id]);
  551. } else
  552. {
  553. // ignore the rest
  554. SkipElement();
  555. }
  556. }
  557. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  558. if( strcmp( mReader->getNodeName(), "library_effects") != 0)
  559. ThrowException( "Expected end of \"library_effects\" element.");
  560. break;
  561. }
  562. }
  563. }
  564. // ------------------------------------------------------------------------------------------------
  565. // Reads an effect entry into the given effect
  566. void ColladaParser::ReadEffect( Collada::Effect& pEffect)
  567. {
  568. // for the moment we don't support any other type of effect.
  569. // TODO: (thom) Rewrite this so that it ignores the whole effect instead of bailing out
  570. TestOpening( "profile_COMMON");
  571. while( mReader->read())
  572. {
  573. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  574. {
  575. if( IsElement( "newparam")) {
  576. // save ID
  577. int attrSID = GetAttribute( "sid");
  578. std::string sid = mReader->getAttributeValue( attrSID);
  579. pEffect.mParams[sid] = EffectParam();
  580. ReadEffectParam( pEffect.mParams[sid]);
  581. }
  582. else if( IsElement( "technique"))
  583. {
  584. // just syntactic sugar
  585. }
  586. /* Shading modes */
  587. else if( IsElement( "phong"))
  588. pEffect.mShadeType = Shade_Phong;
  589. else if( IsElement( "constant"))
  590. pEffect.mShadeType = Shade_Constant;
  591. else if( IsElement( "lambert"))
  592. pEffect.mShadeType = Shade_Lambert;
  593. else if( IsElement( "blinn"))
  594. pEffect.mShadeType = Shade_Blinn;
  595. /* Color + texture properties */
  596. else if( IsElement( "emission"))
  597. ReadEffectColor( pEffect.mEmissive, pEffect.mTexEmissive);
  598. else if( IsElement( "ambient"))
  599. ReadEffectColor( pEffect.mAmbient, pEffect.mTexAmbient);
  600. else if( IsElement( "diffuse"))
  601. ReadEffectColor( pEffect.mDiffuse, pEffect.mTexDiffuse);
  602. else if( IsElement( "specular"))
  603. ReadEffectColor( pEffect.mSpecular, pEffect.mTexSpecular);
  604. else if( IsElement( "reflective")) {
  605. ReadEffectColor( pEffect.mReflective, pEffect.mTexReflective);
  606. }
  607. else if( IsElement( "transparent"))
  608. ReadEffectColor( pEffect.mTransparent,pEffect.mTexTransparent);
  609. else if( IsElement( "shininess"))
  610. ReadEffectFloat( pEffect.mShininess);
  611. /* Single scalar properties */
  612. else if( IsElement( "transparency"))
  613. ReadEffectFloat( pEffect.mTransparency);
  614. else if( IsElement( "index_of_refraction"))
  615. ReadEffectFloat( pEffect.mRefractIndex);
  616. // GOOGLEEARTH/OKINO extensions
  617. // -------------------------------------------------------
  618. else if( IsElement( "double_sided"))
  619. pEffect.mDoubleSided = ReadBoolFromTextContent();
  620. // FCOLLADA extensions
  621. // -------------------------------------------------------
  622. else if( IsElement( "bump")) {
  623. aiColor4D dummy;
  624. ReadEffectColor( dummy,pEffect.mTexBump);
  625. }
  626. // MAX3D extensions
  627. // -------------------------------------------------------
  628. else if( IsElement( "wireframe")) {
  629. pEffect.mWireframe = ReadBoolFromTextContent();
  630. TestClosing( "wireframe");
  631. }
  632. else if( IsElement( "faceted")) {
  633. pEffect.mFaceted = ReadBoolFromTextContent();
  634. TestClosing( "faceted");
  635. }
  636. #if 0
  637. else {
  638. // ignore the rest
  639. SkipElement();
  640. }
  641. #endif
  642. }
  643. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  644. if( strcmp( mReader->getNodeName(), "effect") == 0)
  645. break;
  646. }
  647. }
  648. }
  649. // ------------------------------------------------------------------------------------------------
  650. // Read texture wrapping + UV transform settings from a profile==Maya chunk
  651. void ColladaParser::ReadSamplerProperties( Sampler& out )
  652. {
  653. if (mReader->isEmptyElement())
  654. return;
  655. while( mReader->read())
  656. {
  657. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  658. // MAYA extensions
  659. // -------------------------------------------------------
  660. if( IsElement( "wrapU")) {
  661. out.mWrapU = ReadBoolFromTextContent();
  662. TestClosing( "wrapU");
  663. }
  664. else if( IsElement( "wrapV")) {
  665. out.mWrapU = ReadBoolFromTextContent();
  666. TestClosing( "wrapV");
  667. }
  668. if( IsElement( "mirrorU")) {
  669. out.mMirrorU = ReadBoolFromTextContent();
  670. TestClosing( "mirrorU");
  671. }
  672. else if( IsElement( "mirrorV")) {
  673. out.mMirrorU = ReadBoolFromTextContent();
  674. TestClosing( "mirrorV");
  675. }
  676. else if( IsElement( "repeatU")) {
  677. out.mTransform.mScaling.x = ReadFloatFromTextContent();
  678. TestClosing( "repeatU");
  679. }
  680. else if( IsElement( "repeatV")) {
  681. out.mTransform.mScaling.y = ReadFloatFromTextContent();
  682. TestClosing( "repeatV");
  683. }
  684. else if( IsElement( "offsetU")) {
  685. out.mTransform.mTranslation.x = ReadFloatFromTextContent();
  686. TestClosing( "offsetU");
  687. }
  688. else if( IsElement( "offsetV")) {
  689. out.mTransform.mTranslation.x = ReadFloatFromTextContent();
  690. TestClosing( "offsetV");
  691. }
  692. else if( IsElement( "rotateUV")) {
  693. out.mTransform.mRotation = ReadFloatFromTextContent();
  694. TestClosing( "rotateUV");
  695. }
  696. else if( IsElement( "blend_mode")) {
  697. const char* sz = GetTextContent();
  698. // http://www.feelingsoftware.com/content/view/55/72/lang,en/
  699. // NONE, OVER, IN, OUT, ADD, SUBTRACT, MULTIPLY, DIFFERENCE, LIGHTEN, DARKEN, SATURATE, DESATURATE and ILLUMINATE
  700. if (0 == ASSIMP_strincmp(sz,"ADD",3))
  701. out.mOp = aiTextureOp_Add;
  702. else if (0 == ASSIMP_strincmp(sz,"SUBTRACT",8))
  703. out.mOp = aiTextureOp_Subtract;
  704. else if (0 == ASSIMP_strincmp(sz,"MULTIPLY",8))
  705. out.mOp = aiTextureOp_Multiply;
  706. else {
  707. DefaultLogger::get()->warn("Collada: Unsupported MAYA texture blend mode");
  708. }
  709. TestClosing( "blend_mode");
  710. }
  711. // OKINO extensions
  712. // -------------------------------------------------------
  713. else if( IsElement( "weighting")) {
  714. out.mWeighting = ReadFloatFromTextContent();
  715. TestClosing( "weighting");
  716. }
  717. else if( IsElement( "mix_with_previous_layer")) {
  718. out.mMixWithPrevious = ReadFloatFromTextContent();
  719. TestClosing( "mix_with_previous_layer");
  720. }
  721. // MAX3D extensions
  722. // -------------------------------------------------------
  723. else if( IsElement( "amount")) {
  724. out.mWeighting = ReadFloatFromTextContent();
  725. TestClosing( "amount");
  726. }
  727. }
  728. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  729. if( strcmp( mReader->getNodeName(), "technique") == 0)
  730. break;
  731. }
  732. }
  733. }
  734. // ------------------------------------------------------------------------------------------------
  735. // Reads an effect entry containing a color or a texture defining that color
  736. void ColladaParser::ReadEffectColor( aiColor4D& pColor, Sampler& pSampler)
  737. {
  738. if (mReader->isEmptyElement())
  739. return;
  740. // Save current element name
  741. const std::string curElem = mReader->getNodeName();
  742. while( mReader->read())
  743. {
  744. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  745. if( IsElement( "color"))
  746. {
  747. // text content contains 4 floats
  748. const char* content = GetTextContent();
  749. content = fast_atof_move( content, (float&)pColor.r);
  750. SkipSpacesAndLineEnd( &content);
  751. content = fast_atof_move( content, (float&)pColor.g);
  752. SkipSpacesAndLineEnd( &content);
  753. content = fast_atof_move( content, (float&)pColor.b);
  754. SkipSpacesAndLineEnd( &content);
  755. content = fast_atof_move( content, (float&)pColor.a);
  756. SkipSpacesAndLineEnd( &content);
  757. TestClosing( "color");
  758. }
  759. else if( IsElement( "texture"))
  760. {
  761. // get name of source textur/sampler
  762. int attrTex = GetAttribute( "texture");
  763. pSampler.mName = mReader->getAttributeValue( attrTex);
  764. // get name of UV source channel
  765. attrTex = GetAttribute( "texcoord");
  766. pSampler.mUVChannel = mReader->getAttributeValue( attrTex);
  767. //SkipElement();
  768. }
  769. else if( IsElement( "technique"))
  770. {
  771. const int _profile = GetAttribute( "profile");
  772. const char* profile = mReader->getAttributeValue( _profile );
  773. // Some extensions are quite useful ... ReadSamplerProperties processes
  774. // several extensions in MAYA, OKINO and MAX3D profiles.
  775. if (!::strcmp(profile,"MAYA") || !::strcmp(profile,"MAX3D") || !::strcmp(profile,"OKINO"))
  776. {
  777. // get more information on this sampler
  778. ReadSamplerProperties(pSampler);
  779. }
  780. else SkipElement();
  781. }
  782. else
  783. {
  784. // ignore the rest
  785. SkipElement();
  786. }
  787. }
  788. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){
  789. if (mReader->getNodeName() == curElem)
  790. break;
  791. }
  792. }
  793. }
  794. // ------------------------------------------------------------------------------------------------
  795. // Reads an effect entry containing a float
  796. void ColladaParser::ReadEffectFloat( float& pFloat)
  797. {
  798. while( mReader->read())
  799. {
  800. if( mReader->getNodeType() == irr::io::EXN_ELEMENT){
  801. if( IsElement( "float"))
  802. {
  803. // text content contains a single floats
  804. const char* content = GetTextContent();
  805. content = fast_atof_move( content, pFloat);
  806. SkipSpacesAndLineEnd( &content);
  807. TestClosing( "float");
  808. } else
  809. {
  810. // ignore the rest
  811. SkipElement();
  812. }
  813. }
  814. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){
  815. break;
  816. }
  817. }
  818. }
  819. // ------------------------------------------------------------------------------------------------
  820. // Reads an effect parameter specification of any kind
  821. void ColladaParser::ReadEffectParam( Collada::EffectParam& pParam)
  822. {
  823. while( mReader->read())
  824. {
  825. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  826. if( IsElement( "surface"))
  827. {
  828. // image ID given inside <init_from> tags
  829. TestOpening( "init_from");
  830. const char* content = GetTextContent();
  831. pParam.mType = Param_Surface;
  832. pParam.mReference = content;
  833. TestClosing( "init_from");
  834. // don't care for remaining stuff
  835. SkipElement( "surface");
  836. }
  837. else if( IsElement( "sampler2D"))
  838. {
  839. // surface ID is given inside <source> tags
  840. TestOpening( "source");
  841. const char* content = GetTextContent();
  842. pParam.mType = Param_Sampler;
  843. pParam.mReference = content;
  844. TestClosing( "source");
  845. // don't care for remaining stuff
  846. SkipElement( "sampler2D");
  847. } else
  848. {
  849. // ignore unknown element
  850. SkipElement();
  851. }
  852. }
  853. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  854. break;
  855. }
  856. }
  857. }
  858. // ------------------------------------------------------------------------------------------------
  859. // Reads the geometry library contents
  860. void ColladaParser::ReadGeometryLibrary()
  861. {
  862. while( mReader->read())
  863. {
  864. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  865. {
  866. if( IsElement( "geometry"))
  867. {
  868. // read ID. Another entry which is "optional" by design but obligatory in reality
  869. int indexID = GetAttribute( "id");
  870. std::string id = mReader->getAttributeValue( indexID);
  871. // TODO: (thom) support SIDs
  872. // ai_assert( TestAttribute( "sid") == -1);
  873. // create a mesh and store it in the library under its ID
  874. Mesh* mesh = new Mesh;
  875. mMeshLibrary[id] = mesh;
  876. // read on from there
  877. ReadGeometry( mesh);
  878. } else
  879. {
  880. // ignore the rest
  881. SkipElement();
  882. }
  883. }
  884. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  885. {
  886. if( strcmp( mReader->getNodeName(), "library_geometries") != 0)
  887. ThrowException( "Expected end of \"library_geometries\" element.");
  888. break;
  889. }
  890. }
  891. }
  892. // ------------------------------------------------------------------------------------------------
  893. // Reads a geometry from the geometry library.
  894. void ColladaParser::ReadGeometry( Collada::Mesh* pMesh)
  895. {
  896. while( mReader->read())
  897. {
  898. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  899. {
  900. if( IsElement( "mesh"))
  901. {
  902. // read on from there
  903. ReadMesh( pMesh);
  904. } else
  905. {
  906. // ignore the rest
  907. SkipElement();
  908. }
  909. }
  910. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  911. {
  912. if( strcmp( mReader->getNodeName(), "geometry") != 0)
  913. ThrowException( "Expected end of \"geometry\" element.");
  914. break;
  915. }
  916. }
  917. }
  918. // ------------------------------------------------------------------------------------------------
  919. // Reads a mesh from the geometry library
  920. void ColladaParser::ReadMesh( Mesh* pMesh)
  921. {
  922. // I'm doing a dirty state parsing here because I don't want to open another submethod for it.
  923. // There's a <source> tag defining the name for the accessor inside, and possible a <float_array>
  924. // with it's own ID. This string contains the current source's ID if parsing is inside a <source> element.
  925. std::string presentSourceID;
  926. while( mReader->read())
  927. {
  928. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  929. {
  930. if( IsElement( "source"))
  931. {
  932. // beginning of a source element - store ID for the inner elements
  933. int attrID = GetAttribute( "id");
  934. presentSourceID = mReader->getAttributeValue( attrID);
  935. }
  936. else if( IsElement( "float_array"))
  937. {
  938. ReadFloatArray();
  939. }
  940. else if( IsElement( "technique_common"))
  941. {
  942. // I don't fucking care for your profiles bullshit
  943. }
  944. else if( IsElement( "accessor"))
  945. {
  946. ReadAccessor( presentSourceID);
  947. }
  948. else if( IsElement( "vertices"))
  949. {
  950. // read per-vertex mesh data
  951. ReadVertexData( pMesh);
  952. }
  953. else if( IsElement( "triangles") || IsElement( "lines") || IsElement( "linestrips")
  954. || IsElement( "polygons") || IsElement( "polylist") || IsElement( "trifans") || IsElement( "tristrips"))
  955. {
  956. // read per-index mesh data and faces setup
  957. ReadIndexData( pMesh);
  958. } else
  959. {
  960. // ignore the rest
  961. SkipElement();
  962. }
  963. }
  964. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  965. {
  966. if( strcmp( mReader->getNodeName(), "source") == 0)
  967. {
  968. // end of <source> - reset present source ID
  969. presentSourceID.clear();
  970. }
  971. else if( strcmp( mReader->getNodeName(), "technique_common") == 0)
  972. {
  973. // end of another meaningless element - read over it
  974. }
  975. else if( strcmp( mReader->getNodeName(), "mesh") == 0)
  976. {
  977. // end of <mesh> element - we're done here
  978. break;
  979. } else
  980. {
  981. // everything else should be punished
  982. ThrowException( "Expected end of \"mesh\" element.");
  983. }
  984. }
  985. }
  986. }
  987. // ------------------------------------------------------------------------------------------------
  988. // Reads a data array holding a number of floats, and stores it in the global library
  989. void ColladaParser::ReadFloatArray()
  990. {
  991. // read attributes
  992. int indexID = GetAttribute( "id");
  993. std::string id = mReader->getAttributeValue( indexID);
  994. int indexCount = GetAttribute( "count");
  995. unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( indexCount);
  996. const char* content = GetTextContent();
  997. // read values and store inside an array in the data library
  998. mDataLibrary[id] = Data();
  999. Data& data = mDataLibrary[id];
  1000. data.mValues.reserve( count);
  1001. for( unsigned int a = 0; a < count; a++)
  1002. {
  1003. if( *content == 0)
  1004. ThrowException( "Expected more values while reading float_array contents.");
  1005. float value;
  1006. // read a number
  1007. content = fast_atof_move( content, value);
  1008. data.mValues.push_back( value);
  1009. // skip whitespace after it
  1010. SkipSpacesAndLineEnd( &content);
  1011. }
  1012. // test for closing tag
  1013. TestClosing( "float_array");
  1014. }
  1015. // ------------------------------------------------------------------------------------------------
  1016. // Reads an accessor and stores it in the global library
  1017. void ColladaParser::ReadAccessor( const std::string& pID)
  1018. {
  1019. // read accessor attributes
  1020. int attrSource = GetAttribute( "source");
  1021. const char* source = mReader->getAttributeValue( attrSource);
  1022. if( source[0] != '#')
  1023. ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\".") % source));
  1024. int attrCount = GetAttribute( "count");
  1025. unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( attrCount);
  1026. int attrOffset = TestAttribute( "offset");
  1027. unsigned int offset = 0;
  1028. if( attrOffset > -1)
  1029. offset = (unsigned int) mReader->getAttributeValueAsInt( attrOffset);
  1030. int attrStride = TestAttribute( "stride");
  1031. unsigned int stride = 1;
  1032. if( attrStride > -1)
  1033. stride = (unsigned int) mReader->getAttributeValueAsInt( attrStride);
  1034. // store in the library under the given ID
  1035. mAccessorLibrary[pID] = Accessor();
  1036. Accessor& acc = mAccessorLibrary[pID];
  1037. acc.mCount = count;
  1038. acc.mOffset = offset;
  1039. acc.mStride = stride;
  1040. acc.mSource = source+1; // ignore the leading '#'
  1041. // and read the components
  1042. while( mReader->read())
  1043. {
  1044. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1045. {
  1046. if( IsElement( "param"))
  1047. {
  1048. // read data param
  1049. int attrName = TestAttribute( "name");
  1050. std::string name;
  1051. if( attrName > -1)
  1052. {
  1053. name = mReader->getAttributeValue( attrName);
  1054. // analyse for common type components and store it's sub-offset in the corresponding field
  1055. /* Cartesian coordinates */
  1056. if( name == "X") acc.mSubOffset[0] = acc.mParams.size();
  1057. else if( name == "Y") acc.mSubOffset[1] = acc.mParams.size();
  1058. else if( name == "Z") acc.mSubOffset[2] = acc.mParams.size();
  1059. /* RGBA colors */
  1060. else if( name == "R") acc.mSubOffset[0] = acc.mParams.size();
  1061. else if( name == "G") acc.mSubOffset[1] = acc.mParams.size();
  1062. else if( name == "B") acc.mSubOffset[2] = acc.mParams.size();
  1063. else if( name == "A") acc.mSubOffset[3] = acc.mParams.size();
  1064. /* UVWQ (STPQ) texture coordinates */
  1065. else if( name == "S") acc.mSubOffset[0] = acc.mParams.size();
  1066. else if( name == "T") acc.mSubOffset[1] = acc.mParams.size();
  1067. else if( name == "P") acc.mSubOffset[2] = acc.mParams.size();
  1068. // else if( name == "Q") acc.mSubOffset[3] = acc.mParams.size();
  1069. /* 4D uv coordinates are not supported in Assimp */
  1070. /* Generic extra data, interpreted as UV data, too*/
  1071. else if( name == "U") acc.mSubOffset[0] = acc.mParams.size();
  1072. else if( name == "V") acc.mSubOffset[1] = acc.mParams.size();
  1073. else
  1074. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown accessor parameter \"%s\". Ignoring data channel.") % name));
  1075. }
  1076. acc.mParams.push_back( name);
  1077. // skip remaining stuff of this element, if any
  1078. SkipElement();
  1079. } else
  1080. {
  1081. ThrowException( "Unexpected sub element in tag \"accessor\".");
  1082. }
  1083. }
  1084. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1085. {
  1086. if( strcmp( mReader->getNodeName(), "accessor") != 0)
  1087. ThrowException( "Expected end of \"accessor\" element.");
  1088. break;
  1089. }
  1090. }
  1091. }
  1092. // ------------------------------------------------------------------------------------------------
  1093. // Reads input declarations of per-vertex mesh data into the given mesh
  1094. void ColladaParser::ReadVertexData( Mesh* pMesh)
  1095. {
  1096. // extract the ID of the <vertices> element. Not that we care, but to catch strange referencing schemes we should warn about
  1097. int attrID= GetAttribute( "id");
  1098. pMesh->mVertexID = mReader->getAttributeValue( attrID);
  1099. // a number of <input> elements
  1100. while( mReader->read())
  1101. {
  1102. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1103. {
  1104. if( IsElement( "input"))
  1105. {
  1106. ReadInputChannel( pMesh->mPerVertexData);
  1107. } else
  1108. {
  1109. ThrowException( "Unexpected sub element in tag \"vertices\".");
  1110. }
  1111. }
  1112. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1113. {
  1114. if( strcmp( mReader->getNodeName(), "vertices") != 0)
  1115. ThrowException( "Expected end of \"vertices\" element.");
  1116. break;
  1117. }
  1118. }
  1119. }
  1120. // ------------------------------------------------------------------------------------------------
  1121. // Reads input declarations of per-index mesh data into the given mesh
  1122. void ColladaParser::ReadIndexData( Mesh* pMesh)
  1123. {
  1124. std::vector<size_t> vcount;
  1125. std::vector<InputChannel> perIndexData;
  1126. // read primitive count from the attribute
  1127. int attrCount = GetAttribute( "count");
  1128. size_t numPrimitives = (size_t) mReader->getAttributeValueAsInt( attrCount);
  1129. // material subgroup
  1130. int attrMaterial = TestAttribute( "material");
  1131. SubMesh subgroup;
  1132. if( attrMaterial > -1)
  1133. subgroup.mMaterial = mReader->getAttributeValue( attrMaterial);
  1134. subgroup.mNumFaces = numPrimitives;
  1135. pMesh->mSubMeshes.push_back( subgroup);
  1136. // distinguish between polys and triangles
  1137. std::string elementName = mReader->getNodeName();
  1138. PrimitiveType primType = Prim_Invalid;
  1139. if( IsElement( "lines"))
  1140. primType = Prim_Lines;
  1141. else if( IsElement( "linestrips"))
  1142. primType = Prim_LineStrip;
  1143. else if( IsElement( "polygons"))
  1144. primType = Prim_Polygon;
  1145. else if( IsElement( "polylist"))
  1146. primType = Prim_Polylist;
  1147. else if( IsElement( "triangles"))
  1148. primType = Prim_Triangles;
  1149. else if( IsElement( "trifans"))
  1150. primType = Prim_TriFans;
  1151. else if( IsElement( "tristrips"))
  1152. primType = Prim_TriStrips;
  1153. ai_assert( primType != Prim_Invalid);
  1154. // also a number of <input> elements, but in addition a <p> primitive collection and propably index counts for all primitives
  1155. while( mReader->read())
  1156. {
  1157. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1158. {
  1159. if( IsElement( "input"))
  1160. {
  1161. ReadInputChannel( perIndexData);
  1162. }
  1163. else if( IsElement( "vcount"))
  1164. {
  1165. if( !mReader->isEmptyElement())
  1166. {
  1167. // case <polylist> - specifies the number of indices for each polygon
  1168. const char* content = GetTextContent();
  1169. vcount.reserve( numPrimitives);
  1170. for( unsigned int a = 0; a < numPrimitives; a++)
  1171. {
  1172. if( *content == 0)
  1173. ThrowException( "Expected more values while reading vcount contents.");
  1174. // read a number
  1175. vcount.push_back( (size_t) strtol10( content, &content));
  1176. // skip whitespace after it
  1177. SkipSpacesAndLineEnd( &content);
  1178. }
  1179. TestClosing( "vcount");
  1180. }
  1181. }
  1182. else if( IsElement( "p"))
  1183. {
  1184. if( !mReader->isEmptyElement())
  1185. {
  1186. // now here the actual fun starts - these are the indices to construct the mesh data from
  1187. ReadPrimitives( pMesh, perIndexData, numPrimitives, vcount, primType);
  1188. }
  1189. } else
  1190. {
  1191. ThrowException( "Unexpected sub element in tag \"vertices\".");
  1192. }
  1193. }
  1194. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1195. {
  1196. if( mReader->getNodeName() != elementName)
  1197. ThrowException( boost::str( boost::format( "Expected end of \"%s\" element.") % elementName));
  1198. break;
  1199. }
  1200. }
  1201. }
  1202. // ------------------------------------------------------------------------------------------------
  1203. // Reads a single input channel element and stores it in the given array, if valid
  1204. void ColladaParser::ReadInputChannel( std::vector<InputChannel>& poChannels)
  1205. {
  1206. InputChannel channel;
  1207. // read semantic
  1208. int attrSemantic = GetAttribute( "semantic");
  1209. std::string semantic = mReader->getAttributeValue( attrSemantic);
  1210. channel.mType = GetTypeForSemantic( semantic);
  1211. // read source
  1212. int attrSource = GetAttribute( "source");
  1213. const char* source = mReader->getAttributeValue( attrSource);
  1214. if( source[0] != '#')
  1215. ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\".") % source));
  1216. channel.mAccessor = source+1; // skipping the leading #, hopefully the remaining text is the accessor ID only
  1217. // read index offset, if per-index <input>
  1218. int attrOffset = TestAttribute( "offset");
  1219. if( attrOffset > -1)
  1220. channel.mOffset = mReader->getAttributeValueAsInt( attrOffset);
  1221. // store, if valid type
  1222. if( channel.mType != IT_Invalid)
  1223. poChannels.push_back( channel);
  1224. // skip remaining stuff of this element, if any
  1225. SkipElement();
  1226. }
  1227. // ------------------------------------------------------------------------------------------------
  1228. // Reads a <p> primitive index list and assembles the mesh data into the given mesh
  1229. void ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pPerIndexChannels,
  1230. size_t pNumPrimitives, const std::vector<size_t>& pVCount, PrimitiveType pPrimType)
  1231. {
  1232. // determine number of indices coming per vertex
  1233. // find the offset index for all per-vertex channels
  1234. size_t numOffsets = 1;
  1235. size_t perVertexOffset = -1; // invalid value
  1236. BOOST_FOREACH( const InputChannel& channel, pPerIndexChannels)
  1237. {
  1238. numOffsets = std::max( numOffsets, channel.mOffset+1);
  1239. if( channel.mType == IT_Vertex)
  1240. perVertexOffset = channel.mOffset;
  1241. }
  1242. // determine the expected number of indices
  1243. size_t expectedPointCount = 0;
  1244. switch( pPrimType)
  1245. {
  1246. case Prim_Polylist:
  1247. {
  1248. BOOST_FOREACH( size_t i, pVCount)
  1249. expectedPointCount += i;
  1250. break;
  1251. }
  1252. case Prim_Lines:
  1253. expectedPointCount = 2 * pNumPrimitives;
  1254. break;
  1255. case Prim_Triangles:
  1256. expectedPointCount = 3 * pNumPrimitives;
  1257. break;
  1258. default:
  1259. // other primitive types don't state the index count upfront... we need to guess
  1260. break;
  1261. }
  1262. // and read all indices into a temporary array
  1263. std::vector<size_t> indices;
  1264. if( expectedPointCount > 0)
  1265. indices.reserve( expectedPointCount * numOffsets);
  1266. const char* content = GetTextContent();
  1267. while( *content != 0)
  1268. {
  1269. // read a value
  1270. unsigned int value = strtol10( content, &content);
  1271. indices.push_back( size_t( value));
  1272. // skip whitespace after it
  1273. SkipSpacesAndLineEnd( &content);
  1274. }
  1275. // complain if the index count doesn't fit
  1276. if( expectedPointCount > 0 && indices.size() != expectedPointCount * numOffsets)
  1277. ThrowException( "Expected different index count in <p> element.");
  1278. else if( expectedPointCount == 0 && (indices.size() % numOffsets) != 0)
  1279. ThrowException( "Expected different index count in <p> element.");
  1280. // find the data for all sources
  1281. BOOST_FOREACH( InputChannel& input, pMesh->mPerVertexData)
  1282. {
  1283. if( input.mResolved)
  1284. continue;
  1285. // find accessor
  1286. input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
  1287. // resolve accessor's data pointer as well, if neccessary
  1288. const Accessor* acc = input.mResolved;
  1289. if( !acc->mData)
  1290. acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
  1291. }
  1292. // and the same for the per-index channels
  1293. BOOST_FOREACH( InputChannel& input, pPerIndexChannels)
  1294. {
  1295. if( input.mResolved)
  1296. continue;
  1297. // ignore vertex pointer, it doesn't refer to an accessor
  1298. if( input.mType == IT_Vertex)
  1299. {
  1300. // warn if the vertex channel does not refer to the <vertices> element in the same mesh
  1301. if( input.mAccessor != pMesh->mVertexID)
  1302. ThrowException( "Unsupported vertex referencing scheme. I fucking hate Collada.");
  1303. continue;
  1304. }
  1305. // find accessor
  1306. input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
  1307. // resolve accessor's data pointer as well, if neccessary
  1308. const Accessor* acc = input.mResolved;
  1309. if( !acc->mData)
  1310. acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
  1311. }
  1312. // now assemble vertex data according to those indices
  1313. std::vector<size_t>::const_iterator idx = indices.begin();
  1314. // For continued primitives, the given count does not come all in one <p>, but only one primitive per <p>
  1315. size_t numPrimitives = pNumPrimitives;
  1316. if( pPrimType == Prim_TriFans || pPrimType == Prim_Polygon)
  1317. numPrimitives = 1;
  1318. for( size_t a = 0; a < numPrimitives; a++)
  1319. {
  1320. // determine number of points for this primitive
  1321. size_t numPoints = 0;
  1322. switch( pPrimType)
  1323. {
  1324. case Prim_Lines:
  1325. numPoints = 2;
  1326. break;
  1327. case Prim_Triangles:
  1328. numPoints = 3;
  1329. break;
  1330. case Prim_Polylist:
  1331. numPoints = pVCount[a];
  1332. break;
  1333. case Prim_TriFans:
  1334. case Prim_Polygon:
  1335. numPoints = indices.size() / numOffsets;
  1336. break;
  1337. default:
  1338. // LineStrip and TriStrip not supported due to expected index unmangling
  1339. ThrowException( "Unsupported primitive type.");
  1340. break;
  1341. }
  1342. // store the face size to later reconstruct the face from
  1343. pMesh->mFaceSize.push_back( numPoints);
  1344. // gather that number of vertices
  1345. for( size_t b = 0; b < numPoints; b++)
  1346. {
  1347. // read all indices for this vertex. Yes, in a hacky static array
  1348. assert( numOffsets < 20);
  1349. static size_t vindex[20];
  1350. for( size_t offsets = 0; offsets < numOffsets; ++offsets)
  1351. vindex[offsets] = *idx++;
  1352. // extract per-vertex channels using the global per-vertex offset
  1353. BOOST_FOREACH( const InputChannel& input, pMesh->mPerVertexData)
  1354. ExtractDataObjectFromChannel( input, vindex[perVertexOffset], pMesh);
  1355. // and extract per-index channels using there specified offset
  1356. BOOST_FOREACH( const InputChannel& input, pPerIndexChannels)
  1357. ExtractDataObjectFromChannel( input, vindex[input.mOffset], pMesh);
  1358. }
  1359. }
  1360. // if I ever get my hands on that guy who invented this steaming pile of indirection...
  1361. TestClosing( "p");
  1362. }
  1363. // ------------------------------------------------------------------------------------------------
  1364. // Extracts a single object from an input channel and stores it in the appropriate mesh data array
  1365. void ColladaParser::ExtractDataObjectFromChannel( const InputChannel& pInput, size_t pLocalIndex, Mesh* pMesh)
  1366. {
  1367. // ignore vertex referrer - we handle them that separate
  1368. if( pInput.mType == IT_Vertex)
  1369. return;
  1370. const Accessor& acc = *pInput.mResolved;
  1371. if( pLocalIndex >= acc.mCount)
  1372. ThrowException( boost::str( boost::format( "Invalid data index (%d/%d) in primitive specification") % pLocalIndex % acc.mCount));
  1373. // get a pointer to the start of the data object referred to by the accessor and the local index
  1374. const float* dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex* acc.mStride;
  1375. // assemble according to the accessors component sub-offset list. We don't care, yet,
  1376. // what kind of object exactly we're extracting here
  1377. float obj[4];
  1378. for( size_t c = 0; c < 4; ++c)
  1379. obj[c] = dataObject[acc.mSubOffset[c]];
  1380. // now we reinterpret it according to the type we're reading here
  1381. switch( pInput.mType)
  1382. {
  1383. case IT_Position: // ignore all position streams except 0 - there can be only one position
  1384. if( pInput.mIndex == 0)
  1385. pMesh->mPositions.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1386. else
  1387. DefaultLogger::get()->error("Collada: just one vertex position stream supported");
  1388. break;
  1389. case IT_Normal: // ignore all normal streams except 0 - there can be only one normal
  1390. if( pInput.mIndex == 0)
  1391. pMesh->mNormals.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1392. else
  1393. DefaultLogger::get()->error("Collada: just one vertex normal stream supported");
  1394. break;
  1395. case IT_Tangent: // ignore all tangent streams except 0 - there can be only one tangent
  1396. if( pInput.mIndex == 0)
  1397. pMesh->mTangents.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1398. else
  1399. DefaultLogger::get()->error("Collada: just one vertex tangent stream supported");
  1400. break;
  1401. case IT_Bitangent: // ignore all bitangent streams except 0 - there can be only one bitangent
  1402. if( pInput.mIndex == 0)
  1403. pMesh->mBitangents.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1404. else
  1405. DefaultLogger::get()->error("Collada: just one vertex bitangent stream supported");
  1406. break;
  1407. case IT_Texcoord: // up to 4 texture coord sets are fine, ignore the others
  1408. if( pInput.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS) {
  1409. pMesh->mTexCoords[pInput.mIndex].push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1410. if (0 != acc.mSubOffset[2]) /* hack ... consider cleaner solution */
  1411. pMesh->mNumUVComponents[pInput.mIndex]=3;
  1412. }
  1413. else
  1414. DefaultLogger::get()->error("Collada: too many texture coordinate sets. Skipping.");
  1415. break;
  1416. case IT_Color: // up to 4 color sets are fine, ignore the others
  1417. if( pInput.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS)
  1418. pMesh->mColors[pInput.mIndex].push_back( aiColor4D( obj[0], obj[1], obj[2], obj[3]));
  1419. else
  1420. DefaultLogger::get()->error("Collada: too many vertex color sets. Skipping.");
  1421. break;
  1422. }
  1423. }
  1424. // ------------------------------------------------------------------------------------------------
  1425. // Reads the library of node hierarchies and scene parts
  1426. void ColladaParser::ReadSceneLibrary()
  1427. {
  1428. while( mReader->read())
  1429. {
  1430. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1431. {
  1432. // a visual scene - generate root node under its ID and let ReadNode() do the recursive work
  1433. if( IsElement( "visual_scene"))
  1434. {
  1435. // read ID. Is optional according to the spec, but how on earth should a scene_instance refer to it then?
  1436. int indexID = GetAttribute( "id");
  1437. const char* attrID = mReader->getAttributeValue( indexID);
  1438. // read name if given.
  1439. int indexName = TestAttribute( "name");
  1440. const char* attrName = "unnamed";
  1441. if( indexName > -1)
  1442. attrName = mReader->getAttributeValue( indexName);
  1443. // TODO: (thom) support SIDs
  1444. // assert( TestAttribute( "sid") == -1);
  1445. // create a node and store it in the library under its ID
  1446. Node* node = new Node;
  1447. node->mID = attrID;
  1448. node->mName = attrName;
  1449. mNodeLibrary[node->mID] = node;
  1450. ReadSceneNode( node);
  1451. } else
  1452. {
  1453. // ignore the rest
  1454. SkipElement();
  1455. }
  1456. }
  1457. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1458. {
  1459. if( strcmp( mReader->getNodeName(), "library_visual_scenes") != 0)
  1460. ThrowException( "Expected end of \"library_visual_scenes\" element.");
  1461. break;
  1462. }
  1463. }
  1464. }
  1465. // ------------------------------------------------------------------------------------------------
  1466. // Reads a scene node's contents including children and stores it in the given node
  1467. void ColladaParser::ReadSceneNode( Node* pNode)
  1468. {
  1469. // quit immediately on <bla/> elements
  1470. if( mReader->isEmptyElement())
  1471. return;
  1472. while( mReader->read())
  1473. {
  1474. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  1475. if( IsElement( "node"))
  1476. {
  1477. Node* child = new Node;
  1478. int attrID = TestAttribute( "id");
  1479. if( attrID > -1)
  1480. child->mID = mReader->getAttributeValue( attrID);
  1481. int attrName = TestAttribute( "name");
  1482. if( attrName > -1)
  1483. child->mName = mReader->getAttributeValue( attrName);
  1484. // TODO: (thom) support SIDs
  1485. // assert( TestAttribute( "sid") == -1);
  1486. if (pNode) {
  1487. pNode->mChildren.push_back( child);
  1488. child->mParent = pNode;
  1489. }
  1490. else {
  1491. // no parent node given, probably called from <library_nodes> element.
  1492. // create new node in node library
  1493. mNodeLibrary[child->mID] = pNode = child;
  1494. }
  1495. // read on recursively from there
  1496. ReadSceneNode( child);
  1497. continue;
  1498. }
  1499. // For any further stuff we need a valid node to work on
  1500. else if (!pNode)
  1501. continue;
  1502. if( IsElement( "lookat"))
  1503. ReadNodeTransformation( pNode, TF_LOOKAT);
  1504. else if( IsElement( "matrix"))
  1505. ReadNodeTransformation( pNode, TF_MATRIX);
  1506. else if( IsElement( "rotate"))
  1507. ReadNodeTransformation( pNode, TF_ROTATE);
  1508. else if( IsElement( "scale"))
  1509. ReadNodeTransformation( pNode, TF_SCALE);
  1510. else if( IsElement( "skew"))
  1511. ReadNodeTransformation( pNode, TF_SKEW);
  1512. else if( IsElement( "translate"))
  1513. ReadNodeTransformation( pNode, TF_TRANSLATE);
  1514. else if( IsElement( "render") && pNode->mParent == NULL && 0 == pNode->mPrimaryCamera.length())
  1515. {
  1516. // ... scene evaluation or, in other words, postprocessing pipeline,
  1517. // or, again in other words, a turing-complete description how to
  1518. // render a Collada scene. The only thing that is interesting for
  1519. // us is the primary camera.
  1520. int attrId = TestAttribute("camera_node");
  1521. if (-1 != attrId) {
  1522. const char* s = mReader->getAttributeValue(attrId);
  1523. if (s[0] != '#')
  1524. DefaultLogger::get()->error("Collada: Unresolved reference format of camera");
  1525. else pNode->mPrimaryCamera = s+1;
  1526. }
  1527. }
  1528. else if( IsElement( "instance_node")) {
  1529. // find the node in the library
  1530. int attrID = TestAttribute( "url");
  1531. if( attrID != -1) {
  1532. const char* s = mReader->getAttributeValue(attrID);
  1533. if (s[0] != '#')
  1534. DefaultLogger::get()->error("Collada: Unresolved reference format of node");
  1535. else {
  1536. pNode->mNodeInstances.push_back(NodeInstance());
  1537. pNode->mNodeInstances.back().mNode = s+1;
  1538. }
  1539. }
  1540. }
  1541. else if( IsElement( "instance_geometry")) {
  1542. // Reference to a mesh, with possible material associations
  1543. ReadNodeGeometry( pNode);
  1544. }
  1545. else if( IsElement( "instance_light")) {
  1546. // Reference to a light, name given in 'url' attribute
  1547. int attrID = TestAttribute("url");
  1548. if (-1 == attrID)
  1549. DefaultLogger::get()->warn("Collada: Expected url attribute in <instance_light> element");
  1550. else {
  1551. const char* url = mReader->getAttributeValue( attrID);
  1552. if( url[0] != '#')
  1553. ThrowException( "Unknown reference format in <instance_light> element");
  1554. pNode->mLights.push_back(LightInstance());
  1555. pNode->mLights.back().mLight = url+1;
  1556. }
  1557. }
  1558. else if( IsElement( "instance_camera")) {
  1559. // Reference to a camera, name given in 'url' attribute
  1560. int attrID = TestAttribute("url");
  1561. if (-1 == attrID)
  1562. DefaultLogger::get()->warn("Collada: Expected url attribute in <instance_camera> element");
  1563. else {
  1564. const char* url = mReader->getAttributeValue( attrID);
  1565. if( url[0] != '#')
  1566. ThrowException( "Unknown reference format in <instance_camera> element");
  1567. pNode->mCameras.push_back(CameraInstance());
  1568. pNode->mCameras.back().mCamera = url+1;
  1569. }
  1570. }
  1571. else
  1572. {
  1573. // skip everything else for the moment
  1574. SkipElement();
  1575. }
  1576. }
  1577. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  1578. break;
  1579. }
  1580. }
  1581. }
  1582. // ------------------------------------------------------------------------------------------------
  1583. // Reads a node transformation entry of the given type and adds it to the given node's transformation list.
  1584. void ColladaParser::ReadNodeTransformation( Node* pNode, TransformType pType)
  1585. {
  1586. std::string tagName = mReader->getNodeName();
  1587. // how many parameters to read per transformation type
  1588. static const unsigned int sNumParameters[] = { 9, 4, 3, 3, 7, 16 };
  1589. const char* content = GetTextContent();
  1590. // read as many parameters and store in the transformation
  1591. Transform tf;
  1592. tf.mType = pType;
  1593. for( unsigned int a = 0; a < sNumParameters[pType]; a++)
  1594. {
  1595. // read a number
  1596. content = fast_atof_move( content, tf.f[a]);
  1597. // skip whitespace after it
  1598. SkipSpacesAndLineEnd( &content);
  1599. }
  1600. // place the transformation at the queue of the node
  1601. pNode->mTransforms.push_back( tf);
  1602. // and consum the closing tag
  1603. TestClosing( tagName.c_str());
  1604. }
  1605. // ------------------------------------------------------------------------------------------------
  1606. // Processes bind_vertex_input and bind elements
  1607. void ColladaParser::ReadMaterialVertexInputBinding( Collada::SemanticMappingTable& tbl)
  1608. {
  1609. while( mReader->read())
  1610. {
  1611. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  1612. if( IsElement( "bind_vertex_input"))
  1613. {
  1614. Collada::InputSemanticMapEntry vn;
  1615. // effect semantic
  1616. int n = GetAttribute("semantic");
  1617. std::string s = mReader->getAttributeValue(n);
  1618. // input semantic
  1619. n = GetAttribute("input_semantic");
  1620. vn.mType = GetTypeForSemantic( mReader->getAttributeValue(n) );
  1621. // index of input set
  1622. n = TestAttribute("input_set");
  1623. if (-1 != n)
  1624. vn.mSet = mReader->getAttributeValueAsInt(n);
  1625. tbl.mMap[s] = vn;
  1626. }
  1627. else if( IsElement( "bind")) {
  1628. DefaultLogger::get()->warn("Collada: Found unsupported <bind> element");
  1629. }
  1630. }
  1631. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  1632. if( strcmp( mReader->getNodeName(), "instance_material") == 0)
  1633. break;
  1634. }
  1635. }
  1636. }
  1637. // ------------------------------------------------------------------------------------------------
  1638. // Reads a mesh reference in a node and adds it to the node's mesh list
  1639. void ColladaParser::ReadNodeGeometry( Node* pNode)
  1640. {
  1641. // referred mesh is given as an attribute of the <instance_geometry> element
  1642. int attrUrl = GetAttribute( "url");
  1643. const char* url = mReader->getAttributeValue( attrUrl);
  1644. if( url[0] != '#')
  1645. ThrowException( "Unknown reference format");
  1646. Collada::MeshInstance instance;
  1647. instance.mMesh = url+1; // skipping the leading #
  1648. if( !mReader->isEmptyElement())
  1649. {
  1650. // read material associations. Ignore additional elements inbetween
  1651. while( mReader->read())
  1652. {
  1653. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  1654. if( IsElement( "instance_material"))
  1655. {
  1656. // read ID of the geometry subgroup and the target material
  1657. int attrGroup = GetAttribute( "symbol");
  1658. std::string group = mReader->getAttributeValue( attrGroup);
  1659. int attrMaterial = GetAttribute( "target");
  1660. const char* urlMat = mReader->getAttributeValue( attrMaterial);
  1661. Collada::SemanticMappingTable s;
  1662. if( urlMat[0] != '#')
  1663. ThrowException( "Unknown reference format");
  1664. s.mMatName = urlMat+1;
  1665. // resolve further material details + THIS UGLY AND NASTY semantic mapping stuff
  1666. if( !mReader->isEmptyElement())
  1667. ReadMaterialVertexInputBinding(s);
  1668. // store the association
  1669. instance.mMaterials[group] = s;
  1670. }
  1671. }
  1672. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  1673. if( strcmp( mReader->getNodeName(), "instance_geometry") == 0)
  1674. break;
  1675. }
  1676. }
  1677. }
  1678. // store it
  1679. pNode->mMeshes.push_back( instance);
  1680. }
  1681. // ------------------------------------------------------------------------------------------------
  1682. // Reads the collada scene
  1683. void ColladaParser::ReadScene()
  1684. {
  1685. while( mReader->read())
  1686. {
  1687. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  1688. if( IsElement( "instance_visual_scene"))
  1689. {
  1690. // should be the first and only occurence
  1691. if( mRootNode)
  1692. ThrowException( "Invalid scene containing multiple root nodes");
  1693. // read the url of the scene to instance. Should be of format "#some_name"
  1694. int urlIndex = GetAttribute( "url");
  1695. const char* url = mReader->getAttributeValue( urlIndex);
  1696. if( url[0] != '#')
  1697. ThrowException( "Unknown reference format");
  1698. // find the referred scene, skip the leading #
  1699. NodeLibrary::const_iterator sit = mNodeLibrary.find( url+1);
  1700. if( sit == mNodeLibrary.end())
  1701. ThrowException( "Unable to resolve visual_scene reference \"" + std::string(url) + "\".");
  1702. mRootNode = sit->second;
  1703. } else {
  1704. SkipElement();
  1705. }
  1706. }
  1707. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){
  1708. break;
  1709. }
  1710. }
  1711. }
  1712. // ------------------------------------------------------------------------------------------------
  1713. // Aborts the file reading with an exception
  1714. void ColladaParser::ThrowException( const std::string& pError) const
  1715. {
  1716. throw new ImportErrorException( boost::str( boost::format( "Collada: %s - %s") % mFileName % pError));
  1717. }
  1718. // ------------------------------------------------------------------------------------------------
  1719. // Skips all data until the end node of the current element
  1720. void ColladaParser::SkipElement()
  1721. {
  1722. // nothing to skip if it's an <element />
  1723. if( mReader->isEmptyElement())
  1724. return;
  1725. // reroute
  1726. SkipElement( mReader->getNodeName());
  1727. }
  1728. // ------------------------------------------------------------------------------------------------
  1729. // Skips all data until the end node of the given element
  1730. void ColladaParser::SkipElement( const char* pElement)
  1731. {
  1732. // copy the current node's name because it'a pointer to the reader's internal buffer,
  1733. // which is going to change with the upcoming parsing
  1734. std::string element = pElement;
  1735. while( mReader->read())
  1736. {
  1737. if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1738. if( mReader->getNodeName() == element)
  1739. break;
  1740. }
  1741. }
  1742. // ------------------------------------------------------------------------------------------------
  1743. // Tests for an opening element of the given name, throws an exception if not found
  1744. void ColladaParser::TestOpening( const char* pName)
  1745. {
  1746. // read element start
  1747. if( !mReader->read())
  1748. ThrowException( boost::str( boost::format( "Unexpected end of file while beginning of \"%s\" element.") % pName));
  1749. // whitespace in front is ok, just read again if found
  1750. if( mReader->getNodeType() == irr::io::EXN_TEXT)
  1751. if( !mReader->read())
  1752. ThrowException( boost::str( boost::format( "Unexpected end of file while reading beginning of \"%s\" element.") % pName));
  1753. if( mReader->getNodeType() != irr::io::EXN_ELEMENT || strcmp( mReader->getNodeName(), pName) != 0)
  1754. ThrowException( boost::str( boost::format( "Expected start of \"%s\" element.") % pName));
  1755. }
  1756. // ------------------------------------------------------------------------------------------------
  1757. // Tests for the closing tag of the given element, throws an exception if not found
  1758. void ColladaParser::TestClosing( const char* pName)
  1759. {
  1760. // read closing tag
  1761. if( !mReader->read())
  1762. ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of \"%s\" element.") % pName));
  1763. // whitespace in front is ok, just read again if found
  1764. if( mReader->getNodeType() == irr::io::EXN_TEXT)
  1765. if( !mReader->read())
  1766. ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of \"%s\" element.") % pName));
  1767. if( mReader->getNodeType() != irr::io::EXN_ELEMENT_END || strcmp( mReader->getNodeName(), pName) != 0)
  1768. ThrowException( boost::str( boost::format( "Expected end of \"%s\" element.") % pName));
  1769. }
  1770. // ------------------------------------------------------------------------------------------------
  1771. // Returns the index of the named attribute or -1 if not found. Does not throw, therefore useful for optional attributes
  1772. int ColladaParser::GetAttribute( const char* pAttr) const
  1773. {
  1774. int index = TestAttribute( pAttr);
  1775. if( index != -1)
  1776. return index;
  1777. // attribute not found -> throw an exception
  1778. ThrowException( boost::str( boost::format( "Expected attribute \"%s\" at element \"%s\".") % pAttr % mReader->getNodeName()));
  1779. return -1;
  1780. }
  1781. // ------------------------------------------------------------------------------------------------
  1782. // Tests the present element for the presence of one attribute, returns its index or throws an exception if not found
  1783. int ColladaParser::TestAttribute( const char* pAttr) const
  1784. {
  1785. for( int a = 0; a < mReader->getAttributeCount(); a++)
  1786. if( strcmp( mReader->getAttributeName( a), pAttr) == 0)
  1787. return a;
  1788. return -1;
  1789. }
  1790. // ------------------------------------------------------------------------------------------------
  1791. // Reads the text contents of an element, throws an exception if not given. Skips leading whitespace.
  1792. const char* ColladaParser::GetTextContent()
  1793. {
  1794. const char* sz = TestTextContent();
  1795. if(!sz) {
  1796. ThrowException( "Invalid contents in element \"n\".");
  1797. }
  1798. return sz;
  1799. }
  1800. // ------------------------------------------------------------------------------------------------
  1801. // Reads the text contents of an element, returns NULL if not given. Skips leading whitespace.
  1802. const char* ColladaParser::TestTextContent()
  1803. {
  1804. // present node should be the beginning of an element
  1805. if( mReader->getNodeType() != irr::io::EXN_ELEMENT || mReader->isEmptyElement())
  1806. ThrowException( "Expected opening element");
  1807. // read contents of the element
  1808. if( !mReader->read())
  1809. ThrowException( "Unexpected end of file while reading n element.");
  1810. if( mReader->getNodeType() != irr::io::EXN_TEXT)
  1811. return NULL;
  1812. // skip leading whitespace
  1813. const char* text = mReader->getNodeData();
  1814. SkipSpacesAndLineEnd( &text);
  1815. return text;
  1816. }
  1817. // ------------------------------------------------------------------------------------------------
  1818. // Calculates the resulting transformation fromm all the given transform steps
  1819. aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector<Transform>& pTransforms) const
  1820. {
  1821. aiMatrix4x4 res;
  1822. for( std::vector<Transform>::const_iterator it = pTransforms.begin(); it != pTransforms.end(); ++it)
  1823. {
  1824. const Transform& tf = *it;
  1825. switch( tf.mType)
  1826. {
  1827. case TF_LOOKAT:
  1828. // TODO: (thom)
  1829. assert( false);
  1830. break;
  1831. case TF_ROTATE:
  1832. {
  1833. aiMatrix4x4 rot;
  1834. float angle = tf.f[3] * float( AI_MATH_PI) / 180.0f;
  1835. aiVector3D axis( tf.f[0], tf.f[1], tf.f[2]);
  1836. aiMatrix4x4::Rotation( angle, axis, rot);
  1837. res *= rot;
  1838. break;
  1839. }
  1840. case TF_TRANSLATE:
  1841. {
  1842. aiMatrix4x4 trans;
  1843. aiMatrix4x4::Translation( aiVector3D( tf.f[0], tf.f[1], tf.f[2]), trans);
  1844. res *= trans;
  1845. break;
  1846. }
  1847. case TF_SCALE:
  1848. {
  1849. 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,
  1850. 0.0f, 0.0f, 0.0f, 1.0f);
  1851. res *= scale;
  1852. break;
  1853. }
  1854. case TF_SKEW:
  1855. // TODO: (thom)
  1856. ai_assert( false);
  1857. break;
  1858. case TF_MATRIX:
  1859. {
  1860. 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],
  1861. tf.f[8], tf.f[9], tf.f[10], tf.f[11], tf.f[12], tf.f[13], tf.f[14], tf.f[15]);
  1862. res *= mat;
  1863. break;
  1864. }
  1865. default:
  1866. assert( false);
  1867. break;
  1868. }
  1869. }
  1870. return res;
  1871. }
  1872. // ------------------------------------------------------------------------------------------------
  1873. // Determines the input data type for the given semantic string
  1874. Collada::InputType ColladaParser::GetTypeForSemantic( const std::string& pSemantic)
  1875. {
  1876. if( pSemantic == "POSITION")
  1877. return IT_Position;
  1878. else if( pSemantic == "TEXCOORD")
  1879. return IT_Texcoord;
  1880. else if( pSemantic == "NORMAL")
  1881. return IT_Normal;
  1882. else if( pSemantic == "COLOR")
  1883. return IT_Color;
  1884. else if( pSemantic == "VERTEX")
  1885. return IT_Vertex;
  1886. else if( pSemantic == "BINORMAL")
  1887. return IT_Bitangent;
  1888. else if( pSemantic == "TANGENT")
  1889. return IT_Tangent;
  1890. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown vertex input type \"%s\". Ignoring.") % pSemantic));
  1891. return IT_Invalid;
  1892. }
  1893. #endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER