ColladaParser.cpp 99 KB

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