ColladaParser.cpp 88 KB

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