BabylonExporter.Mesh.cs 21 KB

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