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.

868 lines
28 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. import BarnesHutSolver from './components/physics/BarnesHutSolver';
  2. import Repulsion from './components/physics/RepulsionSolver';
  3. import HierarchicalRepulsion from './components/physics/HierarchicalRepulsionSolver';
  4. import SpringSolver from './components/physics/SpringSolver';
  5. import HierarchicalSpringSolver from './components/physics/HierarchicalSpringSolver';
  6. import CentralGravitySolver from './components/physics/CentralGravitySolver';
  7. import ForceAtlas2BasedRepulsionSolver from './components/physics/FA2BasedRepulsionSolver';
  8. import ForceAtlas2BasedCentralGravitySolver from './components/physics/FA2BasedCentralGravitySolver';
  9. import PhysicsWorker from 'worker!./PhysicsWorkerWrapper';
  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.referenceState = {};
  20. this.freezeCache = {};
  21. this.renderTimer = undefined;
  22. // parameters for the adaptive timestep
  23. this.adaptiveTimestep = false;
  24. this.adaptiveTimestepEnabled = false;
  25. this.adaptiveCounter = 0;
  26. this.adaptiveInterval = 3;
  27. this.stabilized = false;
  28. this.startedStabilization = false;
  29. this.stabilizationIterations = 0;
  30. this.ready = false; // will be set to true if the stabilize
  31. // default options
  32. this.options = {};
  33. this.defaultOptions = {
  34. enabled: true,
  35. useWorker: false,
  36. barnesHut: {
  37. theta: 0.5,
  38. gravitationalConstant: -2000,
  39. centralGravity: 0.3,
  40. springLength: 95,
  41. springConstant: 0.04,
  42. damping: 0.09,
  43. avoidOverlap: 0
  44. },
  45. forceAtlas2Based: {
  46. theta: 0.5,
  47. gravitationalConstant: -50,
  48. centralGravity: 0.01,
  49. springConstant: 0.08,
  50. springLength: 100,
  51. damping: 0.4,
  52. avoidOverlap: 0
  53. },
  54. repulsion: {
  55. centralGravity: 0.2,
  56. springLength: 200,
  57. springConstant: 0.05,
  58. nodeDistance: 100,
  59. damping: 0.09,
  60. avoidOverlap: 0
  61. },
  62. hierarchicalRepulsion: {
  63. centralGravity: 0.0,
  64. springLength: 100,
  65. springConstant: 0.01,
  66. nodeDistance: 120,
  67. damping: 0.09
  68. },
  69. maxVelocity: 50,
  70. minVelocity: 0.75, // px/s
  71. solver: 'barnesHut',
  72. stabilization: {
  73. enabled: true,
  74. iterations: 1000, // maximum number of iteration to stabilize
  75. updateInterval: 50,
  76. onlyDynamicEdges: false,
  77. fit: true
  78. },
  79. timestep: 0.5,
  80. adaptiveTimestep: true
  81. };
  82. util.extend(this.options, this.defaultOptions);
  83. this.timestep = 0.5;
  84. this.layoutFailed = false;
  85. this.draggingNodes = [];
  86. this.positionUpdateHandler = () => {};
  87. this.physicsUpdateHandler = () => {};
  88. this.bindEventListeners();
  89. }
  90. bindEventListeners() {
  91. this.body.emitter.on('initPhysics', () => {this.initPhysics();});
  92. this.body.emitter.on('_layoutFailed', () => {this.layoutFailed = true;});
  93. this.body.emitter.on('resetPhysics', () => {this.stopSimulation(); this.ready = false;});
  94. this.body.emitter.on('disablePhysics', () => {this.physicsEnabled = false; this.stopSimulation();});
  95. this.body.emitter.on('restorePhysics', () => {
  96. this.setOptions(this.options);
  97. if (this.ready === true) {
  98. this.startSimulation();
  99. }
  100. });
  101. this.body.emitter.on('startSimulation', () => {
  102. if (this.ready === true) {
  103. this.startSimulation();
  104. }
  105. });
  106. this.body.emitter.on('stopSimulation', () => {this.stopSimulation();});
  107. this.body.emitter.on('destroy', () => {
  108. this.stopSimulation(false);
  109. this.body.emitter.off();
  110. });
  111. this.body.emitter.on('_positionUpdate', (properties) => this.positionUpdateHandler(properties));
  112. this.body.emitter.on('_physicsUpdate', (properties) => this.physicsUpdateHandler(properties));
  113. // For identifying which nodes to send to worker thread
  114. this.body.emitter.on('dragStart', (properties) => {
  115. this.draggingNodes = properties.nodes;
  116. });
  117. this.body.emitter.on('dragEnd', () => {
  118. this.draggingNodes = [];
  119. });
  120. this.body.emitter.on('destroy', () => {
  121. if (this.physicsWorker) {
  122. this.physicsWorker.terminate();
  123. this.physicsWorker = undefined;
  124. }
  125. });
  126. }
  127. /**
  128. * set the physics options
  129. * @param options
  130. */
  131. setOptions(options) {
  132. if (options !== undefined) {
  133. if (options === false) {
  134. this.options.enabled = false;
  135. this.physicsEnabled = false;
  136. this.stopSimulation();
  137. }
  138. else {
  139. this.physicsEnabled = true;
  140. util.selectiveNotDeepExtend(['stabilization'], this.options, options);
  141. util.mergeOptions(this.options, options, 'stabilization')
  142. if (options.enabled === undefined) {
  143. this.options.enabled = true;
  144. }
  145. if (this.options.enabled === false) {
  146. this.physicsEnabled = false;
  147. this.stopSimulation();
  148. }
  149. // set the timestep
  150. this.timestep = this.options.timestep;
  151. }
  152. }
  153. if (this.options.useWorker) {
  154. this.initPhysicsWorker();
  155. this.physicsWorker.postMessage({type: 'options', data: this.options});
  156. } else {
  157. this.initEmbeddedPhysics();
  158. }
  159. }
  160. /**
  161. * configure the engine.
  162. */
  163. initEmbeddedPhysics() {
  164. this.positionUpdateHandler = () => {};
  165. this.physicsUpdateHandler = () => {};
  166. if (this.physicsWorker) {
  167. this.options.useWorker = false;
  168. this.physicsWorker.terminate();
  169. this.physicsWorker = undefined;
  170. this.initPhysicsData();
  171. }
  172. var options;
  173. if (this.options.solver === 'forceAtlas2Based') {
  174. options = this.options.forceAtlas2Based;
  175. this.nodesSolver = new ForceAtlas2BasedRepulsionSolver(this.body, this.physicsBody, options);
  176. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  177. this.gravitySolver = new ForceAtlas2BasedCentralGravitySolver(this.body, this.physicsBody, options);
  178. }
  179. else if (this.options.solver === 'repulsion') {
  180. options = this.options.repulsion;
  181. this.nodesSolver = new Repulsion(this.body, this.physicsBody, options);
  182. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  183. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  184. }
  185. else if (this.options.solver === 'hierarchicalRepulsion') {
  186. options = this.options.hierarchicalRepulsion;
  187. this.nodesSolver = new HierarchicalRepulsion(this.body, this.physicsBody, options);
  188. this.edgesSolver = new HierarchicalSpringSolver(this.body, this.physicsBody, options);
  189. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  190. }
  191. else { // barnesHut
  192. options = this.options.barnesHut;
  193. this.nodesSolver = new BarnesHutSolver(this.body, this.physicsBody, options);
  194. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  195. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  196. }
  197. this.modelOptions = options;
  198. }
  199. initPhysicsWorker() {
  200. if (!this.physicsWorker) {
  201. if (!__webpack_public_path__) {
  202. let parentScript = document.getElementById('visjs');
  203. if (parentScript) {
  204. let src = parentScript.getAttribute('src')
  205. __webpack_public_path__ = src.substr(0, src.lastIndexOf('/') + 1);
  206. } else {
  207. let scripts = document.getElementsByTagName('script');
  208. for (let i = 0; i < scripts.length; i++) {
  209. let src = scripts[i].getAttribute('src');
  210. if (src && src.length >= 6) {
  211. let position = src.length - 6;
  212. let index = src.indexOf('vis.js', position);
  213. if (index === position) {
  214. __webpack_public_path__ = src.substr(0, src.lastIndexOf('/') + 1);
  215. break;
  216. }
  217. }
  218. }
  219. }
  220. }
  221. this.physicsWorker = new PhysicsWorker();
  222. this.physicsWorker.addEventListener('message', (event) => {
  223. this.physicsWorkerMessageHandler(event);
  224. });
  225. this.physicsWorker.onerror = (event) => {
  226. console.error('Falling back to embedded physics engine', event);
  227. this.initEmbeddedPhysics();
  228. // throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
  229. };
  230. this.positionUpdateHandler = (positions) => {
  231. this.physicsWorker.postMessage({type: 'updatePositions', data: positions});
  232. };
  233. this.physicsUpdateHandler = (properties) => {
  234. if (properties.options.physics !== undefined) {
  235. if (properties.options.physics) {
  236. this.physicsWorker.postMessage({
  237. type: 'addElements',
  238. data: this.createPhysicsNode(properties.id)
  239. });
  240. } else {
  241. this.physicsWorker.postMessage({type: 'removeElements', data: {
  242. nodes: [properties.id.toString()],
  243. edges: []
  244. }});
  245. }
  246. } else {
  247. this.physicsWorker.postMessage({type: 'updateProperties', data: properties});
  248. }
  249. };
  250. }
  251. }
  252. physicsWorkerMessageHandler(event) {
  253. var msg = event.data;
  254. switch (msg.type) {
  255. case 'positions':
  256. this.stabilized = msg.data.stabilized;
  257. var positions = msg.data.positions;
  258. for (let i = 0; i < this.draggingNodes.length; i++) {
  259. delete positions[this.draggingNodes[i]];
  260. }
  261. let nodeIds = Object.keys(positions);
  262. for (let i = 0; i < nodeIds.length; i++) {
  263. let nodeId = nodeIds[i];
  264. let node = this.body.nodes[nodeId];
  265. // handle case where we get a positions from an old physicsObject
  266. if (node) {
  267. node.setX(positions[nodeId].x);
  268. node.setY(positions[nodeId].y);
  269. }
  270. }
  271. break;
  272. default:
  273. console.warn('unhandled physics worker message:', msg);
  274. }
  275. }
  276. /**
  277. * initialize the engine
  278. */
  279. initPhysics() {
  280. if (this.physicsEnabled === true && this.options.enabled === true) {
  281. if (this.options.stabilization.enabled === true) {
  282. this.stabilize();
  283. }
  284. else {
  285. this.stabilized = false;
  286. this.ready = true;
  287. this.body.emitter.emit('fit', {}, this.layoutFailed); // if the layout failed, we use the approximation for the zoom
  288. this.startSimulation();
  289. }
  290. }
  291. else {
  292. this.ready = true;
  293. this.body.emitter.emit('fit');
  294. }
  295. }
  296. /**
  297. * Start the simulation
  298. */
  299. startSimulation() {
  300. if (this.physicsEnabled === true && this.options.enabled === true) {
  301. this.stabilized = false;
  302. // when visible, adaptivity is disabled.
  303. this.adaptiveTimestep = false;
  304. // this sets the width of all nodes initially which could be required for the avoidOverlap
  305. this.body.emitter.emit("_resizeNodes");
  306. if (this.viewFunction === undefined) {
  307. this.viewFunction = this.simulationStep.bind(this);
  308. this.body.emitter.on('initRedraw', this.viewFunction);
  309. this.body.emitter.emit('_startRendering');
  310. }
  311. }
  312. else {
  313. this.body.emitter.emit('_redraw');
  314. }
  315. }
  316. /**
  317. * Stop the simulation, force stabilization.
  318. */
  319. stopSimulation(emit = true) {
  320. this.stabilized = true;
  321. if (emit === true) {
  322. this._emitStabilized();
  323. }
  324. if (this.viewFunction !== undefined) {
  325. this.body.emitter.off('initRedraw', this.viewFunction);
  326. this.viewFunction = undefined;
  327. if (emit === true) {
  328. this.body.emitter.emit('_stopRendering');
  329. }
  330. }
  331. }
  332. /**
  333. * The viewFunction inserts this step into each renderloop. It calls the physics tick and handles the cleanup at stabilized.
  334. *
  335. */
  336. simulationStep() {
  337. // check if the physics have settled
  338. var startTime = Date.now();
  339. this.physicsTick();
  340. var physicsTime = Date.now() - startTime;
  341. // run double speed if it is a little graph
  342. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) {
  343. this.physicsTick();
  344. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  345. this.runDoubleSpeed = true;
  346. }
  347. if (this.stabilized === true) {
  348. this.stopSimulation();
  349. }
  350. }
  351. /**
  352. * trigger the stabilized event.
  353. * @private
  354. */
  355. _emitStabilized(amountOfIterations = this.stabilizationIterations) {
  356. if (this.stabilizationIterations > 1 || this.startedStabilization === true) {
  357. setTimeout(() => {
  358. this.body.emitter.emit('stabilized', {iterations: amountOfIterations});
  359. this.startedStabilization = false;
  360. this.stabilizationIterations = 0;
  361. }, 0);
  362. }
  363. }
  364. /**
  365. * A single simulation step (or 'tick') in the physics simulation
  366. *
  367. * @private
  368. */
  369. physicsTick() {
  370. // this is here to ensure that there is no start event when the network is already stable.
  371. if (this.startedStabilization === false) {
  372. this.body.emitter.emit('startStabilizing');
  373. this.startedStabilization = true;
  374. }
  375. if (this.stabilized === false) {
  376. // adaptivity means the timestep adapts to the situation, only applicable for stabilization
  377. if (this.adaptiveTimestep === true && this.adaptiveTimestepEnabled === true) {
  378. // this is the factor for increasing the timestep on success.
  379. let factor = 1.2;
  380. // we assume the adaptive interval is
  381. if (this.adaptiveCounter % this.adaptiveInterval === 0) { // we leave the timestep stable for "interval" iterations.
  382. // first the big step and revert. Revert saves the reference state.
  383. this.timestep = 2 * this.timestep;
  384. this.calculateForces();
  385. this.moveNodes();
  386. this.revert();
  387. // now the normal step. Since this is the last step, it is the more stable one and we will take this.
  388. this.timestep = 0.5 * this.timestep;
  389. // since it's half the step, we do it twice.
  390. this.calculateForces();
  391. this.moveNodes();
  392. this.calculateForces();
  393. this.moveNodes();
  394. // we compare the two steps. if it is acceptable we double the step.
  395. if (this._evaluateStepQuality() === true) {
  396. this.timestep = factor * this.timestep;
  397. }
  398. else {
  399. // if not, we decrease the step to a minimum of the options timestep.
  400. // if the decreased timestep is smaller than the options step, we do not reset the counter
  401. // we assume that the options timestep is stable enough.
  402. if (this.timestep/factor < this.options.timestep) {
  403. this.timestep = this.options.timestep;
  404. }
  405. else {
  406. // if the timestep was larger than 2 times the option one we check the adaptivity again to ensure
  407. // that large instabilities do not form.
  408. this.adaptiveCounter = -1; // check again next iteration
  409. this.timestep = Math.max(this.options.timestep, this.timestep/factor);
  410. }
  411. }
  412. }
  413. else {
  414. // normal step, keeping timestep constant
  415. this.calculateForces();
  416. this.moveNodes();
  417. }
  418. // increment the counter
  419. this.adaptiveCounter += 1;
  420. }
  421. else {
  422. // case for the static timestep, we reset it to the one in options and take a normal step.
  423. this.timestep = this.options.timestep;
  424. if (this.physicsWorker) {
  425. // console.log('asking working to do a physics iteration');
  426. this.physicsWorker.postMessage({type: 'physicsTick'});
  427. } else {
  428. this.calculateForces();
  429. this.moveNodes();
  430. }
  431. }
  432. // determine if the network has stabilzied
  433. if (this.stabilized === true) {
  434. this.revert();
  435. }
  436. this.stabilizationIterations++;
  437. }
  438. }
  439. createPhysicsNode(nodeId) {
  440. let node = this.body.nodes[nodeId];
  441. if (node && node.options.physics === true) {
  442. // for updating fixed later
  443. this.physicsBody.physicsNodeIndices.push(nodeId);
  444. return {
  445. id: node.id.toString(),
  446. x: node.x,
  447. y: node.y,
  448. options: {
  449. fixed: {
  450. x: node.options.fixed.x,
  451. y: node.options.fixed.y
  452. },
  453. mass: node.options.mass
  454. }
  455. }
  456. }
  457. }
  458. /**
  459. * Nodes and edges can have the physics toggles on or off. A collection of indices is created here so we can skip the check all the time.
  460. *
  461. * @private
  462. */
  463. initPhysicsData() {
  464. let nodes = this.body.nodes;
  465. let edges = this.body.edges;
  466. this.physicsBody.forces = {};
  467. this.physicsBody.physicsNodeIndices = [];
  468. this.physicsBody.physicsEdgeIndices = [];
  469. if (this.physicsWorker) {
  470. let physicsWorkerNodes = {};
  471. let physicsWorkerEdges = {};
  472. for (let nodeId in nodes) {
  473. if (nodes.hasOwnProperty(nodeId)) {
  474. physicsWorkerNodes[nodeId] = this.createPhysicsNode(nodeId);
  475. }
  476. }
  477. for (let edgeId in edges) {
  478. if (edges.hasOwnProperty(edgeId)) {
  479. let edge = edges[edgeId];
  480. if (edge.options.physics === true && edge.connected === true) {
  481. physicsWorkerEdges[edgeId] = {
  482. connected: edge.connected,
  483. id: edge.id,
  484. edgeType: {},
  485. toId: edge.toId,
  486. fromId: edge.fromId,
  487. to: {
  488. id: edge.to.id
  489. },
  490. from: {
  491. id: edge.from.id
  492. },
  493. options: {
  494. length: edge.length
  495. }
  496. };
  497. if (edge.edgeType.via) {
  498. physicsWorkerEdges[edgeId].edgeType = {
  499. via: {
  500. id: edge.edgeType.via.id
  501. }
  502. }
  503. }
  504. }
  505. }
  506. }
  507. this.physicsWorker.postMessage({
  508. type: 'physicsObjects',
  509. data: {
  510. nodes: physicsWorkerNodes,
  511. edges: physicsWorkerEdges
  512. }
  513. });
  514. } else {
  515. // get node indices for physics
  516. for (let nodeId in nodes) {
  517. if (nodes.hasOwnProperty(nodeId)) {
  518. if (nodes[nodeId].options.physics === true) {
  519. this.physicsBody.physicsNodeIndices.push(nodeId);
  520. }
  521. }
  522. }
  523. // get edge indices for physics
  524. for (let edgeId in edges) {
  525. if (edges.hasOwnProperty(edgeId)) {
  526. if (edges[edgeId].options.physics === true) {
  527. this.physicsBody.physicsEdgeIndices.push(edgeId);
  528. }
  529. }
  530. }
  531. // get the velocity and the forces vector
  532. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  533. let nodeId = this.physicsBody.physicsNodeIndices[i];
  534. this.physicsBody.forces[nodeId] = {x: 0, y: 0};
  535. // forces can be reset because they are recalculated. Velocities have to persist.
  536. if (this.physicsBody.velocities[nodeId] === undefined) {
  537. this.physicsBody.velocities[nodeId] = {x: 0, y: 0};
  538. }
  539. }
  540. // clean deleted nodes from the velocity vector
  541. for (let nodeId in this.physicsBody.velocities) {
  542. if (nodes[nodeId] === undefined) {
  543. delete this.physicsBody.velocities[nodeId];
  544. }
  545. }
  546. }
  547. }
  548. /**
  549. * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized.
  550. */
  551. revert() {
  552. var nodeIds = Object.keys(this.previousStates);
  553. var nodes = this.body.nodes;
  554. var velocities = this.physicsBody.velocities;
  555. this.referenceState = {};
  556. for (let i = 0; i < nodeIds.length; i++) {
  557. let nodeId = nodeIds[i];
  558. if (nodes[nodeId] !== undefined) {
  559. if (nodes[nodeId].options.physics === true) {
  560. this.referenceState[nodeId] = {
  561. positions: {x:nodes[nodeId].x, y:nodes[nodeId].y}
  562. };
  563. velocities[nodeId].x = this.previousStates[nodeId].vx;
  564. velocities[nodeId].y = this.previousStates[nodeId].vy;
  565. nodes[nodeId].x = this.previousStates[nodeId].x;
  566. nodes[nodeId].y = this.previousStates[nodeId].y;
  567. }
  568. }
  569. else {
  570. delete this.previousStates[nodeId];
  571. }
  572. }
  573. }
  574. /**
  575. * This compares the reference state to the current state
  576. */
  577. _evaluateStepQuality() {
  578. let dx, dy, dpos;
  579. let nodes = this.body.nodes;
  580. let reference = this.referenceState;
  581. let posThreshold = 0.3;
  582. for (let nodeId in this.referenceState) {
  583. if (this.referenceState.hasOwnProperty(nodeId) && nodes[nodeId] !== undefined) {
  584. dx = nodes[nodeId].x - reference[nodeId].positions.x;
  585. dy = nodes[nodeId].y - reference[nodeId].positions.y;
  586. dpos = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2))
  587. if (dpos > posThreshold) {
  588. return false;
  589. }
  590. }
  591. }
  592. return true;
  593. }
  594. /**
  595. * move the nodes one timestap and check if they are stabilized
  596. * @returns {boolean}
  597. */
  598. moveNodes() {
  599. var nodeIndices = this.physicsBody.physicsNodeIndices;
  600. var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1e9;
  601. var maxNodeVelocity = 0;
  602. var averageNodeVelocity = 0;
  603. // the velocity threshold (energy in the system) for the adaptivity toggle
  604. var velocityAdaptiveThreshold = 5;
  605. for (let i = 0; i < nodeIndices.length; i++) {
  606. let nodeId = nodeIndices[i];
  607. let nodeVelocity = this._performStep(nodeId, maxVelocity);
  608. // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
  609. maxNodeVelocity = Math.max(maxNodeVelocity,nodeVelocity);
  610. averageNodeVelocity += nodeVelocity;
  611. }
  612. // evaluating the stabilized and adaptiveTimestepEnabled conditions
  613. this.adaptiveTimestepEnabled = (averageNodeVelocity/nodeIndices.length) < velocityAdaptiveThreshold;
  614. this.stabilized = maxNodeVelocity < this.options.minVelocity;
  615. }
  616. /**
  617. * Perform the actual step
  618. *
  619. * @param nodeId
  620. * @param maxVelocity
  621. * @returns {number}
  622. * @private
  623. */
  624. _performStep(nodeId,maxVelocity) {
  625. let node = this.body.nodes[nodeId];
  626. let timestep = this.timestep;
  627. let forces = this.physicsBody.forces;
  628. let velocities = this.physicsBody.velocities;
  629. // store the state so we can revert
  630. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  631. if (node.options.fixed.x === false) {
  632. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  633. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  634. velocities[nodeId].x += ax * timestep; // velocity
  635. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  636. node.setX(node.x + velocities[nodeId].x * timestep); // position
  637. }
  638. else {
  639. forces[nodeId].x = 0;
  640. velocities[nodeId].x = 0;
  641. }
  642. if (node.options.fixed.y === false) {
  643. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  644. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  645. velocities[nodeId].y += ay * timestep; // velocity
  646. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  647. node.setY(node.y + velocities[nodeId].y * timestep); // position
  648. }
  649. else {
  650. forces[nodeId].y = 0;
  651. velocities[nodeId].y = 0;
  652. }
  653. let totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  654. return totalVelocity;
  655. }
  656. /**
  657. * calculate the forces for one physics iteration.
  658. */
  659. calculateForces() {
  660. this.gravitySolver.solve();
  661. this.nodesSolver.solve();
  662. this.edgesSolver.solve();
  663. }
  664. /**
  665. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  666. * because only the supportnodes for the smoothCurves have to settle.
  667. *
  668. * @private
  669. */
  670. _freezeNodes() {
  671. var nodes = this.body.nodes;
  672. for (var id in nodes) {
  673. if (nodes.hasOwnProperty(id)) {
  674. if (nodes[id].x && nodes[id].y) {
  675. this.freezeCache[id] = {x:nodes[id].options.fixed.x,y:nodes[id].options.fixed.y};
  676. nodes[id].setFixed(true);
  677. }
  678. }
  679. }
  680. }
  681. /**
  682. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  683. *
  684. * @private
  685. */
  686. _restoreFrozenNodes() {
  687. var nodes = this.body.nodes;
  688. for (var id in nodes) {
  689. if (nodes.hasOwnProperty(id)) {
  690. if (this.freezeCache[id] !== undefined) {
  691. nodes[id].setFixed({x: this.freezeCache[id].x, y: this.freezeCache[id].y});
  692. }
  693. }
  694. }
  695. this.freezeCache = {};
  696. }
  697. /**
  698. * Find a stable position for all nodes
  699. * @private
  700. */
  701. stabilize(iterations = this.options.stabilization.iterations) {
  702. if (typeof iterations !== 'number') {
  703. console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations);
  704. iterations = this.options.stabilization.iterations;
  705. }
  706. if (this.physicsBody.physicsNodeIndices.length === 0) {
  707. this.ready = true;
  708. return;
  709. }
  710. // enable adaptive timesteps
  711. this.adaptiveTimestep = true && this.options.adaptiveTimestep;
  712. // this sets the width of all nodes initially which could be required for the avoidOverlap
  713. this.body.emitter.emit("_resizeNodes");
  714. // stop the render loop
  715. this.stopSimulation();
  716. // set stabilze to false
  717. this.stabilized = false;
  718. // block redraw requests
  719. this.body.emitter.emit('_blockRedraw');
  720. this.targetIterations = iterations;
  721. // start the stabilization
  722. if (this.options.stabilization.onlyDynamicEdges === true) {
  723. this._freezeNodes();
  724. }
  725. this.stabilizationIterations = 0;
  726. setTimeout(() => this._stabilizationBatch(),0);
  727. }
  728. /**
  729. * One batch of stabilization
  730. * @private
  731. */
  732. _stabilizationBatch() {
  733. // this is here to ensure that there is at least one start event.
  734. if (this.startedStabilization === false) {
  735. this.body.emitter.emit('startStabilizing');
  736. this.startedStabilization = true;
  737. }
  738. var count = 0;
  739. while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.targetIterations) {
  740. this.physicsTick();
  741. count++;
  742. }
  743. if (this.stabilized === false && this.stabilizationIterations < this.targetIterations) {
  744. this.body.emitter.emit('stabilizationProgress', {iterations: this.stabilizationIterations, total: this.targetIterations});
  745. setTimeout(this._stabilizationBatch.bind(this),0);
  746. }
  747. else {
  748. this._finalizeStabilization();
  749. }
  750. }
  751. /**
  752. * Wrap up the stabilization, fit and emit the events.
  753. * @private
  754. */
  755. _finalizeStabilization() {
  756. this.body.emitter.emit('_allowRedraw');
  757. if (this.options.stabilization.fit === true) {
  758. this.body.emitter.emit('fit');
  759. }
  760. if (this.options.stabilization.onlyDynamicEdges === true) {
  761. this._restoreFrozenNodes();
  762. }
  763. this.body.emitter.emit('stabilizationIterationsDone');
  764. this.body.emitter.emit('_requestRedraw');
  765. if (this.stabilized === true) {
  766. this._emitStabilized();
  767. }
  768. else {
  769. this.startSimulation();
  770. }
  771. this.ready = true;
  772. }
  773. }
  774. export default PhysicsEngine;