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.

84 lines
2.3 KiB

  1. /**
  2. * @class RepulsionSolver
  3. */
  4. class RepulsionSolver {
  5. /**
  6. * @param {Object} body
  7. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  8. * @param {Object} options
  9. * @constructor RepulsionSolver
  10. */
  11. constructor(body, physicsBody, options) {
  12. this.body = body;
  13. this.physicsBody = physicsBody;
  14. this.setOptions(options);
  15. }
  16. /**
  17. *
  18. * @param {Object} options
  19. */
  20. setOptions(options) {
  21. this.options = options;
  22. }
  23. /**
  24. * Calculate the forces the nodes apply on each other based on a repulsion field.
  25. * This field is linearly approximated.
  26. *
  27. * @private
  28. */
  29. solve() {
  30. var dx, dy, distance, fx, fy, repulsingForce, node1, node2;
  31. var nodes = this.body.nodes;
  32. var nodeIndices = this.physicsBody.physicsNodeIndices;
  33. var forces = this.physicsBody.forces;
  34. // repulsing forces between nodes
  35. var nodeDistance = this.options.nodeDistance;
  36. // approximation constants
  37. var a = (-2 / 3) / nodeDistance;
  38. var b = 4 / 3;
  39. // we loop from i over all but the last entree in the array
  40. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
  41. for (let i = 0; i < nodeIndices.length - 1; i++) {
  42. node1 = nodes[nodeIndices[i]];
  43. for (let j = i + 1; j < nodeIndices.length; j++) {
  44. node2 = nodes[nodeIndices[j]];
  45. dx = node2.x - node1.x;
  46. dy = node2.y - node1.y;
  47. distance = Math.sqrt(dx * dx + dy * dy);
  48. // same condition as BarnesHutSolver, making sure nodes are never 100% overlapping.
  49. if (distance === 0) {
  50. distance = 0.1*Math.random();
  51. dx = distance;
  52. }
  53. if (distance < 2 * nodeDistance) {
  54. if (distance < 0.5 * nodeDistance) {
  55. repulsingForce = 1.0;
  56. }
  57. else {
  58. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / nodeDistance - 1) * steepness))
  59. }
  60. repulsingForce = repulsingForce / distance;
  61. fx = dx * repulsingForce;
  62. fy = dy * repulsingForce;
  63. forces[node1.id].x -= fx;
  64. forces[node1.id].y -= fy;
  65. forces[node2.id].x += fx;
  66. forces[node2.id].y += fy;
  67. }
  68. }
  69. }
  70. }
  71. }
  72. export default RepulsionSolver;