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.

79 lines
2.2 KiB

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