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.

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