ColladaParser.cpp 118 KB

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