ColladaExporter.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2022, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #ifndef ASSIMP_BUILD_NO_EXPORT
  34. #ifndef ASSIMP_BUILD_NO_COLLADA_EXPORTER
  35. #include "ColladaExporter.h"
  36. #include <assimp/Bitmap.h>
  37. #include <assimp/ColladaMetaData.h>
  38. #include <assimp/DefaultIOSystem.h>
  39. #include <assimp/Exceptional.h>
  40. #include <assimp/MathFunctions.h>
  41. #include <assimp/SceneCombiner.h>
  42. #include <assimp/StringUtils.h>
  43. #include <assimp/XMLTools.h>
  44. #include <assimp/commonMetaData.h>
  45. #include <assimp/fast_atof.h>
  46. #include <assimp/scene.h>
  47. #include <assimp/Exporter.hpp>
  48. #include <assimp/IOSystem.hpp>
  49. #include <ctime>
  50. #include <memory>
  51. namespace Assimp {
  52. // ------------------------------------------------------------------------------------------------
  53. // Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp
  54. void ExportSceneCollada(const char *pFile, IOSystem *pIOSystem, const aiScene *pScene, const ExportProperties * /*pProperties*/) {
  55. std::string path = DefaultIOSystem::absolutePath(std::string(pFile));
  56. std::string file = DefaultIOSystem::completeBaseName(std::string(pFile));
  57. // invoke the exporter
  58. ColladaExporter iDoTheExportThing(pScene, pIOSystem, path, file);
  59. if (iDoTheExportThing.mOutput.fail()) {
  60. throw DeadlyExportError("output data creation failed. Most likely the file became too large: " + std::string(pFile));
  61. }
  62. // we're still here - export successfully completed. Write result to the given IOSYstem
  63. std::unique_ptr<IOStream> outfile(pIOSystem->Open(pFile, "wt"));
  64. if (outfile == nullptr) {
  65. throw DeadlyExportError("could not open output .dae file: " + std::string(pFile));
  66. }
  67. // XXX maybe use a small wrapper around IOStream that behaves like std::stringstream in order to avoid the extra copy.
  68. outfile->Write(iDoTheExportThing.mOutput.str().c_str(), static_cast<size_t>(iDoTheExportThing.mOutput.tellp()), 1);
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Encodes a string into a valid XML ID using the xsd:ID schema qualifications.
  72. static const std::string XMLIDEncode(const std::string &name) {
  73. const char XML_ID_CHARS[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-.";
  74. const unsigned int XML_ID_CHARS_COUNT = sizeof(XML_ID_CHARS) / sizeof(char);
  75. if (name.length() == 0) {
  76. return name;
  77. }
  78. std::stringstream idEncoded;
  79. // xsd:ID must start with letter or underscore
  80. if (!((name[0] >= 'A' && name[0] <= 'z') || name[0] == '_')) {
  81. idEncoded << '_';
  82. }
  83. for (std::string::const_iterator it = name.begin(); it != name.end(); ++it) {
  84. // xsd:ID can only contain letters, digits, underscores, hyphens and periods
  85. if (strchr(XML_ID_CHARS, *it) != nullptr) {
  86. idEncoded << *it;
  87. } else {
  88. // Select placeholder character based on invalid character to reduce ID collisions
  89. idEncoded << XML_ID_CHARS[(*it) % XML_ID_CHARS_COUNT];
  90. }
  91. }
  92. return idEncoded.str();
  93. }
  94. // ------------------------------------------------------------------------------------------------
  95. // Helper functions to create unique ids
  96. inline bool IsUniqueId(const std::unordered_set<std::string> &idSet, const std::string &idStr) {
  97. return (idSet.find(idStr) == idSet.end());
  98. }
  99. inline std::string MakeUniqueId(const std::unordered_set<std::string> &idSet, const std::string &idPrefix, const std::string &postfix) {
  100. std::string result(idPrefix + postfix);
  101. if (!IsUniqueId(idSet, result)) {
  102. // Select a number to append
  103. size_t idnum = 1;
  104. do {
  105. result = idPrefix + '_' + ai_to_string(idnum) + postfix;
  106. ++idnum;
  107. } while (!IsUniqueId(idSet, result));
  108. }
  109. return result;
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // Constructor for a specific scene to export
  113. ColladaExporter::ColladaExporter(const aiScene *pScene, IOSystem *pIOSystem, const std::string &path, const std::string &file) :
  114. mIOSystem(pIOSystem),
  115. mPath(path),
  116. mFile(file),
  117. mScene(pScene),
  118. endstr("\n") {
  119. // make sure that all formatting happens using the standard, C locale and not the user's current locale
  120. mOutput.imbue(std::locale("C"));
  121. mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION);
  122. // start writing the file
  123. WriteFile();
  124. }
  125. // ------------------------------------------------------------------------------------------------
  126. // Destructor
  127. ColladaExporter::~ColladaExporter() = default;
  128. // ------------------------------------------------------------------------------------------------
  129. // Starts writing the contents
  130. void ColladaExporter::WriteFile() {
  131. // write the DTD
  132. mOutput << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << endstr;
  133. // COLLADA element start
  134. mOutput << "<COLLADA xmlns=\"http://www.collada.org/2005/11/COLLADASchema\" version=\"1.4.1\">" << endstr;
  135. PushTag();
  136. WriteTextures();
  137. WriteHeader();
  138. // Add node names to the unique id database first so they are most likely to use their names as unique ids
  139. CreateNodeIds(mScene->mRootNode);
  140. WriteCamerasLibrary();
  141. WriteLightsLibrary();
  142. WriteMaterials();
  143. WriteGeometryLibrary();
  144. WriteControllerLibrary();
  145. WriteSceneLibrary();
  146. // customized, Writes the animation library
  147. WriteAnimationsLibrary();
  148. // instantiate the scene(s)
  149. // For Assimp there will only ever be one
  150. mOutput << startstr << "<scene>" << endstr;
  151. PushTag();
  152. mOutput << startstr << "<instance_visual_scene url=\"#" + mSceneId + "\" />" << endstr;
  153. PopTag();
  154. mOutput << startstr << "</scene>" << endstr;
  155. PopTag();
  156. mOutput << "</COLLADA>" << endstr;
  157. }
  158. // ------------------------------------------------------------------------------------------------
  159. // Writes the asset header
  160. void ColladaExporter::WriteHeader() {
  161. static const ai_real epsilon = Math::getEpsilon<ai_real>();
  162. static const aiQuaternion x_rot(aiMatrix3x3(
  163. 0, -1, 0,
  164. 1, 0, 0,
  165. 0, 0, 1));
  166. static const aiQuaternion y_rot(aiMatrix3x3(
  167. 1, 0, 0,
  168. 0, 1, 0,
  169. 0, 0, 1));
  170. static const aiQuaternion z_rot(aiMatrix3x3(
  171. 1, 0, 0,
  172. 0, 0, 1,
  173. 0, -1, 0));
  174. static const unsigned int date_nb_chars = 20;
  175. char date_str[date_nb_chars];
  176. std::time_t date = std::time(nullptr);
  177. std::strftime(date_str, date_nb_chars, "%Y-%m-%dT%H:%M:%S", std::localtime(&date));
  178. aiVector3D scaling;
  179. aiQuaternion rotation;
  180. aiVector3D position;
  181. mScene->mRootNode->mTransformation.Decompose(scaling, rotation, position);
  182. rotation.Normalize();
  183. mAdd_root_node = false;
  184. ai_real scale = 1.0;
  185. if (std::abs(scaling.x - scaling.y) <= epsilon && std::abs(scaling.x - scaling.z) <= epsilon && std::abs(scaling.y - scaling.z) <= epsilon) {
  186. scale = (ai_real)((((double)scaling.x) + ((double)scaling.y) + ((double)scaling.z)) / 3.0);
  187. } else {
  188. mAdd_root_node = true;
  189. }
  190. std::string up_axis = "Y_UP";
  191. if (rotation.Equal(x_rot, epsilon)) {
  192. up_axis = "X_UP";
  193. } else if (rotation.Equal(y_rot, epsilon)) {
  194. up_axis = "Y_UP";
  195. } else if (rotation.Equal(z_rot, epsilon)) {
  196. up_axis = "Z_UP";
  197. } else {
  198. mAdd_root_node = true;
  199. }
  200. if (!position.Equal(aiVector3D(0, 0, 0))) {
  201. mAdd_root_node = true;
  202. }
  203. // Assimp root nodes can have meshes, Collada Scenes cannot
  204. if (mScene->mRootNode->mNumChildren == 0 || mScene->mRootNode->mMeshes != 0) {
  205. mAdd_root_node = true;
  206. }
  207. if (mAdd_root_node) {
  208. up_axis = "Y_UP";
  209. scale = 1.0;
  210. }
  211. mOutput << startstr << "<asset>" << endstr;
  212. PushTag();
  213. mOutput << startstr << "<contributor>" << endstr;
  214. PushTag();
  215. // If no Scene metadata, use root node metadata
  216. aiMetadata *meta = mScene->mMetaData;
  217. if (nullptr == meta) {
  218. meta = mScene->mRootNode->mMetaData;
  219. }
  220. aiString value;
  221. if (!meta || !meta->Get("Author", value)) {
  222. mOutput << startstr << "<author>"
  223. << "Assimp"
  224. << "</author>" << endstr;
  225. } else {
  226. mOutput << startstr << "<author>" << XMLEscape(value.C_Str()) << "</author>" << endstr;
  227. }
  228. if (nullptr == meta || !meta->Get(AI_METADATA_SOURCE_GENERATOR, value)) {
  229. mOutput << startstr << "<authoring_tool>"
  230. << "Assimp Exporter"
  231. << "</authoring_tool>" << endstr;
  232. } else {
  233. mOutput << startstr << "<authoring_tool>" << XMLEscape(value.C_Str()) << "</authoring_tool>" << endstr;
  234. }
  235. if (meta) {
  236. if (meta->Get("Comments", value)) {
  237. mOutput << startstr << "<comments>" << XMLEscape(value.C_Str()) << "</comments>" << endstr;
  238. }
  239. if (meta->Get(AI_METADATA_SOURCE_COPYRIGHT, value)) {
  240. mOutput << startstr << "<copyright>" << XMLEscape(value.C_Str()) << "</copyright>" << endstr;
  241. }
  242. if (meta->Get("SourceData", value)) {
  243. mOutput << startstr << "<source_data>" << XMLEscape(value.C_Str()) << "</source_data>" << endstr;
  244. }
  245. }
  246. PopTag();
  247. mOutput << startstr << "</contributor>" << endstr;
  248. if (nullptr == meta || !meta->Get("Created", value)) {
  249. mOutput << startstr << "<created>" << date_str << "</created>" << endstr;
  250. } else {
  251. mOutput << startstr << "<created>" << XMLEscape(value.C_Str()) << "</created>" << endstr;
  252. }
  253. // Modified date is always the date saved
  254. mOutput << startstr << "<modified>" << date_str << "</modified>" << endstr;
  255. if (meta) {
  256. if (meta->Get("Keywords", value)) {
  257. mOutput << startstr << "<keywords>" << XMLEscape(value.C_Str()) << "</keywords>" << endstr;
  258. }
  259. if (meta->Get("Revision", value)) {
  260. mOutput << startstr << "<revision>" << XMLEscape(value.C_Str()) << "</revision>" << endstr;
  261. }
  262. if (meta->Get("Subject", value)) {
  263. mOutput << startstr << "<subject>" << XMLEscape(value.C_Str()) << "</subject>" << endstr;
  264. }
  265. if (meta->Get("Title", value)) {
  266. mOutput << startstr << "<title>" << XMLEscape(value.C_Str()) << "</title>" << endstr;
  267. }
  268. }
  269. mOutput << startstr << "<unit name=\"meter\" meter=\"" << scale << "\" />" << endstr;
  270. mOutput << startstr << "<up_axis>" << up_axis << "</up_axis>" << endstr;
  271. PopTag();
  272. mOutput << startstr << "</asset>" << endstr;
  273. }
  274. // ------------------------------------------------------------------------------------------------
  275. // Write the embedded textures
  276. void ColladaExporter::WriteTextures() {
  277. static const unsigned int buffer_size = 1024;
  278. char str[buffer_size];
  279. if (mScene->HasTextures()) {
  280. for (unsigned int i = 0; i < mScene->mNumTextures; i++) {
  281. // It would be great to be able to create a directory in portable standard C++, but it's not the case,
  282. // so we just write the textures in the current directory.
  283. aiTexture *texture = mScene->mTextures[i];
  284. if (nullptr == texture) {
  285. continue;
  286. }
  287. ASSIMP_itoa10(str, buffer_size, i + 1);
  288. std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char *)texture->achFormatHint);
  289. std::unique_ptr<IOStream> outfile(mIOSystem->Open(mPath + mIOSystem->getOsSeparator() + name, "wb"));
  290. if (outfile == nullptr) {
  291. throw DeadlyExportError("could not open output texture file: " + mPath + name);
  292. }
  293. if (texture->mHeight == 0) {
  294. outfile->Write((void *)texture->pcData, texture->mWidth, 1);
  295. } else {
  296. Bitmap::Save(texture, outfile.get());
  297. }
  298. outfile->Flush();
  299. textures.insert(std::make_pair(i, name));
  300. }
  301. }
  302. }
  303. // ------------------------------------------------------------------------------------------------
  304. // Write the embedded textures
  305. void ColladaExporter::WriteCamerasLibrary() {
  306. if (mScene->HasCameras()) {
  307. mOutput << startstr << "<library_cameras>" << endstr;
  308. PushTag();
  309. for (size_t a = 0; a < mScene->mNumCameras; ++a)
  310. WriteCamera(a);
  311. PopTag();
  312. mOutput << startstr << "</library_cameras>" << endstr;
  313. }
  314. }
  315. void ColladaExporter::WriteCamera(size_t pIndex) {
  316. const aiCamera *cam = mScene->mCameras[pIndex];
  317. const std::string cameraId = GetObjectUniqueId(AiObjectType::Camera, pIndex);
  318. const std::string cameraName = GetObjectName(AiObjectType::Camera, pIndex);
  319. mOutput << startstr << "<camera id=\"" << cameraId << "\" name=\"" << cameraName << "\" >" << endstr;
  320. PushTag();
  321. mOutput << startstr << "<optics>" << endstr;
  322. PushTag();
  323. mOutput << startstr << "<technique_common>" << endstr;
  324. PushTag();
  325. //assimp doesn't support the import of orthographic cameras! se we write
  326. //always perspective
  327. mOutput << startstr << "<perspective>" << endstr;
  328. PushTag();
  329. mOutput << startstr << "<xfov sid=\"xfov\">" << AI_RAD_TO_DEG(cam->mHorizontalFOV)
  330. << "</xfov>" << endstr;
  331. mOutput << startstr << "<aspect_ratio>"
  332. << cam->mAspect
  333. << "</aspect_ratio>" << endstr;
  334. mOutput << startstr << "<znear sid=\"znear\">"
  335. << cam->mClipPlaneNear
  336. << "</znear>" << endstr;
  337. mOutput << startstr << "<zfar sid=\"zfar\">"
  338. << cam->mClipPlaneFar
  339. << "</zfar>" << endstr;
  340. PopTag();
  341. mOutput << startstr << "</perspective>" << endstr;
  342. PopTag();
  343. mOutput << startstr << "</technique_common>" << endstr;
  344. PopTag();
  345. mOutput << startstr << "</optics>" << endstr;
  346. PopTag();
  347. mOutput << startstr << "</camera>" << endstr;
  348. }
  349. // ------------------------------------------------------------------------------------------------
  350. // Write the embedded textures
  351. void ColladaExporter::WriteLightsLibrary() {
  352. if (mScene->HasLights()) {
  353. mOutput << startstr << "<library_lights>" << endstr;
  354. PushTag();
  355. for (size_t a = 0; a < mScene->mNumLights; ++a)
  356. WriteLight(a);
  357. PopTag();
  358. mOutput << startstr << "</library_lights>" << endstr;
  359. }
  360. }
  361. void ColladaExporter::WriteLight(size_t pIndex) {
  362. const aiLight *light = mScene->mLights[pIndex];
  363. const std::string lightId = GetObjectUniqueId(AiObjectType::Light, pIndex);
  364. const std::string lightName = GetObjectName(AiObjectType::Light, pIndex);
  365. mOutput << startstr << "<light id=\"" << lightId << "\" name=\""
  366. << lightName << "\" >" << endstr;
  367. PushTag();
  368. mOutput << startstr << "<technique_common>" << endstr;
  369. PushTag();
  370. switch (light->mType) {
  371. case aiLightSource_AMBIENT:
  372. WriteAmbienttLight(light);
  373. break;
  374. case aiLightSource_DIRECTIONAL:
  375. WriteDirectionalLight(light);
  376. break;
  377. case aiLightSource_POINT:
  378. WritePointLight(light);
  379. break;
  380. case aiLightSource_SPOT:
  381. WriteSpotLight(light);
  382. break;
  383. case aiLightSource_AREA:
  384. case aiLightSource_UNDEFINED:
  385. case _aiLightSource_Force32Bit:
  386. break;
  387. }
  388. PopTag();
  389. mOutput << startstr << "</technique_common>" << endstr;
  390. PopTag();
  391. mOutput << startstr << "</light>" << endstr;
  392. }
  393. void ColladaExporter::WritePointLight(const aiLight *const light) {
  394. const aiColor3D &color = light->mColorDiffuse;
  395. mOutput << startstr << "<point>" << endstr;
  396. PushTag();
  397. mOutput << startstr << "<color sid=\"color\">"
  398. << color.r << " " << color.g << " " << color.b
  399. << "</color>" << endstr;
  400. mOutput << startstr << "<constant_attenuation>"
  401. << light->mAttenuationConstant
  402. << "</constant_attenuation>" << endstr;
  403. mOutput << startstr << "<linear_attenuation>"
  404. << light->mAttenuationLinear
  405. << "</linear_attenuation>" << endstr;
  406. mOutput << startstr << "<quadratic_attenuation>"
  407. << light->mAttenuationQuadratic
  408. << "</quadratic_attenuation>" << endstr;
  409. PopTag();
  410. mOutput << startstr << "</point>" << endstr;
  411. }
  412. void ColladaExporter::WriteDirectionalLight(const aiLight *const light) {
  413. const aiColor3D &color = light->mColorDiffuse;
  414. mOutput << startstr << "<directional>" << endstr;
  415. PushTag();
  416. mOutput << startstr << "<color sid=\"color\">"
  417. << color.r << " " << color.g << " " << color.b
  418. << "</color>" << endstr;
  419. PopTag();
  420. mOutput << startstr << "</directional>" << endstr;
  421. }
  422. void ColladaExporter::WriteSpotLight(const aiLight *const light) {
  423. const aiColor3D &color = light->mColorDiffuse;
  424. mOutput << startstr << "<spot>" << endstr;
  425. PushTag();
  426. mOutput << startstr << "<color sid=\"color\">"
  427. << color.r << " " << color.g << " " << color.b
  428. << "</color>" << endstr;
  429. mOutput << startstr << "<constant_attenuation>"
  430. << light->mAttenuationConstant
  431. << "</constant_attenuation>" << endstr;
  432. mOutput << startstr << "<linear_attenuation>"
  433. << light->mAttenuationLinear
  434. << "</linear_attenuation>" << endstr;
  435. mOutput << startstr << "<quadratic_attenuation>"
  436. << light->mAttenuationQuadratic
  437. << "</quadratic_attenuation>" << endstr;
  438. /*
  439. out->mAngleOuterCone = AI_DEG_TO_RAD (std::acos(std::pow(0.1f,1.f/srcLight->mFalloffExponent))+
  440. srcLight->mFalloffAngle);
  441. */
  442. const ai_real fallOffAngle = AI_RAD_TO_DEG(light->mAngleInnerCone);
  443. mOutput << startstr << "<falloff_angle sid=\"fall_off_angle\">"
  444. << fallOffAngle
  445. << "</falloff_angle>" << endstr;
  446. double temp = light->mAngleOuterCone - light->mAngleInnerCone;
  447. temp = std::cos(temp);
  448. temp = std::log(temp) / std::log(0.1);
  449. temp = 1 / temp;
  450. mOutput << startstr << "<falloff_exponent sid=\"fall_off_exponent\">"
  451. << temp
  452. << "</falloff_exponent>" << endstr;
  453. PopTag();
  454. mOutput << startstr << "</spot>" << endstr;
  455. }
  456. void ColladaExporter::WriteAmbienttLight(const aiLight *const light) {
  457. const aiColor3D &color = light->mColorAmbient;
  458. mOutput << startstr << "<ambient>" << endstr;
  459. PushTag();
  460. mOutput << startstr << "<color sid=\"color\">"
  461. << color.r << " " << color.g << " " << color.b
  462. << "</color>" << endstr;
  463. PopTag();
  464. mOutput << startstr << "</ambient>" << endstr;
  465. }
  466. // ------------------------------------------------------------------------------------------------
  467. // Reads a single surface entry from the given material keys
  468. bool ColladaExporter::ReadMaterialSurface(Surface &poSurface, const aiMaterial &pSrcMat, aiTextureType pTexture, const char *pKey, size_t pType, size_t pIndex) {
  469. if (pSrcMat.GetTextureCount(pTexture) > 0) {
  470. aiString texfile;
  471. unsigned int uvChannel = 0;
  472. pSrcMat.GetTexture(pTexture, 0, &texfile, nullptr, &uvChannel);
  473. std::string index_str(texfile.C_Str());
  474. if (index_str.size() != 0 && index_str[0] == '*') {
  475. unsigned int index;
  476. index_str = index_str.substr(1, std::string::npos);
  477. try {
  478. index = (unsigned int)strtoul10_64<DeadlyExportError>(index_str.c_str());
  479. } catch (std::exception &error) {
  480. throw DeadlyExportError(error.what());
  481. }
  482. std::map<unsigned int, std::string>::const_iterator name = textures.find(index);
  483. if (name != textures.end()) {
  484. poSurface.texture = name->second;
  485. } else {
  486. throw DeadlyExportError("could not find embedded texture at index " + index_str);
  487. }
  488. } else {
  489. poSurface.texture = texfile.C_Str();
  490. }
  491. poSurface.channel = uvChannel;
  492. poSurface.exist = true;
  493. } else {
  494. if (pKey)
  495. poSurface.exist = pSrcMat.Get(pKey, static_cast<unsigned int>(pType), static_cast<unsigned int>(pIndex), poSurface.color) == aiReturn_SUCCESS;
  496. }
  497. return poSurface.exist;
  498. }
  499. // ------------------------------------------------------------------------------------------------
  500. // Reimplementation of isalnum(,C locale), because AppVeyor does not see standard version.
  501. static bool isalnum_C(char c) {
  502. return (nullptr != strchr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", c));
  503. }
  504. // ------------------------------------------------------------------------------------------------
  505. // Writes an image entry for the given surface
  506. void ColladaExporter::WriteImageEntry(const Surface &pSurface, const std::string &imageId) {
  507. if (!pSurface.texture.empty()) {
  508. mOutput << startstr << "<image id=\"" << imageId << "\">" << endstr;
  509. PushTag();
  510. mOutput << startstr << "<init_from>";
  511. // URL encode image file name first, then XML encode on top
  512. std::stringstream imageUrlEncoded;
  513. for (std::string::const_iterator it = pSurface.texture.begin(); it != pSurface.texture.end(); ++it) {
  514. if (isalnum_C((unsigned char)*it) || *it == ':' || *it == '_' || *it == '-' || *it == '.' || *it == '/' || *it == '\\')
  515. imageUrlEncoded << *it;
  516. else
  517. imageUrlEncoded << '%' << std::hex << size_t((unsigned char)*it) << std::dec;
  518. }
  519. mOutput << XMLEscape(imageUrlEncoded.str());
  520. mOutput << "</init_from>" << endstr;
  521. PopTag();
  522. mOutput << startstr << "</image>" << endstr;
  523. }
  524. }
  525. // ------------------------------------------------------------------------------------------------
  526. // Writes a color-or-texture entry into an effect definition
  527. void ColladaExporter::WriteTextureColorEntry(const Surface &pSurface, const std::string &pTypeName, const std::string &imageId) {
  528. if (pSurface.exist) {
  529. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  530. PushTag();
  531. if (pSurface.texture.empty()) {
  532. mOutput << startstr << "<color sid=\"" << pTypeName << "\">" << pSurface.color.r << " " << pSurface.color.g << " " << pSurface.color.b << " " << pSurface.color.a << "</color>" << endstr;
  533. } else {
  534. mOutput << startstr << "<texture texture=\"" << imageId << "\" texcoord=\"CHANNEL" << pSurface.channel << "\" />" << endstr;
  535. }
  536. PopTag();
  537. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  538. }
  539. }
  540. // ------------------------------------------------------------------------------------------------
  541. // Writes the two parameters necessary for referencing a texture in an effect entry
  542. void ColladaExporter::WriteTextureParamEntry(const Surface &pSurface, const std::string &pTypeName, const std::string &materialId) {
  543. // if surface is a texture, write out the sampler and the surface parameters necessary to reference the texture
  544. if (!pSurface.texture.empty()) {
  545. mOutput << startstr << "<newparam sid=\"" << materialId << "-" << pTypeName << "-surface\">" << endstr;
  546. PushTag();
  547. mOutput << startstr << "<surface type=\"2D\">" << endstr;
  548. PushTag();
  549. mOutput << startstr << "<init_from>" << materialId << "-" << pTypeName << "-image</init_from>" << endstr;
  550. PopTag();
  551. mOutput << startstr << "</surface>" << endstr;
  552. PopTag();
  553. mOutput << startstr << "</newparam>" << endstr;
  554. mOutput << startstr << "<newparam sid=\"" << materialId << "-" << pTypeName << "-sampler\">" << endstr;
  555. PushTag();
  556. mOutput << startstr << "<sampler2D>" << endstr;
  557. PushTag();
  558. mOutput << startstr << "<source>" << materialId << "-" << pTypeName << "-surface</source>" << endstr;
  559. PopTag();
  560. mOutput << startstr << "</sampler2D>" << endstr;
  561. PopTag();
  562. mOutput << startstr << "</newparam>" << endstr;
  563. }
  564. }
  565. // ------------------------------------------------------------------------------------------------
  566. // Writes a scalar property
  567. void ColladaExporter::WriteFloatEntry(const Property &pProperty, const std::string &pTypeName) {
  568. if (pProperty.exist) {
  569. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  570. PushTag();
  571. mOutput << startstr << "<float sid=\"" << pTypeName << "\">" << pProperty.value << "</float>" << endstr;
  572. PopTag();
  573. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  574. }
  575. }
  576. // ------------------------------------------------------------------------------------------------
  577. // Writes the material setup
  578. void ColladaExporter::WriteMaterials() {
  579. std::vector<Material> materials;
  580. materials.resize(mScene->mNumMaterials);
  581. /// collect all materials from the scene
  582. size_t numTextures = 0;
  583. for (size_t a = 0; a < mScene->mNumMaterials; ++a) {
  584. Material &material = materials[a];
  585. material.id = GetObjectUniqueId(AiObjectType::Material, a);
  586. material.name = GetObjectName(AiObjectType::Material, a);
  587. const aiMaterial &mat = *(mScene->mMaterials[a]);
  588. aiShadingMode shading = aiShadingMode_Flat;
  589. material.shading_model = "phong";
  590. if (mat.Get(AI_MATKEY_SHADING_MODEL, shading) == aiReturn_SUCCESS) {
  591. if (shading == aiShadingMode_Phong) {
  592. material.shading_model = "phong";
  593. } else if (shading == aiShadingMode_Blinn) {
  594. material.shading_model = "blinn";
  595. } else if (shading == aiShadingMode_NoShading) {
  596. material.shading_model = "constant";
  597. } else if (shading == aiShadingMode_Gouraud) {
  598. material.shading_model = "lambert";
  599. }
  600. }
  601. if (ReadMaterialSurface(material.ambient, mat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT))
  602. ++numTextures;
  603. if (ReadMaterialSurface(material.diffuse, mat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE))
  604. ++numTextures;
  605. if (ReadMaterialSurface(material.specular, mat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR))
  606. ++numTextures;
  607. if (ReadMaterialSurface(material.emissive, mat, aiTextureType_EMISSIVE, AI_MATKEY_COLOR_EMISSIVE))
  608. ++numTextures;
  609. if (ReadMaterialSurface(material.reflective, mat, aiTextureType_REFLECTION, AI_MATKEY_COLOR_REFLECTIVE))
  610. ++numTextures;
  611. if (ReadMaterialSurface(material.transparent, mat, aiTextureType_OPACITY, AI_MATKEY_COLOR_TRANSPARENT))
  612. ++numTextures;
  613. if (ReadMaterialSurface(material.normal, mat, aiTextureType_NORMALS, nullptr, 0, 0))
  614. ++numTextures;
  615. material.shininess.exist = mat.Get(AI_MATKEY_SHININESS, material.shininess.value) == aiReturn_SUCCESS;
  616. material.transparency.exist = mat.Get(AI_MATKEY_OPACITY, material.transparency.value) == aiReturn_SUCCESS;
  617. material.index_refraction.exist = mat.Get(AI_MATKEY_REFRACTI, material.index_refraction.value) == aiReturn_SUCCESS;
  618. }
  619. // output textures if present
  620. if (numTextures > 0) {
  621. mOutput << startstr << "<library_images>" << endstr;
  622. PushTag();
  623. for (const Material &mat : materials) {
  624. WriteImageEntry(mat.ambient, mat.id + "-ambient-image");
  625. WriteImageEntry(mat.diffuse, mat.id + "-diffuse-image");
  626. WriteImageEntry(mat.specular, mat.id + "-specular-image");
  627. WriteImageEntry(mat.emissive, mat.id + "-emission-image");
  628. WriteImageEntry(mat.reflective, mat.id + "-reflective-image");
  629. WriteImageEntry(mat.transparent, mat.id + "-transparent-image");
  630. WriteImageEntry(mat.normal, mat.id + "-normal-image");
  631. }
  632. PopTag();
  633. mOutput << startstr << "</library_images>" << endstr;
  634. }
  635. // output effects - those are the actual carriers of information
  636. if (!materials.empty()) {
  637. mOutput << startstr << "<library_effects>" << endstr;
  638. PushTag();
  639. for (const Material &mat : materials) {
  640. // this is so ridiculous it must be right
  641. mOutput << startstr << "<effect id=\"" << mat.id << "-fx\" name=\"" << mat.name << "\">" << endstr;
  642. PushTag();
  643. mOutput << startstr << "<profile_COMMON>" << endstr;
  644. PushTag();
  645. // write sampler- and surface params for the texture entries
  646. WriteTextureParamEntry(mat.emissive, "emission", mat.id);
  647. WriteTextureParamEntry(mat.ambient, "ambient", mat.id);
  648. WriteTextureParamEntry(mat.diffuse, "diffuse", mat.id);
  649. WriteTextureParamEntry(mat.specular, "specular", mat.id);
  650. WriteTextureParamEntry(mat.reflective, "reflective", mat.id);
  651. WriteTextureParamEntry(mat.transparent, "transparent", mat.id);
  652. WriteTextureParamEntry(mat.normal, "normal", mat.id);
  653. mOutput << startstr << "<technique sid=\"standard\">" << endstr;
  654. PushTag();
  655. mOutput << startstr << "<" << mat.shading_model << ">" << endstr;
  656. PushTag();
  657. WriteTextureColorEntry(mat.emissive, "emission", mat.id + "-emission-sampler");
  658. WriteTextureColorEntry(mat.ambient, "ambient", mat.id + "-ambient-sampler");
  659. WriteTextureColorEntry(mat.diffuse, "diffuse", mat.id + "-diffuse-sampler");
  660. WriteTextureColorEntry(mat.specular, "specular", mat.id + "-specular-sampler");
  661. WriteFloatEntry(mat.shininess, "shininess");
  662. WriteTextureColorEntry(mat.reflective, "reflective", mat.id + "-reflective-sampler");
  663. WriteTextureColorEntry(mat.transparent, "transparent", mat.id + "-transparent-sampler");
  664. WriteFloatEntry(mat.transparency, "transparency");
  665. WriteFloatEntry(mat.index_refraction, "index_of_refraction");
  666. if (!mat.normal.texture.empty()) {
  667. WriteTextureColorEntry(mat.normal, "bump", mat.id + "-normal-sampler");
  668. }
  669. PopTag();
  670. mOutput << startstr << "</" << mat.shading_model << ">" << endstr;
  671. PopTag();
  672. mOutput << startstr << "</technique>" << endstr;
  673. PopTag();
  674. mOutput << startstr << "</profile_COMMON>" << endstr;
  675. PopTag();
  676. mOutput << startstr << "</effect>" << endstr;
  677. }
  678. PopTag();
  679. mOutput << startstr << "</library_effects>" << endstr;
  680. // write materials - they're just effect references
  681. mOutput << startstr << "<library_materials>" << endstr;
  682. PushTag();
  683. for (std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it) {
  684. const Material &mat = *it;
  685. mOutput << startstr << "<material id=\"" << mat.id << "\" name=\"" << mat.name << "\">" << endstr;
  686. PushTag();
  687. mOutput << startstr << "<instance_effect url=\"#" << mat.id << "-fx\"/>" << endstr;
  688. PopTag();
  689. mOutput << startstr << "</material>" << endstr;
  690. }
  691. PopTag();
  692. mOutput << startstr << "</library_materials>" << endstr;
  693. }
  694. }
  695. // ------------------------------------------------------------------------------------------------
  696. // Writes the controller library
  697. void ColladaExporter::WriteControllerLibrary() {
  698. mOutput << startstr << "<library_controllers>" << endstr;
  699. PushTag();
  700. for (size_t a = 0; a < mScene->mNumMeshes; ++a) {
  701. WriteController(a);
  702. }
  703. PopTag();
  704. mOutput << startstr << "</library_controllers>" << endstr;
  705. }
  706. // ------------------------------------------------------------------------------------------------
  707. // Writes a skin controller of the given mesh
  708. void ColladaExporter::WriteController(size_t pIndex) {
  709. const aiMesh *mesh = mScene->mMeshes[pIndex];
  710. // Is there a skin controller?
  711. if (mesh->mNumBones == 0 || mesh->mNumFaces == 0 || mesh->mNumVertices == 0)
  712. return;
  713. const std::string idstr = GetObjectUniqueId(AiObjectType::Mesh, pIndex);
  714. const std::string namestr = GetObjectName(AiObjectType::Mesh, pIndex);
  715. mOutput << startstr << "<controller id=\"" << idstr << "-skin\" ";
  716. mOutput << "name=\"skinCluster" << pIndex << "\">" << endstr;
  717. PushTag();
  718. mOutput << startstr << "<skin source=\"#" << idstr << "\">" << endstr;
  719. PushTag();
  720. // bind pose matrix
  721. mOutput << startstr << "<bind_shape_matrix>" << endstr;
  722. PushTag();
  723. // I think it is identity in general cases.
  724. aiMatrix4x4 mat;
  725. mOutput << startstr << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << endstr;
  726. mOutput << startstr << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << endstr;
  727. mOutput << startstr << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << endstr;
  728. mOutput << startstr << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4 << endstr;
  729. PopTag();
  730. mOutput << startstr << "</bind_shape_matrix>" << endstr;
  731. mOutput << startstr << "<source id=\"" << idstr << "-skin-joints\" name=\"" << namestr << "-skin-joints\">" << endstr;
  732. PushTag();
  733. mOutput << startstr << "<Name_array id=\"" << idstr << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\">";
  734. for (size_t i = 0; i < mesh->mNumBones; ++i)
  735. mOutput << GetBoneUniqueId(mesh->mBones[i]) << ' ';
  736. mOutput << "</Name_array>" << endstr;
  737. mOutput << startstr << "<technique_common>" << endstr;
  738. PushTag();
  739. mOutput << startstr << "<accessor source=\"#" << idstr << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\" stride=\"" << 1 << "\">" << endstr;
  740. PushTag();
  741. mOutput << startstr << "<param name=\"JOINT\" type=\"Name\"></param>" << endstr;
  742. PopTag();
  743. mOutput << startstr << "</accessor>" << endstr;
  744. PopTag();
  745. mOutput << startstr << "</technique_common>" << endstr;
  746. PopTag();
  747. mOutput << startstr << "</source>" << endstr;
  748. std::vector<ai_real> bind_poses;
  749. bind_poses.reserve(mesh->mNumBones * 16);
  750. for (unsigned int i = 0; i < mesh->mNumBones; ++i)
  751. for (unsigned int j = 0; j < 4; ++j)
  752. bind_poses.insert(bind_poses.end(), mesh->mBones[i]->mOffsetMatrix[j], mesh->mBones[i]->mOffsetMatrix[j] + 4);
  753. WriteFloatArray(idstr + "-skin-bind_poses", FloatType_Mat4x4, (const ai_real *)bind_poses.data(), bind_poses.size() / 16);
  754. bind_poses.clear();
  755. std::vector<ai_real> skin_weights;
  756. skin_weights.reserve(mesh->mNumVertices * mesh->mNumBones);
  757. for (size_t i = 0; i < mesh->mNumBones; ++i)
  758. for (size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  759. skin_weights.push_back(mesh->mBones[i]->mWeights[j].mWeight);
  760. WriteFloatArray(idstr + "-skin-weights", FloatType_Weight, (const ai_real *)skin_weights.data(), skin_weights.size());
  761. skin_weights.clear();
  762. mOutput << startstr << "<joints>" << endstr;
  763. PushTag();
  764. mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstr << "-skin-joints\"></input>" << endstr;
  765. mOutput << startstr << "<input semantic=\"INV_BIND_MATRIX\" source=\"#" << idstr << "-skin-bind_poses\"></input>" << endstr;
  766. PopTag();
  767. mOutput << startstr << "</joints>" << endstr;
  768. mOutput << startstr << "<vertex_weights count=\"" << mesh->mNumVertices << "\">" << endstr;
  769. PushTag();
  770. mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstr << "-skin-joints\" offset=\"0\"></input>" << endstr;
  771. mOutput << startstr << "<input semantic=\"WEIGHT\" source=\"#" << idstr << "-skin-weights\" offset=\"1\"></input>" << endstr;
  772. mOutput << startstr << "<vcount>";
  773. std::vector<ai_uint> num_influences(mesh->mNumVertices, (ai_uint)0);
  774. for (size_t i = 0; i < mesh->mNumBones; ++i)
  775. for (size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  776. ++num_influences[mesh->mBones[i]->mWeights[j].mVertexId];
  777. for (size_t i = 0; i < mesh->mNumVertices; ++i)
  778. mOutput << num_influences[i] << " ";
  779. mOutput << "</vcount>" << endstr;
  780. mOutput << startstr << "<v>";
  781. ai_uint joint_weight_indices_length = 0;
  782. std::vector<ai_uint> accum_influences;
  783. accum_influences.reserve(num_influences.size());
  784. for (size_t i = 0; i < num_influences.size(); ++i) {
  785. accum_influences.push_back(joint_weight_indices_length);
  786. joint_weight_indices_length += num_influences[i];
  787. }
  788. ai_uint weight_index = 0;
  789. std::vector<ai_int> joint_weight_indices(2 * joint_weight_indices_length, (ai_int)-1);
  790. for (unsigned int i = 0; i < mesh->mNumBones; ++i)
  791. for (unsigned j = 0; j < mesh->mBones[i]->mNumWeights; ++j) {
  792. unsigned int vId = mesh->mBones[i]->mWeights[j].mVertexId;
  793. for (ai_uint k = 0; k < num_influences[vId]; ++k) {
  794. if (joint_weight_indices[2 * (accum_influences[vId] + k)] == -1) {
  795. joint_weight_indices[2 * (accum_influences[vId] + k)] = i;
  796. joint_weight_indices[2 * (accum_influences[vId] + k) + 1] = weight_index;
  797. break;
  798. }
  799. }
  800. ++weight_index;
  801. }
  802. for (size_t i = 0; i < joint_weight_indices.size(); ++i)
  803. mOutput << joint_weight_indices[i] << " ";
  804. num_influences.clear();
  805. accum_influences.clear();
  806. joint_weight_indices.clear();
  807. mOutput << "</v>" << endstr;
  808. PopTag();
  809. mOutput << startstr << "</vertex_weights>" << endstr;
  810. PopTag();
  811. mOutput << startstr << "</skin>" << endstr;
  812. PopTag();
  813. mOutput << startstr << "</controller>" << endstr;
  814. }
  815. // ------------------------------------------------------------------------------------------------
  816. // Writes the geometry library
  817. void ColladaExporter::WriteGeometryLibrary() {
  818. mOutput << startstr << "<library_geometries>" << endstr;
  819. PushTag();
  820. for (size_t a = 0; a < mScene->mNumMeshes; ++a)
  821. WriteGeometry(a);
  822. PopTag();
  823. mOutput << startstr << "</library_geometries>" << endstr;
  824. }
  825. // ------------------------------------------------------------------------------------------------
  826. // Writes the given mesh
  827. void ColladaExporter::WriteGeometry(size_t pIndex) {
  828. const aiMesh *mesh = mScene->mMeshes[pIndex];
  829. const std::string geometryId = GetObjectUniqueId(AiObjectType::Mesh, pIndex);
  830. const std::string geometryName = GetObjectName(AiObjectType::Mesh, pIndex);
  831. if (mesh->mNumFaces == 0 || mesh->mNumVertices == 0)
  832. return;
  833. // opening tag
  834. mOutput << startstr << "<geometry id=\"" << geometryId << "\" name=\"" << geometryName << "\" >" << endstr;
  835. PushTag();
  836. mOutput << startstr << "<mesh>" << endstr;
  837. PushTag();
  838. // Positions
  839. WriteFloatArray(geometryId + "-positions", FloatType_Vector, (ai_real *)mesh->mVertices, mesh->mNumVertices);
  840. // Normals, if any
  841. if (mesh->HasNormals())
  842. WriteFloatArray(geometryId + "-normals", FloatType_Vector, (ai_real *)mesh->mNormals, mesh->mNumVertices);
  843. // texture coords
  844. for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
  845. if (mesh->HasTextureCoords(static_cast<unsigned int>(a))) {
  846. WriteFloatArray(geometryId + "-tex" + ai_to_string(a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2,
  847. (ai_real *)mesh->mTextureCoords[a], mesh->mNumVertices);
  848. }
  849. }
  850. // vertex colors
  851. for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
  852. if (mesh->HasVertexColors(static_cast<unsigned int>(a)))
  853. WriteFloatArray(geometryId + "-color" + ai_to_string(a), FloatType_Color, (ai_real *)mesh->mColors[a], mesh->mNumVertices);
  854. }
  855. // assemble vertex structure
  856. // Only write input for POSITION since we will write other as shared inputs in polygon definition
  857. mOutput << startstr << "<vertices id=\"" << geometryId << "-vertices"
  858. << "\">" << endstr;
  859. PushTag();
  860. mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << geometryId << "-positions\" />" << endstr;
  861. PopTag();
  862. mOutput << startstr << "</vertices>" << endstr;
  863. // count the number of lines, triangles and polygon meshes
  864. int countLines = 0;
  865. int countPoly = 0;
  866. for (size_t a = 0; a < mesh->mNumFaces; ++a) {
  867. if (mesh->mFaces[a].mNumIndices == 2)
  868. countLines++;
  869. else if (mesh->mFaces[a].mNumIndices >= 3)
  870. countPoly++;
  871. }
  872. // lines
  873. if (countLines) {
  874. mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr;
  875. PushTag();
  876. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << geometryId << "-vertices\" />" << endstr;
  877. if (mesh->HasNormals())
  878. mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << geometryId << "-normals\" />" << endstr;
  879. for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
  880. if (mesh->HasTextureCoords(static_cast<unsigned int>(a)))
  881. mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << geometryId << "-tex" << a << "\" "
  882. << "set=\"" << a << "\""
  883. << " />" << endstr;
  884. }
  885. for (size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a) {
  886. if (mesh->HasVertexColors(static_cast<unsigned int>(a)))
  887. mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << geometryId << "-color" << a << "\" "
  888. << "set=\"" << a << "\""
  889. << " />" << endstr;
  890. }
  891. mOutput << startstr << "<p>";
  892. for (size_t a = 0; a < mesh->mNumFaces; ++a) {
  893. const aiFace &face = mesh->mFaces[a];
  894. if (face.mNumIndices != 2) continue;
  895. for (size_t b = 0; b < face.mNumIndices; ++b)
  896. mOutput << face.mIndices[b] << " ";
  897. }
  898. mOutput << "</p>" << endstr;
  899. PopTag();
  900. mOutput << startstr << "</lines>" << endstr;
  901. }
  902. // triangle - don't use it, because compatibility problems
  903. // polygons
  904. if (countPoly) {
  905. mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr;
  906. PushTag();
  907. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << geometryId << "-vertices\" />" << endstr;
  908. if (mesh->HasNormals())
  909. mOutput << startstr << "<input offset=\"0\" semantic=\"NORMAL\" source=\"#" << geometryId << "-normals\" />" << endstr;
  910. for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
  911. if (mesh->HasTextureCoords(static_cast<unsigned int>(a)))
  912. mOutput << startstr << "<input offset=\"0\" semantic=\"TEXCOORD\" source=\"#" << geometryId << "-tex" << a << "\" "
  913. << "set=\"" << a << "\""
  914. << " />" << endstr;
  915. }
  916. for (size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a) {
  917. if (mesh->HasVertexColors(static_cast<unsigned int>(a)))
  918. mOutput << startstr << "<input offset=\"0\" semantic=\"COLOR\" source=\"#" << geometryId << "-color" << a << "\" "
  919. << "set=\"" << a << "\""
  920. << " />" << endstr;
  921. }
  922. mOutput << startstr << "<vcount>";
  923. for (size_t a = 0; a < mesh->mNumFaces; ++a) {
  924. if (mesh->mFaces[a].mNumIndices < 3) continue;
  925. mOutput << mesh->mFaces[a].mNumIndices << " ";
  926. }
  927. mOutput << "</vcount>" << endstr;
  928. mOutput << startstr << "<p>";
  929. for (size_t a = 0; a < mesh->mNumFaces; ++a) {
  930. const aiFace &face = mesh->mFaces[a];
  931. if (face.mNumIndices < 3) continue;
  932. for (size_t b = 0; b < face.mNumIndices; ++b)
  933. mOutput << face.mIndices[b] << " ";
  934. }
  935. mOutput << "</p>" << endstr;
  936. PopTag();
  937. mOutput << startstr << "</polylist>" << endstr;
  938. }
  939. // closing tags
  940. PopTag();
  941. mOutput << startstr << "</mesh>" << endstr;
  942. PopTag();
  943. mOutput << startstr << "</geometry>" << endstr;
  944. }
  945. // ------------------------------------------------------------------------------------------------
  946. // Writes a float array of the given type
  947. void ColladaExporter::WriteFloatArray(const std::string &pIdString, FloatDataType pType, const ai_real *pData, size_t pElementCount) {
  948. size_t floatsPerElement = 0;
  949. switch (pType) {
  950. case FloatType_Vector: floatsPerElement = 3; break;
  951. case FloatType_TexCoord2: floatsPerElement = 2; break;
  952. case FloatType_TexCoord3: floatsPerElement = 3; break;
  953. case FloatType_Color: floatsPerElement = 3; break;
  954. case FloatType_Mat4x4: floatsPerElement = 16; break;
  955. case FloatType_Weight: floatsPerElement = 1; break;
  956. case FloatType_Time: floatsPerElement = 1; break;
  957. default:
  958. return;
  959. }
  960. std::string arrayId = XMLIDEncode(pIdString) + "-array";
  961. mOutput << startstr << "<source id=\"" << XMLIDEncode(pIdString) << "\" name=\"" << XMLEscape(pIdString) << "\">" << endstr;
  962. PushTag();
  963. // source array
  964. mOutput << startstr << "<float_array id=\"" << arrayId << "\" count=\"" << pElementCount * floatsPerElement << "\"> ";
  965. PushTag();
  966. if (pType == FloatType_TexCoord2) {
  967. for (size_t a = 0; a < pElementCount; ++a) {
  968. mOutput << pData[a * 3 + 0] << " ";
  969. mOutput << pData[a * 3 + 1] << " ";
  970. }
  971. } else if (pType == FloatType_Color) {
  972. for (size_t a = 0; a < pElementCount; ++a) {
  973. mOutput << pData[a * 4 + 0] << " ";
  974. mOutput << pData[a * 4 + 1] << " ";
  975. mOutput << pData[a * 4 + 2] << " ";
  976. }
  977. } else {
  978. for (size_t a = 0; a < pElementCount * floatsPerElement; ++a)
  979. mOutput << pData[a] << " ";
  980. }
  981. mOutput << "</float_array>" << endstr;
  982. PopTag();
  983. // the usual Collada fun. Let's bloat it even more!
  984. mOutput << startstr << "<technique_common>" << endstr;
  985. PushTag();
  986. mOutput << startstr << "<accessor count=\"" << pElementCount << "\" offset=\"0\" source=\"#" << arrayId << "\" stride=\"" << floatsPerElement << "\">" << endstr;
  987. PushTag();
  988. switch (pType) {
  989. case FloatType_Vector:
  990. mOutput << startstr << "<param name=\"X\" type=\"float\" />" << endstr;
  991. mOutput << startstr << "<param name=\"Y\" type=\"float\" />" << endstr;
  992. mOutput << startstr << "<param name=\"Z\" type=\"float\" />" << endstr;
  993. break;
  994. case FloatType_TexCoord2:
  995. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  996. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  997. break;
  998. case FloatType_TexCoord3:
  999. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  1000. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  1001. mOutput << startstr << "<param name=\"P\" type=\"float\" />" << endstr;
  1002. break;
  1003. case FloatType_Color:
  1004. mOutput << startstr << "<param name=\"R\" type=\"float\" />" << endstr;
  1005. mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr;
  1006. mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr;
  1007. break;
  1008. case FloatType_Mat4x4:
  1009. mOutput << startstr << "<param name=\"TRANSFORM\" type=\"float4x4\" />" << endstr;
  1010. break;
  1011. case FloatType_Weight:
  1012. mOutput << startstr << "<param name=\"WEIGHT\" type=\"float\" />" << endstr;
  1013. break;
  1014. // customized, add animation related
  1015. case FloatType_Time:
  1016. mOutput << startstr << "<param name=\"TIME\" type=\"float\" />" << endstr;
  1017. break;
  1018. }
  1019. PopTag();
  1020. mOutput << startstr << "</accessor>" << endstr;
  1021. PopTag();
  1022. mOutput << startstr << "</technique_common>" << endstr;
  1023. PopTag();
  1024. mOutput << startstr << "</source>" << endstr;
  1025. }
  1026. // ------------------------------------------------------------------------------------------------
  1027. // Writes the scene library
  1028. void ColladaExporter::WriteSceneLibrary() {
  1029. // Determine if we are using the aiScene root or our own
  1030. std::string sceneName("Scene");
  1031. if (mAdd_root_node) {
  1032. mSceneId = MakeUniqueId(mUniqueIds, sceneName, std::string());
  1033. mUniqueIds.insert(mSceneId);
  1034. } else {
  1035. mSceneId = GetNodeUniqueId(mScene->mRootNode);
  1036. sceneName = GetNodeName(mScene->mRootNode);
  1037. }
  1038. mOutput << startstr << "<library_visual_scenes>" << endstr;
  1039. PushTag();
  1040. mOutput << startstr << "<visual_scene id=\"" + mSceneId + "\" name=\"" + sceneName + "\">" << endstr;
  1041. PushTag();
  1042. if (mAdd_root_node) {
  1043. // Export the root node
  1044. WriteNode(mScene->mRootNode);
  1045. } else {
  1046. // Have already exported the root node
  1047. for (size_t a = 0; a < mScene->mRootNode->mNumChildren; ++a)
  1048. WriteNode(mScene->mRootNode->mChildren[a]);
  1049. }
  1050. PopTag();
  1051. mOutput << startstr << "</visual_scene>" << endstr;
  1052. PopTag();
  1053. mOutput << startstr << "</library_visual_scenes>" << endstr;
  1054. }
  1055. // ------------------------------------------------------------------------------------------------
  1056. void ColladaExporter::WriteAnimationLibrary(size_t pIndex) {
  1057. const aiAnimation *anim = mScene->mAnimations[pIndex];
  1058. if (anim->mNumChannels == 0 && anim->mNumMeshChannels == 0 && anim->mNumMorphMeshChannels == 0)
  1059. return;
  1060. const std::string animationNameEscaped = GetObjectName(AiObjectType::Animation, pIndex);
  1061. const std::string idstrEscaped = GetObjectUniqueId(AiObjectType::Animation, pIndex);
  1062. mOutput << startstr << "<animation id=\"" + idstrEscaped + "\" name=\"" + animationNameEscaped + "\">" << endstr;
  1063. PushTag();
  1064. std::string cur_node_idstr;
  1065. for (size_t a = 0; a < anim->mNumChannels; ++a) {
  1066. const aiNodeAnim *nodeAnim = anim->mChannels[a];
  1067. // sanity check
  1068. if (nodeAnim->mNumPositionKeys != nodeAnim->mNumScalingKeys || nodeAnim->mNumPositionKeys != nodeAnim->mNumRotationKeys) {
  1069. continue;
  1070. }
  1071. {
  1072. cur_node_idstr.clear();
  1073. cur_node_idstr += nodeAnim->mNodeName.data;
  1074. cur_node_idstr += std::string("_matrix-input");
  1075. std::vector<ai_real> frames;
  1076. for (size_t i = 0; i < nodeAnim->mNumPositionKeys; ++i) {
  1077. frames.push_back(static_cast<ai_real>(nodeAnim->mPositionKeys[i].mTime));
  1078. }
  1079. WriteFloatArray(cur_node_idstr, FloatType_Time, (const ai_real *)frames.data(), frames.size());
  1080. frames.clear();
  1081. }
  1082. {
  1083. cur_node_idstr.clear();
  1084. cur_node_idstr += nodeAnim->mNodeName.data;
  1085. cur_node_idstr += std::string("_matrix-output");
  1086. std::vector<ai_real> keyframes;
  1087. keyframes.reserve(nodeAnim->mNumPositionKeys * 16);
  1088. for (size_t i = 0; i < nodeAnim->mNumPositionKeys; ++i) {
  1089. aiVector3D Scaling = nodeAnim->mScalingKeys[i].mValue;
  1090. aiMatrix4x4 ScalingM; // identity
  1091. ScalingM[0][0] = Scaling.x;
  1092. ScalingM[1][1] = Scaling.y;
  1093. ScalingM[2][2] = Scaling.z;
  1094. aiQuaternion RotationQ = nodeAnim->mRotationKeys[i].mValue;
  1095. aiMatrix4x4 s = aiMatrix4x4(RotationQ.GetMatrix());
  1096. aiMatrix4x4 RotationM(s.a1, s.a2, s.a3, 0, s.b1, s.b2, s.b3, 0, s.c1, s.c2, s.c3, 0, 0, 0, 0, 1);
  1097. aiVector3D Translation = nodeAnim->mPositionKeys[i].mValue;
  1098. aiMatrix4x4 TranslationM; // identity
  1099. TranslationM[0][3] = Translation.x;
  1100. TranslationM[1][3] = Translation.y;
  1101. TranslationM[2][3] = Translation.z;
  1102. // Combine the above transformations
  1103. aiMatrix4x4 mat = TranslationM * RotationM * ScalingM;
  1104. for (unsigned int j = 0; j < 4; ++j) {
  1105. keyframes.insert(keyframes.end(), mat[j], mat[j] + 4);
  1106. }
  1107. }
  1108. WriteFloatArray(cur_node_idstr, FloatType_Mat4x4, (const ai_real *)keyframes.data(), keyframes.size() / 16);
  1109. }
  1110. {
  1111. std::vector<std::string> names;
  1112. for (size_t i = 0; i < nodeAnim->mNumPositionKeys; ++i) {
  1113. if (nodeAnim->mPreState == aiAnimBehaviour_DEFAULT || nodeAnim->mPreState == aiAnimBehaviour_LINEAR || nodeAnim->mPreState == aiAnimBehaviour_REPEAT) {
  1114. names.emplace_back("LINEAR");
  1115. } else if (nodeAnim->mPostState == aiAnimBehaviour_CONSTANT) {
  1116. names.emplace_back("STEP");
  1117. }
  1118. }
  1119. const std::string cur_node_idstr2 = nodeAnim->mNodeName.data + std::string("_matrix-interpolation");
  1120. std::string arrayId = XMLIDEncode(cur_node_idstr2) + "-array";
  1121. mOutput << startstr << "<source id=\"" << XMLIDEncode(cur_node_idstr2) << "\">" << endstr;
  1122. PushTag();
  1123. // source array
  1124. mOutput << startstr << "<Name_array id=\"" << arrayId << "\" count=\"" << names.size() << "\"> ";
  1125. for (size_t aa = 0; aa < names.size(); ++aa) {
  1126. mOutput << names[aa] << " ";
  1127. }
  1128. mOutput << "</Name_array>" << endstr;
  1129. mOutput << startstr << "<technique_common>" << endstr;
  1130. PushTag();
  1131. mOutput << startstr << "<accessor source=\"#" << arrayId << "\" count=\"" << names.size() << "\" stride=\"" << 1 << "\">" << endstr;
  1132. PushTag();
  1133. mOutput << startstr << "<param name=\"INTERPOLATION\" type=\"name\"></param>" << endstr;
  1134. PopTag();
  1135. mOutput << startstr << "</accessor>" << endstr;
  1136. PopTag();
  1137. mOutput << startstr << "</technique_common>" << endstr;
  1138. PopTag();
  1139. mOutput << startstr << "</source>" << endstr;
  1140. }
  1141. }
  1142. for (size_t a = 0; a < anim->mNumChannels; ++a) {
  1143. const aiNodeAnim *nodeAnim = anim->mChannels[a];
  1144. {
  1145. // samplers
  1146. const std::string node_idstr = nodeAnim->mNodeName.data + std::string("_matrix-sampler");
  1147. mOutput << startstr << "<sampler id=\"" << XMLIDEncode(node_idstr) << "\">" << endstr;
  1148. PushTag();
  1149. mOutput << startstr << "<input semantic=\"INPUT\" source=\"#" << XMLIDEncode(nodeAnim->mNodeName.data + std::string("_matrix-input")) << "\"/>" << endstr;
  1150. mOutput << startstr << "<input semantic=\"OUTPUT\" source=\"#" << XMLIDEncode(nodeAnim->mNodeName.data + std::string("_matrix-output")) << "\"/>" << endstr;
  1151. mOutput << startstr << "<input semantic=\"INTERPOLATION\" source=\"#" << XMLIDEncode(nodeAnim->mNodeName.data + std::string("_matrix-interpolation")) << "\"/>" << endstr;
  1152. PopTag();
  1153. mOutput << startstr << "</sampler>" << endstr;
  1154. }
  1155. }
  1156. for (size_t a = 0; a < anim->mNumChannels; ++a) {
  1157. const aiNodeAnim *nodeAnim = anim->mChannels[a];
  1158. {
  1159. // channels
  1160. mOutput << startstr << "<channel source=\"#" << XMLIDEncode(nodeAnim->mNodeName.data + std::string("_matrix-sampler")) << "\" target=\"" << XMLIDEncode(nodeAnim->mNodeName.data) << "/matrix\"/>" << endstr;
  1161. }
  1162. }
  1163. PopTag();
  1164. mOutput << startstr << "</animation>" << endstr;
  1165. }
  1166. // ------------------------------------------------------------------------------------------------
  1167. void ColladaExporter::WriteAnimationsLibrary() {
  1168. if (mScene->mNumAnimations > 0) {
  1169. mOutput << startstr << "<library_animations>" << endstr;
  1170. PushTag();
  1171. // start recursive write at the root node
  1172. for (size_t a = 0; a < mScene->mNumAnimations; ++a)
  1173. WriteAnimationLibrary(a);
  1174. PopTag();
  1175. mOutput << startstr << "</library_animations>" << endstr;
  1176. }
  1177. }
  1178. // ------------------------------------------------------------------------------------------------
  1179. // Helper to find a bone by name in the scene
  1180. aiBone *findBone(const aiScene *scene, const aiString &name) {
  1181. for (size_t m = 0; m < scene->mNumMeshes; m++) {
  1182. aiMesh *mesh = scene->mMeshes[m];
  1183. for (size_t b = 0; b < mesh->mNumBones; b++) {
  1184. aiBone *bone = mesh->mBones[b];
  1185. if (name == bone->mName) {
  1186. return bone;
  1187. }
  1188. }
  1189. }
  1190. return nullptr;
  1191. }
  1192. // ------------------------------------------------------------------------------------------------
  1193. // Helper to find the node associated with a bone in the scene
  1194. const aiNode *findBoneNode(const aiNode *aNode, const aiBone *bone) {
  1195. if (aNode && bone && aNode->mName == bone->mName) {
  1196. return aNode;
  1197. }
  1198. if (aNode && bone) {
  1199. for (unsigned int i = 0; i < aNode->mNumChildren; ++i) {
  1200. aiNode *aChild = aNode->mChildren[i];
  1201. const aiNode *foundFromChild = nullptr;
  1202. if (aChild) {
  1203. foundFromChild = findBoneNode(aChild, bone);
  1204. if (foundFromChild) {
  1205. return foundFromChild;
  1206. }
  1207. }
  1208. }
  1209. }
  1210. return nullptr;
  1211. }
  1212. const aiNode *findSkeletonRootNode(const aiScene *scene, const aiMesh *mesh) {
  1213. std::set<const aiNode *> topParentBoneNodes;
  1214. if (mesh && mesh->mNumBones > 0) {
  1215. for (unsigned int i = 0; i < mesh->mNumBones; ++i) {
  1216. aiBone *bone = mesh->mBones[i];
  1217. const aiNode *node = findBoneNode(scene->mRootNode, bone);
  1218. if (node) {
  1219. while (node->mParent && findBone(scene, node->mParent->mName) != nullptr) {
  1220. node = node->mParent;
  1221. }
  1222. topParentBoneNodes.insert(node);
  1223. }
  1224. }
  1225. }
  1226. if (!topParentBoneNodes.empty()) {
  1227. const aiNode *parentBoneNode = *topParentBoneNodes.begin();
  1228. if (topParentBoneNodes.size() == 1) {
  1229. return parentBoneNode;
  1230. } else {
  1231. for (auto it : topParentBoneNodes) {
  1232. if (it->mParent) return it->mParent;
  1233. }
  1234. return parentBoneNode;
  1235. }
  1236. }
  1237. return nullptr;
  1238. }
  1239. // ------------------------------------------------------------------------------------------------
  1240. // Recursively writes the given node
  1241. void ColladaExporter::WriteNode(const aiNode *pNode) {
  1242. // If the node is associated with a bone, it is a joint node (JOINT)
  1243. // otherwise it is a normal node (NODE)
  1244. // Assimp-specific: nodes with no name cannot be associated with bones
  1245. const char *node_type;
  1246. bool is_joint, is_skeleton_root = false;
  1247. if (pNode->mName.length == 0 || nullptr == findBone(mScene, pNode->mName)) {
  1248. node_type = "NODE";
  1249. is_joint = false;
  1250. } else {
  1251. node_type = "JOINT";
  1252. is_joint = true;
  1253. if (!pNode->mParent || nullptr == findBone(mScene, pNode->mParent->mName)) {
  1254. is_skeleton_root = true;
  1255. }
  1256. }
  1257. const std::string node_id = GetNodeUniqueId(pNode);
  1258. const std::string node_name = GetNodeName(pNode);
  1259. mOutput << startstr << "<node ";
  1260. if (is_skeleton_root) {
  1261. mFoundSkeletonRootNodeID = node_id; // For now, only support one skeleton in a scene.
  1262. }
  1263. mOutput << "id=\"" << node_id << "\" " << (is_joint ? "sid=\"" + node_id + "\" " : "");
  1264. mOutput << "name=\"" << node_name
  1265. << "\" type=\"" << node_type
  1266. << "\">" << endstr;
  1267. PushTag();
  1268. // write transformation - we can directly put the matrix there
  1269. // TODO: (thom) decompose into scale - rot - quad to allow addressing it by animations afterwards
  1270. aiMatrix4x4 mat = pNode->mTransformation;
  1271. // If this node is a Camera node, the camera coordinate system needs to be multiplied in.
  1272. // When importing from Collada, the mLookAt is set to 0, 0, -1, and the node transform is unchanged.
  1273. // When importing from a different format, mLookAt is set to 0, 0, 1. Therefore, the local camera
  1274. // coordinate system must be changed to matche the Collada specification.
  1275. for (size_t i = 0; i < mScene->mNumCameras; i++) {
  1276. if (mScene->mCameras[i]->mName == pNode->mName) {
  1277. aiMatrix4x4 sourceView;
  1278. mScene->mCameras[i]->GetCameraMatrix(sourceView);
  1279. aiMatrix4x4 colladaView;
  1280. colladaView.a1 = colladaView.c3 = -1; // move into -z space.
  1281. mat *= (sourceView * colladaView);
  1282. break;
  1283. }
  1284. }
  1285. // customized, sid should be 'matrix' to match with loader code.
  1286. //mOutput << startstr << "<matrix sid=\"transform\">";
  1287. mOutput << startstr << "<matrix sid=\"matrix\">";
  1288. mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
  1289. mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " ";
  1290. mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " ";
  1291. mOutput << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4;
  1292. mOutput << "</matrix>" << endstr;
  1293. if (pNode->mNumMeshes == 0) {
  1294. //check if it is a camera node
  1295. for (size_t i = 0; i < mScene->mNumCameras; i++) {
  1296. if (mScene->mCameras[i]->mName == pNode->mName) {
  1297. mOutput << startstr << "<instance_camera url=\"#" << GetObjectUniqueId(AiObjectType::Camera, i) << "\"/>" << endstr;
  1298. break;
  1299. }
  1300. }
  1301. //check if it is a light node
  1302. for (size_t i = 0; i < mScene->mNumLights; i++) {
  1303. if (mScene->mLights[i]->mName == pNode->mName) {
  1304. mOutput << startstr << "<instance_light url=\"#" << GetObjectUniqueId(AiObjectType::Light, i) << "\"/>" << endstr;
  1305. break;
  1306. }
  1307. }
  1308. } else
  1309. // instance every geometry
  1310. for (size_t a = 0; a < pNode->mNumMeshes; ++a) {
  1311. const aiMesh *mesh = mScene->mMeshes[pNode->mMeshes[a]];
  1312. // do not instantiate mesh if empty. I wonder how this could happen
  1313. if (mesh->mNumFaces == 0 || mesh->mNumVertices == 0)
  1314. continue;
  1315. const std::string meshId = GetObjectUniqueId(AiObjectType::Mesh, pNode->mMeshes[a]);
  1316. if (mesh->mNumBones == 0) {
  1317. mOutput << startstr << "<instance_geometry url=\"#" << meshId << "\">" << endstr;
  1318. PushTag();
  1319. } else {
  1320. mOutput << startstr
  1321. << "<instance_controller url=\"#" << meshId << "-skin\">"
  1322. << endstr;
  1323. PushTag();
  1324. // note! this mFoundSkeletonRootNodeID some how affects animation, it makes the mesh attaches to armature skeleton root node.
  1325. // use the first bone to find skeleton root
  1326. const aiNode *skeletonRootBoneNode = findSkeletonRootNode(mScene, mesh);
  1327. if (skeletonRootBoneNode) {
  1328. mFoundSkeletonRootNodeID = GetNodeUniqueId(skeletonRootBoneNode);
  1329. }
  1330. mOutput << startstr << "<skeleton>#" << mFoundSkeletonRootNodeID << "</skeleton>" << endstr;
  1331. }
  1332. mOutput << startstr << "<bind_material>" << endstr;
  1333. PushTag();
  1334. mOutput << startstr << "<technique_common>" << endstr;
  1335. PushTag();
  1336. mOutput << startstr << "<instance_material symbol=\"defaultMaterial\" target=\"#" << GetObjectUniqueId(AiObjectType::Material, mesh->mMaterialIndex) << "\">" << endstr;
  1337. PushTag();
  1338. for (size_t aa = 0; aa < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++aa) {
  1339. if (mesh->HasTextureCoords(static_cast<unsigned int>(aa)))
  1340. // semantic as in <texture texcoord=...>
  1341. // input_semantic as in <input semantic=...>
  1342. // input_set as in <input set=...>
  1343. mOutput << startstr << "<bind_vertex_input semantic=\"CHANNEL" << aa << "\" input_semantic=\"TEXCOORD\" input_set=\"" << aa << "\"/>" << endstr;
  1344. }
  1345. PopTag();
  1346. mOutput << startstr << "</instance_material>" << endstr;
  1347. PopTag();
  1348. mOutput << startstr << "</technique_common>" << endstr;
  1349. PopTag();
  1350. mOutput << startstr << "</bind_material>" << endstr;
  1351. PopTag();
  1352. if (mesh->mNumBones == 0)
  1353. mOutput << startstr << "</instance_geometry>" << endstr;
  1354. else
  1355. mOutput << startstr << "</instance_controller>" << endstr;
  1356. }
  1357. // recurse into subnodes
  1358. for (size_t a = 0; a < pNode->mNumChildren; ++a)
  1359. WriteNode(pNode->mChildren[a]);
  1360. PopTag();
  1361. mOutput << startstr << "</node>" << endstr;
  1362. }
  1363. void ColladaExporter::CreateNodeIds(const aiNode *node) {
  1364. GetNodeUniqueId(node);
  1365. for (size_t a = 0; a < node->mNumChildren; ++a)
  1366. CreateNodeIds(node->mChildren[a]);
  1367. }
  1368. std::string ColladaExporter::GetNodeUniqueId(const aiNode *node) {
  1369. // Use the pointer as the key. This is safe because the scene is immutable.
  1370. auto idIt = mNodeIdMap.find(node);
  1371. if (idIt != mNodeIdMap.cend())
  1372. return idIt->second;
  1373. // Prefer the requested Collada Id if extant
  1374. std::string idStr;
  1375. aiString origId;
  1376. if (node->mMetaData && node->mMetaData->Get(AI_METADATA_COLLADA_ID, origId)) {
  1377. idStr = origId.C_Str();
  1378. } else {
  1379. idStr = node->mName.C_Str();
  1380. }
  1381. // Make sure the requested id is valid
  1382. if (idStr.empty())
  1383. idStr = "node";
  1384. else
  1385. idStr = XMLIDEncode(idStr);
  1386. // Ensure it's unique
  1387. idStr = MakeUniqueId(mUniqueIds, idStr, std::string());
  1388. mUniqueIds.insert(idStr);
  1389. mNodeIdMap.insert(std::make_pair(node, idStr));
  1390. return idStr;
  1391. }
  1392. std::string ColladaExporter::GetNodeName(const aiNode *node) {
  1393. return XMLEscape(node->mName.C_Str());
  1394. }
  1395. std::string ColladaExporter::GetBoneUniqueId(const aiBone *bone) {
  1396. // Find the Node that is this Bone
  1397. const aiNode *boneNode = findBoneNode(mScene->mRootNode, bone);
  1398. if (boneNode == nullptr)
  1399. return std::string();
  1400. return GetNodeUniqueId(boneNode);
  1401. }
  1402. std::string ColladaExporter::GetObjectUniqueId(AiObjectType type, size_t pIndex) {
  1403. auto idIt = GetObjectIdMap(type).find(pIndex);
  1404. if (idIt != GetObjectIdMap(type).cend())
  1405. return idIt->second;
  1406. // Not seen this object before, create and add
  1407. NameIdPair result = AddObjectIndexToMaps(type, pIndex);
  1408. return result.second;
  1409. }
  1410. std::string ColladaExporter::GetObjectName(AiObjectType type, size_t pIndex) {
  1411. auto objectName = GetObjectNameMap(type).find(pIndex);
  1412. if (objectName != GetObjectNameMap(type).cend())
  1413. return objectName->second;
  1414. // Not seen this object before, create and add
  1415. NameIdPair result = AddObjectIndexToMaps(type, pIndex);
  1416. return result.first;
  1417. }
  1418. // Determine unique id and add the name and id to the maps
  1419. // @param type object type
  1420. // @param index object index
  1421. // @param name in/out. Caller to set the original name if known.
  1422. // @param idStr in/out. Caller to set the preferred id if known.
  1423. ColladaExporter::NameIdPair ColladaExporter::AddObjectIndexToMaps(AiObjectType type, size_t index) {
  1424. std::string name;
  1425. std::string idStr;
  1426. std::string idPostfix;
  1427. // Get the name and id postfix
  1428. switch (type) {
  1429. case AiObjectType::Mesh: name = mScene->mMeshes[index]->mName.C_Str(); break;
  1430. case AiObjectType::Material: name = mScene->mMaterials[index]->GetName().C_Str(); break;
  1431. case AiObjectType::Animation: name = mScene->mAnimations[index]->mName.C_Str(); break;
  1432. case AiObjectType::Light:
  1433. name = mScene->mLights[index]->mName.C_Str();
  1434. idPostfix = "-light";
  1435. break;
  1436. case AiObjectType::Camera:
  1437. name = mScene->mCameras[index]->mName.C_Str();
  1438. idPostfix = "-camera";
  1439. break;
  1440. case AiObjectType::Count: throw std::logic_error("ColladaExporter::AiObjectType::Count is not an object type");
  1441. }
  1442. if (name.empty()) {
  1443. // Default ids if empty name
  1444. switch (type) {
  1445. case AiObjectType::Mesh: idStr = std::string("mesh_"); break;
  1446. case AiObjectType::Material: idStr = std::string("material_"); break; // This one should never happen
  1447. case AiObjectType::Animation: idStr = std::string("animation_"); break;
  1448. case AiObjectType::Light: idStr = std::string("light_"); break;
  1449. case AiObjectType::Camera: idStr = std::string("camera_"); break;
  1450. case AiObjectType::Count: throw std::logic_error("ColladaExporter::AiObjectType::Count is not an object type");
  1451. }
  1452. idStr.append(ai_to_string(index));
  1453. } else {
  1454. idStr = XMLIDEncode(name);
  1455. }
  1456. if (!name.empty())
  1457. name = XMLEscape(name);
  1458. idStr = MakeUniqueId(mUniqueIds, idStr, idPostfix);
  1459. // Add to maps
  1460. mUniqueIds.insert(idStr);
  1461. GetObjectIdMap(type).insert(std::make_pair(index, idStr));
  1462. GetObjectNameMap(type).insert(std::make_pair(index, name));
  1463. return std::make_pair(name, idStr);
  1464. }
  1465. } // end of namespace Assimp
  1466. #endif
  1467. #endif