ParametricGeometry.js 2.3 KB

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