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.

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