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.

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