ConvexGeometry.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import {
  2. BufferGeometry,
  3. Float32BufferAttribute,
  4. Geometry
  5. } from "../../../build/three.module.js";
  6. import { ConvexHull } from "../math/ConvexHull.js";
  7. // ConvexGeometry
  8. var ConvexGeometry = function ( points ) {
  9. Geometry.call( this );
  10. this.fromBufferGeometry( new ConvexBufferGeometry( points ) );
  11. this.mergeVertices();
  12. };
  13. ConvexGeometry.prototype = Object.create( Geometry.prototype );
  14. ConvexGeometry.prototype.constructor = ConvexGeometry;
  15. // ConvexBufferGeometry
  16. var ConvexBufferGeometry = function ( points ) {
  17. BufferGeometry.call( this );
  18. // buffers
  19. var vertices = [];
  20. var normals = [];
  21. if ( ConvexHull === undefined ) {
  22. console.error( 'THREE.ConvexBufferGeometry: ConvexBufferGeometry relies on ConvexHull' );
  23. }
  24. var convexHull = new ConvexHull().setFromPoints( points );
  25. // generate vertices and normals
  26. var faces = convexHull.faces;
  27. for ( var i = 0; i < faces.length; i ++ ) {
  28. var face = faces[ i ];
  29. var edge = face.edge;
  30. // we move along a doubly-connected edge list to access all face points (see HalfEdge docs)
  31. do {
  32. var point = edge.head().point;
  33. vertices.push( point.x, point.y, point.z );
  34. normals.push( face.normal.x, face.normal.y, face.normal.z );
  35. edge = edge.next;
  36. } while ( edge !== face.edge );
  37. }
  38. // build geometry
  39. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  41. };
  42. ConvexBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  43. ConvexBufferGeometry.prototype.constructor = ConvexBufferGeometry;
  44. export { ConvexGeometry, ConvexBufferGeometry };