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.

457 lines
14 KiB

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