BabylonExporter.Mesh.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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(IINode meshNode, BabylonScene babylonScene)
  13. {
  14. if (meshNode.IsInstance())
  15. {
  16. return;
  17. }
  18. if (meshNode.GetBoolProperty("babylonjs_noexport"))
  19. {
  20. return;
  21. }
  22. if (!ExportHiddenObjects && meshNode.IsHidden(NodeHideFlags.None, false))
  23. {
  24. return;
  25. }
  26. var babylonMesh = new BabylonMesh();
  27. int vx1, vx2, vx3;
  28. babylonMesh.name = meshNode.Name;
  29. babylonMesh.id = meshNode.GetGuid().ToString();
  30. if (meshNode.HasParent())
  31. {
  32. babylonMesh.parentId = meshNode.ParentNode.GetGuid().ToString();
  33. }
  34. // Misc.
  35. babylonMesh.isVisible = meshNode.Renderable == 1;
  36. babylonMesh.pickable = meshNode.GetBoolProperty("babylonjs_checkpickable");
  37. babylonMesh.receiveShadows = meshNode.RcvShadows == 1;
  38. babylonMesh.showBoundingBox = meshNode.GetBoolProperty("babylonjs_showboundingbox");
  39. babylonMesh.showSubMeshesBoundingBox = meshNode.GetBoolProperty("babylonjs_showsubmeshesboundingbox");
  40. // Collisions
  41. babylonMesh.checkCollisions = meshNode.GetBoolProperty("babylonjs_checkcollisions");
  42. // Skin
  43. var skin = GetSkinModifier(meshNode);
  44. if (skin != null)
  45. {
  46. babylonMesh.skeletonId = skins.IndexOf(skin);
  47. bonesCount = skin.NumBones;
  48. }
  49. // Position / rotation / scaling
  50. var wm = Tools.ExtractCoordinates(meshNode, babylonMesh, exportQuaternionsInsteadOfEulers);
  51. if (wm.Parity)
  52. {
  53. vx1 = 2;
  54. vx2 = 1;
  55. vx3 = 0;
  56. }
  57. else
  58. {
  59. vx1 = 0;
  60. vx2 = 1;
  61. vx3 = 2;
  62. }
  63. // Pivot
  64. var pivotMatrix = Tools.Identity;
  65. pivotMatrix.PreTranslate(meshNode.ObjOffsetPos);
  66. Loader.Global.PreRotateMatrix(pivotMatrix, meshNode.ObjOffsetRot);
  67. Loader.Global.ApplyScaling(pivotMatrix, meshNode.ObjOffsetScale);
  68. babylonMesh.pivotMatrix = pivotMatrix.ToArray();
  69. // Mesh
  70. var objectState = meshNode.EvalWorldState(0, false);
  71. var triObject = objectState.Obj.GetMesh();
  72. var mesh = triObject != null ? triObject.Mesh : null;
  73. RaiseMessage(meshNode.Name, 1);
  74. if (mesh != null)
  75. {
  76. mesh.BuildNormals();
  77. if (mesh.NumFaces < 1)
  78. {
  79. RaiseError(string.Format("Mesh {0} has no face", babylonMesh.name), 2);
  80. }
  81. if (mesh.NumVerts < 3)
  82. {
  83. RaiseError(string.Format("Mesh {0} has not enough vertices", babylonMesh.name), 2);
  84. }
  85. if (mesh.NumVerts >= 65536)
  86. {
  87. RaiseError(string.Format("Mesh {0} has too many vertices (more than 65535)", babylonMesh.name), 2);
  88. }
  89. // Material
  90. var mtl = meshNode.Mtl;
  91. var multiMatsCount = 1;
  92. if (mtl != null)
  93. {
  94. babylonMesh.materialId = mtl.GetGuid().ToString();
  95. if (!referencedMaterials.Contains(mtl))
  96. {
  97. referencedMaterials.Add(mtl);
  98. }
  99. multiMatsCount = Math.Max(mtl.NumSubMtls, 1);
  100. }
  101. babylonMesh.visibility = meshNode.GetVisibility(0, Tools.Forever);
  102. var vertices = new List<GlobalVertex>();
  103. var indices = new List<int>();
  104. var matIDs = new List<int>();
  105. var hasUV = mesh.NumTVerts > 0;
  106. var hasUV2 = mesh.GetNumMapVerts(2) > 0;
  107. var optimizeVertices = meshNode.GetBoolProperty("babylonjs_optimizevertices");
  108. // Skin
  109. IISkinContextData skinContext = null;
  110. if (skin != null)
  111. {
  112. skinContext = skin.GetContextInterface(meshNode);
  113. }
  114. // Compute normals
  115. VNormal[] vnorms = Tools.ComputeNormals(mesh, optimizeVertices);
  116. List<GlobalVertex>[] verticesAlreadyExported = null;
  117. if (optimizeVertices)
  118. {
  119. verticesAlreadyExported = new List<GlobalVertex>[mesh.NumVerts];
  120. }
  121. for (var face = 0; face < mesh.NumFaces; face++)
  122. {
  123. indices.Add(CreateGlobalVertex(mesh, face, vx1, vertices, hasUV, hasUV2, vnorms, verticesAlreadyExported, skinContext));
  124. indices.Add(CreateGlobalVertex(mesh, face, vx2, vertices, hasUV, hasUV2, vnorms, verticesAlreadyExported, skinContext));
  125. indices.Add(CreateGlobalVertex(mesh, face, vx3, vertices, hasUV, hasUV2, vnorms, verticesAlreadyExported, skinContext));
  126. matIDs.Add(mesh.Faces[face].MatID % multiMatsCount);
  127. CheckCancelled();
  128. }
  129. if (vertices.Count >= 65536)
  130. {
  131. RaiseError(string.Format("Mesh {0} has too many vertices: {1} (limit is 65535)", babylonMesh.name, vertices.Count), 2);
  132. if (!optimizeVertices)
  133. {
  134. RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2);
  135. }
  136. }
  137. RaiseMessage(string.Format("{0} vertices, {1} faces", vertices.Count, indices.Count / 3), 2);
  138. // Buffers
  139. babylonMesh.positions = vertices.SelectMany(v => v.Position.ToArraySwitched()).ToArray();
  140. babylonMesh.normals = vertices.SelectMany(v => v.Normal.ToArraySwitched()).ToArray();
  141. if (hasUV)
  142. {
  143. babylonMesh.uvs = vertices.SelectMany(v => v.UV.ToArray()).ToArray();
  144. }
  145. if (hasUV2)
  146. {
  147. babylonMesh.uvs2 = vertices.SelectMany(v => v.UV2.ToArray()).ToArray();
  148. }
  149. if (skin != null)
  150. {
  151. babylonMesh.matricesWeights = vertices.SelectMany(v => v.Weights.ToArray()).ToArray();
  152. babylonMesh.matricesIndices = vertices.Select(v => v.BonesIndices).ToArray();
  153. }
  154. // Submeshes
  155. var sortedIndices = new List<int>();
  156. var subMeshes = new List<BabylonSubMesh>();
  157. var indexStart = 0;
  158. for (var index = 0; index < multiMatsCount; index++)
  159. {
  160. var subMesh = new BabylonSubMesh();
  161. var indexCount = 0;
  162. var minVertexIndex = int.MaxValue;
  163. var maxVertexIndex = int.MinValue;
  164. subMesh.indexStart = indexStart;
  165. subMesh.materialIndex = index;
  166. for (var face = 0; face < matIDs.Count; face++)
  167. {
  168. if (matIDs[face] == index)
  169. {
  170. var a = indices[3 * face];
  171. var b = indices[3 * face + 1];
  172. var c = indices[3 * face + 2];
  173. sortedIndices.Add(a);
  174. sortedIndices.Add(b);
  175. sortedIndices.Add(c);
  176. indexCount += 3;
  177. if (a < minVertexIndex)
  178. {
  179. minVertexIndex = a;
  180. }
  181. if (b < minVertexIndex)
  182. {
  183. minVertexIndex = b;
  184. }
  185. if (c < minVertexIndex)
  186. {
  187. minVertexIndex = c;
  188. }
  189. if (a > maxVertexIndex)
  190. {
  191. maxVertexIndex = a;
  192. }
  193. if (b > maxVertexIndex)
  194. {
  195. maxVertexIndex = b;
  196. }
  197. if (c > maxVertexIndex)
  198. {
  199. maxVertexIndex = c;
  200. }
  201. }
  202. }
  203. if (indexCount != 0)
  204. {
  205. subMesh.indexCount = indexCount;
  206. subMesh.verticesStart = minVertexIndex;
  207. subMesh.verticesCount = maxVertexIndex - minVertexIndex + 1;
  208. indexStart += indexCount;
  209. subMeshes.Add(subMesh);
  210. }
  211. CheckCancelled();
  212. }
  213. babylonMesh.subMeshes = subMeshes.ToArray();
  214. // Buffers - Indices
  215. babylonMesh.indices = sortedIndices.ToArray();
  216. triObject.Dispose();
  217. }
  218. // Instances
  219. var tabs = Loader.Global.NodeTab.Create();
  220. Loader.Global.IInstanceMgr.InstanceMgr.GetInstances(meshNode, tabs);
  221. var instances = new List<BabylonAbstractMesh>();
  222. for (var index = 0; index < tabs.Count; index++)
  223. {
  224. var indexer = new IntPtr(index);
  225. var tab = tabs[indexer];
  226. Marshal.FreeHGlobal(indexer);
  227. if (meshNode.GetGuid() == tab.GetGuid())
  228. {
  229. continue;
  230. }
  231. tab.MarkAsInstance();
  232. var instance = new BabylonAbstractMesh {name = tab.Name};
  233. Tools.ExtractCoordinates(tab, instance, exportQuaternionsInsteadOfEulers);
  234. var instanceAnimations = new List<BabylonAnimation>();
  235. GenerateCoordinatesAnimations(tab, instanceAnimations);
  236. instance.animations = instanceAnimations.ToArray();
  237. instances.Add(instance);
  238. }
  239. babylonMesh.instances = instances.ToArray();
  240. // Animations
  241. var animations = new List<BabylonAnimation>();
  242. GenerateCoordinatesAnimations(meshNode, animations);
  243. if (!ExportFloatController(meshNode.VisController, "visibility", animations))
  244. {
  245. ExportFloatAnimation("visibility", animations, key => new[] { meshNode.GetVisibility(key, Tools.Forever) });
  246. }
  247. babylonMesh.animations = animations.ToArray();
  248. if (meshNode.GetBoolProperty("babylonjs_autoanimate", 1))
  249. {
  250. babylonMesh.autoAnimate = true;
  251. babylonMesh.autoAnimateFrom = (int)meshNode.GetFloatProperty("babylonjs_autoanimate_from");
  252. babylonMesh.autoAnimateTo = (int)meshNode.GetFloatProperty("babylonjs_autoanimate_to", 100);
  253. babylonMesh.autoAnimateLoop = meshNode.GetBoolProperty("babylonjs_autoanimateloop", 1);
  254. }
  255. babylonScene.MeshesList.Add(babylonMesh);
  256. }
  257. public static void GenerateCoordinatesAnimations(IINode meshNode, List<BabylonAnimation> animations)
  258. {
  259. if (!ExportVector3Controller(meshNode.TMController.PositionController, "position", animations))
  260. {
  261. ExportVector3Animation("position", animations, key =>
  262. {
  263. var worldMatrix = meshNode.GetWorldMatrix(key, meshNode.HasParent());
  264. return worldMatrix.Trans.ToArraySwitched();
  265. });
  266. }
  267. if (!ExportQuaternionController(meshNode.TMController.RotationController, "rotationQuaternion", animations))
  268. {
  269. ExportQuaternionAnimation("rotationQuaternion", animations, key =>
  270. {
  271. var worldMatrix = meshNode.GetWorldMatrix(key, meshNode.HasParent());
  272. var affineParts = Loader.Global.AffineParts.Create();
  273. Loader.Global.DecompAffine(worldMatrix, affineParts);
  274. return affineParts.Q.ToArray();
  275. });
  276. }
  277. if (!ExportVector3Controller(meshNode.TMController.ScaleController, "scaling", animations))
  278. {
  279. ExportVector3Animation("scaling", animations, key =>
  280. {
  281. var worldMatrix = meshNode.GetWorldMatrix(key, meshNode.HasParent());
  282. var affineParts = Loader.Global.AffineParts.Create();
  283. Loader.Global.DecompAffine(worldMatrix, affineParts);
  284. return affineParts.K.ToArraySwitched();
  285. });
  286. }
  287. }
  288. int CreateGlobalVertex(IMesh mesh, int face, int facePart, List<GlobalVertex> vertices, bool hasUV, bool hasUV2, VNormal[] vnorms, List<GlobalVertex>[] verticesAlreadyExported, IISkinContextData skinContextData)
  289. {
  290. var faceObject = mesh.Faces[face];
  291. var vertexIndex = (int)faceObject.V[facePart];
  292. var vertex = new GlobalVertex
  293. {
  294. BaseIndex = vertexIndex,
  295. Position = mesh.Verts[vertexIndex],
  296. Normal = vnorms[vertexIndex].GetNormal(verticesAlreadyExported != null ? 1 : faceObject.SmGroup)
  297. };
  298. if (hasUV)
  299. {
  300. var tvertexIndex = (int)mesh.TvFace[face].T[facePart];
  301. vertex.UV = Loader.Global.Point2.Create(mesh.TVerts[tvertexIndex].X, mesh.TVerts[tvertexIndex].Y);
  302. }
  303. if (hasUV2)
  304. {
  305. var tvertexIndex = (int)mesh.MapFaces(2)[face].T[facePart];
  306. vertex.UV2 = Loader.Global.Point2.Create(mesh.MapVerts(2)[tvertexIndex].X, mesh.MapVerts(2)[tvertexIndex].Y);
  307. }
  308. if (skinContextData != null)
  309. {
  310. float weight0 = 0;
  311. float weight1 = 0;
  312. float weight2 = 0;
  313. int bone0 = bonesCount;
  314. int bone1 = bonesCount;
  315. int bone2 = bonesCount;
  316. int bone3 = bonesCount;
  317. int nbBones = skinContextData.GetNumAssignedBones(vertexIndex);
  318. if (nbBones > 0)
  319. {
  320. bone0 = skinContextData.GetAssignedBone(vertexIndex, 0);
  321. weight0 = skinContextData.GetBoneWeight(vertexIndex, 0);
  322. }
  323. if (nbBones > 1)
  324. {
  325. bone1 = skinContextData.GetAssignedBone(vertexIndex, 1);
  326. weight1 = skinContextData.GetBoneWeight(vertexIndex, 1);
  327. }
  328. if (nbBones > 2)
  329. {
  330. bone2 = skinContextData.GetAssignedBone(vertexIndex, 2);
  331. weight2 = skinContextData.GetBoneWeight(vertexIndex, 2);
  332. }
  333. if (nbBones > 3)
  334. {
  335. bone3 = skinContextData.GetAssignedBone(vertexIndex, 3);
  336. }
  337. if (nbBones == 0)
  338. {
  339. weight0 = 1.0f;
  340. bone0 = bonesCount;
  341. }
  342. if (nbBones > 4)
  343. {
  344. RaiseError("Too many bones influences per vertex: " + nbBones + ". Babylon.js only support 4 bones influences per vertex.", 2);
  345. }
  346. vertex.Weights = Loader.Global.Point4.Create(weight0, weight1, weight2, 1.0 - weight0 - weight1 - weight2);
  347. vertex.BonesIndices = (bone3 << 24) | (bone2 << 16) | (bone1 << 8) | bone0;
  348. }
  349. if (verticesAlreadyExported != null)
  350. {
  351. if (verticesAlreadyExported[vertexIndex] != null)
  352. {
  353. var index = verticesAlreadyExported[vertexIndex].IndexOf(vertex);
  354. if (index > -1)
  355. {
  356. return verticesAlreadyExported[vertexIndex][index].CurrentIndex;
  357. }
  358. }
  359. else
  360. {
  361. verticesAlreadyExported[vertexIndex] = new List<GlobalVertex>();
  362. }
  363. vertex.CurrentIndex = vertices.Count;
  364. verticesAlreadyExported[vertexIndex].Add(vertex);
  365. }
  366. vertices.Add(vertex);
  367. return vertices.Count - 1;
  368. }
  369. }
  370. }