BabylonExporter.Mesh.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Autodesk.Max;
  5. using BabylonExport.Entities;
  6. using System.Runtime.InteropServices;
  7. namespace Max2Babylon
  8. {
  9. partial class BabylonExporter
  10. {
  11. Dictionary<IIGameSkin, List<int>> skinSortedBones = new Dictionary<IIGameSkin, List<int>>();
  12. List<int> SortBones(IIGameSkin skin)
  13. {
  14. List<int> boneIds = new List<int>();
  15. Dictionary<int, IIGameNode> boneIndex = new Dictionary<int, IIGameNode>();
  16. for (var index = 0; index < skin.TotalSkinBoneCount; index++)
  17. {
  18. var bone = skin.GetIGameBone(index, false);
  19. if (bone == null)
  20. {
  21. // non bone in skeletton
  22. boneIds.Add(-2);
  23. }
  24. else
  25. {
  26. boneIds.Add(bone.NodeID);
  27. boneIndex[bone.NodeID] = bone;
  28. }
  29. }
  30. while (true)
  31. {
  32. bool foundMisMatch = false;
  33. for (int i = 0; i < boneIds.Count; ++i)
  34. {
  35. var id = boneIds[i];
  36. if(id == -2)
  37. {
  38. continue;
  39. }
  40. var parent = boneIndex[id].NodeParent;
  41. if(parent != null)
  42. {
  43. var parentId = parent.NodeID;
  44. if (boneIds.IndexOf(parentId) > i)
  45. {
  46. boneIds.RemoveAt(i);
  47. boneIds.Insert(boneIds.IndexOf(parentId) + 1, id);
  48. foundMisMatch = true;
  49. break;
  50. }
  51. }
  52. }
  53. if(!foundMisMatch)
  54. {
  55. break;
  56. }
  57. }
  58. return boneIds;
  59. }
  60. private int bonesCount;
  61. private void ExportMesh(IIGameScene scene, IIGameNode meshNode, BabylonScene babylonScene)
  62. {
  63. if (meshNode.MaxNode.IsInstance())
  64. {
  65. return;
  66. }
  67. if (meshNode.MaxNode.GetBoolProperty("babylonjs_noexport"))
  68. {
  69. return;
  70. }
  71. if (!ExportHiddenObjects && meshNode.MaxNode.IsHidden(NodeHideFlags.None, false))
  72. {
  73. return;
  74. }
  75. var gameMesh = meshNode.IGameObject.AsGameMesh();
  76. bool initialized = gameMesh.InitializeData; //needed, the property is in fact a method initializing the exporter that has wrongly been auto
  77. // translated into a property because it has no parameters
  78. var babylonMesh = new BabylonMesh();
  79. babylonMesh.name = meshNode.Name;
  80. babylonMesh.id = meshNode.MaxNode.GetGuid().ToString();
  81. if (meshNode.NodeParent != null)
  82. {
  83. babylonMesh.parentId = meshNode.NodeParent.MaxNode.GetGuid().ToString();
  84. }
  85. // Misc.
  86. babylonMesh.isVisible = meshNode.MaxNode.Renderable == 1;
  87. babylonMesh.pickable = meshNode.MaxNode.GetBoolProperty("babylonjs_checkpickable");
  88. babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows == 1;
  89. babylonMesh.showBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showboundingbox");
  90. babylonMesh.showSubMeshesBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showsubmeshesboundingbox");
  91. babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics == 1;
  92. babylonMesh.alphaIndex = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_alphaindex", 1000);
  93. // Collisions
  94. babylonMesh.checkCollisions = meshNode.MaxNode.GetBoolProperty("babylonjs_checkcollisions");
  95. bool isSkinned = gameMesh.IsObjectSkinned;
  96. var skin = gameMesh.IGameSkin;
  97. var unskinnedMesh = gameMesh;
  98. IGMatrix skinInitPoseMatrix = Loader.Global.GMatrix.Create(Loader.Global.Matrix3.Create(true));
  99. List<int> boneIds = null;
  100. if (isSkinned)
  101. {
  102. bonesCount = skin.TotalSkinBoneCount;
  103. skins.Add(skin);
  104. skinnedNodes.Add(meshNode);
  105. babylonMesh.skeletonId = skins.IndexOf(skin);
  106. skin.GetInitSkinTM(skinInitPoseMatrix);
  107. boneIds = SortBones(skin);
  108. skinSortedBones[skin] = boneIds;
  109. }
  110. // Position / rotation / scaling
  111. {
  112. var localTM = meshNode.GetObjectTM(0);
  113. var meshTrans = localTM.Translation;
  114. var meshRotation = localTM.Rotation;
  115. var meshScale = localTM.Scaling;
  116. babylonMesh.position = new float[] { meshTrans.X, meshTrans.Y, meshTrans.Z };
  117. babylonMesh.rotationQuaternion = new float[] { meshRotation.X, meshRotation.Y, meshRotation.Z, -meshRotation.W };
  118. babylonMesh.scaling = new float[] { meshScale.X, meshScale.Y, meshScale.Z };
  119. }
  120. // Mesh
  121. RaiseMessage(meshNode.Name, 1);
  122. if (unskinnedMesh != null && unskinnedMesh.IGameType == Autodesk.Max.IGameObject.ObjectTypes.Mesh && unskinnedMesh.MaxMesh != null)
  123. {
  124. if (unskinnedMesh.NumberOfFaces < 1)
  125. {
  126. RaiseError(string.Format("Mesh {0} has no face", babylonMesh.name), 2);
  127. }
  128. if (unskinnedMesh.NumberOfVerts < 3)
  129. {
  130. RaiseError(string.Format("Mesh {0} has not enough vertices", babylonMesh.name), 2);
  131. }
  132. if (unskinnedMesh.NumberOfVerts >= 65536)
  133. {
  134. RaiseWarning(string.Format("Mesh {0} 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.", babylonMesh.name), 2);
  135. }
  136. // Material
  137. var mtl = meshNode.NodeMaterial;
  138. var multiMatsCount = 1;
  139. if (mtl != null)
  140. {
  141. babylonMesh.materialId = mtl.MaxMaterial.GetGuid().ToString();
  142. if (!referencedMaterials.Contains(mtl))
  143. {
  144. referencedMaterials.Add(mtl);
  145. }
  146. multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
  147. }
  148. babylonMesh.visibility = meshNode.MaxNode.GetVisibility(0, Tools.Forever);
  149. var vertices = new List<GlobalVertex>();
  150. var indices = new List<int>();
  151. var mappingChannels = unskinnedMesh.ActiveMapChannelNum;
  152. bool hasUV = false;
  153. bool hasUV2 = false;
  154. for (int i = 0; i < mappingChannels.Count; ++i)
  155. {
  156. IntPtr indexer = new IntPtr(i);
  157. var channelNum = mappingChannels[indexer];
  158. if (channelNum == 1)
  159. {
  160. hasUV = true;
  161. }
  162. else if (channelNum == 2)
  163. {
  164. hasUV2 = true;
  165. }
  166. }
  167. var hasColor = unskinnedMesh.NumberOfColorVerts > 0;
  168. var hasAlpha = unskinnedMesh.GetNumberOfMapVerts(-2) > 0;
  169. var optimizeVertices = meshNode.MaxNode.GetBoolProperty("babylonjs_optimizevertices");
  170. // Compute normals
  171. List<GlobalVertex>[] verticesAlreadyExported = null;
  172. if (optimizeVertices)
  173. {
  174. verticesAlreadyExported = new List<GlobalVertex>[unskinnedMesh.NumberOfVerts];
  175. }
  176. var subMeshes = new List<BabylonSubMesh>();
  177. var indexStart = 0;
  178. for (int i = 0; i < multiMatsCount; ++i)
  179. {
  180. if (meshNode.NodeMaterial == null)
  181. {
  182. continue;
  183. }
  184. int materialId = meshNode.NodeMaterial.GetMaterialID(i);
  185. ITab<IFaceEx> materialFaces = null;
  186. var indexCount = 0;
  187. var minVertexIndex = int.MaxValue;
  188. var maxVertexIndex = int.MinValue;
  189. var subMesh = new BabylonSubMesh();
  190. subMesh.indexStart = indexStart;
  191. subMesh.materialIndex = i;
  192. if (multiMatsCount == 1)
  193. {
  194. for (int j = 0; j < unskinnedMesh.NumberOfFaces; ++j)
  195. {
  196. var face = unskinnedMesh.GetFace(j);
  197. ExtractFace(skin, unskinnedMesh, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face, boneIds);
  198. }
  199. }
  200. else
  201. {
  202. materialFaces = unskinnedMesh.GetFacesFromMatID(materialId);
  203. for (int j = 0; j < materialFaces.Count; ++j)
  204. {
  205. var faceIndexer = new IntPtr(j);
  206. var face = materialFaces[faceIndexer];
  207. Marshal.FreeHGlobal(faceIndexer);
  208. ExtractFace(skin, unskinnedMesh, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face, boneIds);
  209. }
  210. }
  211. if (indexCount != 0)
  212. {
  213. subMesh.indexCount = indexCount;
  214. subMesh.verticesStart = minVertexIndex;
  215. subMesh.verticesCount = maxVertexIndex - minVertexIndex + 1;
  216. indexStart += indexCount;
  217. subMeshes.Add(subMesh);
  218. }
  219. }
  220. if (vertices.Count >= 65536)
  221. {
  222. RaiseWarning(string.Format("Mesh {0} has {1} vertices. This may prevent your scene to work on low end devices where 32 bits indice are not supported", babylonMesh.name, vertices.Count), 2);
  223. if (!optimizeVertices)
  224. {
  225. RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2);
  226. }
  227. }
  228. RaiseMessage(string.Format("{0} vertices, {1} faces", vertices.Count, indices.Count / 3), 2);
  229. // Buffers
  230. babylonMesh.positions = vertices.SelectMany(v => new float[] { v.Position.X, v.Position.Y, v.Position.Z }).ToArray();
  231. babylonMesh.normals = vertices.SelectMany(v => new float[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToArray();
  232. if (hasUV)
  233. {
  234. babylonMesh.uvs = vertices.SelectMany(v => new float[] { v.UV.X, 1 - v.UV.Y }).ToArray();
  235. }
  236. if (hasUV2)
  237. {
  238. babylonMesh.uvs2 = vertices.SelectMany(v => new float[] { v.UV2.X, 1 - v.UV2.Y }).ToArray();
  239. }
  240. if (skin != null)
  241. {
  242. babylonMesh.matricesWeights = vertices.SelectMany(v => v.Weights.ToArray()).ToArray();
  243. babylonMesh.matricesIndices = vertices.Select(v => v.BonesIndices).ToArray();
  244. }
  245. if (hasColor)
  246. {
  247. babylonMesh.colors = vertices.SelectMany(v => v.Color.ToArray()).ToArray();
  248. babylonMesh.hasVertexAlpha = hasAlpha;
  249. }
  250. babylonMesh.subMeshes = subMeshes.ToArray();
  251. // Buffers - Indices
  252. babylonMesh.indices = indices.ToArray();
  253. }
  254. // Instances
  255. var tabs = Loader.Global.NodeTab.Create();
  256. Loader.Global.IInstanceMgr.InstanceMgr.GetInstances(meshNode.MaxNode, tabs);
  257. var instances = new List<BabylonAbstractMesh>();
  258. for (var index = 0; index < tabs.Count; index++)
  259. {
  260. var indexer = new IntPtr(index);
  261. var tab = tabs[indexer];
  262. Marshal.FreeHGlobal(indexer);
  263. if (meshNode.MaxNode.GetGuid() == tab.GetGuid())
  264. {
  265. continue;
  266. }
  267. var instanceGameNode = scene.GetIGameNode(tab);
  268. if (instanceGameNode == null)
  269. {
  270. continue;
  271. }
  272. tab.MarkAsInstance();
  273. var instance = new BabylonAbstractMesh { name = tab.Name };
  274. {
  275. var localTM = meshNode.GetObjectTM(0);
  276. var meshTrans = localTM.Translation;
  277. var meshRotation = localTM.Rotation;
  278. var meshScale = localTM.Scaling;
  279. instance.position = new float[] { meshTrans.X, meshTrans.Y, meshTrans.Z };
  280. float rotx = 0, roty = 0, rotz = 0;
  281. unsafe
  282. {
  283. meshRotation.GetEuler(new IntPtr(&rotx), new IntPtr(&roty), new IntPtr(&rotz));
  284. }
  285. instance.rotation = new float[] { rotx, roty, rotz };
  286. instance.scaling = new float[] { meshScale.X, meshScale.Y, meshScale.Z };
  287. }
  288. var instanceAnimations = new List<BabylonAnimation>();
  289. GenerateCoordinatesAnimations(meshNode, instanceAnimations);
  290. instance.animations = instanceAnimations.ToArray();
  291. instances.Add(instance);
  292. }
  293. babylonMesh.instances = instances.ToArray();
  294. // Animations
  295. var animations = new List<BabylonAnimation>();
  296. GenerateCoordinatesAnimations(meshNode, animations);
  297. if (!ExportFloatController(meshNode.MaxNode.VisController, "visibility", animations))
  298. {
  299. ExportFloatAnimation("visibility", animations, key => new[] { meshNode.MaxNode.GetVisibility(key, Tools.Forever) });
  300. }
  301. babylonMesh.animations = animations.ToArray();
  302. if (meshNode.MaxNode.GetBoolProperty("babylonjs_autoanimate", 1))
  303. {
  304. babylonMesh.autoAnimate = true;
  305. babylonMesh.autoAnimateFrom = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_from");
  306. babylonMesh.autoAnimateTo = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_to", 100);
  307. babylonMesh.autoAnimateLoop = meshNode.MaxNode.GetBoolProperty("babylonjs_autoanimateloop", 1);
  308. }
  309. babylonScene.MeshesList.Add(babylonMesh);
  310. }
  311. 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)
  312. {
  313. var a = CreateGlobalVertex(unskinnedMesh, face, 0, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  314. var b = CreateGlobalVertex(unskinnedMesh, face, 2, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  315. var c = CreateGlobalVertex(unskinnedMesh, face, 1, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin, boneIds);
  316. indices.Add(a);
  317. indices.Add(b);
  318. indices.Add(c);
  319. if (a < minVertexIndex)
  320. {
  321. minVertexIndex = a;
  322. }
  323. if (b < minVertexIndex)
  324. {
  325. minVertexIndex = b;
  326. }
  327. if (c < minVertexIndex)
  328. {
  329. minVertexIndex = c;
  330. }
  331. if (a > maxVertexIndex)
  332. {
  333. maxVertexIndex = a;
  334. }
  335. if (b > maxVertexIndex)
  336. {
  337. maxVertexIndex = b;
  338. }
  339. if (c > maxVertexIndex)
  340. {
  341. maxVertexIndex = c;
  342. }
  343. indexCount += 3;
  344. CheckCancelled();
  345. }
  346. public static void GenerateCoordinatesAnimations(IIGameNode meshNode, List<BabylonAnimation> animations)
  347. {
  348. ExportVector3Animation("position", animations, key =>
  349. {
  350. var worldMatrix = meshNode.GetObjectTM(key);
  351. var trans = worldMatrix.Translation;
  352. return new float[] { trans.X, trans.Y, trans.Z };
  353. });
  354. ExportQuaternionAnimation("rotationQuaternion", animations, key =>
  355. {
  356. var worldMatrix = meshNode.GetObjectTM(key);
  357. var rot = worldMatrix.Rotation;
  358. return new float[] { rot.X, rot.Y, rot.Z, -rot.W };
  359. });
  360. ExportVector3Animation("scaling", animations, key =>
  361. {
  362. var worldMatrix = meshNode.GetObjectTM(key);
  363. var scale = worldMatrix.Scaling;
  364. return new float[] { scale.X, scale.Y, scale.Z };
  365. });
  366. }
  367. 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)
  368. {
  369. var vertexIndex = (int)face.Vert[facePart];
  370. var vertex = new GlobalVertex
  371. {
  372. BaseIndex = vertexIndex,
  373. Position = mesh.GetVertex(vertexIndex, true),
  374. Normal = mesh.GetNormal((int)face.Norm[facePart], true)
  375. };
  376. if (hasUV)
  377. {
  378. int[] indices = new int[3];
  379. unsafe
  380. {
  381. fixed (int* indicesPtr = indices)
  382. {
  383. mesh.GetMapFaceIndex(1, face.MeshFaceIndex, new IntPtr(indicesPtr));
  384. }
  385. }
  386. var texCoord = mesh.GetMapVertex(1, indices[facePart]);
  387. vertex.UV = Loader.Global.Point2.Create(texCoord.X, -texCoord.Y);
  388. }
  389. if (hasUV2)
  390. {
  391. int[] indices = new int[3];
  392. unsafe
  393. {
  394. fixed (int* indicesPtr = indices)
  395. {
  396. mesh.GetMapFaceIndex(2, face.MeshFaceIndex, new IntPtr(indicesPtr));
  397. }
  398. }
  399. var texCoord = mesh.GetMapVertex(2, indices[facePart]);
  400. vertex.UV2 = Loader.Global.Point2.Create(texCoord.X, -texCoord.Y);
  401. }
  402. if (hasColor)
  403. {
  404. var vertexColorIndex = (int)face.Color[facePart];
  405. var vertexColor = mesh.GetColorVertex(vertexColorIndex);
  406. float alpha = 1;
  407. if (hasAlpha)
  408. {
  409. IPoint3 p = Loader.Global.Point3.Create();
  410. mesh.GetMapFaceIndex(-2, face.MeshFaceIndex, p.GetNativeHandle());
  411. alpha = p.X;
  412. }
  413. vertex.Color = new float[] { vertexColor.X, vertexColor.Y, vertexColor.Z, alpha };
  414. }
  415. if (skin != null)
  416. {
  417. float weight0 = 0;
  418. float weight1 = 0;
  419. float weight2 = 0;
  420. int bone0 = bonesCount;
  421. int bone1 = bonesCount;
  422. int bone2 = bonesCount;
  423. int bone3 = bonesCount;
  424. int nbBones = skin.GetNumberOfBones(vertexIndex);
  425. if (nbBones > 0)
  426. {
  427. bone0 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 0).NodeID);
  428. weight0 = skin.GetWeight(vertexIndex, 0);
  429. }
  430. if (nbBones > 1)
  431. {
  432. bone1 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 1).NodeID);
  433. weight1 = skin.GetWeight(vertexIndex, 1);
  434. }
  435. if (nbBones > 2)
  436. {
  437. bone2 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 2).NodeID);
  438. weight2 = skin.GetWeight(vertexIndex, 2);
  439. }
  440. if (nbBones > 3)
  441. {
  442. bone3 = boneIds.IndexOf(skin.GetIGameBone(vertexIndex, 3).NodeID);
  443. }
  444. if (nbBones == 0)
  445. {
  446. weight0 = 1.0f;
  447. bone0 = bonesCount;
  448. }
  449. if (nbBones > 4)
  450. {
  451. RaiseError("Too many bones influences per vertex: " + nbBones + ". Babylon.js only support 4 bones influences per vertex.", 2);
  452. }
  453. vertex.Weights = Loader.Global.Point4.Create(weight0, weight1, weight2, 1.0 - weight0 - weight1 - weight2);
  454. vertex.BonesIndices = (bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0;
  455. }
  456. if (verticesAlreadyExported != null)
  457. {
  458. if (verticesAlreadyExported[vertexIndex] != null)
  459. {
  460. var index = verticesAlreadyExported[vertexIndex].IndexOf(vertex);
  461. if (index > -1)
  462. {
  463. return verticesAlreadyExported[vertexIndex][index].CurrentIndex;
  464. }
  465. }
  466. else
  467. {
  468. verticesAlreadyExported[vertexIndex] = new List<GlobalVertex>();
  469. }
  470. vertex.CurrentIndex = vertices.Count;
  471. verticesAlreadyExported[vertexIndex].Add(vertex);
  472. }
  473. vertices.Add(vertex);
  474. return vertices.Count - 1;
  475. }
  476. }
  477. }