babylon.meshBuilder.js 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var MeshBuilder = (function () {
  4. function MeshBuilder() {
  5. }
  6. /**
  7. * Creates a box mesh.
  8. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  9. * The parameter `size` sets the size (float) of each box side (default 1).
  10. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  11. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 `Color3` elements) and `faceUV` (an array of 6 `Vector4` elements).
  12. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  13. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  14. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  15. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  16. */
  17. MeshBuilder.CreateBox = function (name, options, scene) {
  18. var box = new BABYLON.Mesh(name, scene);
  19. var vertexData = BABYLON.VertexData.CreateBox(options);
  20. vertexData.applyToMesh(box, options.updatable);
  21. return box;
  22. };
  23. /**
  24. * Creates a sphere mesh.
  25. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  26. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  28. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  30. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  31. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34. */
  35. MeshBuilder.CreateSphere = function (name, options, scene) {
  36. var sphere = new BABYLON.Mesh(name, scene);
  37. var vertexData = BABYLON.VertexData.CreateSphere(options);
  38. vertexData.applyToMesh(sphere, options.updatable);
  39. return sphere;
  40. };
  41. /**
  42. * Creates a plane polygonal mesh. By default, this is a disc.
  43. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  44. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  45. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  46. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  47. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50. */
  51. MeshBuilder.CreateDisc = function (name, options, scene) {
  52. var disc = new BABYLON.Mesh(name, scene);
  53. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54. vertexData.applyToMesh(disc, options.updatable);
  55. return disc;
  56. };
  57. /**
  58. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  59. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  60. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  61. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  62. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  63. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  64. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  66. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67. */
  68. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  69. var sphere = new BABYLON.Mesh(name, scene);
  70. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  71. vertexData.applyToMesh(sphere, options.updatable);
  72. return sphere;
  73. };
  74. ;
  75. /**
  76. * Creates a ribbon mesh.
  77. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  78. *
  79. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  80. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  81. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  82. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  83. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  84. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  85. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  86. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  87. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  88. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  89. */
  90. MeshBuilder.CreateRibbon = function (name, options, scene) {
  91. var pathArray = options.pathArray;
  92. var closeArray = options.closeArray;
  93. var closePath = options.closePath;
  94. var offset = options.offset;
  95. var sideOrientation = options.sideOrientation;
  96. var instance = options.instance;
  97. var updatable = options.updatable;
  98. if (instance) {
  99. // positionFunction : ribbon case
  100. // only pathArray and sideOrientation parameters are taken into account for positions update
  101. var positionFunction = function (positions) {
  102. var minlg = pathArray[0].length;
  103. var i = 0;
  104. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  105. for (var si = 1; si <= ns; si++) {
  106. for (var p = 0; p < pathArray.length; p++) {
  107. var path = pathArray[p];
  108. var l = path.length;
  109. minlg = (minlg < l) ? minlg : l;
  110. var j = 0;
  111. while (j < minlg) {
  112. positions[i] = path[j].x;
  113. positions[i + 1] = path[j].y;
  114. positions[i + 2] = path[j].z;
  115. j++;
  116. i += 3;
  117. }
  118. if (instance._closePath) {
  119. positions[i] = path[0].x;
  120. positions[i + 1] = path[0].y;
  121. positions[i + 2] = path[0].z;
  122. i += 3;
  123. }
  124. }
  125. }
  126. };
  127. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  128. positionFunction(positions);
  129. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  130. if (!(instance.areNormalsFrozen)) {
  131. var indices = instance.getIndices();
  132. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  133. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  134. if (instance._closePath) {
  135. var indexFirst = 0;
  136. var indexLast = 0;
  137. for (var p = 0; p < pathArray.length; p++) {
  138. indexFirst = instance._idx[p] * 3;
  139. if (p + 1 < pathArray.length) {
  140. indexLast = (instance._idx[p + 1] - 1) * 3;
  141. }
  142. else {
  143. indexLast = normals.length - 3;
  144. }
  145. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  146. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  147. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  148. normals[indexLast] = normals[indexFirst];
  149. normals[indexLast + 1] = normals[indexFirst + 1];
  150. normals[indexLast + 2] = normals[indexFirst + 2];
  151. }
  152. }
  153. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  154. }
  155. return instance;
  156. }
  157. else {
  158. var ribbon = new BABYLON.Mesh(name, scene);
  159. ribbon.sideOrientation = sideOrientation;
  160. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  161. if (closePath) {
  162. ribbon._idx = vertexData._idx;
  163. }
  164. ribbon._closePath = closePath;
  165. ribbon._closeArray = closeArray;
  166. vertexData.applyToMesh(ribbon, updatable);
  167. return ribbon;
  168. }
  169. };
  170. /**
  171. * Creates a cylinder or a cone mesh.
  172. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  173. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  174. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  175. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  176. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  177. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  178. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  179. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  180. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  181. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n `Color3` elements) and `faceUV` (an array of n `Vector4` elements).
  182. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  183. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  184. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  185. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  186. * If `enclose` is false, a ring surface is one element.
  187. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  188. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  189. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  190. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  192. */
  193. MeshBuilder.CreateCylinder = function (name, options, scene) {
  194. var cylinder = new BABYLON.Mesh(name, scene);
  195. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  196. vertexData.applyToMesh(cylinder, options.updatable);
  197. return cylinder;
  198. };
  199. /**
  200. * Creates a torus mesh.
  201. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  202. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  203. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  204. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  205. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  206. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  207. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  208. */
  209. MeshBuilder.CreateTorus = function (name, options, scene) {
  210. var torus = new BABYLON.Mesh(name, scene);
  211. var vertexData = BABYLON.VertexData.CreateTorus(options);
  212. vertexData.applyToMesh(torus, options.updatable);
  213. return torus;
  214. };
  215. /**
  216. * Creates a torus knot mesh.
  217. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  218. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  219. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  220. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  221. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  222. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  223. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  224. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  225. */
  226. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  227. var torusKnot = new BABYLON.Mesh(name, scene);
  228. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  229. vertexData.applyToMesh(torusKnot, options.updatable);
  230. return torusKnot;
  231. };
  232. /**
  233. * Creates a line system mesh.
  234. * A line system is a pool of many lines gathered in a single mesh.
  235. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  236. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  237. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  238. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  239. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  240. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  241. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  242. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  243. */
  244. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  245. var instance = options.instance;
  246. var lines = options.lines;
  247. if (instance) {
  248. var positionFunction = function (positions) {
  249. var i = 0;
  250. for (var l = 0; l < lines.length; l++) {
  251. var points = lines[l];
  252. for (var p = 0; p < points.length; p++) {
  253. positions[i] = points[p].x;
  254. positions[i + 1] = points[p].y;
  255. positions[i + 2] = points[p].z;
  256. i += 3;
  257. }
  258. }
  259. };
  260. instance.updateMeshPositions(positionFunction, false);
  261. return instance;
  262. }
  263. // line system creation
  264. var lineSystem = new BABYLON.LinesMesh(name, scene);
  265. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  266. vertexData.applyToMesh(lineSystem, options.updatable);
  267. return lineSystem;
  268. };
  269. /**
  270. * Creates a line mesh.
  271. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  272. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  273. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  274. * The parameter `points` is an array successive Vector3.
  275. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  276. * When updating an instance, remember that only point positions can change, not the number of points.
  277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  278. */
  279. MeshBuilder.CreateLines = function (name, options, scene) {
  280. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  281. return lines;
  282. };
  283. /**
  284. * Creates a dashed line mesh.
  285. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  286. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  287. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  288. * The parameter `points` is an array successive Vector3.
  289. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  290. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  291. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  292. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  293. * When updating an instance, remember that only point positions can change, not the number of points.
  294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  295. */
  296. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  297. var points = options.points;
  298. var instance = options.instance;
  299. var gapSize = options.gapSize;
  300. var dashNb = options.dashNb;
  301. var dashSize = options.dashSize;
  302. if (instance) {
  303. var positionFunction = function (positions) {
  304. var curvect = BABYLON.Vector3.Zero();
  305. var nbSeg = positions.length / 6;
  306. var lg = 0;
  307. var nb = 0;
  308. var shft = 0;
  309. var dashshft = 0;
  310. var curshft = 0;
  311. var p = 0;
  312. var i = 0;
  313. var j = 0;
  314. for (i = 0; i < points.length - 1; i++) {
  315. points[i + 1].subtractToRef(points[i], curvect);
  316. lg += curvect.length();
  317. }
  318. shft = lg / nbSeg;
  319. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  320. for (i = 0; i < points.length - 1; i++) {
  321. points[i + 1].subtractToRef(points[i], curvect);
  322. nb = Math.floor(curvect.length() / shft);
  323. curvect.normalize();
  324. j = 0;
  325. while (j < nb && p < positions.length) {
  326. curshft = shft * j;
  327. positions[p] = points[i].x + curshft * curvect.x;
  328. positions[p + 1] = points[i].y + curshft * curvect.y;
  329. positions[p + 2] = points[i].z + curshft * curvect.z;
  330. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  331. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  332. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  333. p += 6;
  334. j++;
  335. }
  336. }
  337. while (p < positions.length) {
  338. positions[p] = points[i].x;
  339. positions[p + 1] = points[i].y;
  340. positions[p + 2] = points[i].z;
  341. p += 3;
  342. }
  343. };
  344. instance.updateMeshPositions(positionFunction, false);
  345. return instance;
  346. }
  347. // dashed lines creation
  348. var dashedLines = new BABYLON.LinesMesh(name, scene);
  349. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  350. vertexData.applyToMesh(dashedLines, options.updatable);
  351. dashedLines.dashSize = dashSize;
  352. dashedLines.gapSize = gapSize;
  353. return dashedLines;
  354. };
  355. /**
  356. * Creates an extruded shape mesh.
  357. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  358. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  359. *
  360. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  361. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  362. * extruded along the Z axis.
  363. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  364. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  365. * The parameter `scale` (float, default 1) is the value to scale the shape.
  366. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  367. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  368. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  369. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  370. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  371. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  372. */
  373. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  374. var path = options.path;
  375. var shape = options.shape;
  376. var scale = options.scale || 1;
  377. var rotation = options.rotation || 0;
  378. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  379. var updatable = options.updatable;
  380. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  381. var instance = options.instance;
  382. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  383. };
  384. /**
  385. * Creates an custom extruded shape mesh.
  386. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  387. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  388. *
  389. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  390. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  391. * extruded along the Z axis.
  392. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  393. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  394. * and the distance of this point from the begining of the path :
  395. * ```rotationFunction = function(i, distance) {
  396. * // do things
  397. * return rotationValue; }```
  398. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  399. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  400. * and the distance of this point from the begining of the path :
  401. * ````scaleFunction = function(i, distance) {
  402. * // do things
  403. * return scaleValue;}```
  404. * It must returns a float value that will be the scale value applied to the shape on each path point.
  405. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  406. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  407. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  408. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  409. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  410. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  411. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  412. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  413. */
  414. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  415. var path = options.path;
  416. var shape = options.shape;
  417. var scaleFunction = options.scaleFunction || (function () { return 1; });
  418. var rotationFunction = options.rotationFunction || (function () { return 0; });
  419. var ribbonCloseArray = options.ribbonCloseArray || false;
  420. var ribbonClosePath = options.ribbonClosePath || false;
  421. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  422. var updatable = options.updatable;
  423. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  424. var instance = options.instance;
  425. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  426. };
  427. /**
  428. * Creates lathe mesh.
  429. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  430. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  431. *
  432. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  433. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  434. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  435. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  436. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  437. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  438. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  442. */
  443. MeshBuilder.CreateLathe = function (name, options, scene) {
  444. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  445. var closed = (options.closed === undefined) ? true : options.closed;
  446. var shape = options.shape;
  447. var radius = options.radius || 1;
  448. var tessellation = options.tessellation || 64;
  449. var updatable = options.updatable;
  450. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  451. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  452. var pi2 = Math.PI * 2;
  453. var paths = new Array();
  454. var i = 0;
  455. var p = 0;
  456. var step = pi2 / tessellation * arc;
  457. var rotated;
  458. var path = new Array();
  459. ;
  460. for (i = 0; i <= tessellation; i++) {
  461. var path = [];
  462. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  463. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  464. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  465. }
  466. for (p = 0; p < shape.length; p++) {
  467. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  468. path.push(rotated);
  469. }
  470. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  471. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  472. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  473. }
  474. paths.push(path);
  475. }
  476. // lathe ribbon
  477. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  478. return lathe;
  479. };
  480. /**
  481. * Creates a plane mesh.
  482. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  483. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  484. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  485. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  489. */
  490. MeshBuilder.CreatePlane = function (name, options, scene) {
  491. var plane = new BABYLON.Mesh(name, scene);
  492. var vertexData = BABYLON.VertexData.CreatePlane(options);
  493. vertexData.applyToMesh(plane, options.updatable);
  494. if (options.sourcePlane) {
  495. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  496. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  497. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  498. plane.rotate(vectorProduct, product);
  499. }
  500. return plane;
  501. };
  502. /**
  503. * Creates a ground mesh.
  504. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  505. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  506. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  508. */
  509. MeshBuilder.CreateGround = function (name, options, scene) {
  510. var ground = new BABYLON.GroundMesh(name, scene);
  511. ground._setReady(false);
  512. ground._subdivisions = options.subdivisions || 1;
  513. ground._width = options.width || 1;
  514. ground._height = options.height || 1;
  515. ground._maxX = ground._width / 2;
  516. ground._maxZ = ground._height / 2;
  517. ground._minX = -ground._maxX;
  518. ground._minZ = -ground._maxZ;
  519. var vertexData = BABYLON.VertexData.CreateGround(options);
  520. vertexData.applyToMesh(ground, options.updatable);
  521. ground._setReady(true);
  522. return ground;
  523. };
  524. /**
  525. * Creates a tiled ground mesh.
  526. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  527. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  528. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  529. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  530. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  531. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  532. * numbers of subdivisions on the ground width and height of each tile.
  533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  534. */
  535. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  536. var tiledGround = new BABYLON.Mesh(name, scene);
  537. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  538. vertexData.applyToMesh(tiledGround, options.updatable);
  539. return tiledGround;
  540. };
  541. /**
  542. * Creates a ground mesh from a height map.
  543. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  544. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  545. * The parameter `url` sets the URL of the height map image resource.
  546. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  547. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  548. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  549. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  550. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  551. * This function is passed the newly built mesh : ```function(mesh) { // do things
  552. * return; }```
  553. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  554. */
  555. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  556. var width = options.width || 10;
  557. var height = options.height || 10;
  558. var subdivisions = options.subdivisions || 1;
  559. var minHeight = options.minHeight;
  560. var maxHeight = options.maxHeight || 10;
  561. var updatable = options.updatable;
  562. var onReady = options.onReady;
  563. var ground = new BABYLON.GroundMesh(name, scene);
  564. ground._subdivisions = subdivisions;
  565. ground._width = width;
  566. ground._height = height;
  567. ground._maxX = ground._width / 2;
  568. ground._maxZ = ground._height / 2;
  569. ground._minX = -ground._maxX;
  570. ground._minZ = -ground._maxZ;
  571. ground._setReady(false);
  572. var onload = function (img) {
  573. // Getting height map data
  574. var canvas = document.createElement("canvas");
  575. var context = canvas.getContext("2d");
  576. var bufferWidth = img.width;
  577. var bufferHeight = img.height;
  578. canvas.width = bufferWidth;
  579. canvas.height = bufferHeight;
  580. context.drawImage(img, 0, 0);
  581. // Create VertexData from map data
  582. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  583. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  584. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  585. width: width, height: height,
  586. subdivisions: subdivisions,
  587. minHeight: minHeight, maxHeight: maxHeight,
  588. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  589. });
  590. vertexData.applyToMesh(ground, updatable);
  591. ground._setReady(true);
  592. //execute ready callback, if set
  593. if (onReady) {
  594. onReady(ground);
  595. }
  596. };
  597. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  598. return ground;
  599. };
  600. /**
  601. * Creates a tube mesh.
  602. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  603. *
  604. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  605. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  606. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  607. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  608. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  609. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  610. * It must return a radius value (positive float) :
  611. * ```var radiusFunction = function(i, distance) {
  612. * // do things
  613. * return radius; }```
  614. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  615. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  616. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  617. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  618. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  619. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  620. */
  621. MeshBuilder.CreateTube = function (name, options, scene) {
  622. var path = options.path;
  623. var radius = options.radius || 1;
  624. var tessellation = options.tessellation || 64;
  625. var radiusFunction = options.radiusFunction;
  626. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  627. var updatable = options.updatable;
  628. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  629. var instance = options.instance;
  630. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  631. // tube geometry
  632. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  633. var tangents = path3D.getTangents();
  634. var normals = path3D.getNormals();
  635. var distances = path3D.getDistances();
  636. var pi2 = Math.PI * 2;
  637. var step = pi2 / tessellation * arc;
  638. var returnRadius = function () { return radius; };
  639. var radiusFunctionFinal = radiusFunction || returnRadius;
  640. var circlePath;
  641. var rad;
  642. var normal;
  643. var rotated;
  644. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  645. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  646. for (var i = 0; i < path.length; i++) {
  647. rad = radiusFunctionFinal(i, distances[i]); // current radius
  648. circlePath = Array(); // current circle array
  649. normal = normals[i]; // current normal
  650. for (var t = 0; t < tessellation; t++) {
  651. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  652. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  653. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  654. rotated.scaleInPlace(rad).addInPlace(path[i]);
  655. circlePath[t] = rotated;
  656. }
  657. circlePaths[index] = circlePath;
  658. index++;
  659. }
  660. // cap
  661. var capPath = function (nbPoints, pathIndex) {
  662. var pointCap = Array();
  663. for (var i = 0; i < nbPoints; i++) {
  664. pointCap.push(path[pathIndex]);
  665. }
  666. return pointCap;
  667. };
  668. switch (cap) {
  669. case BABYLON.Mesh.NO_CAP:
  670. break;
  671. case BABYLON.Mesh.CAP_START:
  672. circlePaths[0] = capPath(tessellation, 0);
  673. circlePaths[1] = circlePaths[2].slice(0);
  674. break;
  675. case BABYLON.Mesh.CAP_END:
  676. circlePaths[index] = circlePaths[index - 1].slice(0);
  677. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  678. break;
  679. case BABYLON.Mesh.CAP_ALL:
  680. circlePaths[0] = capPath(tessellation, 0);
  681. circlePaths[1] = circlePaths[2].slice(0);
  682. circlePaths[index] = circlePaths[index - 1].slice(0);
  683. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  684. break;
  685. default:
  686. break;
  687. }
  688. return circlePaths;
  689. };
  690. var path3D;
  691. var pathArray;
  692. if (instance) {
  693. var arc = options.arc || instance.arc;
  694. path3D = (instance.path3D).update(path);
  695. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  696. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  697. instance.path3D = path3D;
  698. instance.pathArray = pathArray;
  699. instance.arc = arc;
  700. return instance;
  701. }
  702. // tube creation
  703. path3D = new BABYLON.Path3D(path);
  704. var newPathArray = new Array();
  705. cap = (cap < 0 || cap > 3) ? 0 : cap;
  706. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  707. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  708. tube.pathArray = pathArray;
  709. tube.path3D = path3D;
  710. tube.tessellation = tessellation;
  711. tube.cap = cap;
  712. tube.arc = options.arc;
  713. return tube;
  714. };
  715. /**
  716. * Creates a polyhedron mesh.
  717. *
  718. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  719. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  720. * to choose the wanted type.
  721. * The parameter `size` (positive float, default 1) sets the polygon size.
  722. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  723. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  724. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  725. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  726. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  727. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  729. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  731. */
  732. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  733. var polyhedron = new BABYLON.Mesh(name, scene);
  734. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  735. vertexData.applyToMesh(polyhedron, options.updatable);
  736. return polyhedron;
  737. };
  738. /**
  739. * Creates a decal mesh.
  740. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  741. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  742. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  743. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  744. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  745. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  746. */
  747. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  748. var indices = sourceMesh.getIndices();
  749. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  750. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  751. var position = options.position || BABYLON.Vector3.Zero();
  752. var normal = options.normal || BABYLON.Vector3.Up();
  753. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  754. var angle = options.angle || 0;
  755. // Getting correct rotation
  756. if (!normal) {
  757. var target = new BABYLON.Vector3(0, 0, 1);
  758. var camera = sourceMesh.getScene().activeCamera;
  759. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  760. normal = camera.globalPosition.subtract(cameraWorldTarget);
  761. }
  762. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  763. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  764. var pitch = Math.atan2(normal.y, len);
  765. // Matrix
  766. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  767. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  768. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  769. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  770. var vertexData = new BABYLON.VertexData();
  771. vertexData.indices = [];
  772. vertexData.positions = [];
  773. vertexData.normals = [];
  774. vertexData.uvs = [];
  775. var currentVertexDataIndex = 0;
  776. var extractDecalVector3 = function (indexId) {
  777. var vertexId = indices[indexId];
  778. var result = new BABYLON.PositionNormalVertex();
  779. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  780. // Send vector to decal local world
  781. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  782. // Get normal
  783. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  784. return result;
  785. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  786. var clip = function (vertices, axis) {
  787. if (vertices.length === 0) {
  788. return vertices;
  789. }
  790. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  791. var clipVertices = function (v0, v1) {
  792. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  793. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  794. };
  795. var result = new Array();
  796. for (var index = 0; index < vertices.length; index += 3) {
  797. var v1Out;
  798. var v2Out;
  799. var v3Out;
  800. var total = 0;
  801. var nV1, nV2, nV3, nV4;
  802. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  803. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  804. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  805. v1Out = d1 > 0;
  806. v2Out = d2 > 0;
  807. v3Out = d3 > 0;
  808. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  809. switch (total) {
  810. case 0:
  811. result.push(vertices[index]);
  812. result.push(vertices[index + 1]);
  813. result.push(vertices[index + 2]);
  814. break;
  815. case 1:
  816. if (v1Out) {
  817. nV1 = vertices[index + 1];
  818. nV2 = vertices[index + 2];
  819. nV3 = clipVertices(vertices[index], nV1);
  820. nV4 = clipVertices(vertices[index], nV2);
  821. }
  822. if (v2Out) {
  823. nV1 = vertices[index];
  824. nV2 = vertices[index + 2];
  825. nV3 = clipVertices(vertices[index + 1], nV1);
  826. nV4 = clipVertices(vertices[index + 1], nV2);
  827. result.push(nV3);
  828. result.push(nV2.clone());
  829. result.push(nV1.clone());
  830. result.push(nV2.clone());
  831. result.push(nV3.clone());
  832. result.push(nV4);
  833. break;
  834. }
  835. if (v3Out) {
  836. nV1 = vertices[index];
  837. nV2 = vertices[index + 1];
  838. nV3 = clipVertices(vertices[index + 2], nV1);
  839. nV4 = clipVertices(vertices[index + 2], nV2);
  840. }
  841. result.push(nV1.clone());
  842. result.push(nV2.clone());
  843. result.push(nV3);
  844. result.push(nV4);
  845. result.push(nV3.clone());
  846. result.push(nV2.clone());
  847. break;
  848. case 2:
  849. if (!v1Out) {
  850. nV1 = vertices[index].clone();
  851. nV2 = clipVertices(nV1, vertices[index + 1]);
  852. nV3 = clipVertices(nV1, vertices[index + 2]);
  853. result.push(nV1);
  854. result.push(nV2);
  855. result.push(nV3);
  856. }
  857. if (!v2Out) {
  858. nV1 = vertices[index + 1].clone();
  859. nV2 = clipVertices(nV1, vertices[index + 2]);
  860. nV3 = clipVertices(nV1, vertices[index]);
  861. result.push(nV1);
  862. result.push(nV2);
  863. result.push(nV3);
  864. }
  865. if (!v3Out) {
  866. nV1 = vertices[index + 2].clone();
  867. nV2 = clipVertices(nV1, vertices[index]);
  868. nV3 = clipVertices(nV1, vertices[index + 1]);
  869. result.push(nV1);
  870. result.push(nV2);
  871. result.push(nV3);
  872. }
  873. break;
  874. case 3:
  875. break;
  876. }
  877. }
  878. return result;
  879. };
  880. for (var index = 0; index < indices.length; index += 3) {
  881. var faceVertices = new Array();
  882. faceVertices.push(extractDecalVector3(index));
  883. faceVertices.push(extractDecalVector3(index + 1));
  884. faceVertices.push(extractDecalVector3(index + 2));
  885. // Clip
  886. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  887. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  888. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  889. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  890. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  891. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  892. if (faceVertices.length === 0) {
  893. continue;
  894. }
  895. // Add UVs and get back to world
  896. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  897. var vertex = faceVertices[vIndex];
  898. //TODO check for Int32Array
  899. vertexData.indices.push(currentVertexDataIndex);
  900. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  901. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  902. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  903. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  904. currentVertexDataIndex++;
  905. }
  906. }
  907. // Return mesh
  908. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  909. vertexData.applyToMesh(decal);
  910. decal.position = position.clone();
  911. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  912. return decal;
  913. };
  914. // Privates
  915. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  916. // extrusion geometry
  917. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  918. var tangents = path3D.getTangents();
  919. var normals = path3D.getNormals();
  920. var binormals = path3D.getBinormals();
  921. var distances = path3D.getDistances();
  922. var angle = 0;
  923. var returnScale = function () { return scale; };
  924. var returnRotation = function () { return rotation; };
  925. var rotate = custom ? rotateFunction : returnRotation;
  926. var scl = custom ? scaleFunction : returnScale;
  927. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  928. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  929. for (var i = 0; i < curve.length; i++) {
  930. var shapePath = new Array();
  931. var angleStep = rotate(i, distances[i]);
  932. var scaleRatio = scl(i, distances[i]);
  933. for (var p = 0; p < shape.length; p++) {
  934. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  935. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  936. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  937. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  938. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  939. shapePath[p] = rotated;
  940. }
  941. shapePaths[index] = shapePath;
  942. angle += angleStep;
  943. index++;
  944. }
  945. // cap
  946. var capPath = function (shapePath) {
  947. var pointCap = Array();
  948. var barycenter = BABYLON.Vector3.Zero();
  949. var i;
  950. for (i = 0; i < shapePath.length; i++) {
  951. barycenter.addInPlace(shapePath[i]);
  952. }
  953. barycenter.scaleInPlace(1 / shapePath.length);
  954. for (i = 0; i < shapePath.length; i++) {
  955. pointCap.push(barycenter);
  956. }
  957. return pointCap;
  958. };
  959. switch (cap) {
  960. case BABYLON.Mesh.NO_CAP:
  961. break;
  962. case BABYLON.Mesh.CAP_START:
  963. shapePaths[0] = capPath(shapePaths[2]);
  964. shapePaths[1] = shapePaths[2].slice(0);
  965. break;
  966. case BABYLON.Mesh.CAP_END:
  967. shapePaths[index] = shapePaths[index - 1];
  968. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  969. break;
  970. case BABYLON.Mesh.CAP_ALL:
  971. shapePaths[0] = capPath(shapePaths[2]);
  972. shapePaths[1] = shapePaths[2].slice(0);
  973. shapePaths[index] = shapePaths[index - 1];
  974. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  975. break;
  976. default:
  977. break;
  978. }
  979. return shapePaths;
  980. };
  981. var path3D;
  982. var pathArray;
  983. if (instance) {
  984. path3D = (instance.path3D).update(curve);
  985. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  986. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  987. return instance;
  988. }
  989. // extruded shape creation
  990. path3D = new BABYLON.Path3D(curve);
  991. var newShapePaths = new Array();
  992. cap = (cap < 0 || cap > 3) ? 0 : cap;
  993. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  994. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  995. extrudedGeneric.pathArray = pathArray;
  996. extrudedGeneric.path3D = path3D;
  997. extrudedGeneric.cap = cap;
  998. return extrudedGeneric;
  999. };
  1000. return MeshBuilder;
  1001. })();
  1002. BABYLON.MeshBuilder = MeshBuilder;
  1003. })(BABYLON || (BABYLON = {}));