ColladaExporter.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, 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 "XMLTools.h"
  40. #include "../include/assimp/IOSystem.hpp"
  41. #include "../include/assimp/Exporter.hpp"
  42. #include "../include/assimp/scene.h"
  43. #include "Exceptional.h"
  44. #include <boost/scoped_ptr.hpp>
  45. #include <ctime>
  46. #include <set>
  47. using namespace Assimp;
  48. namespace Assimp
  49. {
  50. // ------------------------------------------------------------------------------------------------
  51. // Worker function for exporting a scene to Collada. Prototyped and registered in Exporter.cpp
  52. void ExportSceneCollada(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  53. {
  54. std::string path = "";
  55. std::string file = pFile;
  56. // We need to test both types of folder separators because pIOSystem->getOsSeparator() is not reliable.
  57. // Moreover, the path given by some applications is not even consistent with the OS specific type of separator.
  58. const char* end_path = std::max(strrchr(pFile, '\\'), strrchr(pFile, '/'));
  59. if(end_path != NULL) {
  60. path = std::string(pFile, end_path + 1 - pFile);
  61. file = file.substr(end_path + 1 - pFile, file.npos);
  62. std::size_t pos = file.find_last_of('.');
  63. if(pos != file.npos) {
  64. file = file.substr(0, pos);
  65. }
  66. }
  67. // invoke the exporter
  68. ColladaExporter iDoTheExportThing( pScene, pIOSystem, path, file);
  69. // we're still here - export successfully completed. Write result to the given IOSYstem
  70. boost::scoped_ptr<IOStream> outfile (pIOSystem->Open(pFile,"wt"));
  71. if(outfile == NULL) {
  72. throw DeadlyExportError("could not open output .dae file: " + std::string(pFile));
  73. }
  74. // XXX maybe use a small wrapper around IOStream that behaves like std::stringstream in order to avoid the extra copy.
  75. outfile->Write( iDoTheExportThing.mOutput.str().c_str(), static_cast<size_t>(iDoTheExportThing.mOutput.tellp()),1);
  76. }
  77. } // end of namespace Assimp
  78. // ------------------------------------------------------------------------------------------------
  79. // Constructor for a specific scene to export
  80. ColladaExporter::ColladaExporter( const aiScene* pScene, IOSystem* pIOSystem, const std::string& path, const std::string& file) : mIOSystem(pIOSystem), mPath(path), mFile(file)
  81. {
  82. // make sure that all formatting happens using the standard, C locale and not the user's current locale
  83. mOutput.imbue( std::locale("C") );
  84. mScene = pScene;
  85. mSceneOwned = false;
  86. // set up strings
  87. endstr = "\n";
  88. // start writing
  89. WriteFile();
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Destructor
  93. ColladaExporter::~ColladaExporter()
  94. {
  95. if(mSceneOwned) {
  96. delete mScene;
  97. }
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. // Starts writing the contents
  101. void ColladaExporter::WriteFile()
  102. {
  103. // write the DTD
  104. mOutput << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << endstr;
  105. // COLLADA element start
  106. mOutput << "<COLLADA xmlns=\"http://www.collada.org/2005/11/COLLADASchema\" version=\"1.4.1\">" << endstr;
  107. PushTag();
  108. WriteTextures();
  109. WriteHeader();
  110. WriteMaterials();
  111. WriteGeometryLibrary();
  112. WriteSceneLibrary();
  113. // useless Collada fu at the end, just in case we haven't had enough indirections, yet.
  114. mOutput << startstr << "<scene>" << endstr;
  115. PushTag();
  116. mOutput << startstr << "<instance_visual_scene url=\"#" + XMLEscape(mScene->mRootNode->mName.C_Str()) + "\" />" << endstr;
  117. PopTag();
  118. mOutput << startstr << "</scene>" << endstr;
  119. PopTag();
  120. mOutput << "</COLLADA>" << endstr;
  121. }
  122. // ------------------------------------------------------------------------------------------------
  123. // Writes the asset header
  124. void ColladaExporter::WriteHeader()
  125. {
  126. static const float epsilon = 0.00001f;
  127. static const aiQuaternion x_rot(aiMatrix3x3(
  128. 0, -1, 0,
  129. 1, 0, 0,
  130. 0, 0, 1));
  131. static const aiQuaternion y_rot(aiMatrix3x3(
  132. 1, 0, 0,
  133. 0, 1, 0,
  134. 0, 0, 1));
  135. static const aiQuaternion z_rot(aiMatrix3x3(
  136. 1, 0, 0,
  137. 0, 0, 1,
  138. 0, -1, 0));
  139. static const unsigned int date_nb_chars = 20;
  140. char date_str[date_nb_chars];
  141. std::time_t date = std::time(NULL);
  142. std::strftime(date_str, date_nb_chars, "%Y-%m-%dT%H:%M:%S", std::localtime(&date));
  143. std::string scene_name = mScene->mRootNode->mName.C_Str();
  144. aiVector3D scaling;
  145. aiQuaternion rotation;
  146. aiVector3D position;
  147. mScene->mRootNode->mTransformation.Decompose(scaling, rotation, position);
  148. rotation.Normalize();
  149. bool add_root_node = false;
  150. float scale = 1.0;
  151. if(std::abs(scaling.x - scaling.y) <= epsilon && std::abs(scaling.x - scaling.z) <= epsilon && std::abs(scaling.y - scaling.z) <= epsilon) {
  152. scale = (float) ((((double) scaling.x) + ((double) scaling.y) + ((double) scaling.z)) / 3.0);
  153. } else {
  154. add_root_node = true;
  155. }
  156. std::string up_axis = "Y_UP";
  157. if(rotation.Equal(x_rot, epsilon)) {
  158. up_axis = "X_UP";
  159. } else if(rotation.Equal(y_rot, epsilon)) {
  160. up_axis = "Y_UP";
  161. } else if(rotation.Equal(z_rot, epsilon)) {
  162. up_axis = "Z_UP";
  163. } else {
  164. add_root_node = true;
  165. }
  166. if(! position.Equal(aiVector3D(0, 0, 0))) {
  167. add_root_node = true;
  168. }
  169. if(mScene->mRootNode->mNumChildren == 0) {
  170. add_root_node = true;
  171. }
  172. if(add_root_node) {
  173. aiScene* scene;
  174. SceneCombiner::CopyScene(&scene, mScene);
  175. aiNode* root = new aiNode("Scene");
  176. root->mNumChildren = 1;
  177. root->mChildren = new aiNode*[root->mNumChildren];
  178. root->mChildren[0] = scene->mRootNode;
  179. scene->mRootNode->mParent = root;
  180. scene->mRootNode = root;
  181. mScene = scene;
  182. mSceneOwned = true;
  183. up_axis = "Y_UP";
  184. scale = 1.0;
  185. }
  186. mOutput << startstr << "<asset>" << endstr;
  187. PushTag();
  188. mOutput << startstr << "<contributor>" << endstr;
  189. PushTag();
  190. aiMetadata* meta = mScene->mRootNode->mMetaData;
  191. aiString value;
  192. if (!meta || !meta->Get("Author", value))
  193. mOutput << startstr << "<author>" << "Assimp" << "</author>" << endstr;
  194. else
  195. mOutput << startstr << "<author>" << XMLEscape(value.C_Str()) << "</author>" << endstr;
  196. if (!meta || !meta->Get("AuthoringTool", value))
  197. mOutput << startstr << "<authoring_tool>" << "Assimp Exporter" << "</authoring_tool>" << endstr;
  198. else
  199. mOutput << startstr << "<authoring_tool>" << XMLEscape(value.C_Str()) << "</authoring_tool>" << endstr;
  200. //mOutput << startstr << "<author>" << mScene->author.C_Str() << "</author>" << endstr;
  201. //mOutput << startstr << "<authoring_tool>" << mScene->authoringTool.C_Str() << "</authoring_tool>" << endstr;
  202. PopTag();
  203. mOutput << startstr << "</contributor>" << endstr;
  204. mOutput << startstr << "<created>" << date_str << "</created>" << endstr;
  205. mOutput << startstr << "<modified>" << date_str << "</modified>" << endstr;
  206. mOutput << startstr << "<unit name=\"meter\" meter=\"" << scale << "\" />" << endstr;
  207. mOutput << startstr << "<up_axis>" << up_axis << "</up_axis>" << endstr;
  208. PopTag();
  209. mOutput << startstr << "</asset>" << endstr;
  210. }
  211. // ------------------------------------------------------------------------------------------------
  212. // Write the embedded textures
  213. void ColladaExporter::WriteTextures() {
  214. static const unsigned int buffer_size = 1024;
  215. char str[buffer_size];
  216. if(mScene->HasTextures()) {
  217. for(unsigned int i = 0; i < mScene->mNumTextures; i++) {
  218. // It would be great to be able to create a directory in portable standard C++, but it's not the case,
  219. // so we just write the textures in the current directory.
  220. aiTexture* texture = mScene->mTextures[i];
  221. ASSIMP_itoa10(str, buffer_size, i + 1);
  222. std::string name = mFile + "_texture_" + (i < 1000 ? "0" : "") + (i < 100 ? "0" : "") + (i < 10 ? "0" : "") + str + "." + ((const char*) texture->achFormatHint);
  223. boost::scoped_ptr<IOStream> outfile(mIOSystem->Open(mPath + name, "wb"));
  224. if(outfile == NULL) {
  225. throw DeadlyExportError("could not open output texture file: " + mPath + name);
  226. }
  227. if(texture->mHeight == 0) {
  228. outfile->Write((void*) texture->pcData, texture->mWidth, 1);
  229. } else {
  230. Bitmap::Save(texture, outfile.get());
  231. }
  232. outfile->Flush();
  233. textures.insert(std::make_pair(i, name));
  234. }
  235. }
  236. }
  237. // ------------------------------------------------------------------------------------------------
  238. // Reads a single surface entry from the given material keys
  239. void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial* pSrcMat, aiTextureType pTexture, const char* pKey, size_t pType, size_t pIndex)
  240. {
  241. if( pSrcMat->GetTextureCount( pTexture) > 0 )
  242. {
  243. aiString texfile;
  244. unsigned int uvChannel = 0;
  245. pSrcMat->GetTexture( pTexture, 0, &texfile, NULL, &uvChannel);
  246. std::string index_str(texfile.C_Str());
  247. if(index_str.size() != 0 && index_str[0] == '*')
  248. {
  249. unsigned int index;
  250. index_str = index_str.substr(1, std::string::npos);
  251. try {
  252. index = (unsigned int) strtoul10_64(index_str.c_str());
  253. } catch(std::exception& error) {
  254. throw DeadlyExportError(error.what());
  255. }
  256. std::map<unsigned int, std::string>::const_iterator name = textures.find(index);
  257. if(name != textures.end()) {
  258. poSurface.texture = name->second;
  259. } else {
  260. throw DeadlyExportError("could not find embedded texture at index " + index_str);
  261. }
  262. } else
  263. {
  264. poSurface.texture = texfile.C_Str();
  265. }
  266. poSurface.channel = uvChannel;
  267. poSurface.exist = true;
  268. } else
  269. {
  270. if( pKey )
  271. poSurface.exist = pSrcMat->Get( pKey, pType, pIndex, poSurface.color) == aiReturn_SUCCESS;
  272. }
  273. }
  274. // ------------------------------------------------------------------------------------------------
  275. // Writes an image entry for the given surface
  276. void ColladaExporter::WriteImageEntry( const Surface& pSurface, const std::string& pNameAdd)
  277. {
  278. if( !pSurface.texture.empty() )
  279. {
  280. mOutput << startstr << "<image id=\"" << XMLEscape(pNameAdd) << "\">" << endstr;
  281. PushTag();
  282. mOutput << startstr << "<init_from>";
  283. // URL encode image file name first, then XML encode on top
  284. std::stringstream imageUrlEncoded;
  285. for( std::string::const_iterator it = pSurface.texture.begin(); it != pSurface.texture.end(); ++it )
  286. {
  287. if( isalnum( *it) || *it == '_' || *it == '.' || *it == '/' || *it == '\\' )
  288. imageUrlEncoded << *it;
  289. else
  290. imageUrlEncoded << '%' << std::hex << size_t( (unsigned char) *it) << std::dec;
  291. }
  292. mOutput << XMLEscape(imageUrlEncoded.str());
  293. mOutput << "</init_from>" << endstr;
  294. PopTag();
  295. mOutput << startstr << "</image>" << endstr;
  296. }
  297. }
  298. // ------------------------------------------------------------------------------------------------
  299. // Writes a color-or-texture entry into an effect definition
  300. void ColladaExporter::WriteTextureColorEntry( const Surface& pSurface, const std::string& pTypeName, const std::string& pImageName)
  301. {
  302. if(pSurface.exist) {
  303. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  304. PushTag();
  305. if( pSurface.texture.empty() )
  306. {
  307. mOutput << startstr << "<color sid=\"" << pTypeName << "\">" << pSurface.color.r << " " << pSurface.color.g << " " << pSurface.color.b << " " << pSurface.color.a << "</color>" << endstr;
  308. }
  309. else
  310. {
  311. mOutput << startstr << "<texture texture=\"" << XMLEscape(pImageName) << "\" texcoord=\"CHANNEL" << pSurface.channel << "\" />" << endstr;
  312. }
  313. PopTag();
  314. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  315. }
  316. }
  317. // ------------------------------------------------------------------------------------------------
  318. // Writes the two parameters necessary for referencing a texture in an effect entry
  319. void ColladaExporter::WriteTextureParamEntry( const Surface& pSurface, const std::string& pTypeName, const std::string& pMatName)
  320. {
  321. // if surface is a texture, write out the sampler and the surface parameters necessary to reference the texture
  322. if( !pSurface.texture.empty() )
  323. {
  324. mOutput << startstr << "<newparam sid=\"" << XMLEscape(pMatName) << "-" << pTypeName << "-surface\">" << endstr;
  325. PushTag();
  326. mOutput << startstr << "<surface type=\"2D\">" << endstr;
  327. PushTag();
  328. mOutput << startstr << "<init_from>" << XMLEscape(pMatName) << "-" << pTypeName << "-image</init_from>" << endstr;
  329. PopTag();
  330. mOutput << startstr << "</surface>" << endstr;
  331. PopTag();
  332. mOutput << startstr << "</newparam>" << endstr;
  333. mOutput << startstr << "<newparam sid=\"" << XMLEscape(pMatName) << "-" << pTypeName << "-sampler\">" << endstr;
  334. PushTag();
  335. mOutput << startstr << "<sampler2D>" << endstr;
  336. PushTag();
  337. mOutput << startstr << "<source>" << XMLEscape(pMatName) << "-" << pTypeName << "-surface</source>" << endstr;
  338. PopTag();
  339. mOutput << startstr << "</sampler2D>" << endstr;
  340. PopTag();
  341. mOutput << startstr << "</newparam>" << endstr;
  342. }
  343. }
  344. // ------------------------------------------------------------------------------------------------
  345. // Writes a scalar property
  346. void ColladaExporter::WriteFloatEntry( const Property& pProperty, const std::string& pTypeName)
  347. {
  348. if(pProperty.exist) {
  349. mOutput << startstr << "<" << pTypeName << ">" << endstr;
  350. PushTag();
  351. mOutput << startstr << "<float sid=\"" << pTypeName << "\">" << pProperty.value << "</float>" << endstr;
  352. PopTag();
  353. mOutput << startstr << "</" << pTypeName << ">" << endstr;
  354. }
  355. }
  356. // ------------------------------------------------------------------------------------------------
  357. // Writes the material setup
  358. void ColladaExporter::WriteMaterials()
  359. {
  360. materials.resize( mScene->mNumMaterials);
  361. std::set<std::string> material_names;
  362. /// collect all materials from the scene
  363. size_t numTextures = 0;
  364. for( size_t a = 0; a < mScene->mNumMaterials; ++a )
  365. {
  366. const aiMaterial* mat = mScene->mMaterials[a];
  367. aiString name;
  368. if( mat->Get( AI_MATKEY_NAME, name) != aiReturn_SUCCESS )
  369. name = "mat";
  370. materials[a].name = std::string( "m") + boost::lexical_cast<std::string> (a) + name.C_Str();
  371. for( std::string::iterator it = materials[a].name.begin(); it != materials[a].name.end(); ++it ) {
  372. // isalnum on MSVC asserts for code points outside [0,255]. Thus prevent unwanted promotion
  373. // of char to signed int and take the unsigned char value.
  374. if( !isalnum( static_cast<uint8_t>(*it) ) ) {
  375. *it = '_';
  376. }
  377. }
  378. aiShadingMode shading = aiShadingMode_Flat;
  379. materials[a].shading_model = "phong";
  380. if(mat->Get( AI_MATKEY_SHADING_MODEL, shading) == aiReturn_SUCCESS) {
  381. if(shading == aiShadingMode_Phong) {
  382. materials[a].shading_model = "phong";
  383. } else if(shading == aiShadingMode_Blinn) {
  384. materials[a].shading_model = "blinn";
  385. } else if(shading == aiShadingMode_NoShading) {
  386. materials[a].shading_model = "constant";
  387. } else if(shading == aiShadingMode_Gouraud) {
  388. materials[a].shading_model = "lambert";
  389. }
  390. }
  391. ReadMaterialSurface( materials[a].ambient, mat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT);
  392. if( !materials[a].ambient.texture.empty() ) numTextures++;
  393. ReadMaterialSurface( materials[a].diffuse, mat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE);
  394. if( !materials[a].diffuse.texture.empty() ) numTextures++;
  395. ReadMaterialSurface( materials[a].specular, mat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR);
  396. if( !materials[a].specular.texture.empty() ) numTextures++;
  397. ReadMaterialSurface( materials[a].emissive, mat, aiTextureType_EMISSIVE, AI_MATKEY_COLOR_EMISSIVE);
  398. if( !materials[a].emissive.texture.empty() ) numTextures++;
  399. ReadMaterialSurface( materials[a].reflective, mat, aiTextureType_REFLECTION, AI_MATKEY_COLOR_REFLECTIVE);
  400. if( !materials[a].reflective.texture.empty() ) numTextures++;
  401. ReadMaterialSurface( materials[a].transparent, mat, aiTextureType_OPACITY, AI_MATKEY_COLOR_TRANSPARENT);
  402. if( !materials[a].transparent.texture.empty() ) numTextures++;
  403. ReadMaterialSurface( materials[a].normal, mat, aiTextureType_NORMALS, NULL, 0, 0);
  404. if( !materials[a].normal.texture.empty() ) numTextures++;
  405. materials[a].shininess.exist = mat->Get( AI_MATKEY_SHININESS, materials[a].shininess.value) == aiReturn_SUCCESS;
  406. materials[a].transparency.exist = mat->Get( AI_MATKEY_OPACITY, materials[a].transparency.value) == aiReturn_SUCCESS;
  407. materials[a].transparency.value = 1 - materials[a].transparency.value;
  408. materials[a].index_refraction.exist = mat->Get( AI_MATKEY_REFRACTI, materials[a].index_refraction.value) == aiReturn_SUCCESS;
  409. }
  410. // output textures if present
  411. if( numTextures > 0 )
  412. {
  413. mOutput << startstr << "<library_images>" << endstr;
  414. PushTag();
  415. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  416. {
  417. const Material& mat = *it;
  418. WriteImageEntry( mat.ambient, mat.name + "-ambient-image");
  419. WriteImageEntry( mat.diffuse, mat.name + "-diffuse-image");
  420. WriteImageEntry( mat.specular, mat.name + "-specular-image");
  421. WriteImageEntry( mat.emissive, mat.name + "-emission-image");
  422. WriteImageEntry( mat.reflective, mat.name + "-reflective-image");
  423. WriteImageEntry( mat.transparent, mat.name + "-transparent-image");
  424. WriteImageEntry( mat.normal, mat.name + "-normal-image");
  425. }
  426. PopTag();
  427. mOutput << startstr << "</library_images>" << endstr;
  428. }
  429. // output effects - those are the actual carriers of information
  430. if( !materials.empty() )
  431. {
  432. mOutput << startstr << "<library_effects>" << endstr;
  433. PushTag();
  434. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  435. {
  436. const Material& mat = *it;
  437. // this is so ridiculous it must be right
  438. mOutput << startstr << "<effect id=\"" << XMLEscape(mat.name) << "-fx\" name=\"" << XMLEscape(mat.name) << "\">" << endstr;
  439. PushTag();
  440. mOutput << startstr << "<profile_COMMON>" << endstr;
  441. PushTag();
  442. // write sampler- and surface params for the texture entries
  443. WriteTextureParamEntry( mat.emissive, "emission", mat.name);
  444. WriteTextureParamEntry( mat.ambient, "ambient", mat.name);
  445. WriteTextureParamEntry( mat.diffuse, "diffuse", mat.name);
  446. WriteTextureParamEntry( mat.specular, "specular", mat.name);
  447. WriteTextureParamEntry( mat.reflective, "reflective", mat.name);
  448. WriteTextureParamEntry( mat.transparent, "transparent", mat.name);
  449. WriteTextureParamEntry( mat.normal, "normal", mat.name);
  450. mOutput << startstr << "<technique sid=\"standard\">" << endstr;
  451. PushTag();
  452. mOutput << startstr << "<" << mat.shading_model << ">" << endstr;
  453. PushTag();
  454. WriteTextureColorEntry( mat.emissive, "emission", mat.name + "-emission-sampler");
  455. WriteTextureColorEntry( mat.ambient, "ambient", mat.name + "-ambient-sampler");
  456. WriteTextureColorEntry( mat.diffuse, "diffuse", mat.name + "-diffuse-sampler");
  457. WriteTextureColorEntry( mat.specular, "specular", mat.name + "-specular-sampler");
  458. WriteFloatEntry(mat.shininess, "shininess");
  459. WriteTextureColorEntry( mat.reflective, "reflective", mat.name + "-reflective-sampler");
  460. WriteTextureColorEntry( mat.transparent, "transparent", mat.name + "-transparent-sampler");
  461. WriteFloatEntry(mat.transparency, "transparency");
  462. WriteFloatEntry(mat.index_refraction, "index_of_refraction");
  463. if(! mat.normal.texture.empty()) {
  464. WriteTextureColorEntry( mat.normal, "bump", mat.name + "-normal-sampler");
  465. }
  466. PopTag();
  467. mOutput << startstr << "</" << mat.shading_model << ">" << endstr;
  468. PopTag();
  469. mOutput << startstr << "</technique>" << endstr;
  470. PopTag();
  471. mOutput << startstr << "</profile_COMMON>" << endstr;
  472. PopTag();
  473. mOutput << startstr << "</effect>" << endstr;
  474. }
  475. PopTag();
  476. mOutput << startstr << "</library_effects>" << endstr;
  477. // write materials - they're just effect references
  478. mOutput << startstr << "<library_materials>" << endstr;
  479. PushTag();
  480. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  481. {
  482. const Material& mat = *it;
  483. mOutput << startstr << "<material id=\"" << XMLEscape(mat.name) << "\" name=\"" << mat.name << "\">" << endstr;
  484. PushTag();
  485. mOutput << startstr << "<instance_effect url=\"#" << XMLEscape(mat.name) << "-fx\"/>" << endstr;
  486. PopTag();
  487. mOutput << startstr << "</material>" << endstr;
  488. }
  489. PopTag();
  490. mOutput << startstr << "</library_materials>" << endstr;
  491. }
  492. }
  493. // ------------------------------------------------------------------------------------------------
  494. // Writes the geometry library
  495. void ColladaExporter::WriteGeometryLibrary()
  496. {
  497. mOutput << startstr << "<library_geometries>" << endstr;
  498. PushTag();
  499. for( size_t a = 0; a < mScene->mNumMeshes; ++a)
  500. WriteGeometry( a);
  501. PopTag();
  502. mOutput << startstr << "</library_geometries>" << endstr;
  503. }
  504. // ------------------------------------------------------------------------------------------------
  505. // Writes the given mesh
  506. void ColladaExporter::WriteGeometry( size_t pIndex)
  507. {
  508. const aiMesh* mesh = mScene->mMeshes[pIndex];
  509. const std::string idstr = GetMeshId( pIndex);
  510. const std::string idstrEscaped = XMLEscape(idstr);
  511. if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  512. return;
  513. // opening tag
  514. mOutput << startstr << "<geometry id=\"" << idstrEscaped << "\" name=\"" << idstrEscaped << "_name\" >" << endstr;
  515. PushTag();
  516. mOutput << startstr << "<mesh>" << endstr;
  517. PushTag();
  518. // Positions
  519. WriteFloatArray( idstr + "-positions", FloatType_Vector, (float*) mesh->mVertices, mesh->mNumVertices);
  520. // Normals, if any
  521. if( mesh->HasNormals() )
  522. WriteFloatArray( idstr + "-normals", FloatType_Vector, (float*) mesh->mNormals, mesh->mNumVertices);
  523. // texture coords
  524. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  525. {
  526. if( mesh->HasTextureCoords( a) )
  527. {
  528. WriteFloatArray( idstr + "-tex" + boost::lexical_cast<std::string> (a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2,
  529. (float*) mesh->mTextureCoords[a], mesh->mNumVertices);
  530. }
  531. }
  532. // vertex colors
  533. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  534. {
  535. if( mesh->HasVertexColors( a) )
  536. WriteFloatArray( idstr + "-color" + boost::lexical_cast<std::string> (a), FloatType_Color, (float*) mesh->mColors[a], mesh->mNumVertices);
  537. }
  538. // assemble vertex structure
  539. mOutput << startstr << "<vertices id=\"" << idstrEscaped << "-vertices" << "\">" << endstr;
  540. PushTag();
  541. mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << idstrEscaped << "-positions\" />" << endstr;
  542. if( mesh->HasNormals() )
  543. mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << idstrEscaped << "-normals\" />" << endstr;
  544. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  545. {
  546. if( mesh->HasTextureCoords( a) )
  547. mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" " /*<< "set=\"" << a << "\"" */ << " />" << endstr;
  548. }
  549. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
  550. {
  551. if( mesh->HasVertexColors( a) )
  552. mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << idstrEscaped << "-color" << a << "\" " /*<< set=\"" << a << "\"" */ << " />" << endstr;
  553. }
  554. PopTag();
  555. mOutput << startstr << "</vertices>" << endstr;
  556. // count the number of lines, triangles and polygon meshes
  557. int countLines = 0;
  558. int countPoly = 0;
  559. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  560. {
  561. if (mesh->mFaces[a].mNumIndices == 2) countLines++;
  562. else if (mesh->mFaces[a].mNumIndices >= 3) countPoly++;
  563. }
  564. // lines
  565. if (countLines)
  566. {
  567. mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr;
  568. PushTag();
  569. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
  570. mOutput << startstr << "<p>";
  571. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  572. {
  573. const aiFace& face = mesh->mFaces[a];
  574. if (face.mNumIndices != 2) continue;
  575. for( size_t b = 0; b < face.mNumIndices; ++b )
  576. mOutput << face.mIndices[b] << " ";
  577. }
  578. mOutput << "</p>" << endstr;
  579. PopTag();
  580. mOutput << startstr << "</lines>" << endstr;
  581. }
  582. // triangle - dont use it, because compatibility problems
  583. // polygons
  584. if (countPoly)
  585. {
  586. mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr;
  587. PushTag();
  588. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
  589. mOutput << startstr << "<vcount>";
  590. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  591. {
  592. if (mesh->mFaces[a].mNumIndices < 3) continue;
  593. mOutput << mesh->mFaces[a].mNumIndices << " ";
  594. }
  595. mOutput << "</vcount>" << endstr;
  596. mOutput << startstr << "<p>";
  597. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  598. {
  599. const aiFace& face = mesh->mFaces[a];
  600. if (face.mNumIndices < 3) continue;
  601. for( size_t b = 0; b < face.mNumIndices; ++b )
  602. mOutput << face.mIndices[b] << " ";
  603. }
  604. mOutput << "</p>" << endstr;
  605. PopTag();
  606. mOutput << startstr << "</polylist>" << endstr;
  607. }
  608. // closing tags
  609. PopTag();
  610. mOutput << startstr << "</mesh>" << endstr;
  611. PopTag();
  612. mOutput << startstr << "</geometry>" << endstr;
  613. }
  614. // ------------------------------------------------------------------------------------------------
  615. // Writes a float array of the given type
  616. void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataType pType, const float* pData, size_t pElementCount)
  617. {
  618. size_t floatsPerElement = 0;
  619. switch( pType )
  620. {
  621. case FloatType_Vector: floatsPerElement = 3; break;
  622. case FloatType_TexCoord2: floatsPerElement = 2; break;
  623. case FloatType_TexCoord3: floatsPerElement = 3; break;
  624. case FloatType_Color: floatsPerElement = 3; break;
  625. default:
  626. return;
  627. }
  628. std::string arrayId = pIdString + "-array";
  629. mOutput << startstr << "<source id=\"" << XMLEscape(pIdString) << "\" name=\"" << XMLEscape(pIdString) << "\">" << endstr;
  630. PushTag();
  631. // source array
  632. mOutput << startstr << "<float_array id=\"" << XMLEscape(arrayId) << "\" count=\"" << pElementCount * floatsPerElement << "\"> ";
  633. PushTag();
  634. if( pType == FloatType_TexCoord2 )
  635. {
  636. for( size_t a = 0; a < pElementCount; ++a )
  637. {
  638. mOutput << pData[a*3+0] << " ";
  639. mOutput << pData[a*3+1] << " ";
  640. }
  641. }
  642. else if( pType == FloatType_Color )
  643. {
  644. for( size_t a = 0; a < pElementCount; ++a )
  645. {
  646. mOutput << pData[a*4+0] << " ";
  647. mOutput << pData[a*4+1] << " ";
  648. mOutput << pData[a*4+2] << " ";
  649. }
  650. }
  651. else
  652. {
  653. for( size_t a = 0; a < pElementCount * floatsPerElement; ++a )
  654. mOutput << pData[a] << " ";
  655. }
  656. mOutput << "</float_array>" << endstr;
  657. PopTag();
  658. // the usual Collada fun. Let's bloat it even more!
  659. mOutput << startstr << "<technique_common>" << endstr;
  660. PushTag();
  661. mOutput << startstr << "<accessor count=\"" << pElementCount << "\" offset=\"0\" source=\"#" << arrayId << "\" stride=\"" << floatsPerElement << "\">" << endstr;
  662. PushTag();
  663. switch( pType )
  664. {
  665. case FloatType_Vector:
  666. mOutput << startstr << "<param name=\"X\" type=\"float\" />" << endstr;
  667. mOutput << startstr << "<param name=\"Y\" type=\"float\" />" << endstr;
  668. mOutput << startstr << "<param name=\"Z\" type=\"float\" />" << endstr;
  669. break;
  670. case FloatType_TexCoord2:
  671. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  672. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  673. break;
  674. case FloatType_TexCoord3:
  675. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  676. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  677. mOutput << startstr << "<param name=\"P\" type=\"float\" />" << endstr;
  678. break;
  679. case FloatType_Color:
  680. mOutput << startstr << "<param name=\"R\" type=\"float\" />" << endstr;
  681. mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr;
  682. mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr;
  683. break;
  684. }
  685. PopTag();
  686. mOutput << startstr << "</accessor>" << endstr;
  687. PopTag();
  688. mOutput << startstr << "</technique_common>" << endstr;
  689. PopTag();
  690. mOutput << startstr << "</source>" << endstr;
  691. }
  692. // ------------------------------------------------------------------------------------------------
  693. // Writes the scene library
  694. void ColladaExporter::WriteSceneLibrary()
  695. {
  696. const std::string scene_name_escaped = XMLEscape(mScene->mRootNode->mName.C_Str());
  697. mOutput << startstr << "<library_visual_scenes>" << endstr;
  698. PushTag();
  699. mOutput << startstr << "<visual_scene id=\"" + scene_name_escaped + "\" name=\"" + scene_name_escaped + "\">" << endstr;
  700. PushTag();
  701. // start recursive write at the root node
  702. for( size_t a = 0; a < mScene->mRootNode->mNumChildren; ++a )
  703. WriteNode( mScene->mRootNode->mChildren[a]);
  704. PopTag();
  705. mOutput << startstr << "</visual_scene>" << endstr;
  706. PopTag();
  707. mOutput << startstr << "</library_visual_scenes>" << endstr;
  708. }
  709. // ------------------------------------------------------------------------------------------------
  710. // Recursively writes the given node
  711. void ColladaExporter::WriteNode(aiNode* pNode)
  712. {
  713. // the must have a name
  714. if (pNode->mName.length == 0)
  715. {
  716. std::stringstream ss;
  717. ss << "Node_" << pNode;
  718. pNode->mName.Set(ss.str());
  719. }
  720. const std::string node_name_escaped = XMLEscape(pNode->mName.data);
  721. mOutput << startstr << "<node id=\"" << node_name_escaped << "\" name=\"" << node_name_escaped << "\">" << endstr;
  722. PushTag();
  723. // write transformation - we can directly put the matrix there
  724. // TODO: (thom) decompose into scale - rot - quad to allow adressing it by animations afterwards
  725. const aiMatrix4x4& mat = pNode->mTransformation;
  726. mOutput << startstr << "<matrix>";
  727. mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
  728. mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " ";
  729. mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " ";
  730. mOutput << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4;
  731. mOutput << "</matrix>" << endstr;
  732. // instance every geometry
  733. for( size_t a = 0; a < pNode->mNumMeshes; ++a )
  734. {
  735. const aiMesh* mesh = mScene->mMeshes[pNode->mMeshes[a]];
  736. // do not instanciate mesh if empty. I wonder how this could happen
  737. if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  738. continue;
  739. mOutput << startstr << "<instance_geometry url=\"#" << XMLEscape(GetMeshId( pNode->mMeshes[a])) << "\">" << endstr;
  740. PushTag();
  741. mOutput << startstr << "<bind_material>" << endstr;
  742. PushTag();
  743. mOutput << startstr << "<technique_common>" << endstr;
  744. PushTag();
  745. mOutput << startstr << "<instance_material symbol=\"defaultMaterial\" target=\"#" << XMLEscape(materials[mesh->mMaterialIndex].name) << "\" />" << endstr;
  746. PopTag();
  747. mOutput << startstr << "</technique_common>" << endstr;
  748. PopTag();
  749. mOutput << startstr << "</bind_material>" << endstr;
  750. PopTag();
  751. mOutput << startstr << "</instance_geometry>" << endstr;
  752. }
  753. // recurse into subnodes
  754. for( size_t a = 0; a < pNode->mNumChildren; ++a )
  755. WriteNode( pNode->mChildren[a]);
  756. PopTag();
  757. mOutput << startstr << "</node>" << endstr;
  758. }
  759. #endif
  760. #endif