babylon.meshBuilder.ts 94 KB

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