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.

536 lines
17 KiB

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