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.

2513 lines
74 KiB

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