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.

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