ColladaParser.cpp 85 KB

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