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.

74 lines
2.0 KiB

  1. /**
  2. * Created by Alex on 2/23/2015.
  3. */
  4. class SpringSolver {
  5. constructor(body, options) {
  6. this.body = body;
  7. this.options = options;
  8. }
  9. /**
  10. * This function calculates the springforces on the nodes, accounting for the support nodes.
  11. *
  12. * @private
  13. */
  14. solve() {
  15. var edgeLength, edge, edgeId;
  16. var edges = this.body.edges;
  17. // forces caused by the edges, modelled as springs
  18. for (edgeId in edges) {
  19. if (edges.hasOwnProperty(edgeId)) {
  20. edge = edges[edgeId];
  21. if (edge.connected === true) {
  22. // only calculate forces if nodes are in the same sector
  23. if (this.body.nodes[edge.toId] !== undefined && this.body.nodes[edge.fromId] !== undefined) {
  24. edgeLength = edge.properties.length === undefined ? this.options.springLength : edge.properties.length;
  25. if (edge.via != null) {
  26. var node1 = edge.to;
  27. var node2 = edge.via;
  28. var node3 = edge.from;
  29. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  30. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  31. }
  32. else {
  33. this._calculateSpringForce(edge.from, edge.to, edgeLength);
  34. }
  35. }
  36. }
  37. }
  38. }
  39. }
  40. /**
  41. * This is the code actually performing the calculation for the function above.
  42. *
  43. * @param node1
  44. * @param node2
  45. * @param edgeLength
  46. * @private
  47. */
  48. _calculateSpringForce(node1, node2, edgeLength) {
  49. var dx, dy, fx, fy, springForce, distance;
  50. dx = (node1.x - node2.x);
  51. dy = (node1.y - node2.y);
  52. distance = Math.sqrt(dx * dx + dy * dy);
  53. distance = distance == 0 ? 0.01 : distance;
  54. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  55. springForce = this.options.springConstant * (edgeLength - distance) / distance;
  56. fx = dx * springForce;
  57. fy = dy * springForce;
  58. node1.fx += fx;
  59. node1.fy += fy;
  60. node2.fx -= fx;
  61. node2.fy -= fy;
  62. }
  63. }
  64. export {SpringSolver};