AssetImporter.cpp 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Graphics/AnimatedModel.h>
  23. #include <Urho3D/Graphics/Animation.h>
  24. #include <Urho3D/Core/Context.h>
  25. #include <Urho3D/Graphics/DebugRenderer.h>
  26. #include <Urho3D/IO/File.h>
  27. #include <Urho3D/IO/FileSystem.h>
  28. #include <Urho3D/Graphics/Geometry.h>
  29. #include <Urho3D/Graphics/Graphics.h>
  30. #include <Urho3D/Graphics/IndexBuffer.h>
  31. #include <Urho3D/Graphics/Light.h>
  32. #include <Urho3D/Graphics/Material.h>
  33. #include <Urho3D/Graphics/Model.h>
  34. #include <Urho3D/Graphics/Octree.h>
  35. #ifdef URHO3D_PHYSICS
  36. #include <Urho3D/Physics/PhysicsWorld.h>
  37. #endif
  38. #include <Urho3D/Core/ProcessUtils.h>
  39. #include <Urho3D/Math/Quaternion.h>
  40. #include <Urho3D/Resource/ResourceCache.h>
  41. #include <Urho3D/Scene/Scene.h>
  42. #include <Urho3D/Core/StringUtils.h>
  43. #include <Urho3D/Math/Vector3.h>
  44. #include <Urho3D/Graphics/VertexBuffer.h>
  45. #include <Urho3D/Core/WorkQueue.h>
  46. #include <Urho3D/Resource/XMLFile.h>
  47. #include <Urho3D/Graphics/Zone.h>
  48. #include <Urho3D/Container/Sort.h>
  49. #ifdef WIN32
  50. #include <windows.h>
  51. #endif
  52. #include <assimp/cimport.h>
  53. #include <assimp/scene.h>
  54. #include <assimp/postprocess.h>
  55. #include <assimp/DefaultLogger.hpp>
  56. #include <cstring>
  57. #include <Urho3D/Container/DebugNew.h>
  58. using namespace Urho3D;
  59. struct OutModel
  60. {
  61. OutModel() :
  62. rootBone_(0),
  63. totalVertices_(0),
  64. totalIndices_(0)
  65. {
  66. }
  67. String outName_;
  68. aiNode* rootNode_;
  69. HashSet<unsigned> meshIndices_;
  70. PODVector<aiMesh*> meshes_;
  71. PODVector<aiNode*> meshNodes_;
  72. PODVector<aiNode*> bones_;
  73. PODVector<aiAnimation*> animations_;
  74. PODVector<float> boneRadii_;
  75. PODVector<BoundingBox> boneHitboxes_;
  76. aiNode* rootBone_;
  77. unsigned totalVertices_;
  78. unsigned totalIndices_;
  79. };
  80. struct OutScene
  81. {
  82. String outName_;
  83. aiNode* rootNode_;
  84. Vector<OutModel> models_;
  85. PODVector<aiNode*> nodes_;
  86. PODVector<unsigned> nodeModelIndices_;
  87. };
  88. SharedPtr<Context> context_(new Context());
  89. const aiScene* scene_ = 0;
  90. aiNode* rootNode_ = 0;
  91. String inputName_;
  92. String resourcePath_;
  93. String outPath_;
  94. bool useSubdirs_ = true;
  95. bool localIDs_ = false;
  96. bool saveBinary_ = false;
  97. bool createZone_ = true;
  98. bool noAnimations_ = false;
  99. bool noHierarchy_ = false;
  100. bool noMaterials_ = false;
  101. bool noTextures_ = false;
  102. bool noMaterialDiffuseColor_ = false;
  103. bool saveMaterialList_ = false;
  104. bool includeNonSkinningBones_ = false;
  105. bool verboseLog_ = false;
  106. bool emissiveAO_ = false;
  107. bool noOverwriteMaterial_ = false;
  108. bool noOverwriteTexture_ = false;
  109. bool noOverwriteNewerTexture_ = false;
  110. bool checkUniqueModel_ = true;
  111. Vector<String> nonSkinningBoneIncludes_;
  112. Vector<String> nonSkinningBoneExcludes_;
  113. HashSet<aiAnimation*> allAnimations_;
  114. PODVector<aiAnimation*> sceneAnimations_;
  115. float defaultTicksPerSecond_ = 4800.0f;
  116. int main(int argc, char** argv);
  117. void Run(const Vector<String>& arguments);
  118. void DumpNodes(aiNode* rootNode, unsigned level);
  119. void ExportModel(const String& outName, bool animationOnly);
  120. void CollectMeshes(OutModel& model, aiNode* node);
  121. void CollectBones(OutModel& model, bool animationOnly = false);
  122. void CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node);
  123. void CollectAnimations(OutModel* model = 0);
  124. void BuildBoneCollisionInfo(OutModel& model);
  125. void BuildAndSaveModel(OutModel& model);
  126. void BuildAndSaveAnimations(OutModel* model = 0);
  127. void ExportScene(const String& outName, bool asPrefab);
  128. void CollectSceneModels(OutScene& scene, aiNode* node);
  129. Node* CreateSceneNode(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping);
  130. void BuildAndSaveScene(OutScene& scene, bool asPrefab);
  131. void ExportMaterials(HashSet<String>& usedTextures);
  132. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures);
  133. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath);
  134. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName);
  135. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& meshes, aiNode* node);
  136. unsigned GetMeshIndex(aiMesh* mesh);
  137. unsigned GetBoneIndex(OutModel& model, const String& boneName);
  138. aiBone* GetMeshBone(OutModel& model, const String& boneName);
  139. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName);
  140. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  141. blendIndices, Vector<PODVector<float> >& blendWeights);
  142. String GetMeshMaterialName(aiMesh* mesh);
  143. String GetMaterialTextureName(const String& nameIn);
  144. String GenerateMaterialName(aiMaterial* material);
  145. String GenerateTextureName(unsigned texIndex);
  146. unsigned GetNumValidFaces(aiMesh* mesh);
  147. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  148. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  149. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  150. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  151. Vector<PODVector<float> >& blendWeights);
  152. unsigned GetElementMask(aiMesh* mesh);
  153. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive = true);
  154. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode, bool rootInclusive = true);
  155. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode, bool rootInclusive = true);
  156. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode);
  157. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale);
  158. String FromAIString(const aiString& str);
  159. Vector3 ToVector3(const aiVector3D& vec);
  160. Vector2 ToVector2(const aiVector2D& vec);
  161. Quaternion ToQuaternion(const aiQuaternion& quat);
  162. Matrix3x4 ToMatrix3x4(const aiMatrix4x4& mat);
  163. String SanitateAssetName(const String& name);
  164. int main(int argc, char** argv)
  165. {
  166. Vector<String> arguments;
  167. #ifdef WIN32
  168. arguments = ParseArguments(GetCommandLineW());
  169. #else
  170. arguments = ParseArguments(argc, argv);
  171. #endif
  172. Run(arguments);
  173. return 0;
  174. }
  175. void Run(const Vector<String>& arguments)
  176. {
  177. if (arguments.Size() < 2)
  178. {
  179. ErrorExit(
  180. "Usage: AssetImporter <command> <input file> <output file> [options]\n"
  181. "See http://assimp.sourceforge.net/main_features_formats.html for input formats\n\n"
  182. "Commands:\n"
  183. "model Output a model\n"
  184. "scene Output a scene\n"
  185. "node Output a node and its children (prefab)\n"
  186. "dump Dump scene node structure. No output file is generated\n"
  187. "lod Combine several Urho3D models as LOD levels of the output model\n"
  188. " Syntax: lod <dist0> <mdl0> <dist1 <mdl1> ... <output file>\n"
  189. "\n"
  190. "Options:\n"
  191. "-b Save scene in binary format, default format is XML\n"
  192. "-h Generate hard instead of smooth normals if input file has no normals\n"
  193. "-i Use local ID's for scene nodes\n"
  194. "-l Output a material list file for models\n"
  195. "-na Do not output animations\n"
  196. "-nm Do not output materials\n"
  197. "-nt Do not output material textures\n"
  198. "-nc Do not use material diffuse color value, instead output white\n"
  199. "-nh Do not save full node hierarchy (scene mode only)\n"
  200. "-ns Do not create subdirectories for resources\n"
  201. "-nz Do not create a zone and a directional light (scene mode only)\n"
  202. "-nf Do not fix infacing normals\n"
  203. "-p <path> Set path for scene resources. Default is output file path\n"
  204. "-r <name> Use the named scene node as root node\n"
  205. "-f <freq> Animation tick frequency to use if unspecified. Default 4800\n"
  206. "-o Optimize redundant submeshes. Loses scene hierarchy and animations\n"
  207. "-s <filter> Include non-skinning bones in the model's skeleton. Can be given a\n"
  208. " case-insensitive semicolon separated filter list. Bone is included\n"
  209. " if its name contains any of the filters. Prefix filter with minus\n"
  210. " sign to use as an exclude. For example -s \"Bip01;-Dummy;-Helper\"\n"
  211. "-t Generate tangents\n"
  212. "-v Enable verbose Assimp library logging\n"
  213. "-eao Interpret material emissive texture as ambient occlusion\n"
  214. "-cm Check and do not overwrite if material exists\n"
  215. "-ct Check and do not overwrite if texture exists\n"
  216. "-ctn Check and do not overwrite if texture has newer timestamp\n"
  217. "-am Export all meshes even if identical (scene mode only)\n"
  218. );
  219. }
  220. context_->RegisterSubsystem(new FileSystem(context_));
  221. context_->RegisterSubsystem(new ResourceCache(context_));
  222. context_->RegisterSubsystem(new WorkQueue(context_));
  223. RegisterSceneLibrary(context_);
  224. RegisterGraphicsLibrary(context_);
  225. #ifdef URHO3D_PHYSICS
  226. RegisterPhysicsLibrary(context_);
  227. #endif
  228. String command = arguments[0].ToLower();
  229. String rootNodeName;
  230. unsigned flags =
  231. aiProcess_ConvertToLeftHanded |
  232. aiProcess_JoinIdenticalVertices |
  233. aiProcess_Triangulate |
  234. aiProcess_GenSmoothNormals |
  235. aiProcess_LimitBoneWeights |
  236. aiProcess_ImproveCacheLocality |
  237. aiProcess_RemoveRedundantMaterials |
  238. aiProcess_FixInfacingNormals |
  239. aiProcess_FindInvalidData |
  240. aiProcess_GenUVCoords |
  241. aiProcess_FindInstances |
  242. aiProcess_OptimizeMeshes;
  243. for (unsigned i = 2; i < arguments.Size(); ++i)
  244. {
  245. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  246. {
  247. String argument = arguments[i].Substring(1).ToLower();
  248. String value = i + 1 < arguments.Size() ? arguments[i + 1] : String::EMPTY;
  249. if (argument == "b")
  250. saveBinary_ = true;
  251. else if (argument == "h")
  252. {
  253. flags &= ~aiProcess_GenSmoothNormals;
  254. flags |= aiProcess_GenNormals;
  255. }
  256. else if (argument == "i")
  257. localIDs_ = true;
  258. else if (argument == "l")
  259. saveMaterialList_ = true;
  260. else if (argument == "t")
  261. flags |= aiProcess_CalcTangentSpace;
  262. else if (argument == "o")
  263. flags |= aiProcess_PreTransformVertices;
  264. else if (argument.Length() == 2 && argument[0] == 'n')
  265. {
  266. switch (tolower(argument[1]))
  267. {
  268. case 'a':
  269. noAnimations_ = true;
  270. break;
  271. case 'c':
  272. noMaterialDiffuseColor_ = true;
  273. break;
  274. case 'm':
  275. noMaterials_ = true;
  276. break;
  277. case 'h':
  278. noHierarchy_ = true;
  279. break;
  280. case 's':
  281. useSubdirs_ = false;
  282. break;
  283. case 't':
  284. noTextures_ = true;
  285. break;
  286. case 'z':
  287. createZone_ = false;
  288. break;
  289. case 'f':
  290. flags &= ~aiProcess_FixInfacingNormals;
  291. break;
  292. }
  293. }
  294. else if (argument == "p" && !value.Empty())
  295. {
  296. resourcePath_ = AddTrailingSlash(value);
  297. ++i;
  298. }
  299. else if (argument == "r" && !value.Empty())
  300. {
  301. rootNodeName = value;
  302. ++i;
  303. }
  304. else if (argument == "f" && !value.Empty())
  305. {
  306. defaultTicksPerSecond_ = ToFloat(value);
  307. ++i;
  308. }
  309. else if (argument == "s")
  310. {
  311. includeNonSkinningBones_ = true;
  312. if (value.Length() && (value[0] != '-' || value.Length() > 3))
  313. {
  314. Vector<String> filters = value.Split(';');
  315. for (unsigned i = 0; i < filters.Size(); ++i)
  316. {
  317. if (filters[i][0] == '-')
  318. nonSkinningBoneExcludes_.Push(filters[i].Substring(1));
  319. else
  320. nonSkinningBoneIncludes_.Push(filters[i]);
  321. }
  322. }
  323. }
  324. else if (argument == "v")
  325. verboseLog_ = true;
  326. else if (argument == "eao")
  327. emissiveAO_ = true;
  328. else if (argument == "cm")
  329. noOverwriteMaterial_ = true;
  330. else if (argument == "ct")
  331. noOverwriteTexture_ = true;
  332. else if (argument == "ctn")
  333. noOverwriteNewerTexture_ = true;
  334. else if (argument == "am")
  335. checkUniqueModel_ = false;
  336. }
  337. }
  338. if (command == "model" || command == "scene" || command == "node" || command == "dump")
  339. {
  340. String inFile = arguments[1];
  341. String outFile;
  342. if (arguments.Size() > 2 && arguments[2][0] != '-')
  343. outFile = GetInternalPath(arguments[2]);
  344. inputName_ = GetFileName(inFile);
  345. outPath_ = GetPath(outFile);
  346. if (resourcePath_.Empty())
  347. {
  348. resourcePath_ = outPath_;
  349. // If output file already has the Models/ path (model mode), do not take it into the resource path
  350. if (command == "model")
  351. {
  352. if (resourcePath_.EndsWith("Models/", false))
  353. resourcePath_ = resourcePath_.Substring(0, resourcePath_.Length() - 7);
  354. }
  355. if (resourcePath_.Empty())
  356. resourcePath_ = "./";
  357. }
  358. resourcePath_ = AddTrailingSlash(resourcePath_);
  359. if (command != "dump" && outFile.Empty())
  360. ErrorExit("No output file defined");
  361. if (verboseLog_)
  362. Assimp::DefaultLogger::create("", Assimp::Logger::VERBOSE, aiDefaultLogStream_STDOUT);
  363. PrintLine("Reading file " + inFile);
  364. scene_ = aiImportFile(GetNativePath(inFile).CString(), flags);
  365. if (!scene_)
  366. ErrorExit("Could not open or parse input file " + inFile);
  367. if (verboseLog_)
  368. Assimp::DefaultLogger::kill();
  369. rootNode_ = scene_->mRootNode;
  370. if (!rootNodeName.Empty())
  371. {
  372. rootNode_ = GetNode(rootNodeName, rootNode_, false);
  373. if (!rootNode_)
  374. ErrorExit("Could not find scene node " + rootNodeName);
  375. }
  376. if (command == "dump")
  377. {
  378. DumpNodes(rootNode_, 0);
  379. return;
  380. }
  381. if (command == "model")
  382. ExportModel(outFile, scene_->mFlags & AI_SCENE_FLAGS_INCOMPLETE);
  383. if (command == "scene" || command == "node")
  384. {
  385. bool asPrefab = command == "node";
  386. // Saving as prefab requires the hierarchy, especially the root node
  387. if (asPrefab)
  388. noHierarchy_ = false;
  389. ExportScene(outFile, asPrefab);
  390. }
  391. if (!noMaterials_)
  392. {
  393. HashSet<String> usedTextures;
  394. ExportMaterials(usedTextures);
  395. if (!noTextures_)
  396. CopyTextures(usedTextures, GetPath(inFile));
  397. }
  398. }
  399. else if (command == "lod")
  400. {
  401. PODVector<float> lodDistances;
  402. Vector<String> modelNames;
  403. String outFile;
  404. unsigned numLodArguments = 0;
  405. for (unsigned i = 1; i < arguments.Size(); ++i)
  406. {
  407. if (arguments[i][0] == '-')
  408. break;
  409. ++numLodArguments;
  410. }
  411. if (numLodArguments < 4)
  412. ErrorExit("Must define at least 2 LOD levels");
  413. if (!(numLodArguments & 1))
  414. ErrorExit("No output file defined");
  415. for (unsigned i = 1; i < numLodArguments + 1; ++i)
  416. {
  417. if (i == numLodArguments)
  418. outFile = GetInternalPath(arguments[i]);
  419. else
  420. {
  421. if (i & 1)
  422. lodDistances.Push(Max(ToFloat(arguments[i]), 0.0f));
  423. else
  424. modelNames.Push(GetInternalPath(arguments[i]));
  425. }
  426. }
  427. if (lodDistances[0] != 0.0f)
  428. {
  429. PrintLine("Warning: first LOD distance forced to 0");
  430. lodDistances[0] = 0.0f;
  431. }
  432. CombineLods(lodDistances, modelNames, outFile);
  433. }
  434. else
  435. ErrorExit("Unrecognized command " + command);
  436. }
  437. void DumpNodes(aiNode* rootNode, unsigned level)
  438. {
  439. if (!rootNode)
  440. return;
  441. String indent(' ', level * 2);
  442. Vector3 pos, scale;
  443. Quaternion rot;
  444. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  445. GetPosRotScale(transform, pos, rot, scale);
  446. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  447. if (rootNode->mNumMeshes == 1)
  448. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  449. if (rootNode->mNumMeshes > 1)
  450. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  451. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  452. DumpNodes(rootNode->mChildren[i], level + 1);
  453. }
  454. void ExportModel(const String& outName, bool animationOnly)
  455. {
  456. if (outName.Empty())
  457. ErrorExit("No output file defined");
  458. OutModel model;
  459. model.rootNode_ = rootNode_;
  460. model.outName_ = outName;
  461. CollectMeshes(model, model.rootNode_);
  462. CollectBones(model, animationOnly);
  463. BuildBoneCollisionInfo(model);
  464. BuildAndSaveModel(model);
  465. if (!noAnimations_)
  466. {
  467. CollectAnimations(&model);
  468. BuildAndSaveAnimations(&model);
  469. // Save scene-global animations
  470. CollectAnimations();
  471. BuildAndSaveAnimations();
  472. }
  473. }
  474. void CollectMeshes(OutModel& model, aiNode* node)
  475. {
  476. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  477. {
  478. aiMesh* mesh = scene_->mMeshes[node->mMeshes[i]];
  479. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  480. {
  481. if (mesh == model.meshes_[j])
  482. {
  483. PrintLine("Warning: same mesh found multiple times");
  484. break;
  485. }
  486. }
  487. model.meshIndices_.Insert(node->mMeshes[i]);
  488. model.meshes_.Push(mesh);
  489. model.meshNodes_.Push(node);
  490. model.totalVertices_ += mesh->mNumVertices;
  491. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  492. }
  493. for (unsigned i = 0; i < node->mNumChildren; ++i)
  494. CollectMeshes(model, node->mChildren[i]);
  495. }
  496. void CollectBones(OutModel& model, bool animationOnly)
  497. {
  498. HashSet<aiNode*> necessary;
  499. HashSet<aiNode*> rootNodes;
  500. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  501. {
  502. aiMesh* mesh = model.meshes_[i];
  503. aiNode* meshNode = model.meshNodes_[i];
  504. aiNode* meshParentNode = meshNode->mParent;
  505. aiNode* rootNode = 0;
  506. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  507. {
  508. aiBone* bone = mesh->mBones[j];
  509. String boneName(FromAIString(bone->mName));
  510. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  511. if (!boneNode)
  512. ErrorExit("Could not find scene node for bone " + boneName);
  513. necessary.Insert(boneNode);
  514. rootNode = boneNode;
  515. for (;;)
  516. {
  517. boneNode = boneNode->mParent;
  518. if (!boneNode || ((boneNode == meshNode || boneNode == meshParentNode) && !animationOnly))
  519. break;
  520. rootNode = boneNode;
  521. necessary.Insert(boneNode);
  522. }
  523. if (rootNodes.Find(rootNode) == rootNodes.End())
  524. rootNodes.Insert(rootNode);
  525. }
  526. }
  527. // If we find multiple root nodes, try to remedy by using their parent instead
  528. if (rootNodes.Size() > 1)
  529. {
  530. aiNode* commonParent = (*rootNodes.Begin())->mParent;
  531. for (HashSet<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  532. {
  533. if (*i != commonParent)
  534. {
  535. if (!commonParent || (*i)->mParent != commonParent)
  536. ErrorExit("Skeleton with multiple root nodes found, not supported");
  537. }
  538. }
  539. rootNodes.Clear();
  540. rootNodes.Insert(commonParent);
  541. necessary.Insert(commonParent);
  542. }
  543. if (rootNodes.Empty())
  544. return;
  545. model.rootBone_ = *rootNodes.Begin();
  546. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  547. // Initialize the bone collision info
  548. model.boneRadii_.Resize(model.bones_.Size());
  549. model.boneHitboxes_.Resize(model.bones_.Size());
  550. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  551. {
  552. model.boneRadii_[i] = 0.0f;
  553. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  554. }
  555. }
  556. void CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node)
  557. {
  558. bool includeBone = necessary.Find(node) != necessary.End();
  559. String boneName = FromAIString(node->mName);
  560. // Check include/exclude filters for non-skinned bones
  561. if (!includeBone && includeNonSkinningBones_)
  562. {
  563. // If no includes specified, include by default but check for excludes
  564. if (nonSkinningBoneIncludes_.Empty())
  565. includeBone = true;
  566. // Check against includes/excludes
  567. for (unsigned i = 0; i < nonSkinningBoneIncludes_.Size(); ++i)
  568. {
  569. if (boneName.Contains(nonSkinningBoneIncludes_[i], false))
  570. {
  571. includeBone = true;
  572. break;
  573. }
  574. }
  575. for (unsigned i = 0; i < nonSkinningBoneExcludes_.Size(); ++i)
  576. {
  577. if (boneName.Contains(nonSkinningBoneExcludes_[i], false))
  578. {
  579. includeBone = false;
  580. break;
  581. }
  582. }
  583. if (includeBone)
  584. PrintLine("Including non-skinning bone " + boneName);
  585. }
  586. if (includeBone)
  587. dest.Push(node);
  588. for (unsigned i = 0; i < node->mNumChildren; ++i)
  589. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  590. }
  591. void CollectAnimations(OutModel* model)
  592. {
  593. const aiScene* scene = scene_;
  594. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  595. {
  596. aiAnimation* anim = scene->mAnimations[i];
  597. if (allAnimations_.Contains(anim))
  598. continue;
  599. if (model)
  600. {
  601. bool modelBoneFound = false;
  602. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  603. {
  604. aiNodeAnim* channel = anim->mChannels[j];
  605. String channelName = FromAIString(channel->mNodeName);
  606. if (GetBoneIndex(*model, channelName) != M_MAX_UNSIGNED)
  607. {
  608. modelBoneFound = true;
  609. break;
  610. }
  611. }
  612. if (modelBoneFound)
  613. {
  614. model->animations_.Push(anim);
  615. allAnimations_.Insert(anim);
  616. }
  617. }
  618. else
  619. {
  620. sceneAnimations_.Push(anim);
  621. allAnimations_.Insert(anim);
  622. }
  623. }
  624. /// \todo Vertex morphs are ignored for now
  625. }
  626. void BuildBoneCollisionInfo(OutModel& model)
  627. {
  628. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  629. {
  630. aiMesh* mesh = model.meshes_[i];
  631. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  632. {
  633. aiBone* bone = mesh->mBones[j];
  634. String boneName = FromAIString(bone->mName);
  635. unsigned boneIndex = GetBoneIndex(model, boneName);
  636. if (boneIndex == M_MAX_UNSIGNED)
  637. continue;
  638. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  639. {
  640. float weight = bone->mWeights[k].mWeight;
  641. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  642. if (weight > 0.33f)
  643. {
  644. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  645. Vector3 vertex = ToVector3(vertexBoneSpace);
  646. float radius = vertex.Length();
  647. if (radius > model.boneRadii_[boneIndex])
  648. model.boneRadii_[boneIndex] = radius;
  649. model.boneHitboxes_[boneIndex].Merge(vertex);
  650. }
  651. }
  652. }
  653. }
  654. }
  655. void BuildAndSaveModel(OutModel& model)
  656. {
  657. if (!model.rootNode_)
  658. ErrorExit("Null root node for model");
  659. String rootNodeName = FromAIString(model.rootNode_->mName);
  660. if (!model.meshes_.Size())
  661. ErrorExit("No geometries found starting from node " + rootNodeName);
  662. PrintLine("Writing model " + rootNodeName);
  663. SharedPtr<Model> outModel(new Model(context_));
  664. Vector<PODVector<unsigned> > allBoneMappings;
  665. BoundingBox box;
  666. unsigned numValidGeometries = 0;
  667. bool combineBuffers = true;
  668. // Check if buffers can be combined (same vertex element mask, under 65535 vertices)
  669. unsigned elementMask = GetElementMask(model.meshes_[0]);
  670. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  671. {
  672. if (GetNumValidFaces(model.meshes_[i]))
  673. {
  674. ++numValidGeometries;
  675. if (i > 0 && GetElementMask(model.meshes_[i]) != elementMask)
  676. combineBuffers = false;
  677. }
  678. }
  679. // Check if keeping separate buffers allows to avoid 32-bit indices
  680. if (combineBuffers && model.totalVertices_ > 65535)
  681. {
  682. bool allUnder65k = true;
  683. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  684. {
  685. if (GetNumValidFaces(model.meshes_[i]))
  686. {
  687. if (model.meshes_[i]->mNumVertices > 65535)
  688. allUnder65k = false;
  689. }
  690. }
  691. if (allUnder65k == true)
  692. combineBuffers = false;
  693. }
  694. SharedPtr<IndexBuffer> ib;
  695. SharedPtr<VertexBuffer> vb;
  696. Vector<SharedPtr<VertexBuffer> > vbVector;
  697. Vector<SharedPtr<IndexBuffer> > ibVector;
  698. unsigned startVertexOffset = 0;
  699. unsigned startIndexOffset = 0;
  700. unsigned destGeomIndex = 0;
  701. outModel->SetNumGeometries(numValidGeometries);
  702. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  703. {
  704. aiMesh* mesh = model.meshes_[i];
  705. unsigned elementMask = GetElementMask(mesh);
  706. unsigned validFaces = GetNumValidFaces(mesh);
  707. if (!validFaces)
  708. continue;
  709. bool largeIndices;
  710. if (combineBuffers)
  711. largeIndices = model.totalIndices_ > 65535;
  712. else
  713. largeIndices = mesh->mNumVertices > 65535;
  714. // Create new buffers if necessary
  715. if (!combineBuffers || vbVector.Empty())
  716. {
  717. vb = new VertexBuffer(context_);
  718. ib = new IndexBuffer(context_);
  719. if (combineBuffers)
  720. {
  721. ib->SetSize(model.totalIndices_, largeIndices);
  722. vb->SetSize(model.totalVertices_, elementMask);
  723. }
  724. else
  725. {
  726. ib->SetSize(validFaces * 3, largeIndices);
  727. vb->SetSize(mesh->mNumVertices, elementMask);
  728. }
  729. vbVector.Push(vb);
  730. ibVector.Push(ib);
  731. startVertexOffset = 0;
  732. startIndexOffset = 0;
  733. }
  734. // Get the world transform of the mesh for baking into the vertices
  735. Matrix3x4 vertexTransform;
  736. Matrix3 normalTransform;
  737. Vector3 pos, scale;
  738. Quaternion rot;
  739. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  740. vertexTransform = Matrix3x4(pos, rot, scale);
  741. normalTransform = rot.RotationMatrix();
  742. SharedPtr<Geometry> geom(new Geometry(context_));
  743. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  744. String(validFaces * 3) + " indices");
  745. unsigned char* vertexData = vb->GetShadowData();
  746. unsigned char* indexData = ib->GetShadowData();
  747. // Build the index data
  748. if (!largeIndices)
  749. {
  750. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  751. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  752. WriteShortIndices(dest, mesh, j, startVertexOffset);
  753. }
  754. else
  755. {
  756. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  757. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  758. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  759. }
  760. // Build the vertex data
  761. // If there are bones, get blend data
  762. Vector<PODVector<unsigned char> > blendIndices;
  763. Vector<PODVector<float> > blendWeights;
  764. PODVector<unsigned> boneMappings;
  765. if (model.bones_.Size())
  766. GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights);
  767. float* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  768. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  769. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  770. // Calculate the geometry center
  771. Vector3 center = Vector3::ZERO;
  772. if (validFaces)
  773. {
  774. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  775. {
  776. if (mesh->mFaces[j].mNumIndices == 3)
  777. {
  778. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  779. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  780. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  781. }
  782. }
  783. center /= (float)validFaces * 3;
  784. }
  785. // Define the geometry
  786. geom->SetIndexBuffer(ib);
  787. geom->SetVertexBuffer(0, vb);
  788. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, validFaces * 3, true);
  789. outModel->SetNumGeometryLodLevels(destGeomIndex, 1);
  790. outModel->SetGeometry(destGeomIndex, 0, geom);
  791. outModel->SetGeometryCenter(destGeomIndex, center);
  792. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  793. allBoneMappings.Push(boneMappings);
  794. startVertexOffset += mesh->mNumVertices;
  795. startIndexOffset += validFaces * 3;
  796. ++destGeomIndex;
  797. }
  798. // Define the model buffers and bounding box
  799. PODVector<unsigned> emptyMorphRange;
  800. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  801. outModel->SetIndexBuffers(ibVector);
  802. outModel->SetBoundingBox(box);
  803. // Build skeleton if necessary
  804. if (model.bones_.Size() && model.rootBone_)
  805. {
  806. PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  807. FromAIString(model.rootBone_->mName));
  808. Skeleton skeleton;
  809. Vector<Bone>& bones = skeleton.GetModifiableBones();
  810. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  811. {
  812. aiNode* boneNode = model.bones_[i];
  813. String boneName(FromAIString(boneNode->mName));
  814. Bone newBone;
  815. newBone.name_ = boneName;
  816. aiMatrix4x4 transform = boneNode->mTransformation;
  817. // Make the root bone transform relative to the model's root node, if it is not already
  818. if (boneNode == model.rootBone_)
  819. transform = GetDerivedTransform(boneNode, model.rootNode_);
  820. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  821. // Get offset information if exists
  822. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  823. newBone.radius_ = model.boneRadii_[i];
  824. newBone.boundingBox_ = model.boneHitboxes_[i];
  825. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  826. newBone.parentIndex_ = i;
  827. bones.Push(newBone);
  828. }
  829. // Set the bone hierarchy
  830. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  831. {
  832. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  833. for (unsigned j = 0; j < bones.Size(); ++j)
  834. {
  835. if (bones[j].name_ == parentName)
  836. {
  837. bones[i].parentIndex_ = j;
  838. break;
  839. }
  840. }
  841. }
  842. outModel->SetSkeleton(skeleton);
  843. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  844. outModel->SetGeometryBoneMappings(allBoneMappings);
  845. }
  846. File outFile(context_);
  847. if (!outFile.Open(model.outName_, FILE_WRITE))
  848. ErrorExit("Could not open output file " + model.outName_);
  849. outModel->Save(outFile);
  850. // If exporting materials, also save material list for use by the editor
  851. if (!noMaterials_ && saveMaterialList_)
  852. {
  853. String materialListName = ReplaceExtension(model.outName_, ".txt");
  854. File listFile(context_);
  855. if (listFile.Open(materialListName, FILE_WRITE))
  856. {
  857. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  858. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  859. }
  860. else
  861. PrintLine("Warning: could not write material list file " + materialListName);
  862. }
  863. }
  864. void BuildAndSaveAnimations(OutModel* model)
  865. {
  866. const PODVector<aiAnimation*>& animations = model ? model->animations_ : sceneAnimations_;
  867. for (unsigned i = 0; i < animations.Size(); ++i)
  868. {
  869. aiAnimation* anim = animations[i];
  870. float duration = (float)anim->mDuration;
  871. String animName = FromAIString(anim->mName);
  872. String animOutName;
  873. if (animName.Empty())
  874. animName = "Anim" + String(i + 1);
  875. if (model)
  876. animOutName = GetPath(model->outName_) + GetFileName(model->outName_) + "_" + SanitateAssetName(animName) + ".ani";
  877. else
  878. animOutName = outPath_ + SanitateAssetName(animName) + ".ani";
  879. float ticksPerSecond = (float)anim->mTicksPerSecond;
  880. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  881. if (ticksPerSecond < M_EPSILON)
  882. ticksPerSecond = defaultTicksPerSecond_;
  883. float tickConversion = 1.0f / ticksPerSecond;
  884. // Find out the start time of animation from each channel's first keyframe for adjusting the keyframe times
  885. // to start from zero
  886. float startTime = duration;
  887. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  888. {
  889. aiNodeAnim* channel = anim->mChannels[j];
  890. if (channel->mNumPositionKeys > 0)
  891. startTime = Min(startTime, (float)channel->mPositionKeys[0].mTime);
  892. if (channel->mNumRotationKeys > 0)
  893. startTime = Min(startTime, (float)channel->mRotationKeys[0].mTime);
  894. if (channel->mScalingKeys > 0)
  895. startTime = Min(startTime, (float)channel->mScalingKeys[0].mTime);
  896. }
  897. duration -= startTime;
  898. SharedPtr<Animation> outAnim(new Animation(context_));
  899. outAnim->SetAnimationName(animName);
  900. outAnim->SetLength(duration * tickConversion);
  901. PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  902. Vector<AnimationTrack> tracks;
  903. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  904. {
  905. aiNodeAnim* channel = anim->mChannels[j];
  906. String channelName = FromAIString(channel->mNodeName);
  907. aiNode* boneNode = 0;
  908. bool isRootBone = false;
  909. if (model)
  910. {
  911. unsigned boneIndex = GetBoneIndex(*model, channelName);
  912. if (boneIndex == M_MAX_UNSIGNED)
  913. {
  914. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  915. continue;
  916. }
  917. boneNode = model->bones_[boneIndex];
  918. isRootBone = boneIndex == 0;
  919. }
  920. else
  921. {
  922. boneNode = GetNode(channelName, scene_->mRootNode);
  923. if (!boneNode)
  924. {
  925. PrintLine("Warning: skipping animation track " + channelName + " whose scene node was not found");
  926. continue;
  927. }
  928. }
  929. AnimationTrack track;
  930. track.name_ = channelName;
  931. track.nameHash_ = channelName;
  932. // Check which channels are used
  933. track.channelMask_ = 0;
  934. if (channel->mNumPositionKeys > 1)
  935. track.channelMask_ |= CHANNEL_POSITION;
  936. if (channel->mNumRotationKeys > 1)
  937. track.channelMask_ |= CHANNEL_ROTATION;
  938. if (channel->mNumScalingKeys > 1)
  939. track.channelMask_ |= CHANNEL_SCALE;
  940. // Check for redundant identity scale in all keyframes and remove in that case
  941. if (track.channelMask_ & CHANNEL_SCALE)
  942. {
  943. bool redundantScale = true;
  944. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  945. {
  946. float SCALE_EPSILON = 0.000001f;
  947. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  948. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  949. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  950. {
  951. redundantScale = false;
  952. break;
  953. }
  954. }
  955. if (redundantScale)
  956. track.channelMask_ &= ~CHANNEL_SCALE;
  957. }
  958. if (!track.channelMask_)
  959. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  960. // Currently only same amount of keyframes is supported
  961. // Note: should also check the times of individual keyframes for match
  962. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  963. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  964. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  965. {
  966. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  967. continue;
  968. }
  969. unsigned keyFrames = channel->mNumPositionKeys;
  970. if (channel->mNumRotationKeys > keyFrames)
  971. keyFrames = channel->mNumRotationKeys;
  972. if (channel->mNumScalingKeys > keyFrames)
  973. keyFrames = channel->mNumScalingKeys;
  974. for (unsigned k = 0; k < keyFrames; ++k)
  975. {
  976. AnimationKeyFrame kf;
  977. kf.time_ = 0.0f;
  978. kf.position_ = Vector3::ZERO;
  979. kf.rotation_ = Quaternion::IDENTITY;
  980. kf.scale_ = Vector3::ONE;
  981. // Get time for the keyframe. Adjust with animation's start time
  982. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  983. kf.time_ = ((float)channel->mPositionKeys[k].mTime - startTime) * tickConversion;
  984. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  985. kf.time_ = ((float)channel->mRotationKeys[k].mTime - startTime) * tickConversion;
  986. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  987. kf.time_ = ((float)channel->mScalingKeys[k].mTime - startTime) * tickConversion;
  988. // Make sure time stays positive
  989. kf.time_ = Max(kf.time_, 0.0f);
  990. // Start with the bone's base transform
  991. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  992. aiVector3D pos, scale;
  993. aiQuaternion rot;
  994. boneTransform.Decompose(scale, rot, pos);
  995. // Then apply the active channels
  996. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  997. pos = channel->mPositionKeys[k].mValue;
  998. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  999. rot = channel->mRotationKeys[k].mValue;
  1000. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  1001. scale = channel->mScalingKeys[k].mValue;
  1002. // If root bone, transform with the model root node transform
  1003. if (model && isRootBone)
  1004. {
  1005. aiMatrix4x4 transMat, scaleMat, rotMat;
  1006. aiMatrix4x4::Translation(pos, transMat);
  1007. aiMatrix4x4::Scaling(scale, scaleMat);
  1008. rotMat = aiMatrix4x4(rot.GetMatrix());
  1009. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  1010. tform = GetDerivedTransform(tform, boneNode, model->rootNode_);
  1011. tform.Decompose(scale, rot, pos);
  1012. }
  1013. if (track.channelMask_ & CHANNEL_POSITION)
  1014. kf.position_ = ToVector3(pos);
  1015. if (track.channelMask_ & CHANNEL_ROTATION)
  1016. kf.rotation_ = ToQuaternion(rot);
  1017. if (track.channelMask_ & CHANNEL_SCALE)
  1018. kf.scale_ = ToVector3(scale);
  1019. track.keyFrames_.Push(kf);
  1020. }
  1021. tracks.Push(track);
  1022. }
  1023. outAnim->SetTracks(tracks);
  1024. File outFile(context_);
  1025. if (!outFile.Open(animOutName, FILE_WRITE))
  1026. ErrorExit("Could not open output file " + animOutName);
  1027. outAnim->Save(outFile);
  1028. }
  1029. }
  1030. void ExportScene(const String& outName, bool asPrefab)
  1031. {
  1032. OutScene outScene;
  1033. outScene.outName_ = outName;
  1034. outScene.rootNode_ = rootNode_;
  1035. if (useSubdirs_)
  1036. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Models");
  1037. CollectSceneModels(outScene, rootNode_);
  1038. // Save models, their material lists and animations
  1039. for (unsigned i = 0; i < outScene.models_.Size(); ++i)
  1040. BuildAndSaveModel(outScene.models_[i]);
  1041. // Save scene-global animations
  1042. if (!noAnimations_)
  1043. {
  1044. CollectAnimations();
  1045. BuildAndSaveAnimations();
  1046. }
  1047. // Save scene
  1048. BuildAndSaveScene(outScene, asPrefab);
  1049. }
  1050. void CollectSceneModels(OutScene& scene, aiNode* node)
  1051. {
  1052. Vector<Pair<aiNode*, aiMesh*> > meshes;
  1053. GetMeshesUnderNode(meshes, node);
  1054. if (meshes.Size())
  1055. {
  1056. OutModel model;
  1057. model.rootNode_ = node;
  1058. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  1059. for (unsigned i = 0; i < meshes.Size(); ++i)
  1060. {
  1061. aiMesh* mesh = meshes[i].second_;
  1062. unsigned meshIndex = GetMeshIndex(mesh);
  1063. model.meshIndices_.Insert(meshIndex);
  1064. model.meshes_.Push(mesh);
  1065. model.meshNodes_.Push(meshes[i].first_);
  1066. model.totalVertices_ += mesh->mNumVertices;
  1067. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  1068. }
  1069. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  1070. bool unique = true;
  1071. if (checkUniqueModel_)
  1072. {
  1073. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  1074. {
  1075. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  1076. {
  1077. PrintLine("Added node " + FromAIString(node->mName));
  1078. scene.nodes_.Push(node);
  1079. scene.nodeModelIndices_.Push(i);
  1080. unique = false;
  1081. break;
  1082. }
  1083. }
  1084. }
  1085. if (unique)
  1086. {
  1087. PrintLine("Added model " + model.outName_);
  1088. PrintLine("Added node " + FromAIString(node->mName));
  1089. CollectBones(model);
  1090. BuildBoneCollisionInfo(model);
  1091. if (!noAnimations_)
  1092. {
  1093. CollectAnimations(&model);
  1094. BuildAndSaveAnimations(&model);
  1095. }
  1096. scene.models_.Push(model);
  1097. scene.nodes_.Push(node);
  1098. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  1099. }
  1100. }
  1101. for (unsigned i = 0; i < node->mNumChildren; ++i)
  1102. CollectSceneModels(scene, node->mChildren[i]);
  1103. }
  1104. Node* CreateSceneNode(Scene* scene, aiNode* srcNode, HashMap<aiNode*, Node*>& nodeMapping)
  1105. {
  1106. if (nodeMapping.Contains(srcNode))
  1107. return nodeMapping[srcNode];
  1108. // Flatten hierarchy if requested
  1109. if (noHierarchy_)
  1110. {
  1111. Node* outNode = scene->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1112. Vector3 pos, scale;
  1113. Quaternion rot;
  1114. GetPosRotScale(GetDerivedTransform(srcNode, rootNode_), pos, rot, scale);
  1115. outNode->SetTransform(pos, rot, scale);
  1116. nodeMapping[srcNode] = outNode;
  1117. return outNode;
  1118. }
  1119. if (srcNode == rootNode_ || !srcNode->mParent)
  1120. {
  1121. Node* outNode = scene->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1122. Vector3 pos, scale;
  1123. Quaternion rot;
  1124. GetPosRotScale(srcNode->mTransformation, pos, rot, scale);
  1125. outNode->SetTransform(pos, rot, scale);
  1126. nodeMapping[srcNode] = outNode;
  1127. return outNode;
  1128. }
  1129. else
  1130. {
  1131. // Ensure the existence of the parent chain as in the original file
  1132. if (!nodeMapping.Contains(srcNode->mParent))
  1133. CreateSceneNode(scene, srcNode->mParent, nodeMapping);
  1134. Node* parent = nodeMapping[srcNode->mParent];
  1135. Node* outNode = parent->CreateChild(FromAIString(srcNode->mName), localIDs_ ? LOCAL : REPLICATED);
  1136. Vector3 pos, scale;
  1137. Quaternion rot;
  1138. GetPosRotScale(srcNode->mTransformation, pos, rot, scale);
  1139. outNode->SetTransform(pos, rot, scale);
  1140. nodeMapping[srcNode] = outNode;
  1141. return outNode;
  1142. }
  1143. }
  1144. void BuildAndSaveScene(OutScene& scene, bool asPrefab)
  1145. {
  1146. if (!asPrefab)
  1147. PrintLine("Writing scene");
  1148. else
  1149. PrintLine("Writing node hierarchy");
  1150. SharedPtr<Scene> outScene(new Scene(context_));
  1151. if (!asPrefab)
  1152. {
  1153. #ifdef URHO3D_PHYSICS
  1154. /// \todo Make the physics properties configurable
  1155. outScene->CreateComponent<PhysicsWorld>();
  1156. #endif
  1157. /// \todo Make the octree properties configurable, or detect from the scene contents
  1158. outScene->CreateComponent<Octree>();
  1159. outScene->CreateComponent<DebugRenderer>();
  1160. if (createZone_)
  1161. {
  1162. Node* zoneNode = outScene->CreateChild("Zone", localIDs_ ? LOCAL : REPLICATED);
  1163. Zone* zone = zoneNode->CreateComponent<Zone>();
  1164. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.f));
  1165. zone->SetAmbientColor(Color(0.25f, 0.25f, 0.25f));
  1166. // Create default light only if scene does not define them
  1167. if (!scene_->HasLights())
  1168. {
  1169. Node* lightNode = outScene->CreateChild("GlobalLight", localIDs_ ? LOCAL : REPLICATED);
  1170. Light* light = lightNode->CreateComponent<Light>();
  1171. light->SetLightType(LIGHT_DIRECTIONAL);
  1172. lightNode->SetRotation(Quaternion(60.0f, 30.0f, 0.0f));
  1173. }
  1174. }
  1175. }
  1176. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  1177. HashMap<aiNode*, Node*> nodeMapping;
  1178. Node* outRootNode = 0;
  1179. if (asPrefab || !noHierarchy_)
  1180. outRootNode = CreateSceneNode(outScene, rootNode_, nodeMapping);
  1181. // Create geometry nodes
  1182. for (unsigned i = 0; i < scene.nodes_.Size(); ++i)
  1183. {
  1184. const OutModel& model = scene.models_[scene.nodeModelIndices_[i]];
  1185. Node* modelNode = CreateSceneNode(outScene, scene.nodes_[i], nodeMapping);
  1186. StaticModel* staticModel = model.bones_.Empty() ? modelNode->CreateComponent<StaticModel>() : modelNode->CreateComponent<AnimatedModel>();
  1187. // Create a dummy model so that the reference can be stored
  1188. String modelName = (useSubdirs_ ? "Models/" : "") + GetFileNameAndExtension(model.outName_);
  1189. if (!cache->Exists(modelName))
  1190. {
  1191. Model* dummyModel = new Model(context_);
  1192. dummyModel->SetName(modelName);
  1193. dummyModel->SetNumGeometries(model.meshes_.Size());
  1194. cache->AddManualResource(dummyModel);
  1195. }
  1196. staticModel->SetModel(cache->GetResource<Model>(modelName));
  1197. // Set materials if they are known
  1198. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  1199. {
  1200. String matName = GetMeshMaterialName(model.meshes_[j]);
  1201. // Create a dummy material so that the reference can be stored
  1202. if (!cache->Exists(matName))
  1203. {
  1204. Material* dummyMat = new Material(context_);
  1205. dummyMat->SetName(matName);
  1206. cache->AddManualResource(dummyMat);
  1207. }
  1208. staticModel->SetMaterial(j, cache->GetResource<Material>(matName));
  1209. }
  1210. }
  1211. // Create lights
  1212. if (!asPrefab)
  1213. {
  1214. for (unsigned i = 0; i < scene_->mNumLights; ++i)
  1215. {
  1216. aiLight* light = scene_->mLights[i];
  1217. aiNode* lightNode = GetNode(FromAIString(light->mName), rootNode_, true);
  1218. if (!lightNode)
  1219. continue;
  1220. Node* outNode = CreateSceneNode(outScene, lightNode, nodeMapping);
  1221. Vector3 lightAdjustPosition = ToVector3(light->mPosition);
  1222. Vector3 lightAdjustDirection = ToVector3(light->mDirection);
  1223. // If light is not aligned at the scene node, an adjustment node needs to be created
  1224. if (!lightAdjustPosition.Equals(Vector3::ZERO) || (light->mType != aiLightSource_POINT &&
  1225. !lightAdjustDirection.Equals(Vector3::FORWARD)))
  1226. {
  1227. outNode = outNode->CreateChild("LightAdjust");
  1228. outNode->SetPosition(lightAdjustPosition);
  1229. outNode->SetDirection(lightAdjustDirection);
  1230. }
  1231. Light* outLight = outNode->CreateComponent<Light>();
  1232. outLight->SetColor(Color(light->mColorDiffuse.r, light->mColorDiffuse.g, light->mColorDiffuse.b));
  1233. switch (light->mType)
  1234. {
  1235. case aiLightSource_DIRECTIONAL:
  1236. outLight->SetLightType(LIGHT_DIRECTIONAL);
  1237. break;
  1238. case aiLightSource_SPOT:
  1239. outLight->SetLightType(LIGHT_SPOT);
  1240. outLight->SetFov(light->mAngleOuterCone * M_RADTODEG);
  1241. break;
  1242. case aiLightSource_POINT:
  1243. outLight->SetLightType(LIGHT_POINT);
  1244. break;
  1245. default:
  1246. break;
  1247. }
  1248. // Calculate range from attenuation parameters so that light intensity has been reduced to 10% at that distance
  1249. if (light->mType != aiLightSource_DIRECTIONAL)
  1250. {
  1251. float a = light->mAttenuationQuadratic;
  1252. float b = light->mAttenuationLinear;
  1253. float c = -10.0f;
  1254. if (!Equals(a, 0.0f))
  1255. {
  1256. float root1 = (-b + sqrtf(b * b - 4.0f * a * c)) / (2.0f * a);
  1257. float root2 = (-b - sqrtf(b * b - 4.0f * a * c)) / (2.0f * a);
  1258. outLight->SetRange(Max(root1, root2));
  1259. }
  1260. else if (!Equals(b, 0.0f))
  1261. outLight->SetRange(-c / b);
  1262. }
  1263. }
  1264. }
  1265. File file(context_);
  1266. if (!file.Open(scene.outName_, FILE_WRITE))
  1267. ErrorExit("Could not open output file " + scene.outName_);
  1268. if (!asPrefab)
  1269. {
  1270. if (!saveBinary_)
  1271. outScene->SaveXML(file);
  1272. else
  1273. outScene->Save(file);
  1274. }
  1275. else
  1276. {
  1277. if (!saveBinary_)
  1278. outRootNode->SaveXML(file);
  1279. else
  1280. outRootNode->Save(file);
  1281. }
  1282. }
  1283. void ExportMaterials(HashSet<String>& usedTextures)
  1284. {
  1285. if (useSubdirs_)
  1286. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Materials");
  1287. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1288. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  1289. }
  1290. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures)
  1291. {
  1292. aiString matNameStr;
  1293. material->Get(AI_MATKEY_NAME, matNameStr);
  1294. String matName = SanitateAssetName(FromAIString(matNameStr));
  1295. if (matName.Trimmed().Empty())
  1296. matName = GenerateMaterialName(material);
  1297. // Do not actually create a material instance, but instead craft an xml file manually
  1298. XMLFile outMaterial(context_);
  1299. XMLElement materialElem = outMaterial.CreateRoot("material");
  1300. String diffuseTexName;
  1301. String normalTexName;
  1302. String specularTexName;
  1303. String lightmapTexName;
  1304. String emissiveTexName;
  1305. Color diffuseColor = Color::WHITE;
  1306. Color specularColor;
  1307. Color emissiveColor = Color::BLACK;
  1308. bool hasAlpha = false;
  1309. bool twoSided = false;
  1310. float specPower = 1.0f;
  1311. aiString stringVal;
  1312. float floatVal;
  1313. int intVal;
  1314. aiColor3D colorVal;
  1315. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1316. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1317. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1318. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1319. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), stringVal) == AI_SUCCESS)
  1320. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1321. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_LIGHTMAP, 0), stringVal) == AI_SUCCESS)
  1322. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1323. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_EMISSIVE, 0), stringVal) == AI_SUCCESS)
  1324. emissiveTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1325. if (!noMaterialDiffuseColor_)
  1326. {
  1327. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1328. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1329. }
  1330. if (material->Get(AI_MATKEY_COLOR_SPECULAR, colorVal) == AI_SUCCESS)
  1331. specularColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1332. if (!emissiveAO_)
  1333. {
  1334. if (material->Get(AI_MATKEY_COLOR_EMISSIVE, colorVal) == AI_SUCCESS)
  1335. emissiveColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1336. }
  1337. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1338. {
  1339. if (floatVal < 1.0f)
  1340. hasAlpha = true;
  1341. diffuseColor.a_ = floatVal;
  1342. }
  1343. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1344. specPower = floatVal;
  1345. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1346. twoSided = (intVal != 0);
  1347. String techniqueName = "Techniques/NoTexture";
  1348. if (!diffuseTexName.Empty())
  1349. {
  1350. techniqueName = "Techniques/Diff";
  1351. if (!normalTexName.Empty())
  1352. techniqueName += "Normal";
  1353. if (!specularTexName.Empty())
  1354. techniqueName += "Spec";
  1355. // For now lightmap does not coexist with normal & specular
  1356. if (normalTexName.Empty() && specularTexName.Empty() && !lightmapTexName.Empty())
  1357. techniqueName += "LightMap";
  1358. if (lightmapTexName.Empty() && !emissiveTexName.Empty())
  1359. techniqueName += emissiveAO_ ? "AO" : "Emissive";
  1360. }
  1361. if (hasAlpha)
  1362. techniqueName += "Alpha";
  1363. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1364. techniqueElem.SetString("name", techniqueName + ".xml");
  1365. if (!diffuseTexName.Empty())
  1366. {
  1367. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1368. diffuseElem.SetString("unit", "diffuse");
  1369. diffuseElem.SetString("name", GetMaterialTextureName(diffuseTexName));
  1370. usedTextures.Insert(diffuseTexName);
  1371. }
  1372. if (!normalTexName.Empty())
  1373. {
  1374. XMLElement normalElem = materialElem.CreateChild("texture");
  1375. normalElem.SetString("unit", "normal");
  1376. normalElem.SetString("name", GetMaterialTextureName(normalTexName));
  1377. usedTextures.Insert(normalTexName);
  1378. }
  1379. if (!specularTexName.Empty())
  1380. {
  1381. XMLElement specularElem = materialElem.CreateChild("texture");
  1382. specularElem.SetString("unit", "specular");
  1383. specularElem.SetString("name", GetMaterialTextureName(specularTexName));
  1384. usedTextures.Insert(specularTexName);
  1385. }
  1386. if (!lightmapTexName.Empty())
  1387. {
  1388. XMLElement lightmapElem = materialElem.CreateChild("texture");
  1389. lightmapElem.SetString("unit", "emissive");
  1390. lightmapElem.SetString("name", GetMaterialTextureName(lightmapTexName));
  1391. usedTextures.Insert(lightmapTexName);
  1392. }
  1393. if (!emissiveTexName.Empty())
  1394. {
  1395. XMLElement emissiveElem = materialElem.CreateChild("texture");
  1396. emissiveElem.SetString("unit", "emissive");
  1397. emissiveElem.SetString("name", GetMaterialTextureName(emissiveTexName));
  1398. usedTextures.Insert(emissiveTexName);
  1399. }
  1400. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1401. diffuseColorElem.SetString("name", "MatDiffColor");
  1402. diffuseColorElem.SetColor("value", diffuseColor);
  1403. XMLElement specularElem = materialElem.CreateChild("parameter");
  1404. specularElem.SetString("name", "MatSpecColor");
  1405. specularElem.SetVector4("value", Vector4(specularColor.r_, specularColor.g_, specularColor.b_, specPower));
  1406. XMLElement emissiveColorElem = materialElem.CreateChild("parameter");
  1407. emissiveColorElem.SetString("name", "MatEmissiveColor");
  1408. emissiveColorElem.SetColor("value", emissiveColor);
  1409. if (twoSided)
  1410. {
  1411. XMLElement cullElem = materialElem.CreateChild("cull");
  1412. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1413. cullElem.SetString("value", "none");
  1414. shadowCullElem.SetString("value", "none");
  1415. }
  1416. FileSystem* fileSystem = context_->GetSubsystem<FileSystem>();
  1417. String outFileName = resourcePath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".xml";
  1418. if (noOverwriteMaterial_ && fileSystem->FileExists(outFileName))
  1419. {
  1420. PrintLine("Skipping save of existing material " + matName);
  1421. return;
  1422. }
  1423. PrintLine("Writing material " + matName);
  1424. File outFile(context_);
  1425. if (!outFile.Open(outFileName, FILE_WRITE))
  1426. ErrorExit("Could not open output file " + outFileName);
  1427. outMaterial.Save(outFile);
  1428. }
  1429. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath)
  1430. {
  1431. FileSystem* fileSystem = context_->GetSubsystem<FileSystem>();
  1432. if (useSubdirs_)
  1433. fileSystem->CreateDir(resourcePath_ + "Textures");
  1434. for (HashSet<String>::ConstIterator i = usedTextures.Begin(); i != usedTextures.End(); ++i)
  1435. {
  1436. // Handle assimp embedded textures
  1437. if (i->Length() && i->At(0) == '*')
  1438. {
  1439. unsigned texIndex = ToInt(i->Substring(1));
  1440. if (texIndex >= scene_->mNumTextures)
  1441. PrintLine("Skipping out of range texture index " + String(texIndex));
  1442. else
  1443. {
  1444. aiTexture* tex = scene_->mTextures[texIndex];
  1445. String fullDestName = resourcePath_ + GenerateTextureName(texIndex);
  1446. bool destExists = fileSystem->FileExists(fullDestName);
  1447. if (destExists && noOverwriteTexture_)
  1448. {
  1449. PrintLine("Skipping copy of existing embedded texture " + GetFileNameAndExtension(fullDestName));
  1450. continue;
  1451. }
  1452. // Encoded texture
  1453. if (!tex->mHeight)
  1454. {
  1455. PrintLine("Saving embedded texture " + GetFileNameAndExtension(fullDestName));
  1456. File dest(context_, fullDestName, FILE_WRITE);
  1457. dest.Write((const void*)tex->pcData, tex->mWidth);
  1458. }
  1459. // RGBA8 texture
  1460. else
  1461. {
  1462. PrintLine("Saving embedded RGBA texture " + GetFileNameAndExtension(fullDestName));
  1463. Image image(context_);
  1464. image.SetSize(tex->mWidth, tex->mHeight, 4);
  1465. memcpy(image.GetData(), (const void*)tex->pcData, tex->mWidth * tex->mHeight * 4);
  1466. image.SavePNG(fullDestName);
  1467. }
  1468. }
  1469. }
  1470. else
  1471. {
  1472. String fullSourceName = sourcePath + *i;
  1473. String fullDestName = resourcePath_ + (useSubdirs_ ? "Textures/" : "") + *i;
  1474. if (!fileSystem->FileExists(fullSourceName))
  1475. {
  1476. PrintLine("Skipping copy of nonexisting material texture " + *i);
  1477. continue;
  1478. }
  1479. {
  1480. File test(context_, fullSourceName);
  1481. if (!test.GetSize())
  1482. {
  1483. PrintLine("Skipping copy of zero-size material texture " + *i);
  1484. continue;
  1485. }
  1486. }
  1487. bool destExists = fileSystem->FileExists(fullDestName);
  1488. if (destExists && noOverwriteTexture_)
  1489. {
  1490. PrintLine("Skipping copy of existing texture " + *i);
  1491. continue;
  1492. }
  1493. if (destExists && noOverwriteNewerTexture_ && fileSystem->GetLastModifiedTime(fullDestName) >
  1494. fileSystem->GetLastModifiedTime(fullSourceName))
  1495. {
  1496. PrintLine("Skipping copying of material texture " + *i + ", destination is newer");
  1497. continue;
  1498. }
  1499. PrintLine("Copying material texture " + *i);
  1500. fileSystem->Copy(fullSourceName, fullDestName);
  1501. }
  1502. }
  1503. }
  1504. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName)
  1505. {
  1506. // Load models
  1507. Vector<SharedPtr<Model> > srcModels;
  1508. for (unsigned i = 0; i < modelNames.Size(); ++i)
  1509. {
  1510. PrintLine("Reading LOD level " + String(i) + ": model " + modelNames[i] + " distance " + String(lodDistances[i]));
  1511. File srcFile(context_);
  1512. srcFile.Open(modelNames[i]);
  1513. SharedPtr<Model> srcModel(new Model(context_));
  1514. if (!srcModel->Load(srcFile))
  1515. ErrorExit("Could not load input model " + modelNames[i]);
  1516. srcModels.Push(srcModel);
  1517. }
  1518. // Check that none of the models already has LOD levels
  1519. for (unsigned i = 0; i < srcModels.Size(); ++i)
  1520. {
  1521. for (unsigned j = 0; j < srcModels[i]->GetNumGeometries(); ++j)
  1522. {
  1523. if (srcModels[i]->GetNumGeometryLodLevels(j) > 1)
  1524. ErrorExit(modelNames[i] + " already has multiple LOD levels defined");
  1525. }
  1526. }
  1527. // Check for number of geometries (need to have same amount for now)
  1528. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1529. {
  1530. if (srcModels[i]->GetNumGeometries() != srcModels[0]->GetNumGeometries())
  1531. ErrorExit(modelNames[i] + " has different amount of geometries than " + modelNames[0]);
  1532. }
  1533. // If there are bones, check for compatibility (need to have exact match for now)
  1534. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1535. {
  1536. if (srcModels[i]->GetSkeleton().GetNumBones() != srcModels[0]->GetSkeleton().GetNumBones())
  1537. ErrorExit(modelNames[i] + " has different amount of bones than " + modelNames[0]);
  1538. for (unsigned j = 0; j < srcModels[0]->GetSkeleton().GetNumBones(); ++j)
  1539. {
  1540. if (srcModels[i]->GetSkeleton().GetBone(j)->name_ != srcModels[0]->GetSkeleton().GetBone(j)->name_)
  1541. ErrorExit(modelNames[i] + " has different bones than " + modelNames[0]);
  1542. }
  1543. if (srcModels[i]->GetGeometryBoneMappings() != srcModels[0]->GetGeometryBoneMappings())
  1544. ErrorExit(modelNames[i] + " has different per-geometry bone mappings than " + modelNames[0]);
  1545. }
  1546. Vector<SharedPtr<VertexBuffer> > vbVector;
  1547. Vector<SharedPtr<IndexBuffer> > ibVector;
  1548. PODVector<unsigned> emptyMorphRange;
  1549. // Create the final model
  1550. SharedPtr<Model> outModel(new Model(context_));
  1551. outModel->SetNumGeometries(srcModels[0]->GetNumGeometries());
  1552. for (unsigned i = 0; i < srcModels[0]->GetNumGeometries(); ++i)
  1553. {
  1554. outModel->SetNumGeometryLodLevels(i, srcModels.Size());
  1555. for (unsigned j = 0; j < srcModels.Size(); ++j)
  1556. {
  1557. Geometry* geometry = srcModels[j]->GetGeometry(i, 0);
  1558. geometry->SetLodDistance(lodDistances[j]);
  1559. outModel->SetGeometry(i, j, geometry);
  1560. for (unsigned k = 0; k < geometry->GetNumVertexBuffers(); ++k)
  1561. {
  1562. SharedPtr<VertexBuffer> vb(geometry->GetVertexBuffer(k));
  1563. if (!vbVector.Contains(vb))
  1564. vbVector.Push(vb);
  1565. }
  1566. SharedPtr<IndexBuffer> ib(geometry->GetIndexBuffer());
  1567. if (!ibVector.Contains(ib))
  1568. ibVector.Push(ib);
  1569. }
  1570. }
  1571. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  1572. outModel->SetIndexBuffers(ibVector);
  1573. outModel->SetSkeleton(srcModels[0]->GetSkeleton());
  1574. outModel->SetGeometryBoneMappings(srcModels[0]->GetGeometryBoneMappings());
  1575. outModel->SetBoundingBox(srcModels[0]->GetBoundingBox());
  1576. /// \todo Vertex morphs are ignored for now
  1577. // Save the final model
  1578. PrintLine("Writing output model");
  1579. File outFile(context_);
  1580. if (!outFile.Open(outName, FILE_WRITE))
  1581. ErrorExit("Could not open output file " + outName);
  1582. outModel->Save(outFile);
  1583. }
  1584. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& dest, aiNode* node)
  1585. {
  1586. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  1587. dest.Push(MakePair(node, scene_->mMeshes[node->mMeshes[i]]));
  1588. }
  1589. unsigned GetMeshIndex(aiMesh* mesh)
  1590. {
  1591. for (unsigned i = 0; i < scene_->mNumMeshes; ++i)
  1592. {
  1593. if (scene_->mMeshes[i] == mesh)
  1594. return i;
  1595. }
  1596. return M_MAX_UNSIGNED;
  1597. }
  1598. unsigned GetBoneIndex(OutModel& model, const String& boneName)
  1599. {
  1600. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  1601. {
  1602. if (boneName == model.bones_[i]->mName.data)
  1603. return i;
  1604. }
  1605. return M_MAX_UNSIGNED;
  1606. }
  1607. aiBone* GetMeshBone(OutModel& model, const String& boneName)
  1608. {
  1609. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1610. {
  1611. aiMesh* mesh = model.meshes_[i];
  1612. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1613. {
  1614. aiBone* bone = mesh->mBones[j];
  1615. if (boneName == bone->mName.data)
  1616. return bone;
  1617. }
  1618. }
  1619. return 0;
  1620. }
  1621. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName)
  1622. {
  1623. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1624. {
  1625. aiMesh* mesh = model.meshes_[i];
  1626. aiNode* node = model.meshNodes_[i];
  1627. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1628. {
  1629. aiBone* bone = mesh->mBones[j];
  1630. if (boneName == bone->mName.data)
  1631. {
  1632. aiMatrix4x4 offset = bone->mOffsetMatrix;
  1633. aiMatrix4x4 nodeDerivedInverse = GetMeshBakingTransform(node, model.rootNode_);
  1634. nodeDerivedInverse.Inverse();
  1635. offset *= nodeDerivedInverse;
  1636. return ToMatrix3x4(offset);
  1637. }
  1638. }
  1639. }
  1640. return Matrix3x4::IDENTITY;
  1641. }
  1642. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  1643. blendIndices, Vector<PODVector<float> >& blendWeights)
  1644. {
  1645. blendIndices.Resize(mesh->mNumVertices);
  1646. blendWeights.Resize(mesh->mNumVertices);
  1647. boneMappings.Clear();
  1648. // If model has more bones than can fit vertex shader parameters, write the per-geometry mappings
  1649. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  1650. {
  1651. if (mesh->mNumBones > MAX_SKIN_MATRICES)
  1652. {
  1653. ErrorExit(
  1654. "Geometry (submesh) has over 64 bone influences. Try splitting to more submeshes\n"
  1655. "that each stay at 64 bones or below."
  1656. );
  1657. }
  1658. boneMappings.Resize(mesh->mNumBones);
  1659. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1660. {
  1661. aiBone* bone = mesh->mBones[i];
  1662. String boneName = FromAIString(bone->mName);
  1663. unsigned globalIndex = GetBoneIndex(model, boneName);
  1664. if (globalIndex == M_MAX_UNSIGNED)
  1665. ErrorExit("Bone " + boneName + " not found");
  1666. boneMappings[i] = globalIndex;
  1667. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1668. {
  1669. unsigned vertex = bone->mWeights[j].mVertexId;
  1670. blendIndices[vertex].Push(i);
  1671. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1672. if (blendWeights[vertex].Size() > 4)
  1673. ErrorExit("More than 4 bone influences on vertex");
  1674. }
  1675. }
  1676. }
  1677. else
  1678. {
  1679. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1680. {
  1681. aiBone* bone = mesh->mBones[i];
  1682. String boneName = FromAIString(bone->mName);
  1683. unsigned globalIndex = GetBoneIndex(model, boneName);
  1684. if (globalIndex == M_MAX_UNSIGNED)
  1685. ErrorExit("Bone " + boneName + " not found");
  1686. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1687. {
  1688. unsigned vertex = bone->mWeights[j].mVertexId;
  1689. blendIndices[vertex].Push(globalIndex);
  1690. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1691. if (blendWeights[vertex].Size() > 4)
  1692. ErrorExit("More than 4 bone influences on vertex");
  1693. }
  1694. }
  1695. }
  1696. }
  1697. String GetMeshMaterialName(aiMesh* mesh)
  1698. {
  1699. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  1700. aiString matNameStr;
  1701. material->Get(AI_MATKEY_NAME, matNameStr);
  1702. String matName = SanitateAssetName(FromAIString(matNameStr));
  1703. if (matName.Trimmed().Empty())
  1704. matName = GenerateMaterialName(material);
  1705. return (useSubdirs_ ? "Materials/" : "") + matName + ".xml";
  1706. }
  1707. String GenerateMaterialName(aiMaterial* material)
  1708. {
  1709. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  1710. {
  1711. if (scene_->mMaterials[i] == material)
  1712. return inputName_ + "_Material" + String(i);
  1713. }
  1714. // Should not go here
  1715. return String::EMPTY;
  1716. }
  1717. String GetMaterialTextureName(const String& nameIn)
  1718. {
  1719. // Detect assimp embedded texture
  1720. if (nameIn.Length() && nameIn[0] == '*')
  1721. return GenerateTextureName(ToInt(nameIn.Substring(1)));
  1722. else
  1723. return (useSubdirs_ ? "Textures/" : "") + nameIn;
  1724. }
  1725. String GenerateTextureName(unsigned texIndex)
  1726. {
  1727. if (texIndex < scene_->mNumTextures)
  1728. {
  1729. // If embedded texture contains encoded data, use the format hint for file extension. Else save RGBA8 data as PNG
  1730. aiTexture* tex = scene_->mTextures[texIndex];
  1731. if (!tex->mHeight)
  1732. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + "." + tex->achFormatHint;
  1733. else
  1734. return (useSubdirs_ ? "Textures/" : "") + inputName_ + "_Texture" + String(texIndex) + ".png";
  1735. }
  1736. // Should not go here
  1737. return String::EMPTY;
  1738. }
  1739. unsigned GetNumValidFaces(aiMesh* mesh)
  1740. {
  1741. unsigned ret = 0;
  1742. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  1743. {
  1744. if (mesh->mFaces[j].mNumIndices == 3)
  1745. ++ret;
  1746. }
  1747. return ret;
  1748. }
  1749. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1750. {
  1751. if (mesh->mFaces[index].mNumIndices == 3)
  1752. {
  1753. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1754. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1755. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1756. }
  1757. }
  1758. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1759. {
  1760. if (mesh->mFaces[index].mNumIndices == 3)
  1761. {
  1762. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1763. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1764. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1765. }
  1766. }
  1767. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  1768. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  1769. Vector<PODVector<float> >& blendWeights)
  1770. {
  1771. Vector3 vertex = vertexTransform * ToVector3(mesh->mVertices[index]);
  1772. box.Merge(vertex);
  1773. *dest++ = vertex.x_;
  1774. *dest++ = vertex.y_;
  1775. *dest++ = vertex.z_;
  1776. if (elementMask & MASK_NORMAL)
  1777. {
  1778. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1779. *dest++ = normal.x_;
  1780. *dest++ = normal.y_;
  1781. *dest++ = normal.z_;
  1782. }
  1783. if (elementMask & MASK_COLOR)
  1784. {
  1785. *((unsigned*)dest) = Color(mesh->mColors[0][index].r, mesh->mColors[0][index].g, mesh->mColors[0][index].b,
  1786. mesh->mColors[0][index].a).ToUInt();
  1787. ++dest;
  1788. }
  1789. if (elementMask & MASK_TEXCOORD1)
  1790. {
  1791. Vector3 texCoord = ToVector3(mesh->mTextureCoords[0][index]);
  1792. *dest++ = texCoord.x_;
  1793. *dest++ = texCoord.y_;
  1794. }
  1795. if (elementMask & MASK_TEXCOORD2)
  1796. {
  1797. Vector3 texCoord = ToVector3(mesh->mTextureCoords[1][index]);
  1798. *dest++ = texCoord.x_;
  1799. *dest++ = texCoord.y_;
  1800. }
  1801. if (elementMask & MASK_TANGENT)
  1802. {
  1803. Vector3 tangent = normalTransform * ToVector3(mesh->mTangents[index]);
  1804. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1805. Vector3 bitangent = normalTransform * ToVector3(mesh->mBitangents[index]);
  1806. // Check handedness
  1807. float w = 1.0f;
  1808. if ((tangent.CrossProduct(normal)).DotProduct(bitangent) < 0.5f)
  1809. w = -1.0f;
  1810. *dest++ = tangent.x_;
  1811. *dest++ = tangent.y_;
  1812. *dest++ = tangent.z_;
  1813. *dest++ = w;
  1814. }
  1815. if (elementMask & MASK_BLENDWEIGHTS)
  1816. {
  1817. for (unsigned i = 0; i < 4; ++i)
  1818. {
  1819. if (i < blendWeights[index].Size())
  1820. *dest++ = blendWeights[index][i];
  1821. else
  1822. *dest++ = 0.0f;
  1823. }
  1824. }
  1825. if (elementMask & MASK_BLENDINDICES)
  1826. {
  1827. unsigned char* destBytes = (unsigned char*)dest;
  1828. ++dest;
  1829. for (unsigned i = 0; i < 4; ++i)
  1830. {
  1831. if (i < blendIndices[index].Size())
  1832. *destBytes++ = blendIndices[index][i];
  1833. else
  1834. *destBytes++ = 0;
  1835. }
  1836. }
  1837. }
  1838. unsigned GetElementMask(aiMesh* mesh)
  1839. {
  1840. unsigned elementMask = MASK_POSITION;
  1841. if (mesh->HasNormals())
  1842. elementMask |= MASK_NORMAL;
  1843. if (mesh->HasTangentsAndBitangents())
  1844. elementMask |= MASK_TANGENT;
  1845. if (mesh->GetNumColorChannels() > 0)
  1846. elementMask |= MASK_COLOR;
  1847. if (mesh->GetNumUVChannels() > 0)
  1848. elementMask |= MASK_TEXCOORD1;
  1849. if (mesh->GetNumUVChannels() > 1)
  1850. elementMask |= MASK_TEXCOORD2;
  1851. if (mesh->HasBones())
  1852. elementMask |= (MASK_BLENDWEIGHTS | MASK_BLENDINDICES);
  1853. return elementMask;
  1854. }
  1855. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive)
  1856. {
  1857. if (!rootNode)
  1858. return 0;
  1859. if (!name.Compare(rootNode->mName.data, caseSensitive))
  1860. return rootNode;
  1861. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  1862. {
  1863. aiNode* found = GetNode(name, rootNode->mChildren[i], caseSensitive);
  1864. if (found)
  1865. return found;
  1866. }
  1867. return 0;
  1868. }
  1869. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode, bool rootInclusive)
  1870. {
  1871. return GetDerivedTransform(node->mTransformation, node, rootNode, rootInclusive);
  1872. }
  1873. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode, bool rootInclusive)
  1874. {
  1875. // If basenode is defined, go only up to it in the parent chain
  1876. while (node && node != rootNode)
  1877. {
  1878. node = node->mParent;
  1879. if (!rootInclusive && node == rootNode)
  1880. break;
  1881. if (node)
  1882. transform = node->mTransformation * transform;
  1883. }
  1884. return transform;
  1885. }
  1886. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode)
  1887. {
  1888. if (meshNode == modelRootNode)
  1889. return aiMatrix4x4();
  1890. else
  1891. return GetDerivedTransform(meshNode, modelRootNode);
  1892. }
  1893. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale)
  1894. {
  1895. aiVector3D aiPos;
  1896. aiQuaternion aiRot;
  1897. aiVector3D aiScale;
  1898. transform.Decompose(aiScale, aiRot, aiPos);
  1899. pos = ToVector3(aiPos);
  1900. rot = ToQuaternion(aiRot);
  1901. scale = ToVector3(aiScale);
  1902. }
  1903. String FromAIString(const aiString& str)
  1904. {
  1905. return String(str.data);
  1906. }
  1907. Vector3 ToVector3(const aiVector3D& vec)
  1908. {
  1909. return Vector3(vec.x, vec.y, vec.z);
  1910. }
  1911. Vector2 ToVector2(const aiVector2D& vec)
  1912. {
  1913. return Vector2(vec.x, vec.y);
  1914. }
  1915. Quaternion ToQuaternion(const aiQuaternion& quat)
  1916. {
  1917. return Quaternion(quat.w, quat.x, quat.y, quat.z);
  1918. }
  1919. Matrix3x4 ToMatrix3x4(const aiMatrix4x4& mat)
  1920. {
  1921. Matrix3x4 ret;
  1922. memcpy(&ret.m00_, &mat.a1, sizeof(Matrix3x4));
  1923. return ret;
  1924. }
  1925. String SanitateAssetName(const String& name)
  1926. {
  1927. String fixedName = name;
  1928. fixedName.Replace("<", "");
  1929. fixedName.Replace(">", "");
  1930. fixedName.Replace("?", "");
  1931. fixedName.Replace("*", "");
  1932. fixedName.Replace(":", "");
  1933. fixedName.Replace("\"", "");
  1934. fixedName.Replace("/", "");
  1935. fixedName.Replace("\\", "");
  1936. fixedName.Replace("|", "");
  1937. return fixedName;
  1938. }