BabylonExporter.Mesh.cs 32 KB

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