babylon.mesh.vertexData.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  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 = [];
  238. var indices = [];
  239. var normals = [];
  240. var uvs = [];
  241. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  242. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  243. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  244. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  245. var minlg; // minimal length among all paths from pathArray
  246. var lg = []; // array of path lengths : nb of vertex per path
  247. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  248. // if single path in pathArray
  249. if (pathArray.length < 2) {
  250. var ar1 = [];
  251. var ar2 = [];
  252. for (var i = 0; i < pathArray[0].length - offset; i++) {
  253. ar1.push(pathArray[0][i]);
  254. ar2.push(pathArray[0][i + offset]);
  255. }
  256. pathArray = [ar1, ar2];
  257. }
  258. // positions and horizontal distances (u)
  259. var idc = 0;
  260. minlg = pathArray[0].length;
  261. for (p = 0; p < pathArray.length; p++) {
  262. uTotalDistance[p] = 0;
  263. us[p] = [0];
  264. var path = pathArray[p];
  265. var l = path.length;
  266. minlg = (minlg < l) ? minlg : l;
  267. lg[p] = l;
  268. idx[p] = idc;
  269. var j = 0;
  270. while (j < l) {
  271. positions.push(path[j].x, path[j].y, path[j].z);
  272. if (j > 0) {
  273. var vectlg = path[j].subtract(path[j - 1]).length();
  274. var dist = vectlg + uTotalDistance[p];
  275. us[p].push(dist);
  276. uTotalDistance[p] = dist;
  277. }
  278. j++;
  279. }
  280. if (closePath) {
  281. vectlg = path[0].subtract(path[j - 1]).length();
  282. dist = vectlg + uTotalDistance[p];
  283. uTotalDistance[p] = dist;
  284. }
  285. idc += l;
  286. }
  287. // vertical distances (v)
  288. for (i = 0; i < minlg; i++) {
  289. vTotalDistance[i] = 0;
  290. vs[i] = [0];
  291. for (p = 0; p < pathArray.length - 1; p++) {
  292. var path1 = pathArray[p];
  293. var path2 = pathArray[p + 1];
  294. vectlg = path2[i].subtract(path1[i]).length();
  295. dist = vectlg + vTotalDistance[i];
  296. vs[i].push(dist);
  297. vTotalDistance[i] = dist;
  298. }
  299. if (closeArray) {
  300. path1 = pathArray[p];
  301. path2 = pathArray[0];
  302. vectlg = path2[i].subtract(path1[i]).length();
  303. dist = vectlg + vTotalDistance[i];
  304. vTotalDistance[i] = dist;
  305. }
  306. }
  307. // uvs
  308. for (p = 0; p < pathArray.length; p++) {
  309. for (i = 0; i < minlg; i++) {
  310. var u = us[p][i] / uTotalDistance[p];
  311. var v = vs[i][p] / vTotalDistance[i];
  312. uvs.push(u, v);
  313. }
  314. }
  315. // indices
  316. var p = 0; // path index
  317. var i = 0; // positions array index
  318. var l1 = lg[p] - 1; // path1 length
  319. var l2 = lg[p + 1] - 1; // path2 length
  320. var min = (l1 < l2) ? l1 : l2; // current path stop index
  321. var shft = idx[1] - idx[0]; // shift
  322. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  323. while (i <= min && p < path1nb) { // stay under min and don't go over next to last path
  324. // draw two triangles between path1 (p1) and path2 (p2) : (p1.i, p2.i, p1.i+1) and (p2.i+1, p1.i+1, p2.i) clockwise
  325. var t1 = i;
  326. var t2 = i + shft;
  327. var t3 = i + 1;
  328. var t4 = i + shft + 1;
  329. indices.push(i, i + shft, i + 1);
  330. indices.push(i + shft + 1, i + 1, i + shft);
  331. i += 1;
  332. if (i === min) { // if end of one of two consecutive paths reached, go next existing path
  333. if (closePath) { // if closePath, add last triangles between start and end of the paths
  334. indices.push(i, i + shft, idx[p]);
  335. indices.push(idx[p] + shft, idx[p], i + shft);
  336. t3 = idx[p];
  337. t4 = idx[p] + shft;
  338. }
  339. p++;
  340. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  341. shft = idx[0] - idx[p];
  342. l1 = lg[p] - 1;
  343. l2 = lg[0] - 1;
  344. }
  345. else {
  346. shft = idx[p + 1] - idx[p];
  347. l1 = lg[p] - 1;
  348. l2 = lg[p + 1] - 1;
  349. }
  350. i = idx[p];
  351. min = (l1 < l2) ? l1 + i : l2 + i;
  352. }
  353. }
  354. // normals
  355. VertexData.ComputeNormals(positions, indices, normals);
  356. // Result
  357. var vertexData = new VertexData();
  358. vertexData.indices = indices;
  359. vertexData.positions = positions;
  360. vertexData.normals = normals;
  361. vertexData.uvs = uvs;
  362. return vertexData;
  363. }
  364. public static CreateBox(size: number): VertexData {
  365. var normalsSource = [
  366. new Vector3(0, 0, 1),
  367. new Vector3(0, 0, -1),
  368. new Vector3(1, 0, 0),
  369. new Vector3(-1, 0, 0),
  370. new Vector3(0, 1, 0),
  371. new Vector3(0, -1, 0)
  372. ];
  373. var indices = [];
  374. var positions = [];
  375. var normals = [];
  376. var uvs = [];
  377. size = size || 1;
  378. // Create each face in turn.
  379. for (var index = 0; index < normalsSource.length; index++) {
  380. var normal = normalsSource[index];
  381. // Get two vectors perpendicular to the face normal and to each other.
  382. var side1 = new Vector3(normal.y, normal.z, normal.x);
  383. var side2 = Vector3.Cross(normal, side1);
  384. // Six indices (two triangles) per face.
  385. var verticesLength = positions.length / 3;
  386. indices.push(verticesLength);
  387. indices.push(verticesLength + 1);
  388. indices.push(verticesLength + 2);
  389. indices.push(verticesLength);
  390. indices.push(verticesLength + 2);
  391. indices.push(verticesLength + 3);
  392. // Four vertices per face.
  393. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  394. positions.push(vertex.x, vertex.y, vertex.z);
  395. normals.push(normal.x, normal.y, normal.z);
  396. uvs.push(1.0, 1.0);
  397. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  398. positions.push(vertex.x, vertex.y, vertex.z);
  399. normals.push(normal.x, normal.y, normal.z);
  400. uvs.push(0.0, 1.0);
  401. vertex = normal.add(side1).add(side2).scale(size / 2);
  402. positions.push(vertex.x, vertex.y, vertex.z);
  403. normals.push(normal.x, normal.y, normal.z);
  404. uvs.push(0.0, 0.0);
  405. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  406. positions.push(vertex.x, vertex.y, vertex.z);
  407. normals.push(normal.x, normal.y, normal.z);
  408. uvs.push(1.0, 0.0);
  409. }
  410. // Result
  411. var vertexData = new VertexData();
  412. vertexData.indices = indices;
  413. vertexData.positions = positions;
  414. vertexData.normals = normals;
  415. vertexData.uvs = uvs;
  416. return vertexData;
  417. }
  418. public static CreateSphere(segments: number, diameter: number): VertexData {
  419. segments = segments || 32;
  420. diameter = diameter || 1;
  421. var radius = diameter / 2;
  422. var totalZRotationSteps = 2 + segments;
  423. var totalYRotationSteps = 2 * totalZRotationSteps;
  424. var indices = [];
  425. var positions = [];
  426. var normals = [];
  427. var uvs = [];
  428. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  429. var normalizedZ = zRotationStep / totalZRotationSteps;
  430. var angleZ = (normalizedZ * Math.PI);
  431. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  432. var normalizedY = yRotationStep / totalYRotationSteps;
  433. var angleY = normalizedY * Math.PI * 2;
  434. var rotationZ = Matrix.RotationZ(-angleZ);
  435. var rotationY = Matrix.RotationY(angleY);
  436. var afterRotZ = Vector3.TransformCoordinates(Vector3.Up(), rotationZ);
  437. var complete = Vector3.TransformCoordinates(afterRotZ, rotationY);
  438. var vertex = complete.scale(radius);
  439. var normal = Vector3.Normalize(vertex);
  440. positions.push(vertex.x, vertex.y, vertex.z);
  441. normals.push(normal.x, normal.y, normal.z);
  442. uvs.push(normalizedZ, normalizedY);
  443. }
  444. if (zRotationStep > 0) {
  445. var verticesCount = positions.length / 3;
  446. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  447. indices.push((firstIndex));
  448. indices.push((firstIndex + 1));
  449. indices.push(firstIndex + totalYRotationSteps + 1);
  450. indices.push((firstIndex + totalYRotationSteps + 1));
  451. indices.push((firstIndex + 1));
  452. indices.push((firstIndex + totalYRotationSteps + 2));
  453. }
  454. }
  455. }
  456. // Result
  457. var vertexData = new VertexData();
  458. vertexData.indices = indices;
  459. vertexData.positions = positions;
  460. vertexData.normals = normals;
  461. vertexData.uvs = uvs;
  462. return vertexData;
  463. }
  464. public static CreateCylinder(height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: number = 1): VertexData {
  465. var radiusTop = diameterTop / 2;
  466. var radiusBottom = diameterBottom / 2;
  467. var indices = [];
  468. var positions = [];
  469. var normals = [];
  470. var uvs = [];
  471. height = height || 1;
  472. diameterTop = diameterTop || 0.5;
  473. diameterBottom = diameterBottom || 1;
  474. tessellation = tessellation || 16;
  475. subdivisions = subdivisions || 1;
  476. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  477. var getCircleVector = i => {
  478. var angle = (i * 2.0 * Math.PI / tessellation);
  479. var dx = Math.cos(angle);
  480. var dz = Math.sin(angle);
  481. return new Vector3(dx, 0, dz);
  482. };
  483. var createCylinderCap = isTop => {
  484. var radius = isTop ? radiusTop : radiusBottom;
  485. if (radius === 0) {
  486. return;
  487. }
  488. var vbase = positions.length / 3;
  489. var offset = new Vector3(0, height / 2, 0);
  490. var textureScale = new Vector2(0.5, 0.5);
  491. if (!isTop) {
  492. offset.scaleInPlace(-1);
  493. textureScale.x = -textureScale.x;
  494. }
  495. // Positions, normals & uvs
  496. for (var i = 0; i < tessellation; i++) {
  497. var circleVector = getCircleVector(i);
  498. var position = circleVector.scale(radius).add(offset);
  499. var textureCoordinate = new Vector2(
  500. circleVector.x * textureScale.x + 0.5,
  501. circleVector.z * textureScale.y + 0.5
  502. );
  503. positions.push(position.x, position.y, position.z);
  504. uvs.push(textureCoordinate.x, textureCoordinate.y);
  505. }
  506. // Indices
  507. for (i = 0; i < tessellation - 2; i++) {
  508. if (!isTop) {
  509. indices.push(vbase);
  510. indices.push(vbase + (i + 2) % tessellation);
  511. indices.push(vbase + (i + 1) % tessellation);
  512. } else {
  513. indices.push(vbase);
  514. indices.push(vbase + (i + 1) % tessellation);
  515. indices.push(vbase + (i + 2) % tessellation);
  516. }
  517. }
  518. };
  519. var base = new Vector3(0, -1, 0).scale(height / 2);
  520. var offset = new Vector3(0, 1, 0).scale(height / subdivisions);
  521. var stride = tessellation + 1;
  522. // Positions, normals & uvs
  523. for (var i = 0; i <= tessellation; i++) {
  524. var circleVector = getCircleVector(i);
  525. var textureCoordinate = new Vector2(i / tessellation, 0);
  526. var position: Vector3, radius = radiusBottom;
  527. for (var s = 0; s <= subdivisions; s++) {
  528. // Update variables
  529. position = circleVector.scale(radius);
  530. position.addInPlace(base.add(offset.scale(s)));
  531. textureCoordinate.y += 1 / subdivisions;
  532. radius += (radiusTop - radiusBottom) / subdivisions;
  533. // Push in arrays
  534. positions.push(position.x, position.y, position.z);
  535. uvs.push(textureCoordinate.x, textureCoordinate.y);
  536. }
  537. }
  538. subdivisions += 1;
  539. // Indices
  540. for (s = 0; s < subdivisions - 1; s++) {
  541. for (i = 0; i <= tessellation; i++) {
  542. indices.push(i * subdivisions + s);
  543. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  544. indices.push(i * subdivisions + (s + 1));
  545. indices.push(i * subdivisions + (s + 1));
  546. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  547. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  548. }
  549. }
  550. // Create flat triangle fan caps to seal the top and bottom.
  551. createCylinderCap(true);
  552. createCylinderCap(false);
  553. // Normals
  554. VertexData.ComputeNormals(positions, indices, normals);
  555. // Result
  556. var vertexData = new VertexData();
  557. vertexData.indices = indices;
  558. vertexData.positions = positions;
  559. vertexData.normals = normals;
  560. vertexData.uvs = uvs;
  561. return vertexData;
  562. }
  563. public static CreateTorus(diameter, thickness, tessellation) {
  564. var indices = [];
  565. var positions = [];
  566. var normals = [];
  567. var uvs = [];
  568. diameter = diameter || 1;
  569. thickness = thickness || 0.5;
  570. tessellation = tessellation || 16;
  571. var stride = tessellation + 1;
  572. for (var i = 0; i <= tessellation; i++) {
  573. var u = i / tessellation;
  574. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  575. var transform = Matrix.Translation(diameter / 2.0, 0, 0).multiply(Matrix.RotationY(outerAngle));
  576. for (var j = 0; j <= tessellation; j++) {
  577. var v = 1 - j / tessellation;
  578. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  579. var dx = Math.cos(innerAngle);
  580. var dy = Math.sin(innerAngle);
  581. // Create a vertex.
  582. var normal = new Vector3(dx, dy, 0);
  583. var position = normal.scale(thickness / 2);
  584. var textureCoordinate = new Vector2(u, v);
  585. position = Vector3.TransformCoordinates(position, transform);
  586. normal = Vector3.TransformNormal(normal, transform);
  587. positions.push(position.x, position.y, position.z);
  588. normals.push(normal.x, normal.y, normal.z);
  589. uvs.push(textureCoordinate.x, textureCoordinate.y);
  590. // And create indices for two triangles.
  591. var nextI = (i + 1) % stride;
  592. var nextJ = (j + 1) % stride;
  593. indices.push(i * stride + j);
  594. indices.push(i * stride + nextJ);
  595. indices.push(nextI * stride + j);
  596. indices.push(i * stride + nextJ);
  597. indices.push(nextI * stride + nextJ);
  598. indices.push(nextI * stride + j);
  599. }
  600. }
  601. // Result
  602. var vertexData = new VertexData();
  603. vertexData.indices = indices;
  604. vertexData.positions = positions;
  605. vertexData.normals = normals;
  606. vertexData.uvs = uvs;
  607. return vertexData;
  608. }
  609. public static CreateLines(points: Vector3[]): VertexData {
  610. var indices = [];
  611. var positions = [];
  612. for (var index = 0; index < points.length; index++) {
  613. positions.push(points[index].x, points[index].y, points[index].z);
  614. if (index > 0) {
  615. indices.push(index - 1);
  616. indices.push(index);
  617. }
  618. }
  619. // Result
  620. var vertexData = new VertexData();
  621. vertexData.indices = indices;
  622. vertexData.positions = positions;
  623. return vertexData;
  624. }
  625. public static CreateGround(width: number, height: number, subdivisions: number): VertexData {
  626. var indices = [];
  627. var positions = [];
  628. var normals = [];
  629. var uvs = [];
  630. var row: number, col: number;
  631. width = width || 1;
  632. height = height || 1;
  633. subdivisions = subdivisions || 1;
  634. for (row = 0; row <= subdivisions; row++) {
  635. for (col = 0; col <= subdivisions; col++) {
  636. var position = new Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  637. var normal = new Vector3(0, 1.0, 0);
  638. positions.push(position.x, position.y, position.z);
  639. normals.push(normal.x, normal.y, normal.z);
  640. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  641. }
  642. }
  643. for (row = 0; row < subdivisions; row++) {
  644. for (col = 0; col < subdivisions; col++) {
  645. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  646. indices.push(col + 1 + row * (subdivisions + 1));
  647. indices.push(col + row * (subdivisions + 1));
  648. indices.push(col + (row + 1) * (subdivisions + 1));
  649. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  650. indices.push(col + row * (subdivisions + 1));
  651. }
  652. }
  653. // Result
  654. var vertexData = new VertexData();
  655. vertexData.indices = indices;
  656. vertexData.positions = positions;
  657. vertexData.normals = normals;
  658. vertexData.uvs = uvs;
  659. return vertexData;
  660. }
  661. public static CreateTiledGround(xmin: number, zmin: number, xmax: number, zmax: number, subdivisions = { w: 1, h: 1 }, precision = { w: 1, h: 1 }): VertexData {
  662. var indices = [];
  663. var positions = [];
  664. var normals = [];
  665. var uvs = [];
  666. var row: number, col: number, tileRow: number, tileCol: number;
  667. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  668. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  669. precision.w = (precision.w < 1) ? 1 : precision.w;
  670. precision.h = (precision.h < 1) ? 1 : precision.h;
  671. var tileSize = {
  672. 'w': (xmax - xmin) / subdivisions.w,
  673. 'h': (zmax - zmin) / subdivisions.h
  674. };
  675. function applyTile(xTileMin: number, zTileMin: number, xTileMax: number, zTileMax: number) {
  676. // Indices
  677. var base = positions.length / 3;
  678. var rowLength = precision.w + 1;
  679. for (row = 0; row < precision.h; row++) {
  680. for (col = 0; col < precision.w; col++) {
  681. var square = [
  682. base + col + row * rowLength,
  683. base + (col + 1) + row * rowLength,
  684. base + (col + 1) + (row + 1) * rowLength,
  685. base + col + (row + 1) * rowLength
  686. ];
  687. indices.push(square[1]);
  688. indices.push(square[2]);
  689. indices.push(square[3]);
  690. indices.push(square[0]);
  691. indices.push(square[1]);
  692. indices.push(square[3]);
  693. }
  694. }
  695. // Position, normals and uvs
  696. var position = Vector3.Zero();
  697. var normal = new Vector3(0, 1.0, 0);
  698. for (row = 0; row <= precision.h; row++) {
  699. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  700. for (col = 0; col <= precision.w; col++) {
  701. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  702. position.y = 0;
  703. positions.push(position.x, position.y, position.z);
  704. normals.push(normal.x, normal.y, normal.z);
  705. uvs.push(col / precision.w, row / precision.h);
  706. }
  707. }
  708. }
  709. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  710. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  711. applyTile(
  712. xmin + tileCol * tileSize.w,
  713. zmin + tileRow * tileSize.h,
  714. xmin + (tileCol + 1) * tileSize.w,
  715. zmin + (tileRow + 1) * tileSize.h
  716. );
  717. }
  718. }
  719. // Result
  720. var vertexData = new VertexData();
  721. vertexData.indices = indices;
  722. vertexData.positions = positions;
  723. vertexData.normals = normals;
  724. vertexData.uvs = uvs;
  725. return vertexData;
  726. }
  727. public static CreateGroundFromHeightMap(width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, buffer: Uint8Array, bufferWidth: number, bufferHeight: number): VertexData {
  728. var indices = [];
  729. var positions = [];
  730. var normals = [];
  731. var uvs = [];
  732. var row, col;
  733. // Vertices
  734. for (row = 0; row <= subdivisions; row++) {
  735. for (col = 0; col <= subdivisions; col++) {
  736. var position = new Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  737. // Compute height
  738. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  739. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  740. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  741. var r = buffer[pos] / 255.0;
  742. var g = buffer[pos + 1] / 255.0;
  743. var b = buffer[pos + 2] / 255.0;
  744. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  745. position.y = minHeight + (maxHeight - minHeight) * gradient;
  746. // Add vertex
  747. positions.push(position.x, position.y, position.z);
  748. normals.push(0, 0, 0);
  749. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  750. }
  751. }
  752. // Indices
  753. for (row = 0; row < subdivisions; row++) {
  754. for (col = 0; col < subdivisions; col++) {
  755. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  756. indices.push(col + 1 + row * (subdivisions + 1));
  757. indices.push(col + row * (subdivisions + 1));
  758. indices.push(col + (row + 1) * (subdivisions + 1));
  759. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  760. indices.push(col + row * (subdivisions + 1));
  761. }
  762. }
  763. // Normals
  764. VertexData.ComputeNormals(positions, indices, normals);
  765. // Result
  766. var vertexData = new VertexData();
  767. vertexData.indices = indices;
  768. vertexData.positions = positions;
  769. vertexData.normals = normals;
  770. vertexData.uvs = uvs;
  771. return vertexData;
  772. }
  773. public static CreatePlane(size: number): VertexData {
  774. var indices = [];
  775. var positions = [];
  776. var normals = [];
  777. var uvs = [];
  778. size = size || 1;
  779. // Vertices
  780. var halfSize = size / 2.0;
  781. positions.push(-halfSize, -halfSize, 0);
  782. normals.push(0, 0, -1.0);
  783. uvs.push(0.0, 0.0);
  784. positions.push(halfSize, -halfSize, 0);
  785. normals.push(0, 0, -1.0);
  786. uvs.push(1.0, 0.0);
  787. positions.push(halfSize, halfSize, 0);
  788. normals.push(0, 0, -1.0);
  789. uvs.push(1.0, 1.0);
  790. positions.push(-halfSize, halfSize, 0);
  791. normals.push(0, 0, -1.0);
  792. uvs.push(0.0, 1.0);
  793. // Indices
  794. indices.push(0);
  795. indices.push(1);
  796. indices.push(2);
  797. indices.push(0);
  798. indices.push(2);
  799. indices.push(3);
  800. // Result
  801. var vertexData = new VertexData();
  802. vertexData.indices = indices;
  803. vertexData.positions = positions;
  804. vertexData.normals = normals;
  805. vertexData.uvs = uvs;
  806. return vertexData;
  807. }
  808. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  809. public static CreateTorusKnot(radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number): VertexData {
  810. var indices = [];
  811. var positions = [];
  812. var normals = [];
  813. var uvs = [];
  814. radius = radius || 2;
  815. tube = tube || 0.5;
  816. radialSegments = radialSegments || 32;
  817. tubularSegments = tubularSegments || 32;
  818. p = p || 2;
  819. q = q || 3;
  820. // Helper
  821. var getPos = (angle) => {
  822. var cu = Math.cos(angle);
  823. var su = Math.sin(angle);
  824. var quOverP = q / p * angle;
  825. var cs = Math.cos(quOverP);
  826. var tx = radius * (2 + cs) * 0.5 * cu;
  827. var ty = radius * (2 + cs) * su * 0.5;
  828. var tz = radius * Math.sin(quOverP) * 0.5;
  829. return new Vector3(tx, ty, tz);
  830. };
  831. // Vertices
  832. for (var i = 0; i <= radialSegments; i++) {
  833. var modI = i % radialSegments;
  834. var u = modI / radialSegments * 2 * p * Math.PI;
  835. var p1 = getPos(u);
  836. var p2 = getPos(u + 0.01);
  837. var tang = p2.subtract(p1);
  838. var n = p2.add(p1);
  839. var bitan = Vector3.Cross(tang, n);
  840. n = Vector3.Cross(bitan, tang);
  841. bitan.normalize();
  842. n.normalize();
  843. for (var j = 0; j < tubularSegments; j++) {
  844. var modJ = j % tubularSegments;
  845. var v = modJ / tubularSegments * 2 * Math.PI;
  846. var cx = -tube * Math.cos(v);
  847. var cy = tube * Math.sin(v);
  848. positions.push(p1.x + cx * n.x + cy * bitan.x);
  849. positions.push(p1.y + cx * n.y + cy * bitan.y);
  850. positions.push(p1.z + cx * n.z + cy * bitan.z);
  851. uvs.push(i / radialSegments);
  852. uvs.push(j / tubularSegments);
  853. }
  854. }
  855. for (i = 0; i < radialSegments; i++) {
  856. for (j = 0; j < tubularSegments; j++) {
  857. var jNext = (j + 1) % tubularSegments;
  858. var a = i * tubularSegments + j;
  859. var b = (i + 1) * tubularSegments + j;
  860. var c = (i + 1) * tubularSegments + jNext;
  861. var d = i * tubularSegments + jNext;
  862. indices.push(d); indices.push(b); indices.push(a);
  863. indices.push(d); indices.push(c); indices.push(b);
  864. }
  865. }
  866. // Normals
  867. VertexData.ComputeNormals(positions, indices, normals);
  868. // Result
  869. var vertexData = new VertexData();
  870. vertexData.indices = indices;
  871. vertexData.positions = positions;
  872. vertexData.normals = normals;
  873. vertexData.uvs = uvs;
  874. return vertexData;
  875. }
  876. // Tools
  877. public static ComputeNormals(positions: number[], indices: number[], normals: number[]) {
  878. var positionVectors = [];
  879. var facesOfVertices = [];
  880. var index;
  881. for (index = 0; index < positions.length; index += 3) {
  882. var vector3 = new Vector3(positions[index], positions[index + 1], positions[index + 2]);
  883. positionVectors.push(vector3);
  884. facesOfVertices.push([]);
  885. }
  886. // Compute normals
  887. var facesNormals = [];
  888. for (index = 0; index < indices.length / 3; index++) {
  889. var i1 = indices[index * 3];
  890. var i2 = indices[index * 3 + 1];
  891. var i3 = indices[index * 3 + 2];
  892. var p1 = positionVectors[i1];
  893. var p2 = positionVectors[i2];
  894. var p3 = positionVectors[i3];
  895. var p1p2 = p1.subtract(p2);
  896. var p3p2 = p3.subtract(p2);
  897. facesNormals[index] = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  898. facesOfVertices[i1].push(index);
  899. facesOfVertices[i2].push(index);
  900. facesOfVertices[i3].push(index);
  901. }
  902. for (index = 0; index < positionVectors.length; index++) {
  903. var faces = facesOfVertices[index];
  904. var normal = Vector3.Zero();
  905. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  906. normal.addInPlace(facesNormals[faces[faceIndex]]);
  907. }
  908. normal = Vector3.Normalize(normal.scale(1.0 / faces.length));
  909. normals[index * 3] = normal.x;
  910. normals[index * 3 + 1] = normal.y;
  911. normals[index * 3 + 2] = normal.z;
  912. }
  913. }
  914. }
  915. }