ColladaParser.cpp 130 KB

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