ColladaParser.cpp 100 KB

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