ColladaExporter.cpp 33 KB

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