AssetImporter.cpp 82 KB

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