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.

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