Sphere.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. /**
  2. * @author bhouston / http://exocortex.com
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. THREE.Sphere = function ( center, radius ) {
  6. this.center = center === undefined ? new THREE.Vector3() : center.clone();
  7. this.radius = radius === undefined ? 0 : radius;
  8. };
  9. THREE.Sphere.prototype = {
  10. constructor: THREE.Sphere,
  11. set: function ( center, radius ) {
  12. this.center.copy( center );
  13. this.radius = radius;
  14. return this;
  15. },
  16. setFromCenterAndPoints: function ( center, points ) {
  17. var maxRadiusSq = 0;
  18. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19. var radiusSq = center.distanceToSquared( points[ i ] );
  20. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  21. }
  22. this.center = center;
  23. this.radius = Math.sqrt( maxRadiusSq );
  24. return this;
  25. },
  26. copy: function ( sphere ) {
  27. this.center.copy( sphere.center );
  28. this.radius = sphere.radius;
  29. return this;
  30. },
  31. empty: function () {
  32. return ( this.radius <= 0 );
  33. },
  34. containsPoint: function ( point ) {
  35. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  36. },
  37. distanceToPoint: function ( point ) {
  38. return ( point.distanceTo( this.center ) - this.radius );
  39. },
  40. clampPoint: function ( point, optionalTarget ) {
  41. var deltaLengthSq = this.center.distanceToSquared( point );
  42. var result = optionalTarget || new THREE.Vector3();
  43. result.copy( point );
  44. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  45. result.subSelf( this.center ).normalize();
  46. result.multiplyScalar( this.radius ).addSelf( this.center );
  47. }
  48. return result;
  49. },
  50. bounds: function ( optionalTarget ) {
  51. var box = optionalTarget || new THREE.Box3();
  52. box.set( this.center, this.center );
  53. box.expandByScalar( this.radius );
  54. return box;
  55. },
  56. translate: function ( offset ) {
  57. this.center.addSelf( this.offset );
  58. return this;
  59. },
  60. scale: function ( factor ) {
  61. this.radius *= factor;
  62. return this;
  63. },
  64. equals: function ( sphere ) {
  65. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  66. },
  67. clone: function () {
  68. return new THREE.Sphere3().copy( this );
  69. }
  70. };