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.

2399 lines
68 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. var Emitter = require('emitter-component');
  2. var util = require('../util');
  3. var Point3d = require('./Point3d');
  4. var Point2d = require('./Point2d');
  5. var Slider = require('./Slider');
  6. var StepNumber = require('./StepNumber');
  7. var Settings = require('./Settings');
  8. var Validator = require("./../shared/Validator").default;
  9. var {printStyle} = require('./../shared/Validator');
  10. var {allOptions} = require('./options.js');
  11. var DataGroup = require('./DataGroup');
  12. /// enumerate the available styles
  13. Graph3d.STYLE = Settings.STYLE;
  14. /**
  15. * Following label is used in the settings to describe values which should be
  16. * determined by the code while running, from the current data and graph style.
  17. *
  18. * Using 'undefined' directly achieves the same thing, but this is more
  19. * descriptive by describing the intent.
  20. */
  21. var autoByDefault = undefined;
  22. /**
  23. * Default values for option settings.
  24. *
  25. * These are the values used when a Graph3d instance is initialized without
  26. * custom settings.
  27. *
  28. * If a field is not in this list, a default value of 'autoByDefault' is assumed,
  29. * which is just an alias for 'undefined'.
  30. */
  31. Graph3d.DEFAULTS = {
  32. width : '400px',
  33. height : '400px',
  34. filterLabel : 'time',
  35. legendLabel : 'value',
  36. xLabel : 'x',
  37. yLabel : 'y',
  38. zLabel : 'z',
  39. xValueLabel : function(v) { return v; },
  40. yValueLabel : function(v) { return v; },
  41. zValueLabel : function(v) { return v; },
  42. showXAxis : true,
  43. showYAxis : true,
  44. showZAxis : true,
  45. showGrid : true,
  46. showPerspective : true,
  47. showShadow : false,
  48. keepAspectRatio : true,
  49. verticalRatio : 0.5, // 0.1 to 1.0, where 1.0 results in a 'cube'
  50. dotSizeRatio : 0.02, // size of the dots as a fraction of the graph width
  51. dotSizeMinFraction: 0.5, // size of min-value dot as a fraction of dotSizeRatio
  52. dotSizeMaxFraction: 2.5, // size of max-value dot as a fraction of dotSizeRatio
  53. showAnimationControls: autoByDefault,
  54. animationInterval : 1000, // milliseconds
  55. animationPreload : false,
  56. animationAutoStart : autoByDefault,
  57. axisColor : '#4D4D4D',
  58. gridColor : '#D3D3D3',
  59. xCenter : '55%',
  60. yCenter : '50%',
  61. style : Graph3d.STYLE.DOT,
  62. tooltip : false,
  63. tooltipStyle : {
  64. content : {
  65. padding : '10px',
  66. border : '1px solid #4d4d4d',
  67. color : '#1a1a1a',
  68. background : 'rgba(255,255,255,0.7)',
  69. borderRadius : '2px',
  70. boxShadow : '5px 5px 10px rgba(128,128,128,0.5)'
  71. },
  72. line : {
  73. height : '40px',
  74. width : '0',
  75. borderLeft : '1px solid #4d4d4d'
  76. },
  77. dot : {
  78. height : '0',
  79. width : '0',
  80. border : '5px solid #4d4d4d',
  81. borderRadius : '5px'
  82. }
  83. },
  84. dataColor : {
  85. fill : '#7DC1FF',
  86. stroke : '#3267D2',
  87. strokeWidth: 1 // px
  88. },
  89. cameraPosition : {
  90. horizontal: 1.0,
  91. vertical : 0.5,
  92. distance : 1.7
  93. },
  94. /*
  95. The following fields are 'auto by default', see above.
  96. */
  97. showLegend : autoByDefault, // determined by graph style
  98. backgroundColor : autoByDefault,
  99. xBarWidth : autoByDefault,
  100. yBarWidth : autoByDefault,
  101. valueMin : autoByDefault,
  102. valueMax : autoByDefault,
  103. xMin : autoByDefault,
  104. xMax : autoByDefault,
  105. xStep : autoByDefault,
  106. yMin : autoByDefault,
  107. yMax : autoByDefault,
  108. yStep : autoByDefault,
  109. zMin : autoByDefault,
  110. zMax : autoByDefault,
  111. zStep : autoByDefault
  112. };
  113. // -----------------------------------------------------------------------------
  114. // Class Graph3d
  115. // -----------------------------------------------------------------------------
  116. /**
  117. * Graph3d displays data in 3d.
  118. *
  119. * Graph3d is developed in javascript as a Google Visualization Chart.
  120. *
  121. * @constructor Graph3d
  122. * @param {Element} container The DOM element in which the Graph3d will
  123. * be created. Normally a div element.
  124. * @param {DataSet | DataView | Array} [data]
  125. * @param {Object} [options]
  126. */
  127. function Graph3d(container, data, options) {
  128. if (!(this instanceof Graph3d)) {
  129. throw new SyntaxError('Constructor must be called with the new operator');
  130. }
  131. // create variables and set default values
  132. this.containerElement = container;
  133. this.dataGroup = new DataGroup();
  134. this.dataPoints = null; // The table with point objects
  135. // create a frame and canvas
  136. this.create();
  137. Settings.setDefaults(Graph3d.DEFAULTS, this);
  138. // the column indexes
  139. this.colX = undefined;
  140. this.colY = undefined;
  141. this.colZ = undefined;
  142. this.colValue = undefined;
  143. // TODO: customize axis range
  144. // apply options (also when undefined)
  145. this.setOptions(options);
  146. // apply data
  147. this.setData(data);
  148. }
  149. // Extend Graph3d with an Emitter mixin
  150. Emitter(Graph3d.prototype);
  151. /**
  152. * Calculate the scaling values, dependent on the range in x, y, and z direction
  153. */
  154. Graph3d.prototype._setScale = function() {
  155. this.scale = new Point3d(
  156. 1 / this.xRange.range(),
  157. 1 / this.yRange.range(),
  158. 1 / this.zRange.range()
  159. );
  160. // keep aspect ration between x and y scale if desired
  161. if (this.keepAspectRatio) {
  162. if (this.scale.x < this.scale.y) {
  163. //noinspection JSSuspiciousNameCombination
  164. this.scale.y = this.scale.x;
  165. }
  166. else {
  167. //noinspection JSSuspiciousNameCombination
  168. this.scale.x = this.scale.y;
  169. }
  170. }
  171. // scale the vertical axis
  172. this.scale.z *= this.verticalRatio;
  173. // TODO: can this be automated? verticalRatio?
  174. // determine scale for (optional) value
  175. if (this.valueRange !== undefined) {
  176. this.scale.value = 1 / this.valueRange.range();
  177. }
  178. // position the camera arm
  179. var xCenter = this.xRange.center() * this.scale.x;
  180. var yCenter = this.yRange.center() * this.scale.y;
  181. var zCenter = this.zRange.center() * this.scale.z;
  182. this.camera.setArmLocation(xCenter, yCenter, zCenter);
  183. };
  184. /**
  185. * Convert a 3D location to a 2D location on screen
  186. * Source: ttp://en.wikipedia.org/wiki/3D_projection
  187. *
  188. * @param {Point3d} point3d A 3D point with parameters x, y, z
  189. * @returns {Point2d} point2d A 2D point with parameters x, y
  190. */
  191. Graph3d.prototype._convert3Dto2D = function(point3d) {
  192. var translation = this._convertPointToTranslation(point3d);
  193. return this._convertTranslationToScreen(translation);
  194. };
  195. /**
  196. * Convert a 3D location its translation seen from the camera
  197. * Source: http://en.wikipedia.org/wiki/3D_projection
  198. *
  199. * @param {Point3d} point3d A 3D point with parameters x, y, z
  200. * @returns {Point3d} translation A 3D point with parameters x, y, z This is
  201. * the translation of the point, seen from the
  202. * camera.
  203. */
  204. Graph3d.prototype._convertPointToTranslation = function(point3d) {
  205. var cameraLocation = this.camera.getCameraLocation(),
  206. cameraRotation = this.camera.getCameraRotation(),
  207. ax = point3d.x * this.scale.x,
  208. ay = point3d.y * this.scale.y,
  209. az = point3d.z * this.scale.z,
  210. cx = cameraLocation.x,
  211. cy = cameraLocation.y,
  212. cz = cameraLocation.z,
  213. // calculate angles
  214. sinTx = Math.sin(cameraRotation.x),
  215. cosTx = Math.cos(cameraRotation.x),
  216. sinTy = Math.sin(cameraRotation.y),
  217. cosTy = Math.cos(cameraRotation.y),
  218. sinTz = Math.sin(cameraRotation.z),
  219. cosTz = Math.cos(cameraRotation.z),
  220. // calculate translation
  221. dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
  222. dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)),
  223. dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx));
  224. return new Point3d(dx, dy, dz);
  225. };
  226. /**
  227. * Convert a translation point to a point on the screen
  228. *
  229. * @param {Point3d} translation A 3D point with parameters x, y, z This is
  230. * the translation of the point, seen from the
  231. * camera.
  232. * @returns {Point2d} point2d A 2D point with parameters x, y
  233. */
  234. Graph3d.prototype._convertTranslationToScreen = function(translation) {
  235. var ex = this.eye.x,
  236. ey = this.eye.y,
  237. ez = this.eye.z,
  238. dx = translation.x,
  239. dy = translation.y,
  240. dz = translation.z;
  241. // calculate position on screen from translation
  242. var bx;
  243. var by;
  244. if (this.showPerspective) {
  245. bx = (dx - ex) * (ez / dz);
  246. by = (dy - ey) * (ez / dz);
  247. }
  248. else {
  249. bx = dx * -(ez / this.camera.getArmLength());
  250. by = dy * -(ez / this.camera.getArmLength());
  251. }
  252. // shift and scale the point to the center of the screen
  253. // use the width of the graph to scale both horizontally and vertically.
  254. return new Point2d(
  255. this.currentXCenter + bx * this.frame.canvas.clientWidth,
  256. this.currentYCenter - by * this.frame.canvas.clientWidth);
  257. };
  258. /**
  259. * Calculate the translations and screen positions of all points
  260. *
  261. * @param {Array.<Point3d>} points
  262. * @private
  263. */
  264. Graph3d.prototype._calcTranslations = function(points) {
  265. for (var i = 0; i < points.length; i++) {
  266. var point = points[i];
  267. point.trans = this._convertPointToTranslation(point.point);
  268. point.screen = this._convertTranslationToScreen(point.trans);
  269. // calculate the translation of the point at the bottom (needed for sorting)
  270. var transBottom = this._convertPointToTranslation(point.bottom);
  271. point.dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  272. }
  273. // sort the points on depth of their (x,y) position (not on z)
  274. var sortDepth = function (a, b) {
  275. return b.dist - a.dist;
  276. };
  277. points.sort(sortDepth);
  278. };
  279. /**
  280. * Transfer min/max values to the Graph3d instance.
  281. */
  282. Graph3d.prototype._initializeRanges = function() {
  283. // TODO: later on, all min/maxes of all datagroups will be combined here
  284. var dg = this.dataGroup;
  285. this.xRange = dg.xRange;
  286. this.yRange = dg.yRange;
  287. this.zRange = dg.zRange;
  288. this.valueRange = dg.valueRange;
  289. // Values currently needed but which need to be sorted out for
  290. // the multiple graph case.
  291. this.xStep = dg.xStep;
  292. this.yStep = dg.yStep;
  293. this.zStep = dg.zStep;
  294. this.xBarWidth = dg.xBarWidth;
  295. this.yBarWidth = dg.yBarWidth;
  296. this.colX = dg.colX;
  297. this.colY = dg.colY;
  298. this.colZ = dg.colZ;
  299. this.colValue = dg.colValue;
  300. // set the scale dependent on the ranges.
  301. this._setScale();
  302. };
  303. /**
  304. * Return all data values as a list of Point3d objects
  305. *
  306. * @param {vis.DataSet} data
  307. * @returns {Array.<Object>}
  308. */
  309. Graph3d.prototype.getDataPoints = function(data) {
  310. var dataPoints = [];
  311. for (var i = 0; i < data.length; i++) {
  312. var point = new Point3d();
  313. point.x = data[i][this.colX] || 0;
  314. point.y = data[i][this.colY] || 0;
  315. point.z = data[i][this.colZ] || 0;
  316. point.data = data[i];
  317. if (this.colValue !== undefined) {
  318. point.value = data[i][this.colValue] || 0;
  319. }
  320. var obj = {};
  321. obj.point = point;
  322. obj.bottom = new Point3d(point.x, point.y, this.zRange.min);
  323. obj.trans = undefined;
  324. obj.screen = undefined;
  325. dataPoints.push(obj);
  326. }
  327. return dataPoints;
  328. };
  329. /**
  330. * Filter the data based on the current filter
  331. *
  332. * @param {Array} data
  333. * @returns {Array} dataPoints Array with point objects which can be drawn on
  334. * screen
  335. */
  336. Graph3d.prototype._getDataPoints = function (data) {
  337. // TODO: store the created matrix dataPoints in the filters instead of
  338. // reloading each time.
  339. var x, y, i, obj;
  340. var dataPoints = [];
  341. if (this.style === Graph3d.STYLE.GRID ||
  342. this.style === Graph3d.STYLE.SURFACE) {
  343. // copy all values from the data table to a matrix
  344. // the provided values are supposed to form a grid of (x,y) positions
  345. // create two lists with all present x and y values
  346. var dataX = this.dataGroup.getDistinctValues(this.colX, data);
  347. var dataY = this.dataGroup.getDistinctValues(this.colY, data);
  348. dataPoints = this.getDataPoints(data);
  349. // create a grid, a 2d matrix, with all values.
  350. var dataMatrix = []; // temporary data matrix
  351. for (i = 0; i < dataPoints.length; i++) {
  352. obj = dataPoints[i];
  353. // TODO: implement Array().indexOf() for Internet Explorer
  354. var xIndex = dataX.indexOf(obj.point.x);
  355. var yIndex = dataY.indexOf(obj.point.y);
  356. if (dataMatrix[xIndex] === undefined) {
  357. dataMatrix[xIndex] = [];
  358. }
  359. dataMatrix[xIndex][yIndex] = obj;
  360. }
  361. // fill in the pointers to the neighbors.
  362. for (x = 0; x < dataMatrix.length; x++) {
  363. for (y = 0; y < dataMatrix[x].length; y++) {
  364. if (dataMatrix[x][y]) {
  365. dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined;
  366. dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined;
  367. dataMatrix[x][y].pointCross =
  368. (x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ?
  369. dataMatrix[x+1][y+1] :
  370. undefined;
  371. }
  372. }
  373. }
  374. }
  375. else { // 'dot', 'dot-line', etc.
  376. this._checkValueField(data);
  377. dataPoints = this.getDataPoints(data);
  378. if (this.style === Graph3d.STYLE.LINE) {
  379. // Add next member points for line drawing
  380. for (i = 0; i < dataPoints.length; i++) {
  381. if (i > 0) {
  382. dataPoints[i - 1].pointNext = dataPoints[i];
  383. }
  384. }
  385. }
  386. }
  387. return dataPoints;
  388. };
  389. /**
  390. * Create the main frame for the Graph3d.
  391. *
  392. * This function is executed once when a Graph3d object is created. The frame
  393. * contains a canvas, and this canvas contains all objects like the axis and
  394. * nodes.
  395. */
  396. Graph3d.prototype.create = function () {
  397. // remove all elements from the container element.
  398. while (this.containerElement.hasChildNodes()) {
  399. this.containerElement.removeChild(this.containerElement.firstChild);
  400. }
  401. this.frame = document.createElement('div');
  402. this.frame.style.position = 'relative';
  403. this.frame.style.overflow = 'hidden';
  404. // create the graph canvas (HTML canvas element)
  405. this.frame.canvas = document.createElement( 'canvas' );
  406. this.frame.canvas.style.position = 'relative';
  407. this.frame.appendChild(this.frame.canvas);
  408. //if (!this.frame.canvas.getContext) {
  409. {
  410. var noCanvas = document.createElement( 'DIV' );
  411. noCanvas.style.color = 'red';
  412. noCanvas.style.fontWeight = 'bold' ;
  413. noCanvas.style.padding = '10px';
  414. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  415. this.frame.canvas.appendChild(noCanvas);
  416. }
  417. this.frame.filter = document.createElement( 'div' );
  418. this.frame.filter.style.position = 'absolute';
  419. this.frame.filter.style.bottom = '0px';
  420. this.frame.filter.style.left = '0px';
  421. this.frame.filter.style.width = '100%';
  422. this.frame.appendChild(this.frame.filter);
  423. // add event listeners to handle moving and zooming the contents
  424. var me = this;
  425. var onmousedown = function (event) {me._onMouseDown(event);};
  426. var ontouchstart = function (event) {me._onTouchStart(event);};
  427. var onmousewheel = function (event) {me._onWheel(event);};
  428. var ontooltip = function (event) {me._onTooltip(event);};
  429. var onclick = function(event) {me._onClick(event);};
  430. // TODO: these events are never cleaned up... can give a 'memory leakage'
  431. util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
  432. util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
  433. util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
  434. util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
  435. util.addEventListener(this.frame.canvas, 'click', onclick);
  436. // add the new graph to the container element
  437. this.containerElement.appendChild(this.frame);
  438. };
  439. /**
  440. * Set a new size for the graph
  441. *
  442. * @param {number} width
  443. * @param {number} height
  444. * @private
  445. */
  446. Graph3d.prototype._setSize = function(width, height) {
  447. this.frame.style.width = width;
  448. this.frame.style.height = height;
  449. this._resizeCanvas();
  450. };
  451. /**
  452. * Resize the canvas to the current size of the frame
  453. */
  454. Graph3d.prototype._resizeCanvas = function() {
  455. this.frame.canvas.style.width = '100%';
  456. this.frame.canvas.style.height = '100%';
  457. this.frame.canvas.width = this.frame.canvas.clientWidth;
  458. this.frame.canvas.height = this.frame.canvas.clientHeight;
  459. // adjust with for margin
  460. this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px';
  461. };
  462. /**
  463. * Start playing the animation, if requested and filter present. Only applicable
  464. * when animation data is available.
  465. */
  466. Graph3d.prototype.animationStart = function() {
  467. // start animation when option is true
  468. if (!this.animationAutoStart || !this.dataGroup.dataFilter) return;
  469. if (!this.frame.filter || !this.frame.filter.slider)
  470. throw new Error('No animation available');
  471. this.frame.filter.slider.play();
  472. };
  473. /**
  474. * Stop animation
  475. */
  476. Graph3d.prototype.animationStop = function() {
  477. if (!this.frame.filter || !this.frame.filter.slider) return;
  478. this.frame.filter.slider.stop();
  479. };
  480. /**
  481. * Resize the center position based on the current values in this.xCenter
  482. * and this.yCenter (which are strings with a percentage or a value
  483. * in pixels). The center positions are the variables this.currentXCenter
  484. * and this.currentYCenter
  485. */
  486. Graph3d.prototype._resizeCenter = function() {
  487. // calculate the horizontal center position
  488. if (this.xCenter.charAt(this.xCenter.length-1) === '%') {
  489. this.currentXCenter =
  490. parseFloat(this.xCenter) / 100 *
  491. this.frame.canvas.clientWidth;
  492. }
  493. else {
  494. this.currentXCenter = parseFloat(this.xCenter); // supposed to be in px
  495. }
  496. // calculate the vertical center position
  497. if (this.yCenter.charAt(this.yCenter.length-1) === '%') {
  498. this.currentYCenter =
  499. parseFloat(this.yCenter) / 100 *
  500. (this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
  501. }
  502. else {
  503. this.currentYCenter = parseFloat(this.yCenter); // supposed to be in px
  504. }
  505. };
  506. /**
  507. * Retrieve the current camera rotation
  508. *
  509. * @returns {object} An object with parameters horizontal, vertical, and
  510. * distance
  511. */
  512. Graph3d.prototype.getCameraPosition = function() {
  513. var pos = this.camera.getArmRotation();
  514. pos.distance = this.camera.getArmLength();
  515. return pos;
  516. };
  517. /**
  518. * Load data into the 3D Graph
  519. *
  520. * @param {vis.DataSet} data
  521. * @private
  522. */
  523. Graph3d.prototype._readData = function(data) {
  524. // read the data
  525. this.dataPoints = this.dataGroup.initializeData(this, data, this.style);
  526. this._initializeRanges();
  527. this._redrawFilter();
  528. };
  529. /**
  530. * Replace the dataset of the Graph3d
  531. *
  532. * @param {Array | DataSet | DataView} data
  533. */
  534. Graph3d.prototype.setData = function (data) {
  535. if (data === undefined || data === null) return;
  536. this._readData(data);
  537. this.redraw();
  538. this.animationStart();
  539. };
  540. /**
  541. * Update the options. Options will be merged with current options
  542. *
  543. * @param {Object} options
  544. */
  545. Graph3d.prototype.setOptions = function (options) {
  546. if (options === undefined) return;
  547. let errorFound = Validator.validate(options, allOptions);
  548. if (errorFound === true) {
  549. console.log('%cErrors have been found in the supplied options object.', printStyle);
  550. }
  551. this.animationStop();
  552. Settings.setOptions(options, this);
  553. this.setPointDrawingMethod();
  554. this._setSize(this.width, this.height);
  555. this.setData(this.dataGroup.getDataTable());
  556. this.animationStart();
  557. };
  558. /**
  559. * Determine which point drawing method to use for the current graph style.
  560. */
  561. Graph3d.prototype.setPointDrawingMethod = function() {
  562. var method = undefined;
  563. switch (this.style) {
  564. case Graph3d.STYLE.BAR:
  565. method = Graph3d.prototype._redrawBarGraphPoint;
  566. break;
  567. case Graph3d.STYLE.BARCOLOR:
  568. method = Graph3d.prototype._redrawBarColorGraphPoint;
  569. break;
  570. case Graph3d.STYLE.BARSIZE:
  571. method = Graph3d.prototype._redrawBarSizeGraphPoint;
  572. break;
  573. case Graph3d.STYLE.DOT:
  574. method = Graph3d.prototype._redrawDotGraphPoint;
  575. break;
  576. case Graph3d.STYLE.DOTLINE:
  577. method = Graph3d.prototype._redrawDotLineGraphPoint;
  578. break;
  579. case Graph3d.STYLE.DOTCOLOR:
  580. method = Graph3d.prototype._redrawDotColorGraphPoint;
  581. break;
  582. case Graph3d.STYLE.DOTSIZE:
  583. method = Graph3d.prototype._redrawDotSizeGraphPoint;
  584. break;
  585. case Graph3d.STYLE.SURFACE:
  586. method = Graph3d.prototype._redrawSurfaceGraphPoint;
  587. break;
  588. case Graph3d.STYLE.GRID:
  589. method = Graph3d.prototype._redrawGridGraphPoint;
  590. break;
  591. case Graph3d.STYLE.LINE:
  592. method = Graph3d.prototype._redrawLineGraphPoint;
  593. break;
  594. default:
  595. throw new Error('Can not determine point drawing method '
  596. + 'for graph style \'' + this.style + '\'');
  597. }
  598. this._pointDrawingMethod = method;
  599. };
  600. /**
  601. * Redraw the Graph.
  602. */
  603. Graph3d.prototype.redraw = function() {
  604. if (this.dataPoints === undefined) {
  605. throw new Error('Graph data not initialized');
  606. }
  607. this._resizeCanvas();
  608. this._resizeCenter();
  609. this._redrawSlider();
  610. this._redrawClear();
  611. this._redrawAxis();
  612. this._redrawDataGraph();
  613. this._redrawInfo();
  614. this._redrawLegend();
  615. };
  616. /**
  617. * Get drawing context without exposing canvas
  618. *
  619. * @returns {CanvasRenderingContext2D}
  620. * @private
  621. */
  622. Graph3d.prototype._getContext = function() {
  623. var canvas = this.frame.canvas;
  624. var ctx = canvas.getContext('2d');
  625. ctx.lineJoin = 'round';
  626. ctx.lineCap = 'round';
  627. return ctx;
  628. };
  629. /**
  630. * Clear the canvas before redrawing
  631. */
  632. Graph3d.prototype._redrawClear = function() {
  633. var canvas = this.frame.canvas;
  634. var ctx = canvas.getContext('2d');
  635. ctx.clearRect(0, 0, canvas.width, canvas.height);
  636. };
  637. Graph3d.prototype._dotSize = function() {
  638. return this.frame.clientWidth * this.dotSizeRatio;
  639. };
  640. /**
  641. * Get legend width
  642. *
  643. * @returns {*}
  644. * @private
  645. */
  646. Graph3d.prototype._getLegendWidth = function() {
  647. var width;
  648. if (this.style === Graph3d.STYLE.DOTSIZE) {
  649. var dotSize = this._dotSize();
  650. //width = dotSize / 2 + dotSize * 2;
  651. width = dotSize * this.dotSizeMaxFraction;
  652. } else if (this.style === Graph3d.STYLE.BARSIZE) {
  653. width = this.xBarWidth ;
  654. } else {
  655. width = 20;
  656. }
  657. return width;
  658. };
  659. /**
  660. * Redraw the legend based on size, dot color, or surface height
  661. */
  662. Graph3d.prototype._redrawLegend = function() {
  663. //Return without drawing anything, if no legend is specified
  664. if (this.showLegend !== true) {
  665. return;
  666. }
  667. // Do not draw legend when graph style does not support
  668. if (this.style === Graph3d.STYLE.LINE
  669. || this.style === Graph3d.STYLE.BARSIZE //TODO add legend support for BARSIZE
  670. ){
  671. return;
  672. }
  673. // Legend types - size and color. Determine if size legend.
  674. var isSizeLegend = (this.style === Graph3d.STYLE.BARSIZE
  675. || this.style === Graph3d.STYLE.DOTSIZE) ;
  676. // Legend is either tracking z values or style values. This flag if false means use z values.
  677. var isValueLegend = (this.style === Graph3d.STYLE.DOTSIZE
  678. || this.style === Graph3d.STYLE.DOTCOLOR
  679. || this.style === Graph3d.STYLE.BARCOLOR);
  680. var height = Math.max(this.frame.clientHeight * 0.25, 100);
  681. var top = this.margin;
  682. var width = this._getLegendWidth() ; // px - overwritten by size legend
  683. var right = this.frame.clientWidth - this.margin;
  684. var left = right - width;
  685. var bottom = top + height;
  686. var ctx = this._getContext();
  687. ctx.lineWidth = 1;
  688. ctx.font = '14px arial'; // TODO: put in options
  689. if (isSizeLegend === false) {
  690. // draw the color bar
  691. var ymin = 0;
  692. var ymax = height; // Todo: make height customizable
  693. var y;
  694. for (y = ymin; y < ymax; y++) {
  695. var f = (y - ymin) / (ymax - ymin);
  696. var hue = f * 240;
  697. var color = this._hsv2rgb(hue, 1, 1);
  698. ctx.strokeStyle = color;
  699. ctx.beginPath();
  700. ctx.moveTo(left, top + y);
  701. ctx.lineTo(right, top + y);
  702. ctx.stroke();
  703. }
  704. ctx.strokeStyle = this.axisColor;
  705. ctx.strokeRect(left, top, width, height);
  706. } else {
  707. // draw the size legend box
  708. var widthMin;
  709. if (this.style === Graph3d.STYLE.DOTSIZE) {
  710. // Get the proportion to max and min right
  711. widthMin = width * (this.dotSizeMinFraction / this.dotSizeMaxFraction);
  712. } else if (this.style === Graph3d.STYLE.BARSIZE) {
  713. //widthMin = this.xBarWidth * 0.2 this is wrong - barwidth measures in terms of xvalues
  714. }
  715. ctx.strokeStyle = this.axisColor;
  716. ctx.fillStyle = this.dataColor.fill;
  717. ctx.beginPath();
  718. ctx.moveTo(left, top);
  719. ctx.lineTo(right, top);
  720. ctx.lineTo(left + widthMin, bottom);
  721. ctx.lineTo(left, bottom);
  722. ctx.closePath();
  723. ctx.fill();
  724. ctx.stroke();
  725. }
  726. // print value text along the legend edge
  727. var gridLineLen = 5; // px
  728. var legendMin = isValueLegend ? this.valueRange.min : this.zRange.min;
  729. var legendMax = isValueLegend ? this.valueRange.max : this.zRange.max;
  730. var step = new StepNumber(legendMin, legendMax, (legendMax-legendMin)/5, true);
  731. step.start(true);
  732. var from;
  733. var to;
  734. while (!step.end()) {
  735. y = bottom - (step.getCurrent() - legendMin) / (legendMax - legendMin) * height;
  736. from = new Point2d(left - gridLineLen, y);
  737. to = new Point2d(left, y);
  738. this._line(ctx, from, to);
  739. ctx.textAlign = 'right';
  740. ctx.textBaseline = 'middle';
  741. ctx.fillStyle = this.axisColor;
  742. ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
  743. step.next();
  744. }
  745. ctx.textAlign = 'right';
  746. ctx.textBaseline = 'top';
  747. var label = this.legendLabel;
  748. ctx.fillText(label, right, bottom + this.margin);
  749. };
  750. /**
  751. * Redraw the filter
  752. */
  753. Graph3d.prototype._redrawFilter = function() {
  754. var dataFilter = this.dataGroup.dataFilter;
  755. var filter = this.frame.filter;
  756. filter.innerHTML = '';
  757. if (!dataFilter) {
  758. filter.slider = undefined;
  759. return;
  760. }
  761. var options = {
  762. 'visible': this.showAnimationControls
  763. };
  764. var slider = new Slider(filter, options);
  765. filter.slider = slider;
  766. // TODO: css here is not nice here...
  767. filter.style.padding = '10px';
  768. //this.frame.filter.style.backgroundColor = '#EFEFEF';
  769. slider.setValues(dataFilter.values);
  770. slider.setPlayInterval(this.animationInterval);
  771. // create an event handler
  772. var me = this;
  773. var onchange = function () {
  774. var dataFilter = me.dataGroup.dataFilter;
  775. var index = slider.getIndex();
  776. dataFilter.selectValue(index);
  777. me.dataPoints = dataFilter._getDataPoints();
  778. me.redraw();
  779. };
  780. slider.setOnChangeCallback(onchange);
  781. };
  782. /**
  783. * Redraw the slider
  784. */
  785. Graph3d.prototype._redrawSlider = function() {
  786. if ( this.frame.filter.slider !== undefined) {
  787. this.frame.filter.slider.redraw();
  788. }
  789. };
  790. /**
  791. * Redraw common information
  792. */
  793. Graph3d.prototype._redrawInfo = function() {
  794. var info = this.dataGroup.getInfo();
  795. if (info === undefined) return;
  796. var ctx = this._getContext();
  797. ctx.font = '14px arial'; // TODO: put in options
  798. ctx.lineStyle = 'gray';
  799. ctx.fillStyle = 'gray';
  800. ctx.textAlign = 'left';
  801. ctx.textBaseline = 'top';
  802. var x = this.margin;
  803. var y = this.margin;
  804. ctx.fillText(info, x, y);
  805. };
  806. /**
  807. * Draw a line between 2d points 'from' and 'to'.
  808. *
  809. * If stroke style specified, set that as well.
  810. *
  811. * @param {CanvasRenderingContext2D} ctx
  812. * @param {vis.Point2d} from
  813. * @param {vis.Point2d} to
  814. * @param {string} [strokeStyle]
  815. * @private
  816. */
  817. Graph3d.prototype._line = function(ctx, from, to, strokeStyle) {
  818. if (strokeStyle !== undefined) {
  819. ctx.strokeStyle = strokeStyle;
  820. }
  821. ctx.beginPath();
  822. ctx.moveTo(from.x, from.y);
  823. ctx.lineTo(to.x , to.y );
  824. ctx.stroke();
  825. };
  826. /**
  827. *
  828. * @param {CanvasRenderingContext2D} ctx
  829. * @param {vis.Point3d} point3d
  830. * @param {string} text
  831. * @param {number} armAngle
  832. * @param {number} [yMargin=0]
  833. */
  834. Graph3d.prototype.drawAxisLabelX = function(ctx, point3d, text, armAngle, yMargin) {
  835. if (yMargin === undefined) {
  836. yMargin = 0;
  837. }
  838. var point2d = this._convert3Dto2D(point3d);
  839. if (Math.cos(armAngle * 2) > 0) {
  840. ctx.textAlign = 'center';
  841. ctx.textBaseline = 'top';
  842. point2d.y += yMargin;
  843. }
  844. else if (Math.sin(armAngle * 2) < 0){
  845. ctx.textAlign = 'right';
  846. ctx.textBaseline = 'middle';
  847. }
  848. else {
  849. ctx.textAlign = 'left';
  850. ctx.textBaseline = 'middle';
  851. }
  852. ctx.fillStyle = this.axisColor;
  853. ctx.fillText(text, point2d.x, point2d.y);
  854. };
  855. /**
  856. *
  857. * @param {CanvasRenderingContext2D} ctx
  858. * @param {vis.Point3d} point3d
  859. * @param {string} text
  860. * @param {number} armAngle
  861. * @param {number} [yMargin=0]
  862. */
  863. Graph3d.prototype.drawAxisLabelY = function(ctx, point3d, text, armAngle, yMargin) {
  864. if (yMargin === undefined) {
  865. yMargin = 0;
  866. }
  867. var point2d = this._convert3Dto2D(point3d);
  868. if (Math.cos(armAngle * 2) < 0) {
  869. ctx.textAlign = 'center';
  870. ctx.textBaseline = 'top';
  871. point2d.y += yMargin;
  872. }
  873. else if (Math.sin(armAngle * 2) > 0){
  874. ctx.textAlign = 'right';
  875. ctx.textBaseline = 'middle';
  876. }
  877. else {
  878. ctx.textAlign = 'left';
  879. ctx.textBaseline = 'middle';
  880. }
  881. ctx.fillStyle = this.axisColor;
  882. ctx.fillText(text, point2d.x, point2d.y);
  883. };
  884. /**
  885. *
  886. * @param {CanvasRenderingContext2D} ctx
  887. * @param {vis.Point3d} point3d
  888. * @param {string} text
  889. * @param {number} [offset=0]
  890. */
  891. Graph3d.prototype.drawAxisLabelZ = function(ctx, point3d, text, offset) {
  892. if (offset === undefined) {
  893. offset = 0;
  894. }
  895. var point2d = this._convert3Dto2D(point3d);
  896. ctx.textAlign = 'right';
  897. ctx.textBaseline = 'middle';
  898. ctx.fillStyle = this.axisColor;
  899. ctx.fillText(text, point2d.x - offset, point2d.y);
  900. };
  901. /**
  902. /**
  903. * Draw a line between 2d points 'from' and 'to'.
  904. *
  905. * If stroke style specified, set that as well.
  906. *
  907. * @param {CanvasRenderingContext2D} ctx
  908. * @param {vis.Point2d} from
  909. * @param {vis.Point2d} to
  910. * @param {string} [strokeStyle]
  911. * @private
  912. */
  913. Graph3d.prototype._line3d = function(ctx, from, to, strokeStyle) {
  914. var from2d = this._convert3Dto2D(from);
  915. var to2d = this._convert3Dto2D(to);
  916. this._line(ctx, from2d, to2d, strokeStyle);
  917. };
  918. /**
  919. * Redraw the axis
  920. */
  921. Graph3d.prototype._redrawAxis = function() {
  922. var ctx = this._getContext(),
  923. from, to, step, prettyStep,
  924. text, xText, yText, zText,
  925. offset, xOffset, yOffset;
  926. // TODO: get the actual rendered style of the containerElement
  927. //ctx.font = this.containerElement.style.font;
  928. ctx.font = 24 / this.camera.getArmLength() + 'px arial';
  929. // calculate the length for the short grid lines
  930. var gridLenX = 0.025 / this.scale.x;
  931. var gridLenY = 0.025 / this.scale.y;
  932. var textMargin = 5 / this.camera.getArmLength(); // px
  933. var armAngle = this.camera.getArmRotation().horizontal;
  934. var armVector = new Point2d(Math.cos(armAngle), Math.sin(armAngle));
  935. var xRange = this.xRange;
  936. var yRange = this.yRange;
  937. var zRange = this.zRange;
  938. var point3d;
  939. // draw x-grid lines
  940. ctx.lineWidth = 1;
  941. prettyStep = (this.defaultXStep === undefined);
  942. step = new StepNumber(xRange.min, xRange.max, this.xStep, prettyStep);
  943. step.start(true);
  944. while (!step.end()) {
  945. var x = step.getCurrent();
  946. if (this.showGrid) {
  947. from = new Point3d(x, yRange.min, zRange.min);
  948. to = new Point3d(x, yRange.max, zRange.min);
  949. this._line3d(ctx, from, to, this.gridColor);
  950. }
  951. else if (this.showXAxis) {
  952. from = new Point3d(x, yRange.min, zRange.min);
  953. to = new Point3d(x, yRange.min+gridLenX, zRange.min);
  954. this._line3d(ctx, from, to, this.axisColor);
  955. from = new Point3d(x, yRange.max, zRange.min);
  956. to = new Point3d(x, yRange.max-gridLenX, zRange.min);
  957. this._line3d(ctx, from, to, this.axisColor);
  958. }
  959. if (this.showXAxis) {
  960. yText = (armVector.x > 0) ? yRange.min : yRange.max;
  961. point3d = new Point3d(x, yText, zRange.min);
  962. let msg = ' ' + this.xValueLabel(x) + ' ';
  963. this.drawAxisLabelX(ctx, point3d, msg, armAngle, textMargin);
  964. }
  965. step.next();
  966. }
  967. // draw y-grid lines
  968. ctx.lineWidth = 1;
  969. prettyStep = (this.defaultYStep === undefined);
  970. step = new StepNumber(yRange.min, yRange.max, this.yStep, prettyStep);
  971. step.start(true);
  972. while (!step.end()) {
  973. var y = step.getCurrent();
  974. if (this.showGrid) {
  975. from = new Point3d(xRange.min, y, zRange.min);
  976. to = new Point3d(xRange.max, y, zRange.min);
  977. this._line3d(ctx, from, to, this.gridColor);
  978. }
  979. else if (this.showYAxis){
  980. from = new Point3d(xRange.min, y, zRange.min);
  981. to = new Point3d(xRange.min+gridLenY, y, zRange.min);
  982. this._line3d(ctx, from, to, this.axisColor);
  983. from = new Point3d(xRange.max, y, zRange.min);
  984. to = new Point3d(xRange.max-gridLenY, y, zRange.min);
  985. this._line3d(ctx, from, to, this.axisColor);
  986. }
  987. if (this.showYAxis) {
  988. xText = (armVector.y > 0) ? xRange.min : xRange.max;
  989. point3d = new Point3d(xText, y, zRange.min);
  990. let msg = ' ' + this.yValueLabel(y) + ' ';
  991. this.drawAxisLabelY(ctx, point3d, msg, armAngle, textMargin);
  992. }
  993. step.next();
  994. }
  995. // draw z-grid lines and axis
  996. if (this.showZAxis) {
  997. ctx.lineWidth = 1;
  998. prettyStep = (this.defaultZStep === undefined);
  999. step = new StepNumber(zRange.min, zRange.max, this.zStep, prettyStep);
  1000. step.start(true);
  1001. xText = (armVector.x > 0) ? xRange.min : xRange.max;
  1002. yText = (armVector.y < 0) ? yRange.min : yRange.max;
  1003. while (!step.end()) {
  1004. var z = step.getCurrent();
  1005. // TODO: make z-grid lines really 3d?
  1006. var from3d = new Point3d(xText, yText, z);
  1007. var from2d = this._convert3Dto2D(from3d);
  1008. to = new Point2d(from2d.x - textMargin, from2d.y);
  1009. this._line(ctx, from2d, to, this.axisColor);
  1010. let msg = this.zValueLabel(z) + ' ';
  1011. this.drawAxisLabelZ(ctx, from3d, msg, 5);
  1012. step.next();
  1013. }
  1014. ctx.lineWidth = 1;
  1015. from = new Point3d(xText, yText, zRange.min);
  1016. to = new Point3d(xText, yText, zRange.max);
  1017. this._line3d(ctx, from, to, this.axisColor);
  1018. }
  1019. // draw x-axis
  1020. if (this.showXAxis) {
  1021. var xMin2d;
  1022. var xMax2d;
  1023. ctx.lineWidth = 1;
  1024. // line at yMin
  1025. xMin2d = new Point3d(xRange.min, yRange.min, zRange.min);
  1026. xMax2d = new Point3d(xRange.max, yRange.min, zRange.min);
  1027. this._line3d(ctx, xMin2d, xMax2d, this.axisColor);
  1028. // line at ymax
  1029. xMin2d = new Point3d(xRange.min, yRange.max, zRange.min);
  1030. xMax2d = new Point3d(xRange.max, yRange.max, zRange.min);
  1031. this._line3d(ctx, xMin2d, xMax2d, this.axisColor);
  1032. }
  1033. // draw y-axis
  1034. if (this.showYAxis) {
  1035. ctx.lineWidth = 1;
  1036. // line at xMin
  1037. from = new Point3d(xRange.min, yRange.min, zRange.min);
  1038. to = new Point3d(xRange.min, yRange.max, zRange.min);
  1039. this._line3d(ctx, from, to, this.axisColor);
  1040. // line at xMax
  1041. from = new Point3d(xRange.max, yRange.min, zRange.min);
  1042. to = new Point3d(xRange.max, yRange.max, zRange.min);
  1043. this._line3d(ctx, from, to, this.axisColor);
  1044. }
  1045. // draw x-label
  1046. var xLabel = this.xLabel;
  1047. if (xLabel.length > 0 && this.showXAxis) {
  1048. yOffset = 0.1 / this.scale.y;
  1049. xText = (xRange.max + 3*xRange.min)/4;
  1050. yText = (armVector.x > 0) ? yRange.min - yOffset: yRange.max + yOffset;
  1051. text = new Point3d(xText, yText, zRange.min);
  1052. this.drawAxisLabelX(ctx, text, xLabel, armAngle);
  1053. }
  1054. // draw y-label
  1055. var yLabel = this.yLabel;
  1056. if (yLabel.length > 0 && this.showYAxis) {
  1057. xOffset = 0.1 / this.scale.x;
  1058. xText = (armVector.y > 0) ? xRange.min - xOffset : xRange.max + xOffset;
  1059. yText = (yRange.max + 3*yRange.min)/4;
  1060. text = new Point3d(xText, yText, zRange.min);
  1061. this.drawAxisLabelY(ctx, text, yLabel, armAngle);
  1062. }
  1063. // draw z-label
  1064. var zLabel = this.zLabel;
  1065. if (zLabel.length > 0 && this.showZAxis) {
  1066. offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
  1067. xText = (armVector.x > 0) ? xRange.min : xRange.max;
  1068. yText = (armVector.y < 0) ? yRange.min : yRange.max;
  1069. zText = (zRange.max + 3*zRange.min)/4;
  1070. text = new Point3d(xText, yText, zText);
  1071. this.drawAxisLabelZ(ctx, text, zLabel, offset);
  1072. }
  1073. };
  1074. /**
  1075. * Calculate the color based on the given value.
  1076. * @param {number} H Hue, a value be between 0 and 360
  1077. * @param {number} S Saturation, a value between 0 and 1
  1078. * @param {number} V Value, a value between 0 and 1
  1079. * @returns {string}
  1080. * @private
  1081. */
  1082. Graph3d.prototype._hsv2rgb = function(H, S, V) {
  1083. var R, G, B, C, Hi, X;
  1084. C = V * S;
  1085. Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5
  1086. X = C * (1 - Math.abs(((H/60) % 2) - 1));
  1087. switch (Hi) {
  1088. case 0: R = C; G = X; B = 0; break;
  1089. case 1: R = X; G = C; B = 0; break;
  1090. case 2: R = 0; G = C; B = X; break;
  1091. case 3: R = 0; G = X; B = C; break;
  1092. case 4: R = X; G = 0; B = C; break;
  1093. case 5: R = C; G = 0; B = X; break;
  1094. default: R = 0; G = 0; B = 0; break;
  1095. }
  1096. return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')';
  1097. };
  1098. /**
  1099. *
  1100. * @param {vis.Point3d} point
  1101. * @returns {*}
  1102. * @private
  1103. */
  1104. Graph3d.prototype._getStrokeWidth = function(point) {
  1105. if (point !== undefined) {
  1106. if (this.showPerspective) {
  1107. return 1 / -point.trans.z * this.dataColor.strokeWidth;
  1108. }
  1109. else {
  1110. return -(this.eye.z / this.camera.getArmLength()) * this.dataColor.strokeWidth;
  1111. }
  1112. }
  1113. return this.dataColor.strokeWidth;
  1114. };
  1115. // -----------------------------------------------------------------------------
  1116. // Drawing primitives for the graphs
  1117. // -----------------------------------------------------------------------------
  1118. /**
  1119. * Draw a bar element in the view with the given properties.
  1120. *
  1121. * @param {CanvasRenderingContext2D} ctx
  1122. * @param {Object} point
  1123. * @param {number} xWidth
  1124. * @param {number} yWidth
  1125. * @param {string} color
  1126. * @param {string} borderColor
  1127. * @private
  1128. */
  1129. Graph3d.prototype._redrawBar = function(ctx, point, xWidth, yWidth, color, borderColor) {
  1130. var surface;
  1131. // calculate all corner points
  1132. var me = this;
  1133. var point3d = point.point;
  1134. var zMin = this.zRange.min;
  1135. var top = [
  1136. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)},
  1137. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)},
  1138. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)},
  1139. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)}
  1140. ];
  1141. var bottom = [
  1142. {point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, zMin)},
  1143. {point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, zMin)},
  1144. {point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, zMin)},
  1145. {point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, zMin)}
  1146. ];
  1147. // calculate screen location of the points
  1148. top.forEach(function (obj) {
  1149. obj.screen = me._convert3Dto2D(obj.point);
  1150. });
  1151. bottom.forEach(function (obj) {
  1152. obj.screen = me._convert3Dto2D(obj.point);
  1153. });
  1154. // create five sides, calculate both corner points and center points
  1155. var surfaces = [
  1156. {corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)},
  1157. {corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)},
  1158. {corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)},
  1159. {corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)},
  1160. {corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)}
  1161. ];
  1162. point.surfaces = surfaces;
  1163. // calculate the distance of each of the surface centers to the camera
  1164. for (let j = 0; j < surfaces.length; j++) {
  1165. surface = surfaces[j];
  1166. var transCenter = this._convertPointToTranslation(surface.center);
  1167. surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
  1168. // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
  1169. // but the current solution is fast/simple and works in 99.9% of all cases
  1170. // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
  1171. }
  1172. // order the surfaces by their (translated) depth
  1173. surfaces.sort(function (a, b) {
  1174. var diff = b.dist - a.dist;
  1175. if (diff) return diff;
  1176. // if equal depth, sort the top surface last
  1177. if (a.corners === top) return 1;
  1178. if (b.corners === top) return -1;
  1179. // both are equal
  1180. return 0;
  1181. });
  1182. // draw the ordered surfaces
  1183. ctx.lineWidth = this._getStrokeWidth(point);
  1184. ctx.strokeStyle = borderColor;
  1185. ctx.fillStyle = color;
  1186. // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
  1187. for (let j = 2; j < surfaces.length; j++) {
  1188. surface = surfaces[j];
  1189. this._polygon(ctx, surface.corners);
  1190. }
  1191. };
  1192. /**
  1193. * Draw a polygon using the passed points and fill it with the passed style and stroke.
  1194. *
  1195. * @param {CanvasRenderingContext2D} ctx
  1196. * @param {Array.<vis.Point3d>} points an array of points.
  1197. * @param {string} [fillStyle] the fill style to set
  1198. * @param {string} [strokeStyle] the stroke style to set
  1199. */
  1200. Graph3d.prototype._polygon = function(ctx, points, fillStyle, strokeStyle) {
  1201. if (points.length < 2) {
  1202. return;
  1203. }
  1204. if (fillStyle !== undefined) {
  1205. ctx.fillStyle = fillStyle;
  1206. }
  1207. if (strokeStyle !== undefined) {
  1208. ctx.strokeStyle = strokeStyle;
  1209. }
  1210. ctx.beginPath();
  1211. ctx.moveTo(points[0].screen.x, points[0].screen.y);
  1212. for (var i = 1; i < points.length; ++i) {
  1213. var point = points[i];
  1214. ctx.lineTo(point.screen.x, point.screen.y);
  1215. }
  1216. ctx.closePath();
  1217. ctx.fill();
  1218. ctx.stroke(); // TODO: only draw stroke when strokeWidth > 0
  1219. };
  1220. /**
  1221. * @param {CanvasRenderingContext2D} ctx
  1222. * @param {object} point
  1223. * @param {string} color
  1224. * @param {string} borderColor
  1225. * @param {number} [size=this._dotSize()]
  1226. * @private
  1227. */
  1228. Graph3d.prototype._drawCircle = function(ctx, point, color, borderColor, size) {
  1229. var radius = this._calcRadius(point, size);
  1230. ctx.lineWidth = this._getStrokeWidth(point);
  1231. ctx.strokeStyle = borderColor;
  1232. ctx.fillStyle = color;
  1233. ctx.beginPath();
  1234. ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true);
  1235. ctx.fill();
  1236. ctx.stroke();
  1237. };
  1238. /**
  1239. * Determine the colors for the 'regular' graph styles.
  1240. *
  1241. * @param {object} point
  1242. * @returns {{fill, border}}
  1243. * @private
  1244. */
  1245. Graph3d.prototype._getColorsRegular = function(point) {
  1246. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1247. var hue = (1 - (point.point.z - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
  1248. var color = this._hsv2rgb(hue, 1, 1);
  1249. var borderColor = this._hsv2rgb(hue, 1, 0.8);
  1250. return {
  1251. fill : color,
  1252. border: borderColor
  1253. };
  1254. };
  1255. /**
  1256. * Get the colors for the 'color' graph styles.
  1257. * These styles are currently: 'bar-color' and 'dot-color'
  1258. * Color may be set as a string representation of HTML color, like #ff00ff,
  1259. * or calculated from a number, for example, distance from this point
  1260. * The first option is useful when we have some pre-given legend, to which we have to adjust ourselves
  1261. * The second option is useful when we are interested in automatically setting the color, from some value,
  1262. * using some color scale
  1263. * @param {object} point
  1264. * @returns {{fill: *, border: *}}
  1265. * @private
  1266. */
  1267. Graph3d.prototype._getColorsColor = function(point) {
  1268. // calculate the color based on the value
  1269. var color, borderColor;
  1270. if (typeof point.point.value === "string") {
  1271. color = point.point.value;
  1272. borderColor = point.point.value;
  1273. }
  1274. else {
  1275. var hue = (1 - (point.point.value - this.valueRange.min) * this.scale.value) * 240;
  1276. color = this._hsv2rgb(hue, 1, 1);
  1277. borderColor = this._hsv2rgb(hue, 1, 0.8);
  1278. }
  1279. return {
  1280. fill : color,
  1281. border : borderColor
  1282. };
  1283. };
  1284. /**
  1285. * Get the colors for the 'size' graph styles.
  1286. * These styles are currently: 'bar-size' and 'dot-size'
  1287. *
  1288. * @returns {{fill: *, border: (string|colorOptions.stroke|{string, undefined}|string|colorOptions.stroke|{string}|*)}}
  1289. * @private
  1290. */
  1291. Graph3d.prototype._getColorsSize = function() {
  1292. return {
  1293. fill : this.dataColor.fill,
  1294. border : this.dataColor.stroke
  1295. };
  1296. };
  1297. /**
  1298. * Determine the size of a point on-screen, as determined by the
  1299. * distance to the camera.
  1300. *
  1301. * @param {Object} point
  1302. * @param {number} [size=this._dotSize()] the size that needs to be translated to screen coordinates.
  1303. * optional; if not passed, use the default point size.
  1304. * @returns {number}
  1305. * @private
  1306. */
  1307. Graph3d.prototype._calcRadius = function(point, size) {
  1308. if (size === undefined) {
  1309. size = this._dotSize();
  1310. }
  1311. var radius;
  1312. if (this.showPerspective) {
  1313. radius = size / -point.trans.z;
  1314. }
  1315. else {
  1316. radius = size * -(this.eye.z / this.camera.getArmLength());
  1317. }
  1318. if (radius < 0) {
  1319. radius = 0;
  1320. }
  1321. return radius;
  1322. };
  1323. // -----------------------------------------------------------------------------
  1324. // Methods for drawing points per graph style.
  1325. // -----------------------------------------------------------------------------
  1326. /**
  1327. * Draw single datapoint for graph style 'bar'.
  1328. *
  1329. * @param {CanvasRenderingContext2D} ctx
  1330. * @param {Object} point
  1331. * @private
  1332. */
  1333. Graph3d.prototype._redrawBarGraphPoint = function(ctx, point) {
  1334. var xWidth = this.xBarWidth / 2;
  1335. var yWidth = this.yBarWidth / 2;
  1336. var colors = this._getColorsRegular(point);
  1337. this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
  1338. };
  1339. /**
  1340. * Draw single datapoint for graph style 'bar-color'.
  1341. *
  1342. * @param {CanvasRenderingContext2D} ctx
  1343. * @param {Object} point
  1344. * @private
  1345. */
  1346. Graph3d.prototype._redrawBarColorGraphPoint = function(ctx, point) {
  1347. var xWidth = this.xBarWidth / 2;
  1348. var yWidth = this.yBarWidth / 2;
  1349. var colors = this._getColorsColor(point);
  1350. this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
  1351. };
  1352. /**
  1353. * Draw single datapoint for graph style 'bar-size'.
  1354. *
  1355. * @param {CanvasRenderingContext2D} ctx
  1356. * @param {Object} point
  1357. * @private
  1358. */
  1359. Graph3d.prototype._redrawBarSizeGraphPoint = function(ctx, point) {
  1360. // calculate size for the bar
  1361. var fraction = (point.point.value - this.valueRange.min) / this.valueRange.range();
  1362. var xWidth = (this.xBarWidth / 2) * (fraction * 0.8 + 0.2);
  1363. var yWidth = (this.yBarWidth / 2) * (fraction * 0.8 + 0.2);
  1364. var colors = this._getColorsSize();
  1365. this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
  1366. };
  1367. /**
  1368. * Draw single datapoint for graph style 'dot'.
  1369. *
  1370. * @param {CanvasRenderingContext2D} ctx
  1371. * @param {Object} point
  1372. * @private
  1373. */
  1374. Graph3d.prototype._redrawDotGraphPoint = function(ctx, point) {
  1375. var colors = this._getColorsRegular(point);
  1376. this._drawCircle(ctx, point, colors.fill, colors.border);
  1377. };
  1378. /**
  1379. * Draw single datapoint for graph style 'dot-line'.
  1380. *
  1381. * @param {CanvasRenderingContext2D} ctx
  1382. * @param {Object} point
  1383. * @private
  1384. */
  1385. Graph3d.prototype._redrawDotLineGraphPoint = function(ctx, point) {
  1386. // draw a vertical line from the XY-plane to the graph value
  1387. var from = this._convert3Dto2D(point.bottom);
  1388. ctx.lineWidth = 1;
  1389. this._line(ctx, from, point.screen, this.gridColor);
  1390. this._redrawDotGraphPoint(ctx, point);
  1391. };
  1392. /**
  1393. * Draw single datapoint for graph style 'dot-color'.
  1394. *
  1395. * @param {CanvasRenderingContext2D} ctx
  1396. * @param {Object} point
  1397. * @private
  1398. */
  1399. Graph3d.prototype._redrawDotColorGraphPoint = function(ctx, point) {
  1400. var colors = this._getColorsColor(point);
  1401. this._drawCircle(ctx, point, colors.fill, colors.border);
  1402. };
  1403. /**
  1404. * Draw single datapoint for graph style 'dot-size'.
  1405. *
  1406. * @param {CanvasRenderingContext2D} ctx
  1407. * @param {Object} point
  1408. * @private
  1409. */
  1410. Graph3d.prototype._redrawDotSizeGraphPoint = function(ctx, point) {
  1411. var dotSize = this._dotSize();
  1412. var fraction = (point.point.value - this.valueRange.min) / this.valueRange.range();
  1413. var sizeMin = dotSize*this.dotSizeMinFraction;
  1414. var sizeRange = dotSize*this.dotSizeMaxFraction - sizeMin;
  1415. var size = sizeMin + sizeRange*fraction;
  1416. var colors = this._getColorsSize();
  1417. this._drawCircle(ctx, point, colors.fill, colors.border, size);
  1418. };
  1419. /**
  1420. * Draw single datapoint for graph style 'surface'.
  1421. *
  1422. * @param {CanvasRenderingContext2D} ctx
  1423. * @param {Object} point
  1424. * @private
  1425. */
  1426. Graph3d.prototype._redrawSurfaceGraphPoint = function(ctx, point) {
  1427. var right = point.pointRight;
  1428. var top = point.pointTop;
  1429. var cross = point.pointCross;
  1430. if (point === undefined || right === undefined || top === undefined || cross === undefined) {
  1431. return;
  1432. }
  1433. var topSideVisible = true;
  1434. var fillStyle;
  1435. var strokeStyle;
  1436. if (this.showGrayBottom || this.showShadow) {
  1437. // calculate the cross product of the two vectors from center
  1438. // to left and right, in order to know whether we are looking at the
  1439. // bottom or at the top side. We can also use the cross product
  1440. // for calculating light intensity
  1441. var aDiff = Point3d.subtract(cross.trans, point.trans);
  1442. var bDiff = Point3d.subtract(top.trans, right.trans);
  1443. var crossproduct = Point3d.crossProduct(aDiff, bDiff);
  1444. var len = crossproduct.length();
  1445. // FIXME: there is a bug with determining the surface side (shadow or colored)
  1446. topSideVisible = (crossproduct.z > 0);
  1447. }
  1448. if (topSideVisible) {
  1449. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1450. var zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
  1451. var h = (1 - (zAvg - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
  1452. var s = 1; // saturation
  1453. var v;
  1454. if (this.showShadow) {
  1455. v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale
  1456. fillStyle = this._hsv2rgb(h, s, v);
  1457. strokeStyle = fillStyle;
  1458. }
  1459. else {
  1460. v = 1;
  1461. fillStyle = this._hsv2rgb(h, s, v);
  1462. strokeStyle = this.axisColor; // TODO: should be customizable
  1463. }
  1464. }
  1465. else {
  1466. fillStyle = 'gray';
  1467. strokeStyle = this.axisColor;
  1468. }
  1469. ctx.lineWidth = this._getStrokeWidth(point);
  1470. // TODO: only draw stroke when strokeWidth > 0
  1471. var points = [point, right, cross, top];
  1472. this._polygon(ctx, points, fillStyle, strokeStyle);
  1473. };
  1474. /**
  1475. * Helper method for _redrawGridGraphPoint()
  1476. *
  1477. * @param {CanvasRenderingContext2D} ctx
  1478. * @param {Object} from
  1479. * @param {Object} to
  1480. * @private
  1481. */
  1482. Graph3d.prototype._drawGridLine = function(ctx, from, to) {
  1483. if (from === undefined || to === undefined) {
  1484. return;
  1485. }
  1486. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  1487. var zAvg = (from.point.z + to.point.z) / 2;
  1488. var h = (1 - (zAvg - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
  1489. ctx.lineWidth = this._getStrokeWidth(from) * 2;
  1490. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  1491. this._line(ctx, from.screen, to.screen);
  1492. };
  1493. /**
  1494. * Draw single datapoint for graph style 'Grid'.
  1495. *
  1496. * @param {CanvasRenderingContext2D} ctx
  1497. * @param {Object} point
  1498. * @private
  1499. */
  1500. Graph3d.prototype._redrawGridGraphPoint = function(ctx, point) {
  1501. this._drawGridLine(ctx, point, point.pointRight);
  1502. this._drawGridLine(ctx, point, point.pointTop);
  1503. };
  1504. /**
  1505. * Draw single datapoint for graph style 'line'.
  1506. *
  1507. * @param {CanvasRenderingContext2D} ctx
  1508. * @param {Object} point
  1509. * @private
  1510. */
  1511. Graph3d.prototype._redrawLineGraphPoint = function(ctx, point) {
  1512. if (point.pointNext === undefined) {
  1513. return;
  1514. }
  1515. ctx.lineWidth = this._getStrokeWidth(point);
  1516. ctx.strokeStyle = this.dataColor.stroke;
  1517. this._line(ctx, point.screen, point.pointNext.screen);
  1518. };
  1519. /**
  1520. * Draw all datapoints for currently selected graph style.
  1521. *
  1522. */
  1523. Graph3d.prototype._redrawDataGraph = function() {
  1524. var ctx = this._getContext();
  1525. var i;
  1526. if (this.dataPoints === undefined || this.dataPoints.length <= 0)
  1527. return; // TODO: throw exception?
  1528. this._calcTranslations(this.dataPoints);
  1529. for (i = 0; i < this.dataPoints.length; i++) {
  1530. var point = this.dataPoints[i];
  1531. // Using call() ensures that the correct context is used
  1532. this._pointDrawingMethod.call(this, ctx, point);
  1533. }
  1534. };
  1535. // -----------------------------------------------------------------------------
  1536. // End methods for drawing points per graph style.
  1537. // -----------------------------------------------------------------------------
  1538. /**
  1539. * Store startX, startY and startOffset for mouse operations
  1540. *
  1541. * @param {Event} event The event that occurred
  1542. */
  1543. Graph3d.prototype._storeMousePosition = function(event) {
  1544. // get mouse position (different code for IE and all other browsers)
  1545. this.startMouseX = getMouseX(event);
  1546. this.startMouseY = getMouseY(event);
  1547. this._startCameraOffset = this.camera.getOffset();
  1548. };
  1549. /**
  1550. * Start a moving operation inside the provided parent element
  1551. * @param {Event} event The event that occurred (required for
  1552. * retrieving the mouse position)
  1553. */
  1554. Graph3d.prototype._onMouseDown = function(event) {
  1555. event = event || window.event;
  1556. // check if mouse is still down (may be up when focus is lost for example
  1557. // in an iframe)
  1558. if (this.leftButtonDown) {
  1559. this._onMouseUp(event);
  1560. }
  1561. // only react on left mouse button down
  1562. this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
  1563. if (!this.leftButtonDown && !this.touchDown) return;
  1564. this._storeMousePosition(event);
  1565. this.startStart = new Date(this.start);
  1566. this.startEnd = new Date(this.end);
  1567. this.startArmRotation = this.camera.getArmRotation();
  1568. this.frame.style.cursor = 'move';
  1569. // add event listeners to handle moving the contents
  1570. // we store the function onmousemove and onmouseup in the graph, so we can
  1571. // remove the eventlisteners lateron in the function mouseUp()
  1572. var me = this;
  1573. this.onmousemove = function (event) {me._onMouseMove(event);};
  1574. this.onmouseup = function (event) {me._onMouseUp(event);};
  1575. util.addEventListener(document, 'mousemove', me.onmousemove);
  1576. util.addEventListener(document, 'mouseup', me.onmouseup);
  1577. util.preventDefault(event);
  1578. };
  1579. /**
  1580. * Perform moving operating.
  1581. * This function activated from within the funcion Graph.mouseDown().
  1582. * @param {Event} event Well, eehh, the event
  1583. */
  1584. Graph3d.prototype._onMouseMove = function (event) {
  1585. this.moving = true;
  1586. event = event || window.event;
  1587. // calculate change in mouse position
  1588. var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
  1589. var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
  1590. // move with ctrl or rotate by other
  1591. if (event && event.ctrlKey === true) {
  1592. // calculate change in mouse position
  1593. var scaleX = this.frame.clientWidth * 0.5;
  1594. var scaleY = this.frame.clientHeight * 0.5;
  1595. var offXNew = (this._startCameraOffset.x || 0) - ((diffX / scaleX) * this.camera.armLength) * 0.8;
  1596. var offYNew = (this._startCameraOffset.y || 0) + ((diffY / scaleY) * this.camera.armLength) * 0.8;
  1597. this.camera.setOffset(offXNew, offYNew);
  1598. this._storeMousePosition(event);
  1599. } else {
  1600. var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
  1601. var verticalNew = this.startArmRotation.vertical + diffY / 200;
  1602. var snapAngle = 4; // degrees
  1603. var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
  1604. // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
  1605. // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
  1606. if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
  1607. horizontalNew = Math.round(horizontalNew / Math.PI) * Math.PI - 0.001;
  1608. }
  1609. if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
  1610. horizontalNew = (Math.round(horizontalNew / Math.PI - 0.5) + 0.5) * Math.PI - 0.001;
  1611. }
  1612. // snap vertically to nice angles
  1613. if (Math.abs(Math.sin(verticalNew)) < snapValue) {
  1614. verticalNew = Math.round(verticalNew / Math.PI) * Math.PI;
  1615. }
  1616. if (Math.abs(Math.cos(verticalNew)) < snapValue) {
  1617. verticalNew = (Math.round(verticalNew / Math.PI - 0.5) + 0.5) * Math.PI;
  1618. }
  1619. this.camera.setArmRotation(horizontalNew, verticalNew);
  1620. }
  1621. this.redraw();
  1622. // fire a cameraPositionChange event
  1623. var parameters = this.getCameraPosition();
  1624. this.emit('cameraPositionChange', parameters);
  1625. util.preventDefault(event);
  1626. };
  1627. /**
  1628. * Stop moving operating.
  1629. * This function activated from within the funcion Graph.mouseDown().
  1630. * @param {Event} event The event
  1631. */
  1632. Graph3d.prototype._onMouseUp = function (event) {
  1633. this.frame.style.cursor = 'auto';
  1634. this.leftButtonDown = false;
  1635. // remove event listeners here
  1636. util.removeEventListener(document, 'mousemove', this.onmousemove);
  1637. util.removeEventListener(document, 'mouseup', this.onmouseup);
  1638. util.preventDefault(event);
  1639. };
  1640. /**
  1641. * @param {Event} event The event
  1642. */
  1643. Graph3d.prototype._onClick = function (event) {
  1644. if (!this.onclick_callback)
  1645. return;
  1646. if (!this.moving) {
  1647. var boundingRect = this.frame.getBoundingClientRect();
  1648. var mouseX = getMouseX(event) - boundingRect.left;
  1649. var mouseY = getMouseY(event) - boundingRect.top;
  1650. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  1651. if (dataPoint)
  1652. this.onclick_callback(dataPoint.point.data);
  1653. }
  1654. else { // disable onclick callback, if it came immediately after rotate/pan
  1655. this.moving = false;
  1656. }
  1657. util.preventDefault(event);
  1658. };
  1659. /**
  1660. * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
  1661. * @param {Event} event A mouse move event
  1662. */
  1663. Graph3d.prototype._onTooltip = function (event) {
  1664. var delay = 300; // ms
  1665. var boundingRect = this.frame.getBoundingClientRect();
  1666. var mouseX = getMouseX(event) - boundingRect.left;
  1667. var mouseY = getMouseY(event) - boundingRect.top;
  1668. if (!this.showTooltip) {
  1669. return;
  1670. }
  1671. if (this.tooltipTimeout) {
  1672. clearTimeout(this.tooltipTimeout);
  1673. }
  1674. // (delayed) display of a tooltip only if no mouse button is down
  1675. if (this.leftButtonDown) {
  1676. this._hideTooltip();
  1677. return;
  1678. }
  1679. if (this.tooltip && this.tooltip.dataPoint) {
  1680. // tooltip is currently visible
  1681. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  1682. if (dataPoint !== this.tooltip.dataPoint) {
  1683. // datapoint changed
  1684. if (dataPoint) {
  1685. this._showTooltip(dataPoint);
  1686. }
  1687. else {
  1688. this._hideTooltip();
  1689. }
  1690. }
  1691. }
  1692. else {
  1693. // tooltip is currently not visible
  1694. var me = this;
  1695. this.tooltipTimeout = setTimeout(function () {
  1696. me.tooltipTimeout = null;
  1697. // show a tooltip if we have a data point
  1698. var dataPoint = me._dataPointFromXY(mouseX, mouseY);
  1699. if (dataPoint) {
  1700. me._showTooltip(dataPoint);
  1701. }
  1702. }, delay);
  1703. }
  1704. };
  1705. /**
  1706. * Event handler for touchstart event on mobile devices
  1707. * @param {Event} event The event
  1708. */
  1709. Graph3d.prototype._onTouchStart = function(event) {
  1710. this.touchDown = true;
  1711. var me = this;
  1712. this.ontouchmove = function (event) {me._onTouchMove(event);};
  1713. this.ontouchend = function (event) {me._onTouchEnd(event);};
  1714. util.addEventListener(document, 'touchmove', me.ontouchmove);
  1715. util.addEventListener(document, 'touchend', me.ontouchend);
  1716. this._onMouseDown(event);
  1717. };
  1718. /**
  1719. * Event handler for touchmove event on mobile devices
  1720. * @param {Event} event The event
  1721. */
  1722. Graph3d.prototype._onTouchMove = function(event) {
  1723. this._onMouseMove(event);
  1724. };
  1725. /**
  1726. * Event handler for touchend event on mobile devices
  1727. * @param {Event} event The event
  1728. */
  1729. Graph3d.prototype._onTouchEnd = function(event) {
  1730. this.touchDown = false;
  1731. util.removeEventListener(document, 'touchmove', this.ontouchmove);
  1732. util.removeEventListener(document, 'touchend', this.ontouchend);
  1733. this._onMouseUp(event);
  1734. };
  1735. /**
  1736. * Event handler for mouse wheel event, used to zoom the graph
  1737. * Code from http://adomas.org/javascript-mouse-wheel/
  1738. * @param {Event} event The event
  1739. */
  1740. Graph3d.prototype._onWheel = function(event) {
  1741. if (!event) /* For IE. */
  1742. event = window.event;
  1743. // retrieve delta
  1744. var delta = 0;
  1745. if (event.wheelDelta) { /* IE/Opera. */
  1746. delta = event.wheelDelta/120;
  1747. } else if (event.detail) { /* Mozilla case. */
  1748. // In Mozilla, sign of delta is different than in IE.
  1749. // Also, delta is multiple of 3.
  1750. delta = -event.detail/3;
  1751. }
  1752. // If delta is nonzero, handle it.
  1753. // Basically, delta is now positive if wheel was scrolled up,
  1754. // and negative, if wheel was scrolled down.
  1755. if (delta) {
  1756. var oldLength = this.camera.getArmLength();
  1757. var newLength = oldLength * (1 - delta / 10);
  1758. this.camera.setArmLength(newLength);
  1759. this.redraw();
  1760. this._hideTooltip();
  1761. }
  1762. // fire a cameraPositionChange event
  1763. var parameters = this.getCameraPosition();
  1764. this.emit('cameraPositionChange', parameters);
  1765. // Prevent default actions caused by mouse wheel.
  1766. // That might be ugly, but we handle scrolls somehow
  1767. // anyway, so don't bother here..
  1768. util.preventDefault(event);
  1769. };
  1770. /**
  1771. * Test whether a point lies inside given 2D triangle
  1772. *
  1773. * @param {vis.Point2d} point
  1774. * @param {vis.Point2d[]} triangle
  1775. * @returns {boolean} true if given point lies inside or on the edge of the
  1776. * triangle, false otherwise
  1777. * @private
  1778. */
  1779. Graph3d.prototype._insideTriangle = function (point, triangle) {
  1780. var a = triangle[0],
  1781. b = triangle[1],
  1782. c = triangle[2];
  1783. /**
  1784. *
  1785. * @param {number} x
  1786. * @returns {number}
  1787. */
  1788. function sign (x) {
  1789. return x > 0 ? 1 : x < 0 ? -1 : 0;
  1790. }
  1791. var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
  1792. var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
  1793. var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
  1794. // each of the three signs must be either equal to each other or zero
  1795. return (as == 0 || bs == 0 || as == bs) &&
  1796. (bs == 0 || cs == 0 || bs == cs) &&
  1797. (as == 0 || cs == 0 || as == cs);
  1798. };
  1799. /**
  1800. * Find a data point close to given screen position (x, y)
  1801. *
  1802. * @param {number} x
  1803. * @param {number} y
  1804. * @returns {Object | null} The closest data point or null if not close to any
  1805. * data point
  1806. * @private
  1807. */
  1808. Graph3d.prototype._dataPointFromXY = function (x, y) {
  1809. var i,
  1810. distMax = 100, // px
  1811. dataPoint = null,
  1812. closestDataPoint = null,
  1813. closestDist = null,
  1814. center = new Point2d(x, y);
  1815. if (this.style === Graph3d.STYLE.BAR ||
  1816. this.style === Graph3d.STYLE.BARCOLOR ||
  1817. this.style === Graph3d.STYLE.BARSIZE) {
  1818. // the data points are ordered from far away to closest
  1819. for (i = this.dataPoints.length - 1; i >= 0; i--) {
  1820. dataPoint = this.dataPoints[i];
  1821. var surfaces = dataPoint.surfaces;
  1822. if (surfaces) {
  1823. for (var s = surfaces.length - 1; s >= 0; s--) {
  1824. // split each surface in two triangles, and see if the center point is inside one of these
  1825. var surface = surfaces[s];
  1826. var corners = surface.corners;
  1827. var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
  1828. var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
  1829. if (this._insideTriangle(center, triangle1) ||
  1830. this._insideTriangle(center, triangle2)) {
  1831. // return immediately at the first hit
  1832. return dataPoint;
  1833. }
  1834. }
  1835. }
  1836. }
  1837. }
  1838. else {
  1839. // find the closest data point, using distance to the center of the point on 2d screen
  1840. for (i = 0; i < this.dataPoints.length; i++) {
  1841. dataPoint = this.dataPoints[i];
  1842. var point = dataPoint.screen;
  1843. if (point) {
  1844. var distX = Math.abs(x - point.x);
  1845. var distY = Math.abs(y - point.y);
  1846. var dist = Math.sqrt(distX * distX + distY * distY);
  1847. if ((closestDist === null || dist < closestDist) && dist < distMax) {
  1848. closestDist = dist;
  1849. closestDataPoint = dataPoint;
  1850. }
  1851. }
  1852. }
  1853. }
  1854. return closestDataPoint;
  1855. };
  1856. /**
  1857. * Determine if the given style has bars
  1858. *
  1859. * @param {number} style the style to check
  1860. * @returns {boolean} true if bar style, false otherwise
  1861. */
  1862. Graph3d.prototype.hasBars = function(style) {
  1863. return style == Graph3d.STYLE.BAR ||
  1864. style == Graph3d.STYLE.BARCOLOR ||
  1865. style == Graph3d.STYLE.BARSIZE;
  1866. };
  1867. /**
  1868. * Display a tooltip for given data point
  1869. * @param {Object} dataPoint
  1870. * @private
  1871. */
  1872. Graph3d.prototype._showTooltip = function (dataPoint) {
  1873. var content, line, dot;
  1874. if (!this.tooltip) {
  1875. content = document.createElement('div');
  1876. Object.assign(content.style, {}, this.tooltipStyle.content);
  1877. content.style.position = 'absolute';
  1878. line = document.createElement('div');
  1879. Object.assign(line.style, {}, this.tooltipStyle.line);
  1880. line.style.position = 'absolute';
  1881. dot = document.createElement('div');
  1882. Object.assign(dot.style, {}, this.tooltipStyle.dot);
  1883. dot.style.position = 'absolute';
  1884. this.tooltip = {
  1885. dataPoint: null,
  1886. dom: {
  1887. content: content,
  1888. line: line,
  1889. dot: dot
  1890. }
  1891. };
  1892. }
  1893. else {
  1894. content = this.tooltip.dom.content;
  1895. line = this.tooltip.dom.line;
  1896. dot = this.tooltip.dom.dot;
  1897. }
  1898. this._hideTooltip();
  1899. this.tooltip.dataPoint = dataPoint;
  1900. if (typeof this.showTooltip === 'function') {
  1901. content.innerHTML = this.showTooltip(dataPoint.point);
  1902. }
  1903. else {
  1904. content.innerHTML = '<table>' +
  1905. '<tr><td>' + this.xLabel + ':</td><td>' + dataPoint.point.x + '</td></tr>' +
  1906. '<tr><td>' + this.yLabel + ':</td><td>' + dataPoint.point.y + '</td></tr>' +
  1907. '<tr><td>' + this.zLabel + ':</td><td>' + dataPoint.point.z + '</td></tr>' +
  1908. '</table>';
  1909. }
  1910. content.style.left = '0';
  1911. content.style.top = '0';
  1912. this.frame.appendChild(content);
  1913. this.frame.appendChild(line);
  1914. this.frame.appendChild(dot);
  1915. // calculate sizes
  1916. var contentWidth = content.offsetWidth;
  1917. var contentHeight = content.offsetHeight;
  1918. var lineHeight = line.offsetHeight;
  1919. var dotWidth = dot.offsetWidth;
  1920. var dotHeight = dot.offsetHeight;
  1921. var left = dataPoint.screen.x - contentWidth / 2;
  1922. left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
  1923. line.style.left = dataPoint.screen.x + 'px';
  1924. line.style.top = (dataPoint.screen.y - lineHeight) + 'px';
  1925. content.style.left = left + 'px';
  1926. content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px';
  1927. dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px';
  1928. dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px';
  1929. };
  1930. /**
  1931. * Hide the tooltip when displayed
  1932. * @private
  1933. */
  1934. Graph3d.prototype._hideTooltip = function () {
  1935. if (this.tooltip) {
  1936. this.tooltip.dataPoint = null;
  1937. for (var prop in this.tooltip.dom) {
  1938. if (this.tooltip.dom.hasOwnProperty(prop)) {
  1939. var elem = this.tooltip.dom[prop];
  1940. if (elem && elem.parentNode) {
  1941. elem.parentNode.removeChild(elem);
  1942. }
  1943. }
  1944. }
  1945. }
  1946. };
  1947. /**--------------------------------------------------------------------------**/
  1948. /**
  1949. * Get the horizontal mouse position from a mouse event
  1950. *
  1951. * @param {Event} event
  1952. * @returns {number} mouse x
  1953. */
  1954. function getMouseX (event) {
  1955. if ('clientX' in event) return event.clientX;
  1956. return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
  1957. }
  1958. /**
  1959. * Get the vertical mouse position from a mouse event
  1960. *
  1961. * @param {Event} event
  1962. * @returns {number} mouse y
  1963. */
  1964. function getMouseY (event) {
  1965. if ('clientY' in event) return event.clientY;
  1966. return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
  1967. }
  1968. // -----------------------------------------------------------------------------
  1969. // Public methods for specific settings
  1970. // -----------------------------------------------------------------------------
  1971. /**
  1972. * Set the rotation and distance of the camera
  1973. *
  1974. * @param {Object} pos An object with the camera position
  1975. * @param {number} [pos.horizontal] The horizontal rotation, between 0 and 2*PI.
  1976. * Optional, can be left undefined.
  1977. * @param {number} [pos.vertical] The vertical rotation, between 0 and 0.5*PI.
  1978. * if vertical=0.5*PI, the graph is shown from
  1979. * the top. Optional, can be left undefined.
  1980. * @param {number} [pos.distance] The (normalized) distance of the camera to the
  1981. * center of the graph, a value between 0.71 and
  1982. * 5.0. Optional, can be left undefined.
  1983. */
  1984. Graph3d.prototype.setCameraPosition = function(pos) {
  1985. Settings.setCameraPosition(pos, this);
  1986. this.redraw();
  1987. };
  1988. /**
  1989. * Set a new size for the graph
  1990. *
  1991. * @param {string} width Width in pixels or percentage (for example '800px'
  1992. * or '50%')
  1993. * @param {string} height Height in pixels or percentage (for example '400px'
  1994. * or '30%')
  1995. */
  1996. Graph3d.prototype.setSize = function(width, height) {
  1997. this._setSize(width, height);
  1998. this.redraw();
  1999. };
  2000. // -----------------------------------------------------------------------------
  2001. // End public methods for specific settings
  2002. // -----------------------------------------------------------------------------
  2003. module.exports = Graph3d;