Home Reference Source

src/math/integration.js

  1. import { INTEGRATION_TYPE_EULER } from './constants';
  2. import { DEFAULT_SYSTEM_DELTA } from '../core/constants';
  3.  
  4. /**
  5. * Performs euler integration on the particle.
  6. *
  7. * @param {Particle} particle - The particle to integrate
  8. * @param {number} time - The factor of time to use
  9. * @param {number} damping - The damping to use
  10. * @return void
  11. */
  12. const eulerIntegration = (particle, time, damping) => {
  13. if (particle.sleep) {
  14. return;
  15. }
  16.  
  17. particle.old.position.copy(particle.position);
  18. particle.old.velocity.copy(particle.velocity);
  19. particle.acceleration.scalar(1 / particle.mass);
  20. particle.velocity.add(particle.acceleration.scalar(time));
  21. particle.position.add(particle.old.velocity.scalar(time));
  22. damping &&
  23. particle.velocity.scalar(Math.pow(damping, time / DEFAULT_SYSTEM_DELTA));
  24. particle.acceleration.clear();
  25. };
  26.  
  27. /**
  28. * Performs the chosen integration on the particle.
  29. * Defaults to euler integration.
  30. *
  31. * @param {Particle} particle - The particle to integrate
  32. * @param {number} time - The factor of time to use
  33. * @param {number} damping - The damping to use
  34. * @param {string} [type=INTEGRATION_TYPE_EULER] - The algorithm to use
  35. * @return void
  36. */
  37. export const integrate = (
  38. particle,
  39. time,
  40. damping,
  41. type = INTEGRATION_TYPE_EULER
  42. ) => {
  43. switch (type) {
  44. case INTEGRATION_TYPE_EULER:
  45. eulerIntegration(particle, time, damping);
  46. break;
  47. default:
  48. eulerIntegration(particle, time, damping);
  49. }
  50. };