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.

870 lines
27 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. let nodes = {};
  237. nodes[properties.id] = this.createPhysicsNode(properties.id);
  238. this.physicsWorker.postMessage({
  239. type: 'addElements',
  240. data: {
  241. nodes: nodes,
  242. edges: {}
  243. }
  244. });
  245. } else {
  246. this.physicsWorker.postMessage({type: 'removeElements', data: {
  247. nodes: [properties.id.toString()],
  248. edges: []
  249. }});
  250. }
  251. } else {
  252. this.physicsWorker.postMessage({type: 'updateProperties', data: properties});
  253. }
  254. };
  255. }
  256. }
  257. physicsWorkerMessageHandler(event) {
  258. var msg = event.data;
  259. switch (msg.type) {
  260. case 'positions':
  261. this.stabilized = msg.data.stabilized;
  262. var positions = msg.data.positions;
  263. for (let i = 0; i < this.draggingNodes.length; i++) {
  264. delete positions[this.draggingNodes[i]];
  265. }
  266. let nodeIds = Object.keys(positions);
  267. for (let i = 0; i < nodeIds.length; i++) {
  268. let nodeId = nodeIds[i];
  269. let node = this.body.nodes[nodeId];
  270. // handle case where we get a positions from an old physicsObject
  271. if (node) {
  272. node.setX(positions[nodeId].x);
  273. node.setY(positions[nodeId].y);
  274. }
  275. }
  276. break;
  277. default:
  278. console.warn('unhandled physics worker message:', msg);
  279. }
  280. }
  281. /**
  282. * initialize the engine
  283. */
  284. initPhysics() {
  285. if (this.physicsEnabled === true && this.options.enabled === true) {
  286. if (this.options.stabilization.enabled === true) {
  287. this.stabilize();
  288. }
  289. else {
  290. this.stabilized = false;
  291. this.ready = true;
  292. this.body.emitter.emit('fit', {}, this.layoutFailed); // if the layout failed, we use the approximation for the zoom
  293. this.startSimulation();
  294. }
  295. }
  296. else {
  297. this.ready = true;
  298. this.body.emitter.emit('fit');
  299. }
  300. }
  301. /**
  302. * Start the simulation
  303. */
  304. startSimulation() {
  305. if (this.physicsEnabled === true && this.options.enabled === true) {
  306. this.stabilized = false;
  307. // when visible, adaptivity is disabled.
  308. this.adaptiveTimestep = false;
  309. // this sets the width of all nodes initially which could be required for the avoidOverlap
  310. this.body.emitter.emit("_resizeNodes");
  311. if (this.viewFunction === undefined) {
  312. this.viewFunction = this.simulationStep.bind(this);
  313. this.body.emitter.on('initRedraw', this.viewFunction);
  314. this.body.emitter.emit('_startRendering');
  315. }
  316. }
  317. else {
  318. this.body.emitter.emit('_redraw');
  319. }
  320. }
  321. /**
  322. * Stop the simulation, force stabilization.
  323. */
  324. stopSimulation(emit = true) {
  325. this.stabilized = true;
  326. if (emit === true) {
  327. this._emitStabilized();
  328. }
  329. if (this.viewFunction !== undefined) {
  330. this.body.emitter.off('initRedraw', this.viewFunction);
  331. this.viewFunction = undefined;
  332. if (emit === true) {
  333. this.body.emitter.emit('_stopRendering');
  334. }
  335. }
  336. }
  337. /**
  338. * The viewFunction inserts this step into each renderloop. It calls the physics tick and handles the cleanup at stabilized.
  339. *
  340. */
  341. simulationStep() {
  342. // check if the physics have settled
  343. var startTime = Date.now();
  344. this.physicsTick();
  345. var physicsTime = Date.now() - startTime;
  346. // run double speed if it is a little graph
  347. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) {
  348. this.physicsTick();
  349. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  350. this.runDoubleSpeed = true;
  351. }
  352. if (this.stabilized === true) {
  353. this.stopSimulation();
  354. }
  355. }
  356. /**
  357. * trigger the stabilized event.
  358. * @private
  359. */
  360. _emitStabilized(amountOfIterations = this.stabilizationIterations) {
  361. if (this.stabilizationIterations > 1 || this.startedStabilization === true) {
  362. setTimeout(() => {
  363. this.body.emitter.emit('stabilized', {iterations: amountOfIterations});
  364. this.startedStabilization = false;
  365. this.stabilizationIterations = 0;
  366. }, 0);
  367. }
  368. }
  369. /**
  370. * A single simulation step (or 'tick') in the physics simulation
  371. *
  372. * @private
  373. */
  374. physicsTick() {
  375. // this is here to ensure that there is no start event when the network is already stable.
  376. if (this.startedStabilization === false) {
  377. this.body.emitter.emit('startStabilizing');
  378. this.startedStabilization = true;
  379. }
  380. if (this.stabilized === false) {
  381. // adaptivity means the timestep adapts to the situation, only applicable for stabilization
  382. if (this.adaptiveTimestep === true && this.adaptiveTimestepEnabled === true) {
  383. // this is the factor for increasing the timestep on success.
  384. let factor = 1.2;
  385. // we assume the adaptive interval is
  386. if (this.adaptiveCounter % this.adaptiveInterval === 0) { // we leave the timestep stable for "interval" iterations.
  387. // first the big step and revert. Revert saves the reference state.
  388. this.timestep = 2 * this.timestep;
  389. this.calculateForces();
  390. this.moveNodes();
  391. this.revert();
  392. // now the normal step. Since this is the last step, it is the more stable one and we will take this.
  393. this.timestep = 0.5 * this.timestep;
  394. // since it's half the step, we do it twice.
  395. this.calculateForces();
  396. this.moveNodes();
  397. this.calculateForces();
  398. this.moveNodes();
  399. // we compare the two steps. if it is acceptable we double the step.
  400. if (this._evaluateStepQuality() === true) {
  401. this.timestep = factor * this.timestep;
  402. }
  403. else {
  404. // if not, we decrease the step to a minimum of the options timestep.
  405. // if the decreased timestep is smaller than the options step, we do not reset the counter
  406. // we assume that the options timestep is stable enough.
  407. if (this.timestep/factor < this.options.timestep) {
  408. this.timestep = this.options.timestep;
  409. }
  410. else {
  411. // if the timestep was larger than 2 times the option one we check the adaptivity again to ensure
  412. // that large instabilities do not form.
  413. this.adaptiveCounter = -1; // check again next iteration
  414. this.timestep = Math.max(this.options.timestep, this.timestep/factor);
  415. }
  416. }
  417. }
  418. else {
  419. // normal step, keeping timestep constant
  420. this.calculateForces();
  421. this.moveNodes();
  422. }
  423. // increment the counter
  424. this.adaptiveCounter += 1;
  425. }
  426. else {
  427. // case for the static timestep, we reset it to the one in options and take a normal step.
  428. this.timestep = this.options.timestep;
  429. if (this.physicsWorker) {
  430. // console.log('asking working to do a physics iteration');
  431. this.physicsWorker.postMessage({type: 'physicsTick'});
  432. } else {
  433. this.calculateForces();
  434. this.moveNodes();
  435. }
  436. }
  437. // determine if the network has stabilzied
  438. if (this.stabilized === true) {
  439. this.revert();
  440. }
  441. this.stabilizationIterations++;
  442. }
  443. }
  444. createPhysicsNode(nodeId) {
  445. let node = this.body.nodes[nodeId];
  446. if (node) {
  447. return {
  448. id: node.id.toString(),
  449. x: node.x,
  450. y: node.y,
  451. options: {
  452. fixed: {
  453. x: node.options.fixed.x,
  454. y: node.options.fixed.y
  455. },
  456. mass: node.options.mass
  457. }
  458. }
  459. }
  460. }
  461. createPhysicsEdge(edgeId) {
  462. let edge = this.body.edges[edgeId];
  463. if (edge && edge.options.physics === true && edge.connected === true) {
  464. let physicsEdge = {
  465. connected: edge.connected,
  466. id: edge.id,
  467. edgeType: {},
  468. toId: edge.toId,
  469. fromId: edge.fromId,
  470. to: {
  471. id: edge.to.id
  472. },
  473. from: {
  474. id: edge.from.id
  475. },
  476. options: {
  477. length: edge.length
  478. }
  479. };
  480. if (edge.edgeType.via) {
  481. physicsEdge.edgeType = {
  482. via: {
  483. id: edge.edgeType.via.id
  484. }
  485. }
  486. }
  487. return physicsEdge;
  488. }
  489. }
  490. /**
  491. * 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.
  492. *
  493. * @private
  494. */
  495. initPhysicsData() {
  496. let nodes = this.body.nodes;
  497. let edges = this.body.edges;
  498. this.physicsBody.forces = {};
  499. this.physicsBody.physicsNodeIndices = [];
  500. this.physicsBody.physicsEdgeIndices = [];
  501. let physicsWorkerNodes = {};
  502. let physicsWorkerEdges = {};
  503. // get node indices for physics
  504. for (let nodeId in nodes) {
  505. if (nodes.hasOwnProperty(nodeId)) {
  506. if (nodes[nodeId].options.physics === true) {
  507. this.physicsBody.physicsNodeIndices.push(nodeId);
  508. if (this.physicsWorker) {
  509. physicsWorkerNodes[nodeId] = this.createPhysicsNode(nodeId);
  510. }
  511. }
  512. }
  513. }
  514. // get edge indices for physics
  515. for (let edgeId in edges) {
  516. if (edges.hasOwnProperty(edgeId)) {
  517. if (edges[edgeId].options.physics === true) {
  518. this.physicsBody.physicsEdgeIndices.push(edgeId);
  519. if (this.physicsWorker) {
  520. physicsWorkerEdges[edgeId] = this.createPhysicsEdge(edgeId);
  521. }
  522. }
  523. }
  524. }
  525. // get the velocity and the forces vector
  526. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  527. let nodeId = this.physicsBody.physicsNodeIndices[i];
  528. this.physicsBody.forces[nodeId] = {x: 0, y: 0};
  529. // forces can be reset because they are recalculated. Velocities have to persist.
  530. if (this.physicsBody.velocities[nodeId] === undefined) {
  531. this.physicsBody.velocities[nodeId] = {x: 0, y: 0};
  532. }
  533. }
  534. // clean deleted nodes from the velocity vector
  535. for (let nodeId in this.physicsBody.velocities) {
  536. if (nodes[nodeId] === undefined) {
  537. delete this.physicsBody.velocities[nodeId];
  538. }
  539. }
  540. if (this.physicsWorker) {
  541. this.physicsWorker.postMessage({
  542. type: 'initPhysicsData',
  543. data: {
  544. nodes: physicsWorkerNodes,
  545. edges: physicsWorkerEdges
  546. }
  547. });
  548. }
  549. }
  550. /**
  551. * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized.
  552. */
  553. revert() {
  554. var nodeIds = Object.keys(this.previousStates);
  555. var nodes = this.body.nodes;
  556. var velocities = this.physicsBody.velocities;
  557. this.referenceState = {};
  558. for (let i = 0; i < nodeIds.length; i++) {
  559. let nodeId = nodeIds[i];
  560. if (nodes[nodeId] !== undefined) {
  561. if (nodes[nodeId].options.physics === true) {
  562. this.referenceState[nodeId] = {
  563. positions: {x:nodes[nodeId].x, y:nodes[nodeId].y}
  564. };
  565. velocities[nodeId].x = this.previousStates[nodeId].vx;
  566. velocities[nodeId].y = this.previousStates[nodeId].vy;
  567. nodes[nodeId].x = this.previousStates[nodeId].x;
  568. nodes[nodeId].y = this.previousStates[nodeId].y;
  569. }
  570. }
  571. else {
  572. delete this.previousStates[nodeId];
  573. }
  574. }
  575. }
  576. /**
  577. * This compares the reference state to the current state
  578. */
  579. _evaluateStepQuality() {
  580. let dx, dy, dpos;
  581. let nodes = this.body.nodes;
  582. let reference = this.referenceState;
  583. let posThreshold = 0.3;
  584. for (let nodeId in this.referenceState) {
  585. if (this.referenceState.hasOwnProperty(nodeId) && nodes[nodeId] !== undefined) {
  586. dx = nodes[nodeId].x - reference[nodeId].positions.x;
  587. dy = nodes[nodeId].y - reference[nodeId].positions.y;
  588. dpos = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2))
  589. if (dpos > posThreshold) {
  590. return false;
  591. }
  592. }
  593. }
  594. return true;
  595. }
  596. /**
  597. * move the nodes one timestap and check if they are stabilized
  598. * @returns {boolean}
  599. */
  600. moveNodes() {
  601. var nodeIndices = this.physicsBody.physicsNodeIndices;
  602. var maxVelocity = this.options.maxVelocity ? this.options.maxVelocity : 1e9;
  603. var maxNodeVelocity = 0;
  604. var averageNodeVelocity = 0;
  605. // the velocity threshold (energy in the system) for the adaptivity toggle
  606. var velocityAdaptiveThreshold = 5;
  607. for (let i = 0; i < nodeIndices.length; i++) {
  608. let nodeId = nodeIndices[i];
  609. let nodeVelocity = this._performStep(nodeId, maxVelocity);
  610. // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
  611. maxNodeVelocity = Math.max(maxNodeVelocity,nodeVelocity);
  612. averageNodeVelocity += nodeVelocity;
  613. }
  614. // evaluating the stabilized and adaptiveTimestepEnabled conditions
  615. this.adaptiveTimestepEnabled = (averageNodeVelocity/nodeIndices.length) < velocityAdaptiveThreshold;
  616. this.stabilized = maxNodeVelocity < this.options.minVelocity;
  617. }
  618. /**
  619. * Perform the actual step
  620. *
  621. * @param nodeId
  622. * @param maxVelocity
  623. * @returns {number}
  624. * @private
  625. */
  626. _performStep(nodeId,maxVelocity) {
  627. let node = this.body.nodes[nodeId];
  628. let timestep = this.timestep;
  629. let forces = this.physicsBody.forces;
  630. let velocities = this.physicsBody.velocities;
  631. // store the state so we can revert
  632. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  633. if (node.options.fixed.x === false) {
  634. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  635. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  636. velocities[nodeId].x += ax * timestep; // velocity
  637. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  638. node.setX(node.x + velocities[nodeId].x * timestep); // position
  639. }
  640. else {
  641. forces[nodeId].x = 0;
  642. velocities[nodeId].x = 0;
  643. }
  644. if (node.options.fixed.y === false) {
  645. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  646. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  647. velocities[nodeId].y += ay * timestep; // velocity
  648. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  649. node.setY(node.y + velocities[nodeId].y * timestep); // position
  650. }
  651. else {
  652. forces[nodeId].y = 0;
  653. velocities[nodeId].y = 0;
  654. }
  655. let totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  656. return totalVelocity;
  657. }
  658. /**
  659. * calculate the forces for one physics iteration.
  660. */
  661. calculateForces() {
  662. this.gravitySolver.solve();
  663. this.nodesSolver.solve();
  664. this.edgesSolver.solve();
  665. }
  666. /**
  667. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  668. * because only the supportnodes for the smoothCurves have to settle.
  669. *
  670. * @private
  671. */
  672. _freezeNodes() {
  673. var nodes = this.body.nodes;
  674. for (var id in nodes) {
  675. if (nodes.hasOwnProperty(id)) {
  676. if (nodes[id].x && nodes[id].y) {
  677. this.freezeCache[id] = {x:nodes[id].options.fixed.x,y:nodes[id].options.fixed.y};
  678. nodes[id].setFixed(true);
  679. }
  680. }
  681. }
  682. }
  683. /**
  684. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  685. *
  686. * @private
  687. */
  688. _restoreFrozenNodes() {
  689. var nodes = this.body.nodes;
  690. for (var id in nodes) {
  691. if (nodes.hasOwnProperty(id)) {
  692. if (this.freezeCache[id] !== undefined) {
  693. nodes[id].setFixed({x: this.freezeCache[id].x, y: this.freezeCache[id].y});
  694. }
  695. }
  696. }
  697. this.freezeCache = {};
  698. }
  699. /**
  700. * Find a stable position for all nodes
  701. * @private
  702. */
  703. stabilize(iterations = this.options.stabilization.iterations) {
  704. if (typeof iterations !== 'number') {
  705. console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations);
  706. iterations = this.options.stabilization.iterations;
  707. }
  708. if (this.physicsBody.physicsNodeIndices.length === 0) {
  709. this.ready = true;
  710. return;
  711. }
  712. // enable adaptive timesteps
  713. this.adaptiveTimestep = true && this.options.adaptiveTimestep;
  714. // this sets the width of all nodes initially which could be required for the avoidOverlap
  715. this.body.emitter.emit("_resizeNodes");
  716. // stop the render loop
  717. this.stopSimulation();
  718. // set stabilze to false
  719. this.stabilized = false;
  720. // block redraw requests
  721. this.body.emitter.emit('_blockRedraw');
  722. this.targetIterations = iterations;
  723. // start the stabilization
  724. if (this.options.stabilization.onlyDynamicEdges === true) {
  725. this._freezeNodes();
  726. }
  727. this.stabilizationIterations = 0;
  728. setTimeout(() => this._stabilizationBatch(),0);
  729. }
  730. /**
  731. * One batch of stabilization
  732. * @private
  733. */
  734. _stabilizationBatch() {
  735. // this is here to ensure that there is at least one start event.
  736. if (this.startedStabilization === false) {
  737. this.body.emitter.emit('startStabilizing');
  738. this.startedStabilization = true;
  739. }
  740. var count = 0;
  741. while (this.stabilized === false && count < this.options.stabilization.updateInterval && this.stabilizationIterations < this.targetIterations) {
  742. this.physicsTick();
  743. count++;
  744. }
  745. if (this.stabilized === false && this.stabilizationIterations < this.targetIterations) {
  746. this.body.emitter.emit('stabilizationProgress', {iterations: this.stabilizationIterations, total: this.targetIterations});
  747. setTimeout(this._stabilizationBatch.bind(this),0);
  748. }
  749. else {
  750. this._finalizeStabilization();
  751. }
  752. }
  753. /**
  754. * Wrap up the stabilization, fit and emit the events.
  755. * @private
  756. */
  757. _finalizeStabilization() {
  758. this.body.emitter.emit('_allowRedraw');
  759. if (this.options.stabilization.fit === true) {
  760. this.body.emitter.emit('fit');
  761. }
  762. if (this.options.stabilization.onlyDynamicEdges === true) {
  763. this._restoreFrozenNodes();
  764. }
  765. this.body.emitter.emit('stabilizationIterationsDone');
  766. this.body.emitter.emit('_requestRedraw');
  767. if (this.stabilized === true) {
  768. this._emitStabilized();
  769. }
  770. else {
  771. this.startSimulation();
  772. }
  773. this.ready = true;
  774. }
  775. }
  776. export default PhysicsEngine;