babylon.mesh.vertexData.ts 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. module BABYLON {
  2. export interface IGetSetVerticesData {
  3. isVerticesDataPresent(kind: string): boolean;
  4. getVerticesData(kind: string): number[];
  5. getIndices(): number[];
  6. setVerticesData(kind: string, data: number[], updatable?: boolean): void;
  7. updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void;
  8. setIndices(indices: number[]): void;
  9. }
  10. export class VertexData {
  11. public positions: number[];
  12. public normals: number[];
  13. public uvs: number[];
  14. public uv2s: number[];
  15. public colors: number[];
  16. public matricesIndices: number[];
  17. public matricesWeights: number[];
  18. public indices: number[];
  19. public set(data: number[], kind: string) {
  20. switch (kind) {
  21. case VertexBuffer.PositionKind:
  22. this.positions = data;
  23. break;
  24. case VertexBuffer.NormalKind:
  25. this.normals = data;
  26. break;
  27. case VertexBuffer.UVKind:
  28. this.uvs = data;
  29. break;
  30. case VertexBuffer.UV2Kind:
  31. this.uv2s = data;
  32. break;
  33. case VertexBuffer.ColorKind:
  34. this.colors = data;
  35. break;
  36. case VertexBuffer.MatricesIndicesKind:
  37. this.matricesIndices = data;
  38. break;
  39. case VertexBuffer.MatricesWeightsKind:
  40. this.matricesWeights = data;
  41. break;
  42. }
  43. }
  44. public applyToMesh(mesh: Mesh, updatable?: boolean): void {
  45. this._applyTo(mesh, updatable);
  46. }
  47. public applyToGeometry(geometry: Geometry, updatable?: boolean): void {
  48. this._applyTo(geometry, updatable);
  49. }
  50. public updateMesh(mesh: Mesh, updateExtends?: boolean, makeItUnique?: boolean): void {
  51. this._update(mesh);
  52. }
  53. public updateGeometry(geometry: Geometry, updateExtends?: boolean, makeItUnique?: boolean): void {
  54. this._update(geometry);
  55. }
  56. private _applyTo(meshOrGeometry: IGetSetVerticesData, updatable?: boolean) {
  57. if (this.positions) {
  58. meshOrGeometry.setVerticesData(VertexBuffer.PositionKind, this.positions, updatable);
  59. }
  60. if (this.normals) {
  61. meshOrGeometry.setVerticesData(VertexBuffer.NormalKind, this.normals, updatable);
  62. }
  63. if (this.uvs) {
  64. meshOrGeometry.setVerticesData(VertexBuffer.UVKind, this.uvs, updatable);
  65. }
  66. if (this.uv2s) {
  67. meshOrGeometry.setVerticesData(VertexBuffer.UV2Kind, this.uv2s, updatable);
  68. }
  69. if (this.colors) {
  70. meshOrGeometry.setVerticesData(VertexBuffer.ColorKind, this.colors, updatable);
  71. }
  72. if (this.matricesIndices) {
  73. meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  74. }
  75. if (this.matricesWeights) {
  76. meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  77. }
  78. if (this.indices) {
  79. meshOrGeometry.setIndices(this.indices);
  80. }
  81. }
  82. private _update(meshOrGeometry: IGetSetVerticesData, updateExtends?: boolean, makeItUnique?: boolean) {
  83. if (this.positions) {
  84. meshOrGeometry.updateVerticesData(VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  85. }
  86. if (this.normals) {
  87. meshOrGeometry.updateVerticesData(VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  88. }
  89. if (this.uvs) {
  90. meshOrGeometry.updateVerticesData(VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  91. }
  92. if (this.uv2s) {
  93. meshOrGeometry.updateVerticesData(VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  94. }
  95. if (this.colors) {
  96. meshOrGeometry.updateVerticesData(VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  97. }
  98. if (this.matricesIndices) {
  99. meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  100. }
  101. if (this.matricesWeights) {
  102. meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  103. }
  104. if (this.indices) {
  105. meshOrGeometry.setIndices(this.indices);
  106. }
  107. }
  108. public transform(matrix: Matrix): void {
  109. var transformed = Vector3.Zero();
  110. if (this.positions) {
  111. var position = Vector3.Zero();
  112. for (var index = 0; index < this.positions.length; index += 3) {
  113. Vector3.FromArrayToRef(this.positions, index, position);
  114. Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  115. this.positions[index] = transformed.x;
  116. this.positions[index + 1] = transformed.y;
  117. this.positions[index + 2] = transformed.z;
  118. }
  119. }
  120. if (this.normals) {
  121. var normal = Vector3.Zero();
  122. for (index = 0; index < this.normals.length; index += 3) {
  123. Vector3.FromArrayToRef(this.normals, index, normal);
  124. Vector3.TransformNormalToRef(normal, matrix, transformed);
  125. this.normals[index] = transformed.x;
  126. this.normals[index + 1] = transformed.y;
  127. this.normals[index + 2] = transformed.z;
  128. }
  129. }
  130. }
  131. public merge(other: VertexData): void {
  132. if (other.indices) {
  133. if (!this.indices) {
  134. this.indices = [];
  135. }
  136. var offset = this.positions ? this.positions.length / 3 : 0;
  137. for (var index = 0; index < other.indices.length; index++) {
  138. this.indices.push(other.indices[index] + offset);
  139. }
  140. }
  141. if (other.positions) {
  142. if (!this.positions) {
  143. this.positions = [];
  144. }
  145. for (index = 0; index < other.positions.length; index++) {
  146. this.positions.push(other.positions[index]);
  147. }
  148. }
  149. if (other.normals) {
  150. if (!this.normals) {
  151. this.normals = [];
  152. }
  153. for (index = 0; index < other.normals.length; index++) {
  154. this.normals.push(other.normals[index]);
  155. }
  156. }
  157. if (other.uvs) {
  158. if (!this.uvs) {
  159. this.uvs = [];
  160. }
  161. for (index = 0; index < other.uvs.length; index++) {
  162. this.uvs.push(other.uvs[index]);
  163. }
  164. }
  165. if (other.uv2s) {
  166. if (!this.uv2s) {
  167. this.uv2s = [];
  168. }
  169. for (index = 0; index < other.uv2s.length; index++) {
  170. this.uv2s.push(other.uv2s[index]);
  171. }
  172. }
  173. if (other.matricesIndices) {
  174. if (!this.matricesIndices) {
  175. this.matricesIndices = [];
  176. }
  177. for (index = 0; index < other.matricesIndices.length; index++) {
  178. this.matricesIndices.push(other.matricesIndices[index]);
  179. }
  180. }
  181. if (other.matricesWeights) {
  182. if (!this.matricesWeights) {
  183. this.matricesWeights = [];
  184. }
  185. for (index = 0; index < other.matricesWeights.length; index++) {
  186. this.matricesWeights.push(other.matricesWeights[index]);
  187. }
  188. }
  189. if (other.colors) {
  190. if (!this.colors) {
  191. this.colors = [];
  192. }
  193. for (index = 0; index < other.colors.length; index++) {
  194. this.colors.push(other.colors[index]);
  195. }
  196. }
  197. }
  198. // Statics
  199. public static ExtractFromMesh(mesh: Mesh): VertexData {
  200. return VertexData._ExtractFrom(mesh);
  201. }
  202. public static ExtractFromGeometry(geometry: Geometry): VertexData {
  203. return VertexData._ExtractFrom(geometry);
  204. }
  205. private static _ExtractFrom(meshOrGeometry: IGetSetVerticesData): VertexData {
  206. var result = new VertexData();
  207. if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  208. result.positions = meshOrGeometry.getVerticesData(VertexBuffer.PositionKind);
  209. }
  210. if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  211. result.normals = meshOrGeometry.getVerticesData(VertexBuffer.NormalKind);
  212. }
  213. if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UVKind)) {
  214. result.uvs = meshOrGeometry.getVerticesData(VertexBuffer.UVKind);
  215. }
  216. if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  217. result.uv2s = meshOrGeometry.getVerticesData(VertexBuffer.UV2Kind);
  218. }
  219. if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.ColorKind)) {
  220. result.colors = meshOrGeometry.getVerticesData(VertexBuffer.ColorKind);
  221. }
  222. if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  223. result.matricesIndices = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesKind);
  224. }
  225. if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  226. result.matricesWeights = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsKind);
  227. }
  228. result.indices = meshOrGeometry.getIndices();
  229. return result;
  230. }
  231. public static CreateRibbon(pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number): VertexData {
  232. closeArray = closeArray || false;
  233. closePath = closePath || false;
  234. var defaultOffset = Math.floor(pathArray[0].length / 2);
  235. offset = offset || defaultOffset;
  236. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  237. var positions: number[] = [];
  238. var indices: number[] = [];
  239. var normals: number[] = [];
  240. var uvs: number[] = [];
  241. var us: number[][] = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  242. var vs: number[][] = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  243. var uTotalDistance: number[] = []; // uTotalDistance[p] : total distance of path p
  244. var vTotalDistance: number[] = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  245. var minlg: number; // minimal length among all paths from pathArray
  246. var lg: number[] = []; // array of path lengths : nb of vertex per path
  247. var idx: number[] = []; // array of path indexes : index of each path (first vertex) in positions array
  248. var p: number; // path iterator
  249. var i: number; // point iterator
  250. var j: number; // point iterator
  251. // if single path in pathArray
  252. if (pathArray.length < 2) {
  253. var ar1: Vector3[] = [];
  254. var ar2: Vector3[] = [];
  255. for (i = 0; i < pathArray[0].length - offset; i++) {
  256. ar1.push(pathArray[0][i]);
  257. ar2.push(pathArray[0][i + offset]);
  258. }
  259. pathArray = [ar1, ar2];
  260. }
  261. // positions and horizontal distances (u)
  262. var idc: number = 0;
  263. minlg = pathArray[0].length;
  264. for (p = 0; p < pathArray.length; p++) {
  265. uTotalDistance[p] = 0;
  266. us[p] = [0];
  267. var path: Vector3[] = pathArray[p];
  268. var l: number = path.length;
  269. minlg = (minlg < l) ? minlg : l;
  270. lg[p] = l;
  271. idx[p] = idc;
  272. j = 0;
  273. while (j < l) {
  274. positions.push(path[j].x, path[j].y, path[j].z);
  275. if (j > 0) {
  276. var vectlg: number = path[j].subtract(path[j - 1]).length();
  277. var dist: number = vectlg + uTotalDistance[p];
  278. us[p].push(dist);
  279. uTotalDistance[p] = dist;
  280. }
  281. j++;
  282. }
  283. if (closePath) {
  284. vectlg = path[0].subtract(path[j - 1]).length();
  285. dist = vectlg + uTotalDistance[p];
  286. uTotalDistance[p] = dist;
  287. }
  288. idc += l;
  289. }
  290. // vertical distances (v)
  291. for (i = 0; i < minlg; i++) {
  292. vTotalDistance[i] = 0;
  293. vs[i] = [0];
  294. var path1: Vector3[];
  295. var path2: Vector3[];
  296. for (p = 0; p < pathArray.length - 1; p++) {
  297. path1 = pathArray[p];
  298. path2 = pathArray[p + 1];
  299. vectlg = path2[i].subtract(path1[i]).length();
  300. dist = vectlg + vTotalDistance[i];
  301. vs[i].push(dist);
  302. vTotalDistance[i] = dist;
  303. }
  304. if (closeArray) {
  305. path1 = pathArray[p];
  306. path2 = pathArray[0];
  307. vectlg = path2[i].subtract(path1[i]).length();
  308. dist = vectlg + vTotalDistance[i];
  309. vTotalDistance[i] = dist;
  310. }
  311. }
  312. // uvs
  313. var u: number;
  314. var v: number;
  315. for (p = 0; p < pathArray.length; p++) {
  316. for (i = 0; i < minlg; i++) {
  317. u = us[p][i] / uTotalDistance[p];
  318. v = vs[i][p] / vTotalDistance[i];
  319. uvs.push(u, v);
  320. }
  321. }
  322. // indices
  323. p = 0; // path index
  324. var pi: number = 0; // positions array index
  325. var l1: number = lg[p] - 1; // path1 length
  326. var l2: number = lg[p + 1] - 1; // path2 length
  327. var min: number = (l1 < l2) ? l1 : l2; // current path stop index
  328. var shft: number = idx[1] - idx[0]; // shift
  329. var path1nb: number = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  330. var t1: number; // two consecutive triangles, so 4 points : point1
  331. var t2: number; // point2
  332. var t3: number; // point3
  333. var t4: number; // point4
  334. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  335. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  336. t1 = pi;
  337. t2 = pi + shft;
  338. t3 = pi + 1;
  339. t4 = pi + shft + 1;
  340. indices.push(pi, pi + shft, pi + 1);
  341. indices.push(pi + shft + 1, pi + 1, pi + shft);
  342. pi += 1;
  343. if (pi === min) { // if end of one of two consecutive paths reached, go next existing path
  344. if (closePath) { // if closePath, add last triangles between start and end of the paths
  345. indices.push(pi, pi + shft, idx[p]);
  346. indices.push(idx[p] + shft, idx[p], pi + shft);
  347. t3 = idx[p];
  348. t4 = idx[p] + shft;
  349. }
  350. p++;
  351. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  352. shft = idx[0] - idx[p];
  353. l1 = lg[p] - 1;
  354. l2 = lg[0] - 1;
  355. }
  356. else {
  357. shft = idx[p + 1] - idx[p];
  358. l1 = lg[p] - 1;
  359. l2 = lg[p + 1] - 1;
  360. }
  361. pi = idx[p];
  362. min = (l1 < l2) ? l1 + pi : l2 + pi;
  363. }
  364. }
  365. // normals
  366. VertexData.ComputeNormals(positions, indices, normals);
  367. // Result
  368. var vertexData = new VertexData();
  369. vertexData.indices = indices;
  370. vertexData.positions = positions;
  371. vertexData.normals = normals;
  372. vertexData.uvs = uvs;
  373. return vertexData;
  374. }
  375. public static CreateBox(size: number): VertexData {
  376. var normalsSource = [
  377. new Vector3(0, 0, 1),
  378. new Vector3(0, 0, -1),
  379. new Vector3(1, 0, 0),
  380. new Vector3(-1, 0, 0),
  381. new Vector3(0, 1, 0),
  382. new Vector3(0, -1, 0)
  383. ];
  384. var indices = [];
  385. var positions = [];
  386. var normals = [];
  387. var uvs = [];
  388. size = size || 1;
  389. // Create each face in turn.
  390. for (var index = 0; index < normalsSource.length; index++) {
  391. var normal = normalsSource[index];
  392. // Get two vectors perpendicular to the face normal and to each other.
  393. var side1 = new Vector3(normal.y, normal.z, normal.x);
  394. var side2 = Vector3.Cross(normal, side1);
  395. // Six indices (two triangles) per face.
  396. var verticesLength = positions.length / 3;
  397. indices.push(verticesLength);
  398. indices.push(verticesLength + 1);
  399. indices.push(verticesLength + 2);
  400. indices.push(verticesLength);
  401. indices.push(verticesLength + 2);
  402. indices.push(verticesLength + 3);
  403. // Four vertices per face.
  404. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  405. positions.push(vertex.x, vertex.y, vertex.z);
  406. normals.push(normal.x, normal.y, normal.z);
  407. uvs.push(1.0, 1.0);
  408. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  409. positions.push(vertex.x, vertex.y, vertex.z);
  410. normals.push(normal.x, normal.y, normal.z);
  411. uvs.push(0.0, 1.0);
  412. vertex = normal.add(side1).add(side2).scale(size / 2);
  413. positions.push(vertex.x, vertex.y, vertex.z);
  414. normals.push(normal.x, normal.y, normal.z);
  415. uvs.push(0.0, 0.0);
  416. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  417. positions.push(vertex.x, vertex.y, vertex.z);
  418. normals.push(normal.x, normal.y, normal.z);
  419. uvs.push(1.0, 0.0);
  420. }
  421. // Result
  422. var vertexData = new VertexData();
  423. vertexData.indices = indices;
  424. vertexData.positions = positions;
  425. vertexData.normals = normals;
  426. vertexData.uvs = uvs;
  427. return vertexData;
  428. }
  429. public static CreateSphere(segments: number, diameter: number): VertexData {
  430. segments = segments || 32;
  431. diameter = diameter || 1;
  432. var radius = diameter / 2;
  433. var totalZRotationSteps = 2 + segments;
  434. var totalYRotationSteps = 2 * totalZRotationSteps;
  435. var indices = [];
  436. var positions = [];
  437. var normals = [];
  438. var uvs = [];
  439. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  440. var normalizedZ = zRotationStep / totalZRotationSteps;
  441. var angleZ = (normalizedZ * Math.PI);
  442. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  443. var normalizedY = yRotationStep / totalYRotationSteps;
  444. var angleY = normalizedY * Math.PI * 2;
  445. var rotationZ = Matrix.RotationZ(-angleZ);
  446. var rotationY = Matrix.RotationY(angleY);
  447. var afterRotZ = Vector3.TransformCoordinates(Vector3.Up(), rotationZ);
  448. var complete = Vector3.TransformCoordinates(afterRotZ, rotationY);
  449. var vertex = complete.scale(radius);
  450. var normal = Vector3.Normalize(vertex);
  451. positions.push(vertex.x, vertex.y, vertex.z);
  452. normals.push(normal.x, normal.y, normal.z);
  453. uvs.push(normalizedZ, normalizedY);
  454. }
  455. if (zRotationStep > 0) {
  456. var verticesCount = positions.length / 3;
  457. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  458. indices.push((firstIndex));
  459. indices.push((firstIndex + 1));
  460. indices.push(firstIndex + totalYRotationSteps + 1);
  461. indices.push((firstIndex + totalYRotationSteps + 1));
  462. indices.push((firstIndex + 1));
  463. indices.push((firstIndex + totalYRotationSteps + 2));
  464. }
  465. }
  466. }
  467. // Result
  468. var vertexData = new VertexData();
  469. vertexData.indices = indices;
  470. vertexData.positions = positions;
  471. vertexData.normals = normals;
  472. vertexData.uvs = uvs;
  473. return vertexData;
  474. }
  475. public static CreateCylinder(height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: number = 1): VertexData {
  476. var radiusTop = diameterTop / 2;
  477. var radiusBottom = diameterBottom / 2;
  478. var indices = [];
  479. var positions = [];
  480. var normals = [];
  481. var uvs = [];
  482. height = height || 1;
  483. diameterTop = diameterTop || 0.5;
  484. diameterBottom = diameterBottom || 1;
  485. tessellation = tessellation || 16;
  486. subdivisions = subdivisions || 1;
  487. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  488. var getCircleVector = i => {
  489. var angle = (i * 2.0 * Math.PI / tessellation);
  490. var dx = Math.cos(angle);
  491. var dz = Math.sin(angle);
  492. return new Vector3(dx, 0, dz);
  493. };
  494. var createCylinderCap = isTop => {
  495. var radius = isTop ? radiusTop : radiusBottom;
  496. if (radius === 0) {
  497. return;
  498. }
  499. var vbase = positions.length / 3;
  500. var offset = new Vector3(0, height / 2, 0);
  501. var textureScale = new Vector2(0.5, 0.5);
  502. if (!isTop) {
  503. offset.scaleInPlace(-1);
  504. textureScale.x = -textureScale.x;
  505. }
  506. // Positions, normals & uvs
  507. for (var i = 0; i < tessellation; i++) {
  508. var circleVector = getCircleVector(i);
  509. var position = circleVector.scale(radius).add(offset);
  510. var textureCoordinate = new Vector2(
  511. circleVector.x * textureScale.x + 0.5,
  512. circleVector.z * textureScale.y + 0.5
  513. );
  514. positions.push(position.x, position.y, position.z);
  515. uvs.push(textureCoordinate.x, textureCoordinate.y);
  516. }
  517. // Indices
  518. for (i = 0; i < tessellation - 2; i++) {
  519. if (!isTop) {
  520. indices.push(vbase);
  521. indices.push(vbase + (i + 2) % tessellation);
  522. indices.push(vbase + (i + 1) % tessellation);
  523. } else {
  524. indices.push(vbase);
  525. indices.push(vbase + (i + 1) % tessellation);
  526. indices.push(vbase + (i + 2) % tessellation);
  527. }
  528. }
  529. };
  530. var base = new Vector3(0, -1, 0).scale(height / 2);
  531. var offset = new Vector3(0, 1, 0).scale(height / subdivisions);
  532. var stride = tessellation + 1;
  533. // Positions, normals & uvs
  534. for (var i = 0; i <= tessellation; i++) {
  535. var circleVector = getCircleVector(i);
  536. var textureCoordinate = new Vector2(i / tessellation, 0);
  537. var position: Vector3, radius = radiusBottom;
  538. for (var s = 0; s <= subdivisions; s++) {
  539. // Update variables
  540. position = circleVector.scale(radius);
  541. position.addInPlace(base.add(offset.scale(s)));
  542. textureCoordinate.y += 1 / subdivisions;
  543. radius += (radiusTop - radiusBottom) / subdivisions;
  544. // Push in arrays
  545. positions.push(position.x, position.y, position.z);
  546. uvs.push(textureCoordinate.x, textureCoordinate.y);
  547. }
  548. }
  549. subdivisions += 1;
  550. // Indices
  551. for (s = 0; s < subdivisions - 1; s++) {
  552. for (i = 0; i <= tessellation; i++) {
  553. indices.push(i * subdivisions + s);
  554. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  555. indices.push(i * subdivisions + (s + 1));
  556. indices.push(i * subdivisions + (s + 1));
  557. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  558. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  559. }
  560. }
  561. // Create flat triangle fan caps to seal the top and bottom.
  562. createCylinderCap(true);
  563. createCylinderCap(false);
  564. // Normals
  565. VertexData.ComputeNormals(positions, indices, normals);
  566. // Result
  567. var vertexData = new VertexData();
  568. vertexData.indices = indices;
  569. vertexData.positions = positions;
  570. vertexData.normals = normals;
  571. vertexData.uvs = uvs;
  572. return vertexData;
  573. }
  574. public static CreateTorus(diameter, thickness, tessellation) {
  575. var indices = [];
  576. var positions = [];
  577. var normals = [];
  578. var uvs = [];
  579. diameter = diameter || 1;
  580. thickness = thickness || 0.5;
  581. tessellation = tessellation || 16;
  582. var stride = tessellation + 1;
  583. for (var i = 0; i <= tessellation; i++) {
  584. var u = i / tessellation;
  585. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  586. var transform = Matrix.Translation(diameter / 2.0, 0, 0).multiply(Matrix.RotationY(outerAngle));
  587. for (var j = 0; j <= tessellation; j++) {
  588. var v = 1 - j / tessellation;
  589. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  590. var dx = Math.cos(innerAngle);
  591. var dy = Math.sin(innerAngle);
  592. // Create a vertex.
  593. var normal = new Vector3(dx, dy, 0);
  594. var position = normal.scale(thickness / 2);
  595. var textureCoordinate = new Vector2(u, v);
  596. position = Vector3.TransformCoordinates(position, transform);
  597. normal = Vector3.TransformNormal(normal, transform);
  598. positions.push(position.x, position.y, position.z);
  599. normals.push(normal.x, normal.y, normal.z);
  600. uvs.push(textureCoordinate.x, textureCoordinate.y);
  601. // And create indices for two triangles.
  602. var nextI = (i + 1) % stride;
  603. var nextJ = (j + 1) % stride;
  604. indices.push(i * stride + j);
  605. indices.push(i * stride + nextJ);
  606. indices.push(nextI * stride + j);
  607. indices.push(i * stride + nextJ);
  608. indices.push(nextI * stride + nextJ);
  609. indices.push(nextI * stride + j);
  610. }
  611. }
  612. // Result
  613. var vertexData = new VertexData();
  614. vertexData.indices = indices;
  615. vertexData.positions = positions;
  616. vertexData.normals = normals;
  617. vertexData.uvs = uvs;
  618. return vertexData;
  619. }
  620. public static CreateLines(points: Vector3[]): VertexData {
  621. var indices = [];
  622. var positions = [];
  623. for (var index = 0; index < points.length; index++) {
  624. positions.push(points[index].x, points[index].y, points[index].z);
  625. if (index > 0) {
  626. indices.push(index - 1);
  627. indices.push(index);
  628. }
  629. }
  630. // Result
  631. var vertexData = new VertexData();
  632. vertexData.indices = indices;
  633. vertexData.positions = positions;
  634. return vertexData;
  635. }
  636. public static CreateGround(width: number, height: number, subdivisions: number): VertexData {
  637. var indices = [];
  638. var positions = [];
  639. var normals = [];
  640. var uvs = [];
  641. var row: number, col: number;
  642. width = width || 1;
  643. height = height || 1;
  644. subdivisions = subdivisions || 1;
  645. for (row = 0; row <= subdivisions; row++) {
  646. for (col = 0; col <= subdivisions; col++) {
  647. var position = new Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  648. var normal = new Vector3(0, 1.0, 0);
  649. positions.push(position.x, position.y, position.z);
  650. normals.push(normal.x, normal.y, normal.z);
  651. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  652. }
  653. }
  654. for (row = 0; row < subdivisions; row++) {
  655. for (col = 0; col < subdivisions; col++) {
  656. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  657. indices.push(col + 1 + row * (subdivisions + 1));
  658. indices.push(col + row * (subdivisions + 1));
  659. indices.push(col + (row + 1) * (subdivisions + 1));
  660. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  661. indices.push(col + row * (subdivisions + 1));
  662. }
  663. }
  664. // Result
  665. var vertexData = new VertexData();
  666. vertexData.indices = indices;
  667. vertexData.positions = positions;
  668. vertexData.normals = normals;
  669. vertexData.uvs = uvs;
  670. return vertexData;
  671. }
  672. public static CreateTiledGround(xmin: number, zmin: number, xmax: number, zmax: number, subdivisions = { w: 1, h: 1 }, precision = { w: 1, h: 1 }): VertexData {
  673. var indices = [];
  674. var positions = [];
  675. var normals = [];
  676. var uvs = [];
  677. var row: number, col: number, tileRow: number, tileCol: number;
  678. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  679. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  680. precision.w = (precision.w < 1) ? 1 : precision.w;
  681. precision.h = (precision.h < 1) ? 1 : precision.h;
  682. var tileSize = {
  683. 'w': (xmax - xmin) / subdivisions.w,
  684. 'h': (zmax - zmin) / subdivisions.h
  685. };
  686. function applyTile(xTileMin: number, zTileMin: number, xTileMax: number, zTileMax: number) {
  687. // Indices
  688. var base = positions.length / 3;
  689. var rowLength = precision.w + 1;
  690. for (row = 0; row < precision.h; row++) {
  691. for (col = 0; col < precision.w; col++) {
  692. var square = [
  693. base + col + row * rowLength,
  694. base + (col + 1) + row * rowLength,
  695. base + (col + 1) + (row + 1) * rowLength,
  696. base + col + (row + 1) * rowLength
  697. ];
  698. indices.push(square[1]);
  699. indices.push(square[2]);
  700. indices.push(square[3]);
  701. indices.push(square[0]);
  702. indices.push(square[1]);
  703. indices.push(square[3]);
  704. }
  705. }
  706. // Position, normals and uvs
  707. var position = Vector3.Zero();
  708. var normal = new Vector3(0, 1.0, 0);
  709. for (row = 0; row <= precision.h; row++) {
  710. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  711. for (col = 0; col <= precision.w; col++) {
  712. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  713. position.y = 0;
  714. positions.push(position.x, position.y, position.z);
  715. normals.push(normal.x, normal.y, normal.z);
  716. uvs.push(col / precision.w, row / precision.h);
  717. }
  718. }
  719. }
  720. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  721. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  722. applyTile(
  723. xmin + tileCol * tileSize.w,
  724. zmin + tileRow * tileSize.h,
  725. xmin + (tileCol + 1) * tileSize.w,
  726. zmin + (tileRow + 1) * tileSize.h
  727. );
  728. }
  729. }
  730. // Result
  731. var vertexData = new VertexData();
  732. vertexData.indices = indices;
  733. vertexData.positions = positions;
  734. vertexData.normals = normals;
  735. vertexData.uvs = uvs;
  736. return vertexData;
  737. }
  738. public static CreateGroundFromHeightMap(width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, buffer: Uint8Array, bufferWidth: number, bufferHeight: number): VertexData {
  739. var indices = [];
  740. var positions = [];
  741. var normals = [];
  742. var uvs = [];
  743. var row, col;
  744. // Vertices
  745. for (row = 0; row <= subdivisions; row++) {
  746. for (col = 0; col <= subdivisions; col++) {
  747. var position = new Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  748. // Compute height
  749. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  750. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  751. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  752. var r = buffer[pos] / 255.0;
  753. var g = buffer[pos + 1] / 255.0;
  754. var b = buffer[pos + 2] / 255.0;
  755. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  756. position.y = minHeight + (maxHeight - minHeight) * gradient;
  757. // Add vertex
  758. positions.push(position.x, position.y, position.z);
  759. normals.push(0, 0, 0);
  760. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  761. }
  762. }
  763. // Indices
  764. for (row = 0; row < subdivisions; row++) {
  765. for (col = 0; col < subdivisions; col++) {
  766. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  767. indices.push(col + 1 + row * (subdivisions + 1));
  768. indices.push(col + row * (subdivisions + 1));
  769. indices.push(col + (row + 1) * (subdivisions + 1));
  770. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  771. indices.push(col + row * (subdivisions + 1));
  772. }
  773. }
  774. // Normals
  775. VertexData.ComputeNormals(positions, indices, normals);
  776. // Result
  777. var vertexData = new VertexData();
  778. vertexData.indices = indices;
  779. vertexData.positions = positions;
  780. vertexData.normals = normals;
  781. vertexData.uvs = uvs;
  782. return vertexData;
  783. }
  784. public static CreatePlane(size: number): VertexData {
  785. var indices = [];
  786. var positions = [];
  787. var normals = [];
  788. var uvs = [];
  789. size = size || 1;
  790. // Vertices
  791. var halfSize = size / 2.0;
  792. positions.push(-halfSize, -halfSize, 0);
  793. normals.push(0, 0, -1.0);
  794. uvs.push(0.0, 0.0);
  795. positions.push(halfSize, -halfSize, 0);
  796. normals.push(0, 0, -1.0);
  797. uvs.push(1.0, 0.0);
  798. positions.push(halfSize, halfSize, 0);
  799. normals.push(0, 0, -1.0);
  800. uvs.push(1.0, 1.0);
  801. positions.push(-halfSize, halfSize, 0);
  802. normals.push(0, 0, -1.0);
  803. uvs.push(0.0, 1.0);
  804. // Indices
  805. indices.push(0);
  806. indices.push(1);
  807. indices.push(2);
  808. indices.push(0);
  809. indices.push(2);
  810. indices.push(3);
  811. // Result
  812. var vertexData = new VertexData();
  813. vertexData.indices = indices;
  814. vertexData.positions = positions;
  815. vertexData.normals = normals;
  816. vertexData.uvs = uvs;
  817. return vertexData;
  818. }
  819. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  820. public static CreateTorusKnot(radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number): VertexData {
  821. var indices = [];
  822. var positions = [];
  823. var normals = [];
  824. var uvs = [];
  825. radius = radius || 2;
  826. tube = tube || 0.5;
  827. radialSegments = radialSegments || 32;
  828. tubularSegments = tubularSegments || 32;
  829. p = p || 2;
  830. q = q || 3;
  831. // Helper
  832. var getPos = (angle) => {
  833. var cu = Math.cos(angle);
  834. var su = Math.sin(angle);
  835. var quOverP = q / p * angle;
  836. var cs = Math.cos(quOverP);
  837. var tx = radius * (2 + cs) * 0.5 * cu;
  838. var ty = radius * (2 + cs) * su * 0.5;
  839. var tz = radius * Math.sin(quOverP) * 0.5;
  840. return new Vector3(tx, ty, tz);
  841. };
  842. // Vertices
  843. for (var i = 0; i <= radialSegments; i++) {
  844. var modI = i % radialSegments;
  845. var u = modI / radialSegments * 2 * p * Math.PI;
  846. var p1 = getPos(u);
  847. var p2 = getPos(u + 0.01);
  848. var tang = p2.subtract(p1);
  849. var n = p2.add(p1);
  850. var bitan = Vector3.Cross(tang, n);
  851. n = Vector3.Cross(bitan, tang);
  852. bitan.normalize();
  853. n.normalize();
  854. for (var j = 0; j < tubularSegments; j++) {
  855. var modJ = j % tubularSegments;
  856. var v = modJ / tubularSegments * 2 * Math.PI;
  857. var cx = -tube * Math.cos(v);
  858. var cy = tube * Math.sin(v);
  859. positions.push(p1.x + cx * n.x + cy * bitan.x);
  860. positions.push(p1.y + cx * n.y + cy * bitan.y);
  861. positions.push(p1.z + cx * n.z + cy * bitan.z);
  862. uvs.push(i / radialSegments);
  863. uvs.push(j / tubularSegments);
  864. }
  865. }
  866. for (i = 0; i < radialSegments; i++) {
  867. for (j = 0; j < tubularSegments; j++) {
  868. var jNext = (j + 1) % tubularSegments;
  869. var a = i * tubularSegments + j;
  870. var b = (i + 1) * tubularSegments + j;
  871. var c = (i + 1) * tubularSegments + jNext;
  872. var d = i * tubularSegments + jNext;
  873. indices.push(d); indices.push(b); indices.push(a);
  874. indices.push(d); indices.push(c); indices.push(b);
  875. }
  876. }
  877. // Normals
  878. VertexData.ComputeNormals(positions, indices, normals);
  879. // Result
  880. var vertexData = new VertexData();
  881. vertexData.indices = indices;
  882. vertexData.positions = positions;
  883. vertexData.normals = normals;
  884. vertexData.uvs = uvs;
  885. return vertexData;
  886. }
  887. // Tools
  888. public static ComputeNormals(positions: number[], indices: number[], normals: number[]) {
  889. var positionVectors = [];
  890. var facesOfVertices = [];
  891. var index;
  892. for (index = 0; index < positions.length; index += 3) {
  893. var vector3 = new Vector3(positions[index], positions[index + 1], positions[index + 2]);
  894. positionVectors.push(vector3);
  895. facesOfVertices.push([]);
  896. }
  897. // Compute normals
  898. var facesNormals = [];
  899. for (index = 0; index < indices.length / 3; index++) {
  900. var i1 = indices[index * 3];
  901. var i2 = indices[index * 3 + 1];
  902. var i3 = indices[index * 3 + 2];
  903. var p1 = positionVectors[i1];
  904. var p2 = positionVectors[i2];
  905. var p3 = positionVectors[i3];
  906. var p1p2 = p1.subtract(p2);
  907. var p3p2 = p3.subtract(p2);
  908. facesNormals[index] = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  909. facesOfVertices[i1].push(index);
  910. facesOfVertices[i2].push(index);
  911. facesOfVertices[i3].push(index);
  912. }
  913. for (index = 0; index < positionVectors.length; index++) {
  914. var faces = facesOfVertices[index];
  915. var normal = Vector3.Zero();
  916. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  917. normal.addInPlace(facesNormals[faces[faceIndex]]);
  918. }
  919. normal = Vector3.Normalize(normal.scale(1.0 / faces.length));
  920. normals[index * 3] = normal.x;
  921. normals[index * 3 + 1] = normal.y;
  922. normals[index * 3 + 2] = normal.z;
  923. }
  924. }
  925. }
  926. }