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.

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