ColladaExporter.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2017, 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 <assimp/SceneCombiner.h>
  39. #include "StringUtils.h"
  40. #include "XMLTools.h"
  41. #include <assimp/DefaultIOSystem.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 == '/' || *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].index_refraction.exist = mat->Get( AI_MATKEY_REFRACTI, materials[a].index_refraction.value) == aiReturn_SUCCESS;
  584. }
  585. // output textures if present
  586. if( numTextures > 0 )
  587. {
  588. mOutput << startstr << "<library_images>" << endstr;
  589. PushTag();
  590. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  591. {
  592. const Material& mat = *it;
  593. WriteImageEntry( mat.ambient, mat.name + "-ambient-image");
  594. WriteImageEntry( mat.diffuse, mat.name + "-diffuse-image");
  595. WriteImageEntry( mat.specular, mat.name + "-specular-image");
  596. WriteImageEntry( mat.emissive, mat.name + "-emission-image");
  597. WriteImageEntry( mat.reflective, mat.name + "-reflective-image");
  598. WriteImageEntry( mat.transparent, mat.name + "-transparent-image");
  599. WriteImageEntry( mat.normal, mat.name + "-normal-image");
  600. }
  601. PopTag();
  602. mOutput << startstr << "</library_images>" << endstr;
  603. }
  604. // output effects - those are the actual carriers of information
  605. if( !materials.empty() )
  606. {
  607. mOutput << startstr << "<library_effects>" << endstr;
  608. PushTag();
  609. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  610. {
  611. const Material& mat = *it;
  612. // this is so ridiculous it must be right
  613. mOutput << startstr << "<effect id=\"" << XMLEscape(mat.name) << "-fx\" name=\"" << XMLEscape(mat.name) << "\">" << endstr;
  614. PushTag();
  615. mOutput << startstr << "<profile_COMMON>" << endstr;
  616. PushTag();
  617. // write sampler- and surface params for the texture entries
  618. WriteTextureParamEntry( mat.emissive, "emission", mat.name);
  619. WriteTextureParamEntry( mat.ambient, "ambient", mat.name);
  620. WriteTextureParamEntry( mat.diffuse, "diffuse", mat.name);
  621. WriteTextureParamEntry( mat.specular, "specular", mat.name);
  622. WriteTextureParamEntry( mat.reflective, "reflective", mat.name);
  623. WriteTextureParamEntry( mat.transparent, "transparent", mat.name);
  624. WriteTextureParamEntry( mat.normal, "normal", mat.name);
  625. mOutput << startstr << "<technique sid=\"standard\">" << endstr;
  626. PushTag();
  627. mOutput << startstr << "<" << mat.shading_model << ">" << endstr;
  628. PushTag();
  629. WriteTextureColorEntry( mat.emissive, "emission", mat.name + "-emission-sampler");
  630. WriteTextureColorEntry( mat.ambient, "ambient", mat.name + "-ambient-sampler");
  631. WriteTextureColorEntry( mat.diffuse, "diffuse", mat.name + "-diffuse-sampler");
  632. WriteTextureColorEntry( mat.specular, "specular", mat.name + "-specular-sampler");
  633. WriteFloatEntry(mat.shininess, "shininess");
  634. WriteTextureColorEntry( mat.reflective, "reflective", mat.name + "-reflective-sampler");
  635. WriteTextureColorEntry( mat.transparent, "transparent", mat.name + "-transparent-sampler");
  636. WriteFloatEntry(mat.transparency, "transparency");
  637. WriteFloatEntry(mat.index_refraction, "index_of_refraction");
  638. if(! mat.normal.texture.empty()) {
  639. WriteTextureColorEntry( mat.normal, "bump", mat.name + "-normal-sampler");
  640. }
  641. PopTag();
  642. mOutput << startstr << "</" << mat.shading_model << ">" << endstr;
  643. PopTag();
  644. mOutput << startstr << "</technique>" << endstr;
  645. PopTag();
  646. mOutput << startstr << "</profile_COMMON>" << endstr;
  647. PopTag();
  648. mOutput << startstr << "</effect>" << endstr;
  649. }
  650. PopTag();
  651. mOutput << startstr << "</library_effects>" << endstr;
  652. // write materials - they're just effect references
  653. mOutput << startstr << "<library_materials>" << endstr;
  654. PushTag();
  655. for( std::vector<Material>::const_iterator it = materials.begin(); it != materials.end(); ++it )
  656. {
  657. const Material& mat = *it;
  658. mOutput << startstr << "<material id=\"" << XMLEscape(mat.name) << "\" name=\"" << mat.name << "\">" << endstr;
  659. PushTag();
  660. mOutput << startstr << "<instance_effect url=\"#" << XMLEscape(mat.name) << "-fx\"/>" << endstr;
  661. PopTag();
  662. mOutput << startstr << "</material>" << endstr;
  663. }
  664. PopTag();
  665. mOutput << startstr << "</library_materials>" << endstr;
  666. }
  667. }
  668. // ------------------------------------------------------------------------------------------------
  669. // Writes the controller library
  670. void ColladaExporter::WriteControllerLibrary()
  671. {
  672. mOutput << startstr << "<library_controllers>" << endstr;
  673. PushTag();
  674. for( size_t a = 0; a < mScene->mNumMeshes; ++a)
  675. WriteController( a);
  676. PopTag();
  677. mOutput << startstr << "</library_controllers>" << endstr;
  678. }
  679. // ------------------------------------------------------------------------------------------------
  680. // Writes a skin controller of the given mesh
  681. void ColladaExporter::WriteController( size_t pIndex)
  682. {
  683. const aiMesh* mesh = mScene->mMeshes[pIndex];
  684. const std::string idstr = GetMeshId( pIndex);
  685. const std::string idstrEscaped = XMLEscape(idstr);
  686. if ( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  687. return;
  688. if ( mesh->mNumBones == 0 )
  689. return;
  690. mOutput << startstr << "<controller id=\"" << idstrEscaped << "-skin\" ";
  691. mOutput << "name=\"skinCluster" << pIndex << "\">"<< endstr;
  692. PushTag();
  693. mOutput << startstr << "<skin source=\"#" << idstrEscaped << "\">" << endstr;
  694. PushTag();
  695. // bind pose matrix
  696. mOutput << startstr << "<bind_shape_matrix>" << endstr;
  697. PushTag();
  698. // I think it is identity in general cases.
  699. aiMatrix4x4 mat;
  700. mOutput << startstr << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << endstr;
  701. mOutput << startstr << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << endstr;
  702. mOutput << startstr << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << endstr;
  703. mOutput << startstr << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4 << endstr;
  704. PopTag();
  705. mOutput << startstr << "</bind_shape_matrix>" << endstr;
  706. mOutput << startstr << "<source id=\"" << idstrEscaped << "-skin-joints\" name=\"" << idstrEscaped << "-skin-joints\">" << endstr;
  707. PushTag();
  708. mOutput << startstr << "<Name_array id=\"" << idstrEscaped << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\">";
  709. for( size_t i = 0; i < mesh->mNumBones; ++i )
  710. mOutput << XMLEscape(mesh->mBones[i]->mName.C_Str()) << " ";
  711. mOutput << "</Name_array>" << endstr;
  712. mOutput << startstr << "<technique_common>" << endstr;
  713. PushTag();
  714. mOutput << startstr << "<accessor source=\"#" << idstrEscaped << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\" stride=\"" << 1 << "\">" << endstr;
  715. PushTag();
  716. mOutput << startstr << "<param name=\"JOINT\" type=\"Name\"></param>" << endstr;
  717. PopTag();
  718. mOutput << startstr << "</accessor>" << endstr;
  719. PopTag();
  720. mOutput << startstr << "</technique_common>" << endstr;
  721. PopTag();
  722. mOutput << startstr << "</source>" << endstr;
  723. std::vector<ai_real> bind_poses;
  724. bind_poses.reserve(mesh->mNumBones * 16);
  725. for( size_t i = 0; i < mesh->mNumBones; ++i)
  726. for( size_t j = 0; j < 4; ++j)
  727. bind_poses.insert(bind_poses.end(), mesh->mBones[i]->mOffsetMatrix[j], mesh->mBones[i]->mOffsetMatrix[j] + 4);
  728. WriteFloatArray( idstr + "-skin-bind_poses", FloatType_Mat4x4, (const ai_real*) bind_poses.data(), bind_poses.size() / 16);
  729. bind_poses.clear();
  730. std::vector<ai_real> skin_weights;
  731. skin_weights.reserve(mesh->mNumVertices * mesh->mNumBones);
  732. for( size_t i = 0; i < mesh->mNumBones; ++i)
  733. for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  734. skin_weights.push_back(mesh->mBones[i]->mWeights[j].mWeight);
  735. WriteFloatArray( idstr + "-skin-weights", FloatType_Weight, (const ai_real*) skin_weights.data(), skin_weights.size());
  736. skin_weights.clear();
  737. mOutput << startstr << "<joints>" << endstr;
  738. PushTag();
  739. mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstrEscaped << "-skin-joints\"></input>" << endstr;
  740. mOutput << startstr << "<input semantic=\"INV_BIND_MATRIX\" source=\"#" << idstrEscaped << "-skin-bind_poses\"></input>" << endstr;
  741. PopTag();
  742. mOutput << startstr << "</joints>" << endstr;
  743. mOutput << startstr << "<vertex_weights count=\"" << mesh->mNumVertices << "\">" << endstr;
  744. PushTag();
  745. mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstrEscaped << "-skin-joints\" offset=\"0\"></input>" << endstr;
  746. mOutput << startstr << "<input semantic=\"WEIGHT\" source=\"#" << idstrEscaped << "-skin-weights\" offset=\"1\"></input>" << endstr;
  747. mOutput << startstr << "<vcount>";
  748. std::vector<ai_uint> num_influences(mesh->mNumVertices, (ai_uint)0);
  749. for( size_t i = 0; i < mesh->mNumBones; ++i)
  750. for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  751. ++num_influences[mesh->mBones[i]->mWeights[j].mVertexId];
  752. for( size_t i = 0; i < mesh->mNumVertices; ++i)
  753. mOutput << num_influences[i] << " ";
  754. mOutput << "</vcount>" << endstr;
  755. mOutput << startstr << "<v>";
  756. ai_uint joint_weight_indices_length = 0;
  757. std::vector<ai_uint> accum_influences;
  758. accum_influences.reserve(num_influences.size());
  759. for( size_t i = 0; i < num_influences.size(); ++i)
  760. {
  761. accum_influences.push_back(joint_weight_indices_length);
  762. joint_weight_indices_length += num_influences[i];
  763. }
  764. ai_uint weight_index = 0;
  765. std::vector<ai_int> joint_weight_indices(2 * joint_weight_indices_length, (ai_int)-1);
  766. for( size_t i = 0; i < mesh->mNumBones; ++i)
  767. for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
  768. {
  769. unsigned int vId = mesh->mBones[i]->mWeights[j].mVertexId;
  770. for( size_t k = 0; k < num_influences[vId]; ++k)
  771. {
  772. if (joint_weight_indices[2 * (accum_influences[vId] + k)] == -1)
  773. {
  774. joint_weight_indices[2 * (accum_influences[vId] + k)] = i;
  775. joint_weight_indices[2 * (accum_influences[vId] + k) + 1] = weight_index;
  776. break;
  777. }
  778. }
  779. ++weight_index;
  780. }
  781. for( size_t i = 0; i < joint_weight_indices.size(); ++i)
  782. mOutput << joint_weight_indices[i] << " ";
  783. num_influences.clear();
  784. accum_influences.clear();
  785. joint_weight_indices.clear();
  786. mOutput << "</v>" << endstr;
  787. PopTag();
  788. mOutput << startstr << "</vertex_weights>" << endstr;
  789. PopTag();
  790. mOutput << startstr << "</skin>" << endstr;
  791. PopTag();
  792. mOutput << startstr << "</controller>" << endstr;
  793. }
  794. // ------------------------------------------------------------------------------------------------
  795. // Writes the geometry library
  796. void ColladaExporter::WriteGeometryLibrary()
  797. {
  798. mOutput << startstr << "<library_geometries>" << endstr;
  799. PushTag();
  800. for( size_t a = 0; a < mScene->mNumMeshes; ++a)
  801. WriteGeometry( a);
  802. PopTag();
  803. mOutput << startstr << "</library_geometries>" << endstr;
  804. }
  805. // ------------------------------------------------------------------------------------------------
  806. // Writes the given mesh
  807. void ColladaExporter::WriteGeometry( size_t pIndex)
  808. {
  809. const aiMesh* mesh = mScene->mMeshes[pIndex];
  810. const std::string idstr = GetMeshId( pIndex);
  811. const std::string idstrEscaped = XMLEscape(idstr);
  812. if ( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  813. return;
  814. // opening tag
  815. mOutput << startstr << "<geometry id=\"" << idstrEscaped << "\" name=\"" << idstrEscaped << "_name\" >" << endstr;
  816. PushTag();
  817. mOutput << startstr << "<mesh>" << endstr;
  818. PushTag();
  819. // Positions
  820. WriteFloatArray( idstr + "-positions", FloatType_Vector, (ai_real*) mesh->mVertices, mesh->mNumVertices);
  821. // Normals, if any
  822. if( mesh->HasNormals() )
  823. WriteFloatArray( idstr + "-normals", FloatType_Vector, (ai_real*) mesh->mNormals, mesh->mNumVertices);
  824. // texture coords
  825. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  826. {
  827. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  828. {
  829. WriteFloatArray( idstr + "-tex" + to_string(a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2,
  830. (ai_real*) mesh->mTextureCoords[a], mesh->mNumVertices);
  831. }
  832. }
  833. // vertex colors
  834. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
  835. {
  836. if( mesh->HasVertexColors(static_cast<unsigned int>(a)) )
  837. WriteFloatArray( idstr + "-color" + to_string(a), FloatType_Color, (ai_real*) mesh->mColors[a], mesh->mNumVertices);
  838. }
  839. // assemble vertex structure
  840. // Only write input for POSITION since we will write other as shared inputs in polygon definition
  841. mOutput << startstr << "<vertices id=\"" << idstrEscaped << "-vertices" << "\">" << endstr;
  842. PushTag();
  843. mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << idstrEscaped << "-positions\" />" << endstr;
  844. PopTag();
  845. mOutput << startstr << "</vertices>" << endstr;
  846. // count the number of lines, triangles and polygon meshes
  847. int countLines = 0;
  848. int countPoly = 0;
  849. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  850. {
  851. if (mesh->mFaces[a].mNumIndices == 2) countLines++;
  852. else if (mesh->mFaces[a].mNumIndices >= 3) countPoly++;
  853. }
  854. // lines
  855. if (countLines)
  856. {
  857. mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr;
  858. PushTag();
  859. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
  860. if( mesh->HasNormals() )
  861. mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << idstrEscaped << "-normals\" />" << endstr;
  862. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  863. {
  864. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  865. mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  866. }
  867. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
  868. {
  869. if( mesh->HasVertexColors(static_cast<unsigned int>(a) ) )
  870. mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << idstrEscaped << "-color" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  871. }
  872. mOutput << startstr << "<p>";
  873. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  874. {
  875. const aiFace& face = mesh->mFaces[a];
  876. if (face.mNumIndices != 2) continue;
  877. for( size_t b = 0; b < face.mNumIndices; ++b )
  878. mOutput << face.mIndices[b] << " ";
  879. }
  880. mOutput << "</p>" << endstr;
  881. PopTag();
  882. mOutput << startstr << "</lines>" << endstr;
  883. }
  884. // triangle - don't use it, because compatibility problems
  885. // polygons
  886. if (countPoly)
  887. {
  888. mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr;
  889. PushTag();
  890. mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
  891. if( mesh->HasNormals() )
  892. mOutput << startstr << "<input offset=\"0\" semantic=\"NORMAL\" source=\"#" << idstrEscaped << "-normals\" />" << endstr;
  893. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  894. {
  895. if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
  896. mOutput << startstr << "<input offset=\"0\" semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  897. }
  898. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
  899. {
  900. if( mesh->HasVertexColors(static_cast<unsigned int>(a) ) )
  901. mOutput << startstr << "<input offset=\"0\" semantic=\"COLOR\" source=\"#" << idstrEscaped << "-color" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
  902. }
  903. mOutput << startstr << "<vcount>";
  904. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  905. {
  906. if (mesh->mFaces[a].mNumIndices < 3) continue;
  907. mOutput << mesh->mFaces[a].mNumIndices << " ";
  908. }
  909. mOutput << "</vcount>" << endstr;
  910. mOutput << startstr << "<p>";
  911. for( size_t a = 0; a < mesh->mNumFaces; ++a )
  912. {
  913. const aiFace& face = mesh->mFaces[a];
  914. if (face.mNumIndices < 3) continue;
  915. for( size_t b = 0; b < face.mNumIndices; ++b )
  916. mOutput << face.mIndices[b] << " ";
  917. }
  918. mOutput << "</p>" << endstr;
  919. PopTag();
  920. mOutput << startstr << "</polylist>" << endstr;
  921. }
  922. // closing tags
  923. PopTag();
  924. mOutput << startstr << "</mesh>" << endstr;
  925. PopTag();
  926. mOutput << startstr << "</geometry>" << endstr;
  927. }
  928. // ------------------------------------------------------------------------------------------------
  929. // Writes a float array of the given type
  930. void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataType pType, const ai_real* pData, size_t pElementCount)
  931. {
  932. size_t floatsPerElement = 0;
  933. switch( pType )
  934. {
  935. case FloatType_Vector: floatsPerElement = 3; break;
  936. case FloatType_TexCoord2: floatsPerElement = 2; break;
  937. case FloatType_TexCoord3: floatsPerElement = 3; break;
  938. case FloatType_Color: floatsPerElement = 3; break;
  939. case FloatType_Mat4x4: floatsPerElement = 16; break;
  940. case FloatType_Weight: floatsPerElement = 1; break;
  941. default:
  942. return;
  943. }
  944. std::string arrayId = pIdString + "-array";
  945. mOutput << startstr << "<source id=\"" << XMLEscape(pIdString) << "\" name=\"" << XMLEscape(pIdString) << "\">" << endstr;
  946. PushTag();
  947. // source array
  948. mOutput << startstr << "<float_array id=\"" << XMLEscape(arrayId) << "\" count=\"" << pElementCount * floatsPerElement << "\"> ";
  949. PushTag();
  950. if( pType == FloatType_TexCoord2 )
  951. {
  952. for( size_t a = 0; a < pElementCount; ++a )
  953. {
  954. mOutput << pData[a*3+0] << " ";
  955. mOutput << pData[a*3+1] << " ";
  956. }
  957. }
  958. else if( pType == FloatType_Color )
  959. {
  960. for( size_t a = 0; a < pElementCount; ++a )
  961. {
  962. mOutput << pData[a*4+0] << " ";
  963. mOutput << pData[a*4+1] << " ";
  964. mOutput << pData[a*4+2] << " ";
  965. }
  966. }
  967. else
  968. {
  969. for( size_t a = 0; a < pElementCount * floatsPerElement; ++a )
  970. mOutput << pData[a] << " ";
  971. }
  972. mOutput << "</float_array>" << endstr;
  973. PopTag();
  974. // the usual Collada fun. Let's bloat it even more!
  975. mOutput << startstr << "<technique_common>" << endstr;
  976. PushTag();
  977. mOutput << startstr << "<accessor count=\"" << pElementCount << "\" offset=\"0\" source=\"#" << arrayId << "\" stride=\"" << floatsPerElement << "\">" << endstr;
  978. PushTag();
  979. switch( pType )
  980. {
  981. case FloatType_Vector:
  982. mOutput << startstr << "<param name=\"X\" type=\"float\" />" << endstr;
  983. mOutput << startstr << "<param name=\"Y\" type=\"float\" />" << endstr;
  984. mOutput << startstr << "<param name=\"Z\" type=\"float\" />" << endstr;
  985. break;
  986. case FloatType_TexCoord2:
  987. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  988. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  989. break;
  990. case FloatType_TexCoord3:
  991. mOutput << startstr << "<param name=\"S\" type=\"float\" />" << endstr;
  992. mOutput << startstr << "<param name=\"T\" type=\"float\" />" << endstr;
  993. mOutput << startstr << "<param name=\"P\" type=\"float\" />" << endstr;
  994. break;
  995. case FloatType_Color:
  996. mOutput << startstr << "<param name=\"R\" type=\"float\" />" << endstr;
  997. mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr;
  998. mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr;
  999. break;
  1000. case FloatType_Mat4x4:
  1001. mOutput << startstr << "<param name=\"TRANSFORM\" type=\"float4x4\" />" << endstr;
  1002. break;
  1003. case FloatType_Weight:
  1004. mOutput << startstr << "<param name=\"WEIGHT\" type=\"float\" />" << endstr;
  1005. break;
  1006. }
  1007. PopTag();
  1008. mOutput << startstr << "</accessor>" << endstr;
  1009. PopTag();
  1010. mOutput << startstr << "</technique_common>" << endstr;
  1011. PopTag();
  1012. mOutput << startstr << "</source>" << endstr;
  1013. }
  1014. // ------------------------------------------------------------------------------------------------
  1015. // Writes the scene library
  1016. void ColladaExporter::WriteSceneLibrary()
  1017. {
  1018. const std::string scene_name_escaped = XMLEscape(mScene->mRootNode->mName.C_Str());
  1019. mOutput << startstr << "<library_visual_scenes>" << endstr;
  1020. PushTag();
  1021. mOutput << startstr << "<visual_scene id=\"" + scene_name_escaped + "\" name=\"" + scene_name_escaped + "\">" << endstr;
  1022. PushTag();
  1023. // start recursive write at the root node
  1024. for( size_t a = 0; a < mScene->mRootNode->mNumChildren; ++a )
  1025. WriteNode( mScene, mScene->mRootNode->mChildren[a]);
  1026. PopTag();
  1027. mOutput << startstr << "</visual_scene>" << endstr;
  1028. PopTag();
  1029. mOutput << startstr << "</library_visual_scenes>" << endstr;
  1030. }
  1031. // ------------------------------------------------------------------------------------------------
  1032. // Helper to find a bone by name in the scene
  1033. aiBone* findBone( const aiScene* scene, const char * name) {
  1034. for (size_t m=0; m<scene->mNumMeshes; m++) {
  1035. aiMesh * mesh = scene->mMeshes[m];
  1036. for (size_t b=0; b<mesh->mNumBones; b++) {
  1037. aiBone * bone = mesh->mBones[b];
  1038. if (0 == strcmp(name, bone->mName.C_Str())) {
  1039. return bone;
  1040. }
  1041. }
  1042. }
  1043. return NULL;
  1044. }
  1045. // ------------------------------------------------------------------------------------------------
  1046. // Recursively writes the given node
  1047. void ColladaExporter::WriteNode( const aiScene* pScene, aiNode* pNode)
  1048. {
  1049. // the node must have a name
  1050. if (pNode->mName.length == 0)
  1051. {
  1052. std::stringstream ss;
  1053. ss << "Node_" << pNode;
  1054. pNode->mName.Set(ss.str());
  1055. }
  1056. // If the node is associated with a bone, it is a joint node (JOINT)
  1057. // otherwise it is a normal node (NODE)
  1058. const char * node_type;
  1059. bool is_joint, is_skeleton_root = false;
  1060. if (NULL == findBone(pScene, pNode->mName.C_Str())) {
  1061. node_type = "NODE";
  1062. is_joint = false;
  1063. } else {
  1064. node_type = "JOINT";
  1065. is_joint = true;
  1066. if(!pNode->mParent || NULL == findBone(pScene, pNode->mParent->mName.C_Str()))
  1067. is_skeleton_root = true;
  1068. }
  1069. const std::string node_name_escaped = XMLEscape(pNode->mName.data);
  1070. mOutput << startstr
  1071. << "<node ";
  1072. if(is_skeleton_root)
  1073. mOutput << "id=\"" << "skeleton_root" << "\" "; // For now, only support one skeleton in a scene.
  1074. mOutput << (is_joint ? "s" : "") << "id=\"" << node_name_escaped;
  1075. mOutput << "\" name=\"" << node_name_escaped
  1076. << "\" type=\"" << node_type
  1077. << "\">" << endstr;
  1078. PushTag();
  1079. // write transformation - we can directly put the matrix there
  1080. // TODO: (thom) decompose into scale - rot - quad to allow addressing it by animations afterwards
  1081. const aiMatrix4x4& mat = pNode->mTransformation;
  1082. mOutput << startstr << "<matrix sid=\"transform\">";
  1083. mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
  1084. mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " ";
  1085. mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " ";
  1086. mOutput << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4;
  1087. mOutput << "</matrix>" << endstr;
  1088. if(pNode->mNumMeshes==0){
  1089. //check if it is a camera node
  1090. for(size_t i=0; i<mScene->mNumCameras; i++){
  1091. if(mScene->mCameras[i]->mName == pNode->mName){
  1092. mOutput << startstr <<"<instance_camera url=\"#" << node_name_escaped << "-camera\"/>" << endstr;
  1093. break;
  1094. }
  1095. }
  1096. //check if it is a light node
  1097. for(size_t i=0; i<mScene->mNumLights; i++){
  1098. if(mScene->mLights[i]->mName == pNode->mName){
  1099. mOutput << startstr <<"<instance_light url=\"#" << node_name_escaped << "-light\"/>" << endstr;
  1100. break;
  1101. }
  1102. }
  1103. }else
  1104. // instance every geometry
  1105. for( size_t a = 0; a < pNode->mNumMeshes; ++a )
  1106. {
  1107. const aiMesh* mesh = mScene->mMeshes[pNode->mMeshes[a]];
  1108. // do not instanciate mesh if empty. I wonder how this could happen
  1109. if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
  1110. continue;
  1111. if( mesh->mNumBones == 0 )
  1112. {
  1113. mOutput << startstr << "<instance_geometry url=\"#" << XMLEscape(GetMeshId( pNode->mMeshes[a])) << "\">" << endstr;
  1114. PushTag();
  1115. }
  1116. else
  1117. {
  1118. mOutput << startstr
  1119. << "<instance_controller url=\"#" << XMLEscape(GetMeshId( pNode->mMeshes[a])) << "-skin\">"
  1120. << endstr;
  1121. PushTag();
  1122. mOutput << startstr << "<skeleton>#skeleton_root</skeleton>" << endstr;
  1123. }
  1124. mOutput << startstr << "<bind_material>" << endstr;
  1125. PushTag();
  1126. mOutput << startstr << "<technique_common>" << endstr;
  1127. PushTag();
  1128. mOutput << startstr << "<instance_material symbol=\"defaultMaterial\" target=\"#" << XMLEscape(materials[mesh->mMaterialIndex].name) << "\">" << endstr;
  1129. PushTag();
  1130. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
  1131. {
  1132. if( mesh->HasTextureCoords( static_cast<unsigned int>(a) ) )
  1133. // semantic as in <texture texcoord=...>
  1134. // input_semantic as in <input semantic=...>
  1135. // input_set as in <input set=...>
  1136. mOutput << startstr << "<bind_vertex_input semantic=\"CHANNEL" << a << "\" input_semantic=\"TEXCOORD\" input_set=\"" << a << "\"/>" << endstr;
  1137. }
  1138. PopTag();
  1139. mOutput << startstr << "</instance_material>" << endstr;
  1140. PopTag();
  1141. mOutput << startstr << "</technique_common>" << endstr;
  1142. PopTag();
  1143. mOutput << startstr << "</bind_material>" << endstr;
  1144. PopTag();
  1145. if( mesh->mNumBones == 0)
  1146. mOutput << startstr << "</instance_geometry>" << endstr;
  1147. else
  1148. mOutput << startstr << "</instance_controller>" << endstr;
  1149. }
  1150. // recurse into subnodes
  1151. for( size_t a = 0; a < pNode->mNumChildren; ++a )
  1152. WriteNode( pScene, pNode->mChildren[a]);
  1153. PopTag();
  1154. mOutput << startstr << "</node>" << endstr;
  1155. }
  1156. #endif
  1157. #endif