BabylonExporter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. using Autodesk.Max;
  2. using BabylonExport.Entities;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Runtime.InteropServices;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.Windows.Forms;
  13. using Color = System.Drawing.Color;
  14. namespace Max2Babylon
  15. {
  16. internal partial class BabylonExporter
  17. {
  18. public event Action<int> OnImportProgressChanged;
  19. public event Action<string, int> OnWarning;
  20. public event Action<string, Color, int, bool> OnMessage;
  21. public event Action<string, int> OnError;
  22. public bool AutoSave3dsMaxFile { get; set; }
  23. public bool ExportHiddenObjects { get; set; }
  24. public bool IsCancelled { get; set; }
  25. public bool CopyTexturesToOutput { get; set; }
  26. public string MaxSceneFileName { get; set; }
  27. public bool ExportQuaternionsInsteadOfEulers { get; set; }
  28. void ReportProgressChanged(int progress)
  29. {
  30. if (OnImportProgressChanged != null)
  31. {
  32. OnImportProgressChanged(progress);
  33. }
  34. }
  35. void RaiseError(string error, int rank = 0)
  36. {
  37. if (OnError != null)
  38. {
  39. OnError(error, rank);
  40. }
  41. }
  42. void RaiseWarning(string warning, int rank = 0)
  43. {
  44. if (OnWarning != null)
  45. {
  46. OnWarning(warning, rank);
  47. }
  48. }
  49. void RaiseMessage(string message, int rank = 0, bool emphasis = false)
  50. {
  51. RaiseMessage(message, Color.Black, rank, emphasis);
  52. }
  53. void RaiseMessage(string message, Color color, int rank = 0, bool emphasis = false)
  54. {
  55. if (OnMessage != null)
  56. {
  57. OnMessage(message, color, rank, emphasis);
  58. }
  59. }
  60. void CheckCancelled()
  61. {
  62. Application.DoEvents();
  63. if (IsCancelled)
  64. {
  65. throw new OperationCanceledException();
  66. }
  67. }
  68. public async Task ExportAsync(string outputFile, bool generateManifest, bool onlySelected, bool generateBinary, bool exportGltf, Form callerForm)
  69. {
  70. var gameConversionManger = Loader.Global.ConversionManager;
  71. gameConversionManger.CoordSystem = Autodesk.Max.IGameConversionManager.CoordSystem.D3d;
  72. var gameScene = Loader.Global.IGameInterface;
  73. gameScene.InitialiseIGame(onlySelected);
  74. gameScene.SetStaticFrame(0);
  75. MaxSceneFileName = gameScene.SceneFileName;
  76. IsCancelled = false;
  77. RaiseMessage("Exportation started", Color.Blue);
  78. ReportProgressChanged(0);
  79. var babylonScene = new BabylonScene(Path.GetDirectoryName(outputFile));
  80. var rawScene = Loader.Core.RootNode;
  81. if (!Directory.Exists(babylonScene.OutputPath))
  82. {
  83. RaiseError("Exportation stopped: Output folder does not exist");
  84. ReportProgressChanged(100);
  85. return;
  86. }
  87. var watch = new Stopwatch();
  88. watch.Start();
  89. // Save scene
  90. RaiseMessage("Saving 3ds max file");
  91. if (AutoSave3dsMaxFile)
  92. {
  93. var forceSave = Loader.Core.FileSave;
  94. callerForm?.BringToFront();
  95. }
  96. // Producer
  97. babylonScene.producer = new BabylonProducer
  98. {
  99. name = "3dsmax",
  100. #if MAX2017
  101. version = "2017",
  102. #else
  103. version = Loader.Core.ProductVersion.ToString(),
  104. #endif
  105. exporter_version = "0.4.5",
  106. file = Path.GetFileName(outputFile)
  107. };
  108. // Global
  109. babylonScene.autoClear = true;
  110. babylonScene.clearColor = Loader.Core.GetBackGround(0, Tools.Forever).ToArray();
  111. babylonScene.ambientColor = Loader.Core.GetAmbient(0, Tools.Forever).ToArray();
  112. babylonScene.gravity = rawScene.GetVector3Property("babylonjs_gravity");
  113. ExportQuaternionsInsteadOfEulers = rawScene.GetBoolProperty("babylonjs_exportquaternions", 1);
  114. // Sounds
  115. var soundName = rawScene.GetStringProperty("babylonjs_sound_filename", "");
  116. if (!string.IsNullOrEmpty(soundName))
  117. {
  118. var filename = Path.GetFileName(soundName);
  119. var globalSound = new BabylonSound
  120. {
  121. autoplay = rawScene.GetBoolProperty("babylonjs_sound_autoplay", 1),
  122. loop = rawScene.GetBoolProperty("babylonjs_sound_loop", 1),
  123. name = filename
  124. };
  125. babylonScene.SoundsList.Add(globalSound);
  126. try
  127. {
  128. File.Copy(soundName, Path.Combine(babylonScene.OutputPath, filename), true);
  129. }
  130. catch
  131. {
  132. }
  133. }
  134. // Root nodes
  135. RaiseMessage("Exporting nodes");
  136. HashSet<IIGameNode> maxRootNodes = getRootNodes(gameScene);
  137. var progressionStep = 80.0f / maxRootNodes.Count;
  138. var progression = 10.0f;
  139. ReportProgressChanged((int)progression);
  140. referencedMaterials.Clear();
  141. // Reseting is optionnal. It makes each morph target manager export starts from id = 0.
  142. BabylonMorphTargetManager.Reset();
  143. foreach (var maxRootNode in maxRootNodes)
  144. {
  145. exportNodeRec(maxRootNode, babylonScene, gameScene);
  146. progression += progressionStep;
  147. ReportProgressChanged((int)progression);
  148. CheckCancelled();
  149. };
  150. RaiseMessage(string.Format("Total meshes: {0}", babylonScene.MeshesList.Count), Color.Gray, 1);
  151. // Main camera
  152. BabylonCamera babylonMainCamera = null;
  153. ICameraObject maxMainCameraObject = null;
  154. if (babylonMainCamera == null && babylonScene.CamerasList.Count > 0)
  155. {
  156. // Set first camera as main one
  157. babylonMainCamera = babylonScene.CamerasList[0];
  158. babylonScene.activeCameraID = babylonMainCamera.id;
  159. RaiseMessage("Active camera set to " + babylonMainCamera.name, Color.Green, 1, true);
  160. // Retreive camera node with same GUID
  161. var maxCameraNodesAsTab = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Camera);
  162. var maxCameraNodes = TabToList(maxCameraNodesAsTab);
  163. var maxMainCameraNode = maxCameraNodes.Find(_camera => _camera.MaxNode.GetGuid().ToString() == babylonMainCamera.id);
  164. maxMainCameraObject = (maxMainCameraNode.MaxNode.ObjectRef as ICameraObject);
  165. }
  166. if (babylonMainCamera == null)
  167. {
  168. RaiseWarning("No camera defined", 1);
  169. }
  170. else
  171. {
  172. RaiseMessage(string.Format("Total cameras: {0}", babylonScene.CamerasList.Count), Color.Gray, 1);
  173. }
  174. // Default light
  175. if (babylonScene.LightsList.Count == 0)
  176. {
  177. RaiseWarning("No light defined", 1);
  178. RaiseWarning("A default hemispheric light was added for your convenience", 1);
  179. ExportDefaultLight(babylonScene);
  180. }
  181. else
  182. {
  183. RaiseMessage(string.Format("Total lights: {0}", babylonScene.LightsList.Count), Color.Gray, 1);
  184. }
  185. // Materials
  186. RaiseMessage("Exporting materials");
  187. var matsToExport = referencedMaterials.ToArray(); // Snapshot because multimaterials can export new materials
  188. foreach (var mat in matsToExport)
  189. {
  190. ExportMaterial(mat, babylonScene);
  191. CheckCancelled();
  192. }
  193. RaiseMessage(string.Format("Total: {0}", babylonScene.MaterialsList.Count + babylonScene.MultiMaterialsList.Count), Color.Gray, 1);
  194. // Fog
  195. for (var index = 0; index < Loader.Core.NumAtmospheric; index++)
  196. {
  197. var atmospheric = Loader.Core.GetAtmospheric(index);
  198. if (atmospheric.Active(0) && atmospheric.ClassName == "Fog")
  199. {
  200. var fog = atmospheric as IStdFog;
  201. RaiseMessage("Exporting fog");
  202. if (fog != null)
  203. {
  204. babylonScene.fogColor = fog.GetColor(0).ToArray();
  205. babylonScene.fogMode = 3;
  206. }
  207. if (babylonMainCamera != null)
  208. {
  209. babylonScene.fogStart = maxMainCameraObject.GetEnvRange(0, 0, Tools.Forever);
  210. babylonScene.fogEnd = maxMainCameraObject.GetEnvRange(0, 1, Tools.Forever);
  211. }
  212. }
  213. }
  214. // Skeletons
  215. if (skins.Count > 0)
  216. {
  217. RaiseMessage("Exporting skeletons");
  218. foreach (var skin in skins)
  219. {
  220. ExportSkin(skin, babylonScene);
  221. }
  222. }
  223. // Actions
  224. babylonScene.actions = ExportNodeAction(gameScene.GetIGameNode(rawScene));
  225. // Output
  226. RaiseMessage("Saving to output file");
  227. babylonScene.Prepare(false, false);
  228. var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings());
  229. var sb = new StringBuilder();
  230. var sw = new StringWriter(sb, CultureInfo.InvariantCulture);
  231. await Task.Run(() =>
  232. {
  233. using (var jsonWriter = new JsonTextWriterOptimized(sw))
  234. {
  235. jsonWriter.Formatting = Formatting.None;
  236. jsonSerializer.Serialize(jsonWriter, babylonScene);
  237. }
  238. File.WriteAllText(outputFile, sb.ToString());
  239. if (generateManifest)
  240. {
  241. File.WriteAllText(outputFile + ".manifest",
  242. "{\r\n\"version\" : 1,\r\n\"enableSceneOffline\" : true,\r\n\"enableTexturesOffline\" : true\r\n}");
  243. }
  244. });
  245. // Binary
  246. if (generateBinary)
  247. {
  248. RaiseMessage("Generating binary files");
  249. BabylonFileConverter.BinaryConverter.Convert(outputFile, Path.GetDirectoryName(outputFile) + "\\Binary",
  250. message => RaiseMessage(message, 1),
  251. error => RaiseError(error, 1));
  252. }
  253. ReportProgressChanged(100);
  254. // Export glTF
  255. if (exportGltf)
  256. {
  257. ExportGltf(babylonScene, outputFile, generateBinary);
  258. }
  259. watch.Stop();
  260. RaiseMessage(string.Format("Exportation done in {0:0.00}s", watch.ElapsedMilliseconds / 1000.0), Color.Blue);
  261. }
  262. private void exportNodeRec(IIGameNode maxGameNode, BabylonScene babylonScene, IIGameScene maxGameScene)
  263. {
  264. BabylonNode babylonNode = null;
  265. bool hasExporter = true;
  266. switch (maxGameNode.IGameObject.IGameType)
  267. {
  268. case Autodesk.Max.IGameObject.ObjectTypes.Mesh:
  269. babylonNode = ExportMesh(maxGameScene, maxGameNode, babylonScene);
  270. break;
  271. case Autodesk.Max.IGameObject.ObjectTypes.Camera:
  272. babylonNode = ExportCamera(maxGameScene, maxGameNode, babylonScene);
  273. break;
  274. case Autodesk.Max.IGameObject.ObjectTypes.Light:
  275. babylonNode = ExportLight(maxGameScene, maxGameNode, babylonScene);
  276. break;
  277. case Autodesk.Max.IGameObject.ObjectTypes.Unknown:
  278. // Create a dummy (empty mesh) when type is unknown
  279. // An example of unknown type object is the target of target light or camera
  280. babylonNode = ExportDummy(maxGameScene, maxGameNode, babylonScene);
  281. break;
  282. default:
  283. // The type of node is not exportable (helper, spline, xref...)
  284. hasExporter = false;
  285. break;
  286. }
  287. CheckCancelled();
  288. // If node is not exported successfully but is significant
  289. if (babylonNode == null &&
  290. isNodeRelevantToExport(maxGameNode))
  291. {
  292. //if (!hasExporter)
  293. //{
  294. // RaiseWarning($"Type '{maxGameNode.IGameObject.IGameType}' of node '{maxGameNode.Name}' has no exporter, an empty node is exported instead", 1);
  295. //}
  296. // Create a dummy (empty mesh)
  297. babylonNode = ExportDummy(maxGameScene, maxGameNode, babylonScene);
  298. };
  299. if (babylonNode != null)
  300. {
  301. // Export its children
  302. for (int i = 0; i < maxGameNode.ChildCount; i++)
  303. {
  304. var descendant = maxGameNode.GetNodeChild(i);
  305. exportNodeRec(descendant, babylonScene, maxGameScene);
  306. }
  307. }
  308. }
  309. /// <summary>
  310. /// Return true if node descendant hierarchy has any exportable Mesh, Camera or Light
  311. /// </summary>
  312. private bool isNodeRelevantToExport(IIGameNode maxGameNode)
  313. {
  314. bool isRelevantToExport;
  315. switch (maxGameNode.IGameObject.IGameType)
  316. {
  317. case Autodesk.Max.IGameObject.ObjectTypes.Mesh:
  318. isRelevantToExport = IsMeshExportable(maxGameNode);
  319. break;
  320. case Autodesk.Max.IGameObject.ObjectTypes.Camera:
  321. isRelevantToExport = IsCameraExportable(maxGameNode);
  322. break;
  323. case Autodesk.Max.IGameObject.ObjectTypes.Light:
  324. isRelevantToExport = IsLightExportable(maxGameNode);
  325. break;
  326. default:
  327. isRelevantToExport = false;
  328. break;
  329. }
  330. if (isRelevantToExport)
  331. {
  332. return true;
  333. }
  334. // Descandant recursivity
  335. List<IIGameNode> maxDescendants = getDescendants(maxGameNode);
  336. int indexDescendant = 0;
  337. while (indexDescendant < maxDescendants.Count) // while instead of for to stop as soon as a relevant node has been found
  338. {
  339. if (isNodeRelevantToExport(maxDescendants[indexDescendant]))
  340. {
  341. return true;
  342. }
  343. indexDescendant++;
  344. }
  345. // No relevant node found in hierarchy
  346. return false;
  347. }
  348. private List<IIGameNode> getDescendants(IIGameNode maxGameNode)
  349. {
  350. var maxDescendants = new List<IIGameNode>();
  351. for (int i = 0; i < maxGameNode.ChildCount; i++)
  352. {
  353. maxDescendants.Add(maxGameNode.GetNodeChild(i));
  354. }
  355. return maxDescendants;
  356. }
  357. private HashSet<IIGameNode> getRootNodes(IIGameScene maxGameScene)
  358. {
  359. HashSet<IIGameNode> maxGameNodes = new HashSet<IIGameNode>();
  360. Func<IIGameNode, IIGameNode> getMaxRootNode = delegate (IIGameNode maxGameNode)
  361. {
  362. while (maxGameNode.NodeParent != null)
  363. {
  364. maxGameNode = maxGameNode.NodeParent;
  365. }
  366. return maxGameNode;
  367. };
  368. Action<Autodesk.Max.IGameObject.ObjectTypes> addMaxRootNodes = delegate (Autodesk.Max.IGameObject.ObjectTypes type)
  369. {
  370. ITab<IIGameNode> maxGameNodesOfType = maxGameScene.GetIGameNodeByType(type);
  371. if (maxGameNodesOfType != null)
  372. {
  373. TabToList(maxGameNodesOfType).ForEach(maxGameNode =>
  374. {
  375. var maxRootNode = getMaxRootNode(maxGameNode);
  376. maxGameNodes.Add(maxRootNode);
  377. });
  378. }
  379. };
  380. addMaxRootNodes(Autodesk.Max.IGameObject.ObjectTypes.Mesh);
  381. addMaxRootNodes(Autodesk.Max.IGameObject.ObjectTypes.Light);
  382. addMaxRootNodes(Autodesk.Max.IGameObject.ObjectTypes.Camera);
  383. return maxGameNodes;
  384. }
  385. private static List<T> TabToList<T>(ITab<T> tab)
  386. {
  387. if (tab == null)
  388. {
  389. return null;
  390. }
  391. else
  392. {
  393. List<T> list = new List<T>();
  394. for (int i = 0; i < tab.Count; i++)
  395. {
  396. #if MAX2017
  397. var indexer = i;
  398. #else
  399. var indexer = new IntPtr(i);
  400. Marshal.FreeHGlobal(indexer);
  401. #endif
  402. list.Add(tab[indexer]);
  403. }
  404. return list;
  405. }
  406. }
  407. }
  408. }