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.

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