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.

675 lines
20 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
  1. import PhysicsBase from './PhysicsBase';
  2. import PhysicsWorker from 'worker!./PhysicsWorkerWrapper';
  3. var util = require('../../util');
  4. class PhysicsEngine extends PhysicsBase {
  5. constructor(body) {
  6. super();
  7. this.body = body;
  8. this.physicsEnabled = true;
  9. this.simulationInterval = 1000 / 60;
  10. this.requiresTimeout = true;
  11. this.freezeCache = {};
  12. this.renderTimer = undefined;
  13. this.ready = false; // will be set to true if the stabilize
  14. // default options
  15. this.defaultOptions = {
  16. enabled: true,
  17. useWorker: false,
  18. barnesHut: {
  19. theta: 0.5,
  20. gravitationalConstant: -2000,
  21. centralGravity: 0.3,
  22. springLength: 95,
  23. springConstant: 0.04,
  24. damping: 0.09,
  25. avoidOverlap: 0
  26. },
  27. forceAtlas2Based: {
  28. theta: 0.5,
  29. gravitationalConstant: -50,
  30. centralGravity: 0.01,
  31. springConstant: 0.08,
  32. springLength: 100,
  33. damping: 0.4,
  34. avoidOverlap: 0
  35. },
  36. repulsion: {
  37. centralGravity: 0.2,
  38. springLength: 200,
  39. springConstant: 0.05,
  40. nodeDistance: 100,
  41. damping: 0.09,
  42. avoidOverlap: 0
  43. },
  44. hierarchicalRepulsion: {
  45. centralGravity: 0.0,
  46. springLength: 100,
  47. springConstant: 0.01,
  48. nodeDistance: 120,
  49. damping: 0.09
  50. },
  51. maxVelocity: 50,
  52. minVelocity: 0.75, // px/s
  53. solver: 'barnesHut',
  54. stabilization: {
  55. enabled: true,
  56. iterations: 1000, // maximum number of iteration to stabilize
  57. updateInterval: 50,
  58. onlyDynamicEdges: false,
  59. fit: true
  60. },
  61. timestep: 0.5,
  62. adaptiveTimestep: true
  63. };
  64. util.extend(this.options, this.defaultOptions);
  65. this.layoutFailed = false;
  66. this.draggingNodes = [];
  67. this.positionUpdateHandler = () => {};
  68. this.physicsUpdateHandler = () => {};
  69. this.emit = this.body.emitter.emit;
  70. this.bindEventListeners();
  71. }
  72. bindEventListeners() {
  73. this.body.emitter.on('initPhysics', () => {this.initPhysics();});
  74. this.body.emitter.on('_layoutFailed', () => {this.layoutFailed = true;});
  75. this.body.emitter.on('resetPhysics', () => {this.stopSimulation(); this.ready = false;});
  76. this.body.emitter.on('disablePhysics', () => {this.physicsEnabled = false; this.stopSimulation();});
  77. this.body.emitter.on('restorePhysics', () => {
  78. this.setOptions(this.options);
  79. if (this.ready === true) {
  80. this.startSimulation();
  81. }
  82. });
  83. this.body.emitter.on('startSimulation', () => {
  84. if (this.ready === true) {
  85. this.startSimulation();
  86. }
  87. });
  88. this.body.emitter.on('stopSimulation', () => {this.stopSimulation();});
  89. this.body.emitter.on('destroy', () => {
  90. this.stopSimulation(false);
  91. this.body.emitter.off();
  92. });
  93. this.body.emitter.on('_positionUpdate', (properties) => this.positionUpdateHandler(properties));
  94. this.body.emitter.on('_physicsUpdate', (properties) => this.physicsUpdateHandler(properties));
  95. this.body.emitter.on('dragStart', (properties) => {
  96. this.draggingNodes = properties.nodes;
  97. });
  98. this.body.emitter.on('dragEnd', () => {
  99. this.draggingNodes = [];
  100. });
  101. this.body.emitter.on('destroy', () => {
  102. if (this.physicsWorker) {
  103. this.physicsWorker.terminate();
  104. this.physicsWorker = undefined;
  105. }
  106. });
  107. }
  108. /**
  109. * set the physics options
  110. * @param options
  111. */
  112. setOptions(options) {
  113. if (options !== undefined) {
  114. if (options === false) {
  115. this.options.enabled = false;
  116. this.physicsEnabled = false;
  117. this.stopSimulation();
  118. }
  119. else {
  120. this.physicsEnabled = true;
  121. util.selectiveNotDeepExtend(['stabilization'], this.options, options);
  122. util.mergeOptions(this.options, options, 'stabilization')
  123. if (options.enabled === undefined) {
  124. this.options.enabled = true;
  125. }
  126. if (this.options.enabled === false) {
  127. this.physicsEnabled = false;
  128. this.stopSimulation();
  129. }
  130. // set the timestep
  131. this.timestep = this.options.timestep;
  132. }
  133. }
  134. if (this.options.useWorker) {
  135. this.initPhysicsWorker();
  136. this.physicsWorker.postMessage({type: 'options', data: this.options});
  137. } else {
  138. this.initEmbeddedPhysics();
  139. }
  140. }
  141. /**
  142. * configure the engine.
  143. */
  144. initEmbeddedPhysics() {
  145. this.positionUpdateHandler = () => {};
  146. this.physicsUpdateHandler = () => {};
  147. if (this.physicsWorker) {
  148. this.options.useWorker = false;
  149. this.physicsWorker.terminate();
  150. this.physicsWorker = undefined;
  151. this.initPhysicsData();
  152. }
  153. this.initPhysicsSolvers();
  154. }
  155. initPhysicsWorker() {
  156. if (!this.physicsWorker) {
  157. // setup path to webworker javascript file
  158. if (!__webpack_public_path__) {
  159. let parentScript = document.getElementById('visjs');
  160. if (parentScript) {
  161. let src = parentScript.getAttribute('src')
  162. __webpack_public_path__ = src.substr(0, src.lastIndexOf('/') + 1);
  163. } else {
  164. let scripts = document.getElementsByTagName('script');
  165. for (let i = 0; i < scripts.length; i++) {
  166. let src = scripts[i].getAttribute('src');
  167. if (src && src.length >= 6) {
  168. let position = src.length - 6;
  169. let index = src.indexOf('vis.js', position);
  170. if (index === position) {
  171. __webpack_public_path__ = src.substr(0, src.lastIndexOf('/') + 1);
  172. break;
  173. }
  174. }
  175. }
  176. }
  177. }
  178. // launch webworker
  179. this.physicsWorker = new PhysicsWorker();
  180. this.physicsWorker.addEventListener('message', (event) => {
  181. this.physicsWorkerMessageHandler(event);
  182. });
  183. this.physicsWorker.onerror = (event) => {
  184. console.error('Falling back to embedded physics engine', event);
  185. this.initEmbeddedPhysics();
  186. // throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
  187. };
  188. this.positionUpdateHandler = (positions) => {
  189. this.physicsWorker.postMessage({type: 'updatePositions', data: positions});
  190. };
  191. this.physicsUpdateHandler = (properties) => {
  192. this._physicsUpdateHandler(properties);
  193. };
  194. }
  195. }
  196. _physicsUpdateHandler(properties) {
  197. if (properties.options.physics !== undefined) {
  198. if (properties.options.physics) {
  199. let data = {
  200. nodes: {},
  201. edges: {}
  202. };
  203. if (properties.type === 'node') {
  204. data.nodes[properties.id] = this.createPhysicsNode(properties.id);
  205. } else if (properties.type === 'edge') {
  206. data.edges[properties.id] = this.createPhysicsEdge(properties.id);
  207. } else {
  208. console.warn('invalid element type');
  209. }
  210. this.physicsWorker.postMessage({
  211. type: 'addElements',
  212. data: data
  213. });
  214. } else {
  215. let data = {
  216. nodeIds: [],
  217. edgeIds: []
  218. };
  219. if (properties.type === 'node') {
  220. data.nodeIds = [properties.id.toString()];
  221. } else if (properties.type === 'edge') {
  222. data.edgeIds = [properties.id.toString()];
  223. } else {
  224. console.warn('invalid element type');
  225. }
  226. this.physicsWorker.postMessage({type: 'removeElements', data: data});
  227. }
  228. } else {
  229. this.physicsWorker.postMessage({type: 'updateProperties', data: properties});
  230. }
  231. }
  232. physicsWorkerMessageHandler(event) {
  233. var msg = event.data;
  234. switch (msg.type) {
  235. case 'positions':
  236. this.stabilized = msg.data.stabilized;
  237. this._receivedPositions(msg.data.positions);
  238. break;
  239. case 'finalizeStabilization':
  240. this.stabilizationIterations = msg.data.stabilizationIterations;
  241. this._finalizeStabilization();
  242. break;
  243. case 'emit':
  244. this.emit(msg.data.event, msg.data.data);
  245. break;
  246. default:
  247. console.warn('unhandled physics worker message:', msg);
  248. }
  249. }
  250. _receivedPositions(positions) {
  251. for (let i = 0; i < this.draggingNodes.length; i++) {
  252. delete positions[this.draggingNodes[i]];
  253. }
  254. let nodeIds = Object.keys(positions);
  255. for (let i = 0; i < nodeIds.length; i++) {
  256. let nodeId = nodeIds[i];
  257. let node = this.body.nodes[nodeId];
  258. // handle case where we get a positions from an old physicsObject
  259. if (node) {
  260. node.setX(positions[nodeId].x);
  261. node.setY(positions[nodeId].y);
  262. }
  263. }
  264. }
  265. /**
  266. * initialize the engine
  267. */
  268. initPhysics() {
  269. if (this.physicsEnabled === true && this.options.enabled === true) {
  270. if (this.options.stabilization.enabled === true) {
  271. this.stabilize();
  272. }
  273. else {
  274. this.stabilized = false;
  275. this.ready = true;
  276. this.body.emitter.emit('fit', {}, this.layoutFailed); // if the layout failed, we use the approximation for the zoom
  277. this.startSimulation();
  278. }
  279. }
  280. else {
  281. this.ready = true;
  282. this.body.emitter.emit('fit');
  283. }
  284. }
  285. /**
  286. * Start the simulation
  287. */
  288. startSimulation() {
  289. if (this.physicsEnabled === true && this.options.enabled === true) {
  290. this.stabilized = false;
  291. this._updateWorkerStabilized();
  292. // when visible, adaptivity is disabled.
  293. this.adaptiveTimestep = false;
  294. // this sets the width of all nodes initially which could be required for the avoidOverlap
  295. this.body.emitter.emit("_resizeNodes");
  296. if (this.viewFunction === undefined) {
  297. this.viewFunction = this.simulationStep.bind(this);
  298. this.body.emitter.on('initRedraw', this.viewFunction);
  299. this.body.emitter.emit('_startRendering');
  300. }
  301. }
  302. else {
  303. this.body.emitter.emit('_redraw');
  304. }
  305. }
  306. /**
  307. * Stop the simulation, force stabilization.
  308. */
  309. stopSimulation(emit = true) {
  310. this.stabilized = true;
  311. this._updateWorkerStabilized();
  312. if (emit === true) {
  313. this._emitStabilized();
  314. }
  315. if (this.viewFunction !== undefined) {
  316. this.body.emitter.off('initRedraw', this.viewFunction);
  317. this.viewFunction = undefined;
  318. if (emit === true) {
  319. this.body.emitter.emit('_stopRendering');
  320. }
  321. }
  322. }
  323. _updateWorkerStabilized() {
  324. if (this.physicsWorker) {
  325. this.physicsWorker.postMessage({
  326. type: 'setStabilized',
  327. data: this.stabilized
  328. });
  329. }
  330. }
  331. /**
  332. * The viewFunction inserts this step into each renderloop. It calls the physics tick and handles the cleanup at stabilized.
  333. *
  334. */
  335. simulationStep() {
  336. if (this.physicsWorker) {
  337. this.physicsWorker.postMessage({type: 'physicsTick'});
  338. } else {
  339. // check if the physics have settled
  340. var startTime = Date.now();
  341. this.physicsTick();
  342. var physicsTime = Date.now() - startTime;
  343. // run double speed if it is a little graph
  344. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) {
  345. this.physicsTick();
  346. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  347. this.runDoubleSpeed = true;
  348. }
  349. }
  350. if (this.stabilized === true) {
  351. this.stopSimulation();
  352. }
  353. }
  354. // TODO determine when startedStabilization needs to be propogated from the worker
  355. /**
  356. * trigger the stabilized event.
  357. * @private
  358. */
  359. _emitStabilized(amountOfIterations = this.stabilizationIterations) {
  360. if (this.stabilizationIterations > 1 || this.startedStabilization === true) {
  361. setTimeout(() => {
  362. this.body.emitter.emit('stabilized', {iterations: amountOfIterations});
  363. this.startedStabilization = false;
  364. this.stabilizationIterations = 0;
  365. }, 0);
  366. }
  367. }
  368. createPhysicsNode(nodeId) {
  369. let node = this.body.nodes[nodeId];
  370. if (node) {
  371. return {
  372. id: node.id.toString(),
  373. x: node.x,
  374. y: node.y,
  375. // TODO update on change
  376. edges: {
  377. length: node.edges.length
  378. },
  379. options: {
  380. fixed: {
  381. x: node.options.fixed.x,
  382. y: node.options.fixed.y
  383. },
  384. mass: node.options.mass
  385. }
  386. }
  387. }
  388. }
  389. createPhysicsEdge(edgeId) {
  390. let edge = this.body.edges[edgeId];
  391. if (edge && edge.options.physics === true) {
  392. let physicsEdge = {
  393. id: edge.id,
  394. connected: edge.connected,
  395. edgeType: {},
  396. toId: edge.toId,
  397. fromId: edge.fromId,
  398. options: {
  399. length: edge.length
  400. }
  401. };
  402. // TODO test/implment dynamic
  403. if (edge.edgeType.via) {
  404. physicsEdge.edgeType = {
  405. via: {
  406. id: edge.edgeType.via.id
  407. }
  408. }
  409. }
  410. return physicsEdge;
  411. }
  412. }
  413. /**
  414. * 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.
  415. *
  416. * @private
  417. */
  418. initPhysicsData() {
  419. let nodes = this.body.nodes;
  420. let edges = this.body.edges;
  421. this.physicsBody.forces = {};
  422. this.physicsBody.physicsNodeIndices = [];
  423. this.physicsBody.physicsEdgeIndices = [];
  424. let physicsWorkerNodes = {};
  425. let physicsWorkerEdges = {};
  426. // get node indices for physics
  427. for (let nodeId in nodes) {
  428. if (nodes.hasOwnProperty(nodeId)) {
  429. if (nodes[nodeId].options.physics === true) {
  430. this.physicsBody.physicsNodeIndices.push(nodeId);
  431. if (this.physicsWorker) {
  432. physicsWorkerNodes[nodeId] = this.createPhysicsNode(nodeId);
  433. }
  434. }
  435. }
  436. }
  437. // get edge indices for physics
  438. for (let edgeId in edges) {
  439. if (edges.hasOwnProperty(edgeId)) {
  440. if (edges[edgeId].options.physics === true) {
  441. this.physicsBody.physicsEdgeIndices.push(edgeId);
  442. if (this.physicsWorker) {
  443. physicsWorkerEdges[edgeId] = this.createPhysicsEdge(edgeId);
  444. }
  445. }
  446. }
  447. }
  448. // get the velocity and the forces vector
  449. for (let i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  450. let nodeId = this.physicsBody.physicsNodeIndices[i];
  451. this.physicsBody.forces[nodeId] = {x: 0, y: 0};
  452. // forces can be reset because they are recalculated. Velocities have to persist.
  453. if (this.physicsBody.velocities[nodeId] === undefined) {
  454. this.physicsBody.velocities[nodeId] = {x: 0, y: 0};
  455. }
  456. }
  457. // clean deleted nodes from the velocity vector
  458. for (let nodeId in this.physicsBody.velocities) {
  459. if (nodes[nodeId] === undefined) {
  460. delete this.physicsBody.velocities[nodeId];
  461. }
  462. }
  463. if (this.physicsWorker) {
  464. this.physicsWorker.postMessage({
  465. type: 'initPhysicsData',
  466. data: {
  467. nodes: physicsWorkerNodes,
  468. edges: physicsWorkerEdges
  469. }
  470. });
  471. }
  472. }
  473. /**
  474. * Perform the actual step
  475. *
  476. * @param nodeId
  477. * @param maxVelocity
  478. * @returns {number}
  479. * @private
  480. */
  481. _performStep(nodeId,maxVelocity) {
  482. let node = this.body.nodes[nodeId];
  483. let timestep = this.timestep;
  484. let forces = this.physicsBody.forces;
  485. let velocities = this.physicsBody.velocities;
  486. // store the state so we can revert
  487. this.previousStates[nodeId] = {x:node.x, y:node.y, vx:velocities[nodeId].x, vy:velocities[nodeId].y};
  488. if (node.options.fixed.x === false) {
  489. let dx = this.modelOptions.damping * velocities[nodeId].x; // damping force
  490. let ax = (forces[nodeId].x - dx) / node.options.mass; // acceleration
  491. velocities[nodeId].x += ax * timestep; // velocity
  492. velocities[nodeId].x = (Math.abs(velocities[nodeId].x) > maxVelocity) ? ((velocities[nodeId].x > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].x;
  493. node.setX(node.x + velocities[nodeId].x * timestep); // position
  494. }
  495. else {
  496. forces[nodeId].x = 0;
  497. velocities[nodeId].x = 0;
  498. }
  499. if (node.options.fixed.y === false) {
  500. let dy = this.modelOptions.damping * velocities[nodeId].y; // damping force
  501. let ay = (forces[nodeId].y - dy) / node.options.mass; // acceleration
  502. velocities[nodeId].y += ay * timestep; // velocity
  503. velocities[nodeId].y = (Math.abs(velocities[nodeId].y) > maxVelocity) ? ((velocities[nodeId].y > 0) ? maxVelocity : -maxVelocity) : velocities[nodeId].y;
  504. node.setY(node.y + velocities[nodeId].y * timestep); // position
  505. }
  506. else {
  507. forces[nodeId].y = 0;
  508. velocities[nodeId].y = 0;
  509. }
  510. let totalVelocity = Math.sqrt(Math.pow(velocities[nodeId].x,2) + Math.pow(velocities[nodeId].y,2));
  511. return totalVelocity;
  512. }
  513. // TODO probably want to move freeze/restore to PhysicsBase and do in worker if running
  514. /**
  515. * When initializing and stabilizing, we can freeze nodes with a predefined position. This greatly speeds up stabilization
  516. * because only the supportnodes for the smoothCurves have to settle.
  517. *
  518. * @private
  519. */
  520. _freezeNodes() {
  521. var nodes = this.body.nodes;
  522. for (var id in nodes) {
  523. if (nodes.hasOwnProperty(id)) {
  524. if (nodes[id].x && nodes[id].y) {
  525. this.freezeCache[id] = {x:nodes[id].options.fixed.x,y:nodes[id].options.fixed.y};
  526. nodes[id].setFixed(true);
  527. }
  528. }
  529. }
  530. }
  531. /**
  532. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  533. *
  534. * @private
  535. */
  536. _restoreFrozenNodes() {
  537. var nodes = this.body.nodes;
  538. for (var id in nodes) {
  539. if (nodes.hasOwnProperty(id)) {
  540. if (this.freezeCache[id] !== undefined) {
  541. nodes[id].setFixed({x: this.freezeCache[id].x, y: this.freezeCache[id].y});
  542. }
  543. }
  544. }
  545. this.freezeCache = {};
  546. }
  547. /**
  548. * Find a stable position for all nodes
  549. * @private
  550. */
  551. stabilize(iterations = this.options.stabilization.iterations) {
  552. if (typeof iterations !== 'number') {
  553. console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', this.options.stabilization.iterations);
  554. iterations = this.options.stabilization.iterations;
  555. }
  556. if (this.physicsBody.physicsNodeIndices.length === 0) {
  557. this.ready = true;
  558. return;
  559. }
  560. // enable adaptive timesteps
  561. this.adaptiveTimestep = true && this.options.adaptiveTimestep;
  562. // this sets the width of all nodes initially which could be required for the avoidOverlap
  563. this.body.emitter.emit("_resizeNodes");
  564. // stop the render loop
  565. this.stopSimulation();
  566. // set stabilize to false
  567. this.stabilized = false;
  568. // block redraw requests
  569. this.body.emitter.emit('_blockRedraw');
  570. this.targetIterations = iterations;
  571. // start the stabilization
  572. if (this.options.stabilization.onlyDynamicEdges === true) {
  573. this._freezeNodes();
  574. }
  575. this.stabilizationIterations = 0;
  576. if (this.physicsWorker) {
  577. this.physicsWorker.postMessage({
  578. type: 'stabilize',
  579. data: {
  580. targetIterations: iterations
  581. }
  582. });
  583. } else {
  584. setTimeout(() => this._stabilizationBatch(), 0);
  585. }
  586. }
  587. /**
  588. * Wrap up the stabilization, fit and emit the events.
  589. * @private
  590. */
  591. _finalizeStabilization() {
  592. this.body.emitter.emit('_allowRedraw');
  593. if (this.options.stabilization.fit === true) {
  594. this.body.emitter.emit('fit');
  595. }
  596. if (this.options.stabilization.onlyDynamicEdges === true) {
  597. this._restoreFrozenNodes();
  598. }
  599. this.body.emitter.emit('stabilizationIterationsDone');
  600. this.body.emitter.emit('_requestRedraw');
  601. if (this.stabilized === true) {
  602. this._emitStabilized();
  603. }
  604. else {
  605. this.startSimulation();
  606. }
  607. this.ready = true;
  608. }
  609. }
  610. export default PhysicsEngine;