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.

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