Guest User

Plot function

a guest
Dec 17th, 2023
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const Plot = ({fx, length, resolution}) => {
  2.  
  3.     const vertices = [];
  4.     const indices = [];
  5.     const radialSegments = 50;
  6.     const rings = resolution;
  7.  
  8.     const addVertex = (v) => {
  9.       vertices.push(v.x,v.y,v.z);
  10.     }
  11.  
  12.     const addIndex = (x) => {
  13.       indices.push(x);
  14.     }
  15.  
  16.     const P = (x,y,dy,r,u) => {
  17.       const normal = -1/dy;
  18.       return {
  19.         x: x + r*Math.cos(u) * 1,
  20.         y: y + r*Math.cos(u) * normal,
  21.         z: r*Math.sin(u)
  22.       }
  23.     }
  24.     const U = (x) => {
  25.       return x/radialSegments * Math.PI * 2;
  26.     }
  27.     const X = (x) => {
  28.       return (x/rings-length/2);
  29.     }
  30.  
  31.     const r1 = 0.1;
  32.  
  33.     for(let i = 0; i < length*rings; i++) {
  34.       const x = X(i);
  35.       const x1 = X(i-1);
  36.  
  37.       const y = fx({x:x});
  38.       const y1 = fx({x:x1});
  39.  
  40.       const h = 1e-2;
  41.       const dy = (fx({x: x+h}) - fx({x :x-h})) / (2*h)
  42.       const dy1 = (fx({x: x1+h}) - fx({x :x1-h})) / (2*h)
  43.  
  44.       if(Math.abs(y) >= length/2)
  45.         continue;
  46.  
  47.       for(let j = 0; j <= radialSegments; j++) {
  48.  
  49.         const v0 = P( x,  y,  dy, r1, U(j)  );
  50.         const v1 = P( x,  y,  dy, r1, U(j+1));
  51.         const v2 = P(x1, y1, dy1, r1, U(j+1));
  52.         const v3 = P(x1, y1, dy1, r1, U(j)  );
  53.        
  54.         addVertex(v0);
  55.         addVertex(v1);
  56.         addVertex(v2);
  57.         addVertex(v3);
  58.        
  59.  
  60.         const index = vertices.length / 3;
  61.  
  62.         addIndex(index);
  63.         addIndex(index + 1);
  64.         addIndex(index + 2);
  65.  
  66.         addIndex(index);
  67.         addIndex(index + 2);
  68.         addIndex(index + 3);
  69.       }
  70.     }
  71.  
  72.     const positionAttribute = new BufferAttribute(new Float32Array(vertices), 3);
  73.     const indexAttribute = new BufferAttribute(new Uint32Array(indices), 1);
  74.     const customGeometry = new BufferGeometry();
  75.     customGeometry.setAttribute('position', positionAttribute);
  76.     customGeometry.setIndex(indexAttribute);
  77.     customGeometry.computeVertexNormals();
  78.     return (
  79.       <>
  80.       <mesh geometry={customGeometry}>
  81.         <meshStandardMaterial color={0xff0000} side={DoubleSide} flatShading={true}/>
  82.       </mesh>
  83.       </>
  84.      
  85.     )
  86. }
Advertisement
Add Comment
Please, Sign In to add comment