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.

678 lines
21 KiB

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