BabylonExporter.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using Autodesk.Max;
  11. using BabylonExport.Entities;
  12. using Newtonsoft.Json;
  13. using Color = System.Drawing.Color;
  14. using System.Runtime.InteropServices;
  15. namespace Max2Babylon
  16. {
  17. internal partial class BabylonExporter
  18. {
  19. public event Action<int> OnImportProgressChanged;
  20. public event Action<string, int> OnWarning;
  21. public event Action<string, Color, int, bool> OnMessage;
  22. public event Action<string, int> OnError;
  23. string maxSceneFileName;
  24. readonly List<string> alreadyExportedTextures = new List<string>();
  25. public bool AutoSave3dsMaxFile { get; set; }
  26. public bool ExportHiddenObjects { get; set; }
  27. public bool IsCancelled { get; set; }
  28. public bool CopyTexturesToOutput { get; set; }
  29. private bool exportQuaternionsInsteadOfEulers;
  30. void ReportProgressChanged(int progress)
  31. {
  32. if (OnImportProgressChanged != null)
  33. {
  34. OnImportProgressChanged(progress);
  35. }
  36. }
  37. void RaiseError(string error, int rank = 0)
  38. {
  39. if (OnError != null)
  40. {
  41. OnError(error, rank);
  42. }
  43. }
  44. void RaiseWarning(string warning, int rank = 0)
  45. {
  46. if (OnWarning != null)
  47. {
  48. OnWarning(warning, rank);
  49. }
  50. }
  51. void RaiseMessage(string message, int rank = 0, bool emphasis = false)
  52. {
  53. RaiseMessage(message, Color.Black, rank, emphasis);
  54. }
  55. void RaiseMessage(string message, Color color, int rank = 0, bool emphasis = false)
  56. {
  57. if (OnMessage != null)
  58. {
  59. OnMessage(message, color, rank, emphasis);
  60. }
  61. }
  62. void CheckCancelled()
  63. {
  64. Application.DoEvents();
  65. if (IsCancelled)
  66. {
  67. throw new OperationCanceledException();
  68. }
  69. }
  70. public async Task ExportAsync(string outputFile, bool generateManifest, bool onlySelected, Form callerForm)
  71. {
  72. var gameConversionManger = Loader.Global.ConversionManager;
  73. gameConversionManger.CoordSystem = Autodesk.Max.IGameConversionManager.CoordSystem.D3d;
  74. var gameScene = Loader.Global.IGameInterface;
  75. gameScene.InitialiseIGame(onlySelected);
  76. gameScene.SetStaticFrame(0);
  77. maxSceneFileName = gameScene.SceneFileName;
  78. IsCancelled = false;
  79. RaiseMessage("Exportation started", Color.Blue);
  80. ReportProgressChanged(0);
  81. var babylonScene = new BabylonScene(Path.GetDirectoryName(outputFile));
  82. var rawScene = Loader.Core.RootNode;
  83. alreadyExportedTextures.Clear();
  84. if (!Directory.Exists(babylonScene.OutputPath))
  85. {
  86. RaiseError("Exportation stopped: Output folder does not exist");
  87. ReportProgressChanged(100);
  88. return;
  89. }
  90. var watch = new Stopwatch();
  91. watch.Start();
  92. // Save scene
  93. RaiseMessage("Saving 3ds max file");
  94. if (AutoSave3dsMaxFile)
  95. {
  96. var forceSave = Loader.Core.FileSave;
  97. if (callerForm != null)
  98. {
  99. callerForm.BringToFront();
  100. }
  101. }
  102. // Global
  103. babylonScene.autoClear = true;
  104. babylonScene.clearColor = Loader.Core.GetBackGround(0, Tools.Forever).ToArray();
  105. babylonScene.ambientColor = Loader.Core.GetAmbient(0, Tools.Forever).ToArray();
  106. babylonScene.gravity = rawScene.GetVector3Property("babylonjs_gravity");
  107. exportQuaternionsInsteadOfEulers = rawScene.GetBoolProperty("babylonjs_exportquaternions", 1);
  108. // Cameras
  109. BabylonCamera mainCamera = null;
  110. ICameraObject mainCameraNode = null;
  111. RaiseMessage("Exporting cameras");
  112. var camerasTab = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Camera);
  113. for (int ix = 0; ix < camerasTab.Count; ++ix)
  114. {
  115. var indexer = new IntPtr(ix);
  116. var cameraNode = camerasTab[indexer];
  117. Marshal.FreeHGlobal(indexer);
  118. ExportCamera(cameraNode, babylonScene);
  119. if (mainCamera == null && babylonScene.CamerasList.Count > 0)
  120. {
  121. mainCameraNode = (cameraNode.MaxNode.ObjectRef as ICameraObject);
  122. mainCamera = babylonScene.CamerasList[0];
  123. babylonScene.activeCameraID = mainCamera.id;
  124. RaiseMessage("Active camera set to " + mainCamera.name, Color.Green, 1, true);
  125. }
  126. }
  127. if (mainCamera == null)
  128. {
  129. RaiseWarning("No camera defined", 1);
  130. }
  131. else
  132. {
  133. RaiseMessage(string.Format("Total: {0}", babylonScene.CamerasList.Count), Color.Gray, 1);
  134. }
  135. // Fog
  136. for (var index = 0; index < Loader.Core.NumAtmospheric; index++)
  137. {
  138. var atmospheric = Loader.Core.GetAtmospheric(index);
  139. if (atmospheric.Active(0) && atmospheric.ClassName == "Fog")
  140. {
  141. var fog = atmospheric as IStdFog;
  142. RaiseMessage("Exporting fog");
  143. if (fog != null)
  144. {
  145. babylonScene.fogColor = fog.GetColor(0).ToArray();
  146. babylonScene.fogMode = 3;
  147. }
  148. #if !MAX2015
  149. else
  150. {
  151. var paramBlock = atmospheric.GetReference(0) as IIParamBlock;
  152. babylonScene.fogColor = Tools.GetParamBlockValueColor(paramBlock, "Fog Color");
  153. babylonScene.fogMode = 3;
  154. }
  155. #endif
  156. if (mainCamera != null)
  157. {
  158. babylonScene.fogStart = mainCameraNode.GetEnvRange(0, 0, Tools.Forever);
  159. babylonScene.fogEnd = mainCameraNode.GetEnvRange(0, 1, Tools.Forever);
  160. }
  161. }
  162. }
  163. // Meshes
  164. ReportProgressChanged(10);
  165. RaiseMessage("Exporting meshes");
  166. var meshes = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Mesh);
  167. var progressionStep = 80.0f / meshes.Count;
  168. var progression = 10.0f;
  169. for (int ix = 0; ix < meshes.Count; ++ix)
  170. {
  171. var indexer = new IntPtr(ix);
  172. var meshNode = meshes[indexer];
  173. Marshal.FreeHGlobal(indexer);
  174. ExportMesh(gameScene, meshNode, babylonScene);
  175. ReportProgressChanged((int)progression);
  176. CheckCancelled();
  177. }
  178. // Materials
  179. RaiseMessage("Exporting materials");
  180. var matsToExport = referencedMaterials.ToArray(); // Snapshot because multimaterials can export new materials
  181. foreach (var mat in matsToExport)
  182. {
  183. ExportMaterial(mat, babylonScene);
  184. CheckCancelled();
  185. }
  186. RaiseMessage(string.Format("Total: {0}", babylonScene.MaterialsList.Count + babylonScene.MultiMaterialsList.Count), Color.Gray, 1);
  187. // Lights
  188. RaiseMessage("Exporting lights");
  189. var lightNodes = gameScene.GetIGameNodeByType(Autodesk.Max.IGameObject.ObjectTypes.Light);
  190. for (var i = 0; i < lightNodes.Count; ++i)
  191. {
  192. ExportLight(lightNodes[new IntPtr(i)], babylonScene);
  193. CheckCancelled();
  194. }
  195. if (babylonScene.LightsList.Count == 0)
  196. {
  197. RaiseWarning("No light defined", 1);
  198. RaiseWarning("A default hemispheric light was added for your convenience", 1);
  199. ExportDefaultLight(babylonScene);
  200. }
  201. else
  202. {
  203. RaiseMessage(string.Format("Total: {0}", babylonScene.LightsList.Count), Color.Gray, 1);
  204. }
  205. // Skeletons
  206. if (skins.Count > 0)
  207. {
  208. RaiseMessage("Exporting skeletons");
  209. foreach (var skin in skins)
  210. {
  211. ExportSkin(skin, babylonScene);
  212. }
  213. }
  214. // Output
  215. RaiseMessage("Saving to output file");
  216. babylonScene.Prepare(false);
  217. var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings());
  218. var sb = new StringBuilder();
  219. var sw = new StringWriter(sb, CultureInfo.InvariantCulture);
  220. await Task.Run(() =>
  221. {
  222. using (var jsonWriter = new JsonTextWriterOptimized(sw))
  223. {
  224. jsonWriter.Formatting = Formatting.None;
  225. jsonSerializer.Serialize(jsonWriter, babylonScene);
  226. }
  227. File.WriteAllText(outputFile, sb.ToString());
  228. if (generateManifest)
  229. {
  230. File.WriteAllText(outputFile + ".manifest",
  231. "{\r\n\"version\" : 1,\r\n\"enableSceneOffline\" : true,\r\n\"enableTexturesOffline\" : true\r\n}");
  232. }
  233. });
  234. ReportProgressChanged(100);
  235. watch.Stop();
  236. RaiseMessage(string.Format("Exportation done in {0:0.00}s", watch.ElapsedMilliseconds / 1000.0), Color.Blue);
  237. }
  238. }
  239. }