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.

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