ParametricGeometry.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. /**
  2. * Parametric Surfaces Geometry
  3. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  4. */
  5. import {
  6. BufferGeometry,
  7. Float32BufferAttribute,
  8. Vector3
  9. } from 'three';
  10. class ParametricGeometry extends BufferGeometry {
  11. constructor( func = ( u, v, target ) => target.set( u, v, Math.cos( u ) * Math.sin( v ) ), slices = 8, stacks = 8 ) {
  12. super();
  13. this.type = 'ParametricGeometry';
  14. this.parameters = {
  15. func: func,
  16. slices: slices,
  17. stacks: stacks
  18. };
  19. // buffers
  20. const indices = [];
  21. const vertices = [];
  22. const normals = [];
  23. const uvs = [];
  24. const EPS = 0.00001;
  25. const normal = new Vector3();
  26. const p0 = new Vector3(), p1 = new Vector3();
  27. const pu = new Vector3(), pv = new Vector3();
  28. // generate vertices, normals and uvs
  29. const sliceCount = slices + 1;
  30. for ( let i = 0; i <= stacks; i ++ ) {
  31. const v = i / stacks;
  32. for ( let j = 0; j <= slices; j ++ ) {
  33. const u = j / slices;
  34. // vertex
  35. func( u, v, p0 );
  36. vertices.push( p0.x, p0.y, p0.z );
  37. // normal
  38. // approximate tangent vectors via finite differences
  39. if ( u - EPS >= 0 ) {
  40. func( u - EPS, v, p1 );
  41. pu.subVectors( p0, p1 );
  42. } else {
  43. func( u + EPS, v, p1 );
  44. pu.subVectors( p1, p0 );
  45. }
  46. if ( v - EPS >= 0 ) {
  47. func( u, v - EPS, p1 );
  48. pv.subVectors( p0, p1 );
  49. } else {
  50. func( u, v + EPS, p1 );
  51. pv.subVectors( p1, p0 );
  52. }
  53. // cross product of tangent vectors returns surface normal
  54. normal.crossVectors( pu, pv ).normalize();
  55. normals.push( normal.x, normal.y, normal.z );
  56. // uv
  57. uvs.push( u, v );
  58. }
  59. }
  60. // generate indices
  61. for ( let i = 0; i < stacks; i ++ ) {
  62. for ( let j = 0; j < slices; j ++ ) {
  63. const a = i * sliceCount + j;
  64. const b = i * sliceCount + j + 1;
  65. const c = ( i + 1 ) * sliceCount + j + 1;
  66. const d = ( i + 1 ) * sliceCount + j;
  67. // faces one and two
  68. indices.push( a, b, d );
  69. indices.push( b, c, d );
  70. }
  71. }
  72. // build geometry
  73. this.setIndex( indices );
  74. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  75. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  76. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  77. }
  78. }
  79. export { ParametricGeometry };