ModelImporter.cpp 14 KB

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