ColladaExporter.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2016, 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 "Bitmap.h"
  37. #include "fast_atof.h"
  38. #include "SceneCombiner.h"
  39. #include "DefaultIOSystem.h"
  40. #include "StringUtils.h"
  41. #include "XMLTools.h"
  42. #include <assimp/IOSystem.hpp>
  43. #include <assimp/Exporter.hpp>
  44. #include <assimp/scene.h>
  45. #include "Exceptional.h"
  46. #include <memory>
  47. #include <ctime>
  48. #include <set>
  49. #include <vector>
  50. #include <iostream>
  51. using namespace Assimp;
  52. namespace Assimp
  53. {
  54. // ------------------------------------------------------------------------------------------------
  55. // Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp
  56. void ExportSceneCollada(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  57. {
  58. std::string path = DefaultIOSystem::absolutePath(std::string(pFile));
  59. std::string file = DefaultIOSystem::completeBaseName(std::string(pFile));
  60. // invoke the exporter
  61. ColladaExporter iDoTheExportThing( pScene, pIOSystem, path, file);
  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 == NULL) {
  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. } // end of namespace Assimp
  71. // ------------------------------------------------------------------------------------------------
  72. // Constructor for a specific scene to export
  73. ColladaExporter::ColladaExporter( const aiScene* pScene, IOSystem* pIOSystem, const std::string& path, const std::string& file) : mIOSystem(pIOSystem), mPath(path), mFile(file)
  74. {
  75. // make sure that all formatting happens using the standard, C locale and not the user's current locale
  76. mOutput.imbue( std::locale("C") );
  77. mOutput.precision(16);
  78. mScene = pScene;
  79. mSceneOwned = false;
  80. // set up strings
  81. endstr = "\n";
  82. // start writing
  83. WriteFile();
  84. }
  85. // ------------------------------------------------------------------------------------------------
  86. // Destructor
  87. ColladaExporter::~ColladaExporter()
  88. {
  89. if(mSceneOwned) {
  90. delete mScene;
  91. }
  92. }
  93. // ------------------------------------------------------------------------------------------------
  94. // Starts writing the contents
  95. void ColladaExporter::WriteFile()
  96. {
  97. // write the DTD
  98. mOutput << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << endstr;
  99. // COLLADA element start
  100. mOutput << "<COLLADA xmlns=\"http://www.collada.org/2005/11/COLLADASchema\" version=\"1.4.1\">" << endstr;
  101. PushTag();
  102. WriteTextures();
  103. WriteHeader();
  104. WriteCamerasLibrary();
  105. WriteLightsLibrary();
  106. WriteMaterials();
  107. WriteGeometryLibrary();
  108. WriteControllerLibrary();
  109. WriteSceneLibrary();
  110. // useless Collada fu at the end, just in case we haven't had enough indirections, yet.
  111. mOutput << startstr << "<scene>" << endstr;
  112. PushTag();
  113. mOutput << startstr << "<instance_visual_scene url=\"#" + XMLEscape(mScene->mRootNode->mName.C_Str()) + "\" />" << endstr;
  114. PopTag();
  115. mOutput << startstr << "</scene>" << endstr;
  116. PopTag();
  117. mOutput << "</COLLADA>" << endstr;
  118. }
  119. // ------------------------------------------------------------------------------------------------
  120. // Writes the asset header
  121. void ColladaExporter::WriteHeader()
  122. {
  123. static const ai_real epsilon = ai_real( 0.00001 );
  124. static const aiQuaternion x_rot(aiMatrix3x3(
  125. 0, -1, 0,
  126. 1, 0, 0,
  127. 0, 0, 1));
  128. static const aiQuaternion y_rot(aiMatrix3x3(
  129. 1, 0, 0,
  130. 0, 1, 0,
  131. 0, 0, 1));
  132. static const aiQuaternion z_rot(aiMatrix3x3(
  133. 1, 0, 0,
  134. 0, 0, 1,
  135. 0, -1, 0));
  136. static const unsigned int date_nb_chars = 20;
  137. char date_str[date_nb_chars];
  138. std::time_t date = std::time(NULL);
  139. std::strftime(date_str, date_nb_chars, "%Y-%m-%dT%H:%M:%S", std::localtime(&date));
  140. aiVector3D scaling;
  141. aiQuaternion rotation;
  142. aiVector3D position;
  143. mScene->mRootNode->mTransformation.Decompose(scaling, rotation, position);
  144. rotation.Normalize();
  145. bool add_root_node = false;
  146. ai_real scale = 1.0;
  147. if(std::abs(scaling.x - scaling.y) <= epsilon && std::abs(scaling.x - scaling.z) <= epsilon && std::abs(scaling.y - scaling.z) <= epsilon) {
  148. scale = (ai_real) ((((double) scaling.x) + ((double) scaling.y) + ((double) scaling.z)) / 3.0);
  149. } else {
  150. add_root_node = true;
  151. }
  152. std::string up_axis = "Y_UP";
  153. if(rotation.Equal(x_rot, epsilon)) {
  154. up_axis = "X_UP";
  155. } else if(rotation.Equal(y_rot, epsilon)) {
  156. up_axis = "Y_UP";
  157. } else if(rotation.Equal(z_rot, epsilon)) {
  158. up_axis = "Z_UP";
  159. } else {
  160. add_root_node = true;
  161. }
  162. if(! position.Equal(aiVector3D(0, 0, 0))) {
  163. add_root_node = true;
  164. }
  165. if(mScene->mRootNode->mNumChildren == 0) {
  166. add_root_node = true;
  167. }
  168. if(add_root_node) {
  169. aiScene* scene;
  170. SceneCombiner::CopyScene(&scene, mScene);
  171. aiNode* root = new aiNode("Scene");
  172. root->mNumChildren = 1;
  173. root->mChildren = new aiNode*[root->mNumChildren];
  174. root->mChildren[0] = scene->mRootNode;
  175. scene->mRootNode->mParent = root;
  176. scene->mRootNode = root;
  177. mScene = scene;
  178. mSceneOwned = true;
  179. up_axis = "Y_UP";
  180. scale = 1.0;
  181. }
  182. mOutput << startstr << "<asset>" << endstr;
  183. PushTag();
  184. mOutput << startstr << "<contributor>" << endstr;
  185. PushTag();
  186. aiMetadata* meta = mScene->mRootNode->mMetaData;
  187. aiString value;
  188. if (!meta || !meta->Get("Author", value))
  189. mOutput << startstr << "<author>" << "Assimp" << "</author>" << endstr;
  190. else
  191. mOutput << startstr << "<author>" << XMLEscape(value.C_Str()) << "</author>" << endstr;
  192. if (!meta || !meta->Get("AuthoringTool", value))
  193. mOutput << startstr << "<authoring_tool>" << "Assimp Exporter" << "</authoring_tool>" << endstr;
  194. else
  195. mOutput << startstr << "<authoring_tool>" << XMLEscape(value.C_Str()) << "</authoring_tool>" << endstr;
  196. //mOutput << startstr << "<author>" << mScene->author.C_Str() << "</author>" << endstr;
  197. //mOutput << startstr << "<authoring_tool>" << mScene->authoringTool.C_Str() << "</authoring_tool>" << endstr;
  198. PopTag();
  199. mOutput << startstr << "</contributor>" << endstr;
  200. mOutput << startstr << "<created>" << date_str << "</created>" << endstr;
  201. mOutput << startstr << "<modified>" << date_str << "</modified>" << endstr;
  202. mOutput << startstr << "<unit name=\"meter\" meter=\"" << scale << "\" />" << endstr;
  203. mOutput << startstr << "<up_axis>" << up_axis << "</up_axis>" << endstr;
  204. PopTag();
  205. mOutput << startstr << "</asset>" << endstr;
  206. }
  207. // ------------------------------------------------------------------------------------------------
  208. // Write the embedded textures
  209. void ColladaExporter::WriteTextures() {
  210. static const unsigned int buffer_size = 1024;
  211. char str[buffer_size];
  212. if(mScene->HasTextures()) {
  213. for(unsigned int i = 0; i < mScene->mNumTextures; i++) {
  214. // It would be great to be able to create a directory in portable standard C++, but it's not the case,
  215. // so we just write the textures in the current directory.
  216. aiTexture* texture = mScene->mTextures[i];
  217. ASSIMP_itoa10(str, buffer_size, i + 1);
  218. std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char*) texture->achFormatHint);
  219. std::unique_ptr<IOStream> outfile(mIOSystem->Open(mPath + name, "wb"));
  220. if(outfile == NULL) {
  221. throw DeadlyExportError("could not open output texture file: " + mPath + name);
  222. }
  223. if(texture->mHeight == 0) {
  224. outfile->Write((void*) texture->pcData, texture->mWidth, 1);
  225. } else {
  226. Bitmap::Save(texture, outfile.get());
  227. }
  228. outfile->Flush();
  229. textures.insert(std::make_pair(i, name));
  230. }
  231. }
  232. }
  233. // ------------------------------------------------------------------------------------------------
  234. // Write the embedded textures
  235. void ColladaExporter::WriteCamerasLibrary() {
  236. if(mScene->HasCameras()) {
  237. mOutput << startstr << "<library_cameras>" << endstr;
  238. PushTag();
  239. for( size_t a = 0; a < mScene->mNumCameras; ++a)
  240. WriteCamera( a);
  241. PopTag();
  242. mOutput << startstr << "</library_cameras>" << endstr;
  243. }
  244. }
  245. void ColladaExporter::WriteCamera(size_t pIndex){
  246. const aiCamera *cam = mScene->mCameras[pIndex];
  247. const std::string idstrEscaped = XMLEscape(cam->mName.C_Str());
  248. mOutput << startstr << "<camera id=\"" << idstrEscaped << "-camera\" name=\"" << idstrEscaped << "_name\" >" << endstr;
  249. PushTag();
  250. mOutput << startstr << "<optics>" << endstr;
  251. PushTag();
  252. mOutput << startstr << "<technique_common>" << endstr;
  253. PushTag();
  254. //assimp doesn't support the import of orthographic cameras! se we write
  255. //always perspective
  256. mOutput << startstr << "<perspective>" << endstr;
  257. PushTag();
  258. mOutput << startstr << "<xfov sid=\"xfov\">"<<
  259. AI_RAD_TO_DEG(cam->mHorizontalFOV)
  260. <<"</xfov>" << endstr;
  261. mOutput << startstr << "<aspect_ratio>"
  262. << cam->mAspect
  263. << "</aspect_ratio>" << endstr;
  264. mOutput << startstr << "<znear sid=\"znear\">"
  265. << cam->mClipPlaneNear
  266. << "</znear>" << endstr;
  267. mOutput << startstr << "<zfar sid=\"zfar\">"
  268. << cam->mClipPlaneFar
  269. << "</zfar>" << endstr;
  270. PopTag();
  271. mOutput << startstr << "</perspective>" << endstr;
  272. PopTag();
  273. mOutput << startstr << "</technique_common>" << endstr;
  274. PopTag();
  275. mOutput << startstr << "</optics>" << endstr;
  276. PopTag();
  277. mOutput << startstr << "</camera>" << endstr;
  278. }
  279. // ------------------------------------------------------------------------------------------------
  280. // Write the embedded textures
  281. void ColladaExporter::WriteLightsLibrary() {
  282. if(mScene->HasLights()) {
  283. mOutput << startstr << "<library_lights>" << endstr;
  284. PushTag();
  285. for( size_t a = 0; a < mScene->mNumLights; ++a)
  286. WriteLight( a);
  287. PopTag();
  288. mOutput << startstr << "</library_lights>" << endstr;
  289. }
  290. }
  291. void ColladaExporter::WriteLight(size_t pIndex){
  292. const aiLight *light = mScene->mLights[pIndex];
  293. const std::string idstrEscaped = XMLEscape(light->mName.C_Str());
  294. mOutput << startstr << "<light id=\"" << idstrEscaped << "-light\" name=\""
  295. << idstrEscaped << "_name\" >" << endstr;
  296. PushTag();
  297. mOutput << startstr << "<technique_common>" << endstr;
  298. PushTag();
  299. switch(light->mType){
  300. case aiLightSource_AMBIENT:
  301. WriteAmbienttLight(light);
  302. break;
  303. case aiLightSource_DIRECTIONAL:
  304. WriteDirectionalLight(light);
  305. break;
  306. case aiLightSource_POINT:
  307. WritePointLight(light);
  308. break;
  309. case aiLightSource_SPOT:
  310. WriteSpotLight(light);
  311. break;
  312. case aiLightSource_AREA:
  313. case aiLightSource_UNDEFINED:
  314. case _aiLightSource_Force32Bit:
  315. break;
  316. }
  317. PopTag();
  318. mOutput << startstr << "</technique_common>" << endstr;
  319. PopTag();
  320. mOutput << startstr << "</light>" << endstr;
  321. }
  322. void ColladaExporter::WritePointLight(const aiLight *const light){
  323. const aiColor3D &color= light->mColorDiffuse;
  324. mOutput << startstr << "<point>" << endstr;
  325. PushTag();
  326. mOutput << startstr << "<color sid=\"color\">"
  327. << color.r<<" "<<color.g<<" "<<color.b
  328. <<"</color>" << endstr;
  329. mOutput << startstr << "<constant_attenuation>"
  330. << light->mAttenuationConstant
  331. <<"</constant_attenuation>" << endstr;
  332. mOutput << startstr << "<linear_attenuation>"
  333. << light->mAttenuationLinear
  334. <<"</linear_attenuation>" << endstr;
  335. mOutput << startstr << "<quadratic_attenuation>"
  336. << light->mAttenuationQuadratic
  337. <<"</quadratic_attenuation>" << endstr;
  338. PopTag();
  339. mOutput << startstr << "</point>" << endstr;
  340. }
  341. void ColladaExporter::WriteDirectionalLight(const aiLight *const light){
  342. const aiColor3D &color= light->mColorDiffuse;
  343. mOutput << startstr << "<directional>" << endstr;
  344. PushTag();
  345. mOutput << startstr << "<color sid=\"color\">"
  346. << color.r<<" "<<color.g<<" "<<color.b
  347. <<"</color>" << endstr;
  348. PopTag();
  349. mOutput << startstr << "</directional>" << endstr;
  350. }
  351. void ColladaExporter::WriteSpotLight(const aiLight *const light){
  352. const aiColor3D &color= light->mColorDiffuse;
  353. mOutput << startstr << "<spot>" << endstr;
  354. PushTag();
  355. mOutput << startstr << "<color sid=\"color\">"
  356. << color.r<<" "<<color.g<<" "<<color.b
  357. <<"</color>" << endstr;
  358. mOutput << startstr << "<constant_attenuation>"
  359. << light->mAttenuationConstant
  360. <<"</constant_attenuation>" << endstr;
  361. mOutput << startstr << "<linear_attenuation>"
  362. << light->mAttenuationLinear
  363. <<"</linear_attenuation>" << endstr;
  364. mOutput << startstr << "<quadratic_attenuation>"
  365. << light->mAttenuationQuadratic
  366. <<"</quadratic_attenuation>" << endstr;
  367. /*
  368. out->mAngleOuterCone = AI_DEG_TO_RAD (std::acos(std::pow(0.1f,1.f/srcLight->mFalloffExponent))+
  369. srcLight->mFalloffAngle);
  370. */
  371. const ai_real fallOffAngle = AI_RAD_TO_DEG(light->mAngleInnerCone);
  372. mOutput << startstr <<"<falloff_angle sid=\"fall_off_angle\">"
  373. << fallOffAngle
  374. <<"</falloff_angle>" << endstr;
  375. double temp = light->mAngleOuterCone-light->mAngleInnerCone;
  376. temp = std::cos(temp);
  377. temp = std::log(temp)/std::log(0.1);
  378. temp = 1/temp;
  379. mOutput << startstr << "<falloff_exponent sid=\"fall_off_exponent\">"
  380. << temp
  381. <<"</falloff_exponent>" << endstr;
  382. PopTag();
  383. mOutput << startstr << "</spot>" << endstr;
  384. }
  385. void ColladaExporter::WriteAmbienttLight(const aiLight *const light){
  386. const aiColor3D &color= light->mColorAmbient;
  387. mOutput << startstr << "<ambient>" << endstr;
  388. PushTag();
  389. mOutput << startstr << "<color sid=\"color\">"
  390. << color.r<<" "<<color.g<<" "<<color.b
  391. <<"</color>" << endstr;
  392. PopTag();
  393. mOutput << startstr << "</ambient>" << endstr;
  394. }
  395. // ------------------------------------------------------------------------------------------------
  396. // Reads a single surface entry from the given material keys
  397. void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial* pSrcMat, aiTextureType pTexture, const char* pKey, size_t pType, size_t pIndex)
  398. {
  399. if( pSrcMat->GetTextureCount( pTexture) > 0 )
  400. {
  401. aiString texfile;
  402. unsigned int uvChannel = 0;
  403. pSrcMat->GetTexture( pTexture, 0, &texfile, NULL, &uvChannel);
  404. std::string index_str(texfile.C_Str());
  405. if(index_str.size() != 0 && index_str[0] == '*')
  406. {
  407. unsigned int index;
  408. index_str = index_str.substr(1, std::string::npos);
  409. try {
  410. index = (unsigned int) strtoul10_64(index_str.c_str());
  411. } catch(std::exception& error) {
  412. throw DeadlyExportError(error.what());
  413. }
  414. std::map<unsigned int, std::string>::const_iterator name = textures.find(index);
  415. if(name != textures.end()) {
  416. poSurface.texture = name->second;
  417. } else {
  418. throw DeadlyExportError("could not find embedded texture at index " + index_str);
  419. }
  420. } else
  421. {
  422. poSurface.texture = texfile.C_Str();
  423. }
  424. poSurface.channel = uvChannel;
  425. poSurface.exist = true;
  426. } else
  427. {
  428. if( pKey )
  429. poSurface.exist = pSrcMat->Get( pKey, static_cast<unsigned int>(pType), static_cast<unsigned int>(pIndex), poSurface.color) == aiReturn_SUCCESS;
  430. }
  431. }
  432. // ------------------------------------------------------------------------------------------------
  433. // Reimplementation of isalnum(,C locale), because AppVeyor does not see standard version.
  434. static bool isalnum_C(char c)
  435. {
  436. return ( nullptr != strchr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",c) );
  437. }
  438. // ------------------------------------------------------------------------------------------------
  439. // Writes an image entry for the given surface
  440. void ColladaExporter::WriteImageEntry( const Surface& pSurface, const std::string& pNameAdd)
  441. {
  442. if( !pSurface.texture.empty() )
  443. {
  444. mOutput << startstr << "<image id=\"" << XMLEscape(pNameAdd) << "\">" << endstr;
  445. PushTag();
  446. mOutput << startstr << "<init_from>";
  447. // URL encode image file name first, then XML encode on top
  448. std::stringstream imageUrlEncoded;
  449. for( std::string::const_iterator it = pSurface.texture.begin(); it != pSurface.texture.end(); ++it )
  450. {
  451. if( isalnum_C( (unsigned char) *it) || *it == ':' || *it == '_' || *it == '.' || *it == '/' || *it == '\\' )
  452. imageUrlEncoded << *it;
  453. else
  454. imageUrlEncoded << '%' << std::hex << size_t( (unsigned char) *it) << std::dec;
  455. }
  456. mOutput << XMLEscape(imageUrlEncoded.str());
  457. mOutput << "</init_from>" << endstr;
  458. PopTag();
  459. mOutput << startstr << "</image>" << endstr;
  460. }
  461. }
  462. // ------------------------------------------------------------------------------------------------
  463. // Writes a color-or-texture entry into an effect definition
  464. void ColladaExporter::WriteTextureColorEntry( const Surface& pSurface, const std::string& pTypeName, const std::string& pImageName)
  465. {
  466. if(pSurface.exist) {
  467. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  468. PushTag();
  469. if( pSurface.texture.empty() )
  470. {
  471. mOutput << startstr << "<color sid=\"" << pTypeName << "\">" << pSurface.color.r << " " << pSurface.color.g << " " << pSurface.color.b << " " << pSurface.color.a << "</color>" << endstr;
  472. }
  473. else
  474. {
  475. mOutput << startstr << "<texture texture=\"" << XMLEscape(pImageName) << "\" texcoord=\"CHANNEL" << pSurface.channel << "\" />" << endstr;
  476. }
  477. PopTag();
  478. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  479. }
  480. }
  481. // ------------------------------------------------------------------------------------------------
  482. // Writes the two parameters necessary for referencing a texture in an effect entry
  483. void ColladaExporter::WriteTextureParamEntry( const Surface& pSurface, const std::string& pTypeName, const std::string& pMatName)
  484. {
  485. // if surface is a texture, write out the sampler and the surface parameters necessary to reference the texture
  486. if( !pSurface.texture.empty() )
  487. {
  488. mOutput << startstr << "<newparam sid=\"" << XMLEscape(pMatName) << "-" << pTypeName << "-surface\">" << endstr;
  489. PushTag();
  490. mOutput << startstr << "<surface type=\"2D\">" << endstr;
  491. PushTag();
  492. mOutput << startstr << "<init_from>" << XMLEscape(pMatName) << "-" << pTypeName << "-image</init_from>" << endstr;
  493. PopTag();
  494. mOutput << startstr << "</surface>" << endstr;
  495. PopTag();
  496. mOutput << startstr << "</newparam>" << endstr;
  497. mOutput << startstr << "<newparam sid=\"" << XMLEscape(pMatName) << "-" << pTypeName << "-sampler\">" << endstr;
  498. PushTag();
  499. mOutput << startstr << "<sampler2D>" << endstr;
  500. PushTag();
  501. mOutput << startstr << "<source>" << XMLEscape(pMatName) << "-" << pTypeName << "-surface</source>" << endstr;
  502. PopTag();
  503. mOutput << startstr << "</sampler2D>" << endstr;
  504. PopTag();
  505. mOutput << startstr << "</newparam>" << endstr;
  506. }
  507. }
  508. // ------------------------------------------------------------------------------------------------
  509. // Writes a scalar property
  510. void ColladaExporter::WriteFloatEntry( const Property& pProperty, const std::string& pTypeName)
  511. {
  512. if(pProperty.exist) {
  513. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  514. PushTag();
  515. mOutput << startstr << "<float sid=\"" << pTypeName << "\">" << pProperty.value << "</float>" << endstr;
  516. PopTag();
  517. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  518. }
  519. }
  520. // ------------------------------------------------------------------------------------------------
  521. // Writes the material setup
  522. void ColladaExporter::WriteMaterials()
  523. {
  524. materials.resize( mScene->mNumMaterials);
  525. /// collect all materials from the scene
  526. size_t numTextures = 0;
  527. for( size_t a = 0; a < mScene->mNumMaterials; ++a )
  528. {
  529. const aiMaterial* mat = mScene->mMaterials[a];
  530. aiString name;
  531. if( mat->Get( AI_MATKEY_NAME, name) != aiReturn_SUCCESS ) {
  532. name = "mat";
  533. materials[a].name = std::string( "m") + to_string(a) + name.C_Str();
  534. } else {
  535. // try to use the material's name if no other material has already taken it, else append #
  536. std::string testName = name.C_Str();
  537. size_t materialCountWithThisName = 0;
  538. for( size_t i = 0; i < a; i ++ ) {
  539. if( materials[i].name == testName ) {
  540. materialCountWithThisName ++;
  541. }
  542. }
  543. if( materialCountWithThisName == 0 ) {
  544. materials[a].name = name.C_Str();
  545. } else {
  546. materials[a].name = std::string(name.C_Str()) + to_string(materialCountWithThisName);
  547. }
  548. }
  549. for( std::string::iterator it = materials[a].name.begin(); it != materials[a].name.end(); ++it ) {
  550. if( !isalnum_C( *it ) ) {
  551. *it = '_';
  552. }
  553. }
  554. aiShadingMode shading = aiShadingMode_Flat;
  555. materials[a].shading_model = "phong";
  556. if(mat->Get( AI_MATKEY_SHADING_MODEL, shading) == aiReturn_SUCCESS) {
  557. if(shading == aiShadingMode_Phong) {
  558. materials[a].shading_model = "phong";
  559. } else if(shading == aiShadingMode_Blinn) {
  560. materials[a].shading_model = "blinn";
  561. } else if(shading == aiShadingMode_NoShading) {
  562. materials[a].shading_model = "constant";
  563. } else if(shading == aiShadingMode_Gouraud) {
  564. materials[a].shading_model = "lambert";
  565. }
  566. }
  567. ReadMaterialSurface( materials[a].ambient, mat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT);
  568. if( !materials[a].ambient.texture.empty() ) numTextures++;
  569. ReadMaterialSurface( materials[a].diffuse, mat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE);
  570. if( !materials[a].diffuse.texture.empty() ) numTextures++;
  571. ReadMaterialSurface( materials[a].specular, mat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR);
  572. if( !materials[a].specular.texture.empty() ) numTextures++;
  573. ReadMaterialSurface( materials[a].emissive, mat, aiTextureType_EMISSIVE, AI_MATKEY_COLOR_EMISSIVE);
  574. if( !materials[a].emissive.texture.empty() ) numTextures++;
  575. ReadMaterialSurface( materials[a].reflective, mat, aiTextureType_REFLECTION, AI_MATKEY_COLOR_REFLECTIVE);
  576. if( !materials[a].reflective.texture.empty() ) numTextures++;
  577. ReadMaterialSurface( materials[a].transparent, mat, aiTextureType_OPACITY, AI_MATKEY_COLOR_TRANSPARENT);
  578. if( !materials[a].transparent.texture.empty() ) numTextures++;
  579. ReadMaterialSurface( materials[a].normal, mat, aiTextureType_NORMALS, NULL, 0, 0);
  580. if( !materials[a].normal.texture.empty() ) numTextures++;
  581. materials[a].shininess.exist = mat->Get( AI_MATKEY_SHININESS, materials[a].shininess.value) == aiReturn_SUCCESS;
  582. materials[a].transparency.exist = mat->Get( AI_MATKEY_OPACITY, materials[a].transparency.value) == aiReturn_SUCCESS;
  583. materials[a].transparency.value = materials[a].transparency.value;
  584. materials[a].index_refraction.exist = mat->Get( AI_MATKEY_REFRACTI, materials[a].index_refraction.value) == aiReturn_SUCCESS;
  585. }
  586. // output textures if present
  587. if( numTextures > 0 )
  588. {
  589. mOutput << startstr << "<library_images>" << endstr;
  590. PushTag();
  591. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  592. {
  593. const Material& mat = *it;
  594. WriteImageEntry( mat.ambient, mat.name + "-ambient-image");
  595. WriteImageEntry( mat.diffuse, mat.name + "-diffuse-image");
  596. WriteImageEntry( mat.specular, mat.name + "-specular-image");
  597. WriteImageEntry( mat.emissive, mat.name + "-emission-image");
  598. WriteImageEntry( mat.reflective, mat.name + "-reflective-image");
  599. WriteImageEntry( mat.transparent, mat.name + "-transparent-image");
  600. WriteImageEntry( mat.normal, mat.name + "-normal-image");
  601. }
  602. PopTag();
  603. mOutput << startstr << "</library_images>" << endstr;
  604. }
  605. // output effects - those are the actual carriers of information
  606. if( !materials.empty() )
  607. {
  608. mOutput << startstr << "<library_effects>" << endstr;
  609. PushTag();
  610. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  611. {
  612. const Material& mat = *it;
  613. // this is so ridiculous it must be right
  614. mOutput << startstr << "<effect id=\"" << XMLEscape(mat.name) << "-fx\" name=\"" << XMLEscape(mat.name) << "\">" << endstr;
  615. PushTag();
  616. mOutput << startstr << "<profile_COMMON>" << endstr;
  617. PushTag();
  618. // write sampler- and surface params for the texture entries
  619. WriteTextureParamEntry( mat.emissive, "emission", mat.name);
  620. WriteTextureParamEntry( mat.ambient, "ambient", mat.name);
  621. WriteTextureParamEntry( mat.diffuse, "diffuse", mat.name);
  622. WriteTextureParamEntry( mat.specular, "specular", mat.name);
  623. WriteTextureParamEntry( mat.reflective, "reflective", mat.name);
  624. WriteTextureParamEntry( mat.transparent, "transparent", mat.name);
  625. WriteTextureParamEntry( mat.normal, "normal", mat.name);
  626. mOutput << startstr << "<technique sid=\"standard\">" << endstr;
  627. PushTag();
  628. mOutput << startstr << "<" << mat.shading_model << ">" << endstr;
  629. PushTag();
  630. WriteTextureColorEntry( mat.emissive, "emission", mat.name + "-emission-sampler");
  631. WriteTextureColorEntry( mat.ambient, "ambient", mat.name + "-ambient-sampler");
  632. WriteTextureColorEntry( mat.diffuse, "diffuse", mat.name + "-diffuse-sampler");
  633. WriteTextureColorEntry( mat.specular, "specular", mat.name + "-specular-sampler");
  634. WriteFloatEntry(mat.shininess, "shininess");
  635. WriteTextureColorEntry( mat.reflective, "reflective", mat.name + "-reflective-sampler");
  636. WriteTextureColorEntry( mat.transparent, "transparent", mat.name + "-transparent-sampler");
  637. WriteFloatEntry(mat.transparency, "transparency");
  638. WriteFloatEntry(mat.index_refraction, "index_of_refraction");
  639. if(! mat.normal.texture.empty()) {
  640. WriteTextureColorEntry( mat.normal, "bump", mat.name + "-normal-sampler");
  641. }
  642. PopTag();
  643. mOutput << startstr << "</" << mat.shading_model << ">" << endstr;
  644. PopTag();
  645. mOutput << startstr << "</technique>" << endstr;
  646. PopTag();
  647. mOutput << startstr << "</profile_COMMON>" << endstr;
  648. PopTag();
  649. mOutput << startstr << "</effect>" << endstr;
  650. }
  651. PopTag();
  652. mOutput << startstr << "</library_effects>" << endstr;
  653. // write materials - they're just effect references
  654. mOutput << startstr << "<library_materials>" << endstr;
  655. PushTag();
  656. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  657. {
  658. const Material& mat = *it;
  659. mOutput << startstr << "<material id=\"" << XMLEscape(mat.name) << "\" name=\"" << mat.name << "\">" << endstr;
  660. PushTag();
  661. mOutput << startstr << "<instance_effect url=\"#" << XMLEscape(mat.name) << "-fx\"/>" << endstr;
  662. PopTag();
  663. mOutput << startstr << "</material>" << endstr;
  664. }
  665. PopTag();
  666. mOutput << startstr << "</library_materials>" << endstr;
  667. }
  668. }
  669. // ------------------------------------------------------------------------------------------------
  670. // Writes the controller library
  671. void ColladaExporter::WriteControllerLibrary()
  672. {
  673. mOutput << startstr << "<library_controllers>" << endstr;
  674. PushTag();
  675. for( size_t a = 0; a < mScene->mNumMeshes; ++a)
  676. WriteController( a);
  677. PopTag();
  678. mOutput << startstr << "</library_controllers>" << endstr;
  679. }
  680. // ------------------------------------------------------------------------------------------------
  681. // Writes a skin controller of the given mesh
  682. void ColladaExporter::WriteController( size_t pIndex)
  683. {
  684. const aiMesh* mesh = mScene->mMeshes[pIndex];
  685. const std::string idstr = GetMeshId( pIndex);
  686. const std::string idstrEscaped = XMLEscape(idstr);
  687. if ( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  688. return;
  689. if ( mesh->mNumBones == 0 )
  690. return;
  691. mOutput << startstr << "<controller id=\"" << idstrEscaped << "-skin\" ";
  692. mOutput << "name=\"skinCluster" << pIndex << "\">"<< endstr;
  693. PushTag();
  694. mOutput << startstr << "<skin source=\"#" << idstrEscaped << "\">" << endstr;
  695. PushTag();
  696. // bind pose matrix
  697. mOutput << startstr << "<bind_shape_matrix>" << endstr;
  698. PushTag();
  699. // I think it is identity in general cases.
  700. aiMatrix4x4 mat;
  701. mOutput << startstr << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << endstr;
  702. mOutput << startstr << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << endstr;
  703. mOutput << startstr << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << endstr;
  704. mOutput << startstr << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4 << endstr;
  705. PopTag();
  706. mOutput << startstr << "</bind_shape_matrix>" << endstr;
  707. mOutput << startstr << "<source id=\"" << idstrEscaped << "-skin-joints\" name=\"" << idstrEscaped << "-skin-joints\">" << endstr;
  708. PushTag();
  709. mOutput << startstr << "<Name_array id=\"" << idstrEscaped << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\">";
  710. for( size_t i = 0; i < mesh->mNumBones; ++i )
  711. mOutput << XMLEscape(mesh->mBones[i]->mName.C_Str()) << " ";
  712. mOutput << "</Name_array>" << endstr;
  713. mOutput << startstr << "<technique_common>" << endstr;
  714. PushTag();
  715. mOutput << startstr << "<accessor source=\"#" << idstrEscaped << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\" stride=\"" << 1 << "\">" << endstr;
  716. PushTag();
  717. mOutput << startstr << "<param name=\"JOINT\" type=\"Name\"></param>" << endstr;
  718. PopTag();
  719. mOutput << startstr << "</accessor>" << endstr;
  720. PopTag();
  721. mOutput << startstr << "</technique_common>" << endstr;
  722. PopTag();
  723. mOutput << startstr << "</source>" << endstr;
  724. std::vector<ai_real> bind_poses;
  725. bind_poses.reserve(mesh->mNumBones * 16);
  726. for( size_t i = 0; i < mesh->mNumBones; ++i)
  727. for( size_t j = 0; j < 4; ++j)
  728. bind_poses.insert(bind_poses.end(), mesh->mBones[i]->mOffsetMatrix[j], mesh->mBones[i]->mOffsetMatrix[j] + 4);
  729. WriteFloatArray( idstr + "-skin-bind_poses", FloatType_Mat4x4, (const ai_real*) bind_poses.data(), bind_poses.size() / 16);
  730. bind_poses.clear();
  731. std::vector<ai_real> skin_weights;
  732. skin_weights.reserve(mesh->mNumVertices * mesh->mNumBones);
  733. for( size_t i = 0; i < mesh->mNumBones; ++i)
  734. for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  735. skin_weights.push_back(mesh->mBones[i]->mWeights[j].mWeight);
  736. WriteFloatArray( idstr + "-skin-weights", FloatType_Weight, (const ai_real*) skin_weights.data(), skin_weights.size());
  737. skin_weights.clear();
  738. mOutput << startstr << "<joints>" << endstr;
  739. PushTag();
  740. mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstrEscaped << "-skin-joints\"></input>" << endstr;
  741. mOutput << startstr << "<input semantic=\"INV_BIND_MATRIX\" source=\"#" << idstrEscaped << "-skin-bind_poses\"></input>" << endstr;
  742. PopTag();
  743. mOutput << startstr << "</joints>" << endstr;
  744. mOutput << startstr << "<vertex_weights count=\"" << mesh->mNumVertices << "\">" << endstr;
  745. PushTag();
  746. mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstrEscaped << "-skin-joints\" offset=\"0\"></input>" << endstr;
  747. mOutput << startstr << "<input semantic=\"WEIGHT\" source=\"#" << idstrEscaped << "-skin-weights\" offset=\"1\"></input>" << endstr;
  748. mOutput << startstr << "<vcount>";
  749. std::vector<ai_uint> num_influences(mesh->mNumVertices, (ai_uint)0);
  750. for( size_t i = 0; i < mesh->mNumBones; ++i)
  751. for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  752. ++num_influences[mesh->mBones[i]->mWeights[j].mVertexId];
  753. for( size_t i = 0; i < mesh->mNumVertices; ++i)
  754. mOutput << num_influences[i] << " ";
  755. mOutput << "</vcount>" << endstr;
  756. mOutput << startstr << "<v>";
  757. ai_uint joint_weight_indices_length = 0;
  758. std::vector<ai_uint> accum_influences;
  759. accum_influences.reserve(num_influences.size());
  760. for( size_t i = 0; i < num_influences.size(); ++i)
  761. {
  762. accum_influences.push_back(joint_weight_indices_length);
  763. joint_weight_indices_length += num_influences[i];
  764. }
  765. ai_uint weight_index = 0;
  766. std::vector<ai_int> joint_weight_indices(2 * joint_weight_indices_length, (ai_int)-1);
  767. for( size_t i = 0; i < mesh->mNumBones; ++i)
  768. for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  769. {
  770. unsigned int vId = mesh->mBones[i]->mWeights[j].mVertexId;
  771. for( size_t k = 0; k < num_influences[vId]; ++k)
  772. {
  773. if (joint_weight_indices[2 * (accum_influences[vId] + k)] == -1)
  774. {
  775. joint_weight_indices[2 * (accum_influences[vId] + k)] = i;
  776. joint_weight_indices[2 * (accum_influences[vId] + k) + 1] = weight_index;
  777. break;
  778. }
  779. }
  780. ++weight_index;
  781. }
  782. for( size_t i = 0; i < joint_weight_indices.size(); ++i)
  783. mOutput << joint_weight_indices[i] << " ";
  784. num_influences.clear();
  785. accum_influences.clear();
  786. joint_weight_indices.clear();
  787. mOutput << "</v>" << endstr;
  788. PopTag();
  789. mOutput << startstr << "</vertex_weights>" << endstr;
  790. PopTag();
  791. mOutput << startstr << "</skin>" << endstr;
  792. PopTag();
  793. mOutput << startstr << "</controller>" << endstr;
  794. }
  795. // ------------------------------------------------------------------------------------------------
  796. // Writes the geometry library
  797. void ColladaExporter::WriteGeometryLibrary()
  798. {
  799. mOutput << startstr << "<library_geometries>" << endstr;
  800. PushTag();
  801. for( size_t a = 0; a < mScene->mNumMeshes; ++a)
  802. WriteGeometry( a);
  803. PopTag();
  804. mOutput << startstr << "</library_geometries>" << endstr;
  805. }
  806. // ------------------------------------------------------------------------------------------------
  807. // Writes the given mesh
  808. void ColladaExporter::WriteGeometry( size_t pIndex)
  809. {
  810. const aiMesh* mesh = mScene->mMeshes[pIndex];
  811. const std::string idstr = GetMeshId( pIndex);
  812. const std::string idstrEscaped = XMLEscape(idstr);
  813. if ( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  814. return;
  815. // opening tag
  816. mOutput << startstr << "<geometry id=\"" << idstrEscaped << "\" name=\"" << idstrEscaped << "_name\" >" << endstr;
  817. PushTag();
  818. mOutput << startstr << "<mesh>" << endstr;
  819. PushTag();
  820. // Positions
  821. WriteFloatArray( idstr + "-positions", FloatType_Vector, (ai_real*) mesh->mVertices, mesh->mNumVertices);
  822. // Normals, if any
  823. if( mesh->HasNormals() )
  824. WriteFloatArray( idstr + "-normals", FloatType_Vector, (ai_real*) mesh->mNormals, mesh->mNumVertices);
  825. // texture coords
  826. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  827. {
  828. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  829. {
  830. WriteFloatArray( idstr + "-tex" + to_string(a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2,
  831. (ai_real*) mesh->mTextureCoords[a], mesh->mNumVertices);
  832. }
  833. }
  834. // vertex colors
  835. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  836. {
  837. if( mesh->HasVertexColors(static_cast<unsigned int>(a)) )
  838. WriteFloatArray( idstr + "-color" + to_string(a), FloatType_Color, (ai_real*) mesh->mColors[a], mesh->mNumVertices);
  839. }
  840. // assemble vertex structure
  841. // Only write input for POSITION since we will write other as shared inputs in polygon definition
  842. mOutput << startstr << "<vertices id=\"" << idstrEscaped << "-vertices" << "\">" << endstr;
  843. PushTag();
  844. mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << idstrEscaped << "-positions\" />" << endstr;
  845. PopTag();
  846. mOutput << startstr << "</vertices>" << endstr;
  847. // count the number of lines, triangles and polygon meshes
  848. int countLines = 0;
  849. int countPoly = 0;
  850. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  851. {
  852. if (mesh->mFaces[a].mNumIndices == 2) countLines++;
  853. else if (mesh->mFaces[a].mNumIndices >= 3) countPoly++;
  854. }
  855. // lines
  856. if (countLines)
  857. {
  858. mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr;
  859. PushTag();
  860. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
  861. if( mesh->HasNormals() )
  862. mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << idstrEscaped << "-normals\" />" << endstr;
  863. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  864. {
  865. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  866. mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  867. }
  868. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
  869. {
  870. if( mesh->HasVertexColors(static_cast<unsigned int>(a) ) )
  871. mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << idstrEscaped << "-color" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  872. }
  873. mOutput << startstr << "<p>";
  874. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  875. {
  876. const aiFace& face = mesh->mFaces[a];
  877. if (face.mNumIndices != 2) continue;
  878. for( size_t b = 0; b < face.mNumIndices; ++b )
  879. mOutput << face.mIndices[b] << " ";
  880. }
  881. mOutput << "</p>" << endstr;
  882. PopTag();
  883. mOutput << startstr << "</lines>" << endstr;
  884. }
  885. // triangle - don't use it, because compatibility problems
  886. // polygons
  887. if (countPoly)
  888. {
  889. mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr;
  890. PushTag();
  891. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
  892. if( mesh->HasNormals() )
  893. mOutput << startstr << "<input offset=\"0\" semantic=\"NORMAL\" source=\"#" << idstrEscaped << "-normals\" />" << endstr;
  894. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  895. {
  896. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  897. mOutput << startstr << "<input offset=\"0\" semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  898. }
  899. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
  900. {
  901. if( mesh->HasVertexColors(static_cast<unsigned int>(a) ) )
  902. mOutput << startstr << "<input offset=\"0\" semantic=\"COLOR\" source=\"#" << idstrEscaped << "-color" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  903. }
  904. mOutput << startstr << "<vcount>";
  905. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  906. {
  907. if (mesh->mFaces[a].mNumIndices < 3) continue;
  908. mOutput << mesh->mFaces[a].mNumIndices << " ";
  909. }
  910. mOutput << "</vcount>" << endstr;
  911. mOutput << startstr << "<p>";
  912. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  913. {
  914. const aiFace& face = mesh->mFaces[a];
  915. if (face.mNumIndices < 3) continue;
  916. for( size_t b = 0; b < face.mNumIndices; ++b )
  917. mOutput << face.mIndices[b] << " ";
  918. }
  919. mOutput << "</p>" << endstr;
  920. PopTag();
  921. mOutput << startstr << "</polylist>" << endstr;
  922. }
  923. // closing tags
  924. PopTag();
  925. mOutput << startstr << "</mesh>" << endstr;
  926. PopTag();
  927. mOutput << startstr << "</geometry>" << endstr;
  928. }
  929. // ------------------------------------------------------------------------------------------------
  930. // Writes a float array of the given type
  931. void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataType pType, const ai_real* pData, size_t pElementCount)
  932. {
  933. size_t floatsPerElement = 0;
  934. switch( pType )
  935. {
  936. case FloatType_Vector: floatsPerElement = 3; break;
  937. case FloatType_TexCoord2: floatsPerElement = 2; break;
  938. case FloatType_TexCoord3: floatsPerElement = 3; break;
  939. case FloatType_Color: floatsPerElement = 3; break;
  940. case FloatType_Mat4x4: floatsPerElement = 16; break;
  941. case FloatType_Weight: floatsPerElement = 1; break;
  942. default:
  943. return;
  944. }
  945. std::string arrayId = pIdString + "-array";
  946. mOutput << startstr << "<source id=\"" << XMLEscape(pIdString) << "\" name=\"" << XMLEscape(pIdString) << "\">" << endstr;
  947. PushTag();
  948. // source array
  949. mOutput << startstr << "<float_array id=\"" << XMLEscape(arrayId) << "\" count=\"" << pElementCount * floatsPerElement << "\"> ";
  950. PushTag();
  951. if( pType == FloatType_TexCoord2 )
  952. {
  953. for( size_t a = 0; a < pElementCount; ++a )
  954. {
  955. mOutput << pData[a*3+0] << " ";
  956. mOutput << pData[a*3+1] << " ";
  957. }
  958. }
  959. else if( pType == FloatType_Color )
  960. {
  961. for( size_t a = 0; a < pElementCount; ++a )
  962. {
  963. mOutput << pData[a*4+0] << " ";
  964. mOutput << pData[a*4+1] << " ";
  965. mOutput << pData[a*4+2] << " ";
  966. }
  967. }
  968. else
  969. {
  970. for( size_t a = 0; a < pElementCount * floatsPerElement; ++a )
  971. mOutput << pData[a] << " ";
  972. }
  973. mOutput << "</float_array>" << endstr;
  974. PopTag();
  975. // the usual Collada fun. Let's bloat it even more!
  976. mOutput << startstr << "<technique_common>" << endstr;
  977. PushTag();
  978. mOutput << startstr << "<accessor count=\"" << pElementCount << "\" offset=\"0\" source=\"#" << arrayId << "\" stride=\"" << floatsPerElement << "\">" << endstr;
  979. PushTag();
  980. switch( pType )
  981. {
  982. case FloatType_Vector:
  983. mOutput << startstr << "<param name=\"X\" type=\"float\" />" << endstr;
  984. mOutput << startstr << "<param name=\"Y\" type=\"float\" />" << endstr;
  985. mOutput << startstr << "<param name=\"Z\" type=\"float\" />" << endstr;
  986. break;
  987. case FloatType_TexCoord2:
  988. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  989. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  990. break;
  991. case FloatType_TexCoord3:
  992. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  993. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  994. mOutput << startstr << "<param name=\"P\" type=\"float\" />" << endstr;
  995. break;
  996. case FloatType_Color:
  997. mOutput << startstr << "<param name=\"R\" type=\"float\" />" << endstr;
  998. mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr;
  999. mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr;
  1000. break;
  1001. case FloatType_Mat4x4:
  1002. mOutput << startstr << "<param name=\"TRANSFORM\" type=\"float4x4\" />" << endstr;
  1003. break;
  1004. case FloatType_Weight:
  1005. mOutput << startstr << "<param name=\"WEIGHT\" type=\"float\" />" << endstr;
  1006. break;
  1007. }
  1008. PopTag();
  1009. mOutput << startstr << "</accessor>" << endstr;
  1010. PopTag();
  1011. mOutput << startstr << "</technique_common>" << endstr;
  1012. PopTag();
  1013. mOutput << startstr << "</source>" << endstr;
  1014. }
  1015. // ------------------------------------------------------------------------------------------------
  1016. // Writes the scene library
  1017. void ColladaExporter::WriteSceneLibrary()
  1018. {
  1019. const std::string scene_name_escaped = XMLEscape(mScene->mRootNode->mName.C_Str());
  1020. mOutput << startstr << "<library_visual_scenes>" << endstr;
  1021. PushTag();
  1022. mOutput << startstr << "<visual_scene id=\"" + scene_name_escaped + "\" name=\"" + scene_name_escaped + "\">" << endstr;
  1023. PushTag();
  1024. // start recursive write at the root node
  1025. for( size_t a = 0; a < mScene->mRootNode->mNumChildren; ++a )
  1026. WriteNode( mScene, mScene->mRootNode->mChildren[a]);
  1027. PopTag();
  1028. mOutput << startstr << "</visual_scene>" << endstr;
  1029. PopTag();
  1030. mOutput << startstr << "</library_visual_scenes>" << endstr;
  1031. }
  1032. // ------------------------------------------------------------------------------------------------
  1033. // Helper to find a bone by name in the scene
  1034. aiBone* findBone( const aiScene* scene, const char * name) {
  1035. for (size_t m=0; m<scene->mNumMeshes; m++) {
  1036. aiMesh * mesh = scene->mMeshes[m];
  1037. for (size_t b=0; b<mesh->mNumBones; b++) {
  1038. aiBone * bone = mesh->mBones[b];
  1039. if (0 == strcmp(name, bone->mName.C_Str())) {
  1040. return bone;
  1041. }
  1042. }
  1043. }
  1044. return NULL;
  1045. }
  1046. // ------------------------------------------------------------------------------------------------
  1047. // Recursively writes the given node
  1048. void ColladaExporter::WriteNode( const aiScene* pScene, aiNode* pNode)
  1049. {
  1050. // the node must have a name
  1051. if (pNode->mName.length == 0)
  1052. {
  1053. std::stringstream ss;
  1054. ss << "Node_" << pNode;
  1055. pNode->mName.Set(ss.str());
  1056. }
  1057. // If the node is associated with a bone, it is a joint node (JOINT)
  1058. // otherwise it is a normal node (NODE)
  1059. const char * node_type;
  1060. bool is_joint, is_skeleton_root = false;
  1061. if (NULL == findBone(pScene, pNode->mName.C_Str())) {
  1062. node_type = "NODE";
  1063. is_joint = false;
  1064. } else {
  1065. node_type = "JOINT";
  1066. is_joint = true;
  1067. if(!pNode->mParent || NULL == findBone(pScene, pNode->mParent->mName.C_Str()))
  1068. is_skeleton_root = true;
  1069. }
  1070. const std::string node_name_escaped = XMLEscape(pNode->mName.data);
  1071. mOutput << startstr
  1072. << "<node ";
  1073. if(is_skeleton_root)
  1074. mOutput << "id=\"" << "skeleton_root" << "\" "; // For now, only support one skeleton in a scene.
  1075. mOutput << (is_joint ? "s" : "") << "id=\"" << node_name_escaped;
  1076. mOutput << "\" name=\"" << node_name_escaped
  1077. << "\" type=\"" << node_type
  1078. << "\">" << endstr;
  1079. PushTag();
  1080. // write transformation - we can directly put the matrix there
  1081. // TODO: (thom) decompose into scale - rot - quad to allow addressing it by animations afterwards
  1082. const aiMatrix4x4& mat = pNode->mTransformation;
  1083. mOutput << startstr << "<matrix sid=\"transform\">";
  1084. mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
  1085. mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " ";
  1086. mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " ";
  1087. mOutput << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4;
  1088. mOutput << "</matrix>" << endstr;
  1089. if(pNode->mNumMeshes==0){
  1090. //check if it is a camera node
  1091. for(size_t i=0; i<mScene->mNumCameras; i++){
  1092. if(mScene->mCameras[i]->mName == pNode->mName){
  1093. mOutput << startstr <<"<instance_camera url=\"#" << node_name_escaped << "-camera\"/>" << endstr;
  1094. break;
  1095. }
  1096. }
  1097. //check if it is a light node
  1098. for(size_t i=0; i<mScene->mNumLights; i++){
  1099. if(mScene->mLights[i]->mName == pNode->mName){
  1100. mOutput << startstr <<"<instance_light url=\"#" << node_name_escaped << "-light\"/>" << endstr;
  1101. break;
  1102. }
  1103. }
  1104. }else
  1105. // instance every geometry
  1106. for( size_t a = 0; a < pNode->mNumMeshes; ++a )
  1107. {
  1108. const aiMesh* mesh = mScene->mMeshes[pNode->mMeshes[a]];
  1109. // do not instanciate mesh if empty. I wonder how this could happen
  1110. if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  1111. continue;
  1112. if( mesh->mNumBones == 0 )
  1113. {
  1114. mOutput << startstr << "<instance_geometry url=\"#" << XMLEscape(GetMeshId( pNode->mMeshes[a])) << "\">" << endstr;
  1115. PushTag();
  1116. }
  1117. else
  1118. {
  1119. mOutput << startstr
  1120. << "<instance_controller url=\"#" << XMLEscape(GetMeshId( pNode->mMeshes[a])) << "-skin\">"
  1121. << endstr;
  1122. PushTag();
  1123. mOutput << startstr << "<skeleton>#skeleton_root</skeleton>" << endstr;
  1124. }
  1125. mOutput << startstr << "<bind_material>" << endstr;
  1126. PushTag();
  1127. mOutput << startstr << "<technique_common>" << endstr;
  1128. PushTag();
  1129. mOutput << startstr << "<instance_material symbol=\"defaultMaterial\" target=\"#" << XMLEscape(materials[mesh->mMaterialIndex].name) << "\">" << endstr;
  1130. PushTag();
  1131. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  1132. {
  1133. if( mesh->HasTextureCoords( static_cast<unsigned int>(a) ) )
  1134. // semantic as in <texture texcoord=...>
  1135. // input_semantic as in <input semantic=...>
  1136. // input_set as in <input set=...>
  1137. mOutput << startstr << "<bind_vertex_input semantic=\"CHANNEL" << a << "\" input_semantic=\"TEXCOORD\" input_set=\"" << a << "\"/>" << endstr;
  1138. }
  1139. PopTag();
  1140. mOutput << startstr << "</instance_material>" << endstr;
  1141. PopTag();
  1142. mOutput << startstr << "</technique_common>" << endstr;
  1143. PopTag();
  1144. mOutput << startstr << "</bind_material>" << endstr;
  1145. PopTag();
  1146. if( mesh->mNumBones == 0)
  1147. mOutput << startstr << "</instance_geometry>" << endstr;
  1148. else
  1149. mOutput << startstr << "</instance_controller>" << endstr;
  1150. }
  1151. // recurse into subnodes
  1152. for( size_t a = 0; a < pNode->mNumChildren; ++a )
  1153. WriteNode( pScene, pNode->mChildren[a]);
  1154. PopTag();
  1155. mOutput << startstr << "</node>" << endstr;
  1156. }
  1157. #endif
  1158. #endif