ColladaParser.cpp 126 KB

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