AssetImporter.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. //
  2. // Copyright (c) 2008-2013 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 "Animation.h"
  23. #include "Context.h"
  24. #include "DebugRenderer.h"
  25. #include "File.h"
  26. #include "FileSystem.h"
  27. #include "Geometry.h"
  28. #include "Graphics.h"
  29. #include "IndexBuffer.h"
  30. #include "Light.h"
  31. #include "Material.h"
  32. #include "Model.h"
  33. #include "Octree.h"
  34. #include "PhysicsWorld.h"
  35. #include "ProcessUtils.h"
  36. #include "Quaternion.h"
  37. #include "ResourceCache.h"
  38. #include "Scene.h"
  39. #include "StaticModel.h"
  40. #include "StringUtils.h"
  41. #include "Vector3.h"
  42. #include "VertexBuffer.h"
  43. #include "WorkQueue.h"
  44. #include "XMLFile.h"
  45. #include "Zone.h"
  46. #include "Sort.h"
  47. #ifdef WIN32
  48. #include <windows.h>
  49. #endif
  50. #include <assimp/cimport.h>
  51. #include <assimp/scene.h>
  52. #include <assimp/postprocess.h>
  53. #include <cstring>
  54. #include "DebugNew.h"
  55. using namespace Urho3D;
  56. struct OutModel
  57. {
  58. OutModel() :
  59. rootBone_(0),
  60. totalVertices_(0),
  61. totalIndices_(0)
  62. {
  63. }
  64. String outName_;
  65. aiNode* rootNode_;
  66. HashSet<unsigned> meshIndices_;
  67. PODVector<aiMesh*> meshes_;
  68. PODVector<aiNode*> meshNodes_;
  69. PODVector<aiNode*> bones_;
  70. PODVector<aiAnimation*> animations_;
  71. PODVector<float> boneRadii_;
  72. PODVector<BoundingBox> boneHitboxes_;
  73. aiNode* rootBone_;
  74. unsigned totalVertices_;
  75. unsigned totalIndices_;
  76. };
  77. struct OutScene
  78. {
  79. String outName_;
  80. aiNode* rootNode_;
  81. Vector<OutModel> models_;
  82. PODVector<aiNode*> nodes_;
  83. PODVector<unsigned> nodeModelIndices_;
  84. };
  85. SharedPtr<Context> context_(new Context());
  86. const aiScene* scene_ = 0;
  87. aiNode* rootNode_ = 0;
  88. String resourcePath_;
  89. bool useSubdirs_ = true;
  90. bool localIDs_ = false;
  91. bool saveBinary_ = false;
  92. bool createZone_ = true;
  93. bool noAnimations_ = false;
  94. bool noMaterials_ = false;
  95. float defaultTicksPerSecond_ = 4800.0f;
  96. int main(int argc, char** argv);
  97. void Run(const Vector<String>& arguments);
  98. void DumpNodes(aiNode* rootNode, unsigned level);
  99. void ExportModel(const String& outName);
  100. void CollectMeshes(OutModel& model, aiNode* node);
  101. void CollectBones(OutModel& model);
  102. void CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node);
  103. void CollectAnimations(OutModel& model);
  104. void BuildBoneCollisionInfo(OutModel& model);
  105. void BuildAndSaveModel(OutModel& model);
  106. void BuildAndSaveAnimations(OutModel& model);
  107. void ExportScene(const String& outName);
  108. void CollectSceneModels(OutScene& scene, aiNode* node);
  109. void BuildAndSaveScene(OutScene& scene);
  110. void ExportMaterials(HashSet<String>& usedTextures);
  111. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures);
  112. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath);
  113. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName);
  114. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& meshes, aiNode* node);
  115. unsigned GetMeshIndex(aiMesh* mesh);
  116. unsigned GetBoneIndex(OutModel& model, const String& boneName);
  117. aiBone* GetMeshBone(OutModel& model, const String& boneName);
  118. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName);
  119. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  120. blendIndices, Vector<PODVector<float> >& blendWeights);
  121. String GetMeshMaterialName(aiMesh* mesh);
  122. unsigned GetNumValidFaces(aiMesh* mesh);
  123. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  124. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset);
  125. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  126. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  127. Vector<PODVector<float> >& blendWeights);
  128. unsigned GetElementMask(aiMesh* mesh);
  129. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive = true);
  130. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode);
  131. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode);
  132. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode);
  133. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale);
  134. String FromAIString(const aiString& str);
  135. Vector3 ToVector3(const aiVector3D& vec);
  136. Vector2 ToVector2(const aiVector2D& vec);
  137. Quaternion ToQuaternion(const aiQuaternion& quat);
  138. String SanitateAssetName(const String& name);
  139. int main(int argc, char** argv)
  140. {
  141. Vector<String> arguments;
  142. #ifdef WIN32
  143. arguments = ParseArguments(GetCommandLineW());
  144. #else
  145. arguments = ParseArguments(argc, argv);
  146. #endif
  147. Run(arguments);
  148. return 0;
  149. }
  150. void Run(const Vector<String>& arguments)
  151. {
  152. if (arguments.Size() < 2)
  153. {
  154. ErrorExit(
  155. "Usage: AssetImporter <command> <input file> <output file> [options]\n"
  156. "See http://assimp.sourceforge.net/main_features_formats.html for input formats\n\n"
  157. "Commands:\n"
  158. "model Output a model and a material list\n"
  159. "scene Output a scene\n"
  160. "dump Dump scene node structure. No output file is generated\n"
  161. "lod Combine several Urho3D models as LOD levels of the output model\n"
  162. " Syntax: lod <dist0> <mdl0> <dist1 <mdl1> ... <output file>\n"
  163. "\n"
  164. "Options:\n"
  165. "-b Save scene in binary format, default format is XML\n"
  166. "-h Generate hard instead of smooth normals if input file has no normals\n"
  167. "-i Use local ID's for scene nodes\n"
  168. "-na Do not output animations\n"
  169. "-nm Do not output materials\n"
  170. "-ns Do not create subdirectories for resources\n"
  171. "-nz Do not create a zone and a directional light (scene mode only)\n"
  172. "-pX Set path X for scene resources. Default is output file path\n"
  173. "-rX Use scene node X as root node\n"
  174. "-fX Animation tick frequency to use if unspecified. Default 4800\n"
  175. "-t Generate tangents\n"
  176. );
  177. }
  178. RegisterSceneLibrary(context_);
  179. RegisterGraphicsLibrary(context_);
  180. RegisterPhysicsLibrary(context_);
  181. context_->RegisterSubsystem(new FileSystem(context_));
  182. context_->RegisterSubsystem(new ResourceCache(context_));
  183. context_->RegisterSubsystem(new WorkQueue(context_));
  184. String command = arguments[0].ToLower();
  185. String rootNodeName;
  186. unsigned flags =
  187. aiProcess_ConvertToLeftHanded |
  188. aiProcess_JoinIdenticalVertices |
  189. aiProcess_Triangulate |
  190. aiProcess_GenSmoothNormals |
  191. aiProcess_LimitBoneWeights |
  192. aiProcess_ImproveCacheLocality |
  193. aiProcess_RemoveRedundantMaterials |
  194. aiProcess_FixInfacingNormals |
  195. aiProcess_FindInvalidData |
  196. aiProcess_GenUVCoords |
  197. aiProcess_FindInstances |
  198. aiProcess_OptimizeMeshes;
  199. for (unsigned i = 2; i < arguments.Size(); ++i)
  200. {
  201. if (arguments[i].Length() >= 2 && arguments[i][0] == '-')
  202. {
  203. String parameter;
  204. if (arguments[i].Length() >= 3)
  205. parameter = arguments[i].Substring(2);
  206. switch (tolower(arguments[i][1]))
  207. {
  208. case 'b':
  209. saveBinary_ = true;
  210. break;
  211. case 'h':
  212. flags &= ~aiProcess_GenSmoothNormals;
  213. flags |= aiProcess_GenNormals;
  214. break;
  215. case 'i':
  216. localIDs_ = true;
  217. break;
  218. case 'p':
  219. resourcePath_ = AddTrailingSlash(parameter);
  220. break;
  221. case 'r':
  222. rootNodeName = parameter;
  223. break;
  224. case 't':
  225. flags |= aiProcess_CalcTangentSpace;
  226. break;
  227. case 'f':
  228. defaultTicksPerSecond_ = ToFloat(parameter);
  229. break;
  230. case 'n':
  231. if (!parameter.Empty())
  232. {
  233. switch (tolower(parameter[0]))
  234. {
  235. case 'a':
  236. noAnimations_ = true;
  237. break;
  238. case 'm':
  239. noMaterials_ = true;
  240. break;
  241. case 's':
  242. useSubdirs_ = false;
  243. break;
  244. case 'z':
  245. createZone_ = false;
  246. break;
  247. }
  248. }
  249. break;
  250. }
  251. }
  252. }
  253. if (command == "model" || command == "scene" || command == "dump")
  254. {
  255. String inFile = arguments[1];
  256. String outFile;
  257. if (arguments.Size() > 2 && arguments[2][0] != '-')
  258. outFile = GetInternalPath(arguments[2]);
  259. if (resourcePath_.Empty())
  260. {
  261. resourcePath_ = GetPath(outFile);
  262. // If output file already has the Models/ path (model mode), do not take it into the resource path
  263. if (command == "model")
  264. {
  265. String resPathLower = resourcePath_.ToLower();
  266. if (resPathLower.FindLast("models/") == resPathLower.Length() - 7)
  267. resourcePath_ = resourcePath_.Substring(0, resourcePath_.Length() - 7);
  268. }
  269. if (resourcePath_.Empty())
  270. resourcePath_ = "./";
  271. }
  272. resourcePath_ = AddTrailingSlash(resourcePath_);
  273. if (command != "dump" && outFile.Empty())
  274. ErrorExit("No output file defined");
  275. PrintLine("Reading file " + inFile);
  276. scene_ = aiImportFile(GetNativePath(inFile).CString(), flags);
  277. if (!scene_)
  278. ErrorExit("Could not open or parse input file " + inFile);
  279. rootNode_ = scene_->mRootNode;
  280. if (!rootNodeName.Empty())
  281. {
  282. rootNode_ = GetNode(rootNodeName, rootNode_, false);
  283. if (!rootNode_)
  284. ErrorExit("Could not find scene node " + rootNodeName);
  285. }
  286. if (command == "dump")
  287. {
  288. DumpNodes(rootNode_, 0);
  289. return;
  290. }
  291. if (command == "model")
  292. ExportModel(outFile);
  293. if (command == "scene")
  294. ExportScene(outFile);
  295. if (!noMaterials_)
  296. {
  297. HashSet<String> usedTextures;
  298. ExportMaterials(usedTextures);
  299. CopyTextures(usedTextures, GetPath(inFile));
  300. }
  301. }
  302. else if (command == "lod")
  303. {
  304. PODVector<float> lodDistances;
  305. Vector<String> modelNames;
  306. String outFile;
  307. unsigned numLodArguments = 0;
  308. for (unsigned i = 1; i < arguments.Size(); ++i)
  309. {
  310. if (arguments[i][0] == '-')
  311. break;
  312. ++numLodArguments;
  313. }
  314. if (numLodArguments < 4)
  315. ErrorExit("Must define at least 2 LOD levels");
  316. if (!(numLodArguments & 1))
  317. ErrorExit("No output file defined");
  318. for (unsigned i = 1; i < numLodArguments + 1; ++i)
  319. {
  320. if (i == numLodArguments)
  321. outFile = GetInternalPath(arguments[i]);
  322. else
  323. {
  324. if (i & 1)
  325. lodDistances.Push(Max(ToFloat(arguments[i]), 0.0f));
  326. else
  327. modelNames.Push(GetInternalPath(arguments[i]));
  328. }
  329. }
  330. if (lodDistances[0] != 0.0f)
  331. {
  332. PrintLine("Warning: first LOD distance forced to 0");
  333. lodDistances[0] = 0.0f;
  334. }
  335. CombineLods(lodDistances, modelNames, outFile);
  336. }
  337. else
  338. ErrorExit("Unrecognized command " + command);
  339. }
  340. void DumpNodes(aiNode* rootNode, unsigned level)
  341. {
  342. if (!rootNode)
  343. return;
  344. String indent(' ', level * 2);
  345. Vector3 pos, scale;
  346. Quaternion rot;
  347. aiMatrix4x4 transform = GetDerivedTransform(rootNode, rootNode_);
  348. GetPosRotScale(transform, pos, rot, scale);
  349. PrintLine(indent + "Node " + FromAIString(rootNode->mName) + " pos " + String(pos));
  350. if (rootNode->mNumMeshes == 1)
  351. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometry");
  352. if (rootNode->mNumMeshes > 1)
  353. PrintLine(indent + " " + String(rootNode->mNumMeshes) + " geometries");
  354. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  355. DumpNodes(rootNode->mChildren[i], level + 1);
  356. }
  357. void ExportModel(const String& outName)
  358. {
  359. if (outName.Empty())
  360. ErrorExit("No output file defined");
  361. OutModel model;
  362. model.rootNode_ = rootNode_;
  363. model.outName_ = outName;
  364. CollectMeshes(model, model.rootNode_);
  365. CollectBones(model);
  366. BuildBoneCollisionInfo(model);
  367. BuildAndSaveModel(model);
  368. if (!noAnimations_)
  369. {
  370. CollectAnimations(model);
  371. BuildAndSaveAnimations(model);
  372. }
  373. }
  374. void CollectMeshes(OutModel& model, aiNode* node)
  375. {
  376. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  377. {
  378. aiMesh* mesh = scene_->mMeshes[node->mMeshes[i]];
  379. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  380. {
  381. if (mesh == model.meshes_[j])
  382. {
  383. PrintLine("Warning: same mesh found multiple times");
  384. break;
  385. }
  386. }
  387. model.meshIndices_.Insert(node->mMeshes[i]);
  388. model.meshes_.Push(mesh);
  389. model.meshNodes_.Push(node);
  390. model.totalVertices_ += mesh->mNumVertices;
  391. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  392. }
  393. for (unsigned i = 0; i < node->mNumChildren; ++i)
  394. CollectMeshes(model, node->mChildren[i]);
  395. }
  396. void CollectBones(OutModel& model)
  397. {
  398. HashSet<aiNode*> necessary;
  399. HashSet<aiNode*> rootNodes;
  400. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  401. {
  402. aiMesh* mesh = model.meshes_[i];
  403. aiNode* meshNode = model.meshNodes_[i];
  404. aiNode* meshParentNode = meshNode->mParent;
  405. aiNode* rootNode = 0;
  406. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  407. {
  408. aiBone* bone = mesh->mBones[j];
  409. String boneName(FromAIString(bone->mName));
  410. aiNode* boneNode = GetNode(boneName, scene_->mRootNode, true);
  411. if (!boneNode)
  412. ErrorExit("Could not find scene node for bone " + boneName);
  413. necessary.Insert(boneNode);
  414. rootNode = boneNode;
  415. for (;;)
  416. {
  417. boneNode = boneNode->mParent;
  418. if (!boneNode || boneNode == meshNode || boneNode == meshParentNode)
  419. break;
  420. rootNode = boneNode;
  421. necessary.Insert(boneNode);
  422. }
  423. if (rootNodes.Find(rootNode) == rootNodes.End())
  424. rootNodes.Insert(rootNode);
  425. }
  426. }
  427. // If we find multiple root nodes, try to remedy by using their parent instead
  428. if (rootNodes.Size() > 1)
  429. {
  430. aiNode* commonParent = (*rootNodes.Begin())->mParent;
  431. for (HashSet<aiNode*>::Iterator i = rootNodes.Begin(); i != rootNodes.End(); ++i)
  432. {
  433. if (*i != commonParent)
  434. {
  435. if (!commonParent || (*i)->mParent != commonParent)
  436. ErrorExit("Skeleton with multiple root nodes found, not supported");
  437. }
  438. }
  439. rootNodes.Clear();
  440. rootNodes.Insert(commonParent);
  441. necessary.Insert(commonParent);
  442. }
  443. if (rootNodes.Empty())
  444. return;
  445. model.rootBone_ = *rootNodes.Begin();
  446. CollectBonesFinal(model.bones_, necessary, model.rootBone_);
  447. // Initialize the bone collision info
  448. model.boneRadii_.Resize(model.bones_.Size());
  449. model.boneHitboxes_.Resize(model.bones_.Size());
  450. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  451. {
  452. model.boneRadii_[i] = 0.0f;
  453. model.boneHitboxes_[i] = BoundingBox(0.0f, 0.0f);
  454. }
  455. }
  456. void CollectBonesFinal(PODVector<aiNode*>& dest, const HashSet<aiNode*>& necessary, aiNode* node)
  457. {
  458. if (necessary.Find(node) != necessary.End())
  459. {
  460. dest.Push(node);
  461. for (unsigned i = 0; i < node->mNumChildren; ++i)
  462. CollectBonesFinal(dest, necessary, node->mChildren[i]);
  463. }
  464. }
  465. void CollectAnimations(OutModel& model)
  466. {
  467. const aiScene* scene = scene_;
  468. for (unsigned i = 0; i < scene->mNumAnimations; ++i)
  469. {
  470. aiAnimation* anim = scene->mAnimations[i];
  471. bool modelBoneFound = false;
  472. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  473. {
  474. aiNodeAnim* channel = anim->mChannels[j];
  475. String channelName = FromAIString(channel->mNodeName);
  476. if (GetBoneIndex(model, channelName) != M_MAX_UNSIGNED)
  477. {
  478. modelBoneFound = true;
  479. break;
  480. }
  481. }
  482. if (modelBoneFound)
  483. model.animations_.Push(anim);
  484. }
  485. /// \todo Vertex morphs are ignored for now
  486. }
  487. void BuildBoneCollisionInfo(OutModel& model)
  488. {
  489. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  490. {
  491. aiMesh* mesh = model.meshes_[i];
  492. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  493. {
  494. aiBone* bone = mesh->mBones[j];
  495. String boneName = FromAIString(bone->mName);
  496. unsigned boneIndex = GetBoneIndex(model, boneName);
  497. if (boneIndex == M_MAX_UNSIGNED)
  498. continue;
  499. for (unsigned k = 0; k < bone->mNumWeights; ++k)
  500. {
  501. float weight = bone->mWeights[k].mWeight;
  502. if (weight > 0.33f)
  503. {
  504. aiVector3D vertexBoneSpace = bone->mOffsetMatrix * mesh->mVertices[bone->mWeights[k].mVertexId];
  505. Vector3 vertex = ToVector3(vertexBoneSpace);
  506. float radius = vertex.Length();
  507. if (radius > model.boneRadii_[boneIndex])
  508. model.boneRadii_[boneIndex] = radius;
  509. model.boneHitboxes_[boneIndex].Merge(vertex);
  510. }
  511. }
  512. }
  513. }
  514. }
  515. void BuildAndSaveModel(OutModel& model)
  516. {
  517. if (!model.rootNode_)
  518. ErrorExit("Null root node for model");
  519. String rootNodeName = FromAIString(model.rootNode_->mName);
  520. if (!model.meshes_.Size())
  521. ErrorExit("No geometries found starting from node " + rootNodeName);
  522. PrintLine("Writing model " + rootNodeName);
  523. SharedPtr<Model> outModel(new Model(context_));
  524. outModel->SetNumGeometries(model.meshes_.Size());
  525. Vector<PODVector<unsigned> > allBoneMappings;
  526. BoundingBox box;
  527. bool combineBuffers = true;
  528. // Check if buffers can be combined (same vertex element mask, under 65535 vertices)
  529. unsigned elementMask = GetElementMask(model.meshes_[0]);
  530. for (unsigned i = 1; i < model.meshes_.Size(); ++i)
  531. {
  532. if (GetElementMask(model.meshes_[i]) != elementMask)
  533. {
  534. combineBuffers = false;
  535. break;
  536. }
  537. }
  538. // Check if keeping separate buffers allows to avoid 32-bit indices
  539. if (combineBuffers && model.totalVertices_ > 65535)
  540. {
  541. bool allUnder65k = true;
  542. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  543. {
  544. if (model.meshes_[i]->mNumVertices > 65535)
  545. allUnder65k = false;
  546. }
  547. if (allUnder65k == true)
  548. combineBuffers = false;
  549. }
  550. /// \todo Skip empty submeshes (if no valid faces)
  551. SharedPtr<IndexBuffer> ib;
  552. SharedPtr<VertexBuffer> vb;
  553. Vector<SharedPtr<VertexBuffer> > vbVector;
  554. Vector<SharedPtr<IndexBuffer> > ibVector;
  555. unsigned startVertexOffset = 0;
  556. unsigned startIndexOffset = 0;
  557. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  558. {
  559. aiMesh* mesh = model.meshes_[i];
  560. unsigned elementMask = GetElementMask(mesh);
  561. unsigned validFaces = GetNumValidFaces(mesh);
  562. bool largeIndices;
  563. if (combineBuffers)
  564. largeIndices = model.totalIndices_ > 65535;
  565. else
  566. largeIndices = mesh->mNumVertices > 65535;
  567. // Create new buffers if necessary
  568. if (!combineBuffers || vbVector.Empty())
  569. {
  570. vb = new VertexBuffer(context_);
  571. ib = new IndexBuffer(context_);
  572. if (combineBuffers)
  573. {
  574. ib->SetSize(model.totalIndices_, largeIndices);
  575. vb->SetSize(model.totalVertices_, elementMask);
  576. }
  577. else
  578. {
  579. ib->SetSize(validFaces * 3, largeIndices);
  580. vb->SetSize(mesh->mNumVertices, elementMask);
  581. }
  582. vbVector.Push(vb);
  583. ibVector.Push(ib);
  584. startVertexOffset = 0;
  585. startIndexOffset = 0;
  586. }
  587. // Get the world transform of the mesh for baking into the vertices
  588. Matrix3x4 vertexTransform;
  589. Matrix3 normalTransform;
  590. Vector3 pos, scale;
  591. Quaternion rot;
  592. GetPosRotScale(GetMeshBakingTransform(model.meshNodes_[i], model.rootNode_), pos, rot, scale);
  593. vertexTransform = Matrix3x4(pos, rot, scale);
  594. normalTransform = rot.RotationMatrix();
  595. SharedPtr<Geometry> geom(new Geometry(context_));
  596. PrintLine("Writing geometry " + String(i) + " with " + String(mesh->mNumVertices) + " vertices " +
  597. String(validFaces * 3) + " indices");
  598. unsigned char* vertexData = vb->GetShadowData();
  599. unsigned char* indexData = ib->GetShadowData();
  600. // Build the index data
  601. if (!largeIndices)
  602. {
  603. unsigned short* dest = (unsigned short*)indexData + startIndexOffset;
  604. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  605. WriteShortIndices(dest, mesh, j, startVertexOffset);
  606. }
  607. else
  608. {
  609. unsigned* dest = (unsigned*)indexData + startIndexOffset;
  610. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  611. WriteLargeIndices(dest, mesh, j, startVertexOffset);
  612. }
  613. // Build the vertex data
  614. // If there are bones, get blend data
  615. Vector<PODVector<unsigned char> > blendIndices;
  616. Vector<PODVector<float> > blendWeights;
  617. PODVector<unsigned> boneMappings;
  618. if (model.bones_.Size())
  619. GetBlendData(model, mesh, boneMappings, blendIndices, blendWeights);
  620. float* dest = (float*)((unsigned char*)vertexData + startVertexOffset * vb->GetVertexSize());
  621. for (unsigned j = 0; j < mesh->mNumVertices; ++j)
  622. WriteVertex(dest, mesh, j, elementMask, box, vertexTransform, normalTransform, blendIndices, blendWeights);
  623. // Calculate the geometry center
  624. Vector3 center = Vector3::ZERO;
  625. if (validFaces)
  626. {
  627. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  628. {
  629. if (mesh->mFaces[j].mNumIndices == 3)
  630. {
  631. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[0]]);
  632. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[1]]);
  633. center += vertexTransform * ToVector3(mesh->mVertices[mesh->mFaces[j].mIndices[2]]);
  634. }
  635. }
  636. center /= (float)validFaces * 3;
  637. }
  638. // Define the model buffers
  639. Vector<SharedPtr<VertexBuffer> > vbVector;
  640. Vector<SharedPtr<IndexBuffer> > ibVector;
  641. PODVector<unsigned> emptyMorphRange;
  642. vbVector.Push(vb);
  643. ibVector.Push(ib);
  644. outModel->SetVertexBuffers(vbVector, emptyMorphRange, emptyMorphRange);
  645. outModel->SetIndexBuffers(ibVector);
  646. // Define the geometry
  647. geom->SetIndexBuffer(ib);
  648. geom->SetVertexBuffer(0, vb);
  649. geom->SetDrawRange(TRIANGLE_LIST, startIndexOffset, validFaces * 3, true);
  650. outModel->SetNumGeometryLodLevels(i, 1);
  651. outModel->SetGeometry(i, 0, geom);
  652. outModel->SetGeometryCenter(i, center);
  653. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  654. allBoneMappings.Push(boneMappings);
  655. startVertexOffset += mesh->mNumVertices;
  656. startIndexOffset += validFaces * 3;
  657. }
  658. outModel->SetBoundingBox(box);
  659. // Build skeleton if necessary
  660. if (model.bones_.Size() && model.rootBone_)
  661. {
  662. PrintLine("Writing skeleton with " + String(model.bones_.Size()) + " bones, rootbone " +
  663. FromAIString(model.rootBone_->mName));
  664. Skeleton skeleton;
  665. Vector<Bone>& bones = skeleton.GetModifiableBones();
  666. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  667. {
  668. aiNode* boneNode = model.bones_[i];
  669. String boneName(FromAIString(boneNode->mName));
  670. Bone newBone;
  671. newBone.name_ = boneName;
  672. aiMatrix4x4 transform = boneNode->mTransformation;
  673. // Make the root bone transform relative to the model's root node, if it is not already
  674. if (boneNode == model.rootBone_)
  675. transform = GetDerivedTransform(boneNode, model.rootNode_);
  676. GetPosRotScale(transform, newBone.initialPosition_, newBone.initialRotation_, newBone.initialScale_);
  677. // Get offset information if exists
  678. newBone.offsetMatrix_ = GetOffsetMatrix(model, boneName);
  679. newBone.radius_ = model.boneRadii_[i];
  680. newBone.boundingBox_ = model.boneHitboxes_[i];
  681. newBone.collisionMask_ = BONECOLLISION_SPHERE | BONECOLLISION_BOX;
  682. newBone.parentIndex_ = i;
  683. bones.Push(newBone);
  684. }
  685. // Set the bone hierarchy
  686. for (unsigned i = 1; i < model.bones_.Size(); ++i)
  687. {
  688. String parentName = FromAIString(model.bones_[i]->mParent->mName);
  689. for (unsigned j = 0; j < bones.Size(); ++j)
  690. {
  691. if (bones[j].name_ == parentName)
  692. {
  693. bones[i].parentIndex_ = j;
  694. break;
  695. }
  696. }
  697. }
  698. outModel->SetSkeleton(skeleton);
  699. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  700. outModel->SetGeometryBoneMappings(allBoneMappings);
  701. }
  702. File outFile(context_);
  703. if (!outFile.Open(model.outName_, FILE_WRITE))
  704. ErrorExit("Could not open output file " + model.outName_);
  705. outModel->Save(outFile);
  706. // If exporting materials, also save material list for use by the editor
  707. if (!noMaterials_)
  708. {
  709. String materialListName = ReplaceExtension(model.outName_, ".txt");
  710. File listFile(context_);
  711. if (listFile.Open(materialListName, FILE_WRITE))
  712. {
  713. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  714. listFile.WriteLine(GetMeshMaterialName(model.meshes_[i]));
  715. }
  716. else
  717. PrintLine("Warning: could not write material list file " + materialListName);
  718. }
  719. }
  720. void BuildAndSaveAnimations(OutModel& model)
  721. {
  722. for (unsigned i = 0; i < model.animations_.Size(); ++i)
  723. {
  724. aiAnimation* anim = model.animations_[i];
  725. String animName = FromAIString(anim->mName);
  726. if (animName.Empty())
  727. animName = "Anim" + String(i + 1);
  728. String animOutName = GetPath(model.outName_) + GetFileName(model.outName_) + "_" + SanitateAssetName(animName) + ".ani";
  729. SharedPtr<Animation> outAnim(new Animation(context_));
  730. float ticksPerSecond = (float)anim->mTicksPerSecond;
  731. // If ticks per second not specified, it's probably a .X file. In this case use the default tick rate
  732. if (ticksPerSecond < M_EPSILON)
  733. ticksPerSecond = defaultTicksPerSecond_;
  734. float tickConversion = 1.0f / ticksPerSecond;
  735. outAnim->SetAnimationName(animName);
  736. outAnim->SetLength((float)anim->mDuration * tickConversion);
  737. PrintLine("Writing animation " + animName + " length " + String(outAnim->GetLength()));
  738. Vector<AnimationTrack> tracks;
  739. for (unsigned j = 0; j < anim->mNumChannels; ++j)
  740. {
  741. aiNodeAnim* channel = anim->mChannels[j];
  742. String channelName = FromAIString(channel->mNodeName);
  743. unsigned boneIndex = GetBoneIndex(model, channelName);
  744. if (boneIndex == M_MAX_UNSIGNED)
  745. {
  746. PrintLine("Warning: skipping animation track " + channelName + " not found in model skeleton");
  747. continue;
  748. }
  749. aiNode* boneNode = model.bones_[boneIndex];
  750. AnimationTrack track;
  751. track.name_ = channelName;
  752. track.nameHash_ = StringHash(channelName);
  753. // Check which channels are used
  754. track.channelMask_ = 0;
  755. if (channel->mNumPositionKeys > 1)
  756. track.channelMask_ |= CHANNEL_POSITION;
  757. if (channel->mNumRotationKeys > 1)
  758. track.channelMask_ |= CHANNEL_ROTATION;
  759. if (channel->mNumScalingKeys > 1)
  760. track.channelMask_ |= CHANNEL_SCALE;
  761. // Check for redundant identity scale in all keyframes and remove in that case
  762. if (track.channelMask_ & CHANNEL_SCALE)
  763. {
  764. bool redundantScale = true;
  765. for (unsigned k = 0; k < channel->mNumScalingKeys; ++k)
  766. {
  767. float SCALE_EPSILON = 0.000001f;
  768. Vector3 scaleVec = ToVector3(channel->mScalingKeys[k].mValue);
  769. if (fabsf(scaleVec.x_ - 1.0f) >= SCALE_EPSILON || fabsf(scaleVec.y_ - 1.0f) >= SCALE_EPSILON ||
  770. fabsf(scaleVec.z_ - 1.0f) >= SCALE_EPSILON)
  771. {
  772. redundantScale = false;
  773. break;
  774. }
  775. }
  776. if (redundantScale)
  777. track.channelMask_ &= ~CHANNEL_SCALE;
  778. }
  779. if (!track.channelMask_)
  780. PrintLine("Warning: skipping animation track " + channelName + " with no keyframes");
  781. // Currently only same amount of keyframes is supported
  782. // Note: should also check the times of individual keyframes for match
  783. if ((channel->mNumPositionKeys > 1 && channel->mNumRotationKeys > 1 && channel->mNumPositionKeys != channel->mNumRotationKeys) ||
  784. (channel->mNumPositionKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumPositionKeys != channel->mNumScalingKeys) ||
  785. (channel->mNumRotationKeys > 1 && channel->mNumScalingKeys > 1 && channel->mNumRotationKeys != channel->mNumScalingKeys))
  786. {
  787. PrintLine("Warning: differing amounts of channel keyframes, skipping animation track " + channelName);
  788. continue;
  789. }
  790. unsigned keyFrames = channel->mNumPositionKeys;
  791. if (channel->mNumRotationKeys > keyFrames)
  792. keyFrames = channel->mNumRotationKeys;
  793. if (channel->mNumScalingKeys > keyFrames)
  794. keyFrames = channel->mNumScalingKeys;
  795. for (unsigned k = 0; k < keyFrames; ++k)
  796. {
  797. AnimationKeyFrame kf;
  798. kf.time_ = 0.0f;
  799. kf.position_ = Vector3::ZERO;
  800. kf.rotation_ = Quaternion::IDENTITY;
  801. kf.scale_ = Vector3::ONE;
  802. // Get time for the keyframe
  803. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  804. kf.time_ = (float)channel->mPositionKeys[k].mTime * tickConversion;
  805. else if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  806. kf.time_ = (float)channel->mRotationKeys[k].mTime * tickConversion;
  807. else if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  808. kf.time_ = (float)channel->mScalingKeys[k].mTime * tickConversion;
  809. // Start with the bone's base transform
  810. aiMatrix4x4 boneTransform = boneNode->mTransformation;
  811. aiVector3D pos, scale;
  812. aiQuaternion rot;
  813. boneTransform.Decompose(scale, rot, pos);
  814. // Then apply the active channels
  815. if (track.channelMask_ & CHANNEL_POSITION && k < channel->mNumPositionKeys)
  816. pos = channel->mPositionKeys[k].mValue;
  817. if (track.channelMask_ & CHANNEL_ROTATION && k < channel->mNumRotationKeys)
  818. rot = channel->mRotationKeys[k].mValue;
  819. if (track.channelMask_ & CHANNEL_SCALE && k < channel->mNumScalingKeys)
  820. scale = channel->mScalingKeys[k].mValue;
  821. // If root bone, transform with the model root node transform
  822. if (!boneIndex)
  823. {
  824. aiMatrix4x4 transMat, scaleMat, rotMat;
  825. aiMatrix4x4::Translation(pos, transMat);
  826. aiMatrix4x4::Scaling(scale, scaleMat);
  827. rotMat = aiMatrix4x4(rot.GetMatrix());
  828. aiMatrix4x4 tform = transMat * rotMat * scaleMat;
  829. tform = GetDerivedTransform(tform, boneNode, model.rootNode_);
  830. tform.Decompose(scale, rot, pos);
  831. }
  832. if (track.channelMask_ & CHANNEL_POSITION)
  833. kf.position_ = ToVector3(pos);
  834. if (track.channelMask_ & CHANNEL_ROTATION)
  835. kf.rotation_ = ToQuaternion(rot);
  836. if (track.channelMask_ & CHANNEL_SCALE)
  837. kf.scale_ = ToVector3(scale);
  838. track.keyFrames_.Push(kf);
  839. }
  840. tracks.Push(track);
  841. }
  842. outAnim->SetTracks(tracks);
  843. File outFile(context_);
  844. if (!outFile.Open(animOutName, FILE_WRITE))
  845. ErrorExit("Could not open output file " + animOutName);
  846. outAnim->Save(outFile);
  847. }
  848. }
  849. void ExportScene(const String& outName)
  850. {
  851. OutScene outScene;
  852. outScene.outName_ = outName;
  853. outScene.rootNode_ = rootNode_;
  854. if (useSubdirs_)
  855. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Models");
  856. CollectSceneModels(outScene, rootNode_);
  857. // Save models and their material lists
  858. for (unsigned i = 0; i < outScene.models_.Size(); ++i)
  859. BuildAndSaveModel(outScene.models_[i]);
  860. // Save scene
  861. BuildAndSaveScene(outScene);
  862. }
  863. void CollectSceneModels(OutScene& scene, aiNode* node)
  864. {
  865. Vector<Pair<aiNode*, aiMesh*> > meshes;
  866. GetMeshesUnderNode(meshes, node);
  867. if (meshes.Size())
  868. {
  869. OutModel model;
  870. model.rootNode_ = node;
  871. model.outName_ = resourcePath_ + (useSubdirs_ ? "Models/" : "") + SanitateAssetName(FromAIString(node->mName)) + ".mdl";
  872. for (unsigned i = 0; i < meshes.Size(); ++i)
  873. {
  874. aiMesh* mesh = meshes[i].second_;
  875. unsigned meshIndex = GetMeshIndex(mesh);
  876. model.meshIndices_.Insert(meshIndex);
  877. model.meshes_.Push(mesh);
  878. model.meshNodes_.Push(meshes[i].first_);
  879. model.totalVertices_ += mesh->mNumVertices;
  880. model.totalIndices_ += GetNumValidFaces(mesh) * 3;
  881. }
  882. // Check if a model with identical mesh indices already exists. If yes, do not export twice
  883. bool unique = true;
  884. for (unsigned i = 0; i < scene.models_.Size(); ++i)
  885. {
  886. if (scene.models_[i].meshIndices_ == model.meshIndices_)
  887. {
  888. PrintLine("Added node " + FromAIString(node->mName));
  889. scene.nodes_.Push(node);
  890. scene.nodeModelIndices_.Push(i);
  891. unique = false;
  892. break;
  893. }
  894. }
  895. if (unique)
  896. {
  897. PrintLine("Added model " + model.outName_);
  898. PrintLine("Added node " + FromAIString(node->mName));
  899. CollectBones(model);
  900. BuildBoneCollisionInfo(model);
  901. if (!noAnimations_)
  902. {
  903. CollectAnimations(model);
  904. BuildAndSaveAnimations(model);
  905. }
  906. scene.models_.Push(model);
  907. scene.nodes_.Push(node);
  908. scene.nodeModelIndices_.Push(scene.models_.Size() - 1);
  909. }
  910. }
  911. for (unsigned i = 0; i < node->mNumChildren; ++i)
  912. CollectSceneModels(scene, node->mChildren[i]);
  913. }
  914. void BuildAndSaveScene(OutScene& scene)
  915. {
  916. PrintLine("Writing scene");
  917. SharedPtr<Scene> outScene(new Scene(context_));
  918. /// \todo Make the physics properties configurable
  919. outScene->CreateComponent<PhysicsWorld>();
  920. /// \todo Make the octree properties configurable, or detect from the scene contents
  921. outScene->CreateComponent<Octree>();
  922. outScene->CreateComponent<DebugRenderer>();
  923. if (createZone_)
  924. {
  925. Node* zoneNode = outScene->CreateChild("Zone", localIDs_ ? LOCAL : REPLICATED);
  926. Zone* zone = zoneNode->CreateComponent<Zone>();
  927. zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.f));
  928. zone->SetAmbientColor(Color(0.25f, 0.25f, 0.25f));
  929. Node* lightNode = outScene->CreateChild("GlobalLight", localIDs_ ? LOCAL : REPLICATED);
  930. Light* light = lightNode->CreateComponent<Light>();
  931. light->SetLightType(LIGHT_DIRECTIONAL);
  932. lightNode->SetRotation(Quaternion(60.0f, 30.0f, 0.0f));
  933. }
  934. ResourceCache* cache = context_->GetSubsystem<ResourceCache>();
  935. for (unsigned i = 0; i < scene.nodes_.Size(); ++i)
  936. {
  937. const OutModel& model = scene.models_[scene.nodeModelIndices_[i]];
  938. // Create a static model component for each node
  939. Node* modelNode = outScene->CreateChild(FromAIString(scene.nodes_[i]->mName), localIDs_ ? LOCAL : REPLICATED);
  940. StaticModel* staticModel = modelNode->CreateComponent<StaticModel>();
  941. // Create a dummy model so that the reference can be stored
  942. String modelName = (useSubdirs_ ? "Models/" : "") + GetFileNameAndExtension(model.outName_);
  943. if (!cache->Exists(modelName))
  944. {
  945. Model* dummyModel = new Model(context_);
  946. dummyModel->SetName(modelName);
  947. dummyModel->SetNumGeometries(model.meshes_.Size());
  948. cache->AddManualResource(dummyModel);
  949. }
  950. staticModel->SetModel(cache->GetResource<Model>(modelName));
  951. // Set a flattened transform
  952. Vector3 pos, scale;
  953. Quaternion rot;
  954. GetPosRotScale(GetDerivedTransform(scene.nodes_[i], rootNode_), pos, rot, scale);
  955. modelNode->SetTransform(pos, rot, scale);
  956. // Set materials if they are known
  957. for (unsigned j = 0; j < model.meshes_.Size(); ++j)
  958. {
  959. String matName = GetMeshMaterialName(model.meshes_[j]);
  960. if (!matName.Empty())
  961. {
  962. // Create a dummy material so that the reference can be stored
  963. if (!cache->Exists(matName))
  964. {
  965. Material* dummyMat = new Material(context_);
  966. dummyMat->SetName(matName);
  967. cache->AddManualResource(dummyMat);
  968. }
  969. staticModel->SetMaterial(j, cache->GetResource<Material>(matName));
  970. }
  971. }
  972. }
  973. File file(context_);
  974. if (!file.Open(scene.outName_, FILE_WRITE))
  975. ErrorExit("Could not open output file " + scene.outName_);
  976. if (!saveBinary_)
  977. outScene->SaveXML(file);
  978. else
  979. outScene->Save(file);
  980. }
  981. void ExportMaterials(HashSet<String>& usedTextures)
  982. {
  983. if (useSubdirs_)
  984. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Materials");
  985. for (unsigned i = 0; i < scene_->mNumMaterials; ++i)
  986. BuildAndSaveMaterial(scene_->mMaterials[i], usedTextures);
  987. }
  988. void BuildAndSaveMaterial(aiMaterial* material, HashSet<String>& usedTextures)
  989. {
  990. // Material must have name so it can be successfully saved
  991. aiString matNameStr;
  992. material->Get(AI_MATKEY_NAME, matNameStr);
  993. String matName = SanitateAssetName(FromAIString(matNameStr));
  994. if (matName.Empty())
  995. return;
  996. PrintLine("Writing material " + matName);
  997. // Do not actually create a material instance, but instead craft an xml file manually
  998. XMLFile outMaterial(context_);
  999. XMLElement materialElem = outMaterial.CreateRoot("material");
  1000. String diffuseTexName;
  1001. String normalTexName;
  1002. String specularTexName;
  1003. Color diffuseColor;
  1004. Color specularColor;
  1005. bool hasAlpha = false;
  1006. bool twoSided = false;
  1007. float specPower = 1.0f;
  1008. aiString stringVal;
  1009. float floatVal;
  1010. int intVal;
  1011. aiColor3D colorVal;
  1012. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), stringVal) == AI_SUCCESS)
  1013. diffuseTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1014. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_NORMALS, 0), stringVal) == AI_SUCCESS)
  1015. normalTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1016. if (material->Get(AI_MATKEY_TEXTURE(aiTextureType_SPECULAR, 0), stringVal) == AI_SUCCESS)
  1017. specularTexName = GetFileNameAndExtension(FromAIString(stringVal));
  1018. if (material->Get(AI_MATKEY_COLOR_DIFFUSE, colorVal) == AI_SUCCESS)
  1019. diffuseColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1020. if (material->Get(AI_MATKEY_COLOR_SPECULAR, colorVal) == AI_SUCCESS)
  1021. specularColor = Color(colorVal.r, colorVal.g, colorVal.b);
  1022. if (material->Get(AI_MATKEY_OPACITY, floatVal) == AI_SUCCESS)
  1023. {
  1024. if (floatVal < 1.0f)
  1025. hasAlpha = true;
  1026. diffuseColor.a_ = floatVal;
  1027. }
  1028. if (material->Get(AI_MATKEY_SHININESS, floatVal) == AI_SUCCESS)
  1029. specPower = floatVal;
  1030. if (material->Get(AI_MATKEY_TWOSIDED, intVal) == AI_SUCCESS)
  1031. twoSided = (intVal != 0);
  1032. String techniqueName = "Techniques/NoTexture";
  1033. if (!diffuseTexName.Empty())
  1034. {
  1035. techniqueName = "Techniques/Diff";
  1036. if (!normalTexName.Empty())
  1037. techniqueName += "Normal";
  1038. if (!specularTexName.Empty())
  1039. techniqueName += "Spec";
  1040. }
  1041. if (hasAlpha)
  1042. techniqueName += "Alpha";
  1043. XMLElement techniqueElem = materialElem.CreateChild("technique");
  1044. techniqueElem.SetString("name", techniqueName + ".xml");
  1045. if (!diffuseTexName.Empty())
  1046. {
  1047. XMLElement diffuseElem = materialElem.CreateChild("texture");
  1048. diffuseElem.SetString("unit", "diffuse");
  1049. diffuseElem.SetString("name", (useSubdirs_ ? "Textures/" : "") + diffuseTexName);
  1050. usedTextures.Insert(diffuseTexName);
  1051. }
  1052. if (!normalTexName.Empty())
  1053. {
  1054. XMLElement normalElem = materialElem.CreateChild("texture");
  1055. normalElem.SetString("unit", "normal");
  1056. normalElem.SetString("name", (useSubdirs_ ? "Textures/" : "") + normalTexName);
  1057. usedTextures.Insert(normalTexName);
  1058. }
  1059. if (!specularTexName.Empty())
  1060. {
  1061. XMLElement normalElem = materialElem.CreateChild("texture");
  1062. normalElem.SetString("unit", "specular");
  1063. normalElem.SetString("name", (useSubdirs_ ? "Textures/" : "") + specularTexName);
  1064. usedTextures.Insert(specularTexName);
  1065. }
  1066. XMLElement diffuseColorElem = materialElem.CreateChild("parameter");
  1067. diffuseColorElem.SetString("name", "MatDiffColor");
  1068. diffuseColorElem.SetColor("value", diffuseColor);
  1069. XMLElement specularElem = materialElem.CreateChild("parameter");
  1070. specularElem.SetString("name", "MatSpecColor");
  1071. specularElem.SetVector4("value", Vector4(specularColor.r_, specularColor.g_, specularColor.b_, specPower));
  1072. if (twoSided)
  1073. {
  1074. XMLElement cullElem = materialElem.CreateChild("cull");
  1075. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  1076. cullElem.SetString("value", "none");
  1077. shadowCullElem.SetString("value", "none");
  1078. }
  1079. File outFile(context_);
  1080. String outFileName = resourcePath_ + (useSubdirs_ ? "Materials/" : "" ) + matName + ".xml";
  1081. if (!outFile.Open(outFileName, FILE_WRITE))
  1082. ErrorExit("Could not open output file " + outFileName);
  1083. outMaterial.Save(outFile);
  1084. }
  1085. void CopyTextures(const HashSet<String>& usedTextures, const String& sourcePath)
  1086. {
  1087. if (useSubdirs_)
  1088. context_->GetSubsystem<FileSystem>()->CreateDir(resourcePath_ + "Textures");
  1089. for (HashSet<String>::ConstIterator i = usedTextures.Begin(); i != usedTextures.End(); ++i)
  1090. {
  1091. PrintLine("Copying texture " + (*i));
  1092. context_->GetSubsystem<FileSystem>()->Copy(sourcePath + *i, resourcePath_ + (useSubdirs_ ? "Textures/" : "") + *i);
  1093. }
  1094. }
  1095. void CombineLods(const PODVector<float>& lodDistances, const Vector<String>& modelNames, const String& outName)
  1096. {
  1097. // Load models
  1098. Vector<SharedPtr<Model> > srcModels;
  1099. for (unsigned i = 0; i < modelNames.Size(); ++i)
  1100. {
  1101. PrintLine("Reading LOD level " + String(i) + ": model " + modelNames[i] + " distance " + String(lodDistances[i]));
  1102. File srcFile(context_);
  1103. srcFile.Open(modelNames[i]);
  1104. SharedPtr<Model> srcModel(new Model(context_));
  1105. if (!srcModel->Load(srcFile))
  1106. ErrorExit("Could not load input model " + modelNames[i]);
  1107. srcModels.Push(srcModel);
  1108. }
  1109. // Check that none of the models already has LOD levels
  1110. for (unsigned i = 0; i < srcModels.Size(); ++i)
  1111. {
  1112. for (unsigned j = 0; j < srcModels[i]->GetNumGeometries(); ++j)
  1113. {
  1114. if (srcModels[i]->GetNumGeometryLodLevels(j) > 1)
  1115. ErrorExit(modelNames[i] + " already has multiple LOD levels defined");
  1116. }
  1117. }
  1118. // Check for number of geometries (need to have same amount for now)
  1119. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1120. {
  1121. if (srcModels[i]->GetNumGeometries() != srcModels[0]->GetNumGeometries())
  1122. ErrorExit(modelNames[i] + " has different amount of geometries than " + modelNames[0]);
  1123. }
  1124. // If there are bones, check for compatibility (need to have exact match for now)
  1125. for (unsigned i = 1; i < srcModels.Size(); ++i)
  1126. {
  1127. if (srcModels[i]->GetSkeleton().GetNumBones() != srcModels[0]->GetSkeleton().GetNumBones())
  1128. ErrorExit(modelNames[i] + " has different amount of bones than " + modelNames[0]);
  1129. for (unsigned j = 0; j < srcModels[0]->GetSkeleton().GetNumBones(); ++j)
  1130. {
  1131. if (srcModels[i]->GetSkeleton().GetBone(j)->name_ != srcModels[0]->GetSkeleton().GetBone(j)->name_)
  1132. ErrorExit(modelNames[i] + " has different bones than " + modelNames[0]);
  1133. }
  1134. if (srcModels[i]->GetGeometryBoneMappings() != srcModels[0]->GetGeometryBoneMappings())
  1135. ErrorExit(modelNames[i] + " has different per-geometry bone mappings than " + modelNames[0]);
  1136. }
  1137. // Create the final model
  1138. SharedPtr<Model> outModel(new Model(context_));
  1139. outModel->SetNumGeometries(srcModels[0]->GetNumGeometries());
  1140. for (unsigned i = 0; i < srcModels[0]->GetNumGeometries(); ++i)
  1141. {
  1142. outModel->SetNumGeometryLodLevels(i, srcModels.Size());
  1143. for (unsigned j = 0; j < srcModels.Size(); ++j)
  1144. {
  1145. Geometry* geom = srcModels[j]->GetGeometry(i, 0);
  1146. geom->SetLodDistance(lodDistances[j]);
  1147. outModel->SetGeometry(i, j, geom);
  1148. }
  1149. }
  1150. outModel->SetSkeleton(srcModels[0]->GetSkeleton());
  1151. outModel->SetGeometryBoneMappings(srcModels[0]->GetGeometryBoneMappings());
  1152. outModel->SetBoundingBox(srcModels[0]->GetBoundingBox());
  1153. /// \todo Vertex morphs are ignored for now
  1154. // Save the final model
  1155. PrintLine("Writing output model");
  1156. File outFile(context_);
  1157. if (!outFile.Open(outName, FILE_WRITE))
  1158. ErrorExit("Could not open output file " + outName);
  1159. outModel->Save(outFile);
  1160. }
  1161. void GetMeshesUnderNode(Vector<Pair<aiNode*, aiMesh*> >& dest, aiNode* node)
  1162. {
  1163. for (unsigned i = 0; i < node->mNumMeshes; ++i)
  1164. dest.Push(MakePair(node, scene_->mMeshes[node->mMeshes[i]]));
  1165. }
  1166. unsigned GetMeshIndex(aiMesh* mesh)
  1167. {
  1168. for (unsigned i = 0; i < scene_->mNumMeshes; ++i)
  1169. {
  1170. if (scene_->mMeshes[i] == mesh)
  1171. return i;
  1172. }
  1173. return M_MAX_UNSIGNED;
  1174. }
  1175. unsigned GetBoneIndex(OutModel& model, const String& boneName)
  1176. {
  1177. for (unsigned i = 0; i < model.bones_.Size(); ++i)
  1178. {
  1179. if (boneName == model.bones_[i]->mName.data)
  1180. return i;
  1181. }
  1182. return M_MAX_UNSIGNED;
  1183. }
  1184. aiBone* GetMeshBone(OutModel& model, const String& boneName)
  1185. {
  1186. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1187. {
  1188. aiMesh* mesh = model.meshes_[i];
  1189. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1190. {
  1191. aiBone* bone = mesh->mBones[j];
  1192. if (boneName == bone->mName.data)
  1193. return bone;
  1194. }
  1195. }
  1196. return 0;
  1197. }
  1198. Matrix3x4 GetOffsetMatrix(OutModel& model, const String& boneName)
  1199. {
  1200. for (unsigned i = 0; i < model.meshes_.Size(); ++i)
  1201. {
  1202. aiMesh* mesh = model.meshes_[i];
  1203. aiNode* node = model.meshNodes_[i];
  1204. for (unsigned j = 0; j < mesh->mNumBones; ++j)
  1205. {
  1206. aiBone* bone = mesh->mBones[j];
  1207. if (boneName == bone->mName.data)
  1208. {
  1209. aiMatrix4x4 offset = bone->mOffsetMatrix;
  1210. aiMatrix4x4 nodeDerivedInverse = GetMeshBakingTransform(node, model.rootNode_);
  1211. nodeDerivedInverse.Inverse();
  1212. offset *= nodeDerivedInverse;
  1213. Matrix3x4 ret;
  1214. memcpy(&ret.m00_, &offset.a1, sizeof(Matrix3x4));
  1215. return ret;
  1216. }
  1217. }
  1218. }
  1219. return Matrix3x4::IDENTITY;
  1220. }
  1221. void GetBlendData(OutModel& model, aiMesh* mesh, PODVector<unsigned>& boneMappings, Vector<PODVector<unsigned char> >&
  1222. blendIndices, Vector<PODVector<float> >& blendWeights)
  1223. {
  1224. blendIndices.Resize(mesh->mNumVertices);
  1225. blendWeights.Resize(mesh->mNumVertices);
  1226. boneMappings.Clear();
  1227. // If model has more bones than can fit vertex shader parameters, write the per-geometry mappings
  1228. if (model.bones_.Size() > MAX_SKIN_MATRICES)
  1229. {
  1230. if (mesh->mNumBones > MAX_SKIN_MATRICES)
  1231. ErrorExit("Geometry has too many bone influences");
  1232. boneMappings.Resize(mesh->mNumBones);
  1233. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1234. {
  1235. aiBone* bone = mesh->mBones[i];
  1236. String boneName = FromAIString(bone->mName);
  1237. unsigned globalIndex = GetBoneIndex(model, boneName);
  1238. if (globalIndex == M_MAX_UNSIGNED)
  1239. ErrorExit("Bone " + boneName + " not found");
  1240. boneMappings[i] = globalIndex;
  1241. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1242. {
  1243. unsigned vertex = bone->mWeights[j].mVertexId;
  1244. blendIndices[vertex].Push(i);
  1245. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1246. if (blendWeights[vertex].Size() > 4)
  1247. ErrorExit("More than 4 bone influences on vertex");
  1248. }
  1249. }
  1250. }
  1251. else
  1252. {
  1253. for (unsigned i = 0; i < mesh->mNumBones; ++i)
  1254. {
  1255. aiBone* bone = mesh->mBones[i];
  1256. String boneName = FromAIString(bone->mName);
  1257. unsigned globalIndex = GetBoneIndex(model, boneName);
  1258. if (globalIndex == M_MAX_UNSIGNED)
  1259. ErrorExit("Bone " + boneName + " not found");
  1260. for (unsigned j = 0; j < bone->mNumWeights; ++j)
  1261. {
  1262. unsigned vertex = bone->mWeights[j].mVertexId;
  1263. blendIndices[vertex].Push(globalIndex);
  1264. blendWeights[vertex].Push(bone->mWeights[j].mWeight);
  1265. if (blendWeights[vertex].Size() > 4)
  1266. ErrorExit("More than 4 bone influences on vertex");
  1267. }
  1268. }
  1269. }
  1270. }
  1271. String GetMeshMaterialName(aiMesh* mesh)
  1272. {
  1273. aiMaterial* material = scene_->mMaterials[mesh->mMaterialIndex];
  1274. aiString matNameStr;
  1275. material->Get(AI_MATKEY_NAME, matNameStr);
  1276. String matName = SanitateAssetName(FromAIString(matNameStr));
  1277. if (matName.Empty())
  1278. return matName;
  1279. else
  1280. return (useSubdirs_ ? "Materials/" : "") + matName + ".xml";
  1281. }
  1282. unsigned GetNumValidFaces(aiMesh* mesh)
  1283. {
  1284. unsigned ret = 0;
  1285. for (unsigned j = 0; j < mesh->mNumFaces; ++j)
  1286. {
  1287. if (mesh->mFaces[j].mNumIndices == 3)
  1288. ++ret;
  1289. }
  1290. return ret;
  1291. }
  1292. void WriteShortIndices(unsigned short*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1293. {
  1294. if (mesh->mFaces[index].mNumIndices == 3)
  1295. {
  1296. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1297. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1298. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1299. }
  1300. }
  1301. void WriteLargeIndices(unsigned*& dest, aiMesh* mesh, unsigned index, unsigned offset)
  1302. {
  1303. if (mesh->mFaces[index].mNumIndices == 3)
  1304. {
  1305. *dest++ = mesh->mFaces[index].mIndices[0] + offset;
  1306. *dest++ = mesh->mFaces[index].mIndices[1] + offset;
  1307. *dest++ = mesh->mFaces[index].mIndices[2] + offset;
  1308. }
  1309. }
  1310. void WriteVertex(float*& dest, aiMesh* mesh, unsigned index, unsigned elementMask, BoundingBox& box,
  1311. const Matrix3x4& vertexTransform, const Matrix3& normalTransform, Vector<PODVector<unsigned char> >& blendIndices,
  1312. Vector<PODVector<float> >& blendWeights)
  1313. {
  1314. Vector3 vertex = vertexTransform * ToVector3(mesh->mVertices[index]);
  1315. box.Merge(vertex);
  1316. *dest++ = vertex.x_;
  1317. *dest++ = vertex.y_;
  1318. *dest++ = vertex.z_;
  1319. if (elementMask & MASK_NORMAL)
  1320. {
  1321. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1322. *dest++ = normal.x_;
  1323. *dest++ = normal.y_;
  1324. *dest++ = normal.z_;
  1325. }
  1326. if (elementMask & MASK_COLOR)
  1327. {
  1328. *((unsigned*)dest) = Color(mesh->mColors[0][index].r, mesh->mColors[0][index].g, mesh->mColors[0][index].b,
  1329. mesh->mColors[0][index].a).ToUInt();
  1330. ++dest;
  1331. }
  1332. if (elementMask & MASK_TEXCOORD1)
  1333. {
  1334. Vector3 texCoord = ToVector3(mesh->mTextureCoords[0][index]);
  1335. *dest++ = texCoord.x_;
  1336. *dest++ = texCoord.y_;
  1337. }
  1338. if (elementMask & MASK_TEXCOORD2)
  1339. {
  1340. Vector3 texCoord = ToVector3(mesh->mTextureCoords[1][index]);
  1341. *dest++ = texCoord.x_;
  1342. *dest++ = texCoord.y_;
  1343. }
  1344. if (elementMask & MASK_TANGENT)
  1345. {
  1346. Vector3 tangent = normalTransform * ToVector3(mesh->mTangents[index]);
  1347. Vector3 normal = normalTransform * ToVector3(mesh->mNormals[index]);
  1348. Vector3 bitangent = normalTransform * ToVector3(mesh->mBitangents[index]);
  1349. // Check handedness
  1350. float w = 1.0f;
  1351. if ((tangent.CrossProduct(normal)).DotProduct(bitangent) < 0.5f)
  1352. w = -1.0f;
  1353. *dest++ = tangent.x_;
  1354. *dest++ = tangent.y_;
  1355. *dest++ = tangent.z_;
  1356. *dest++ = w;
  1357. }
  1358. if (elementMask & MASK_BLENDWEIGHTS)
  1359. {
  1360. for (unsigned i = 0; i < 4; ++i)
  1361. {
  1362. if (i < blendWeights[index].Size())
  1363. *dest++ = blendWeights[index][i];
  1364. else
  1365. *dest++ = 0.0f;
  1366. }
  1367. }
  1368. if (elementMask & MASK_BLENDINDICES)
  1369. {
  1370. unsigned char* destBytes = (unsigned char*)dest;
  1371. ++dest;
  1372. for (unsigned i = 0; i < 4; ++i)
  1373. {
  1374. if (i < blendIndices[index].Size())
  1375. *destBytes++ = blendIndices[index][i];
  1376. else
  1377. *destBytes++ = 0;
  1378. }
  1379. }
  1380. }
  1381. unsigned GetElementMask(aiMesh* mesh)
  1382. {
  1383. unsigned elementMask = MASK_POSITION;
  1384. if (mesh->HasNormals())
  1385. elementMask |= MASK_NORMAL;
  1386. if (mesh->HasTangentsAndBitangents())
  1387. elementMask |= MASK_TANGENT;
  1388. if (mesh->GetNumColorChannels() > 0)
  1389. elementMask |= MASK_COLOR;
  1390. if (mesh->GetNumUVChannels() > 0)
  1391. elementMask |= MASK_TEXCOORD1;
  1392. if (mesh->GetNumUVChannels() > 1)
  1393. elementMask |= MASK_TEXCOORD2;
  1394. if (mesh->HasBones())
  1395. elementMask |= (MASK_BLENDWEIGHTS | MASK_BLENDINDICES);
  1396. return elementMask;
  1397. }
  1398. aiNode* GetNode(const String& name, aiNode* rootNode, bool caseSensitive)
  1399. {
  1400. if (!rootNode)
  1401. return 0;
  1402. if (!name.Compare(rootNode->mName.data, caseSensitive))
  1403. return rootNode;
  1404. for (unsigned i = 0; i < rootNode->mNumChildren; ++i)
  1405. {
  1406. aiNode* found = GetNode(name, rootNode->mChildren[i], caseSensitive);
  1407. if (found)
  1408. return found;
  1409. }
  1410. return 0;
  1411. }
  1412. aiMatrix4x4 GetDerivedTransform(aiNode* node, aiNode* rootNode)
  1413. {
  1414. return GetDerivedTransform(node->mTransformation, node, rootNode);
  1415. }
  1416. aiMatrix4x4 GetDerivedTransform(aiMatrix4x4 transform, aiNode* node, aiNode* rootNode)
  1417. {
  1418. // If basenode is defined, go only up to it in the parent chain
  1419. while (node && node != rootNode)
  1420. {
  1421. node = node->mParent;
  1422. if (node)
  1423. transform = node->mTransformation * transform;
  1424. }
  1425. return transform;
  1426. }
  1427. aiMatrix4x4 GetMeshBakingTransform(aiNode* meshNode, aiNode* modelRootNode)
  1428. {
  1429. if (meshNode == modelRootNode)
  1430. return aiMatrix4x4();
  1431. else
  1432. return GetDerivedTransform(meshNode, modelRootNode);
  1433. }
  1434. void GetPosRotScale(const aiMatrix4x4& transform, Vector3& pos, Quaternion& rot, Vector3& scale)
  1435. {
  1436. aiVector3D aiPos;
  1437. aiQuaternion aiRot;
  1438. aiVector3D aiScale;
  1439. transform.Decompose(aiScale, aiRot, aiPos);
  1440. pos = ToVector3(aiPos);
  1441. rot = ToQuaternion(aiRot);
  1442. scale = ToVector3(aiScale);
  1443. }
  1444. String FromAIString(const aiString& str)
  1445. {
  1446. return String(str.data);
  1447. }
  1448. Vector3 ToVector3(const aiVector3D& vec)
  1449. {
  1450. return Vector3(vec.x, vec.y, vec.z);
  1451. }
  1452. Vector2 ToVector2(const aiVector2D& vec)
  1453. {
  1454. return Vector2(vec.x, vec.y);
  1455. }
  1456. Quaternion ToQuaternion(const aiQuaternion& quat)
  1457. {
  1458. return Quaternion(quat.w, quat.x, quat.y, quat.z);
  1459. }
  1460. String SanitateAssetName(const String& name)
  1461. {
  1462. String fixedName = name;
  1463. fixedName.Replace("<", "");
  1464. fixedName.Replace(">", "");
  1465. fixedName.Replace("?", "");
  1466. fixedName.Replace("*", "");
  1467. fixedName.Replace(":", "");
  1468. fixedName.Replace("\"", "");
  1469. fixedName.Replace("/", "");
  1470. fixedName.Replace("\\", "");
  1471. fixedName.Replace("|", "");
  1472. return fixedName;
  1473. }