ColladaParser.cpp 129 KB

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