BabylonExporter.Mesh.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. using Autodesk.Max;
  2. using BabylonExport.Entities;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. namespace Max2Babylon
  9. {
  10. partial class BabylonExporter
  11. {
  12. private int bonesCount;
  13. readonly Dictionary<IIGameSkin, List<int>> skinSortedBones = new Dictionary<IIGameSkin, List<int>>();
  14. private bool IsMeshExportable(IIGameNode meshNode)
  15. {
  16. if (meshNode.MaxNode.GetBoolProperty("babylonjs_noexport"))
  17. {
  18. return false;
  19. }
  20. if (!ExportHiddenObjects && meshNode.MaxNode.IsHidden(NodeHideFlags.None, false))
  21. {
  22. return false;
  23. }
  24. return true;
  25. }
  26. private BabylonNode ExportDummy(IIGameScene scene, IIGameNode meshNode, BabylonScene babylonScene)
  27. {
  28. RaiseMessage(meshNode.Name, 1);
  29. var gameMesh = meshNode.IGameObject.AsGameMesh();
  30. bool initialized = gameMesh.InitializeData; // needed, the property is in fact a method initializing the exporter that has wrongly been auto
  31. // translated into a property because it has no parameters
  32. var babylonMesh = new BabylonMesh { name = meshNode.Name, id = meshNode.MaxNode.GetGuid().ToString() };
  33. babylonMesh.isDummy = true;
  34. // Position / rotation / scaling / hierarchy
  35. exportNode(babylonMesh, meshNode, scene, babylonScene);
  36. // Animations
  37. exportAnimation(babylonMesh, meshNode);
  38. babylonScene.MeshesList.Add(babylonMesh);
  39. return babylonMesh;
  40. }
  41. private BabylonNode ExportMesh(IIGameScene scene, IIGameNode meshNode, BabylonScene babylonScene)
  42. {
  43. if (IsMeshExportable(meshNode) == false)
  44. {
  45. return null;
  46. }
  47. RaiseMessage(meshNode.Name, 1);
  48. // Instances
  49. var tabs = Loader.Global.NodeTab.Create();
  50. Loader.Global.IInstanceMgr.InstanceMgr.GetInstances(meshNode.MaxNode, tabs);
  51. if (tabs.Count > 1)
  52. {
  53. // For a mesh with instances, we distinguish between master and instance meshes:
  54. // - a master mesh stores all the info of the mesh (transform, hierarchy, animations + vertices, indices, materials, bones...)
  55. // - an instance mesh only stores the info of the node (transform, hierarchy, animations)
  56. // Check if this mesh has already been exported
  57. BabylonMesh babylonMasterMesh = null;
  58. var index = 0;
  59. while (babylonMasterMesh == null &&
  60. index < tabs.Count)
  61. {
  62. #if MAX2017
  63. var indexer = index;
  64. #else
  65. var indexer = new IntPtr(index);
  66. #endif
  67. var tab = tabs[indexer];
  68. babylonMasterMesh = babylonScene.MeshesList.Find(_babylonMesh => {
  69. // Same id
  70. return _babylonMesh.id == tab.GetGuid().ToString() &&
  71. // Mesh is not a dummy
  72. _babylonMesh.isDummy == false;
  73. });
  74. index++;
  75. }
  76. if (babylonMasterMesh != null)
  77. {
  78. // Mesh already exported
  79. // Export this node as instance
  80. meshNode.MaxNode.MarkAsInstance();
  81. var babylonInstanceMesh = new BabylonAbstractMesh { name = meshNode.Name, id = meshNode.MaxNode.GetGuid().ToString() };
  82. // Add instance to master mesh
  83. List<BabylonAbstractMesh> list = babylonMasterMesh.instances != null ? babylonMasterMesh.instances.ToList() : new List<BabylonAbstractMesh>();
  84. list.Add(babylonInstanceMesh);
  85. babylonMasterMesh.instances = list.ToArray();
  86. // Export transform / hierarchy / animations
  87. exportNode(babylonInstanceMesh, meshNode, scene, babylonScene);
  88. // Animations
  89. exportAnimation(babylonInstanceMesh, meshNode);
  90. return babylonInstanceMesh;
  91. }
  92. }
  93. var gameMesh = meshNode.IGameObject.AsGameMesh();
  94. bool initialized = gameMesh.InitializeData; // needed, the property is in fact a method initializing the exporter that has wrongly been auto
  95. // translated into a property because it has no parameters
  96. var babylonMesh = new BabylonMesh { name = meshNode.Name, id = meshNode.MaxNode.GetGuid().ToString() };
  97. // Position / rotation / scaling / hierarchy
  98. exportNode(babylonMesh, meshNode, scene, babylonScene);
  99. // Sounds
  100. var soundName = meshNode.MaxNode.GetStringProperty("babylonjs_sound_filename", "");
  101. if (!string.IsNullOrEmpty(soundName))
  102. {
  103. var filename = Path.GetFileName(soundName);
  104. var meshSound = new BabylonSound
  105. {
  106. name = filename,
  107. autoplay = meshNode.MaxNode.GetBoolProperty("babylonjs_sound_autoplay", 1),
  108. loop = meshNode.MaxNode.GetBoolProperty("babylonjs_sound_loop", 1),
  109. volume = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_volume", 1.0f),
  110. playbackRate = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_playbackrate", 1.0f),
  111. connectedMeshId = babylonMesh.id,
  112. isDirectional = false,
  113. spatialSound = false,
  114. distanceModel = meshNode.MaxNode.GetStringProperty("babylonjs_sound_distancemodel", "linear"),
  115. maxDistance = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_maxdistance", 100f),
  116. rolloffFactor = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_rolloff", 1.0f),
  117. refDistance = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_refdistance", 1.0f),
  118. };
  119. var isDirectional = meshNode.MaxNode.GetBoolProperty("babylonjs_sound_directional");
  120. if (isDirectional)
  121. {
  122. meshSound.isDirectional = true;
  123. meshSound.coneInnerAngle = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_coneinnerangle", 360f);
  124. meshSound.coneOuterAngle = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_coneouterangle", 360f);
  125. meshSound.coneOuterGain = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_coneoutergain", 1.0f);
  126. }
  127. babylonScene.SoundsList.Add(meshSound);
  128. try
  129. {
  130. File.Copy(soundName, Path.Combine(babylonScene.OutputPath, filename), true);
  131. }
  132. catch
  133. {
  134. }
  135. }
  136. // Misc.
  137. #if MAX2017
  138. babylonMesh.isVisible = meshNode.MaxNode.Renderable;
  139. babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows;
  140. babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics;
  141. #else
  142. babylonMesh.isVisible = meshNode.MaxNode.Renderable == 1;
  143. babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows == 1;
  144. babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics == 1;
  145. #endif
  146. babylonMesh.pickable = meshNode.MaxNode.GetBoolProperty("babylonjs_checkpickable");
  147. babylonMesh.showBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showboundingbox");
  148. babylonMesh.showSubMeshesBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showsubmeshesboundingbox");
  149. babylonMesh.alphaIndex = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_alphaindex", 1000);
  150. // Actions
  151. babylonMesh.actions = ExportNodeAction(meshNode);
  152. // Collisions
  153. babylonMesh.checkCollisions = meshNode.MaxNode.GetBoolProperty("babylonjs_checkcollisions");
  154. var isSkinned = gameMesh.IsObjectSkinned;
  155. var skin = gameMesh.IGameSkin;
  156. var unskinnedMesh = gameMesh;
  157. IGMatrix skinInitPoseMatrix = Loader.Global.GMatrix.Create(Loader.Global.Matrix3.Create(true));
  158. List<int> boneIds = null;
  159. int maxNbBones = 0;
  160. if (isSkinned)
  161. {
  162. bonesCount = skin.TotalSkinBoneCount;
  163. skins.Add(skin);
  164. skinnedNodes.Add(meshNode);
  165. babylonMesh.skeletonId = skins.IndexOf(skin);
  166. skin.GetInitSkinTM(skinInitPoseMatrix);
  167. boneIds = SortBones(skin);
  168. skinSortedBones[skin] = boneIds;
  169. }
  170. // Mesh
  171. if (unskinnedMesh.IGameType == Autodesk.Max.IGameObject.ObjectTypes.Mesh && unskinnedMesh.MaxMesh != null)
  172. {
  173. if (unskinnedMesh.NumberOfFaces < 1)
  174. {
  175. RaiseError($"Mesh {babylonMesh.name} has no face", 2);
  176. }
  177. if (unskinnedMesh.NumberOfVerts < 3)
  178. {
  179. RaiseError($"Mesh {babylonMesh.name} has not enough vertices", 2);
  180. }
  181. if (unskinnedMesh.NumberOfVerts >= 65536)
  182. {
  183. RaiseWarning($"Mesh {babylonMesh.name} has tmore than 65536 vertices which means that it will require specific WebGL extension to be rendered. This may impact portability of your scene on low end devices.", 2);
  184. }
  185. if (skin != null)
  186. {
  187. for (var vertexIndex = 0; vertexIndex < unskinnedMesh.NumberOfVerts; vertexIndex++)
  188. {
  189. maxNbBones = Math.Max(maxNbBones, skin.GetNumberOfBones(vertexIndex));
  190. }
  191. }
  192. // Physics
  193. var impostorText = meshNode.MaxNode.GetStringProperty("babylonjs_impostor", "None");
  194. if (impostorText != "None")
  195. {
  196. switch (impostorText)
  197. {
  198. case "Sphere":
  199. babylonMesh.physicsImpostor = 1;
  200. break;
  201. case "Box":
  202. babylonMesh.physicsImpostor = 2;
  203. break;
  204. case "Plane":
  205. babylonMesh.physicsImpostor = 3;
  206. break;
  207. default:
  208. babylonMesh.physicsImpostor = 0;
  209. break;
  210. }
  211. babylonMesh.physicsMass = meshNode.MaxNode.GetFloatProperty("babylonjs_mass");
  212. babylonMesh.physicsFriction = meshNode.MaxNode.GetFloatProperty("babylonjs_friction", 0.2f);
  213. babylonMesh.physicsRestitution = meshNode.MaxNode.GetFloatProperty("babylonjs_restitution", 0.2f);
  214. }
  215. // Material
  216. var mtl = meshNode.NodeMaterial;
  217. var multiMatsCount = 1;
  218. if (mtl != null)
  219. {
  220. babylonMesh.materialId = mtl.MaxMaterial.GetGuid().ToString();
  221. if (!referencedMaterials.Contains(mtl))
  222. {
  223. referencedMaterials.Add(mtl);
  224. }
  225. multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
  226. }
  227. babylonMesh.visibility = meshNode.MaxNode.GetVisibility(0, Tools.Forever);
  228. var vertices = new List<GlobalVertex>();
  229. var indices = new List<int>();
  230. var mappingChannels = unskinnedMesh.ActiveMapChannelNum;
  231. bool hasUV = false;
  232. bool hasUV2 = false;
  233. for (int i = 0; i < mappingChannels.Count; ++i)
  234. {
  235. #if MAX2017
  236. var indexer = i;
  237. #else
  238. var indexer = new IntPtr(i);
  239. #endif
  240. var channelNum = mappingChannels[indexer];
  241. if (channelNum == 1)
  242. {
  243. hasUV = true;
  244. }
  245. else if (channelNum == 2)
  246. {
  247. hasUV2 = true;
  248. }
  249. }
  250. var hasColor = unskinnedMesh.NumberOfColorVerts > 0;
  251. var hasAlpha = unskinnedMesh.GetNumberOfMapVerts(-2) > 0;
  252. var optimizeVertices = meshNode.MaxNode.GetBoolProperty("babylonjs_optimizevertices");
  253. // Compute normals
  254. var subMeshes = new List<BabylonSubMesh>();
  255. ExtractGeometry(vertices, indices, subMeshes, boneIds, skin, unskinnedMesh, hasUV, hasUV2, hasColor, hasAlpha, optimizeVertices, multiMatsCount, meshNode);
  256. if (vertices.Count >= 65536)
  257. {
  258. RaiseWarning($"Mesh {babylonMesh.name} has {vertices.Count} vertices. This may prevent your scene to work on low end devices where 32 bits indice are not supported", 2);
  259. if (!optimizeVertices)
  260. {
  261. RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2);
  262. }
  263. }
  264. RaiseMessage($"{vertices.Count} vertices, {indices.Count/3} faces", 2);
  265. // Buffers
  266. babylonMesh.positions = vertices.SelectMany(v => new[] { v.Position.X, v.Position.Y, v.Position.Z }).ToArray();
  267. babylonMesh.normals = vertices.SelectMany(v => new[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToArray();
  268. if (hasUV)
  269. {
  270. babylonMesh.uvs = vertices.SelectMany(v => new[] { v.UV.X, 1 - v.UV.Y }).ToArray();
  271. }
  272. if (hasUV2)
  273. {
  274. babylonMesh.uvs2 = vertices.SelectMany(v => new[] { v.UV2.X, 1 - v.UV2.Y }).ToArray();
  275. }
  276. if (skin != null)
  277. {
  278. babylonMesh.matricesWeights = vertices.SelectMany(v => v.Weights.ToArray()).ToArray();
  279. babylonMesh.matricesIndices = vertices.Select(v => v.BonesIndices).ToArray();
  280. babylonMesh.numBoneInfluencers = maxNbBones;
  281. if (maxNbBones > 4)
  282. {
  283. babylonMesh.matricesWeightsExtra = vertices.SelectMany(v => v.WeightsExtra != null ? v.WeightsExtra.ToArray() : new[] {0.0f, 0.0f, 0.0f, 0.0f }).ToArray();
  284. babylonMesh.matricesIndicesExtra = vertices.Select(v => v.BonesIndicesExtra).ToArray();
  285. }
  286. }
  287. if (hasColor)
  288. {
  289. babylonMesh.colors = vertices.SelectMany(v => v.Color.ToArray()).ToArray();
  290. babylonMesh.hasVertexAlpha = hasAlpha;
  291. }
  292. babylonMesh.subMeshes = subMeshes.ToArray();
  293. // Buffers - Indices
  294. babylonMesh.indices = indices.ToArray();
  295. // ------------------------
  296. // ---- Morph targets -----
  297. // ------------------------
  298. // Retreive modifiers with morpher flag
  299. List<IIGameModifier> modifiers = new List<IIGameModifier>();
  300. for (int i = 0; i < meshNode.IGameObject.NumModifiers; i++)
  301. {
  302. var modifier = meshNode.IGameObject.GetIGameModifier(i);
  303. if (modifier.ModifierType == Autodesk.Max.IGameModifier.ModType.Morpher)
  304. {
  305. modifiers.Add(modifier);
  306. }
  307. }
  308. // Cast modifiers to morphers
  309. List<IIGameMorpher> morphers = modifiers.ConvertAll(new Converter<IIGameModifier, IIGameMorpher>(modifier => modifier.AsGameMorpher()));
  310. var hasMorphTarget = false;
  311. morphers.ForEach(morpher =>
  312. {
  313. if (morpher.NumberOfMorphTargets > 0)
  314. {
  315. hasMorphTarget = true;
  316. }
  317. });
  318. if (hasMorphTarget)
  319. {
  320. RaiseMessage("Export morph targets", 2);
  321. // Morph Target Manager
  322. var babylonMorphTargetManager = new BabylonMorphTargetManager();
  323. babylonScene.MorphTargetManagersList.Add(babylonMorphTargetManager);
  324. babylonMesh.morphTargetManagerId = babylonMorphTargetManager.id;
  325. // Morph Targets
  326. var babylonMorphTargets = new List<BabylonMorphTarget>();
  327. // All morphers are considered identical
  328. // Their targets are concatenated
  329. morphers.ForEach(morpher =>
  330. {
  331. for (int i = 0; i < morpher.NumberOfMorphTargets; i++)
  332. {
  333. // Morph target
  334. var maxMorphTarget = morpher.GetMorphTarget(i);
  335. // Ensure target still exists (green color legend)
  336. if (maxMorphTarget != null)
  337. {
  338. var babylonMorphTarget = new BabylonMorphTarget
  339. {
  340. name = maxMorphTarget.Name
  341. };
  342. babylonMorphTargets.Add(babylonMorphTarget);
  343. // TODO - Influence
  344. babylonMorphTarget.influence = 0f;
  345. // Target geometry
  346. var targetVertices = ExtractVertices(maxMorphTarget, optimizeVertices);
  347. babylonMorphTarget.positions = targetVertices.SelectMany(v => new[] { v.Position.X, v.Position.Y, v.Position.Z }).ToArray();
  348. babylonMorphTarget.normals = targetVertices.SelectMany(v => new[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToArray();
  349. // Animations
  350. var animations = new List<BabylonAnimation>();
  351. var morphWeight = morpher.GetMorphWeight(i);
  352. ExportFloatGameController(morphWeight, "influence", animations);
  353. if (animations.Count > 0)
  354. {
  355. babylonMorphTarget.animations = animations.ToArray();
  356. }
  357. }
  358. }
  359. });
  360. babylonMorphTargetManager.targets = babylonMorphTargets.ToArray();
  361. }
  362. }
  363. // Animations
  364. // Done last to avoid '0 vertex found' error (unkown cause)
  365. exportAnimation(babylonMesh, meshNode);
  366. babylonScene.MeshesList.Add(babylonMesh);
  367. return babylonMesh;
  368. }
  369. private List<GlobalVertex> ExtractVertices(IIGameNode maxMorphTarget, bool optimizeVertices)
  370. {
  371. var gameMesh = maxMorphTarget.IGameObject.AsGameMesh();
  372. bool initialized = gameMesh.InitializeData; // needed, the property is in fact a method initializing the exporter that has wrongly been auto
  373. // translated into a property because it has no parameters
  374. var mtl = maxMorphTarget.NodeMaterial;
  375. var multiMatsCount = 1;
  376. if (mtl != null)
  377. {
  378. multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
  379. }
  380. var vertices = new List<GlobalVertex>();
  381. ExtractGeometry(vertices, new List<int>(), new List<BabylonSubMesh>(), null, null, gameMesh, false, false, false, false, optimizeVertices, multiMatsCount, maxMorphTarget);
  382. return vertices;
  383. }
  384. private void ExtractGeometry(List<GlobalVertex> vertices, List<int> indices, List<BabylonSubMesh> subMeshes, List<int> boneIds, IIGameSkin skin, IIGameMesh unskinnedMesh, bool hasUV, bool hasUV2, bool hasColor, bool hasAlpha, bool optimizeVertices, int multiMatsCount, IIGameNode meshNode)
  385. {
  386. List<GlobalVertex>[] verticesAlreadyExported = null;
  387. if (optimizeVertices)
  388. {
  389. verticesAlreadyExported = new List<GlobalVertex>[unskinnedMesh.NumberOfVerts];
  390. }
  391. var indexStart = 0;
  392. for (int i = 0; i < multiMatsCount; ++i)
  393. {
  394. int materialId = meshNode.NodeMaterial?.GetMaterialID(i) ?? 0;
  395. var indexCount = 0;
  396. var minVertexIndex = int.MaxValue;
  397. var maxVertexIndex = int.MinValue;
  398. var subMesh = new BabylonSubMesh { indexStart = indexStart, materialIndex = i };
  399. if (multiMatsCount == 1)
  400. {
  401. for (int j = 0; j < unskinnedMesh.NumberOfFaces; ++j)
  402. {
  403. var face = unskinnedMesh.GetFace(j);
  404. ExtractFace(skin, unskinnedMesh, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face, boneIds);
  405. }
  406. }
  407. else
  408. {
  409. ITab<IFaceEx> materialFaces = unskinnedMesh.GetFacesFromMatID(materialId);
  410. for (int j = 0; j < materialFaces.Count; ++j)
  411. {
  412. #if MAX2017
  413. var faceIndexer = j;
  414. #else
  415. var faceIndexer = new IntPtr(j);
  416. #endif
  417. var face = materialFaces[faceIndexer];
  418. #if !MAX2017
  419. Marshal.FreeHGlobal(faceIndexer);
  420. #endif
  421. ExtractFace(skin, unskinnedMesh, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face, boneIds);
  422. }
  423. }
  424. if (indexCount != 0)
  425. {
  426. subMesh.indexCount = indexCount;
  427. subMesh.verticesStart = minVertexIndex;
  428. subMesh.verticesCount = maxVertexIndex - minVertexIndex + 1;
  429. indexStart += indexCount;
  430. subMeshes.Add(subMesh);
  431. }
  432. }
  433. }
  434. private void ExtractFace(IIGameSkin skin, IIGameMesh unskinnedMesh, List<GlobalVertex> vertices, List<int> indices, bool hasUV, bool hasUV2, bool hasColor, bool hasAlpha, List<GlobalVertex>[] verticesAlreadyExported, ref int indexCount, ref int minVertexIndex, ref int maxVertexIndex, IFaceEx face, List<int> boneIds)
  435. {
  436. var a = CreateGlobalVertex(unskinnedMesh, face, 0, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  437. var b = CreateGlobalVertex(unskinnedMesh, face, 2, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  438. var c = CreateGlobalVertex(unskinnedMesh, face, 1, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  439. indices.Add(a);
  440. indices.Add(b);
  441. indices.Add(c);
  442. if (a < minVertexIndex)
  443. {
  444. minVertexIndex = a;
  445. }
  446. if (b < minVertexIndex)
  447. {
  448. minVertexIndex = b;
  449. }
  450. if (c < minVertexIndex)
  451. {
  452. minVertexIndex = c;
  453. }
  454. if (a > maxVertexIndex)
  455. {
  456. maxVertexIndex = a;
  457. }
  458. if (b > maxVertexIndex)
  459. {
  460. maxVertexIndex = b;
  461. }
  462. if (c > maxVertexIndex)
  463. {
  464. maxVertexIndex = c;
  465. }
  466. indexCount += 3;
  467. CheckCancelled();
  468. }
  469. List<int> SortBones(IIGameSkin skin)
  470. {
  471. var boneIds = new List<int>();
  472. var boneIndex = new Dictionary<int, IIGameNode>();
  473. for (var index = 0; index < skin.TotalSkinBoneCount; index++)
  474. {
  475. var bone = skin.GetIGameBone(index, false);
  476. if (bone == null)
  477. {
  478. // non bone in skeletton
  479. boneIds.Add(-2);
  480. }
  481. else
  482. {
  483. boneIds.Add(bone.NodeID);
  484. boneIndex[bone.NodeID] = bone;
  485. }
  486. }
  487. while (true)
  488. {
  489. bool foundMisMatch = false;
  490. for (int i = 0; i < boneIds.Count; ++i)
  491. {
  492. var id = boneIds[i];
  493. if (id == -2)
  494. {
  495. continue;
  496. }
  497. var parent = boneIndex[id].NodeParent;
  498. if (parent != null)
  499. {
  500. var parentId = parent.NodeID;
  501. if (boneIds.IndexOf(parentId) > i)
  502. {
  503. boneIds.RemoveAt(i);
  504. boneIds.Insert(boneIds.IndexOf(parentId) + 1, id);
  505. foundMisMatch = true;
  506. break;
  507. }
  508. }
  509. }
  510. if (!foundMisMatch)
  511. {
  512. break;
  513. }
  514. }
  515. return boneIds;
  516. }
  517. int CreateGlobalVertex(IIGameMesh mesh, IFaceEx face, int facePart, List<GlobalVertex> vertices, bool hasUV, bool hasUV2, bool hasColor, bool hasAlpha, List<GlobalVertex>[] verticesAlreadyExported, IIGameSkin skin, List<int> boneIds)
  518. {
  519. var vertexIndex = (int)face.Vert[facePart];
  520. var vertex = new GlobalVertex
  521. {
  522. BaseIndex = vertexIndex,
  523. Position = mesh.GetVertex(vertexIndex, true),
  524. Normal = mesh.GetNormal((int)face.Norm[facePart], true)
  525. };
  526. if (hasUV)
  527. {
  528. var indices = new int[3];
  529. unsafe
  530. {
  531. fixed (int* indicesPtr = indices)
  532. {
  533. mesh.GetMapFaceIndex(1, face.MeshFaceIndex, new IntPtr(indicesPtr));
  534. }
  535. }
  536. var texCoord = mesh.GetMapVertex(1, indices[facePart]);
  537. vertex.UV = Loader.Global.Point2.Create(texCoord.X, -texCoord.Y);
  538. }
  539. if (hasUV2)
  540. {
  541. var indices = new int[3];
  542. unsafe
  543. {
  544. fixed (int* indicesPtr = indices)
  545. {
  546. mesh.GetMapFaceIndex(2, face.MeshFaceIndex, new IntPtr(indicesPtr));
  547. }
  548. }
  549. var texCoord = mesh.GetMapVertex(2, indices[facePart]);
  550. vertex.UV2 = Loader.Global.Point2.Create(texCoord.X, -texCoord.Y);
  551. }
  552. if (hasColor)
  553. {
  554. var vertexColorIndex = (int)face.Color[facePart];
  555. var vertexColor = mesh.GetColorVertex(vertexColorIndex);
  556. float alpha = 1;
  557. if (hasAlpha)
  558. {
  559. var indices = new int[3];
  560. unsafe
  561. {
  562. fixed (int* indicesPtr = indices)
  563. {
  564. mesh.GetMapFaceIndex(-2, face.MeshFaceIndex, new IntPtr(indicesPtr));
  565. }
  566. }
  567. var color = mesh.GetMapVertex(-2, indices[facePart]);
  568. alpha = color.X;
  569. }
  570. vertex.Color = new[] { vertexColor.X, vertexColor.Y, vertexColor.Z, alpha };
  571. }
  572. if (skin != null)
  573. {
  574. float weight0 = 0;
  575. float weight1 = 0;
  576. float weight2 = 0;
  577. float weight3 = 0;
  578. int bone0 = bonesCount;
  579. int bone1 = bonesCount;
  580. int bone2 = bonesCount;
  581. int bone3 = bonesCount;
  582. var nbBones = skin.GetNumberOfBones(vertexIndex);
  583. if (nbBones > 0)
  584. {
  585. bone0 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 0).NodeID);
  586. weight0 = skin.GetWeight(vertexIndex, 0);
  587. }
  588. if (nbBones > 1)
  589. {
  590. bone1 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 1).NodeID);
  591. weight1 = skin.GetWeight(vertexIndex, 1);
  592. }
  593. if (nbBones > 2)
  594. {
  595. bone2 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 2).NodeID);
  596. weight2 = skin.GetWeight(vertexIndex, 2);
  597. }
  598. if (nbBones > 3)
  599. {
  600. bone3 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 3).NodeID);
  601. weight3 = skin.GetWeight(vertexIndex, 3);
  602. }
  603. if (nbBones == 0)
  604. {
  605. weight0 = 1.0f;
  606. bone0 = bonesCount;
  607. }
  608. vertex.Weights = Loader.Global.Point4.Create(weight0, weight1, weight2, weight3);
  609. vertex.BonesIndices = (bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0;
  610. if (nbBones > 4)
  611. {
  612. bone0 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 4).NodeID);
  613. weight0 = skin.GetWeight(vertexIndex, 4);
  614. weight1 = 0;
  615. weight2 = 0;
  616. weight3 = 0;
  617. if (nbBones > 5)
  618. {
  619. bone1 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 5).NodeID);
  620. weight1 = skin.GetWeight(vertexIndex, 5);
  621. }
  622. if (nbBones > 6)
  623. {
  624. bone2 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 6).NodeID);
  625. weight2 = skin.GetWeight(vertexIndex, 6);
  626. }
  627. if (nbBones > 7)
  628. {
  629. bone3 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 7).NodeID);
  630. weight3 = skin.GetWeight(vertexIndex, 7);
  631. }
  632. vertex.WeightsExtra = Loader.Global.Point4.Create(weight0, weight1, weight2, weight3);
  633. vertex.BonesIndicesExtra = (bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0;
  634. if (nbBones > 8)
  635. {
  636. RaiseError("Too many bones influences per vertex: " + nbBones + ". Babylon.js only support 8 bones influences per vertex.", 2);
  637. }
  638. }
  639. }
  640. if (verticesAlreadyExported != null)
  641. {
  642. if (verticesAlreadyExported[vertexIndex] != null)
  643. {
  644. var index = verticesAlreadyExported[vertexIndex].IndexOf(vertex);
  645. if (index > -1)
  646. {
  647. return verticesAlreadyExported[vertexIndex][index].CurrentIndex;
  648. }
  649. }
  650. else
  651. {
  652. verticesAlreadyExported[vertexIndex] = new List<GlobalVertex>();
  653. }
  654. vertex.CurrentIndex = vertices.Count;
  655. verticesAlreadyExported[vertexIndex].Add(vertex);
  656. }
  657. vertices.Add(vertex);
  658. return vertices.Count - 1;
  659. }
  660. private void exportNode(BabylonAbstractMesh babylonAbstractMesh, IIGameNode maxGameNode, IIGameScene maxGameScene, BabylonScene babylonScene)
  661. {
  662. // Position / rotation / scaling
  663. exportTransform(babylonAbstractMesh, maxGameNode);
  664. // Hierarchy
  665. if (maxGameNode.NodeParent != null)
  666. {
  667. babylonAbstractMesh.parentId = maxGameNode.NodeParent.MaxNode.GetGuid().ToString();
  668. }
  669. }
  670. private void exportTransform(BabylonAbstractMesh babylonAbstractMesh, IIGameNode maxGameNode)
  671. {
  672. // Position / rotation / scaling
  673. var localTM = maxGameNode.GetObjectTM(0);
  674. if (maxGameNode.NodeParent != null)
  675. {
  676. var parentWorld = maxGameNode.NodeParent.GetObjectTM(0);
  677. localTM.MultiplyBy(parentWorld.Inverse);
  678. }
  679. var meshTrans = localTM.Translation;
  680. var meshRotation = localTM.Rotation;
  681. var meshScale = localTM.Scaling;
  682. babylonAbstractMesh.position = new[] { meshTrans.X, meshTrans.Y, meshTrans.Z };
  683. var rotationQuaternion = new BabylonQuaternion { X = meshRotation.X, Y = meshRotation.Y, Z = meshRotation.Z, W = -meshRotation.W };
  684. if (ExportQuaternionsInsteadOfEulers)
  685. {
  686. babylonAbstractMesh.rotationQuaternion = rotationQuaternion.ToArray();
  687. }
  688. else
  689. {
  690. babylonAbstractMesh.rotation = rotationQuaternion.toEulerAngles().ToArray();
  691. }
  692. babylonAbstractMesh.scaling = new[] { meshScale.X, meshScale.Y, meshScale.Z };
  693. }
  694. private void exportAnimation(BabylonNode babylonNode, IIGameNode maxGameNode)
  695. {
  696. var animations = new List<BabylonAnimation>();
  697. GenerateCoordinatesAnimations(maxGameNode, animations);
  698. if (!ExportFloatController(maxGameNode.MaxNode.VisController, "visibility", animations))
  699. {
  700. ExportFloatAnimation("visibility", animations, key => new[] { maxGameNode.MaxNode.GetVisibility(key, Tools.Forever) });
  701. }
  702. babylonNode.animations = animations.ToArray();
  703. if (maxGameNode.MaxNode.GetBoolProperty("babylonjs_autoanimate", 1))
  704. {
  705. babylonNode.autoAnimate = true;
  706. babylonNode.autoAnimateFrom = (int)maxGameNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_from");
  707. babylonNode.autoAnimateTo = (int)maxGameNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_to", 100);
  708. babylonNode.autoAnimateLoop = maxGameNode.MaxNode.GetBoolProperty("babylonjs_autoanimateloop", 1);
  709. }
  710. }
  711. public void GenerateCoordinatesAnimations(IIGameNode meshNode, List<BabylonAnimation> animations)
  712. {
  713. if (meshNode.IGameControl.IsAnimated(IGameControlType.Pos) ||
  714. meshNode.IGameControl.IsAnimated(IGameControlType.PosX) ||
  715. meshNode.IGameControl.IsAnimated(IGameControlType.PosY) ||
  716. meshNode.IGameControl.IsAnimated(IGameControlType.PosZ))
  717. {
  718. ExportVector3Animation("position", animations, key =>
  719. {
  720. var worldMatrix = meshNode.GetObjectTM(key);
  721. if (meshNode.NodeParent != null)
  722. {
  723. var parentWorld = meshNode.NodeParent.GetObjectTM(key);
  724. worldMatrix.MultiplyBy(parentWorld.Inverse);
  725. }
  726. var trans = worldMatrix.Translation;
  727. return new[] { trans.X, trans.Y, trans.Z };
  728. });
  729. }
  730. if (meshNode.IGameControl.IsAnimated(IGameControlType.Rot) ||
  731. meshNode.IGameControl.IsAnimated(IGameControlType.EulerX) ||
  732. meshNode.IGameControl.IsAnimated(IGameControlType.EulerY) ||
  733. meshNode.IGameControl.IsAnimated(IGameControlType.EulerZ))
  734. {
  735. ExportQuaternionAnimation("rotationQuaternion", animations, key =>
  736. {
  737. var worldMatrix = meshNode.GetObjectTM(key);
  738. if (meshNode.NodeParent != null)
  739. {
  740. var parentWorld = meshNode.NodeParent.GetObjectTM(key);
  741. worldMatrix.MultiplyBy(parentWorld.Inverse);
  742. }
  743. var rot = worldMatrix.Rotation;
  744. return new[] { rot.X, rot.Y, rot.Z, -rot.W };
  745. });
  746. }
  747. if (meshNode.IGameControl.IsAnimated(IGameControlType.Scale))
  748. {
  749. ExportVector3Animation("scaling", animations, key =>
  750. {
  751. var worldMatrix = meshNode.GetObjectTM(key);
  752. if (meshNode.NodeParent != null)
  753. {
  754. var parentWorld = meshNode.NodeParent.GetObjectTM(key);
  755. worldMatrix.MultiplyBy(parentWorld.Inverse);
  756. }
  757. var scale = worldMatrix.Scaling;
  758. return new[] { scale.X, scale.Y, scale.Z };
  759. });
  760. }
  761. }
  762. }
  763. }