ColladaExporter.cpp 63 KB

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