BabylonExporter.GLTFExporter.Mesh.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. using Autodesk.Max;
  2. using BabylonExport.Entities;
  3. using GLTFExport.Entities;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. namespace Max2Babylon
  9. {
  10. partial class BabylonExporter
  11. {
  12. private GLTFNode ExportMesh(BabylonMesh babylonMesh, GLTF gltf, GLTFNode gltfParentNode, BabylonScene babylonScene)
  13. {
  14. RaiseMessage("GLTFExporter.Mesh | Export mesh named: " + babylonMesh.name, 1);
  15. // --------------------------
  16. // ---------- Node ----------
  17. // --------------------------
  18. RaiseMessage("GLTFExporter.Mesh | Node", 2);
  19. // Node
  20. var gltfNode = new GLTFNode();
  21. gltfNode.name = babylonMesh.name;
  22. gltfNode.index = gltf.NodesList.Count;
  23. gltf.NodesList.Add(gltfNode);
  24. // Hierarchy
  25. if (gltfParentNode != null)
  26. {
  27. RaiseMessage("GLTFExporter.Mesh | Add " + babylonMesh.name + " as child to " + gltfParentNode.name, 3);
  28. gltfParentNode.ChildrenList.Add(gltfNode.index);
  29. }
  30. else
  31. {
  32. // It's a root node
  33. // Only root nodes are listed in a gltf scene
  34. RaiseMessage("GLTFExporter.Mesh | Add " + babylonMesh.name + " as root node to scene", 3);
  35. gltf.scenes[0].NodesList.Add(gltfNode.index);
  36. }
  37. // Transform
  38. gltfNode.translation = babylonMesh.position;
  39. // TODO - Choose between this method and the extra root node
  40. // Switch from left to right handed coordinate system
  41. //gltfNode.translation[0] *= -1;
  42. if (babylonMesh.rotationQuaternion != null)
  43. {
  44. gltfNode.rotation = babylonMesh.rotationQuaternion;
  45. }
  46. else
  47. {
  48. // Convert rotation vector to quaternion
  49. BabylonVector3 rotationVector3 = new BabylonVector3
  50. {
  51. X = babylonMesh.rotation[0],
  52. Y = babylonMesh.rotation[1],
  53. Z = babylonMesh.rotation[2]
  54. };
  55. gltfNode.rotation = rotationVector3.toQuaternionGltf().ToArray();
  56. }
  57. gltfNode.scale = babylonMesh.scaling;
  58. // --------------------------
  59. // --- Mesh from babylon ----
  60. // --------------------------
  61. if (babylonMesh.positions == null)
  62. {
  63. RaiseMessage("GLTFExporter.Mesh | Mesh is a dummy", 2);
  64. return gltfNode;
  65. }
  66. RaiseMessage("GLTFExporter.Mesh | Mesh from babylon", 2);
  67. // Retreive general data from babylon mesh
  68. int nbVertices = babylonMesh.positions.Length / 3;
  69. bool hasUV = babylonMesh.uvs != null && babylonMesh.uvs.Length > 0;
  70. bool hasUV2 = babylonMesh.uvs2 != null && babylonMesh.uvs2.Length > 0;
  71. bool hasColor = babylonMesh.colors != null && babylonMesh.colors.Length > 0;
  72. RaiseMessage("GLTFExporter.Mesh | nbVertices=" + nbVertices, 3);
  73. RaiseMessage("GLTFExporter.Mesh | hasUV=" + hasUV, 3);
  74. RaiseMessage("GLTFExporter.Mesh | hasUV2=" + hasUV2, 3);
  75. RaiseMessage("GLTFExporter.Mesh | hasColor=" + hasColor, 3);
  76. // Retreive vertices data from babylon mesh
  77. List<GLTFGlobalVertex> globalVertices = new List<GLTFGlobalVertex>();
  78. for (int indexVertex = 0; indexVertex < nbVertices; indexVertex++)
  79. {
  80. GLTFGlobalVertex globalVertex = new GLTFGlobalVertex();
  81. globalVertex.Position = createIPoint3(babylonMesh.positions, indexVertex);
  82. // Switch from left to right handed coordinate system
  83. //globalVertex.Position.X *= -1;
  84. globalVertex.Normal = createIPoint3(babylonMesh.normals, indexVertex);
  85. if (hasUV)
  86. {
  87. globalVertex.UV = createIPoint2(babylonMesh.uvs, indexVertex);
  88. // For glTF, the origin of the UV coordinates (0, 0) corresponds to the upper left corner of a texture image
  89. // While for Babylon, it corresponds to the lower left corner of a texture image
  90. globalVertex.UV.Y = 1 - globalVertex.UV.Y;
  91. }
  92. if (hasUV2)
  93. {
  94. globalVertex.UV2 = createIPoint2(babylonMesh.uvs2, indexVertex);
  95. // For glTF, the origin of the UV coordinates (0, 0) corresponds to the upper left corner of a texture image
  96. // While for Babylon, it corresponds to the lower left corner of a texture image
  97. globalVertex.UV2.Y = 1 - globalVertex.UV2.Y;
  98. }
  99. if (hasColor)
  100. {
  101. globalVertex.Color = createIPoint4(babylonMesh.colors, indexVertex).ToArray();
  102. }
  103. globalVertices.Add(globalVertex);
  104. }
  105. // Retreive indices from babylon mesh
  106. List<ushort> babylonIndices = new List<ushort>();
  107. babylonIndices = babylonMesh.indices.ToList().ConvertAll(new Converter<int, ushort>(n => (ushort)n));
  108. // For triangle primitives in gltf, the front face has a counter-clockwise (CCW) winding order
  109. // Swap face side
  110. //for (int i = 0; i < babylonIndices.Count; i += 3)
  111. //{
  112. // var tmp = babylonIndices[i];
  113. // babylonIndices[i] = babylonIndices[i + 2];
  114. // babylonIndices[i + 2] = tmp;
  115. //}
  116. // --------------------------
  117. // ------- Init glTF --------
  118. // --------------------------
  119. RaiseMessage("GLTFExporter.Mesh | Init glTF", 2);
  120. // Mesh
  121. var gltfMesh = new GLTFMesh { name = babylonMesh.name };
  122. gltfMesh.index = gltf.MeshesList.Count;
  123. gltf.MeshesList.Add(gltfMesh);
  124. gltfNode.mesh = gltfMesh.index;
  125. gltfMesh.gltfNode = gltfNode;
  126. // Buffer
  127. var buffer = new GLTFBuffer
  128. {
  129. uri = gltfMesh.name + ".bin"
  130. };
  131. buffer.index = gltf.BuffersList.Count;
  132. gltf.BuffersList.Add(buffer);
  133. // BufferView - Scalar
  134. var bufferViewScalar = new GLTFBufferView
  135. {
  136. name = "bufferViewScalar",
  137. buffer = buffer.index,
  138. Buffer = buffer
  139. };
  140. bufferViewScalar.index = gltf.BufferViewsList.Count;
  141. gltf.BufferViewsList.Add(bufferViewScalar);
  142. // BufferView - Vector3
  143. var bufferViewFloatVec3 = new GLTFBufferView
  144. {
  145. name = "bufferViewFloatVec3",
  146. buffer = buffer.index,
  147. Buffer = buffer,
  148. byteOffset = 0,
  149. byteStride = 12 // Field only defined for buffer views that contain vertex attributes. A vertex needs 3 * 4 bytes
  150. };
  151. bufferViewFloatVec3.index = gltf.BufferViewsList.Count;
  152. gltf.BufferViewsList.Add(bufferViewFloatVec3);
  153. // BufferView - Vector4
  154. GLTFBufferView bufferViewFloatVec4 = null;
  155. if (hasColor)
  156. {
  157. bufferViewFloatVec4 = new GLTFBufferView
  158. {
  159. name = "bufferViewFloatVec4",
  160. buffer = buffer.index,
  161. Buffer = buffer,
  162. byteOffset = 0,
  163. byteStride = 16 // Field only defined for buffer views that contain vertex attributes. A vertex needs 4 * 4 bytes
  164. };
  165. bufferViewFloatVec4.index = gltf.BufferViewsList.Count;
  166. gltf.BufferViewsList.Add(bufferViewFloatVec4);
  167. }
  168. // BufferView - Vector2
  169. GLTFBufferView bufferViewFloatVec2 = null;
  170. if (hasUV || hasUV2)
  171. {
  172. bufferViewFloatVec2 = new GLTFBufferView
  173. {
  174. name = "bufferViewFloatVec2",
  175. buffer = buffer.index,
  176. Buffer = buffer,
  177. byteStride = 8 // Field only defined for buffer views that contain vertex attributes. A vertex needs 2 * 4 bytes
  178. };
  179. bufferViewFloatVec2.index = gltf.BufferViewsList.Count;
  180. gltf.BufferViewsList.Add(bufferViewFloatVec2);
  181. }
  182. // --------------------------
  183. // ---- glTF primitives -----
  184. // --------------------------
  185. RaiseMessage("GLTFExporter.Mesh | glTF primitives", 2);
  186. var meshPrimitives = new List<GLTFMeshPrimitive>();
  187. // Global vertices are sorted per submesh
  188. var globalVerticesSubMeshes = new List<List<GLTFGlobalVertex>>();
  189. // In gltf, indices of each mesh primitive are 0-based (ie: min value is 0)
  190. // Thus, the gltf indices list is a concatenation of sub lists all 0-based
  191. // Example for 2 triangles, each being a submesh:
  192. // babylonIndices = {0,1,2, 3,4,5} gives as result gltfIndicies = {0,1,2, 0,1,2}
  193. var gltfIndices = new List<ushort>();
  194. foreach (BabylonSubMesh babylonSubMesh in babylonMesh.subMeshes)
  195. {
  196. // --------------------------
  197. // ------ SubMesh data ------
  198. // --------------------------
  199. List<GLTFGlobalVertex> globalVerticesSubMesh = globalVertices.GetRange(babylonSubMesh.verticesStart, babylonSubMesh.verticesCount);
  200. globalVerticesSubMeshes.Add(globalVerticesSubMesh);
  201. List<ushort> _indices = babylonIndices.GetRange(babylonSubMesh.indexStart, babylonSubMesh.indexCount);
  202. // Indices of this submesh / primitive are updated to be 0-based
  203. var minIndiceValue = _indices.Min(); // Should be equal to babylonSubMesh.indexStart
  204. for (int indexIndice = 0; indexIndice < _indices.Count; indexIndice++)
  205. {
  206. _indices[indexIndice] -= minIndiceValue;
  207. }
  208. gltfIndices.AddRange(_indices);
  209. // --------------------------
  210. // -- Init glTF primitive ---
  211. // --------------------------
  212. // MeshPrimitive
  213. var meshPrimitive = new GLTFMeshPrimitive
  214. {
  215. attributes = new Dictionary<string, int>()
  216. };
  217. meshPrimitives.Add(meshPrimitive);
  218. // Accessor - Indices
  219. var accessorIndices = new GLTFAccessor
  220. {
  221. name = "accessorIndices",
  222. bufferView = bufferViewScalar.index,
  223. BufferView = bufferViewScalar,
  224. componentType = GLTFAccessor.ComponentType.UNSIGNED_SHORT,
  225. type = GLTFAccessor.TypeEnum.SCALAR.ToString()
  226. };
  227. accessorIndices.index = gltf.AccessorsList.Count;
  228. gltf.AccessorsList.Add(accessorIndices);
  229. meshPrimitive.indices = accessorIndices.index;
  230. // Accessor - Positions
  231. var accessorPositions = new GLTFAccessor
  232. {
  233. name = "accessorPositions",
  234. bufferView = bufferViewFloatVec3.index,
  235. BufferView = bufferViewFloatVec3,
  236. componentType = GLTFAccessor.ComponentType.FLOAT,
  237. type = GLTFAccessor.TypeEnum.VEC3.ToString(),
  238. min = new float[] { float.MaxValue, float.MaxValue, float.MaxValue },
  239. max = new float[] { float.MinValue, float.MinValue, float.MinValue }
  240. };
  241. accessorPositions.index = gltf.AccessorsList.Count;
  242. gltf.AccessorsList.Add(accessorPositions);
  243. meshPrimitive.attributes.Add(GLTFMeshPrimitive.Attribute.POSITION.ToString(), accessorPositions.index);
  244. // Accessor - Normals
  245. var accessorNormals = new GLTFAccessor
  246. {
  247. name = "accessorNormals",
  248. bufferView = bufferViewFloatVec3.index,
  249. BufferView = bufferViewFloatVec3,
  250. componentType = GLTFAccessor.ComponentType.FLOAT,
  251. type = GLTFAccessor.TypeEnum.VEC3.ToString()
  252. };
  253. accessorNormals.index = gltf.AccessorsList.Count;
  254. gltf.AccessorsList.Add(accessorNormals);
  255. meshPrimitive.attributes.Add(GLTFMeshPrimitive.Attribute.NORMAL.ToString(), accessorNormals.index);
  256. // Accessor - Colors
  257. GLTFAccessor accessorColors = null;
  258. if (hasColor)
  259. {
  260. accessorColors = new GLTFAccessor
  261. {
  262. name = "accessorColors",
  263. bufferView = bufferViewFloatVec4.index,
  264. BufferView = bufferViewFloatVec4,
  265. componentType = GLTFAccessor.ComponentType.FLOAT,
  266. type = GLTFAccessor.TypeEnum.VEC4.ToString()
  267. };
  268. accessorColors.index = gltf.AccessorsList.Count;
  269. gltf.AccessorsList.Add(accessorColors);
  270. meshPrimitive.attributes.Add(GLTFMeshPrimitive.Attribute.COLOR_0.ToString(), accessorColors.index);
  271. }
  272. // Accessor - UV
  273. GLTFAccessor accessorUVs = null;
  274. if (hasUV)
  275. {
  276. accessorUVs = new GLTFAccessor
  277. {
  278. name = "accessorUVs",
  279. bufferView = bufferViewFloatVec2.index,
  280. BufferView = bufferViewFloatVec2,
  281. componentType = GLTFAccessor.ComponentType.FLOAT,
  282. type = GLTFAccessor.TypeEnum.VEC2.ToString()
  283. };
  284. accessorUVs.index = gltf.AccessorsList.Count;
  285. gltf.AccessorsList.Add(accessorUVs);
  286. meshPrimitive.attributes.Add(GLTFMeshPrimitive.Attribute.TEXCOORD_0.ToString(), accessorUVs.index);
  287. }
  288. // Accessor - UV2
  289. GLTFAccessor accessorUV2s = null;
  290. if (hasUV2)
  291. {
  292. accessorUV2s = new GLTFAccessor
  293. {
  294. name = "accessorUV2s",
  295. bufferView = bufferViewFloatVec2.index,
  296. BufferView = bufferViewFloatVec2,
  297. componentType = GLTFAccessor.ComponentType.FLOAT,
  298. type = GLTFAccessor.TypeEnum.VEC2.ToString()
  299. };
  300. accessorUV2s.index = gltf.AccessorsList.Count;
  301. gltf.AccessorsList.Add(accessorUV2s);
  302. meshPrimitive.attributes.Add(GLTFMeshPrimitive.Attribute.TEXCOORD_1.ToString(), accessorUV2s.index);
  303. }
  304. // --------------------------
  305. // - Update glTF primitive --
  306. // --------------------------
  307. RaiseMessage("GLTFExporter.Mesh | Mesh as glTF", 3);
  308. // Material
  309. if (babylonMesh.materialId != null)
  310. {
  311. // Retreive the babylon material
  312. var babylonMaterialId = babylonMesh.materialId;
  313. var babylonMaterials = new List<BabylonMaterial>(babylonScene.materials);
  314. var babylonMaterial = babylonMaterials.Find(_babylonMaterial => _babylonMaterial.id == babylonMaterialId);
  315. if (babylonMaterial == null)
  316. {
  317. // It's a multi material
  318. var babylonMultiMaterials = new List<BabylonMultiMaterial>(babylonScene.multiMaterials);
  319. var babylonMultiMaterial = babylonMultiMaterials.Find(_babylonMultiMaterial => _babylonMultiMaterial.id == babylonMesh.materialId);
  320. babylonMaterialId = babylonMultiMaterial.materials[babylonSubMesh.materialIndex];
  321. babylonMaterial = babylonMaterials.Find(_babylonMaterial => _babylonMaterial.id == babylonMaterialId);
  322. }
  323. // Update primitive material index
  324. var indexMaterial = babylonMaterialsToExport.FindIndex(_babylonMaterial => _babylonMaterial == babylonMaterial);
  325. if (indexMaterial == -1)
  326. {
  327. // Store material for exportation
  328. indexMaterial = babylonMaterialsToExport.Count;
  329. babylonMaterialsToExport.Add(babylonMaterial);
  330. }
  331. meshPrimitive.material = indexMaterial;
  332. // TODO - Add and retreive info from babylon material
  333. meshPrimitive.mode = GLTFMeshPrimitive.FillMode.TRIANGLES;
  334. }
  335. // Update min and max vertex position for each component (X, Y, Z)
  336. globalVerticesSubMesh.ForEach((globalVertex) =>
  337. {
  338. var positionArray = new float[] { globalVertex.Position.X, globalVertex.Position.Y, globalVertex.Position.Z };
  339. for (int indexComponent = 0; indexComponent < positionArray.Length; indexComponent++)
  340. {
  341. if (positionArray[indexComponent] < accessorPositions.min[indexComponent])
  342. {
  343. accessorPositions.min[indexComponent] = positionArray[indexComponent];
  344. }
  345. if (positionArray[indexComponent] > accessorPositions.max[indexComponent])
  346. {
  347. accessorPositions.max[indexComponent] = positionArray[indexComponent];
  348. }
  349. }
  350. });
  351. // Update byte length and count of accessors, bufferViews and buffers
  352. // Scalar
  353. AddElementsToAccessor(accessorIndices, _indices.Count);
  354. // Vector3
  355. AddElementsToAccessor(accessorPositions, globalVerticesSubMesh.Count);
  356. AddElementsToAccessor(accessorNormals, globalVerticesSubMesh.Count);
  357. // Vector4
  358. if (hasColor)
  359. {
  360. AddElementsToAccessor(accessorColors, globalVerticesSubMesh.Count);
  361. }
  362. // Vector2
  363. if (hasUV)
  364. {
  365. AddElementsToAccessor(accessorUVs, globalVerticesSubMesh.Count);
  366. }
  367. if (hasUV2)
  368. {
  369. AddElementsToAccessor(accessorUV2s, globalVerticesSubMesh.Count);
  370. }
  371. }
  372. gltfMesh.primitives = meshPrimitives.ToArray();
  373. // Update byte offset of bufferViews
  374. GLTFBufferView lastBufferView = null;
  375. gltf.BufferViewsList.FindAll(bufferView => bufferView.buffer == buffer.index).ForEach(bufferView =>
  376. {
  377. if (lastBufferView != null)
  378. {
  379. bufferView.byteOffset = lastBufferView.byteOffset + lastBufferView.byteLength;
  380. }
  381. lastBufferView = bufferView;
  382. });
  383. // --------------------------
  384. // --------- Saving ---------
  385. // --------------------------
  386. string outputBinaryFile = Path.Combine(gltf.OutputPath, gltfMesh.name + ".bin");
  387. RaiseMessage("GLTFExporter.Mesh | Saving " + outputBinaryFile, 2);
  388. // Write data to binary file
  389. using (BinaryWriter writer = new BinaryWriter(File.Open(outputBinaryFile, FileMode.Create)))
  390. {
  391. // BufferView - Scalar
  392. gltfIndices.ForEach(n => writer.Write(n));
  393. // BufferView - Vector3
  394. globalVerticesSubMeshes.ForEach(globalVerticesSubMesh =>
  395. {
  396. List<float> vertices = globalVerticesSubMesh.SelectMany(v => new[] { v.Position.X, v.Position.Y, v.Position.Z }).ToList();
  397. vertices.ForEach(n => writer.Write(n));
  398. List<float> normals = globalVerticesSubMesh.SelectMany(v => new[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToList();
  399. normals.ForEach(n => writer.Write(n));
  400. });
  401. // BufferView - Vector4
  402. globalVerticesSubMeshes.ForEach(globalVerticesSubMesh =>
  403. {
  404. if (hasColor)
  405. {
  406. List<float> colors = globalVerticesSubMesh.SelectMany(v => new[] { v.Color[0], v.Color[1], v.Color[2], v.Color[3] }).ToList();
  407. colors.ForEach(n => writer.Write(n));
  408. }
  409. });
  410. // BufferView - Vector2
  411. globalVerticesSubMeshes.ForEach(globalVerticesSubMesh =>
  412. {
  413. if (hasUV)
  414. {
  415. List<float> uvs = globalVerticesSubMesh.SelectMany(v => new[] { v.UV.X, v.UV.Y }).ToList();
  416. uvs.ForEach(n => writer.Write(n));
  417. }
  418. if (hasUV2)
  419. {
  420. List<float> uvs2 = globalVerticesSubMesh.SelectMany(v => new[] { v.UV2.X, v.UV2.Y }).ToList();
  421. uvs2.ForEach(n => writer.Write(n));
  422. }
  423. });
  424. }
  425. return gltfNode;
  426. }
  427. private IPoint2 createIPoint2(float[] array, int index)
  428. {
  429. var startIndex = index * 2;
  430. return Loader.Global.Point2.Create(array[startIndex], array[startIndex + 1]);
  431. }
  432. private IPoint3 createIPoint3(float[] array, int index)
  433. {
  434. var startIndex = index * 3;
  435. return Loader.Global.Point3.Create(array[startIndex], array[startIndex + 1], array[startIndex + 2]);
  436. }
  437. private IPoint4 createIPoint4(float[] array, int index)
  438. {
  439. var startIndex = index * 4;
  440. return Loader.Global.Point4.Create(array[startIndex], array[startIndex + 1], array[startIndex + 2], array[startIndex + 3]);
  441. }
  442. private void AddElementsToAccessor(GLTFAccessor accessor, int count)
  443. {
  444. GLTFBufferView bufferView = accessor.BufferView;
  445. GLTFBuffer buffer = bufferView.Buffer;
  446. accessor.byteOffset = bufferView.byteLength;
  447. accessor.count += count;
  448. bufferView.byteLength += accessor.getByteLength();
  449. buffer.byteLength += accessor.getByteLength();
  450. }
  451. }
  452. }