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.

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