ColladaParser.cpp 88 KB

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