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.

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