AssetImporter.cpp 91 KB

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