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.

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