ColladaParser.cpp 118 KB

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