ColladaParser.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641
  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_animations"))
  141. ReadAnimationLibrary();
  142. else if( IsElement( "library_controllers"))
  143. ReadControllerLibrary();
  144. else if( IsElement( "library_images"))
  145. ReadImageLibrary();
  146. else if( IsElement( "library_materials"))
  147. ReadMaterialLibrary();
  148. else if( IsElement( "library_effects"))
  149. ReadEffectLibrary();
  150. else if( IsElement( "library_geometries"))
  151. ReadGeometryLibrary();
  152. else if( IsElement( "library_visual_scenes"))
  153. ReadSceneLibrary();
  154. else if( IsElement( "library_lights"))
  155. ReadLightLibrary();
  156. else if( IsElement( "library_cameras"))
  157. ReadCameraLibrary();
  158. else if( IsElement( "library_nodes"))
  159. ReadSceneNode(NULL); /* some hacking to reuse this piece of code */
  160. else if( IsElement( "scene"))
  161. ReadScene();
  162. else
  163. SkipElement();
  164. }
  165. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  166. break;
  167. }
  168. }
  169. }
  170. // ------------------------------------------------------------------------------------------------
  171. // Reads asset informations such as coordinate system informations and legal blah
  172. void ColladaParser::ReadAssetInfo()
  173. {
  174. while( mReader->read())
  175. {
  176. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  177. {
  178. if( IsElement( "unit"))
  179. {
  180. // read unit data from the element's attributes
  181. int attrIndex = GetAttribute( "meter");
  182. mUnitSize = mReader->getAttributeValueAsFloat( attrIndex);
  183. // consume the trailing stuff
  184. if( !mReader->isEmptyElement())
  185. SkipElement();
  186. }
  187. else if( IsElement( "up_axis"))
  188. {
  189. // read content, strip whitespace, compare
  190. const char* content = GetTextContent();
  191. if( strncmp( content, "X_UP", 4) == 0)
  192. mUpDirection = UP_X;
  193. else if( strncmp( content, "Y_UP", 4) == 0)
  194. mUpDirection = UP_Y;
  195. else
  196. mUpDirection = UP_Z;
  197. // check element end
  198. TestClosing( "up_axis");
  199. } else
  200. {
  201. SkipElement();
  202. }
  203. }
  204. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  205. {
  206. if( strcmp( mReader->getNodeName(), "asset") != 0)
  207. ThrowException( "Expected end of \"asset\" element.");
  208. break;
  209. }
  210. }
  211. }
  212. // ------------------------------------------------------------------------------------------------
  213. // Reads the animation library
  214. void ColladaParser::ReadAnimationLibrary()
  215. {
  216. while( mReader->read())
  217. {
  218. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  219. {
  220. if( IsElement( "animation"))
  221. {
  222. // delegate the reading. Depending on the inner elements it will be a container or a anim channel
  223. ReadAnimation( &mAnims);
  224. } else
  225. {
  226. // ignore the rest
  227. SkipElement();
  228. }
  229. }
  230. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  231. {
  232. if( strcmp( mReader->getNodeName(), "library_animations") != 0)
  233. ThrowException( "Expected end of \"library_animations\" element.");
  234. break;
  235. }
  236. }
  237. }
  238. // ------------------------------------------------------------------------------------------------
  239. // Reads an animation into the given parent structure
  240. void ColladaParser::ReadAnimation( Collada::Animation* pParent)
  241. {
  242. // an <animation> element may be a container for grouping sub-elements or an animation channel
  243. // this is the channel we're writing to, in case it's a channel
  244. AnimationChannel channel;
  245. // this is the anim container in case we're a container
  246. Animation* anim = NULL;
  247. // optional name given as an attribute
  248. std::string animName;
  249. int indexName = TestAttribute( "name");
  250. int indexID = TestAttribute( "id");
  251. if( indexName >= 0)
  252. animName = mReader->getAttributeValue( indexName);
  253. else if( indexID >= 0)
  254. animName = mReader->getAttributeValue( indexID);
  255. else
  256. animName = "animation";
  257. while( mReader->read())
  258. {
  259. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  260. {
  261. // we have subanimations
  262. if( IsElement( "animation"))
  263. {
  264. // create container from our element
  265. if( !anim)
  266. {
  267. anim = new Animation;
  268. anim->mName = animName;
  269. pParent->mSubAnims.push_back( anim);
  270. }
  271. // recurse into the subelement
  272. ReadAnimation( anim);
  273. }
  274. else if( IsElement( "source"))
  275. {
  276. // possible animation data - we'll never know. Better store it
  277. ReadSource();
  278. }
  279. else if( IsElement( "sampler"))
  280. {
  281. // have it read into our channel
  282. ReadAnimationSampler( channel);
  283. }
  284. else if( IsElement( "channel"))
  285. {
  286. // the binding element whose whole purpose is to provide the target to animate
  287. // Thanks, Collada! A directly posted information would have been too simple, I guess.
  288. // Better add another indirection to that! Can't have enough of those.
  289. int indexTarget = GetAttribute( "target");
  290. channel.mTarget = mReader->getAttributeValue( indexTarget);
  291. if( !mReader->isEmptyElement())
  292. SkipElement();
  293. }
  294. else
  295. {
  296. // ignore the rest
  297. SkipElement();
  298. }
  299. }
  300. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  301. {
  302. if( strcmp( mReader->getNodeName(), "animation") != 0)
  303. ThrowException( "Expected end of \"animation\" element.");
  304. break;
  305. }
  306. }
  307. // it turned out to be a channel - add it
  308. if( !channel.mTarget.empty())
  309. pParent->mChannels.push_back( channel);
  310. }
  311. // ------------------------------------------------------------------------------------------------
  312. // Reads an animation sampler into the given anim channel
  313. void ColladaParser::ReadAnimationSampler( Collada::AnimationChannel& pChannel)
  314. {
  315. while( mReader->read())
  316. {
  317. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  318. {
  319. if( IsElement( "input"))
  320. {
  321. int indexSemantic = GetAttribute( "semantic");
  322. const char* semantic = mReader->getAttributeValue( indexSemantic);
  323. int indexSource = GetAttribute( "source");
  324. const char* source = mReader->getAttributeValue( indexSource);
  325. if( source[0] != '#')
  326. ThrowException( "Unsupported URL format");
  327. source++;
  328. if( strcmp( semantic, "INPUT") == 0)
  329. pChannel.mSourceTimes = source;
  330. else if( strcmp( semantic, "OUTPUT") == 0)
  331. pChannel.mSourceValues = source;
  332. if( !mReader->isEmptyElement())
  333. SkipElement();
  334. }
  335. else
  336. {
  337. // ignore the rest
  338. SkipElement();
  339. }
  340. }
  341. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  342. {
  343. if( strcmp( mReader->getNodeName(), "sampler") != 0)
  344. ThrowException( "Expected end of \"sampler\" element.");
  345. break;
  346. }
  347. }
  348. }
  349. // ------------------------------------------------------------------------------------------------
  350. // Reads the skeleton controller library
  351. void ColladaParser::ReadControllerLibrary()
  352. {
  353. while( mReader->read())
  354. {
  355. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  356. {
  357. if( IsElement( "controller"))
  358. {
  359. // read ID. Ask the spec if it's neccessary or optional... you might be surprised.
  360. int attrID = GetAttribute( "id");
  361. std::string id = mReader->getAttributeValue( attrID);
  362. // create an entry and store it in the library under its ID
  363. mControllerLibrary[id] = Controller();
  364. // read on from there
  365. ReadController( mControllerLibrary[id]);
  366. } else
  367. {
  368. // ignore the rest
  369. SkipElement();
  370. }
  371. }
  372. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  373. {
  374. if( strcmp( mReader->getNodeName(), "library_controllers") != 0)
  375. ThrowException( "Expected end of \"library_controllers\" element.");
  376. break;
  377. }
  378. }
  379. }
  380. // ------------------------------------------------------------------------------------------------
  381. // Reads a controller into the given mesh structure
  382. void ColladaParser::ReadController( Collada::Controller& pController)
  383. {
  384. while( mReader->read())
  385. {
  386. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  387. {
  388. // two types of controllers: "skin" and "morph". Only the first one is relevant, we skip the other
  389. if( IsElement( "morph"))
  390. {
  391. // should skip everything inside, so there's no danger of catching elements inbetween
  392. SkipElement();
  393. }
  394. else if( IsElement( "skin"))
  395. {
  396. // read the mesh it refers to. According to the spec this could also be another
  397. // controller, but I refuse to implement every bullshit idea they've come up with
  398. int sourceIndex = GetAttribute( "source");
  399. pController.mMeshId = mReader->getAttributeValue( sourceIndex) + 1;
  400. }
  401. else if( IsElement( "bind_shape_matrix"))
  402. {
  403. // content is 16 floats to define some sort of matrix... I'm going to ignore this
  404. // as long as I don't have a clue how to interpret it
  405. SkipElement();
  406. }
  407. else if( IsElement( "source"))
  408. {
  409. // data array - we have specialists to handle this
  410. ReadSource();
  411. }
  412. else if( IsElement( "joints"))
  413. {
  414. ReadControllerJoints( pController);
  415. }
  416. else if( IsElement( "vertex_weights"))
  417. {
  418. ReadControllerWeights( pController);
  419. }
  420. else
  421. {
  422. // ignore the rest
  423. SkipElement();
  424. }
  425. }
  426. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  427. {
  428. if( strcmp( mReader->getNodeName(), "controller") == 0)
  429. break;
  430. else if( strcmp( mReader->getNodeName(), "skin") != 0)
  431. ThrowException( "Expected end of \"controller\" element.");
  432. }
  433. }
  434. }
  435. // ------------------------------------------------------------------------------------------------
  436. // Reads the joint definitions for the given controller
  437. void ColladaParser::ReadControllerJoints( Collada::Controller& pController)
  438. {
  439. while( mReader->read())
  440. {
  441. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  442. {
  443. // Input channels for joint data. Two possible semantics: "JOINT" and "INV_BIND_MATRIX"
  444. if( IsElement( "input"))
  445. {
  446. int indexSemantic = GetAttribute( "semantic");
  447. const char* attrSemantic = mReader->getAttributeValue( indexSemantic);
  448. int indexSource = GetAttribute( "source");
  449. const char* attrSource = mReader->getAttributeValue( indexSource);
  450. // local URLS always start with a '#'. We don't support global URLs
  451. if( attrSource[0] != '#')
  452. ThrowException( boost::str( boost::format( "Unsupported URL format in \"%s\"") % attrSource));
  453. attrSource++;
  454. // parse source URL to corresponding source
  455. if( strcmp( attrSemantic, "JOINT") == 0)
  456. pController.mJointNameSource = attrSource;
  457. else if( strcmp( attrSemantic, "INV_BIND_MATRIX") == 0)
  458. pController.mJointOffsetMatrixSource = attrSource;
  459. else
  460. ThrowException( boost::str( boost::format( "Unknown semantic \"%s\" in joint data") % attrSemantic));
  461. // skip inner data, if present
  462. if( !mReader->isEmptyElement())
  463. SkipElement();
  464. }
  465. else
  466. {
  467. // ignore the rest
  468. SkipElement();
  469. }
  470. }
  471. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  472. {
  473. if( strcmp( mReader->getNodeName(), "joints") != 0)
  474. ThrowException( "Expected end of \"joints\" element.");
  475. break;
  476. }
  477. }
  478. }
  479. // ------------------------------------------------------------------------------------------------
  480. // Reads the joint weights for the given controller
  481. void ColladaParser::ReadControllerWeights( Collada::Controller& pController)
  482. {
  483. // read vertex count from attributes and resize the array accordingly
  484. int indexCount = GetAttribute( "count");
  485. size_t vertexCount = (size_t) mReader->getAttributeValueAsInt( indexCount);
  486. pController.mWeightCounts.resize( vertexCount);
  487. while( mReader->read())
  488. {
  489. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  490. {
  491. // Input channels for weight data. Two possible semantics: "JOINT" and "WEIGHT"
  492. if( IsElement( "input"))
  493. {
  494. InputChannel channel;
  495. int indexSemantic = GetAttribute( "semantic");
  496. const char* attrSemantic = mReader->getAttributeValue( indexSemantic);
  497. int indexSource = GetAttribute( "source");
  498. const char* attrSource = mReader->getAttributeValue( indexSource);
  499. int indexOffset = TestAttribute( "offset");
  500. if( indexOffset >= 0)
  501. channel.mOffset = mReader->getAttributeValueAsInt( indexOffset);
  502. // local URLS always start with a '#'. We don't support global URLs
  503. if( attrSource[0] != '#')
  504. ThrowException( boost::str( boost::format( "Unsupported URL format in \"%s\"") % attrSource));
  505. channel.mAccessor = attrSource + 1;
  506. // parse source URL to corresponding source
  507. if( strcmp( attrSemantic, "JOINT") == 0)
  508. pController.mWeightInputJoints = channel;
  509. else if( strcmp( attrSemantic, "WEIGHT") == 0)
  510. pController.mWeightInputWeights = channel;
  511. else
  512. ThrowException( boost::str( boost::format( "Unknown semantic \"%s\" in vertex_weight data") % attrSemantic));
  513. // skip inner data, if present
  514. if( !mReader->isEmptyElement())
  515. SkipElement();
  516. }
  517. else if( IsElement( "vcount"))
  518. {
  519. // read weight count per vertex
  520. const char* text = GetTextContent();
  521. size_t numWeights = 0;
  522. for( std::vector<size_t>::iterator it = pController.mWeightCounts.begin(); it != pController.mWeightCounts.end(); ++it)
  523. {
  524. if( *text == 0)
  525. ThrowException( "Out of data while reading vcount");
  526. *it = strtol10( text, &text);
  527. numWeights += *it;
  528. SkipSpacesAndLineEnd( &text);
  529. }
  530. TestClosing( "vcount");
  531. // reserve weight count
  532. pController.mWeights.resize( numWeights);
  533. }
  534. else if( IsElement( "v"))
  535. {
  536. // read JointIndex - WeightIndex pairs
  537. const char* text = GetTextContent();
  538. for( std::vector< std::pair<size_t, size_t> >::iterator it = pController.mWeights.begin(); it != pController.mWeights.end(); ++it)
  539. {
  540. if( *text == 0)
  541. ThrowException( "Out of data while reading vertex_weights");
  542. it->first = strtol10( text, &text);
  543. SkipSpacesAndLineEnd( &text);
  544. if( *text == 0)
  545. ThrowException( "Out of data while reading vertex_weights");
  546. it->second = strtol10( text, &text);
  547. SkipSpacesAndLineEnd( &text);
  548. }
  549. TestClosing( "v");
  550. }
  551. else
  552. {
  553. // ignore the rest
  554. SkipElement();
  555. }
  556. }
  557. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  558. {
  559. if( strcmp( mReader->getNodeName(), "vertex_weights") != 0)
  560. ThrowException( "Expected end of \"vertex_weights\" element.");
  561. break;
  562. }
  563. }
  564. }
  565. // ------------------------------------------------------------------------------------------------
  566. // Reads the image library contents
  567. void ColladaParser::ReadImageLibrary()
  568. {
  569. while( mReader->read())
  570. {
  571. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  572. if( IsElement( "image"))
  573. {
  574. // read ID. Another entry which is "optional" by design but obligatory in reality
  575. int attrID = GetAttribute( "id");
  576. std::string id = mReader->getAttributeValue( attrID);
  577. // create an entry and store it in the library under its ID
  578. mImageLibrary[id] = Image();
  579. // read on from there
  580. ReadImage( mImageLibrary[id]);
  581. } else
  582. {
  583. // ignore the rest
  584. SkipElement();
  585. }
  586. }
  587. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  588. if( strcmp( mReader->getNodeName(), "library_images") != 0)
  589. ThrowException( "Expected end of \"library_images\" element.");
  590. break;
  591. }
  592. }
  593. }
  594. // ------------------------------------------------------------------------------------------------
  595. // Reads an image entry into the given image
  596. void ColladaParser::ReadImage( Collada::Image& pImage)
  597. {
  598. while( mReader->read())
  599. {
  600. if( mReader->getNodeType() == irr::io::EXN_ELEMENT){
  601. // Need to run different code paths here, depending on the Collada XSD version
  602. if( IsElement( "init_from"))
  603. {
  604. if (mFormat == FV_1_4_n)
  605. {
  606. // element content is filename - hopefully
  607. const char* sz = TestTextContent();
  608. if (sz)pImage.mFileName = sz;
  609. TestClosing( "init_from");
  610. }
  611. else if (mFormat == FV_1_5_n)
  612. {
  613. // make sure we skip over mip and array initializations, which
  614. // we don't support, but which could confuse the loader if
  615. // they're not skipped.
  616. int attrib = TestAttribute("array_index");
  617. if (attrib != -1 && mReader->getAttributeValueAsInt(attrib) > 0) {
  618. DefaultLogger::get()->warn("Collada: Ignoring texture array index");
  619. continue;
  620. }
  621. attrib = TestAttribute("mip_index");
  622. if (attrib != -1 && mReader->getAttributeValueAsInt(attrib) > 0) {
  623. DefaultLogger::get()->warn("Collada: Ignoring MIP map layer");
  624. continue;
  625. }
  626. // TODO: correctly jump over cube and volume maps?
  627. }
  628. }
  629. else if (mFormat == FV_1_5_n)
  630. {
  631. if( IsElement( "ref"))
  632. {
  633. // element content is filename - hopefully
  634. const char* sz = TestTextContent();
  635. if (sz)pImage.mFileName = sz;
  636. TestClosing( "ref");
  637. }
  638. else if( IsElement( "hex") && !pImage.mFileName.length())
  639. {
  640. // embedded image. get format
  641. const int attrib = TestAttribute("format");
  642. if (-1 == attrib)
  643. DefaultLogger::get()->warn("Collada: Unknown image file format");
  644. else pImage.mEmbeddedFormat = mReader->getAttributeValue(attrib);
  645. const char* data = GetTextContent();
  646. // hexadecimal-encoded binary octets. First of all, find the
  647. // required buffer size to reserve enough storage.
  648. const char* cur = data;
  649. while (!IsSpaceOrNewLine(*cur)) cur++;
  650. const unsigned int size = (unsigned int)(cur-data) * 2;
  651. pImage.mImageData.resize(size);
  652. for (unsigned int i = 0; i < size;++i)
  653. pImage.mImageData[i] = HexOctetToDecimal(data+(i<<1));
  654. TestClosing( "hex");
  655. }
  656. }
  657. else
  658. {
  659. // ignore the rest
  660. SkipElement();
  661. }
  662. }
  663. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  664. if( strcmp( mReader->getNodeName(), "image") == 0)
  665. break;
  666. }
  667. }
  668. }
  669. // ------------------------------------------------------------------------------------------------
  670. // Reads the material library
  671. void ColladaParser::ReadMaterialLibrary()
  672. {
  673. while( mReader->read())
  674. {
  675. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  676. {
  677. if( IsElement( "material"))
  678. {
  679. // read ID. By now you propably know my opinion about this "specification"
  680. int attrID = GetAttribute( "id");
  681. std::string id = mReader->getAttributeValue( attrID);
  682. // create an entry and store it in the library under its ID
  683. ReadMaterial(mMaterialLibrary[id] = Material());
  684. } else
  685. {
  686. // ignore the rest
  687. SkipElement();
  688. }
  689. }
  690. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  691. {
  692. if( strcmp( mReader->getNodeName(), "library_materials") != 0)
  693. ThrowException( "Expected end of \"library_materials\" element.");
  694. break;
  695. }
  696. }
  697. }
  698. // ------------------------------------------------------------------------------------------------
  699. // Reads the light library
  700. void ColladaParser::ReadLightLibrary()
  701. {
  702. while( mReader->read())
  703. {
  704. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  705. if( IsElement( "light"))
  706. {
  707. // read ID. By now you propably know my opinion about this "specification"
  708. int attrID = GetAttribute( "id");
  709. std::string id = mReader->getAttributeValue( attrID);
  710. // create an entry and store it in the library under its ID
  711. ReadLight(mLightLibrary[id] = Light());
  712. } else
  713. {
  714. // ignore the rest
  715. SkipElement();
  716. }
  717. }
  718. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  719. if( strcmp( mReader->getNodeName(), "library_lights") != 0)
  720. ThrowException( "Expected end of \"library_lights\" element.");
  721. break;
  722. }
  723. }
  724. }
  725. // ------------------------------------------------------------------------------------------------
  726. // Reads the camera library
  727. void ColladaParser::ReadCameraLibrary()
  728. {
  729. while( mReader->read())
  730. {
  731. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  732. if( IsElement( "camera"))
  733. {
  734. // read ID. By now you propably know my opinion about this "specification"
  735. int attrID = GetAttribute( "id");
  736. std::string id = mReader->getAttributeValue( attrID);
  737. // create an entry and store it in the library under its ID
  738. Camera& cam = mCameraLibrary[id];
  739. attrID = TestAttribute( "name");
  740. if (attrID != -1)
  741. cam.mName = mReader->getAttributeValue( attrID);
  742. ReadCamera(cam);
  743. } else
  744. {
  745. // ignore the rest
  746. SkipElement();
  747. }
  748. }
  749. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  750. if( strcmp( mReader->getNodeName(), "library_cameras") != 0)
  751. ThrowException( "Expected end of \"library_cameras\" element.");
  752. break;
  753. }
  754. }
  755. }
  756. // ------------------------------------------------------------------------------------------------
  757. // Reads a material entry into the given material
  758. void ColladaParser::ReadMaterial( Collada::Material& pMaterial)
  759. {
  760. while( mReader->read())
  761. {
  762. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  763. if( IsElement( "instance_effect"))
  764. {
  765. // referred effect by URL
  766. int attrUrl = GetAttribute( "url");
  767. const char* url = mReader->getAttributeValue( attrUrl);
  768. if( url[0] != '#')
  769. ThrowException( "Unknown reference format");
  770. pMaterial.mEffect = url+1;
  771. SkipElement();
  772. } else
  773. {
  774. // ignore the rest
  775. SkipElement();
  776. }
  777. }
  778. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  779. if( strcmp( mReader->getNodeName(), "material") != 0)
  780. ThrowException( "Expected end of \"material\" element.");
  781. break;
  782. }
  783. }
  784. }
  785. // ------------------------------------------------------------------------------------------------
  786. // Reads a light entry into the given light
  787. void ColladaParser::ReadLight( Collada::Light& pLight)
  788. {
  789. while( mReader->read())
  790. {
  791. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  792. if (IsElement("spot")) {
  793. pLight.mType = aiLightSource_SPOT;
  794. }
  795. else if (IsElement("ambient")) {
  796. pLight.mType = aiLightSource_AMBIENT;
  797. }
  798. else if (IsElement("directional")) {
  799. pLight.mType = aiLightSource_DIRECTIONAL;
  800. }
  801. else if (IsElement("point")) {
  802. pLight.mType = aiLightSource_POINT;
  803. }
  804. else if (IsElement("color")) {
  805. // text content contains 3 floats
  806. const char* content = GetTextContent();
  807. content = fast_atof_move( content, (float&)pLight.mColor.r);
  808. SkipSpacesAndLineEnd( &content);
  809. content = fast_atof_move( content, (float&)pLight.mColor.g);
  810. SkipSpacesAndLineEnd( &content);
  811. content = fast_atof_move( content, (float&)pLight.mColor.b);
  812. SkipSpacesAndLineEnd( &content);
  813. TestClosing( "color");
  814. }
  815. else if (IsElement("constant_attenuation")) {
  816. pLight.mAttConstant = ReadFloatFromTextContent();
  817. TestClosing("constant_attenuation");
  818. }
  819. else if (IsElement("linear_attenuation")) {
  820. pLight.mAttLinear = ReadFloatFromTextContent();
  821. TestClosing("linear_attenuation");
  822. }
  823. else if (IsElement("quadratic_attenuation")) {
  824. pLight.mAttQuadratic = ReadFloatFromTextContent();
  825. TestClosing("quadratic_attenuation");
  826. }
  827. else if (IsElement("falloff_angle")) {
  828. pLight.mFalloffAngle = ReadFloatFromTextContent();
  829. TestClosing("falloff_angle");
  830. }
  831. else if (IsElement("falloff_exponent")) {
  832. pLight.mFalloffExponent = ReadFloatFromTextContent();
  833. TestClosing("falloff_exponent");
  834. }
  835. // FCOLLADA extensions
  836. // -------------------------------------------------------
  837. else if (IsElement("outer_cone")) {
  838. pLight.mOuterAngle = ReadFloatFromTextContent();
  839. TestClosing("outer_cone");
  840. }
  841. // ... and this one is even deprecated
  842. else if (IsElement("penumbra_angle")) {
  843. pLight.mPenumbraAngle = ReadFloatFromTextContent();
  844. TestClosing("penumbra_angle");
  845. }
  846. else if (IsElement("intensity")) {
  847. pLight.mIntensity = ReadFloatFromTextContent();
  848. TestClosing("intensity");
  849. }
  850. }
  851. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  852. if( strcmp( mReader->getNodeName(), "light") == 0)
  853. break;
  854. }
  855. }
  856. }
  857. // ------------------------------------------------------------------------------------------------
  858. // Reads a camera entry into the given light
  859. void ColladaParser::ReadCamera( Collada::Camera& pCamera)
  860. {
  861. while( mReader->read())
  862. {
  863. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  864. if (IsElement("orthographic")) {
  865. pCamera.mOrtho = true;
  866. }
  867. else if (IsElement("xfov") || IsElement("xmag")) {
  868. pCamera.mHorFov = ReadFloatFromTextContent();
  869. TestClosing((pCamera.mOrtho ? "xmag" : "xfov"));
  870. }
  871. else if (IsElement("yfov") || IsElement("ymag")) {
  872. pCamera.mVerFov = ReadFloatFromTextContent();
  873. TestClosing((pCamera.mOrtho ? "ymag" : "yfov"));
  874. }
  875. else if (IsElement("aspect_ratio")) {
  876. pCamera.mAspect = ReadFloatFromTextContent();
  877. TestClosing("aspect_ratio");
  878. }
  879. else if (IsElement("znear")) {
  880. pCamera.mZNear = ReadFloatFromTextContent();
  881. TestClosing("znear");
  882. }
  883. else if (IsElement("zfar")) {
  884. pCamera.mZFar = ReadFloatFromTextContent();
  885. TestClosing("zfar");
  886. }
  887. }
  888. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  889. if( strcmp( mReader->getNodeName(), "camera") == 0)
  890. break;
  891. }
  892. }
  893. }
  894. // ------------------------------------------------------------------------------------------------
  895. // Reads the effect library
  896. void ColladaParser::ReadEffectLibrary()
  897. {
  898. while( mReader->read())
  899. {
  900. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  901. if( IsElement( "effect"))
  902. {
  903. // read ID. Do I have to repeat my ranting about "optional" attributes?
  904. // Alex: .... no, not necessary. Please shut up and leave more space for
  905. // me to complain about the fucking Collada spec with its fucking
  906. // 'optional' attributes ...
  907. int attrID = GetAttribute( "id");
  908. std::string id = mReader->getAttributeValue( attrID);
  909. // create an entry and store it in the library under its ID
  910. mEffectLibrary[id] = Effect();
  911. // read on from there
  912. ReadEffect( mEffectLibrary[id]);
  913. } else
  914. {
  915. // ignore the rest
  916. SkipElement();
  917. }
  918. }
  919. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  920. if( strcmp( mReader->getNodeName(), "library_effects") != 0)
  921. ThrowException( "Expected end of \"library_effects\" element.");
  922. break;
  923. }
  924. }
  925. }
  926. // ------------------------------------------------------------------------------------------------
  927. // Reads an effect entry into the given effect
  928. void ColladaParser::ReadEffect( Collada::Effect& pEffect)
  929. {
  930. // for the moment we don't support any other type of effect.
  931. // TODO: (thom) Rewrite this so that it ignores the whole effect instead of bailing out
  932. TestOpening( "profile_COMMON");
  933. while( mReader->read())
  934. {
  935. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  936. {
  937. if( IsElement( "newparam")) {
  938. // save ID
  939. int attrSID = GetAttribute( "sid");
  940. std::string sid = mReader->getAttributeValue( attrSID);
  941. pEffect.mParams[sid] = EffectParam();
  942. ReadEffectParam( pEffect.mParams[sid]);
  943. }
  944. else if( IsElement( "technique"))
  945. {
  946. // just syntactic sugar
  947. }
  948. /* Shading modes */
  949. else if( IsElement( "phong"))
  950. pEffect.mShadeType = Shade_Phong;
  951. else if( IsElement( "constant"))
  952. pEffect.mShadeType = Shade_Constant;
  953. else if( IsElement( "lambert"))
  954. pEffect.mShadeType = Shade_Lambert;
  955. else if( IsElement( "blinn"))
  956. pEffect.mShadeType = Shade_Blinn;
  957. /* Color + texture properties */
  958. else if( IsElement( "emission"))
  959. ReadEffectColor( pEffect.mEmissive, pEffect.mTexEmissive);
  960. else if( IsElement( "ambient"))
  961. ReadEffectColor( pEffect.mAmbient, pEffect.mTexAmbient);
  962. else if( IsElement( "diffuse"))
  963. ReadEffectColor( pEffect.mDiffuse, pEffect.mTexDiffuse);
  964. else if( IsElement( "specular"))
  965. ReadEffectColor( pEffect.mSpecular, pEffect.mTexSpecular);
  966. else if( IsElement( "reflective")) {
  967. ReadEffectColor( pEffect.mReflective, pEffect.mTexReflective);
  968. }
  969. else if( IsElement( "transparent")) {
  970. ReadEffectColor( pEffect.mTransparent,pEffect.mTexTransparent);
  971. }
  972. else if( IsElement( "shininess"))
  973. ReadEffectFloat( pEffect.mShininess);
  974. /* Single scalar properties */
  975. else if( IsElement( "transparency"))
  976. ReadEffectFloat( pEffect.mTransparency);
  977. else if( IsElement( "index_of_refraction"))
  978. ReadEffectFloat( pEffect.mRefractIndex);
  979. // GOOGLEEARTH/OKINO extensions
  980. // -------------------------------------------------------
  981. else if( IsElement( "double_sided"))
  982. pEffect.mDoubleSided = ReadBoolFromTextContent();
  983. // FCOLLADA extensions
  984. // -------------------------------------------------------
  985. else if( IsElement( "bump")) {
  986. aiColor4D dummy;
  987. ReadEffectColor( dummy,pEffect.mTexBump);
  988. }
  989. // MAX3D extensions
  990. // -------------------------------------------------------
  991. else if( IsElement( "wireframe")) {
  992. pEffect.mWireframe = ReadBoolFromTextContent();
  993. TestClosing( "wireframe");
  994. }
  995. else if( IsElement( "faceted")) {
  996. pEffect.mFaceted = ReadBoolFromTextContent();
  997. TestClosing( "faceted");
  998. }
  999. #if 0
  1000. else {
  1001. // ignore the rest
  1002. SkipElement();
  1003. }
  1004. #endif
  1005. }
  1006. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  1007. if( strcmp( mReader->getNodeName(), "effect") == 0)
  1008. break;
  1009. }
  1010. }
  1011. }
  1012. // ------------------------------------------------------------------------------------------------
  1013. // Read texture wrapping + UV transform settings from a profile==Maya chunk
  1014. void ColladaParser::ReadSamplerProperties( Sampler& out )
  1015. {
  1016. if (mReader->isEmptyElement())
  1017. return;
  1018. while( mReader->read())
  1019. {
  1020. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  1021. // MAYA extensions
  1022. // -------------------------------------------------------
  1023. if( IsElement( "wrapU")) {
  1024. out.mWrapU = ReadBoolFromTextContent();
  1025. TestClosing( "wrapU");
  1026. }
  1027. else if( IsElement( "wrapV")) {
  1028. out.mWrapU = ReadBoolFromTextContent();
  1029. TestClosing( "wrapV");
  1030. }
  1031. if( IsElement( "mirrorU")) {
  1032. out.mMirrorU = ReadBoolFromTextContent();
  1033. TestClosing( "mirrorU");
  1034. }
  1035. else if( IsElement( "mirrorV")) {
  1036. out.mMirrorU = ReadBoolFromTextContent();
  1037. TestClosing( "mirrorV");
  1038. }
  1039. else if( IsElement( "repeatU")) {
  1040. out.mTransform.mScaling.x = ReadFloatFromTextContent();
  1041. TestClosing( "repeatU");
  1042. }
  1043. else if( IsElement( "repeatV")) {
  1044. out.mTransform.mScaling.y = ReadFloatFromTextContent();
  1045. TestClosing( "repeatV");
  1046. }
  1047. else if( IsElement( "offsetU")) {
  1048. out.mTransform.mTranslation.x = ReadFloatFromTextContent();
  1049. TestClosing( "offsetU");
  1050. }
  1051. else if( IsElement( "offsetV")) {
  1052. out.mTransform.mTranslation.x = ReadFloatFromTextContent();
  1053. TestClosing( "offsetV");
  1054. }
  1055. else if( IsElement( "rotateUV")) {
  1056. out.mTransform.mRotation = ReadFloatFromTextContent();
  1057. TestClosing( "rotateUV");
  1058. }
  1059. else if( IsElement( "blend_mode")) {
  1060. const char* sz = GetTextContent();
  1061. // http://www.feelingsoftware.com/content/view/55/72/lang,en/
  1062. // NONE, OVER, IN, OUT, ADD, SUBTRACT, MULTIPLY, DIFFERENCE, LIGHTEN, DARKEN, SATURATE, DESATURATE and ILLUMINATE
  1063. if (0 == ASSIMP_strincmp(sz,"ADD",3))
  1064. out.mOp = aiTextureOp_Add;
  1065. else if (0 == ASSIMP_strincmp(sz,"SUBTRACT",8))
  1066. out.mOp = aiTextureOp_Subtract;
  1067. else if (0 == ASSIMP_strincmp(sz,"MULTIPLY",8))
  1068. out.mOp = aiTextureOp_Multiply;
  1069. else {
  1070. DefaultLogger::get()->warn("Collada: Unsupported MAYA texture blend mode");
  1071. }
  1072. TestClosing( "blend_mode");
  1073. }
  1074. // OKINO extensions
  1075. // -------------------------------------------------------
  1076. else if( IsElement( "weighting")) {
  1077. out.mWeighting = ReadFloatFromTextContent();
  1078. TestClosing( "weighting");
  1079. }
  1080. else if( IsElement( "mix_with_previous_layer")) {
  1081. out.mMixWithPrevious = ReadFloatFromTextContent();
  1082. TestClosing( "mix_with_previous_layer");
  1083. }
  1084. // MAX3D extensions
  1085. // -------------------------------------------------------
  1086. else if( IsElement( "amount")) {
  1087. out.mWeighting = ReadFloatFromTextContent();
  1088. TestClosing( "amount");
  1089. }
  1090. }
  1091. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  1092. if( strcmp( mReader->getNodeName(), "technique") == 0)
  1093. break;
  1094. }
  1095. }
  1096. }
  1097. // ------------------------------------------------------------------------------------------------
  1098. // Reads an effect entry containing a color or a texture defining that color
  1099. void ColladaParser::ReadEffectColor( aiColor4D& pColor, Sampler& pSampler)
  1100. {
  1101. if (mReader->isEmptyElement())
  1102. return;
  1103. // Save current element name
  1104. const std::string curElem = mReader->getNodeName();
  1105. while( mReader->read())
  1106. {
  1107. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  1108. if( IsElement( "color"))
  1109. {
  1110. // text content contains 4 floats
  1111. const char* content = GetTextContent();
  1112. content = fast_atof_move( content, (float&)pColor.r);
  1113. SkipSpacesAndLineEnd( &content);
  1114. content = fast_atof_move( content, (float&)pColor.g);
  1115. SkipSpacesAndLineEnd( &content);
  1116. content = fast_atof_move( content, (float&)pColor.b);
  1117. SkipSpacesAndLineEnd( &content);
  1118. content = fast_atof_move( content, (float&)pColor.a);
  1119. SkipSpacesAndLineEnd( &content);
  1120. TestClosing( "color");
  1121. }
  1122. else if( IsElement( "texture"))
  1123. {
  1124. // get name of source textur/sampler
  1125. int attrTex = GetAttribute( "texture");
  1126. pSampler.mName = mReader->getAttributeValue( attrTex);
  1127. // get name of UV source channel
  1128. attrTex = GetAttribute( "texcoord");
  1129. pSampler.mUVChannel = mReader->getAttributeValue( attrTex);
  1130. //SkipElement();
  1131. }
  1132. else if( IsElement( "technique"))
  1133. {
  1134. const int _profile = GetAttribute( "profile");
  1135. const char* profile = mReader->getAttributeValue( _profile );
  1136. // Some extensions are quite useful ... ReadSamplerProperties processes
  1137. // several extensions in MAYA, OKINO and MAX3D profiles.
  1138. if (!::strcmp(profile,"MAYA") || !::strcmp(profile,"MAX3D") || !::strcmp(profile,"OKINO"))
  1139. {
  1140. // get more information on this sampler
  1141. ReadSamplerProperties(pSampler);
  1142. }
  1143. else SkipElement();
  1144. }
  1145. else
  1146. {
  1147. // ignore the rest
  1148. SkipElement();
  1149. }
  1150. }
  1151. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){
  1152. if (mReader->getNodeName() == curElem)
  1153. break;
  1154. }
  1155. }
  1156. }
  1157. // ------------------------------------------------------------------------------------------------
  1158. // Reads an effect entry containing a float
  1159. void ColladaParser::ReadEffectFloat( float& pFloat)
  1160. {
  1161. while( mReader->read())
  1162. {
  1163. if( mReader->getNodeType() == irr::io::EXN_ELEMENT){
  1164. if( IsElement( "float"))
  1165. {
  1166. // text content contains a single floats
  1167. const char* content = GetTextContent();
  1168. content = fast_atof_move( content, pFloat);
  1169. SkipSpacesAndLineEnd( &content);
  1170. TestClosing( "float");
  1171. } else
  1172. {
  1173. // ignore the rest
  1174. SkipElement();
  1175. }
  1176. }
  1177. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){
  1178. break;
  1179. }
  1180. }
  1181. }
  1182. // ------------------------------------------------------------------------------------------------
  1183. // Reads an effect parameter specification of any kind
  1184. void ColladaParser::ReadEffectParam( Collada::EffectParam& pParam)
  1185. {
  1186. while( mReader->read())
  1187. {
  1188. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  1189. if( IsElement( "surface"))
  1190. {
  1191. // image ID given inside <init_from> tags
  1192. TestOpening( "init_from");
  1193. const char* content = GetTextContent();
  1194. pParam.mType = Param_Surface;
  1195. pParam.mReference = content;
  1196. TestClosing( "init_from");
  1197. // don't care for remaining stuff
  1198. SkipElement( "surface");
  1199. }
  1200. else if( IsElement( "sampler2D"))
  1201. {
  1202. // surface ID is given inside <source> tags
  1203. TestOpening( "source");
  1204. const char* content = GetTextContent();
  1205. pParam.mType = Param_Sampler;
  1206. pParam.mReference = content;
  1207. TestClosing( "source");
  1208. // don't care for remaining stuff
  1209. SkipElement( "sampler2D");
  1210. } else
  1211. {
  1212. // ignore unknown element
  1213. SkipElement();
  1214. }
  1215. }
  1216. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  1217. break;
  1218. }
  1219. }
  1220. }
  1221. // ------------------------------------------------------------------------------------------------
  1222. // Reads the geometry library contents
  1223. void ColladaParser::ReadGeometryLibrary()
  1224. {
  1225. while( mReader->read())
  1226. {
  1227. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1228. {
  1229. if( IsElement( "geometry"))
  1230. {
  1231. // read ID. Another entry which is "optional" by design but obligatory in reality
  1232. int indexID = GetAttribute( "id");
  1233. std::string id = mReader->getAttributeValue( indexID);
  1234. // TODO: (thom) support SIDs
  1235. // ai_assert( TestAttribute( "sid") == -1);
  1236. // create a mesh and store it in the library under its ID
  1237. Mesh* mesh = new Mesh;
  1238. mMeshLibrary[id] = mesh;
  1239. // read on from there
  1240. ReadGeometry( mesh);
  1241. } else
  1242. {
  1243. // ignore the rest
  1244. SkipElement();
  1245. }
  1246. }
  1247. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1248. {
  1249. if( strcmp( mReader->getNodeName(), "library_geometries") != 0)
  1250. ThrowException( "Expected end of \"library_geometries\" element.");
  1251. break;
  1252. }
  1253. }
  1254. }
  1255. // ------------------------------------------------------------------------------------------------
  1256. // Reads a geometry from the geometry library.
  1257. void ColladaParser::ReadGeometry( Collada::Mesh* pMesh)
  1258. {
  1259. while( mReader->read())
  1260. {
  1261. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1262. {
  1263. if( IsElement( "mesh"))
  1264. {
  1265. // read on from there
  1266. ReadMesh( pMesh);
  1267. } else
  1268. {
  1269. // ignore the rest
  1270. SkipElement();
  1271. }
  1272. }
  1273. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1274. {
  1275. if( strcmp( mReader->getNodeName(), "geometry") != 0)
  1276. ThrowException( "Expected end of \"geometry\" element.");
  1277. break;
  1278. }
  1279. }
  1280. }
  1281. // ------------------------------------------------------------------------------------------------
  1282. // Reads a mesh from the geometry library
  1283. void ColladaParser::ReadMesh( Mesh* pMesh)
  1284. {
  1285. while( mReader->read())
  1286. {
  1287. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1288. {
  1289. if( IsElement( "source"))
  1290. {
  1291. // we have professionals dealing with this
  1292. ReadSource();
  1293. }
  1294. else if( IsElement( "vertices"))
  1295. {
  1296. // read per-vertex mesh data
  1297. ReadVertexData( pMesh);
  1298. }
  1299. else if( IsElement( "triangles") || IsElement( "lines") || IsElement( "linestrips")
  1300. || IsElement( "polygons") || IsElement( "polylist") || IsElement( "trifans") || IsElement( "tristrips"))
  1301. {
  1302. // read per-index mesh data and faces setup
  1303. ReadIndexData( pMesh);
  1304. } else
  1305. {
  1306. // ignore the rest
  1307. SkipElement();
  1308. }
  1309. }
  1310. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1311. {
  1312. if( strcmp( mReader->getNodeName(), "technique_common") == 0)
  1313. {
  1314. // end of another meaningless element - read over it
  1315. }
  1316. else if( strcmp( mReader->getNodeName(), "mesh") == 0)
  1317. {
  1318. // end of <mesh> element - we're done here
  1319. break;
  1320. } else
  1321. {
  1322. // everything else should be punished
  1323. ThrowException( "Expected end of \"mesh\" element.");
  1324. }
  1325. }
  1326. }
  1327. }
  1328. // ------------------------------------------------------------------------------------------------
  1329. // Reads a source element
  1330. void ColladaParser::ReadSource()
  1331. {
  1332. int indexID = GetAttribute( "id");
  1333. std::string sourceID = mReader->getAttributeValue( indexID);
  1334. while( mReader->read())
  1335. {
  1336. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1337. {
  1338. if( IsElement( "float_array") || IsElement( "IDREF_array") || IsElement( "Name_array"))
  1339. {
  1340. ReadDataArray();
  1341. }
  1342. else if( IsElement( "technique_common"))
  1343. {
  1344. // I don't fucking care for your profiles bullshit
  1345. }
  1346. else if( IsElement( "accessor"))
  1347. {
  1348. ReadAccessor( sourceID);
  1349. } else
  1350. {
  1351. // ignore the rest
  1352. SkipElement();
  1353. }
  1354. }
  1355. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1356. {
  1357. if( strcmp( mReader->getNodeName(), "source") == 0)
  1358. {
  1359. // end of <source> - we're done
  1360. break;
  1361. }
  1362. else if( strcmp( mReader->getNodeName(), "technique_common") == 0)
  1363. {
  1364. // end of another meaningless element - read over it
  1365. } else
  1366. {
  1367. // everything else should be punished
  1368. ThrowException( "Expected end of \"source\" element.");
  1369. }
  1370. }
  1371. }
  1372. }
  1373. // ------------------------------------------------------------------------------------------------
  1374. // Reads a data array holding a number of floats, and stores it in the global library
  1375. void ColladaParser::ReadDataArray()
  1376. {
  1377. std::string elmName = mReader->getNodeName();
  1378. bool isStringArray = (elmName == "IDREF_array" || elmName == "Name_array");
  1379. // read attributes
  1380. int indexID = GetAttribute( "id");
  1381. std::string id = mReader->getAttributeValue( indexID);
  1382. int indexCount = GetAttribute( "count");
  1383. unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( indexCount);
  1384. const char* content = GetTextContent();
  1385. // read values and store inside an array in the data library
  1386. mDataLibrary[id] = Data();
  1387. Data& data = mDataLibrary[id];
  1388. data.mIsStringArray = isStringArray;
  1389. if( isStringArray)
  1390. {
  1391. data.mStrings.reserve( count);
  1392. std::string s;
  1393. for( unsigned int a = 0; a < count; a++)
  1394. {
  1395. if( *content == 0)
  1396. ThrowException( "Expected more values while reading IDREF_array contents.");
  1397. s.clear();
  1398. while( !IsSpaceOrNewLine( *content))
  1399. s += *content++;
  1400. data.mStrings.push_back( s);
  1401. SkipSpacesAndLineEnd( &content);
  1402. }
  1403. } else
  1404. {
  1405. data.mValues.reserve( count);
  1406. for( unsigned int a = 0; a < count; a++)
  1407. {
  1408. if( *content == 0)
  1409. ThrowException( "Expected more values while reading float_array contents.");
  1410. float value;
  1411. // read a number
  1412. content = fast_atof_move( content, value);
  1413. data.mValues.push_back( value);
  1414. // skip whitespace after it
  1415. SkipSpacesAndLineEnd( &content);
  1416. }
  1417. }
  1418. // test for closing tag
  1419. TestClosing( elmName.c_str());
  1420. }
  1421. // ------------------------------------------------------------------------------------------------
  1422. // Reads an accessor and stores it in the global library
  1423. void ColladaParser::ReadAccessor( const std::string& pID)
  1424. {
  1425. // read accessor attributes
  1426. int attrSource = GetAttribute( "source");
  1427. const char* source = mReader->getAttributeValue( attrSource);
  1428. if( source[0] != '#')
  1429. ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\".") % source));
  1430. int attrCount = GetAttribute( "count");
  1431. unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( attrCount);
  1432. int attrOffset = TestAttribute( "offset");
  1433. unsigned int offset = 0;
  1434. if( attrOffset > -1)
  1435. offset = (unsigned int) mReader->getAttributeValueAsInt( attrOffset);
  1436. int attrStride = TestAttribute( "stride");
  1437. unsigned int stride = 1;
  1438. if( attrStride > -1)
  1439. stride = (unsigned int) mReader->getAttributeValueAsInt( attrStride);
  1440. // store in the library under the given ID
  1441. mAccessorLibrary[pID] = Accessor();
  1442. Accessor& acc = mAccessorLibrary[pID];
  1443. acc.mCount = count;
  1444. acc.mOffset = offset;
  1445. acc.mStride = stride;
  1446. acc.mSource = source+1; // ignore the leading '#'
  1447. // and read the components
  1448. while( mReader->read())
  1449. {
  1450. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1451. {
  1452. if( IsElement( "param"))
  1453. {
  1454. // read data param
  1455. int attrName = TestAttribute( "name");
  1456. std::string name;
  1457. if( attrName > -1)
  1458. {
  1459. name = mReader->getAttributeValue( attrName);
  1460. // analyse for common type components and store it's sub-offset in the corresponding field
  1461. /* Cartesian coordinates */
  1462. if( name == "X") acc.mSubOffset[0] = acc.mParams.size();
  1463. else if( name == "Y") acc.mSubOffset[1] = acc.mParams.size();
  1464. else if( name == "Z") acc.mSubOffset[2] = acc.mParams.size();
  1465. /* RGBA colors */
  1466. else if( name == "R") acc.mSubOffset[0] = acc.mParams.size();
  1467. else if( name == "G") acc.mSubOffset[1] = acc.mParams.size();
  1468. else if( name == "B") acc.mSubOffset[2] = acc.mParams.size();
  1469. else if( name == "A") acc.mSubOffset[3] = acc.mParams.size();
  1470. /* UVWQ (STPQ) texture coordinates */
  1471. else if( name == "S") acc.mSubOffset[0] = acc.mParams.size();
  1472. else if( name == "T") acc.mSubOffset[1] = acc.mParams.size();
  1473. else if( name == "P") acc.mSubOffset[2] = acc.mParams.size();
  1474. // else if( name == "Q") acc.mSubOffset[3] = acc.mParams.size();
  1475. /* 4D uv coordinates are not supported in Assimp */
  1476. /* Generic extra data, interpreted as UV data, too*/
  1477. else if( name == "U") acc.mSubOffset[0] = acc.mParams.size();
  1478. else if( name == "V") acc.mSubOffset[1] = acc.mParams.size();
  1479. else
  1480. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown accessor parameter \"%s\". Ignoring data channel.") % name));
  1481. }
  1482. acc.mParams.push_back( name);
  1483. // skip remaining stuff of this element, if any
  1484. SkipElement();
  1485. } else
  1486. {
  1487. ThrowException( "Unexpected sub element in tag \"accessor\".");
  1488. }
  1489. }
  1490. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1491. {
  1492. if( strcmp( mReader->getNodeName(), "accessor") != 0)
  1493. ThrowException( "Expected end of \"accessor\" element.");
  1494. break;
  1495. }
  1496. }
  1497. }
  1498. // ------------------------------------------------------------------------------------------------
  1499. // Reads input declarations of per-vertex mesh data into the given mesh
  1500. void ColladaParser::ReadVertexData( Mesh* pMesh)
  1501. {
  1502. // extract the ID of the <vertices> element. Not that we care, but to catch strange referencing schemes we should warn about
  1503. int attrID= GetAttribute( "id");
  1504. pMesh->mVertexID = mReader->getAttributeValue( attrID);
  1505. // a number of <input> elements
  1506. while( mReader->read())
  1507. {
  1508. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1509. {
  1510. if( IsElement( "input"))
  1511. {
  1512. ReadInputChannel( pMesh->mPerVertexData);
  1513. } else
  1514. {
  1515. ThrowException( "Unexpected sub element in tag \"vertices\".");
  1516. }
  1517. }
  1518. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1519. {
  1520. if( strcmp( mReader->getNodeName(), "vertices") != 0)
  1521. ThrowException( "Expected end of \"vertices\" element.");
  1522. break;
  1523. }
  1524. }
  1525. }
  1526. // ------------------------------------------------------------------------------------------------
  1527. // Reads input declarations of per-index mesh data into the given mesh
  1528. void ColladaParser::ReadIndexData( Mesh* pMesh)
  1529. {
  1530. std::vector<size_t> vcount;
  1531. std::vector<InputChannel> perIndexData;
  1532. // read primitive count from the attribute
  1533. int attrCount = GetAttribute( "count");
  1534. size_t numPrimitives = (size_t) mReader->getAttributeValueAsInt( attrCount);
  1535. // material subgroup
  1536. int attrMaterial = TestAttribute( "material");
  1537. SubMesh subgroup;
  1538. if( attrMaterial > -1)
  1539. subgroup.mMaterial = mReader->getAttributeValue( attrMaterial);
  1540. subgroup.mNumFaces = numPrimitives;
  1541. pMesh->mSubMeshes.push_back( subgroup);
  1542. // distinguish between polys and triangles
  1543. std::string elementName = mReader->getNodeName();
  1544. PrimitiveType primType = Prim_Invalid;
  1545. if( IsElement( "lines"))
  1546. primType = Prim_Lines;
  1547. else if( IsElement( "linestrips"))
  1548. primType = Prim_LineStrip;
  1549. else if( IsElement( "polygons"))
  1550. primType = Prim_Polygon;
  1551. else if( IsElement( "polylist"))
  1552. primType = Prim_Polylist;
  1553. else if( IsElement( "triangles"))
  1554. primType = Prim_Triangles;
  1555. else if( IsElement( "trifans"))
  1556. primType = Prim_TriFans;
  1557. else if( IsElement( "tristrips"))
  1558. primType = Prim_TriStrips;
  1559. ai_assert( primType != Prim_Invalid);
  1560. // also a number of <input> elements, but in addition a <p> primitive collection and propably index counts for all primitives
  1561. while( mReader->read())
  1562. {
  1563. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1564. {
  1565. if( IsElement( "input"))
  1566. {
  1567. ReadInputChannel( perIndexData);
  1568. }
  1569. else if( IsElement( "vcount"))
  1570. {
  1571. if( !mReader->isEmptyElement())
  1572. {
  1573. // case <polylist> - specifies the number of indices for each polygon
  1574. const char* content = GetTextContent();
  1575. vcount.reserve( numPrimitives);
  1576. for( unsigned int a = 0; a < numPrimitives; a++)
  1577. {
  1578. if( *content == 0)
  1579. ThrowException( "Expected more values while reading vcount contents.");
  1580. // read a number
  1581. vcount.push_back( (size_t) strtol10( content, &content));
  1582. // skip whitespace after it
  1583. SkipSpacesAndLineEnd( &content);
  1584. }
  1585. TestClosing( "vcount");
  1586. }
  1587. }
  1588. else if( IsElement( "p"))
  1589. {
  1590. if( !mReader->isEmptyElement())
  1591. {
  1592. // now here the actual fun starts - these are the indices to construct the mesh data from
  1593. ReadPrimitives( pMesh, perIndexData, numPrimitives, vcount, primType);
  1594. }
  1595. } else
  1596. {
  1597. ThrowException( "Unexpected sub element in tag \"vertices\".");
  1598. }
  1599. }
  1600. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1601. {
  1602. if( mReader->getNodeName() != elementName)
  1603. ThrowException( boost::str( boost::format( "Expected end of \"%s\" element.") % elementName));
  1604. break;
  1605. }
  1606. }
  1607. }
  1608. // ------------------------------------------------------------------------------------------------
  1609. // Reads a single input channel element and stores it in the given array, if valid
  1610. void ColladaParser::ReadInputChannel( std::vector<InputChannel>& poChannels)
  1611. {
  1612. InputChannel channel;
  1613. // read semantic
  1614. int attrSemantic = GetAttribute( "semantic");
  1615. std::string semantic = mReader->getAttributeValue( attrSemantic);
  1616. channel.mType = GetTypeForSemantic( semantic);
  1617. // read source
  1618. int attrSource = GetAttribute( "source");
  1619. const char* source = mReader->getAttributeValue( attrSource);
  1620. if( source[0] != '#')
  1621. ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\".") % source));
  1622. channel.mAccessor = source+1; // skipping the leading #, hopefully the remaining text is the accessor ID only
  1623. // read index offset, if per-index <input>
  1624. int attrOffset = TestAttribute( "offset");
  1625. if( attrOffset > -1)
  1626. channel.mOffset = mReader->getAttributeValueAsInt( attrOffset);
  1627. // read set if texture coordinates
  1628. if(channel.mType == IT_Texcoord || channel.mType == IT_Color){
  1629. int attrSet = TestAttribute("set");
  1630. if(attrSet > -1){
  1631. attrSet = mReader->getAttributeValueAsInt( attrSet);
  1632. if(attrSet < 0)
  1633. ThrowException( boost::str( boost::format( "Invalid index \"%i\" for set attribute") % (attrSet)));
  1634. channel.mIndex = attrSet;
  1635. }
  1636. }
  1637. // store, if valid type
  1638. if( channel.mType != IT_Invalid)
  1639. poChannels.push_back( channel);
  1640. // skip remaining stuff of this element, if any
  1641. SkipElement();
  1642. }
  1643. // ------------------------------------------------------------------------------------------------
  1644. // Reads a <p> primitive index list and assembles the mesh data into the given mesh
  1645. void ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pPerIndexChannels,
  1646. size_t pNumPrimitives, const std::vector<size_t>& pVCount, PrimitiveType pPrimType)
  1647. {
  1648. // determine number of indices coming per vertex
  1649. // find the offset index for all per-vertex channels
  1650. size_t numOffsets = 1;
  1651. size_t perVertexOffset = 0xffffffff; // invalid value
  1652. BOOST_FOREACH( const InputChannel& channel, pPerIndexChannels)
  1653. {
  1654. numOffsets = std::max( numOffsets, channel.mOffset+1);
  1655. if( channel.mType == IT_Vertex)
  1656. perVertexOffset = channel.mOffset;
  1657. }
  1658. // determine the expected number of indices
  1659. size_t expectedPointCount = 0;
  1660. switch( pPrimType)
  1661. {
  1662. case Prim_Polylist:
  1663. {
  1664. BOOST_FOREACH( size_t i, pVCount)
  1665. expectedPointCount += i;
  1666. break;
  1667. }
  1668. case Prim_Lines:
  1669. expectedPointCount = 2 * pNumPrimitives;
  1670. break;
  1671. case Prim_Triangles:
  1672. expectedPointCount = 3 * pNumPrimitives;
  1673. break;
  1674. default:
  1675. // other primitive types don't state the index count upfront... we need to guess
  1676. break;
  1677. }
  1678. // and read all indices into a temporary array
  1679. std::vector<size_t> indices;
  1680. if( expectedPointCount > 0)
  1681. indices.reserve( expectedPointCount * numOffsets);
  1682. const char* content = GetTextContent();
  1683. while( *content != 0)
  1684. {
  1685. // read a value
  1686. unsigned int value = strtol10( content, &content);
  1687. indices.push_back( size_t( value));
  1688. // skip whitespace after it
  1689. SkipSpacesAndLineEnd( &content);
  1690. }
  1691. // complain if the index count doesn't fit
  1692. if( expectedPointCount > 0 && indices.size() != expectedPointCount * numOffsets)
  1693. ThrowException( "Expected different index count in <p> element.");
  1694. else if( expectedPointCount == 0 && (indices.size() % numOffsets) != 0)
  1695. ThrowException( "Expected different index count in <p> element.");
  1696. // find the data for all sources
  1697. BOOST_FOREACH( InputChannel& input, pMesh->mPerVertexData)
  1698. {
  1699. if( input.mResolved)
  1700. continue;
  1701. // find accessor
  1702. input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
  1703. // resolve accessor's data pointer as well, if neccessary
  1704. const Accessor* acc = input.mResolved;
  1705. if( !acc->mData)
  1706. acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
  1707. }
  1708. // and the same for the per-index channels
  1709. BOOST_FOREACH( InputChannel& input, pPerIndexChannels)
  1710. {
  1711. if( input.mResolved)
  1712. continue;
  1713. // ignore vertex pointer, it doesn't refer to an accessor
  1714. if( input.mType == IT_Vertex)
  1715. {
  1716. // warn if the vertex channel does not refer to the <vertices> element in the same mesh
  1717. if( input.mAccessor != pMesh->mVertexID)
  1718. ThrowException( "Unsupported vertex referencing scheme. I fucking hate Collada.");
  1719. continue;
  1720. }
  1721. // find accessor
  1722. input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor);
  1723. // resolve accessor's data pointer as well, if neccessary
  1724. const Accessor* acc = input.mResolved;
  1725. if( !acc->mData)
  1726. acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
  1727. }
  1728. // now assemble vertex data according to those indices
  1729. std::vector<size_t>::const_iterator idx = indices.begin();
  1730. // For continued primitives, the given count does not come all in one <p>, but only one primitive per <p>
  1731. size_t numPrimitives = pNumPrimitives;
  1732. if( pPrimType == Prim_TriFans || pPrimType == Prim_Polygon)
  1733. numPrimitives = 1;
  1734. pMesh->mFaceSize.reserve( numPrimitives);
  1735. pMesh->mFacePosIndices.reserve( indices.size() / numOffsets);
  1736. for( size_t a = 0; a < numPrimitives; a++)
  1737. {
  1738. // determine number of points for this primitive
  1739. size_t numPoints = 0;
  1740. switch( pPrimType)
  1741. {
  1742. case Prim_Lines:
  1743. numPoints = 2;
  1744. break;
  1745. case Prim_Triangles:
  1746. numPoints = 3;
  1747. break;
  1748. case Prim_Polylist:
  1749. numPoints = pVCount[a];
  1750. break;
  1751. case Prim_TriFans:
  1752. case Prim_Polygon:
  1753. numPoints = indices.size() / numOffsets;
  1754. break;
  1755. default:
  1756. // LineStrip and TriStrip not supported due to expected index unmangling
  1757. ThrowException( "Unsupported primitive type.");
  1758. break;
  1759. }
  1760. // store the face size to later reconstruct the face from
  1761. pMesh->mFaceSize.push_back( numPoints);
  1762. // gather that number of vertices
  1763. for( size_t b = 0; b < numPoints; b++)
  1764. {
  1765. // read all indices for this vertex. Yes, in a hacky static array
  1766. assert( numOffsets < 20 && perVertexOffset < 20);
  1767. static size_t vindex[20];
  1768. for( size_t offsets = 0; offsets < numOffsets; ++offsets)
  1769. vindex[offsets] = *idx++;
  1770. // extract per-vertex channels using the global per-vertex offset
  1771. BOOST_FOREACH( const InputChannel& input, pMesh->mPerVertexData)
  1772. ExtractDataObjectFromChannel( input, vindex[perVertexOffset], pMesh);
  1773. // and extract per-index channels using there specified offset
  1774. BOOST_FOREACH( const InputChannel& input, pPerIndexChannels)
  1775. ExtractDataObjectFromChannel( input, vindex[input.mOffset], pMesh);
  1776. // store the vertex-data index for later assignment of bone vertex weights
  1777. pMesh->mFacePosIndices.push_back( vindex[perVertexOffset]);
  1778. }
  1779. }
  1780. // if I ever get my hands on that guy who invented this steaming pile of indirection...
  1781. TestClosing( "p");
  1782. }
  1783. // ------------------------------------------------------------------------------------------------
  1784. // Extracts a single object from an input channel and stores it in the appropriate mesh data array
  1785. void ColladaParser::ExtractDataObjectFromChannel( const InputChannel& pInput, size_t pLocalIndex, Mesh* pMesh)
  1786. {
  1787. // ignore vertex referrer - we handle them that separate
  1788. if( pInput.mType == IT_Vertex)
  1789. return;
  1790. const Accessor& acc = *pInput.mResolved;
  1791. if( pLocalIndex >= acc.mCount)
  1792. ThrowException( boost::str( boost::format( "Invalid data index (%d/%d) in primitive specification") % pLocalIndex % acc.mCount));
  1793. // get a pointer to the start of the data object referred to by the accessor and the local index
  1794. const float* dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex* acc.mStride;
  1795. // assemble according to the accessors component sub-offset list. We don't care, yet,
  1796. // what kind of object exactly we're extracting here
  1797. float obj[4];
  1798. for( size_t c = 0; c < 4; ++c)
  1799. obj[c] = dataObject[acc.mSubOffset[c]];
  1800. // now we reinterpret it according to the type we're reading here
  1801. switch( pInput.mType)
  1802. {
  1803. case IT_Position: // ignore all position streams except 0 - there can be only one position
  1804. if( pInput.mIndex == 0)
  1805. pMesh->mPositions.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1806. else
  1807. DefaultLogger::get()->error("Collada: just one vertex position stream supported");
  1808. break;
  1809. case IT_Normal:
  1810. // pad to current vertex count if necessary
  1811. if( pMesh->mNormals.size() < pMesh->mPositions.size()-1)
  1812. pMesh->mNormals.insert( pMesh->mNormals.end(), pMesh->mPositions.size() - pMesh->mNormals.size() - 1, aiVector3D( 0, 1, 0));
  1813. // ignore all normal streams except 0 - there can be only one normal
  1814. if( pInput.mIndex == 0)
  1815. pMesh->mNormals.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1816. else
  1817. DefaultLogger::get()->error("Collada: just one vertex normal stream supported");
  1818. break;
  1819. case IT_Tangent:
  1820. // pad to current vertex count if necessary
  1821. if( pMesh->mTangents.size() < pMesh->mPositions.size()-1)
  1822. pMesh->mTangents.insert( pMesh->mTangents.end(), pMesh->mPositions.size() - pMesh->mTangents.size() - 1, aiVector3D( 1, 0, 0));
  1823. // ignore all tangent streams except 0 - there can be only one tangent
  1824. if( pInput.mIndex == 0)
  1825. pMesh->mTangents.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1826. else
  1827. DefaultLogger::get()->error("Collada: just one vertex tangent stream supported");
  1828. break;
  1829. case IT_Bitangent:
  1830. // pad to current vertex count if necessary
  1831. if( pMesh->mBitangents.size() < pMesh->mPositions.size()-1)
  1832. pMesh->mBitangents.insert( pMesh->mBitangents.end(), pMesh->mPositions.size() - pMesh->mBitangents.size() - 1, aiVector3D( 0, 0, 1));
  1833. // ignore all bitangent streams except 0 - there can be only one bitangent
  1834. if( pInput.mIndex == 0)
  1835. pMesh->mBitangents.push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1836. else
  1837. DefaultLogger::get()->error("Collada: just one vertex bitangent stream supported");
  1838. break;
  1839. case IT_Texcoord:
  1840. // up to 4 texture coord sets are fine, ignore the others
  1841. if( pInput.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS)
  1842. {
  1843. // pad to current vertex count if necessary
  1844. if( pMesh->mTexCoords[pInput.mIndex].size() < pMesh->mPositions.size()-1)
  1845. pMesh->mTexCoords[pInput.mIndex].insert( pMesh->mTexCoords[pInput.mIndex].end(),
  1846. pMesh->mPositions.size() - pMesh->mTexCoords[pInput.mIndex].size() - 1, aiVector3D( 0, 0, 0));
  1847. pMesh->mTexCoords[pInput.mIndex].push_back( aiVector3D( obj[0], obj[1], obj[2]));
  1848. if (0 != acc.mSubOffset[2] || 0 != acc.mSubOffset[3]) /* hack ... consider cleaner solution */
  1849. pMesh->mNumUVComponents[pInput.mIndex]=3;
  1850. } else
  1851. {
  1852. DefaultLogger::get()->error("Collada: too many texture coordinate sets. Skipping.");
  1853. }
  1854. break;
  1855. case IT_Color:
  1856. // up to 4 color sets are fine, ignore the others
  1857. if( pInput.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS)
  1858. {
  1859. // pad to current vertex count if necessary
  1860. if( pMesh->mColors[pInput.mIndex].size() < pMesh->mPositions.size()-1)
  1861. pMesh->mColors[pInput.mIndex].insert( pMesh->mColors[pInput.mIndex].end(),
  1862. pMesh->mPositions.size() - pMesh->mColors[pInput.mIndex].size() - 1, aiColor4D( 0, 0, 0, 1));
  1863. pMesh->mColors[pInput.mIndex].push_back( aiColor4D( obj[0], obj[1], obj[2], obj[3]));
  1864. } else
  1865. {
  1866. DefaultLogger::get()->error("Collada: too many vertex color sets. Skipping.");
  1867. }
  1868. break;
  1869. }
  1870. }
  1871. // ------------------------------------------------------------------------------------------------
  1872. // Reads the library of node hierarchies and scene parts
  1873. void ColladaParser::ReadSceneLibrary()
  1874. {
  1875. while( mReader->read())
  1876. {
  1877. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1878. {
  1879. // a visual scene - generate root node under its ID and let ReadNode() do the recursive work
  1880. if( IsElement( "visual_scene"))
  1881. {
  1882. // read ID. Is optional according to the spec, but how on earth should a scene_instance refer to it then?
  1883. int indexID = GetAttribute( "id");
  1884. const char* attrID = mReader->getAttributeValue( indexID);
  1885. // read name if given.
  1886. int indexName = TestAttribute( "name");
  1887. const char* attrName = "unnamed";
  1888. if( indexName > -1)
  1889. attrName = mReader->getAttributeValue( indexName);
  1890. // TODO: (thom) support SIDs
  1891. // assert( TestAttribute( "sid") == -1);
  1892. // create a node and store it in the library under its ID
  1893. Node* node = new Node;
  1894. node->mID = attrID;
  1895. node->mName = attrName;
  1896. mNodeLibrary[node->mID] = node;
  1897. ReadSceneNode( node);
  1898. } else
  1899. {
  1900. // ignore the rest
  1901. SkipElement();
  1902. }
  1903. }
  1904. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1905. {
  1906. if( strcmp( mReader->getNodeName(), "library_visual_scenes") == 0)
  1907. //ThrowException( "Expected end of \"library_visual_scenes\" element.");
  1908. break;
  1909. }
  1910. }
  1911. }
  1912. // ------------------------------------------------------------------------------------------------
  1913. // Reads a scene node's contents including children and stores it in the given node
  1914. void ColladaParser::ReadSceneNode( Node* pNode)
  1915. {
  1916. // quit immediately on <bla/> elements
  1917. if( mReader->isEmptyElement())
  1918. return;
  1919. while( mReader->read())
  1920. {
  1921. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1922. {
  1923. if( IsElement( "node"))
  1924. {
  1925. Node* child = new Node;
  1926. int attrID = TestAttribute( "id");
  1927. if( attrID > -1)
  1928. child->mID = mReader->getAttributeValue( attrID);
  1929. int attrName = TestAttribute( "name");
  1930. if( attrName > -1)
  1931. child->mName = mReader->getAttributeValue( attrName);
  1932. // TODO: (thom) support SIDs
  1933. // assert( TestAttribute( "sid") == -1);
  1934. if (pNode)
  1935. {
  1936. pNode->mChildren.push_back( child);
  1937. child->mParent = pNode;
  1938. }
  1939. else
  1940. {
  1941. // no parent node given, probably called from <library_nodes> element.
  1942. // create new node in node library
  1943. mNodeLibrary[child->mID] = pNode = child;
  1944. }
  1945. // read on recursively from there
  1946. ReadSceneNode( child);
  1947. continue;
  1948. }
  1949. // For any further stuff we need a valid node to work on
  1950. else if (!pNode)
  1951. continue;
  1952. if( IsElement( "lookat"))
  1953. ReadNodeTransformation( pNode, TF_LOOKAT);
  1954. else if( IsElement( "matrix"))
  1955. ReadNodeTransformation( pNode, TF_MATRIX);
  1956. else if( IsElement( "rotate"))
  1957. ReadNodeTransformation( pNode, TF_ROTATE);
  1958. else if( IsElement( "scale"))
  1959. ReadNodeTransformation( pNode, TF_SCALE);
  1960. else if( IsElement( "skew"))
  1961. ReadNodeTransformation( pNode, TF_SKEW);
  1962. else if( IsElement( "translate"))
  1963. ReadNodeTransformation( pNode, TF_TRANSLATE);
  1964. else if( IsElement( "render") && pNode->mParent == NULL && 0 == pNode->mPrimaryCamera.length())
  1965. {
  1966. // ... scene evaluation or, in other words, postprocessing pipeline,
  1967. // or, again in other words, a turing-complete description how to
  1968. // render a Collada scene. The only thing that is interesting for
  1969. // us is the primary camera.
  1970. int attrId = TestAttribute("camera_node");
  1971. if (-1 != attrId)
  1972. {
  1973. const char* s = mReader->getAttributeValue(attrId);
  1974. if (s[0] != '#')
  1975. DefaultLogger::get()->error("Collada: Unresolved reference format of camera");
  1976. else
  1977. pNode->mPrimaryCamera = s+1;
  1978. }
  1979. }
  1980. else if( IsElement( "instance_node"))
  1981. {
  1982. // find the node in the library
  1983. int attrID = TestAttribute( "url");
  1984. if( attrID != -1)
  1985. {
  1986. const char* s = mReader->getAttributeValue(attrID);
  1987. if (s[0] != '#')
  1988. DefaultLogger::get()->error("Collada: Unresolved reference format of node");
  1989. else
  1990. {
  1991. pNode->mNodeInstances.push_back(NodeInstance());
  1992. pNode->mNodeInstances.back().mNode = s+1;
  1993. }
  1994. }
  1995. }
  1996. else if( IsElement( "instance_geometry") || IsElement( "instance_controller"))
  1997. {
  1998. // Reference to a mesh or controller, with possible material associations
  1999. ReadNodeGeometry( pNode);
  2000. }
  2001. else if( IsElement( "instance_light"))
  2002. {
  2003. // Reference to a light, name given in 'url' attribute
  2004. int attrID = TestAttribute("url");
  2005. if (-1 == attrID)
  2006. DefaultLogger::get()->warn("Collada: Expected url attribute in <instance_light> element");
  2007. else
  2008. {
  2009. const char* url = mReader->getAttributeValue( attrID);
  2010. if( url[0] != '#')
  2011. ThrowException( "Unknown reference format in <instance_light> element");
  2012. pNode->mLights.push_back(LightInstance());
  2013. pNode->mLights.back().mLight = url+1;
  2014. }
  2015. }
  2016. else if( IsElement( "instance_camera"))
  2017. {
  2018. // Reference to a camera, name given in 'url' attribute
  2019. int attrID = TestAttribute("url");
  2020. if (-1 == attrID)
  2021. DefaultLogger::get()->warn("Collada: Expected url attribute in <instance_camera> element");
  2022. else
  2023. {
  2024. const char* url = mReader->getAttributeValue( attrID);
  2025. if( url[0] != '#')
  2026. ThrowException( "Unknown reference format in <instance_camera> element");
  2027. pNode->mCameras.push_back(CameraInstance());
  2028. pNode->mCameras.back().mCamera = url+1;
  2029. }
  2030. }
  2031. else
  2032. {
  2033. // skip everything else for the moment
  2034. SkipElement();
  2035. }
  2036. }
  2037. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  2038. break;
  2039. }
  2040. }
  2041. }
  2042. // ------------------------------------------------------------------------------------------------
  2043. // Reads a node transformation entry of the given type and adds it to the given node's transformation list.
  2044. void ColladaParser::ReadNodeTransformation( Node* pNode, TransformType pType)
  2045. {
  2046. std::string tagName = mReader->getNodeName();
  2047. Transform tf;
  2048. tf.mType = pType;
  2049. // read SID
  2050. int indexSID = TestAttribute( "sid");
  2051. if( indexSID >= 0)
  2052. tf.mID = mReader->getAttributeValue( indexSID);
  2053. // how many parameters to read per transformation type
  2054. static const unsigned int sNumParameters[] = { 9, 4, 3, 3, 7, 16 };
  2055. const char* content = GetTextContent();
  2056. // read as many parameters and store in the transformation
  2057. for( unsigned int a = 0; a < sNumParameters[pType]; a++)
  2058. {
  2059. // read a number
  2060. content = fast_atof_move( content, tf.f[a]);
  2061. // skip whitespace after it
  2062. SkipSpacesAndLineEnd( &content);
  2063. }
  2064. // place the transformation at the queue of the node
  2065. pNode->mTransforms.push_back( tf);
  2066. // and consum the closing tag
  2067. TestClosing( tagName.c_str());
  2068. }
  2069. // ------------------------------------------------------------------------------------------------
  2070. // Processes bind_vertex_input and bind elements
  2071. void ColladaParser::ReadMaterialVertexInputBinding( Collada::SemanticMappingTable& tbl)
  2072. {
  2073. while( mReader->read())
  2074. {
  2075. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  2076. if( IsElement( "bind_vertex_input"))
  2077. {
  2078. Collada::InputSemanticMapEntry vn;
  2079. // effect semantic
  2080. int n = GetAttribute("semantic");
  2081. std::string s = mReader->getAttributeValue(n);
  2082. // input semantic
  2083. n = GetAttribute("input_semantic");
  2084. vn.mType = GetTypeForSemantic( mReader->getAttributeValue(n) );
  2085. // index of input set
  2086. n = TestAttribute("input_set");
  2087. if (-1 != n)
  2088. vn.mSet = mReader->getAttributeValueAsInt(n);
  2089. tbl.mMap[s] = vn;
  2090. }
  2091. else if( IsElement( "bind")) {
  2092. DefaultLogger::get()->warn("Collada: Found unsupported <bind> element");
  2093. }
  2094. }
  2095. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
  2096. if( strcmp( mReader->getNodeName(), "instance_material") == 0)
  2097. break;
  2098. }
  2099. }
  2100. }
  2101. // ------------------------------------------------------------------------------------------------
  2102. // Reads a mesh reference in a node and adds it to the node's mesh list
  2103. void ColladaParser::ReadNodeGeometry( Node* pNode)
  2104. {
  2105. // referred mesh is given as an attribute of the <instance_geometry> element
  2106. int attrUrl = GetAttribute( "url");
  2107. const char* url = mReader->getAttributeValue( attrUrl);
  2108. if( url[0] != '#')
  2109. ThrowException( "Unknown reference format");
  2110. Collada::MeshInstance instance;
  2111. instance.mMeshOrController = url+1; // skipping the leading #
  2112. if( !mReader->isEmptyElement())
  2113. {
  2114. // read material associations. Ignore additional elements inbetween
  2115. while( mReader->read())
  2116. {
  2117. if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
  2118. {
  2119. if( IsElement( "instance_material"))
  2120. {
  2121. // read ID of the geometry subgroup and the target material
  2122. int attrGroup = GetAttribute( "symbol");
  2123. std::string group = mReader->getAttributeValue( attrGroup);
  2124. int attrMaterial = GetAttribute( "target");
  2125. const char* urlMat = mReader->getAttributeValue( attrMaterial);
  2126. Collada::SemanticMappingTable s;
  2127. if( urlMat[0] != '#')
  2128. ThrowException( "Unknown reference format");
  2129. s.mMatName = urlMat+1;
  2130. // resolve further material details + THIS UGLY AND NASTY semantic mapping stuff
  2131. if( !mReader->isEmptyElement())
  2132. ReadMaterialVertexInputBinding(s);
  2133. // store the association
  2134. instance.mMaterials[group] = s;
  2135. }
  2136. }
  2137. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  2138. {
  2139. if( strcmp( mReader->getNodeName(), "instance_geometry") == 0
  2140. || strcmp( mReader->getNodeName(), "instance_controller") == 0)
  2141. break;
  2142. }
  2143. }
  2144. }
  2145. // store it
  2146. pNode->mMeshes.push_back( instance);
  2147. }
  2148. // ------------------------------------------------------------------------------------------------
  2149. // Reads the collada scene
  2150. void ColladaParser::ReadScene()
  2151. {
  2152. while( mReader->read())
  2153. {
  2154. if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
  2155. if( IsElement( "instance_visual_scene"))
  2156. {
  2157. // should be the first and only occurence
  2158. if( mRootNode)
  2159. ThrowException( "Invalid scene containing multiple root nodes");
  2160. // read the url of the scene to instance. Should be of format "#some_name"
  2161. int urlIndex = GetAttribute( "url");
  2162. const char* url = mReader->getAttributeValue( urlIndex);
  2163. if( url[0] != '#')
  2164. ThrowException( "Unknown reference format");
  2165. // find the referred scene, skip the leading #
  2166. NodeLibrary::const_iterator sit = mNodeLibrary.find( url+1);
  2167. if( sit == mNodeLibrary.end())
  2168. ThrowException( "Unable to resolve visual_scene reference \"" + std::string(url) + "\".");
  2169. mRootNode = sit->second;
  2170. } else {
  2171. SkipElement();
  2172. }
  2173. }
  2174. else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){
  2175. break;
  2176. }
  2177. }
  2178. }
  2179. // ------------------------------------------------------------------------------------------------
  2180. // Aborts the file reading with an exception
  2181. void ColladaParser::ThrowException( const std::string& pError) const
  2182. {
  2183. throw new ImportErrorException( boost::str( boost::format( "Collada: %s - %s") % mFileName % pError));
  2184. }
  2185. // ------------------------------------------------------------------------------------------------
  2186. // Skips all data until the end node of the current element
  2187. void ColladaParser::SkipElement()
  2188. {
  2189. // nothing to skip if it's an <element />
  2190. if( mReader->isEmptyElement())
  2191. return;
  2192. // reroute
  2193. SkipElement( mReader->getNodeName());
  2194. }
  2195. // ------------------------------------------------------------------------------------------------
  2196. // Skips all data until the end node of the given element
  2197. void ColladaParser::SkipElement( const char* pElement)
  2198. {
  2199. // copy the current node's name because it'a pointer to the reader's internal buffer,
  2200. // which is going to change with the upcoming parsing
  2201. std::string element = pElement;
  2202. while( mReader->read())
  2203. {
  2204. if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  2205. if( mReader->getNodeName() == element)
  2206. break;
  2207. }
  2208. }
  2209. // ------------------------------------------------------------------------------------------------
  2210. // Tests for an opening element of the given name, throws an exception if not found
  2211. void ColladaParser::TestOpening( const char* pName)
  2212. {
  2213. // read element start
  2214. if( !mReader->read())
  2215. ThrowException( boost::str( boost::format( "Unexpected end of file while beginning of \"%s\" element.") % pName));
  2216. // whitespace in front is ok, just read again if found
  2217. if( mReader->getNodeType() == irr::io::EXN_TEXT)
  2218. if( !mReader->read())
  2219. ThrowException( boost::str( boost::format( "Unexpected end of file while reading beginning of \"%s\" element.") % pName));
  2220. if( mReader->getNodeType() != irr::io::EXN_ELEMENT || strcmp( mReader->getNodeName(), pName) != 0)
  2221. ThrowException( boost::str( boost::format( "Expected start of \"%s\" element.") % pName));
  2222. }
  2223. // ------------------------------------------------------------------------------------------------
  2224. // Tests for the closing tag of the given element, throws an exception if not found
  2225. void ColladaParser::TestClosing( const char* pName)
  2226. {
  2227. // read closing tag
  2228. if( !mReader->read())
  2229. ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of \"%s\" element.") % pName));
  2230. // whitespace in front is ok, just read again if found
  2231. if( mReader->getNodeType() == irr::io::EXN_TEXT)
  2232. if( !mReader->read())
  2233. ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of \"%s\" element.") % pName));
  2234. if( mReader->getNodeType() != irr::io::EXN_ELEMENT_END || strcmp( mReader->getNodeName(), pName) != 0)
  2235. ThrowException( boost::str( boost::format( "Expected end of \"%s\" element.") % pName));
  2236. }
  2237. // ------------------------------------------------------------------------------------------------
  2238. // Returns the index of the named attribute or -1 if not found. Does not throw, therefore useful for optional attributes
  2239. int ColladaParser::GetAttribute( const char* pAttr) const
  2240. {
  2241. int index = TestAttribute( pAttr);
  2242. if( index != -1)
  2243. return index;
  2244. // attribute not found -> throw an exception
  2245. ThrowException( boost::str( boost::format( "Expected attribute \"%s\" at element \"%s\".") % pAttr % mReader->getNodeName()));
  2246. return -1;
  2247. }
  2248. // ------------------------------------------------------------------------------------------------
  2249. // Tests the present element for the presence of one attribute, returns its index or throws an exception if not found
  2250. int ColladaParser::TestAttribute( const char* pAttr) const
  2251. {
  2252. for( int a = 0; a < mReader->getAttributeCount(); a++)
  2253. if( strcmp( mReader->getAttributeName( a), pAttr) == 0)
  2254. return a;
  2255. return -1;
  2256. }
  2257. // ------------------------------------------------------------------------------------------------
  2258. // Reads the text contents of an element, throws an exception if not given. Skips leading whitespace.
  2259. const char* ColladaParser::GetTextContent()
  2260. {
  2261. const char* sz = TestTextContent();
  2262. if(!sz) {
  2263. ThrowException( "Invalid contents in element \"n\".");
  2264. }
  2265. return sz;
  2266. }
  2267. // ------------------------------------------------------------------------------------------------
  2268. // Reads the text contents of an element, returns NULL if not given. Skips leading whitespace.
  2269. const char* ColladaParser::TestTextContent()
  2270. {
  2271. // present node should be the beginning of an element
  2272. if( mReader->getNodeType() != irr::io::EXN_ELEMENT || mReader->isEmptyElement())
  2273. ThrowException( "Expected opening element");
  2274. // read contents of the element
  2275. if( !mReader->read())
  2276. ThrowException( "Unexpected end of file while reading n element.");
  2277. if( mReader->getNodeType() != irr::io::EXN_TEXT)
  2278. return NULL;
  2279. // skip leading whitespace
  2280. const char* text = mReader->getNodeData();
  2281. SkipSpacesAndLineEnd( &text);
  2282. return text;
  2283. }
  2284. // ------------------------------------------------------------------------------------------------
  2285. // Calculates the resulting transformation fromm all the given transform steps
  2286. aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector<Transform>& pTransforms) const
  2287. {
  2288. aiMatrix4x4 res;
  2289. for( std::vector<Transform>::const_iterator it = pTransforms.begin(); it != pTransforms.end(); ++it)
  2290. {
  2291. const Transform& tf = *it;
  2292. switch( tf.mType)
  2293. {
  2294. case TF_LOOKAT:
  2295. {
  2296. aiVector3D pos( tf.f[0], tf.f[1], tf.f[2]);
  2297. aiVector3D dstPos( tf.f[3], tf.f[4], tf.f[5]);
  2298. aiVector3D up = aiVector3D( tf.f[6], tf.f[7], tf.f[8]).Normalize();
  2299. aiVector3D dir = aiVector3D( dstPos - pos).Normalize();
  2300. aiVector3D right = (dir ^ up).Normalize();
  2301. res *= aiMatrix4x4(
  2302. right.x, up.x, -dir.x, pos.x,
  2303. right.y, up.y, -dir.y, pos.y,
  2304. right.z, up.z, -dir.z, pos.z,
  2305. 0, 0, 0, 1);
  2306. break;
  2307. }
  2308. case TF_ROTATE:
  2309. {
  2310. aiMatrix4x4 rot;
  2311. float angle = tf.f[3] * float( AI_MATH_PI) / 180.0f;
  2312. aiVector3D axis( tf.f[0], tf.f[1], tf.f[2]);
  2313. aiMatrix4x4::Rotation( angle, axis, rot);
  2314. res *= rot;
  2315. break;
  2316. }
  2317. case TF_TRANSLATE:
  2318. {
  2319. aiMatrix4x4 trans;
  2320. aiMatrix4x4::Translation( aiVector3D( tf.f[0], tf.f[1], tf.f[2]), trans);
  2321. res *= trans;
  2322. break;
  2323. }
  2324. case TF_SCALE:
  2325. {
  2326. 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,
  2327. 0.0f, 0.0f, 0.0f, 1.0f);
  2328. res *= scale;
  2329. break;
  2330. }
  2331. case TF_SKEW:
  2332. // TODO: (thom)
  2333. ai_assert( false);
  2334. break;
  2335. case TF_MATRIX:
  2336. {
  2337. 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],
  2338. tf.f[8], tf.f[9], tf.f[10], tf.f[11], tf.f[12], tf.f[13], tf.f[14], tf.f[15]);
  2339. res *= mat;
  2340. break;
  2341. }
  2342. default:
  2343. assert( false);
  2344. break;
  2345. }
  2346. }
  2347. return res;
  2348. }
  2349. // ------------------------------------------------------------------------------------------------
  2350. // Determines the input data type for the given semantic string
  2351. Collada::InputType ColladaParser::GetTypeForSemantic( const std::string& pSemantic)
  2352. {
  2353. if( pSemantic == "POSITION")
  2354. return IT_Position;
  2355. else if( pSemantic == "TEXCOORD")
  2356. return IT_Texcoord;
  2357. else if( pSemantic == "NORMAL")
  2358. return IT_Normal;
  2359. else if( pSemantic == "COLOR")
  2360. return IT_Color;
  2361. else if( pSemantic == "VERTEX")
  2362. return IT_Vertex;
  2363. else if( pSemantic == "BINORMAL")
  2364. return IT_Bitangent;
  2365. else if( pSemantic == "TANGENT")
  2366. return IT_Tangent;
  2367. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown vertex input type \"%s\". Ignoring.") % pSemantic));
  2368. return IT_Invalid;
  2369. }
  2370. #endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER