babylon.meshBuilder.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. module BABYLON {
  2. export class MeshBuilder {
  3. public static CreateBox(name: string, options: { width?: number, height?: number, depth?: number, faceUV?: Vector4[], faceColors?: Color4[], sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
  4. var box = new Mesh(name, scene);
  5. var vertexData = VertexData.CreateBox(options);
  6. vertexData.applyToMesh(box, options.updatable);
  7. return box;
  8. }
  9. public static CreateSphere(name: string, options: { segments?: number, diameter?: number, diameterX?: number, diameterY?: number, diameterZ?: number, arc?: number, slice?: number, sideOrientation?: number, updatable?: boolean }, scene: any): Mesh {
  10. var sphere = new Mesh(name, scene);
  11. var vertexData = VertexData.CreateSphere(options);
  12. vertexData.applyToMesh(sphere, options.updatable);
  13. return sphere;
  14. }
  15. public static CreateDisc(name: string, options: { radius: number, tessellation: number, updatable?: boolean, sideOrientation?: number }, scene: Scene): Mesh {
  16. var disc = new Mesh(name, scene);
  17. var vertexData = VertexData.CreateDisc(options);
  18. vertexData.applyToMesh(disc, options.updatable);
  19. return disc;
  20. }
  21. public static CreateRibbon(name: string, options: { pathArray: Vector3[][], closeArray?: boolean, closePath?: boolean, offset?: number, updatable?: boolean, sideOrientation?: number, instance?: Mesh }, scene?: Scene): Mesh {
  22. var pathArray = options.pathArray;
  23. var closeArray = options.closeArray;
  24. var closePath = options.closePath;
  25. var offset = options.offset;
  26. var sideOrientation = options.sideOrientation;
  27. var instance = options.instance;
  28. var updatable = options.updatable;
  29. if (instance) { // existing ribbon instance update
  30. // positionFunction : ribbon case
  31. // only pathArray and sideOrientation parameters are taken into account for positions update
  32. var positionFunction = positions => {
  33. var minlg = pathArray[0].length;
  34. var i = 0;
  35. var ns = (instance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  36. for (var si = 1; si <= ns; si++) {
  37. for (var p = 0; p < pathArray.length; p++) {
  38. var path = pathArray[p];
  39. var l = path.length;
  40. minlg = (minlg < l) ? minlg : l;
  41. var j = 0;
  42. while (j < minlg) {
  43. positions[i] = path[j].x;
  44. positions[i + 1] = path[j].y;
  45. positions[i + 2] = path[j].z;
  46. j++;
  47. i += 3;
  48. }
  49. if ((<any>instance)._closePath) {
  50. positions[i] = path[0].x;
  51. positions[i + 1] = path[0].y;
  52. positions[i + 2] = path[0].z;
  53. i += 3;
  54. }
  55. }
  56. }
  57. };
  58. var positions = instance.getVerticesData(VertexBuffer.PositionKind);
  59. positionFunction(positions);
  60. instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  61. if (!(instance.areNormalsFrozen)) {
  62. var indices = instance.getIndices();
  63. var normals = instance.getVerticesData(VertexBuffer.NormalKind);
  64. VertexData.ComputeNormals(positions, indices, normals);
  65. if ((<any>instance)._closePath) {
  66. var indexFirst: number = 0;
  67. var indexLast: number = 0;
  68. for (var p = 0; p < pathArray.length; p++) {
  69. indexFirst = (<any>instance)._idx[p] * 3;
  70. if (p + 1 < pathArray.length) {
  71. indexLast = ((<any>instance)._idx[p + 1] - 1) * 3;
  72. }
  73. else {
  74. indexLast = normals.length - 3;
  75. }
  76. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  77. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  78. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  79. normals[indexLast] = normals[indexFirst];
  80. normals[indexLast + 1] = normals[indexFirst + 1];
  81. normals[indexLast + 2] = normals[indexFirst + 2];
  82. }
  83. }
  84. instance.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  85. }
  86. return instance;
  87. }
  88. else { // new ribbon creation
  89. var ribbon = new Mesh(name, scene);
  90. ribbon.sideOrientation = sideOrientation;
  91. var vertexData = VertexData.CreateRibbon(options);
  92. if (closePath) {
  93. (<any>ribbon)._idx = (<any>vertexData)._idx;
  94. }
  95. (<any>ribbon)._closePath = closePath;
  96. (<any>ribbon)._closeArray = closeArray;
  97. vertexData.applyToMesh(ribbon, updatable);
  98. return ribbon;
  99. }
  100. }
  101. 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, sideOrientation?: number }, scene: any): Mesh {
  102. var cylinder = new Mesh(name, scene);
  103. var vertexData = VertexData.CreateCylinder(options);
  104. vertexData.applyToMesh(cylinder, options.updatable);
  105. return cylinder;
  106. }
  107. public static CreateTorus(name: string, options: { diameter?: number, thickness?: number, tessellation?: number, updatable?: boolean, sideOrientation?: number }, scene: any): Mesh {
  108. var torus = new Mesh(name, scene);
  109. var vertexData = VertexData.CreateTorus(options);
  110. vertexData.applyToMesh(torus, options.updatable);
  111. return torus;
  112. }
  113. public static CreateTorusKnot(name: string, options: { radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, p?: number, q?: number, updatable?: boolean, sideOrientation?: number }, scene: any): Mesh {
  114. var torusKnot = new Mesh(name, scene);
  115. var vertexData = VertexData.CreateTorusKnot(options);
  116. vertexData.applyToMesh(torusKnot, options.updatable);
  117. return torusKnot;
  118. }
  119. public static CreateLines(name: string, options: { points: Vector3[], updatable?: boolean, instance?: LinesMesh }, scene: Scene): LinesMesh {
  120. var instance = options.instance;
  121. var points = options.points;
  122. if (instance) { // lines update
  123. var positionFunction = positions => {
  124. var i = 0;
  125. for (var p = 0; p < points.length; p++) {
  126. positions[i] = points[p].x;
  127. positions[i + 1] = points[p].y;
  128. positions[i + 2] = points[p].z;
  129. i += 3;
  130. }
  131. };
  132. instance.updateMeshPositions(positionFunction, false);
  133. return instance;
  134. }
  135. // lines creation
  136. var lines = new LinesMesh(name, scene);
  137. var vertexData = VertexData.CreateLines(options);
  138. vertexData.applyToMesh(lines, options.updatable);
  139. return lines;
  140. }
  141. public static CreateDashedLines(name: string, options: { points: Vector3[], dashSize?: number, gapSize?: number, dashNb?: number, updatable?: boolean, instance?: LinesMesh }, scene: Scene): LinesMesh {
  142. var points = options.points;
  143. var instance = options.instance;
  144. var gapSize = options.gapSize;
  145. var dashNb = options.dashNb;
  146. var dashSize = options.dashSize;
  147. if (instance) { // dashed lines update
  148. var positionFunction = (positions: number[]): void => {
  149. var curvect = Vector3.Zero();
  150. var nbSeg = positions.length / 6;
  151. var lg = 0;
  152. var nb = 0;
  153. var shft = 0;
  154. var dashshft = 0;
  155. var curshft = 0;
  156. var p = 0;
  157. var i = 0;
  158. var j = 0;
  159. for (i = 0; i < points.length - 1; i++) {
  160. points[i + 1].subtractToRef(points[i], curvect);
  161. lg += curvect.length();
  162. }
  163. shft = lg / nbSeg;
  164. dashshft = (<any>instance).dashSize * shft / ((<any>instance).dashSize + (<any>instance).gapSize);
  165. for (i = 0; i < points.length - 1; i++) {
  166. points[i + 1].subtractToRef(points[i], curvect);
  167. nb = Math.floor(curvect.length() / shft);
  168. curvect.normalize();
  169. j = 0;
  170. while (j < nb && p < positions.length) {
  171. curshft = shft * j;
  172. positions[p] = points[i].x + curshft * curvect.x;
  173. positions[p + 1] = points[i].y + curshft * curvect.y;
  174. positions[p + 2] = points[i].z + curshft * curvect.z;
  175. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  176. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  177. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  178. p += 6;
  179. j++;
  180. }
  181. }
  182. while (p < positions.length) {
  183. positions[p] = points[i].x;
  184. positions[p + 1] = points[i].y;
  185. positions[p + 2] = points[i].z;
  186. p += 3;
  187. }
  188. };
  189. instance.updateMeshPositions(positionFunction, false);
  190. return instance;
  191. }
  192. // dashed lines creation
  193. var dashedLines = new LinesMesh(name, scene);
  194. var vertexData = VertexData.CreateDashedLines(options);
  195. vertexData.applyToMesh(dashedLines, options.updatable);
  196. (<any>dashedLines).dashSize = dashSize;
  197. (<any>dashedLines).gapSize = gapSize;
  198. return dashedLines;
  199. }
  200. public static ExtrudeShape(name: string, options: { shape: Vector3[], path: Vector3[], scale?: number, rotation?: number, cap?: number, updatable?: boolean, sideOrientation?: number, instance?: Mesh }, scene: Scene): Mesh {
  201. var path = options.path;
  202. var shape = options.shape;
  203. var scale = options.scale || 1;
  204. var rotation = options.rotation || 0;
  205. var cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  206. var updatable = options.updatable;
  207. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  208. var instance = options.instance;
  209. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  210. }
  211. public static ExtrudeShapeCustom(name: string, options: { shape: Vector3[], path: Vector3[], scaleFunction?, rotationFunction?, ribbonCloseArray?: boolean, ribbonClosePath?: boolean, cap?: number, updatable?: boolean, sideOrientation?: number, instance?: Mesh }, scene: Scene): Mesh {
  212. var path = options.path;
  213. var shape = options.shape;
  214. var scaleFunction = options.scaleFunction || (() => { return 1; });
  215. var rotationFunction = options.rotationFunction || (() => { return 0; });
  216. var ribbonCloseArray = options.ribbonCloseArray || false;
  217. var ribbonClosePath = options.ribbonClosePath || false;
  218. var cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  219. var updatable = options.updatable;
  220. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  221. var instance = options.instance;
  222. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  223. }
  224. public static CreateLathe(name: string, options: { shape: Vector3[], radius?: number, tessellation?: number, arc?: number, closed?: boolean, updatable?: boolean, sideOrientation?: number }, scene: Scene): Mesh {
  225. var arc: number = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  226. var closed: boolean = (options.closed === undefined) ? true : options.closed;
  227. var shape = options.shape;
  228. var radius = options.radius || 1;
  229. var tessellation = options.tessellation || 64;
  230. var updatable = options.updatable;
  231. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  232. var pi2 = Math.PI * 2;
  233. var shapeLathe = new Array<Vector3>();
  234. // first rotatable point
  235. var i = 0;
  236. while (shape[i].x === 0) {
  237. i++;
  238. }
  239. var pt = shape[i];
  240. for (i = 0; i < shape.length; i++) {
  241. shapeLathe.push(shape[i].subtract(pt));
  242. }
  243. // circle path
  244. var step = pi2 / tessellation * arc;
  245. var rotated;
  246. var path = new Array<Vector3>();;
  247. for (i = 0; i <= tessellation; i++) {
  248. rotated = new Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  249. path.push(rotated);
  250. }
  251. if (closed) {
  252. path.push(path[0]);
  253. }
  254. // extrusion
  255. var scaleFunction = () => { return 1; };
  256. var rotateFunction = () => { return 0; };
  257. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  258. return lathe;
  259. }
  260. public static CreatePlane(name: string, options: { size?: number, width?: number, height?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
  261. var plane = new Mesh(name, scene);
  262. var vertexData = VertexData.CreatePlane(options);
  263. vertexData.applyToMesh(plane, options.updatable);
  264. return plane;
  265. }
  266. public static CreateGround(name: string, options: { width?: number, height?: number, subdivisions?: number, updatable?: boolean }, scene: any): Mesh {
  267. var ground = new GroundMesh(name, scene);
  268. ground._setReady(false);
  269. ground._subdivisions = options.subdivisions || 1;
  270. var vertexData = VertexData.CreateGround(options);
  271. vertexData.applyToMesh(ground, options.updatable);
  272. ground._setReady(true);
  273. return ground;
  274. }
  275. 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 {
  276. var tiledGround = new Mesh(name, scene);
  277. var vertexData = VertexData.CreateTiledGround(options);
  278. vertexData.applyToMesh(tiledGround, options.updatable);
  279. return tiledGround;
  280. }
  281. public static CreateGroundFromHeightMap(name: string, url: string, options: { width?: number, height?: number, subdivisions?: number, minHeight?: number, maxHeight?: number, updatable?: boolean, onReady?: (mesh: GroundMesh) => void }, scene: Scene): GroundMesh {
  282. var width = options.width || 10;
  283. var height = options.height || 10;
  284. var subdivisions = options.subdivisions || 1;
  285. var minHeight = options.minHeight;
  286. var maxHeight = options.maxHeight || 10;
  287. var updatable = options.updatable;
  288. var onReady = options.onReady;
  289. var ground = new GroundMesh(name, scene);
  290. ground._subdivisions = subdivisions;
  291. ground._setReady(false);
  292. var onload = img => {
  293. // Getting height map data
  294. var canvas = document.createElement("canvas");
  295. var context = canvas.getContext("2d");
  296. var bufferWidth = img.width;
  297. var bufferHeight = img.height;
  298. canvas.width = bufferWidth;
  299. canvas.height = bufferHeight;
  300. context.drawImage(img, 0, 0);
  301. // Create VertexData from map data
  302. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  303. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, bufferWidth, bufferHeight).data);
  304. var vertexData = VertexData.CreateGroundFromHeightMap({
  305. width, height,
  306. subdivisions,
  307. minHeight, maxHeight,
  308. buffer, bufferWidth, bufferHeight
  309. });
  310. vertexData.applyToMesh(ground, updatable);
  311. ground._setReady(true);
  312. //execute ready callback, if set
  313. if (onReady) {
  314. onReady(ground);
  315. }
  316. };
  317. Tools.LoadImage(url, onload, () => { }, scene.database);
  318. return ground;
  319. }
  320. 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, instance?: Mesh }, scene: Scene): Mesh {
  321. var path = options.path;
  322. var radius = options.radius || 1;
  323. var tessellation = options.tessellation || 64;
  324. var radiusFunction = options.radiusFunction;
  325. var cap = options.cap || Mesh.NO_CAP;
  326. var updatable = options.updatable;
  327. var sideOrientation = options.sideOrientation || Mesh.DEFAULTSIDE;
  328. var instance = options.instance;
  329. // tube geometry
  330. var tubePathArray = (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) => {
  331. var tangents = path3D.getTangents();
  332. var normals = path3D.getNormals();
  333. var distances = path3D.getDistances();
  334. var pi2 = Math.PI * 2;
  335. var step = pi2 / tessellation * arc;
  336. var returnRadius: { (i: number, distance: number): number; } = () => radius;
  337. var radiusFunctionFinal: { (i: number, distance: number): number; } = radiusFunction || returnRadius;
  338. var circlePath: Vector3[];
  339. var rad: number;
  340. var normal: Vector3;
  341. var rotated: Vector3;
  342. var rotationMatrix: Matrix = Matrix.Zero();
  343. var index = (cap === Mesh._NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  344. for (var i = 0; i < path.length; i++) {
  345. rad = radiusFunctionFinal(i, distances[i]); // current radius
  346. circlePath = Array<Vector3>(); // current circle array
  347. normal = normals[i]; // current normal
  348. for (var t = 0; t < tessellation; t++) {
  349. Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  350. rotated = Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  351. circlePath.push(rotated);
  352. }
  353. circlePaths[index] = circlePath;
  354. index++;
  355. }
  356. // cap
  357. var capPath = (nbPoints, pathIndex) => {
  358. var pointCap = Array<Vector3>();
  359. for (var i = 0; i < nbPoints; i++) {
  360. pointCap.push(path[pathIndex]);
  361. }
  362. return pointCap;
  363. };
  364. switch (cap) {
  365. case Mesh.NO_CAP:
  366. break;
  367. case Mesh.CAP_START:
  368. circlePaths[0] = capPath(tessellation, 0);
  369. circlePaths[1] = circlePaths[2].slice(0);
  370. break;
  371. case Mesh.CAP_END:
  372. circlePaths[index] = circlePaths[index - 1].slice(0);
  373. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  374. break;
  375. case Mesh.CAP_ALL:
  376. circlePaths[0] = capPath(tessellation, 0);
  377. circlePaths[1] = circlePaths[2].slice(0);
  378. circlePaths[index] = circlePaths[index - 1].slice(0);
  379. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  380. break;
  381. default:
  382. break;
  383. }
  384. return circlePaths;
  385. };
  386. var path3D;
  387. var pathArray;
  388. if (instance) { // tube update
  389. var arc = options.arc || (<any>instance).arc;
  390. path3D = ((<any>instance).path3D).update(path);
  391. pathArray = tubePathArray(path, path3D, (<any>instance).pathArray, radius, (<any>instance).tessellation, radiusFunction, (<any>instance).cap, arc);
  392. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  393. (<any>instance).path3D = path3D;
  394. (<any>instance).pathArray = pathArray;
  395. (<any>instance).arc = arc;
  396. return instance;
  397. }
  398. // tube creation
  399. path3D = <any>new Path3D(path);
  400. var newPathArray = new Array<Array<Vector3>>();
  401. cap = (cap < 0 || cap > 3) ? 0 : cap;
  402. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  403. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  404. (<any>tube).pathArray = pathArray;
  405. (<any>tube).path3D = path3D;
  406. (<any>tube).tessellation = tessellation;
  407. (<any>tube).cap = cap;
  408. (<any>tube).arc = options.arc;
  409. return tube;
  410. }
  411. public static CreatePolyhedron(name: string, options: { type?: number, size?: number, sizeX?: number, sizeY?: number, sizeZ?: number, custom?: any, faceUV?: Vector4[], faceColors?: Color4[], singleFace?: boolean, updatable?: boolean, sideOrientation?: number }, scene: Scene): Mesh {
  412. var polyhedron = new Mesh(name, scene);
  413. var vertexData = VertexData.CreatePolyhedron(options);
  414. vertexData.applyToMesh(polyhedron, options.updatable);
  415. return polyhedron;
  416. }
  417. public static CreateDecal(name: string, sourceMesh: AbstractMesh, options: { position?: Vector3, normal?: Vector3, size?: Vector3, angle?: number }): Mesh {
  418. var indices = sourceMesh.getIndices();
  419. var positions = sourceMesh.getVerticesData(VertexBuffer.PositionKind);
  420. var normals = sourceMesh.getVerticesData(VertexBuffer.NormalKind);
  421. var position = options.position || Vector3.Zero();
  422. var normal = options.normal || Vector3.Up();
  423. var size = options.size || new Vector3(1, 1, 1);
  424. var angle = options.angle || 0;
  425. // Getting correct rotation
  426. if (!normal) {
  427. var target = new Vector3(0, 0, 1);
  428. var camera = sourceMesh.getScene().activeCamera;
  429. var cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  430. normal = camera.globalPosition.subtract(cameraWorldTarget);
  431. }
  432. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  433. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  434. var pitch = Math.atan2(normal.y, len);
  435. // Matrix
  436. var decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));
  437. var inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);
  438. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  439. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  440. var vertexData = new VertexData();
  441. vertexData.indices = [];
  442. vertexData.positions = [];
  443. vertexData.normals = [];
  444. vertexData.uvs = [];
  445. var currentVertexDataIndex = 0;
  446. var extractDecalVector3 = (indexId: number): PositionNormalVertex => {
  447. var vertexId = indices[indexId];
  448. var result = new PositionNormalVertex();
  449. result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  450. // Send vector to decal local world
  451. result.position = Vector3.TransformCoordinates(result.position, transformMatrix);
  452. // Get normal
  453. result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  454. return result;
  455. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  456. var clip = (vertices: PositionNormalVertex[], axis: Vector3): PositionNormalVertex[]=> {
  457. if (vertices.length === 0) {
  458. return vertices;
  459. }
  460. var clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));
  461. var clipVertices = (v0: PositionNormalVertex, v1: PositionNormalVertex): PositionNormalVertex => {
  462. var clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  463. return new PositionNormalVertex(
  464. Vector3.Lerp(v0.position, v1.position, clipFactor),
  465. Vector3.Lerp(v0.normal, v1.normal, clipFactor)
  466. );
  467. };
  468. var result = new Array<PositionNormalVertex>();
  469. for (var index = 0; index < vertices.length; index += 3) {
  470. var v1Out: boolean;
  471. var v2Out: boolean;
  472. var v3Out: boolean;
  473. var total = 0;
  474. var nV1: PositionNormalVertex, nV2: PositionNormalVertex, nV3: PositionNormalVertex, nV4: PositionNormalVertex;
  475. var d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;
  476. var d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  477. var d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  478. v1Out = d1 > 0;
  479. v2Out = d2 > 0;
  480. v3Out = d3 > 0;
  481. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  482. switch (total) {
  483. case 0:
  484. result.push(vertices[index]);
  485. result.push(vertices[index + 1]);
  486. result.push(vertices[index + 2]);
  487. break;
  488. case 1:
  489. if (v1Out) {
  490. nV1 = vertices[index + 1];
  491. nV2 = vertices[index + 2];
  492. nV3 = clipVertices(vertices[index], nV1);
  493. nV4 = clipVertices(vertices[index], nV2);
  494. }
  495. if (v2Out) {
  496. nV1 = vertices[index];
  497. nV2 = vertices[index + 2];
  498. nV3 = clipVertices(vertices[index + 1], nV1);
  499. nV4 = clipVertices(vertices[index + 1], nV2);
  500. result.push(nV3);
  501. result.push(nV2.clone());
  502. result.push(nV1.clone());
  503. result.push(nV2.clone());
  504. result.push(nV3.clone());
  505. result.push(nV4);
  506. break;
  507. }
  508. if (v3Out) {
  509. nV1 = vertices[index];
  510. nV2 = vertices[index + 1];
  511. nV3 = clipVertices(vertices[index + 2], nV1);
  512. nV4 = clipVertices(vertices[index + 2], nV2);
  513. }
  514. result.push(nV1.clone());
  515. result.push(nV2.clone());
  516. result.push(nV3);
  517. result.push(nV4);
  518. result.push(nV3.clone());
  519. result.push(nV2.clone());
  520. break;
  521. case 2:
  522. if (!v1Out) {
  523. nV1 = vertices[index].clone();
  524. nV2 = clipVertices(nV1, vertices[index + 1]);
  525. nV3 = clipVertices(nV1, vertices[index + 2]);
  526. result.push(nV1);
  527. result.push(nV2);
  528. result.push(nV3);
  529. }
  530. if (!v2Out) {
  531. nV1 = vertices[index + 1].clone();
  532. nV2 = clipVertices(nV1, vertices[index + 2]);
  533. nV3 = clipVertices(nV1, vertices[index]);
  534. result.push(nV1);
  535. result.push(nV2);
  536. result.push(nV3);
  537. }
  538. if (!v3Out) {
  539. nV1 = vertices[index + 2].clone();
  540. nV2 = clipVertices(nV1, vertices[index]);
  541. nV3 = clipVertices(nV1, vertices[index + 1]);
  542. result.push(nV1);
  543. result.push(nV2);
  544. result.push(nV3);
  545. }
  546. break;
  547. case 3:
  548. break;
  549. }
  550. }
  551. return result;
  552. };
  553. for (var index = 0; index < indices.length; index += 3) {
  554. var faceVertices = new Array<PositionNormalVertex>();
  555. faceVertices.push(extractDecalVector3(index));
  556. faceVertices.push(extractDecalVector3(index + 1));
  557. faceVertices.push(extractDecalVector3(index + 2));
  558. // Clip
  559. faceVertices = clip(faceVertices, new Vector3(1, 0, 0));
  560. faceVertices = clip(faceVertices, new Vector3(-1, 0, 0));
  561. faceVertices = clip(faceVertices, new Vector3(0, 1, 0));
  562. faceVertices = clip(faceVertices, new Vector3(0, -1, 0));
  563. faceVertices = clip(faceVertices, new Vector3(0, 0, 1));
  564. faceVertices = clip(faceVertices, new Vector3(0, 0, -1));
  565. if (faceVertices.length === 0) {
  566. continue;
  567. }
  568. // Add UVs and get back to world
  569. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  570. var vertex = faceVertices[vIndex];
  571. vertexData.indices.push(currentVertexDataIndex);
  572. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  573. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  574. (<number[]>vertexData.uvs).push(0.5 + vertex.position.x / size.x);
  575. (<number[]>vertexData.uvs).push(0.5 + vertex.position.y / size.y);
  576. currentVertexDataIndex++;
  577. }
  578. }
  579. // Return mesh
  580. var decal = new Mesh(name, sourceMesh.getScene());
  581. vertexData.applyToMesh(decal);
  582. decal.position = position.clone();
  583. decal.rotation = new Vector3(pitch, yaw, angle);
  584. return decal;
  585. }
  586. // Privates
  587. private static _ExtrudeShapeGeneric(name: string, shape: Vector3[], curve: Vector3[], scale: number, rotation: number, scaleFunction: { (i: number, distance: number): number; }, rotateFunction: { (i: number, distance: number): number; }, rbCA: boolean, rbCP: boolean, cap: number, custom: boolean, scene: Scene, updtbl: boolean, side: number, instance: Mesh): Mesh {
  588. // extrusion geometry
  589. var extrusionPathArray = (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) => {
  590. var tangents = path3D.getTangents();
  591. var normals = path3D.getNormals();
  592. var binormals = path3D.getBinormals();
  593. var distances = path3D.getDistances();
  594. var angle = 0;
  595. var returnScale: { (i: number, distance: number): number; } = () => { return scale; };
  596. var returnRotation: { (i: number, distance: number): number; } = () => { return rotation; };
  597. var rotate: { (i: number, distance: number): number; } = custom ? rotateFunction : returnRotation;
  598. var scl: { (i: number, distance: number): number; } = custom ? scaleFunction : returnScale;
  599. var index = (cap === Mesh.NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  600. var rotationMatrix: Matrix = Matrix.Zero();
  601. for (var i = 0; i < curve.length; i++) {
  602. var shapePath = new Array<Vector3>();
  603. var angleStep = rotate(i, distances[i]);
  604. var scaleRatio = scl(i, distances[i]);
  605. for (var p = 0; p < shape.length; p++) {
  606. Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  607. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  608. var rotated = Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  609. shapePath.push(rotated);
  610. }
  611. shapePaths[index] = shapePath;
  612. angle += angleStep;
  613. index++;
  614. }
  615. // cap
  616. var capPath = shapePath => {
  617. var pointCap = Array<Vector3>();
  618. var barycenter = Vector3.Zero();
  619. var i: number;
  620. for (i = 0; i < shapePath.length; i++) {
  621. barycenter.addInPlace(shapePath[i]);
  622. }
  623. barycenter.scaleInPlace(1 / shapePath.length);
  624. for (i = 0; i < shapePath.length; i++) {
  625. pointCap.push(barycenter);
  626. }
  627. return pointCap;
  628. };
  629. switch (cap) {
  630. case Mesh.NO_CAP:
  631. break;
  632. case Mesh.CAP_START:
  633. shapePaths[0] = capPath(shapePaths[2]);
  634. shapePaths[1] = shapePaths[2].slice(0);
  635. break;
  636. case Mesh.CAP_END:
  637. shapePaths[index] = shapePaths[index - 1];
  638. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  639. break;
  640. case Mesh.CAP_ALL:
  641. shapePaths[0] = capPath(shapePaths[2]);
  642. shapePaths[1] = shapePaths[2].slice(0);
  643. shapePaths[index] = shapePaths[index - 1];
  644. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  645. break;
  646. default:
  647. break;
  648. }
  649. return shapePaths;
  650. };
  651. var path3D;
  652. var pathArray;
  653. if (instance) { // instance update
  654. path3D = ((<any>instance).path3D).update(curve);
  655. pathArray = extrusionPathArray(shape, curve, (<any>instance).path3D, (<any>instance).pathArray, scale, rotation, scaleFunction, rotateFunction, (<any>instance).cap, custom);
  656. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  657. return instance;
  658. }
  659. // extruded shape creation
  660. path3D = <any>new Path3D(curve);
  661. var newShapePaths = new Array<Array<Vector3>>();
  662. cap = (cap < 0 || cap > 3) ? 0 : cap;
  663. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  664. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  665. (<any>extrudedGeneric).pathArray = pathArray;
  666. (<any>extrudedGeneric).path3D = path3D;
  667. (<any>extrudedGeneric).cap = cap;
  668. return extrudedGeneric;
  669. }
  670. }
  671. }