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.

72 lines
2.0 KiB

  1. /**
  2. * Created by Alex on 2/23/2015.
  3. */
  4. class HierarchicalRepulsionSolver {
  5. constructor(body, physicsBody, options) {
  6. this.body = body;
  7. this.physicsBody = physicsBody;
  8. this.setOptions(options);
  9. }
  10. setOptions(options) {
  11. this.options = options;
  12. }
  13. /**
  14. * Calculate the forces the nodes apply on each other based on a repulsion field.
  15. * This field is linearly approximated.
  16. *
  17. * @private
  18. */
  19. solve() {
  20. var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j;
  21. var nodes = this.body.nodes;
  22. var nodeIndices = this.physicsBody.physicsNodeIndices;
  23. var forces = this.physicsBody.forces;
  24. // repulsing forces between nodes
  25. var nodeDistance = this.options.nodeDistance;
  26. // we loop from i over all but the last entree in the array
  27. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i == j
  28. for (i = 0; i < nodeIndices.length - 1; i++) {
  29. node1 = nodes[nodeIndices[i]];
  30. for (j = i + 1; j < nodeIndices.length; j++) {
  31. node2 = nodes[nodeIndices[j]];
  32. // nodes only affect nodes on their level
  33. if (node1.level == node2.level) {
  34. dx = node2.x - node1.x;
  35. dy = node2.y - node1.y;
  36. distance = Math.sqrt(dx * dx + dy * dy);
  37. var steepness = 0.05;
  38. if (distance < nodeDistance) {
  39. repulsingForce = -Math.pow(steepness * distance, 2) + Math.pow(steepness * nodeDistance, 2);
  40. }
  41. else {
  42. repulsingForce = 0;
  43. }
  44. // normalize force with
  45. if (distance == 0) {
  46. distance = 0.01;
  47. }
  48. else {
  49. repulsingForce = repulsingForce / distance;
  50. }
  51. fx = dx * repulsingForce;
  52. fy = dy * repulsingForce;
  53. forces[node1.id].x -= fx;
  54. forces[node1.id].y -= fy;
  55. forces[node2.id].x += fx;
  56. forces[node2.id].y += fy;
  57. }
  58. }
  59. }
  60. }
  61. }
  62. export {HierarchicalRepulsionSolver};