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.

2345 lines
70 KiB

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