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.

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