vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.5 KiB

  1. /**
  2. * @class CentralGravitySolver
  3. */
  4. class CentralGravitySolver {
  5. /**
  6. *
  7. * @param {Object} body
  8. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  9. * @param {Object} options
  10. * @constructor CentralGravitySolver
  11. */
  12. constructor(body, physicsBody, options) {
  13. this.body = body;
  14. this.physicsBody = physicsBody;
  15. this.setOptions(options);
  16. }
  17. /**
  18. *
  19. * @param {Object} options
  20. */
  21. setOptions(options) {
  22. this.options = options;
  23. }
  24. /**
  25. * Calculates forces for each node
  26. */
  27. solve() {
  28. let dx, dy, distance, node;
  29. let nodes = this.body.nodes;
  30. let nodeIndices = this.physicsBody.physicsNodeIndices;
  31. let forces = this.physicsBody.forces;
  32. for (let i = 0; i < nodeIndices.length; i++) {
  33. let nodeId = nodeIndices[i];
  34. node = nodes[nodeId];
  35. dx = -node.x;
  36. dy = -node.y;
  37. distance = Math.sqrt(dx * dx + dy * dy);
  38. this._calculateForces(distance, dx, dy, forces, node);
  39. }
  40. }
  41. /**
  42. * Calculate the forces based on the distance.
  43. * @param {number} distance
  44. * @param {number} dx
  45. * @param {number} dy
  46. * @param {Object<vis.Node.id, vis.Node>} forces
  47. * @param {vis.Node} node
  48. * @private
  49. */
  50. _calculateForces(distance, dx, dy, forces, node) {
  51. let gravityForce = (distance === 0) ? 0 : (this.options.centralGravity / distance);
  52. forces[node.id].x = dx * gravityForce;
  53. forces[node.id].y = dy * gravityForce;
  54. }
  55. }
  56. export default CentralGravitySolver;