ColladaParser.cpp 117 KB

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