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. private int bonesCount;
  12. private void ExportMesh(IIGameScene scene, IIGameNode meshNode, BabylonScene babylonScene)
  13. {
  14. if (meshNode.MaxNode.IsInstance())
  15. {
  16. return;
  17. }
  18. if (meshNode.MaxNode.GetBoolProperty("babylonjs_noexport"))
  19. {
  20. return;
  21. }
  22. if (!ExportHiddenObjects && meshNode.MaxNode.IsHidden(NodeHideFlags.None, false))
  23. {
  24. return;
  25. }
  26. var gameMesh = meshNode.IGameObject.AsGameMesh();
  27. bool initialized = gameMesh.InitializeData;
  28. var babylonMesh = new BabylonMesh();
  29. babylonMesh.name = meshNode.Name;
  30. babylonMesh.id = meshNode.MaxNode.GetGuid().ToString();
  31. if (meshNode.NodeParent != null)
  32. {
  33. babylonMesh.parentId = meshNode.NodeParent.MaxNode.GetGuid().ToString();
  34. }
  35. // Misc.
  36. babylonMesh.isVisible = meshNode.MaxNode.Renderable == 1;
  37. babylonMesh.pickable = meshNode.MaxNode.GetBoolProperty("babylonjs_checkpickable");
  38. babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows == 1;
  39. babylonMesh.showBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showboundingbox");
  40. babylonMesh.showSubMeshesBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showsubmeshesboundingbox");
  41. // Collisions
  42. babylonMesh.checkCollisions = meshNode.MaxNode.GetBoolProperty("babylonjs_checkcollisions");
  43. bool isSkinned = gameMesh.IsObjectSkinned;
  44. var skin = gameMesh.IGameSkin;
  45. var unskinnedMesh = gameMesh;
  46. if (isSkinned)
  47. {
  48. unskinnedMesh = skin.InitialPose;
  49. bonesCount = skin.TotalSkinBoneCount;
  50. skins.Add(skin);
  51. babylonMesh.skeletonId = skins.IndexOf(skin);
  52. }
  53. // Position / rotation / scaling
  54. {
  55. var localTM = meshNode.GetLocalTM(0);
  56. //var worldTM = meshNode.GetWorldTM(0);
  57. //var objTM = meshNode.GetObjectTM(0);
  58. var meshTrans = localTM.Translation;
  59. var meshRotation = localTM.Rotation;
  60. var meshScale = localTM.Scaling;
  61. babylonMesh.position = new float[] { meshTrans.X, meshTrans.Y, meshTrans.Z };
  62. float rotx = 0, roty = 0, rotz = 0;
  63. unsafe
  64. {
  65. meshRotation.GetEuler(new IntPtr(&rotx), new IntPtr(&roty), new IntPtr(&rotz));
  66. }
  67. babylonMesh.rotation = new float[] { rotx, roty, rotz };
  68. //babylonMesh.rotationQuaternion = new float[] { meshRotation.X, meshRotation.Y, meshRotation.Z, meshRotation.W };
  69. babylonMesh.scaling = new float[] { meshScale.X, meshScale.Y, meshScale.Z };
  70. }
  71. //// Pivot // something to do with GameMesh ?
  72. //meshNode.GetObjectTM
  73. //var pivotMatrix = Tools.Identity;
  74. //pivotMatrix.PreTranslate(meshNode.ObjOffsetPos);
  75. //Loader.Global.PreRotateMatrix(pivotMatrix, meshNode.ObjOffsetRot);
  76. //Loader.Global.ApplyScaling(pivotMatrix, meshNode.ObjOffsetScale);
  77. //babylonMesh.pivotMatrix = pivotMatrix.ToArray();
  78. // Mesh
  79. RaiseMessage(meshNode.Name, 1);
  80. if (unskinnedMesh != null && unskinnedMesh.IGameType == Autodesk.Max.IGameObject.ObjectTypes.Mesh && unskinnedMesh.MaxMesh != null)
  81. {
  82. if (unskinnedMesh.NumberOfFaces < 1)
  83. {
  84. RaiseError(string.Format("Mesh {0} has no face", babylonMesh.name), 2);
  85. }
  86. if (unskinnedMesh.NumberOfVerts < 3)
  87. {
  88. RaiseError(string.Format("Mesh {0} has not enough vertices", babylonMesh.name), 2);
  89. }
  90. if (unskinnedMesh.NumberOfVerts >= 65536)
  91. {
  92. 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);
  93. }
  94. // Material
  95. var mtl = meshNode.NodeMaterial;
  96. var multiMatsCount = 1;
  97. if (mtl != null)
  98. {
  99. babylonMesh.materialId = mtl.MaxMaterial.GetGuid().ToString();
  100. if (!referencedMaterials.Contains(mtl))
  101. {
  102. referencedMaterials.Add(mtl);
  103. }
  104. multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
  105. }
  106. babylonMesh.visibility = meshNode.MaxNode.GetVisibility(0, Tools.Forever);
  107. var vertices = new List<GlobalVertex>();
  108. var indices = new List<int>();
  109. var hasUV = unskinnedMesh.NumberOfTexVerts > 0;
  110. var hasUV2 = unskinnedMesh.GetNumberOfMapVerts(2) > 0;
  111. var hasColor = unskinnedMesh.NumberOfColorVerts > 0;
  112. var hasAlpha = unskinnedMesh.GetNumberOfMapVerts(-2) > 0;
  113. var optimizeVertices = meshNode.MaxNode.GetBoolProperty("babylonjs_optimizevertices");
  114. // Compute normals
  115. // VNormal[] vnorms = Tools.ComputeNormals(mesh, optimizeVertices);
  116. List<GlobalVertex>[] verticesAlreadyExported = null;
  117. if (optimizeVertices)
  118. {
  119. verticesAlreadyExported = new List<GlobalVertex>[unskinnedMesh.NumberOfVerts];
  120. }
  121. var subMeshes = new List<BabylonSubMesh>();
  122. var indexStart = 0;
  123. List<Guid> orderedSubMeshes = new List<Guid>();
  124. for(int i=0;i< meshNode.NodeMaterial.SubMaterialCount; ++i)
  125. {
  126. orderedSubMeshes.Add(meshNode.NodeMaterial.GetSubMaterial(i).MaxMaterial.GetGuid());
  127. }
  128. var materialIds = unskinnedMesh.ActiveMatIDs;
  129. for(int i=0; i< materialIds.Count; ++i)
  130. {
  131. var materialIndexer = new IntPtr(i);
  132. int materialId = materialIds[materialIndexer];
  133. Marshal.FreeHGlobal(materialIndexer);
  134. var materialFaces = unskinnedMesh.GetFacesFromMatID(materialId);
  135. var indexCount = 0;
  136. var minVertexIndex = int.MaxValue;
  137. var maxVertexIndex = int.MinValue;
  138. var subMesh = new BabylonSubMesh();
  139. subMesh.indexStart = indexStart;
  140. subMesh.materialIndex = materialId;
  141. for (int j= 0; j<materialFaces.Count; ++j)
  142. {
  143. var faceIndexer = new IntPtr(j);
  144. var face = materialFaces[faceIndexer];
  145. Marshal.FreeHGlobal(faceIndexer);
  146. var a = CreateGlobalVertex(unskinnedMesh, face, 0, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin);
  147. var b = CreateGlobalVertex(unskinnedMesh, face, 2, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin);
  148. var c = CreateGlobalVertex(unskinnedMesh, face, 1, vertices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, skin);
  149. indices.Add(a);
  150. indices.Add(b);
  151. indices.Add(c);
  152. if (a < minVertexIndex)
  153. {
  154. minVertexIndex = a;
  155. }
  156. if (b < minVertexIndex)
  157. {
  158. minVertexIndex = b;
  159. }
  160. if (c < minVertexIndex)
  161. {
  162. minVertexIndex = c;
  163. }
  164. if (a > maxVertexIndex)
  165. {
  166. maxVertexIndex = a;
  167. }
  168. if (b > maxVertexIndex)
  169. {
  170. maxVertexIndex = b;
  171. }
  172. if (c > maxVertexIndex)
  173. {
  174. maxVertexIndex = c;
  175. }
  176. indexCount += 3;
  177. CheckCancelled();
  178. }
  179. if (indexCount != 0)
  180. {
  181. subMesh.indexCount = indexCount;
  182. subMesh.verticesStart = minVertexIndex;
  183. subMesh.verticesCount = maxVertexIndex - minVertexIndex + 1;
  184. indexStart += indexCount;
  185. subMeshes.Add(subMesh);
  186. }
  187. }
  188. if (vertices.Count >= 65536)
  189. {
  190. RaiseError(string.Format("Mesh {0} has too many vertices: {1} (limit is 65535)", babylonMesh.name, vertices.Count), 2);
  191. if (!optimizeVertices)
  192. {
  193. RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2);
  194. }
  195. }
  196. RaiseMessage(string.Format("{0} vertices, {1} faces", vertices.Count, indices.Count / 3), 2);
  197. // Buffers
  198. babylonMesh.positions = vertices.SelectMany(v => new float[] { v.Position.X, v.Position.Y, v.Position.Z }).ToArray();
  199. babylonMesh.normals = vertices.SelectMany(v => new float[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToArray();
  200. if (hasUV)
  201. {
  202. babylonMesh.uvs = vertices.SelectMany(v => new float[] { v.UV.X, 1-v.UV.Y }).ToArray();
  203. }
  204. if (hasUV2)
  205. {
  206. babylonMesh.uvs2 = vertices.SelectMany(v => new float[] { v.UV2.X, 1-v.UV2.Y }).ToArray();
  207. }
  208. if (skin != null)
  209. {
  210. babylonMesh.matricesWeights = vertices.SelectMany(v => v.Weights.ToArray()).ToArray();
  211. babylonMesh.matricesIndices = vertices.Select(v => v.BonesIndices).ToArray();
  212. }
  213. if (hasColor)
  214. {
  215. babylonMesh.colors = vertices.SelectMany(v => v.Color.ToArray()).ToArray();
  216. babylonMesh.hasVertexAlpha = hasAlpha;
  217. }
  218. babylonMesh.subMeshes = subMeshes.ToArray();
  219. // Buffers - Indices
  220. babylonMesh.indices = indices.ToArray();
  221. }
  222. // handle instances and animations
  223. // Instances
  224. var tabs = Loader.Global.NodeTab.Create();
  225. Loader.Global.IInstanceMgr.InstanceMgr.GetInstances(meshNode.MaxNode, tabs);
  226. var instances = new List<BabylonAbstractMesh>();
  227. for (var index = 0; index < tabs.Count; index++)
  228. {
  229. var indexer = new IntPtr(index);
  230. var tab = tabs[indexer];
  231. Marshal.FreeHGlobal(indexer);
  232. if (meshNode.MaxNode.GetGuid() == tab.GetGuid())
  233. {
  234. continue;
  235. }
  236. var instanceGameNode = scene.GetIGameNode(tab);
  237. if(instanceGameNode == null)
  238. {
  239. continue;
  240. }
  241. tab.MarkAsInstance();
  242. var instance = new BabylonAbstractMesh { name = tab.Name };
  243. {
  244. var localTM = instanceGameNode.GetLocalTM(0);
  245. //var worldTM = meshNode.GetWorldTM(0);
  246. //var objTM = meshNode.GetObjectTM(0);
  247. var meshTrans = localTM.Translation;
  248. var meshRotation = localTM.Rotation;
  249. var meshScale = localTM.Scaling;
  250. instance.position = new float[] { meshTrans.X, meshTrans.Y, meshTrans.Z };
  251. float rotx = 0, roty = 0, rotz = 0;
  252. unsafe
  253. {
  254. meshRotation.GetEuler(new IntPtr(&rotx), new IntPtr(&roty), new IntPtr(&rotz));
  255. }
  256. instance.rotation = new float[] { rotx, roty, rotz };
  257. instance.scaling = new float[] { meshScale.X, meshScale.Y, meshScale.Z };
  258. }
  259. //var instanceAnimations = new List<BabylonAnimation>();
  260. //GenerateCoordinatesAnimations(tab, instanceAnimations);
  261. //instance.animations = instanceAnimations.ToArray();
  262. instances.Add(instance);
  263. }
  264. babylonMesh.instances = instances.ToArray();
  265. // Animations
  266. //var animations = new List<BabylonAnimation>();
  267. //GenerateCoordinatesAnimations(meshNode, animations);
  268. //if (!ExportFloatController(meshNode.VisController, "visibility", animations))
  269. //{
  270. // ExportFloatAnimation("visibility", animations, key => new[] { meshNode.GetVisibility(key, Tools.Forever) });
  271. //}
  272. //babylonMesh.animations = animations.ToArray();
  273. if (meshNode.MaxNode.GetBoolProperty("babylonjs_autoanimate", 1))
  274. {
  275. babylonMesh.autoAnimate = true;
  276. babylonMesh.autoAnimateFrom = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_from");
  277. babylonMesh.autoAnimateTo = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_autoanimate_to", 100);
  278. babylonMesh.autoAnimateLoop = meshNode.MaxNode.GetBoolProperty("babylonjs_autoanimateloop", 1);
  279. }
  280. babylonScene.MeshesList.Add(babylonMesh);
  281. }
  282. //public static void GenerateCoordinatesAnimations(IIGameNode meshNode, List<BabylonAnimation> animations)
  283. //{
  284. // var control = meshNode.IGameControl;
  285. // if (control.IsAnimated(IGameControlType.Tm))
  286. // {
  287. // // combined tm anim
  288. // ExportTMAnimation(control, animations);
  289. // }
  290. // else
  291. // {
  292. // if (control.IsAnimated(IGameControlType.Pos))
  293. // {
  294. // ExportPosAnimation(control, animations);
  295. // }
  296. // }
  297. // //if (!ExportVector3Controller(meshNode.TMController.PositionController, "position", animations))
  298. // //{
  299. // // ExportVector3Animation("position", animations, key =>
  300. // // {
  301. // // var worldMatrix = meshNode.GetWorldMatrix(key, meshNode.HasParent());
  302. // // return worldMatrix.Trans.ToArraySwitched();
  303. // // });
  304. // //}
  305. // //if (!ExportQuaternionController(meshNode.TMController.RotationController, "rotationQuaternion", animations))
  306. // //{
  307. // // ExportQuaternionAnimation("rotationQuaternion", animations, key =>
  308. // // {
  309. // // var worldMatrix = meshNode.GetWorldMatrix(key, meshNode.HasParent());
  310. // // var affineParts = Loader.Global.AffineParts.Create();
  311. // // Loader.Global.DecompAffine(worldMatrix, affineParts);
  312. // // return affineParts.Q.ToArray();
  313. // // });
  314. // //}
  315. // //if (!ExportVector3Controller(meshNode.TMController.ScaleController, "scaling", animations))
  316. // //{
  317. // // ExportVector3Animation("scaling", animations, key =>
  318. // // {
  319. // // var worldMatrix = meshNode.GetWorldMatrix(key, meshNode.HasParent());
  320. // // var affineParts = Loader.Global.AffineParts.Create();
  321. // // Loader.Global.DecompAffine(worldMatrix, affineParts);
  322. // // return affineParts.K.ToArraySwitched();
  323. // // });
  324. // //}
  325. //}
  326. //private static void ExportPosAnimation(IIGameControl control, List<BabylonAnimation> animations)
  327. //{
  328. // ITab<IIGameKey> keys = Loader.Global.Tab.Create<IIGameKey>();
  329. // if(control.GetLinearKeys(keys, IGameControlType.Pos))
  330. // {
  331. // if(keys.Count != 0)
  332. // {
  333. // // todo
  334. // return;
  335. // }
  336. // }
  337. // // full sampling
  338. // if(control.GetFullSampledKeys(keys, Loader.Global.FrameRate, IGameControlType.Pos, false))
  339. // {
  340. // if(keys.Count != 0)
  341. // {
  342. // List<BabylonAnimationKey> babKeys = new List<BabylonAnimationKey>();
  343. // for(int i = 0; i < keys.Count; ++i)
  344. // {
  345. // var keyIndexer = new IntPtr(i);
  346. // var key = keys[keyIndexer];
  347. // babKeys.Add(new BabylonAnimationKey {
  348. // frame = key.T /Ticks,
  349. // values = new float[] { key.SampleKey.Pval.X, key.SampleKey.Pval.Y, key.SampleKey.Pval.Z }
  350. // });
  351. // }
  352. // var babylonAnimation = new BabylonAnimation
  353. // {
  354. // dataType = BabylonAnimation.DataType.Vector3,
  355. // name = "position animation",
  356. // keys = babKeys.ToArray(),
  357. // framePerSecond = Loader.Global.FrameRate,
  358. // loopBehavior = BabylonAnimation.LoopBehavior.Cycle,
  359. // property = "position",
  360. // };
  361. // animations.Add(babylonAnimation);
  362. // }
  363. // }
  364. //}
  365. //private static void ExportTMAnimation(IIGameControl control, List<BabylonAnimation> animations)
  366. //{
  367. //}
  368. int CreateGlobalVertex(IIGameMesh mesh, IFaceEx face, int facePart, List<GlobalVertex> vertices, bool hasUV, bool hasUV2, bool hasColor, bool hasAlpha, List<GlobalVertex>[] verticesAlreadyExported, IIGameSkin skin)
  369. {
  370. var vertexIndex = (int)face.Vert[facePart];
  371. var vertex = new GlobalVertex
  372. {
  373. BaseIndex = vertexIndex,
  374. Position = mesh.GetVertex(vertexIndex, true),
  375. Normal = mesh.GetNormal((int)face.Norm[facePart], true) //vnorms[vertexIndex].GetNormal(verticesAlreadyExported != null ? 1 : faceObject.SmGroup)
  376. };
  377. if (hasUV)
  378. {
  379. var tvertexIndex = (int)face.TexCoord[facePart];
  380. vertex.UV = mesh.GetTexVertex(tvertexIndex);
  381. }
  382. if (hasUV2)
  383. {
  384. IPoint3 p = Loader.Global.Point3.Create();
  385. var tvertexIndex = mesh.GetMapFaceIndex(2, face.MeshFaceIndex, p.GetNativeHandle());
  386. vertex.UV2 = Loader.Global.Point2.Create(p.X, p.Y);
  387. }
  388. if (hasColor)
  389. {
  390. var vertexColorIndex = (int)face.Color[facePart];
  391. var vertexColor = mesh.GetColorVertex(vertexColorIndex);
  392. float alpha = 1;
  393. if (hasAlpha)
  394. {
  395. IPoint3 p = Loader.Global.Point3.Create();
  396. mesh.GetMapFaceIndex(-2, face.MeshFaceIndex, p.GetNativeHandle());
  397. alpha = p.X;
  398. }
  399. vertex.Color = new float[] { vertexColor.X, vertexColor.Y, vertexColor.Z, alpha};
  400. }
  401. if (skin != null)
  402. {
  403. float weight0 = 0;
  404. float weight1 = 0;
  405. float weight2 = 0;
  406. int bone0 = bonesCount;
  407. int bone1 = bonesCount;
  408. int bone2 = bonesCount;
  409. int bone3 = bonesCount;
  410. int nbBones = skin.GetNumberOfBones(vertexIndex);
  411. if (nbBones > 0)
  412. {
  413. bone0 = skin.GetBoneIndex(skin.GetBone(vertexIndex, 0),false);
  414. weight0 = skin.GetWeight(vertexIndex, 0);
  415. }
  416. if (nbBones > 1)
  417. {
  418. bone1 = skin.GetBoneIndex(skin.GetBone(vertexIndex, 1), false);
  419. weight1 = skin.GetWeight(vertexIndex, 1);
  420. }
  421. if (nbBones > 2)
  422. {
  423. bone2 = skin.GetBoneIndex(skin.GetBone(vertexIndex, 2), false);
  424. weight2 = skin.GetWeight(vertexIndex, 2);
  425. }
  426. if (nbBones > 3)
  427. {
  428. bone3 = skin.GetBoneIndex(skin.GetBone(vertexIndex, 3), false);
  429. }
  430. if (nbBones == 0)
  431. {
  432. weight0 = 1.0f;
  433. bone0 = bonesCount;
  434. }
  435. if (nbBones > 4)
  436. {
  437. RaiseError("Too many bones influences per vertex: " + nbBones + ". Babylon.js only support 4 bones influences per vertex.", 2);
  438. }
  439. vertex.Weights = Loader.Global.Point4.Create(weight0, weight1, weight2, 1.0 - weight0 - weight1 - weight2);
  440. vertex.BonesIndices = (bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0;
  441. }
  442. if (verticesAlreadyExported != null)
  443. {
  444. if (verticesAlreadyExported[vertexIndex] != null)
  445. {
  446. var index = verticesAlreadyExported[vertexIndex].IndexOf(vertex);
  447. if (index > -1)
  448. {
  449. return verticesAlreadyExported[vertexIndex][index].CurrentIndex;
  450. }
  451. }
  452. else
  453. {
  454. verticesAlreadyExported[vertexIndex] = new List<GlobalVertex>();
  455. }
  456. vertex.CurrentIndex = vertices.Count;
  457. verticesAlreadyExported[vertexIndex].Add(vertex);
  458. }
  459. vertices.Add(vertex);
  460. return vertices.Count - 1;
  461. }
  462. }
  463. }