BabylonExporter.Mesh.cs 32 KB

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