babylon.meshBuilder.ts 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. module BABYLON {
  2. /**
  3. * Class containing static functions to help procedurally build meshes
  4. */
  5. export class MeshBuilder {
  6. private static updateSideOrientation(orientation?: number): number {
  7. if (orientation == Mesh.DOUBLESIDE) {
  8. return Mesh.DOUBLESIDE;
  9. }
  10. if (orientation === undefined || orientation === null) {
  11. return Mesh.FRONTSIDE;
  12. }
  13. return orientation;
  14. }
  15. /**
  16. * Creates a box mesh
  17. * * The parameter `size` sets the size (float) of each box side (default 1)
  18. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  19. * * 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)
  20. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  24. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  25. * @param name defines the name of the mesh
  26. * @param options defines the options used to create the mesh
  27. * @param scene defines the hosting scene
  28. * @returns the box mesh
  29. */
  30. public static CreateBox(name: string, options: { size?: number, width?: number, height?: number, depth?: number, faceUV?: Vector4[], faceColors?: Color4[], sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, updatable?: boolean }, scene: Nullable<Scene> = null): Mesh {
  31. var box = new Mesh(name, scene);
  32. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  33. box._originalBuilderSideOrientation = options.sideOrientation;
  34. var vertexData = VertexData.CreateBox(options);
  35. vertexData.applyToMesh(box, options.updatable);
  36. return box;
  37. }
  38. /**
  39. * Creates a sphere mesh
  40. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  41. * * 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`)
  42. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  43. * * 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
  44. * * 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)
  45. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  48. * @param name defines the name of the mesh
  49. * @param options defines the options used to create the mesh
  50. * @param scene defines the hosting scene
  51. * @returns the sphere mesh
  52. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53. */
  54. public static CreateSphere(name: string, options: { segments?: number, diameter?: number, diameterX?: number, diameterY?: number, diameterZ?: number, arc?: number, slice?: number, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, updatable?: boolean }, scene: any): Mesh {
  55. var sphere = new Mesh(name, scene);
  56. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57. sphere._originalBuilderSideOrientation = options.sideOrientation;
  58. var vertexData = VertexData.CreateSphere(options);
  59. vertexData.applyToMesh(sphere, options.updatable);
  60. return sphere;
  61. }
  62. /**
  63. * Creates a plane polygonal mesh. By default, this is a disc
  64. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  65. * * 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
  66. * * 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
  67. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  69. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70. * @param name defines the name of the mesh
  71. * @param options defines the options used to create the mesh
  72. * @param scene defines the hosting scene
  73. * @returns the plane polygonal mesh
  74. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  75. */
  76. public static CreateDisc(name: string, options: { radius?: number, tessellation?: number, arc?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: Nullable<Scene> = null): Mesh {
  77. var disc = new Mesh(name, scene);
  78. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  79. disc._originalBuilderSideOrientation = options.sideOrientation;
  80. var vertexData = VertexData.CreateDisc(options);
  81. vertexData.applyToMesh(disc, options.updatable);
  82. return disc;
  83. }
  84. /**
  85. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  86. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  87. * * 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`)
  88. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  89. * * 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
  90. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  91. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  92. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  93. * @param name defines the name of the mesh
  94. * @param options defines the options used to create the mesh
  95. * @param scene defines the hosting scene
  96. * @returns the icosahedron mesh
  97. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  98. */
  99. public static CreateIcoSphere(name: string, options: { radius?: number, radiusX?: number, radiusY?: number, radiusZ?: number, flat?: boolean, subdivisions?: number, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, updatable?: boolean }, scene: Scene): Mesh {
  100. var sphere = new Mesh(name, scene);
  101. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  102. sphere._originalBuilderSideOrientation = options.sideOrientation;
  103. var vertexData = VertexData.CreateIcoSphere(options);
  104. vertexData.applyToMesh(sphere, options.updatable);
  105. return sphere;
  106. };
  107. /**
  108. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  109. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  110. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  111. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  112. * * 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
  113. * * 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
  114. * * 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
  115. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  116. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  117. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  118. * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones
  119. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  120. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  121. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  122. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  123. * @param name defines the name of the mesh
  124. * @param options defines the options used to create the mesh
  125. * @param scene defines the hosting scene
  126. * @returns the ribbon mesh
  127. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  128. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  129. */
  130. public static CreateRibbon(name: string, options: { pathArray: Vector3[][], closeArray?: boolean, closePath?: boolean, offset?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, instance?: Mesh, invertUV?: boolean, uvs?: Vector2[], colors?: Color4[] }, scene: Nullable<Scene> = null): Mesh {
  131. var pathArray = options.pathArray;
  132. var closeArray = options.closeArray;
  133. var closePath = options.closePath;
  134. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  135. var instance = options.instance;
  136. var updatable = options.updatable;
  137. if (instance) { // existing ribbon instance update
  138. // positionFunction : ribbon case
  139. // only pathArray and sideOrientation parameters are taken into account for positions update
  140. Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Tmp.Vector3[0]); // minimum
  141. Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, Tmp.Vector3[1]);
  142. var positionFunction = (positions: FloatArray) => {
  143. var minlg = pathArray[0].length;
  144. var i = 0;
  145. var ns = ((<Mesh>instance)._originalBuilderSideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  146. for (var si = 1; si <= ns; si++) {
  147. for (var p = 0; p < pathArray.length; p++) {
  148. var path = pathArray[p];
  149. var l = path.length;
  150. minlg = (minlg < l) ? minlg : l;
  151. var j = 0;
  152. while (j < minlg) {
  153. positions[i] = path[j].x;
  154. positions[i + 1] = path[j].y;
  155. positions[i + 2] = path[j].z;
  156. if (path[j].x < Tmp.Vector3[0].x) {
  157. Tmp.Vector3[0].x = path[j].x;
  158. }
  159. if (path[j].x > Tmp.Vector3[1].x) {
  160. Tmp.Vector3[1].x = path[j].x;
  161. }
  162. if (path[j].y < Tmp.Vector3[0].y) {
  163. Tmp.Vector3[0].y = path[j].y;
  164. }
  165. if (path[j].y > Tmp.Vector3[1].y) {
  166. Tmp.Vector3[1].y = path[j].y;
  167. }
  168. if (path[j].z < Tmp.Vector3[0].z) {
  169. Tmp.Vector3[0].z = path[j].z;
  170. }
  171. if (path[j].z > Tmp.Vector3[1].z) {
  172. Tmp.Vector3[1].z = path[j].z;
  173. }
  174. j++;
  175. i += 3;
  176. }
  177. if ((<any>instance)._closePath) {
  178. positions[i] = path[0].x;
  179. positions[i + 1] = path[0].y;
  180. positions[i + 2] = path[0].z;
  181. i += 3;
  182. }
  183. }
  184. }
  185. };
  186. var positions = <FloatArray>instance.getVerticesData(VertexBuffer.PositionKind);
  187. positionFunction(positions);
  188. instance._boundingInfo = new BoundingInfo(Tmp.Vector3[0], Tmp.Vector3[1]);
  189. instance._boundingInfo.update(instance._worldMatrix);
  190. instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  191. if (options.colors) {
  192. var colors = <FloatArray>instance.getVerticesData(VertexBuffer.ColorKind);
  193. for (var c = 0; c < options.colors.length; c++) {
  194. colors[c * 4] = options.colors[c].r;
  195. colors[c * 4 + 1] = options.colors[c].g;
  196. colors[c * 4 + 2] = options.colors[c].b;
  197. colors[c * 4 + 3] = options.colors[c].a;
  198. }
  199. instance.updateVerticesData(VertexBuffer.ColorKind, colors, false, false);
  200. }
  201. if (options.uvs) {
  202. var uvs = <FloatArray>instance.getVerticesData(VertexBuffer.UVKind);
  203. for (var i = 0; i < options.uvs.length; i++) {
  204. uvs[i * 2] = options.uvs[i].x;
  205. uvs[i * 2 + 1] = options.uvs[i].y;
  206. }
  207. instance.updateVerticesData(VertexBuffer.UVKind, uvs, false, false);
  208. }
  209. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  210. var indices = instance.getIndices();
  211. var normals = <FloatArray>instance.getVerticesData(VertexBuffer.NormalKind);
  212. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  213. VertexData.ComputeNormals(positions, indices, normals, params);
  214. if ((<any>instance)._closePath) {
  215. var indexFirst: number = 0;
  216. var indexLast: number = 0;
  217. for (var p = 0; p < pathArray.length; p++) {
  218. indexFirst = (<any>instance)._idx[p] * 3;
  219. if (p + 1 < pathArray.length) {
  220. indexLast = ((<any>instance)._idx[p + 1] - 1) * 3;
  221. }
  222. else {
  223. indexLast = normals.length - 3;
  224. }
  225. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  226. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  227. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  228. normals[indexLast] = normals[indexFirst];
  229. normals[indexLast + 1] = normals[indexFirst + 1];
  230. normals[indexLast + 2] = normals[indexFirst + 2];
  231. }
  232. }
  233. if (!(instance.areNormalsFrozen)) {
  234. instance.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  235. }
  236. }
  237. return instance;
  238. }
  239. else { // new ribbon creation
  240. var ribbon = new Mesh(name, scene);
  241. ribbon._originalBuilderSideOrientation = sideOrientation;
  242. var vertexData = VertexData.CreateRibbon(options);
  243. if (closePath) {
  244. (<any>ribbon)._idx = (<any>vertexData)._idx;
  245. }
  246. (<any>ribbon)._closePath = closePath;
  247. (<any>ribbon)._closeArray = closeArray;
  248. vertexData.applyToMesh(ribbon, updatable);
  249. return ribbon;
  250. }
  251. }
  252. /**
  253. * Creates a cylinder or a cone mesh
  254. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  255. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  256. * * 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.
  257. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  258. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  259. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  260. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  261. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  262. * * 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).
  263. * * 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
  264. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  265. * * 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
  266. * * 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.
  267. * * If `enclose` is false, a ring surface is one element.
  268. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  269. * * 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
  270. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  271. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  272. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  273. * @param name defines the name of the mesh
  274. * @param options defines the options used to create the mesh
  275. * @param scene defines the hosting scene
  276. * @returns the cylinder mesh
  277. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  278. */
  279. public static CreateCylinder(name: string, options: { height?: number, diameterTop?: number, diameterBottom?: number, diameter?: number, tessellation?: number, subdivisions?: number, arc?: number, faceColors?: Color4[], faceUV?: Vector4[], updatable?: boolean, hasRings?: boolean, enclose?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: any): Mesh {
  280. var cylinder = new Mesh(name, scene);
  281. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  282. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  283. var vertexData = VertexData.CreateCylinder(options);
  284. vertexData.applyToMesh(cylinder, options.updatable);
  285. return cylinder;
  286. }
  287. /**
  288. * Creates a torus mesh
  289. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  290. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  291. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  292. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  293. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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. * @param name defines the name of the mesh
  296. * @param options defines the options used to create the mesh
  297. * @param scene defines the hosting scene
  298. * @returns the torus mesh
  299. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  300. */
  301. public static CreateTorus(name: string, options: { diameter?: number, thickness?: number, tessellation?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: any): Mesh {
  302. var torus = new Mesh(name, scene);
  303. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  304. torus._originalBuilderSideOrientation = options.sideOrientation;
  305. var vertexData = VertexData.CreateTorus(options);
  306. vertexData.applyToMesh(torus, options.updatable);
  307. return torus;
  308. }
  309. /**
  310. * Creates a torus knot mesh
  311. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  312. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  313. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  314. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  315. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  316. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  317. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  318. * @param name defines the name of the mesh
  319. * @param options defines the options used to create the mesh
  320. * @param scene defines the hosting scene
  321. * @returns the torus knot mesh
  322. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  323. */
  324. public static CreateTorusKnot(name: string, options: { radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, p?: number, q?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: any): Mesh {
  325. var torusKnot = new Mesh(name, scene);
  326. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  327. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  328. var vertexData = VertexData.CreateTorusKnot(options);
  329. vertexData.applyToMesh(torusKnot, options.updatable);
  330. return torusKnot;
  331. }
  332. /**
  333. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  334. * * 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
  335. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  336. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  337. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  338. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  339. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  340. * * 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
  341. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  342. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  343. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  344. * @param name defines the name of the new line system
  345. * @param options defines the options used to create the line system
  346. * @param scene defines the hosting scene
  347. * @returns a new line system mesh
  348. */
  349. public static CreateLineSystem(name: string, options: { lines: Vector3[][], updatable?: boolean, instance?: Nullable<LinesMesh>, colors?: Nullable<Color4[][]>, useVertexAlpha?: boolean }, scene: Nullable<Scene>): LinesMesh {
  350. var instance = options.instance;
  351. var lines = options.lines;
  352. var colors = options.colors;
  353. if (instance) { // lines update
  354. var positions = instance.getVerticesData(VertexBuffer.PositionKind)!;
  355. var vertexColor;
  356. var lineColors;
  357. if (colors) {
  358. vertexColor = instance.getVerticesData(VertexBuffer.ColorKind)!;
  359. }
  360. var i = 0;
  361. var c = 0;
  362. for (var l = 0; l < lines.length; l++) {
  363. var points = lines[l];
  364. for (var p = 0; p < points.length; p++) {
  365. positions[i] = points[p].x;
  366. positions[i + 1] = points[p].y;
  367. positions[i + 2] = points[p].z;
  368. if (colors && vertexColor) {
  369. lineColors = colors[l];
  370. vertexColor[c] = lineColors[p].r;
  371. vertexColor[c + 1] = lineColors[p].g;
  372. vertexColor[c + 2] = lineColors[p].b;
  373. vertexColor[c + 3] = lineColors[p].a;
  374. c += 4;
  375. }
  376. i += 3;
  377. }
  378. }
  379. instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  380. if (colors && vertexColor) {
  381. instance.updateVerticesData(VertexBuffer.ColorKind, vertexColor, false, false)
  382. }
  383. return instance;
  384. }
  385. // line system creation
  386. var useVertexColor = (colors) ? true : false;
  387. var lineSystem = new LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  388. var vertexData = VertexData.CreateLineSystem(options);
  389. vertexData.applyToMesh(lineSystem, options.updatable);
  390. return lineSystem;
  391. }
  392. /**
  393. * Creates a line mesh
  394. * 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
  395. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  396. * * The parameter `points` is an array successive Vector3
  397. * * 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
  398. * * The optional parameter `colors` is an array of successive Color4, one per line point
  399. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  400. * * When updating an instance, remember that only point positions can change, not the number of points
  401. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  402. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  403. * @param name defines the name of the new line system
  404. * @param options defines the options used to create the line system
  405. * @param scene defines the hosting scene
  406. * @returns a new line mesh
  407. */
  408. public static CreateLines(name: string, options: { points: Vector3[], updatable?: boolean, instance?: Nullable<LinesMesh>, colors?: Color4[], useVertexAlpha?: boolean }, scene: Nullable<Scene> = null): LinesMesh {
  409. var colors = (options.colors) ? [options.colors] : null;
  410. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  411. return lines;
  412. }
  413. /**
  414. * Creates a dashed line mesh
  415. * * 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
  416. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  417. * * The parameter `points` is an array successive Vector3
  418. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  419. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  420. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  421. * * 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
  422. * * When updating an instance, remember that only point positions can change, not the number of points
  423. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  424. * @param name defines the name of the mesh
  425. * @param options defines the options used to create the mesh
  426. * @param scene defines the hosting scene
  427. * @returns the dashed line mesh
  428. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  429. */
  430. public static CreateDashedLines(name: string, options: { points: Vector3[], dashSize?: number, gapSize?: number, dashNb?: number, updatable?: boolean, instance?: LinesMesh }, scene: Nullable<Scene> = null): LinesMesh {
  431. var points = options.points;
  432. var instance = options.instance;
  433. var gapSize = options.gapSize || 1;
  434. var dashSize = options.dashSize || 3;
  435. if (instance) { // dashed lines update
  436. var positionFunction = (positions: FloatArray): void => {
  437. var curvect = Vector3.Zero();
  438. var nbSeg = positions.length / 6;
  439. var lg = 0;
  440. var nb = 0;
  441. var shft = 0;
  442. var dashshft = 0;
  443. var curshft = 0;
  444. var p = 0;
  445. var i = 0;
  446. var j = 0;
  447. for (i = 0; i < points.length - 1; i++) {
  448. points[i + 1].subtractToRef(points[i], curvect);
  449. lg += curvect.length();
  450. }
  451. shft = lg / nbSeg;
  452. dashshft = (<any>instance).dashSize * shft / ((<any>instance).dashSize + (<any>instance).gapSize);
  453. for (i = 0; i < points.length - 1; i++) {
  454. points[i + 1].subtractToRef(points[i], curvect);
  455. nb = Math.floor(curvect.length() / shft);
  456. curvect.normalize();
  457. j = 0;
  458. while (j < nb && p < positions.length) {
  459. curshft = shft * j;
  460. positions[p] = points[i].x + curshft * curvect.x;
  461. positions[p + 1] = points[i].y + curshft * curvect.y;
  462. positions[p + 2] = points[i].z + curshft * curvect.z;
  463. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  464. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  465. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  466. p += 6;
  467. j++;
  468. }
  469. }
  470. while (p < positions.length) {
  471. positions[p] = points[i].x;
  472. positions[p + 1] = points[i].y;
  473. positions[p + 2] = points[i].z;
  474. p += 3;
  475. }
  476. };
  477. instance.updateMeshPositions(positionFunction, false);
  478. return instance;
  479. }
  480. // dashed lines creation
  481. var dashedLines = new LinesMesh(name, scene);
  482. var vertexData = VertexData.CreateDashedLines(options);
  483. vertexData.applyToMesh(dashedLines, options.updatable);
  484. (<any>dashedLines).dashSize = dashSize;
  485. (<any>dashedLines).gapSize = gapSize;
  486. return dashedLines;
  487. }
  488. /**
  489. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  490. * * 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 extruded along the Z axis.
  491. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  492. * * 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.
  493. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  494. * * 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
  495. * * 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
  496. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  497. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  498. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  499. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  500. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  501. * @param name defines the name of the mesh
  502. * @param options defines the options used to create the mesh
  503. * @param scene defines the hosting scene
  504. * @returns the extruded shape mesh
  505. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  506. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  507. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  508. */
  509. public static ExtrudeShape(name: string, options: { shape: Vector3[], path: Vector3[], scale?: number, rotation?: number, cap?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, instance?: Mesh, invertUV?: boolean }, scene: Nullable<Scene> = null): Mesh {
  510. var path = options.path;
  511. var shape = options.shape;
  512. var scale = options.scale || 1;
  513. var rotation = options.rotation || 0;
  514. var cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  515. var updatable = options.updatable;
  516. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  517. var instance = options.instance || null;
  518. var invertUV = options.invertUV || false;
  519. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);
  520. }
  521. /**
  522. * Creates an custom extruded shape mesh.
  523. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  524. * * 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 extruded along the Z axis.
  525. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  526. * * 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 and the distance of this point from the begining of the path
  527. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  528. * * 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 and the distance of this point from the begining of the path
  529. * * It must returns a float value that will be the scale value applied to the shape on each path point
  530. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  531. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  532. * * 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
  533. * * 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
  534. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  535. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  536. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  537. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  538. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  539. * @param name defines the name of the mesh
  540. * @param options defines the options used to create the mesh
  541. * @param scene defines the hosting scene
  542. * @returns the custom extruded shape mesh
  543. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  544. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  545. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  546. */
  547. public static ExtrudeShapeCustom(name: string, options: { shape: Vector3[], path: Vector3[], scaleFunction?: any, rotationFunction?: any, ribbonCloseArray?: boolean, ribbonClosePath?: boolean, cap?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, instance?: Mesh, invertUV?: boolean }, scene: Scene): Mesh {
  548. var path = options.path;
  549. var shape = options.shape;
  550. var scaleFunction = options.scaleFunction || (() => { return 1; });
  551. var rotationFunction = options.rotationFunction || (() => { return 0; });
  552. var ribbonCloseArray = options.ribbonCloseArray || false;
  553. var ribbonClosePath = options.ribbonClosePath || false;
  554. var cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  555. var updatable = options.updatable;
  556. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  557. var instance = options.instance;
  558. var invertUV = options.invertUV || false;
  559. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);
  560. }
  561. /**
  562. * Creates lathe mesh.
  563. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  564. * * 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 rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  565. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  566. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  567. * * 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
  568. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  569. * * 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
  570. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  571. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  572. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  573. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  574. * @param name defines the name of the mesh
  575. * @param options defines the options used to create the mesh
  576. * @param scene defines the hosting scene
  577. * @returns the lathe mesh
  578. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  579. */
  580. public static CreateLathe(name: string, options: { shape: Vector3[], radius?: number, tessellation?: number, arc?: number, closed?: boolean, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, cap?: number, invertUV?: boolean }, scene: Scene): Mesh {
  581. var arc: number = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  582. var closed: boolean = (options.closed === undefined) ? true : options.closed;
  583. var shape = options.shape;
  584. var radius = options.radius || 1;
  585. var tessellation = options.tessellation || 64;
  586. var updatable = options.updatable;
  587. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  588. var cap = options.cap || Mesh.NO_CAP;
  589. var pi2 = Math.PI * 2;
  590. var paths = new Array();
  591. var invertUV = options.invertUV || false;
  592. var i = 0;
  593. var p = 0;
  594. var step = pi2 / tessellation * arc;
  595. var rotated;
  596. var path = new Array<Vector3>();;
  597. for (i = 0; i <= tessellation; i++) {
  598. var path: Vector3[] = [];
  599. if (cap == Mesh.CAP_START || cap == Mesh.CAP_ALL) {
  600. path.push(new Vector3(0, shape[0].y, 0));
  601. path.push(new Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  602. }
  603. for (p = 0; p < shape.length; p++) {
  604. rotated = new Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  605. path.push(rotated);
  606. }
  607. if (cap == Mesh.CAP_END || cap == Mesh.CAP_ALL) {
  608. path.push(new 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));
  609. path.push(new Vector3(0, shape[shape.length - 1].y, 0));
  610. }
  611. paths.push(path);
  612. }
  613. // lathe ribbon
  614. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  615. return lathe;
  616. }
  617. /**
  618. * Creates a plane mesh
  619. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  620. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  621. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  622. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  623. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  624. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  625. * @param name defines the name of the mesh
  626. * @param options defines the options used to create the mesh
  627. * @param scene defines the hosting scene
  628. * @returns the plane mesh
  629. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  630. */
  631. public static CreatePlane(name: string, options: { size?: number, width?: number, height?: number, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, updatable?: boolean, sourcePlane?: Plane }, scene: Scene): Mesh {
  632. var plane = new Mesh(name, scene);
  633. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  634. plane._originalBuilderSideOrientation = options.sideOrientation;
  635. var vertexData = VertexData.CreatePlane(options);
  636. vertexData.applyToMesh(plane, options.updatable);
  637. if (options.sourcePlane) {
  638. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  639. var product = Math.acos(Vector3.Dot(options.sourcePlane.normal, Axis.Z));
  640. var vectorProduct = Vector3.Cross(Axis.Z, options.sourcePlane.normal);
  641. plane.rotate(vectorProduct, product);
  642. }
  643. return plane;
  644. }
  645. /**
  646. * Creates a ground mesh
  647. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  648. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  649. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  650. * @param name defines the name of the mesh
  651. * @param options defines the options used to create the mesh
  652. * @param scene defines the hosting scene
  653. * @returns the ground mesh
  654. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  655. */
  656. public static CreateGround(name: string, options: { width?: number, height?: number, subdivisions?: number, subdivisionsX?: number, subdivisionsY?: number, updatable?: boolean }, scene: any): Mesh {
  657. var ground = new GroundMesh(name, scene);
  658. ground._setReady(false);
  659. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  660. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  661. ground._width = options.width || 1;
  662. ground._height = options.height || 1;
  663. ground._maxX = ground._width / 2;
  664. ground._maxZ = ground._height / 2;
  665. ground._minX = -ground._maxX;
  666. ground._minZ = -ground._maxZ;
  667. var vertexData = VertexData.CreateGround(options);
  668. vertexData.applyToMesh(ground, options.updatable);
  669. ground._setReady(true);
  670. return ground;
  671. }
  672. /**
  673. * Creates a tiled ground mesh
  674. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  675. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  676. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  677. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  678. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  679. * @param name defines the name of the mesh
  680. * @param options defines the options used to create the mesh
  681. * @param scene defines the hosting scene
  682. * @returns the tiled ground mesh
  683. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  684. */
  685. public static CreateTiledGround(name: string, options: { xmin: number, zmin: number, xmax: number, zmax: number, subdivisions?: { w: number; h: number; }, precision?: { w: number; h: number; }, updatable?: boolean }, scene: Scene): Mesh {
  686. var tiledGround = new Mesh(name, scene);
  687. var vertexData = VertexData.CreateTiledGround(options);
  688. vertexData.applyToMesh(tiledGround, options.updatable);
  689. return tiledGround;
  690. }
  691. /**
  692. * Creates a ground mesh from a height map
  693. * * The parameter `url` sets the URL of the height map image resource.
  694. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  695. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  696. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  697. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  698. * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  699. * * 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).
  700. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  701. * @param name defines the name of the mesh
  702. * @param url defines the url to the height map
  703. * @param options defines the options used to create the mesh
  704. * @param scene defines the hosting scene
  705. * @returns the ground mesh
  706. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  707. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  708. */
  709. public static CreateGroundFromHeightMap(name: string, url: string, options: { width?: number, height?: number, subdivisions?: number, minHeight?: number, maxHeight?: number, colorFilter?: Color3, updatable?: boolean, onReady?: (mesh: GroundMesh) => void }, scene: Scene): GroundMesh {
  710. var width = options.width || 10.0;
  711. var height = options.height || 10.0;
  712. var subdivisions = options.subdivisions || 1 | 0;
  713. var minHeight = options.minHeight || 0.0;
  714. var maxHeight = options.maxHeight || 1.0;
  715. var filter = options.colorFilter || new Color3(0.3, 0.59, 0.11);
  716. var updatable = options.updatable;
  717. var onReady = options.onReady;
  718. var ground = new GroundMesh(name, scene);
  719. ground._subdivisionsX = subdivisions;
  720. ground._subdivisionsY = subdivisions;
  721. ground._width = width;
  722. ground._height = height;
  723. ground._maxX = ground._width / 2.0;
  724. ground._maxZ = ground._height / 2.0;
  725. ground._minX = -ground._maxX;
  726. ground._minZ = -ground._maxZ;
  727. ground._setReady(false);
  728. var onload = (img: HTMLImageElement) => {
  729. // Getting height map data
  730. var canvas = document.createElement("canvas");
  731. var context = canvas.getContext("2d");
  732. if (!context) {
  733. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  734. }
  735. if (scene.isDisposed) {
  736. return;
  737. }
  738. var bufferWidth = img.width;
  739. var bufferHeight = img.height;
  740. canvas.width = bufferWidth;
  741. canvas.height = bufferHeight;
  742. context.drawImage(img, 0, 0);
  743. // Create VertexData from map data
  744. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  745. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, bufferWidth, bufferHeight).data);
  746. var vertexData = VertexData.CreateGroundFromHeightMap({
  747. width: width, height: height,
  748. subdivisions: subdivisions,
  749. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  750. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  751. });
  752. vertexData.applyToMesh(ground, updatable);
  753. //execute ready callback, if set
  754. if (onReady) {
  755. onReady(ground);
  756. }
  757. ground._setReady(true);
  758. };
  759. Tools.LoadImage(url, onload, () => { }, scene.database);
  760. return ground;
  761. }
  762. /**
  763. * Creates a polygon mesh
  764. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  765. * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  766. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  767. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  768. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4)
  769. * * Remember you can only change the shape positions, not their number when updating a polygon
  770. * @param name defines the name of the mesh
  771. * @param options defines the options used to create the mesh
  772. * @param scene defines the hosting scene
  773. * @returns the polygon mesh
  774. */
  775. public static CreatePolygon(name: string, options: { shape: Vector3[], holes?: Vector3[][], depth?: number, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: Scene): Mesh {
  776. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  777. var shape = options.shape;
  778. var holes = options.holes || [];
  779. var depth = options.depth || 0;
  780. var contours: Array<Vector2> = [];
  781. var hole: Array<Vector2> = [];
  782. for (var i = 0; i < shape.length; i++) {
  783. contours[i] = new Vector2(shape[i].x, shape[i].z);
  784. }
  785. var epsilon = 0.00000001;
  786. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  787. contours.pop();
  788. }
  789. var polygonTriangulation = new PolygonMeshBuilder(name, contours, scene);
  790. for (var hNb = 0; hNb < holes.length; hNb++) {
  791. hole = [];
  792. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  793. hole.push(new Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  794. }
  795. polygonTriangulation.addHole(hole);
  796. }
  797. var polygon = polygonTriangulation.build(options.updatable, depth);
  798. polygon._originalBuilderSideOrientation = options.sideOrientation;
  799. var vertexData = VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  800. vertexData.applyToMesh(polygon, options.updatable);
  801. return polygon;
  802. };
  803. /**
  804. * Creates an extruded polygon mesh, with depth in the Y direction.
  805. * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements)
  806. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  807. * @param name defines the name of the mesh
  808. * @param options defines the options used to create the mesh
  809. * @param scene defines the hosting scene
  810. * @returns the polygon mesh
  811. */
  812. public static ExtrudePolygon(name: string, options: { shape: Vector3[], holes?: Vector3[][], depth?: number, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: Scene): Mesh {
  813. return MeshBuilder.CreatePolygon(name, options, scene);
  814. };
  815. /**
  816. * Creates a tube mesh.
  817. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  818. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  819. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  820. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  821. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  822. * * 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. It must return a radius value (positive float)
  823. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  824. * * 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
  825. * * 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
  826. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  827. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  828. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  829. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  830. * @param name defines the name of the mesh
  831. * @param options defines the options used to create the mesh
  832. * @param scene defines the hosting scene
  833. * @returns the tube mesh
  834. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  835. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  836. */
  837. public static CreateTube(name: string, options: { path: Vector3[], radius?: number, tessellation?: number, radiusFunction?: { (i: number, distance: number): number; }, cap?: number, arc?: number, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4, instance?: Mesh, invertUV?: boolean }, scene: Scene): Mesh {
  838. var path = options.path;
  839. var instance = options.instance;
  840. var radius = 1.0;
  841. if (instance) {
  842. radius = (<any>instance).radius;
  843. }
  844. if (options.radius !== undefined) {
  845. radius = options.radius;
  846. };
  847. var tessellation = options.tessellation || 64 | 0;
  848. var radiusFunction = options.radiusFunction || null;
  849. var cap = options.cap || Mesh.NO_CAP;
  850. var invertUV = options.invertUV || false;
  851. var updatable = options.updatable;
  852. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  853. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  854. // tube geometry
  855. var tubePathArray = (path: Vector3[], path3D: Path3D, circlePaths: Vector3[][], radius: number, tessellation: number,
  856. radiusFunction: Nullable<{ (i: number, distance: number): number; }>, cap: number, arc: number) => {
  857. var tangents = path3D.getTangents();
  858. var normals = path3D.getNormals();
  859. var distances = path3D.getDistances();
  860. var pi2 = Math.PI * 2;
  861. var step = pi2 / tessellation * arc;
  862. var returnRadius: { (i: number, distance: number): number; } = () => radius;
  863. var radiusFunctionFinal: { (i: number, distance: number): number; } = radiusFunction || returnRadius;
  864. var circlePath: Vector3[];
  865. var rad: number;
  866. var normal: Vector3;
  867. var rotated: Vector3;
  868. var rotationMatrix: Matrix = Tmp.Matrix[0];
  869. var index = (cap === Mesh._NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  870. for (var i = 0; i < path.length; i++) {
  871. rad = radiusFunctionFinal(i, distances[i]); // current radius
  872. circlePath = Array<Vector3>(); // current circle array
  873. normal = normals[i]; // current normal
  874. for (var t = 0; t < tessellation; t++) {
  875. Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  876. rotated = circlePath[t] ? circlePath[t] : Vector3.Zero();
  877. Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  878. rotated.scaleInPlace(rad).addInPlace(path[i]);
  879. circlePath[t] = rotated;
  880. }
  881. circlePaths[index] = circlePath;
  882. index++;
  883. }
  884. // cap
  885. var capPath = (nbPoints: number, pathIndex: number): Array<Vector3> => {
  886. var pointCap = Array<Vector3>();
  887. for (var i = 0; i < nbPoints; i++) {
  888. pointCap.push(path[pathIndex]);
  889. }
  890. return pointCap;
  891. };
  892. switch (cap) {
  893. case Mesh.NO_CAP:
  894. break;
  895. case Mesh.CAP_START:
  896. circlePaths[0] = capPath(tessellation, 0);
  897. circlePaths[1] = circlePaths[2].slice(0);
  898. break;
  899. case Mesh.CAP_END:
  900. circlePaths[index] = circlePaths[index - 1].slice(0);
  901. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  902. break;
  903. case Mesh.CAP_ALL:
  904. circlePaths[0] = capPath(tessellation, 0);
  905. circlePaths[1] = circlePaths[2].slice(0);
  906. circlePaths[index] = circlePaths[index - 1].slice(0);
  907. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  908. break;
  909. default:
  910. break;
  911. }
  912. return circlePaths;
  913. };
  914. var path3D;
  915. var pathArray;
  916. if (instance) { // tube update
  917. var arc = options.arc || (<any>instance).arc;
  918. path3D = ((<any>instance).path3D).update(path);
  919. pathArray = tubePathArray(path, path3D, (<any>instance).pathArray, radius, (<any>instance).tessellation, radiusFunction, (<any>instance).cap, arc);
  920. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  921. (<any>instance).path3D = path3D;
  922. (<any>instance).pathArray = pathArray;
  923. (<any>instance).arc = arc;
  924. (<any>instance).radius = radius;
  925. return instance;
  926. }
  927. // tube creation
  928. path3D = <any>new Path3D(path);
  929. var newPathArray = new Array<Array<Vector3>>();
  930. cap = (cap < 0 || cap > 3) ? 0 : cap;
  931. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  932. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  933. (<any>tube).pathArray = pathArray;
  934. (<any>tube).path3D = path3D;
  935. (<any>tube).tessellation = tessellation;
  936. (<any>tube).cap = cap;
  937. (<any>tube).arc = options.arc;
  938. (<any>tube).radius = radius;
  939. return tube;
  940. }
  941. /**
  942. * Creates a polyhedron mesh
  943. * * 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 to choose the wanted type
  944. * * The parameter `size` (positive float, default 1) sets the polygon size
  945. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  946. * * 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`
  947. * * 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
  948. * * 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)`)
  949. * * 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
  950. * * 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
  951. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  952. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  953. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  954. * @param name defines the name of the mesh
  955. * @param options defines the options used to create the mesh
  956. * @param scene defines the hosting scene
  957. * @returns the polyhedron mesh
  958. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  959. */
  960. public static CreatePolyhedron(name: string, options: { type?: number, size?: number, sizeX?: number, sizeY?: number, sizeZ?: number, custom?: any, faceUV?: Vector4[], faceColors?: Color4[], flat?: boolean, updatable?: boolean, sideOrientation?: number, frontUVs?: Vector4, backUVs?: Vector4 }, scene: Scene): Mesh {
  961. var polyhedron = new Mesh(name, scene);
  962. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  963. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  964. var vertexData = VertexData.CreatePolyhedron(options);
  965. vertexData.applyToMesh(polyhedron, options.updatable);
  966. return polyhedron;
  967. }
  968. /**
  969. * Creates a decal mesh.
  970. * 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
  971. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  972. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  973. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  974. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  975. * @param name defines the name of the mesh
  976. * @param sourceMesh defines the mesh where the decal must be applied
  977. * @param options defines the options used to create the mesh
  978. * @param scene defines the hosting scene
  979. * @returns the decal mesh
  980. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  981. */
  982. public static CreateDecal(name: string, sourceMesh: AbstractMesh, options: { position?: Vector3, normal?: Vector3, size?: Vector3, angle?: number }): Mesh {
  983. var indices = <IndicesArray>sourceMesh.getIndices();
  984. var positions = sourceMesh.getVerticesData(VertexBuffer.PositionKind);
  985. var normals = sourceMesh.getVerticesData(VertexBuffer.NormalKind);
  986. var position = options.position || Vector3.Zero();
  987. var normal = options.normal || Vector3.Up();
  988. var size = options.size || Vector3.One();
  989. var angle = options.angle || 0;
  990. // Getting correct rotation
  991. if (!normal) {
  992. var target = new Vector3(0, 0, 1);
  993. var camera = <Camera>sourceMesh.getScene().activeCamera;
  994. var cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  995. normal = camera.globalPosition.subtract(cameraWorldTarget);
  996. }
  997. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  998. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  999. var pitch = Math.atan2(normal.y, len);
  1000. // Matrix
  1001. var decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));
  1002. var inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);
  1003. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  1004. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  1005. var vertexData = new VertexData();
  1006. vertexData.indices = [];
  1007. vertexData.positions = [];
  1008. vertexData.normals = [];
  1009. vertexData.uvs = [];
  1010. var currentVertexDataIndex = 0;
  1011. var extractDecalVector3 = (indexId: number): PositionNormalVertex => {
  1012. var result = new PositionNormalVertex();
  1013. if (!indices || !positions || !normals) {
  1014. return result;
  1015. }
  1016. var vertexId = indices[indexId];
  1017. result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  1018. // Send vector to decal local world
  1019. result.position = Vector3.TransformCoordinates(result.position, transformMatrix);
  1020. // Get normal
  1021. result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  1022. result.normal = Vector3.TransformNormal(result.normal, transformMatrix);
  1023. return result;
  1024. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  1025. var clip = (vertices: PositionNormalVertex[], axis: Vector3): PositionNormalVertex[] => {
  1026. if (vertices.length === 0) {
  1027. return vertices;
  1028. }
  1029. var clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));
  1030. var clipVertices = (v0: PositionNormalVertex, v1: PositionNormalVertex): PositionNormalVertex => {
  1031. var clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  1032. return new PositionNormalVertex(
  1033. Vector3.Lerp(v0.position, v1.position, clipFactor),
  1034. Vector3.Lerp(v0.normal, v1.normal, clipFactor)
  1035. );
  1036. };
  1037. var result = new Array<PositionNormalVertex>();
  1038. for (var index = 0; index < vertices.length; index += 3) {
  1039. var v1Out: boolean;
  1040. var v2Out: boolean;
  1041. var v3Out: boolean;
  1042. var total = 0;
  1043. let nV1: Nullable<PositionNormalVertex> = null;
  1044. let nV2: Nullable<PositionNormalVertex> = null;
  1045. let nV3: Nullable<PositionNormalVertex> = null;
  1046. let nV4: Nullable<PositionNormalVertex> = null;
  1047. var d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;
  1048. var d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  1049. var d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  1050. v1Out = d1 > 0;
  1051. v2Out = d2 > 0;
  1052. v3Out = d3 > 0;
  1053. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  1054. switch (total) {
  1055. case 0:
  1056. result.push(vertices[index]);
  1057. result.push(vertices[index + 1]);
  1058. result.push(vertices[index + 2]);
  1059. break;
  1060. case 1:
  1061. if (v1Out) {
  1062. nV1 = vertices[index + 1];
  1063. nV2 = vertices[index + 2];
  1064. nV3 = clipVertices(vertices[index], nV1);
  1065. nV4 = clipVertices(vertices[index], nV2);
  1066. }
  1067. if (v2Out) {
  1068. nV1 = vertices[index];
  1069. nV2 = vertices[index + 2];
  1070. nV3 = clipVertices(vertices[index + 1], nV1);
  1071. nV4 = clipVertices(vertices[index + 1], nV2);
  1072. result.push(nV3);
  1073. result.push(nV2.clone());
  1074. result.push(nV1.clone());
  1075. result.push(nV2.clone());
  1076. result.push(nV3.clone());
  1077. result.push(nV4);
  1078. break;
  1079. }
  1080. if (v3Out) {
  1081. nV1 = vertices[index];
  1082. nV2 = vertices[index + 1];
  1083. nV3 = clipVertices(vertices[index + 2], nV1);
  1084. nV4 = clipVertices(vertices[index + 2], nV2);
  1085. }
  1086. if (nV1 && nV2 && nV3 && nV4) {
  1087. result.push(nV1.clone());
  1088. result.push(nV2.clone());
  1089. result.push(nV3);
  1090. result.push(nV4);
  1091. result.push(nV3.clone());
  1092. result.push(nV2.clone());
  1093. }
  1094. break;
  1095. case 2:
  1096. if (!v1Out) {
  1097. nV1 = vertices[index].clone();
  1098. nV2 = clipVertices(nV1, vertices[index + 1]);
  1099. nV3 = clipVertices(nV1, vertices[index + 2]);
  1100. result.push(nV1);
  1101. result.push(nV2);
  1102. result.push(nV3);
  1103. }
  1104. if (!v2Out) {
  1105. nV1 = vertices[index + 1].clone();
  1106. nV2 = clipVertices(nV1, vertices[index + 2]);
  1107. nV3 = clipVertices(nV1, vertices[index]);
  1108. result.push(nV1);
  1109. result.push(nV2);
  1110. result.push(nV3);
  1111. }
  1112. if (!v3Out) {
  1113. nV1 = vertices[index + 2].clone();
  1114. nV2 = clipVertices(nV1, vertices[index]);
  1115. nV3 = clipVertices(nV1, vertices[index + 1]);
  1116. result.push(nV1);
  1117. result.push(nV2);
  1118. result.push(nV3);
  1119. }
  1120. break;
  1121. case 3:
  1122. break;
  1123. }
  1124. }
  1125. return result;
  1126. };
  1127. for (var index = 0; index < indices.length; index += 3) {
  1128. var faceVertices = new Array<PositionNormalVertex>();
  1129. faceVertices.push(extractDecalVector3(index));
  1130. faceVertices.push(extractDecalVector3(index + 1));
  1131. faceVertices.push(extractDecalVector3(index + 2));
  1132. // Clip
  1133. faceVertices = clip(faceVertices, new Vector3(1, 0, 0));
  1134. faceVertices = clip(faceVertices, new Vector3(-1, 0, 0));
  1135. faceVertices = clip(faceVertices, new Vector3(0, 1, 0));
  1136. faceVertices = clip(faceVertices, new Vector3(0, -1, 0));
  1137. faceVertices = clip(faceVertices, new Vector3(0, 0, 1));
  1138. faceVertices = clip(faceVertices, new Vector3(0, 0, -1));
  1139. if (faceVertices.length === 0) {
  1140. continue;
  1141. }
  1142. // Add UVs and get back to world
  1143. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  1144. var vertex = faceVertices[vIndex];
  1145. //TODO check for Int32Array | Uint32Array | Uint16Array
  1146. (<number[]>vertexData.indices).push(currentVertexDataIndex);
  1147. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  1148. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  1149. (<number[]>vertexData.uvs).push(0.5 + vertex.position.x / size.x);
  1150. (<number[]>vertexData.uvs).push(0.5 + vertex.position.y / size.y);
  1151. currentVertexDataIndex++;
  1152. }
  1153. }
  1154. // Return mesh
  1155. var decal = new Mesh(name, sourceMesh.getScene());
  1156. vertexData.applyToMesh(decal);
  1157. decal.position = position.clone();
  1158. decal.rotation = new Vector3(pitch, yaw, angle);
  1159. return decal;
  1160. }
  1161. // Privates
  1162. private static _ExtrudeShapeGeneric(name: string, shape: Vector3[], curve: Vector3[], scale: Nullable<number>, rotation: Nullable<number>, scaleFunction: Nullable<{ (i: number, distance: number): number; }>,
  1163. rotateFunction: Nullable<{ (i: number, distance: number): number; }>, rbCA: boolean, rbCP: boolean, cap: number, custom: boolean,
  1164. scene: Nullable<Scene>, updtbl: boolean, side: number, instance: Nullable<Mesh>, invertUV: boolean, frontUVs: Nullable<Vector4>, backUVs: Nullable<Vector4>): Mesh {
  1165. // extrusion geometry
  1166. var extrusionPathArray = (shape: Vector3[], curve: Vector3[], path3D: Path3D, shapePaths: Vector3[][], scale: Nullable<number>, rotation: Nullable<number>,
  1167. scaleFunction: Nullable<{ (i: number, distance: number): number; }>, rotateFunction: Nullable<{ (i: number, distance: number): number; }>, cap: number, custom: boolean) => {
  1168. var tangents = path3D.getTangents();
  1169. var normals = path3D.getNormals();
  1170. var binormals = path3D.getBinormals();
  1171. var distances = path3D.getDistances();
  1172. var angle = 0;
  1173. var returnScale: { (i: number, distance: number): number; } = () => { return scale !== null ? scale : 1; };
  1174. var returnRotation: { (i: number, distance: number): number; } = () => { return rotation !== null ? rotation : 0; };
  1175. var rotate: { (i: number, distance: number): number; } = custom && rotateFunction ? rotateFunction : returnRotation;
  1176. var scl: { (i: number, distance: number): number; } = custom && scaleFunction ? scaleFunction : returnScale;
  1177. var index = (cap === Mesh.NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  1178. var rotationMatrix: Matrix = Tmp.Matrix[0];
  1179. for (var i = 0; i < curve.length; i++) {
  1180. var shapePath = new Array<Vector3>();
  1181. var angleStep = rotate(i, distances[i]);
  1182. var scaleRatio = scl(i, distances[i]);
  1183. for (var p = 0; p < shape.length; p++) {
  1184. Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  1185. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  1186. var rotated = shapePath[p] ? shapePath[p] : Vector3.Zero();
  1187. Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  1188. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  1189. shapePath[p] = rotated;
  1190. }
  1191. shapePaths[index] = shapePath;
  1192. angle += angleStep;
  1193. index++;
  1194. }
  1195. // cap
  1196. var capPath = (shapePath: Vector3[]) => {
  1197. var pointCap = Array<Vector3>();
  1198. var barycenter = Vector3.Zero();
  1199. var i: number;
  1200. for (i = 0; i < shapePath.length; i++) {
  1201. barycenter.addInPlace(shapePath[i]);
  1202. }
  1203. barycenter.scaleInPlace(1.0 / shapePath.length);
  1204. for (i = 0; i < shapePath.length; i++) {
  1205. pointCap.push(barycenter);
  1206. }
  1207. return pointCap;
  1208. };
  1209. switch (cap) {
  1210. case Mesh.NO_CAP:
  1211. break;
  1212. case Mesh.CAP_START:
  1213. shapePaths[0] = capPath(shapePaths[2]);
  1214. shapePaths[1] = shapePaths[2];
  1215. break;
  1216. case Mesh.CAP_END:
  1217. shapePaths[index] = shapePaths[index - 1];
  1218. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  1219. break;
  1220. case Mesh.CAP_ALL:
  1221. shapePaths[0] = capPath(shapePaths[2]);
  1222. shapePaths[1] = shapePaths[2];
  1223. shapePaths[index] = shapePaths[index - 1];
  1224. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  1225. break;
  1226. default:
  1227. break;
  1228. }
  1229. return shapePaths;
  1230. };
  1231. var path3D;
  1232. var pathArray;
  1233. if (instance) { // instance update
  1234. path3D = ((<any>instance).path3D).update(curve);
  1235. pathArray = extrusionPathArray(shape, curve, (<any>instance).path3D, (<any>instance).pathArray, scale, rotation, scaleFunction, rotateFunction, (<any>instance).cap, custom);
  1236. instance = Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  1237. return instance;
  1238. }
  1239. // extruded shape creation
  1240. path3D = <any>new Path3D(curve);
  1241. var newShapePaths = new Array<Array<Vector3>>();
  1242. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1243. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  1244. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  1245. (<any>extrudedGeneric).pathArray = pathArray;
  1246. (<any>extrudedGeneric).path3D = path3D;
  1247. (<any>extrudedGeneric).cap = cap;
  1248. return extrudedGeneric;
  1249. }
  1250. }
  1251. }