SplineCurve.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { Curve } from '../core/Curve.js';
  2. import { CatmullRom } from '../core/Interpolations.js';
  3. import { Vector2 } from '../../math/Vector2.js';
  4. function SplineCurve( points /* array of Vector2 */ ) {
  5. Curve.call( this );
  6. this.type = 'SplineCurve';
  7. this.points = points || [];
  8. }
  9. SplineCurve.prototype = Object.create( Curve.prototype );
  10. SplineCurve.prototype.constructor = SplineCurve;
  11. SplineCurve.prototype.isSplineCurve = true;
  12. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  13. const point = optionalTarget || new Vector2();
  14. const points = this.points;
  15. const p = ( points.length - 1 ) * t;
  16. const intPoint = Math.floor( p );
  17. const weight = p - intPoint;
  18. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19. const p1 = points[ intPoint ];
  20. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  22. point.set(
  23. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  25. );
  26. return point;
  27. };
  28. SplineCurve.prototype.copy = function ( source ) {
  29. Curve.prototype.copy.call( this, source );
  30. this.points = [];
  31. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  32. const point = source.points[ i ];
  33. this.points.push( point.clone() );
  34. }
  35. return this;
  36. };
  37. SplineCurve.prototype.toJSON = function () {
  38. const data = Curve.prototype.toJSON.call( this );
  39. data.points = [];
  40. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  41. const point = this.points[ i ];
  42. data.points.push( point.toArray() );
  43. }
  44. return data;
  45. };
  46. SplineCurve.prototype.fromJSON = function ( json ) {
  47. Curve.prototype.fromJSON.call( this, json );
  48. this.points = [];
  49. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  50. const point = json.points[ i ];
  51. this.points.push( new Vector2().fromArray( point ) );
  52. }
  53. return this;
  54. };
  55. export { SplineCurve };