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.

434 lines
13 KiB

  1. /**
  2. * Created by Alex on 2/23/2015.
  3. */
  4. import {BarnesHutSolver} from "./components/physics/BarnesHutSolver";
  5. import {Repulsion} from "./components/physics/RepulsionSolver";
  6. import {HierarchicalRepulsion} from "./components/physics/HierarchicalRepulsionSolver";
  7. import {SpringSolver} from "./components/physics/SpringSolver";
  8. import {HierarchicalSpringSolver} from "./components/physics/HierarchicalSpringSolver";
  9. import {CentralGravitySolver} from "./components/physics/CentralGravitySolver";
  10. var util = require('../../util');
  11. class PhysicsEngine {
  12. constructor(body) {
  13. this.body = body;
  14. this.physicsBody = {physicsNodeIndices:[], physicsEdgeIndices:[], forces: {}, velocities: {}};
  15. this.simulationInterval = 1000 / 60;
  16. this.requiresTimeout = true;
  17. this.previousStates = {};
  18. this.renderTimer == undefined;
  19. this.stabilized = false;
  20. this.stabilizationIterations = 0;
  21. this.ready = false; // will be set to true if the stabilize
  22. // default options
  23. this.options = {};
  24. this.defaultOptions = {
  25. barnesHut: {
  26. thetaInverted: 1 / 0.5, // inverted to save time during calculation
  27. gravitationalConstant: -2000,
  28. centralGravity: 0.3,
  29. springLength: 95,
  30. springConstant: 0.04,
  31. damping: 0.09
  32. },
  33. repulsion: {
  34. centralGravity: 0.0,
  35. springLength: 200,
  36. springConstant: 0.05,
  37. nodeDistance: 100,
  38. damping: 0.09
  39. },
  40. hierarchicalRepulsion: {
  41. centralGravity: 0.0,
  42. springLength: 100,
  43. springConstant: 0.01,
  44. nodeDistance: 150,
  45. damping: 0.09
  46. },
  47. solver: 'BarnesHut',
  48. timestep: 0.5,
  49. maxVelocity: 50,
  50. minVelocity: 0.1, // px/s
  51. stabilization: {
  52. enabled: true,
  53. iterations: 1000, // maximum number of iteration to stabilize
  54. updateInterval: 100,
  55. onlyDynamicEdges: false,
  56. zoomExtent: true
  57. }
  58. }
  59. util.extend(this.options, this.defaultOptions);
  60. this.body.emitter.on("initPhysics", () => {this.initPhysics();});
  61. this.body.emitter.on("resetPhysics", () => {this.stopSimulation(); this.ready = false;});
  62. this.body.emitter.on("startSimulation", () => {
  63. if (this.ready === true) {
  64. this.stabilized = false;
  65. this.runSimulation();
  66. }
  67. })
  68. this.body.emitter.on("stopSimulation", () => {this.stopSimulation();});
  69. }
  70. setOptions(options) {
  71. if (options !== undefined) {
  72. util.selectiveNotDeepExtend(['stabilization'],this.options, options);
  73. util.mergeOptions(this.options, options, 'stabilization')
  74. }
  75. this.init();
  76. }
  77. init() {
  78. var options;
  79. if (this.options.solver == "repulsion") {
  80. options = this.options.repulsion;
  81. this.nodesSolver = new Repulsion(this.body, this.physicsBody, options);
  82. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  83. }
  84. else if (this.options.solver == "hierarchicalRepulsion") {
  85. options = this.options.hierarchicalRepulsion;
  86. this.nodesSolver = new HierarchicalRepulsion(this.body, this.physicsBody, options);
  87. this.edgesSolver = new HierarchicalSpringSolver(this.body, this.physicsBody, options);
  88. }
  89. else { // barnesHut
  90. options = this.options.barnesHut;
  91. this.nodesSolver = new BarnesHutSolver(this.body, this.physicsBody, options);
  92. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  93. }
  94. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  95. this.modelOptions = options;
  96. }
  97. initPhysics() {
  98. this.stabilized = false;
  99. if (this.options.stabilization.enabled === true) {
  100. this.stabilize();
  101. }
  102. else {
  103. this.ready = true;
  104. this.body.emitter.emit("zoomExtent", {duration:0}, true)
  105. this.runSimulation();
  106. }
  107. }
  108. stopSimulation() {
  109. this.stabilized = true;
  110. if (this.viewFunction !== undefined) {
  111. this.body.emitter.off("initRedraw", this.viewFunction);
  112. this.viewFunction = undefined;
  113. this.body.emitter.emit("_stopRendering");
  114. }
  115. }
  116. runSimulation() {
  117. if (this.viewFunction === undefined) {
  118. this.viewFunction = this.simulationStep.bind(this);
  119. this.body.emitter.on("initRedraw", this.viewFunction);
  120. this.body.emitter.emit("_startRendering");
  121. }
  122. }
  123. simulationStep() {
  124. // check if the physics have settled
  125. var startTime = Date.now();
  126. this.physicsTick();
  127. var physicsTime = Date.now() - startTime;
  128. // run double speed if it is a little graph
  129. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed == true) && this.stabilized === false) {
  130. this.physicsTick();
  131. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  132. this.runDoubleSpeed = true;
  133. }
  134. if (this.stabilized === true) {
  135. if (this.stabilizationIterations > 1) {
  136. // trigger the "stabilized" event.
  137. // The event is triggered on the next tick, to prevent the case that
  138. // it is fired while initializing the Network, in which case you would not
  139. // be able to catch it
  140. var me = this;
  141. var params = {
  142. iterations: this.stabilizationIterations
  143. };
  144. this.stabilizationIterations = 0;
  145. this.startedStabilization = false;
  146. setTimeout(function () {
  147. me.body.emitter.emit("stabilized", params);
  148. }, 0);
  149. }
  150. else {
  151. this.stabilizationIterations = 0;
  152. }
  153. this.stopSimulation();
  154. }
  155. }
  156. /**
  157. * A single simulation step (or "tick") in the physics simulation
  158. *
  159. * @private
  160. */
  161. physicsTick() {
  162. if (this.stabilized === false) {
  163. this.calculateForces();
  164. this.stabilized = this.moveNodes();
  165. // determine if the network has stabilzied
  166. if (this.stabilized === true) {
  167. this.revert();
  168. }
  169. else {
  170. // this is here to ensure that there is no start event when the network is already stable.
  171. if (this.startedStabilization == false) {
  172. this.body.emitter.emit("startStabilizing");
  173. this.startedStabilization = true;
  174. }
  175. }
  176. this.stabilizationIterations++;
  177. }
  178. }
  179. /**
  180. * Smooth curves are created by adding invisible nodes in the center of the edges. These nodes are also
  181. * handled in the calculateForces function. We then use a quadratic curve with the center node as control.
  182. * This function joins the datanodes and invisible (called support) nodes into one object.
  183. * We do this so we do not contaminate this.body.nodes with the support nodes.
  184. *
  185. * @private
  186. */
  187. _updatePhysicsIndices() {
  188. this.physicsBody.forces = {};
  189. this.physicsBody.physicsNodeIndices = [];
  190. this.physicsBody.physicsEdgeIndices = [];
  191. let nodes = this.body.nodes;
  192. let edges = this.body.edges;
  193. // get node indices for physics
  194. for (let nodeId in nodes) {
  195. if (nodes.hasOwnProperty(nodeId)) {
  196. if (nodes[nodeId].options.physics === true) {
  197. this.physicsBody.physicsNodeIndices.push(nodeId);
  198. }
  199. }
  200. }
  201. // get edge indices for physics
  202. for (let edgeId in edges) {
  203. if (edges.hasOwnProperty(edgeId)) {
  204. if (edges[edgeId].options.physics === true) {
  205. this.physicsBody.physicsEdgeIndices.push(edgeId);
  206. }
  207. }
  208. }
  209. // get the velocity and the forces vector
  210. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  211. let nodeId = this.physicsBody.physicsNodeIndices[i];
  212. this.physicsBody.forces[nodeId] = {x:0,y:0};
  213. // forces can be reset because they are recalculated. Velocities have to persist.
  214. if (this.physicsBody.velocities[nodeId] === undefined) {
  215. this.physicsBody.velocities[nodeId] = {x:0,y:0};
  216. }
  217. }
  218. // clean deleted nodes from the velocity vector
  219. for (let nodeId in this.physicsBody.velocities) {
  220. if (nodes[nodeId] === undefined) {
  221. delete this.physicsBody.velocities[nodeId];
  222. }
  223. }
  224. }
  225. revert() {
  226. var nodeIds = Object.keys(this.previousStates);
  227. var nodes = this.body.nodes;
  228. var velocities = this.physicsBody.velocities;
  229. for (let i = 0; i < nodeIds.length; i++) {
  230. let nodeId = nodeIds[i];
  231. if (nodes[nodeId] !== undefined) {
  232. velocities[nodeId].x = this.previousStates[nodeId].vx;
  233. velocities[nodeId].y = this.previousStates[nodeId].vy;
  234. nodes[nodeId].x = this.previousStates[nodeId].x;
  235. nodes[nodeId].y = this.previousStates[nodeId].y;
  236. }
  237. else {
  238. delete this.previousStates[nodeId];
  239. }
  240. }
  241. }
  242. moveNodes() {
  243. var nodesPresent = false;
  244. var nodeIndices = this.physicsBody.physicsNodeIndices;
  245. var maxVelocity = this.options.maxVelocity === 0 ? 1e9 : this.options.maxVelocity;
  246. var stabilized = true;
  247. var vminCorrected = this.options.minVelocity / Math.max(this.body.view.scale,0.05);
  248. for (let i = 0; i < nodeIndices.length; i++) {
  249. let nodeId = nodeIndices[i];
  250. let nodeVelocity = this._performStep(nodeId, maxVelocity);
  251. // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
  252. stabilized = nodeVelocity < vminCorrected && stabilized === true;
  253. nodesPresent = true;
  254. }
  255. if (nodesPresent == true) {
  256. if (vminCorrected > 0.5*this.options.maxVelocity) {
  257. return false;
  258. }
  259. else {
  260. return stabilized;
  261. }
  262. }
  263. return true;
  264. }
  265. _performStep(nodeId,maxVelocity) {
  266. var node = this.body.nodes[nodeId];
  267. var timestep = this.options.timestep;
  268. var forces = this.physicsBody.forces;
  269. var velocities = this.physicsBody.velocities;
  270. // store the state so we can revert
  271. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  272. if (!node.xFixed) {
  273. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  274. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  275. velocities[nodeId].x += ax * timestep; // velocity
  276. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  277. node.x += velocities[nodeId].x * timestep; // position
  278. }
  279. else {
  280. forces[nodeId].x = 0;
  281. velocities[nodeId].x = 0;
  282. }
  283. if (!node.yFixed) {
  284. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  285. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  286. velocities[nodeId].y += ay * timestep; // velocity
  287. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  288. node.y += velocities[nodeId].y * timestep; // position
  289. }
  290. else {
  291. forces[nodeId].y = 0;
  292. velocities[nodeId].y = 0;
  293. }
  294. var totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  295. return totalVelocity;
  296. }
  297. calculateForces() {
  298. this.gravitySolver.solve();
  299. this.nodesSolver.solve();
  300. this.edgesSolver.solve();
  301. }
  302. /**
  303. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  304. * because only the supportnodes for the smoothCurves have to settle.
  305. *
  306. * @private
  307. */
  308. _freezeNodes() {
  309. var nodes = this.body.nodes;
  310. for (var id in nodes) {
  311. if (nodes.hasOwnProperty(id)) {
  312. if (nodes[id].x != null && nodes[id].y != null) {
  313. nodes[id].fixedData.x = nodes[id].xFixed;
  314. nodes[id].fixedData.y = nodes[id].yFixed;
  315. nodes[id].xFixed = true;
  316. nodes[id].yFixed = true;
  317. }
  318. }
  319. }
  320. }
  321. /**
  322. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  323. *
  324. * @private
  325. */
  326. _restoreFrozenNodes() {
  327. var nodes = this.body.nodes;
  328. for (var id in nodes) {
  329. if (nodes.hasOwnProperty(id)) {
  330. if (nodes[id].fixedData.x != null) {
  331. nodes[id].xFixed = nodes[id].fixedData.x;
  332. nodes[id].yFixed = nodes[id].fixedData.y;
  333. }
  334. }
  335. }
  336. }
  337. /**
  338. * Find a stable position for all nodes
  339. * @private
  340. */
  341. stabilize() {
  342. if (this.options.stabilization.onlyDynamicEdges == true) {
  343. this._freezeNodes();
  344. }
  345. this.stabilizationSteps = 0;
  346. setTimeout(this._stabilizationBatch.bind(this),0);
  347. }
  348. _stabilizationBatch() {
  349. var count = 0;
  350. while (this.stabilized == false && count < this.options.stabilization.updateInterval && this.stabilizationSteps < this.options.stabilization.iterations) {
  351. this.physicsTick();
  352. this.stabilizationSteps++;
  353. count++;
  354. }
  355. if (this.stabilized == false && this.stabilizationSteps < this.options.stabilization.iterations) {
  356. this.body.emitter.emit("stabilizationProgress", {steps: this.stabilizationSteps, total: this.options.stabilization.iterations});
  357. setTimeout(this._stabilizationBatch.bind(this),0);
  358. }
  359. else {
  360. this._finalizeStabilization();
  361. }
  362. }
  363. _finalizeStabilization() {
  364. if (this.options.stabilization.zoomExtent == true) {
  365. this.body.emitter.emit("zoomExtent", {duration:0});
  366. }
  367. if (this.options.stabilization.onlyDynamicEdges == true) {
  368. this._restoreFrozenNodes();
  369. }
  370. this.body.emitter.emit("stabilizationIterationsDone");
  371. this.body.emitter.emit("_requestRedraw");
  372. this.ready = true;
  373. }
  374. }
  375. export default PhysicsEngine;