ModelImporter.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. //
  2. // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
  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/Core/ProcessUtils.h>
  23. #include <Atomic/IO/Log.h>
  24. #include <Atomic/IO/File.h>
  25. #include <Atomic/IO/FileSystem.h>
  26. #include <Atomic/Scene/Node.h>
  27. #include <Atomic/Graphics/AnimatedModel.h>
  28. #include <Atomic/Graphics/Animation.h>
  29. #include <Atomic/Graphics/AnimationController.h>
  30. #include <Atomic/Graphics/StaticModel.h>
  31. #include <Atomic/Graphics/Model.h>
  32. #include <Atomic/Resource/ResourceCache.h>
  33. #include <Atomic/Resource/XMLFile.h>
  34. #include "../Import/OpenAssetImporter.h"
  35. #include "Asset.h"
  36. #include "AssetDatabase.h"
  37. #include "ModelImporter.h"
  38. namespace ToolCore
  39. {
  40. /// Node + Model (static or animated)
  41. ModelImporter::ModelImporter(Context* context, Asset *asset) : AssetImporter(context, asset)
  42. {
  43. requiresCacheFile_ = true;
  44. SetDefaults();
  45. }
  46. ModelImporter::~ModelImporter()
  47. {
  48. }
  49. void ModelImporter::SetDefaults()
  50. {
  51. AssetImporter::SetDefaults();
  52. SharedPtr<OpenAssetImporter> importer(new OpenAssetImporter(context_));
  53. scale_ = 1.0;
  54. importAnimations_ = false;
  55. importMaterials_ = importer->GetImportMaterialsDefault();
  56. includeNonSkinningBones_ = importer->GetIncludeNonSkinningBones();
  57. animationInfo_.Clear();
  58. genLightmapUV_ = false;
  59. }
  60. bool ModelImporter::ImportModel()
  61. {
  62. ATOMIC_LOGDEBUGF("Importing Model: %s", asset_->GetPath().CString());
  63. SharedPtr<OpenAssetImporter> importer(new OpenAssetImporter(context_));
  64. importer->SetVerboseLog(true);
  65. importer->SetScale(scale_);
  66. importer->SetExportAnimations(false);
  67. importer->SetImportNode(importNode_);
  68. importer->SetImportMaterials(importMaterials_);
  69. importer->SetIncludeNonSkinningBones(includeNonSkinningBones_);
  70. if (importer->Load(asset_->GetPath()))
  71. {
  72. importer->ExportModel(asset_->GetCachePath());
  73. return true;
  74. }
  75. else
  76. {
  77. asset_->PostImportError(importer->GetErrorMessage());
  78. }
  79. return false;
  80. }
  81. /*void ModelImporter::SetImportMaterials(bool importMat)
  82. {
  83. LOGDEBUGF("Importing Materials of: %s", asset_->GetPath().CString());
  84. SharedPtr<OpenAssetImporter> importer(new OpenAssetImporter(context_));
  85. importer->SetImportMaterials(importMat);
  86. }*/
  87. bool ModelImporter::ImportAnimation(const String& filename, const String& name, float startTime, float endTime)
  88. {
  89. SharedPtr<OpenAssetImporter> importer(new OpenAssetImporter(context_));
  90. //importer->SetVerboseLog(true);
  91. importer->SetScale(scale_);
  92. importer->SetExportAnimations(true);
  93. importer->SetStartTime(startTime);
  94. importer->SetEndTime(endTime);
  95. if (importer->Load(filename))
  96. {
  97. importer->ExportModel(asset_->GetCachePath(), name, true);
  98. const Vector<OpenAssetImporter::AnimationInfo>& infos = importer->GetAnimationInfos();
  99. for (unsigned i = 0; i < infos.Size(); i++)
  100. {
  101. const OpenAssetImporter::AnimationInfo& info = infos.At(i);
  102. String pathName, fileName, extension;
  103. SplitPath(info.cacheFilename_, pathName, fileName, extension);
  104. ResourceCache* cache = GetSubsystem<ResourceCache>();
  105. AnimatedModel* animatedModel = importNode_->GetComponent<AnimatedModel>();
  106. AnimationController* controller = importNode_->GetComponent<AnimationController>();
  107. if (!controller)
  108. {
  109. importNode_->CreateComponent<AnimationController>();
  110. controller = importNode_->GetComponent<AnimationController>();
  111. }
  112. SharedPtr<Animation> animation = cache->GetTempResource<Animation>(fileName + extension);
  113. if (animation)
  114. controller->AddAnimationResource(animation);
  115. ATOMIC_LOGINFOF("Import Info: %s : %s", info.name_.CString(), fileName.CString());
  116. }
  117. return true;
  118. }
  119. return false;
  120. }
  121. bool ModelImporter::ImportAnimations()
  122. {
  123. if (!animationInfo_.Size())
  124. {
  125. if (!ImportAnimation(asset_->GetPath(), "RootAnim"))
  126. return false;
  127. }
  128. // embedded animations
  129. for (unsigned i = 0; i < animationInfo_.Size(); i++)
  130. {
  131. const SharedPtr<AnimationImportInfo>& info = animationInfo_[i];
  132. if (!ImportAnimation(asset_->GetPath(), info->GetName(), info->GetStartTime(), info->GetEndTime()))
  133. return false;
  134. }
  135. // add @ animations
  136. FileSystem* fs = GetSubsystem<FileSystem>();
  137. String pathName, fileName, ext;
  138. SplitPath(asset_->GetPath(), pathName, fileName, ext);
  139. Vector<String> results;
  140. fs->ScanDir(results, pathName, ext, SCAN_FILES, false);
  141. for (unsigned i = 0; i < results.Size(); i++)
  142. {
  143. const String& result = results[i];
  144. if (result.Contains("@"))
  145. {
  146. Vector<String> components = GetFileName(result).Split('@');
  147. if (components.Size() == 2 && components[1].Length() && components[0] == fileName)
  148. {
  149. String animationName = components[1];
  150. AssetDatabase* db = GetSubsystem<AssetDatabase>();
  151. Asset* asset = db->GetAssetByPath(pathName + result);
  152. assert(asset);
  153. assert(asset->GetImporter()->GetType() == ModelImporter::GetTypeStatic());
  154. ModelImporter* importer = (ModelImporter*) asset->GetImporter();
  155. if (!importer->animationInfo_.Size())
  156. {
  157. if (!ImportAnimation(asset->GetPath(), animationName))
  158. return false;
  159. }
  160. else
  161. {
  162. // embedded animations
  163. for (unsigned i = 0; i < importer->animationInfo_.Size(); i++)
  164. {
  165. const SharedPtr<AnimationImportInfo>& info = importer->animationInfo_[i];
  166. if (!ImportAnimation(asset->GetPath(), info->GetName(), info->GetStartTime(), info->GetEndTime()))
  167. return false;
  168. }
  169. }
  170. }
  171. }
  172. }
  173. return true;
  174. }
  175. bool ModelImporter::Import()
  176. {
  177. String ext = asset_->GetExtension();
  178. String modelAssetFilename = asset_->GetPath();
  179. importNode_ = new Node(context_);
  180. if (ext == ".mdl")
  181. {
  182. FileSystem* fs = GetSubsystem<FileSystem>();
  183. ResourceCache* cache = GetSubsystem<ResourceCache>();
  184. // mdl files are native file format that doesn't need to be converted
  185. // doesn't allow scale, animations
  186. String cacheFilename = asset_->GetCachePath() + ".mdl";
  187. if (!fs->Copy(asset_->GetPath(), cacheFilename))
  188. {
  189. importNode_= 0;
  190. return false;
  191. }
  192. Model* mdl = cache->GetResource<Model>(cacheFilename);
  193. if (!mdl)
  194. {
  195. importNode_= 0;
  196. return false;
  197. }
  198. if (genLightmapUV_)
  199. {
  200. if (!OpenAssetImporter::GenerateLightmapUV(mdl))
  201. {
  202. ATOMIC_LOGERRORF("Failed to generate lightmap UV %s", asset_->GetPath().CString());
  203. importNode_= 0;
  204. return false;
  205. }
  206. File outFile(context_);
  207. if (!outFile.Open(cacheFilename, FILE_WRITE))
  208. {
  209. ATOMIC_LOGERRORF("Could not open output file %s", asset_->GetPath().CString());
  210. importNode_= 0;
  211. return false;
  212. }
  213. mdl->Save(outFile);
  214. outFile.Close();
  215. // Force a reload, though file watchers will catch this delayed and load again
  216. cache->ReloadResource(mdl);
  217. }
  218. importNode_->CreateComponent<StaticModel>()->SetModel(mdl);
  219. }
  220. else
  221. {
  222. // skip external animations, they will be brought in when importing their
  223. // corresponding model
  224. if (!modelAssetFilename.Contains("@"))
  225. {
  226. ImportModel();
  227. if (importAnimations_)
  228. {
  229. ImportAnimations();
  230. }
  231. SetImportMaterials(importMaterials_);
  232. }
  233. }
  234. File outFile(context_);
  235. if (!outFile.Open(asset_->GetCachePath(), FILE_WRITE))
  236. ErrorExit("Could not open output file " + asset_->GetCachePath());
  237. importNode_->SaveXML(outFile);
  238. importNode_ = 0;
  239. return true;
  240. }
  241. unsigned ModelImporter::GetAnimationCount()
  242. {
  243. return animationInfo_.Size();
  244. }
  245. void ModelImporter::SetAnimationCount(unsigned count)
  246. {
  247. if (animationInfo_.Size() >= count)
  248. {
  249. animationInfo_.Resize(count);
  250. }
  251. else
  252. {
  253. for (unsigned i = animationInfo_.Size(); i < count; i++)
  254. {
  255. SharedPtr<AnimationImportInfo> info(new AnimationImportInfo(context_));
  256. animationInfo_.Push(info);
  257. }
  258. }
  259. }
  260. void ModelImporter::GetAnimations(PODVector<Animation*>& animations)
  261. {
  262. animations.Clear();
  263. SharedPtr<File> file(new File(context_, asset_->GetCachePath()));
  264. SharedPtr<XMLFile> xml(new XMLFile(context_));
  265. if (!xml->Load(*file))
  266. return;
  267. SharedPtr<Node> node(new Node(context_));
  268. node->LoadXML(xml->GetRoot());
  269. AnimationController* controller = node->GetComponent<AnimationController>();
  270. if (!controller)
  271. return;
  272. const Vector<SharedPtr<Animation>>& animresources = controller->GetAnimationResources();
  273. for (unsigned i = 0; i < animresources.Size(); i++)
  274. {
  275. if (animresources[i].NotNull())
  276. {
  277. animations.Push(animresources[i]);
  278. }
  279. }
  280. }
  281. void ModelImporter::GetAssetCacheMap(HashMap<String, String>& assetMap)
  282. {
  283. if (asset_.Null())
  284. return;
  285. String assetPath = asset_->GetRelativePath().ToLower();
  286. String cachePath = asset_->GetGUID().ToLower();
  287. // Default is load node xml
  288. assetMap["Node;" + assetPath] = cachePath;
  289. assetMap["Model;" + assetPath] = cachePath + ".mdl";
  290. PODVector<Animation*> animations;
  291. GetAnimations(animations);
  292. for (unsigned i = 0; i < animations.Size(); i++)
  293. {
  294. Animation* anim = animations[i];
  295. assetMap["Animation;" + anim->GetAnimationName().ToLower() + "@" + assetPath] = cachePath + "_" + anim->GetAnimationName() + ".ani";
  296. }
  297. }
  298. bool ModelImporter::LoadSettingsInternal(JSONValue& jsonRoot)
  299. {
  300. if (!AssetImporter::LoadSettingsInternal(jsonRoot))
  301. return false;
  302. JSONValue import = jsonRoot.Get("ModelImporter");
  303. SetDefaults();
  304. if (import.Get("scale").IsNumber())
  305. scale_ = import.Get("scale").GetDouble();
  306. if (import.Get("genLightmapUV").IsBool())
  307. genLightmapUV_ = import.Get("genLightmapUV").GetBool();
  308. if (import.Get("importAnimations").IsBool())
  309. importAnimations_ = import.Get("importAnimations").GetBool();
  310. if (import.Get("importMaterials").IsBool())
  311. {
  312. importMaterials_ = import.Get("importMaterials").GetBool();
  313. }
  314. else
  315. {
  316. }
  317. if (import.Get("animInfo").IsArray())
  318. {
  319. JSONArray animInfo = import.Get("animInfo").GetArray();
  320. for (unsigned i = 0; i < animInfo.Size(); i++)
  321. {
  322. JSONValue anim = animInfo[i];
  323. SharedPtr<AnimationImportInfo> info(new AnimationImportInfo(context_));
  324. info->name_ = anim.Get("name").GetString();
  325. info->SetStartTime(anim.Get("startTime").GetFloat());
  326. info->SetEndTime(anim.Get("endTime").GetFloat());
  327. animationInfo_.Push(info);
  328. }
  329. }
  330. return true;
  331. }
  332. bool ModelImporter::SaveSettingsInternal(JSONValue& jsonRoot)
  333. {
  334. if (!AssetImporter::SaveSettingsInternal(jsonRoot))
  335. return false;
  336. JSONValue save;
  337. save.Set("scale", scale_);
  338. save.Set("importAnimations", importAnimations_);
  339. save.Set("importMaterials", importMaterials_);
  340. save.Set("genLightmapUV", genLightmapUV_);
  341. JSONArray animInfo;
  342. for (unsigned i = 0; i < animationInfo_.Size(); i++)
  343. {
  344. const SharedPtr<AnimationImportInfo>& info = animationInfo_[i];
  345. JSONValue jinfo;
  346. jinfo.Set("name", info->GetName());
  347. jinfo.Set("startTime", info->GetStartTime());
  348. jinfo.Set("endTime", info->GetEndTime());
  349. animInfo.Push(jinfo);
  350. }
  351. save.Set("animInfo", animInfo);
  352. jsonRoot.Set("ModelImporter", save);
  353. return true;
  354. }
  355. Resource* ModelImporter::GetResource(const String& typeName)
  356. {
  357. ResourceCache* cache = GetSubsystem<ResourceCache>();
  358. Model* model = cache->GetResource<Model>(asset_->GetCachePath() + ".mdl");
  359. return model;
  360. }
  361. Node* ModelImporter::InstantiateNode(Node* parent, const String& name)
  362. {
  363. SharedPtr<File> file(new File(context_, asset_->GetCachePath()));
  364. SharedPtr<XMLFile> xml(new XMLFile(context_));
  365. if (!xml->Load(*file))
  366. return 0;
  367. Node* node = parent->CreateChild(name);
  368. node->LoadXML(xml->GetRoot());
  369. node->SetName(asset_->GetName());
  370. return node;
  371. }
  372. }