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.

60 lines
1.4 KiB

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