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.

418 lines
13 KiB

  1. /**
  2. * Created by Alex on 2/23/2015.
  3. */
  4. import {BarnesHutSolver} from "./components/physics/BarnesHutSolver";
  5. import {Repulsion} from "./components/physics/RepulsionSolver";
  6. import {HierarchicalRepulsion} from "./components/physics/HierarchicalRepulsionSolver";
  7. import {SpringSolver} from "./components/physics/SpringSolver";
  8. import {HierarchicalSpringSolver} from "./components/physics/HierarchicalSpringSolver";
  9. import {CentralGravitySolver} from "./components/physics/CentralGravitySolver";
  10. var util = require('../../util');
  11. class PhysicsEngine {
  12. constructor(body, options) {
  13. this.body = body;
  14. this.physicsBody = {calculationNodes: {}, calculationNodeIndices:[], forces: {}, velocities: {}};
  15. this.scale = 1;
  16. this.viewFunction = undefined;
  17. this.body.emitter.on("_setScale", (scale) => this.scale = scale);
  18. this.simulationInterval = 1000 / 60;
  19. this.requiresTimeout = true;
  20. this.previousStates = {};
  21. this.renderTimer == undefined;
  22. this.stabilized = false;
  23. this.stabilizationIterations = 0;
  24. // default options
  25. this.options = {
  26. barnesHut: {
  27. thetaInverted: 1 / 0.5, // inverted to save time during calculation
  28. gravitationalConstant: -2000,
  29. centralGravity: 0.3,
  30. springLength: 95,
  31. springConstant: 0.04,
  32. damping: 0.09
  33. },
  34. repulsion: {
  35. centralGravity: 0.0,
  36. springLength: 200,
  37. springConstant: 0.05,
  38. nodeDistance: 100,
  39. damping: 0.09
  40. },
  41. hierarchicalRepulsion: {
  42. centralGravity: 0.0,
  43. springLength: 100,
  44. springConstant: 0.01,
  45. nodeDistance: 150,
  46. damping: 0.09
  47. },
  48. model: 'BarnesHut',
  49. timestep: 0.5,
  50. maxVelocity: 50,
  51. minVelocity: 0.1, // px/s
  52. stabilization: {
  53. enabled: true,
  54. iterations: 1000, // maximum number of iteration to stabilize
  55. updateInterval: 100,
  56. onlyDynamicEdges: false,
  57. zoomExtent: true
  58. }
  59. }
  60. this.setOptions(options);
  61. }
  62. setOptions(options) {
  63. if (options !== undefined) {
  64. if (typeof options.stabilization == 'boolean') {
  65. options.stabilization = {
  66. enabled: options.stabilization
  67. }
  68. }
  69. util.deepExtend(this.options, options);
  70. }
  71. this.init();
  72. }
  73. init() {
  74. var options;
  75. if (this.options.model == "repulsion") {
  76. options = this.options.repulsion;
  77. this.nodesSolver = new Repulsion(this.body, this.physicsBody, options);
  78. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  79. }
  80. else if (this.options.model == "hierarchicalRepulsion") {
  81. options = this.options.hierarchicalRepulsion;
  82. this.nodesSolver = new HierarchicalRepulsion(this.body, this.physicsBody, options);
  83. this.edgesSolver = new HierarchicalSpringSolver(this.body, this.physicsBody, options);
  84. }
  85. else { // barnesHut
  86. options = this.options.barnesHut;
  87. this.nodesSolver = new BarnesHutSolver(this.body, this.physicsBody, options);
  88. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  89. }
  90. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  91. this.modelOptions = options;
  92. }
  93. startSimulation() {
  94. this.stabilized = false;
  95. if (this.options.stabilization.enabled === true) {
  96. this.stabilize();
  97. }
  98. else {
  99. this.runSimulation();
  100. }
  101. }
  102. runSimulation() {
  103. if (this.viewFunction === undefined) {
  104. this.viewFunction = this.simulationStep.bind(this);
  105. this.body.emitter.on("_beforeRender", this.viewFunction);
  106. this.body.emitter.emit("_startRendering");
  107. }
  108. }
  109. simulationStep() {
  110. // check if the physics have settled
  111. var startTime = Date.now();
  112. this.physicsTick();
  113. var physicsTime = Date.now() - startTime;
  114. // run double speed if it is a little graph
  115. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed == true) && this.stabilized === false) {
  116. this.physicsTick();
  117. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  118. this.runDoubleSpeed = true;
  119. }
  120. if (this.stabilized === true) {
  121. if (this.stabilizationIterations > 1) {
  122. // trigger the "stabilized" event.
  123. // The event is triggered on the next tick, to prevent the case that
  124. // it is fired while initializing the Network, in which case you would not
  125. // be able to catch it
  126. var me = this;
  127. var params = {
  128. iterations: this.stabilizationIterations
  129. };
  130. this.stabilizationIterations = 0;
  131. this.startedStabilization = false;
  132. setTimeout(function () {
  133. me.body.emitter.emit("stabilized", params);
  134. }, 0);
  135. }
  136. else {
  137. this.stabilizationIterations = 0;
  138. }
  139. this.body.emitter.emit("_stopRendering");
  140. }
  141. }
  142. /**
  143. * A single simulation step (or "tick") in the physics simulation
  144. *
  145. * @private
  146. */
  147. physicsTick() {
  148. if (this.stabilized === false) {
  149. this.calculateForces();
  150. this.stabilized = this.moveNodes();
  151. // determine if the network has stabilzied
  152. if (this.stabilized === true) {
  153. this.revert();
  154. }
  155. else {
  156. // this is here to ensure that there is no start event when the network is already stable.
  157. if (this.startedStabilization == false) {
  158. this.body.emitter.emit("startStabilizing");
  159. this.startedStabilization = true;
  160. }
  161. }
  162. this.stabilizationIterations++;
  163. }
  164. }
  165. /**
  166. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  167. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  168. * This function joins the datanodes and invisible (called support) nodes into one object.
  169. * We do this so we do not contaminate this.body.nodes with the support nodes.
  170. *
  171. * @private
  172. */
  173. _updateCalculationNodes() {
  174. this.physicsBody.calculationNodes = {};
  175. this.physicsBody.forces = {};
  176. this.physicsBody.calculationNodeIndices = [];
  177. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  178. let nodeId = this.body.nodeIndices[i];
  179. this.physicsBody.calculationNodes[nodeId] = this.body.nodes[nodeId];
  180. }
  181. // if support nodes are used, we have them here
  182. var supportNodes = this.body.supportNodes;
  183. for (let i = 0; i < this.body.supportNodeIndices.length; i++) {
  184. let supportNodeId = this.body.supportNodeIndices[i];
  185. if (this.body.edges[supportNodes[supportNodeId].parentEdgeId] !== undefined) {
  186. this.physicsBody.calculationNodes[supportNodeId] = supportNodes[supportNodeId];
  187. }
  188. else {
  189. console.error("Support node detected that does not have an edge!")
  190. }
  191. }
  192. this.physicsBody.calculationNodeIndices = Object.keys(this.physicsBody.calculationNodes);
  193. for (let i = 0; i < this.physicsBody.calculationNodeIndices.length; i++) {
  194. let nodeId = this.physicsBody.calculationNodeIndices[i];
  195. this.physicsBody.forces[nodeId] = {x:0,y:0};
  196. // forces can be reset because they are recalculated. Velocities have to persist.
  197. if (this.physicsBody.velocities[nodeId] === undefined) {
  198. this.physicsBody.velocities[nodeId] = {x:0,y:0};
  199. }
  200. }
  201. // clean deleted nodes from the velocity vector
  202. for (let nodeId in this.physicsBody.velocities) {
  203. if (this.physicsBody.calculationNodes[nodeId] === undefined) {
  204. delete this.physicsBody.velocities[nodeId];
  205. }
  206. }
  207. }
  208. revert() {
  209. var nodeIds = Object.keys(this.previousStates);
  210. var nodes = this.physicsBody.calculationNodes;
  211. var velocities = this.physicsBody.velocities;
  212. for (let i = 0; i < nodeIds.length; i++) {
  213. let nodeId = nodeIds[i];
  214. if (nodes[nodeId] !== undefined) {
  215. velocities[nodeId].x = this.previousStates[nodeId].vx;
  216. velocities[nodeId].y = this.previousStates[nodeId].vy;
  217. nodes[nodeId].x = this.previousStates[nodeId].x;
  218. nodes[nodeId].y = this.previousStates[nodeId].y;
  219. }
  220. else {
  221. delete this.previousStates[nodeId];
  222. }
  223. }
  224. }
  225. moveNodes() {
  226. var nodesPresent = false;
  227. var nodeIndices = this.physicsBody.calculationNodeIndices;
  228. var maxVelocity = this.options.maxVelocity === 0 ? 1e9 : this.options.maxVelocity;
  229. var stabilized = true;
  230. var vminCorrected = this.options.minVelocity / Math.max(this.scale,0.05);
  231. for (let i = 0; i < nodeIndices.length; i++) {
  232. let nodeId = nodeIndices[i];
  233. let nodeVelocity = this._performStep(nodeId, maxVelocity);
  234. // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
  235. stabilized = nodeVelocity < vminCorrected && stabilized === true;
  236. nodesPresent = true;
  237. }
  238. if (nodesPresent == true) {
  239. if (vminCorrected > 0.5*this.options.maxVelocity) {
  240. return false;
  241. }
  242. else {
  243. return stabilized;
  244. }
  245. }
  246. return true;
  247. }
  248. _performStep(nodeId,maxVelocity) {
  249. var node = this.physicsBody.calculationNodes[nodeId];
  250. var timestep = this.options.timestep;
  251. var forces = this.physicsBody.forces;
  252. var velocities = this.physicsBody.velocities;
  253. // store the state so we can revert
  254. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  255. if (!node.xFixed) {
  256. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  257. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  258. velocities[nodeId].x += ax * timestep; // velocity
  259. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  260. node.x += velocities[nodeId].x * timestep; // position
  261. }
  262. else {
  263. forces[nodeId].x = 0;
  264. velocities[nodeId].x = 0;
  265. }
  266. if (!node.yFixed) {
  267. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  268. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  269. velocities[nodeId].y += ay * timestep; // velocity
  270. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  271. node.y += velocities[nodeId].y * timestep; // position
  272. }
  273. else {
  274. forces[nodeId].y = 0;
  275. velocities[nodeId].y = 0;
  276. }
  277. var totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  278. return totalVelocity;
  279. }
  280. calculateForces() {
  281. this.gravitySolver.solve();
  282. this.nodesSolver.solve();
  283. this.edgesSolver.solve();
  284. }
  285. /**
  286. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  287. * because only the supportnodes for the smoothCurves have to settle.
  288. *
  289. * @private
  290. */
  291. _freezeNodes() {
  292. var nodes = this.body.nodes;
  293. for (var id in nodes) {
  294. if (nodes.hasOwnProperty(id)) {
  295. if (nodes[id].x != null && nodes[id].y != null) {
  296. nodes[id].fixedData.x = nodes[id].xFixed;
  297. nodes[id].fixedData.y = nodes[id].yFixed;
  298. nodes[id].xFixed = true;
  299. nodes[id].yFixed = true;
  300. }
  301. }
  302. }
  303. }
  304. /**
  305. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  306. *
  307. * @private
  308. */
  309. _restoreFrozenNodes() {
  310. var nodes = this.body.nodes;
  311. for (var id in nodes) {
  312. if (nodes.hasOwnProperty(id)) {
  313. if (nodes[id].fixedData.x != null) {
  314. nodes[id].xFixed = nodes[id].fixedData.x;
  315. nodes[id].yFixed = nodes[id].fixedData.y;
  316. }
  317. }
  318. }
  319. }
  320. /**
  321. * Find a stable position for all nodes
  322. * @private
  323. */
  324. stabilize() {
  325. if (this.options.stabilization.onlyDynamicEdges == true) {
  326. this._freezeNodes();
  327. }
  328. this.stabilizationSteps = 0;
  329. setTimeout(this._stabilizationBatch.bind(this),0);
  330. }
  331. _stabilizationBatch() {
  332. var count = 0;
  333. while (this.stabilized == false && count < this.options.stabilization.updateInterval && this.stabilizationSteps < this.options.stabilization.iterations) {
  334. this.physicsTick();
  335. this.stabilizationSteps++;
  336. count++;
  337. }
  338. if (this.stabilized == false && this.stabilizationSteps < this.options.stabilization.iterations) {
  339. this.body.emitter.emit("stabilizationProgress", {steps: this.stabilizationSteps, total: this.options.stabilization.iterations});
  340. setTimeout(this._stabilizationBatch.bind(this),0);
  341. }
  342. else {
  343. this._finalizeStabilization();
  344. }
  345. }
  346. _finalizeStabilization() {
  347. if (this.options.stabilization.zoomExtent == true) {
  348. this.body.emitter.emit("zoomExtent", {duration:0});
  349. }
  350. if (this.options.stabilization.onlyDynamicEdges == true) {
  351. this._restoreFrozenNodes();
  352. }
  353. this.body.emitter.emit("stabilizationIterationsDone");
  354. this.body.emitter.emit("_requestRedraw");
  355. }
  356. }
  357. export {PhysicsEngine};