ConvexGeometry.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import {
  2. BufferGeometry,
  3. Float32BufferAttribute
  4. } from 'three';
  5. import { ConvexHull } from '../math/ConvexHull.js';
  6. /**
  7. * This class can be used to generate a convex hull for a given array of 3D points.
  8. * The average time complexity for this task is considered to be O(nlog(n)).
  9. *
  10. * ```js
  11. * const geometry = new ConvexGeometry( points );
  12. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  13. * const mesh = new THREE.Mesh( geometry, material );
  14. * scene.add( mesh );
  15. * ```
  16. *
  17. * @augments BufferGeometry
  18. */
  19. class ConvexGeometry extends BufferGeometry {
  20. /**
  21. * Constructs a new convex geometry.
  22. *
  23. * @param {Array<Vector3>} points - An array of points in 3D space which should be enclosed by the convex hull.
  24. */
  25. constructor( points = [] ) {
  26. super();
  27. // buffers
  28. const vertices = [];
  29. const normals = [];
  30. const convexHull = new ConvexHull().setFromPoints( points );
  31. // generate vertices and normals
  32. const faces = convexHull.faces;
  33. for ( let i = 0; i < faces.length; i ++ ) {
  34. const face = faces[ i ];
  35. let edge = face.edge;
  36. // we move along a doubly-connected edge list to access all face points (see HalfEdge docs)
  37. do {
  38. const point = edge.head().point;
  39. vertices.push( point.x, point.y, point.z );
  40. normals.push( face.normal.x, face.normal.y, face.normal.z );
  41. edge = edge.next;
  42. } while ( edge !== face.edge );
  43. }
  44. // build geometry
  45. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  46. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  47. }
  48. }
  49. export { ConvexGeometry };
粤ICP备19079148号