1 /* 2 Copyright 2008-2026 3 Matthias Ehmann, 4 Carsten Miller, 5 Andreas Walter, 6 Alfred Wassermann 7 8 This file is part of JSXGraph. 9 10 JSXGraph is free software dual licensed under the GNU LGPL or MIT License. 11 12 You can redistribute it and/or modify it under the terms of the 13 14 * GNU Lesser General Public License as published by 15 the Free Software Foundation, either version 3 of the License, or 16 (at your option) any later version 17 OR 18 * MIT License: https://github.com/jsxgraph/jsxgraph/blob/master/LICENSE.MIT 19 20 JSXGraph is distributed in the hope that it will be useful, 21 but WITHOUT ANY WARRANTY; without even the implied warranty of 22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 23 GNU Lesser General Public License for more details. 24 25 You should have received a copy of the GNU Lesser General Public License and 26 the MIT License along with JSXGraph. If not, see <https://www.gnu.org/licenses/> 27 and <https://opensource.org/licenses/MIT/>. 28 */ 29 /* 30 Some functionalities in this file were developed as part of a software project 31 with students. We would like to thank all contributors for their help: 32 33 Winter semester 2023/2024: 34 Lars Hofmann 35 Leonhard Iser 36 Vincent Kulicke 37 Laura Rinas 38 */ 39 40 /*global JXG:true, define: true*/ 41 42 import JXG from "../jxg.js"; 43 import Const from "../base/constants.js"; 44 import Coords from "../base/coords.js"; 45 import Type from "../utils/type.js"; 46 import Mat from "../math/math.js"; 47 import Geometry from "../math/geometry.js"; 48 import Numerics from "../math/numerics.js"; 49 import Env from "../utils/env.js"; 50 import GeometryElement from "../base/element.js"; 51 import Composition from "../base/composition.js"; 52 53 /** 54 * 3D view inside a JXGraph board. 55 * 56 * @class Creates a new 3D view. Do not use this constructor to create a 3D view. Use {@link JXG.Board#create} with 57 * type {@link View3D} instead. 58 * 59 * @augments JXG.GeometryElement 60 * @param {Array} parents Array consisting of lower left corner [x, y] of the view inside the board, [width, height] of the view 61 * and box size [[x1, x2], [y1,y2], [z1,z2]]. If the view's azimuth=0 and elevation=0, the 3D view will cover a rectangle with lower left corner 62 * [x,y] and side lengths [w, h] of the board. 63 */ 64 JXG.View3D = function (board, parents, attributes) { 65 this.constructor(board, attributes, Const.OBJECT_TYPE_VIEW3D, Const.OBJECT_CLASS_3D); 66 67 /** 68 * An associative array containing all geometric objects belonging to the view. 69 * Key is the id of the object and value is a reference to the object. 70 * @type Object 71 * @private 72 */ 73 this.objects = {}; 74 75 /** 76 * An array containing all the elements in the view that are sorted due to their depth order. 77 * @Type Object 78 * @private 79 */ 80 this.depthOrdered = {}; 81 82 /** 83 * TODO: why deleted? 84 * An array containing all geometric objects in this view in the order of construction. 85 * @type Array 86 * @private 87 */ 88 // this.objectsList = []; 89 90 /** 91 * An associative array / dictionary to store the objects of the board by name. The name of the object is the key and value is a reference to the object. 92 * @type Object 93 * @private 94 */ 95 this.elementsByName = {}; 96 97 /** 98 * Default axes of the 3D view, contains the axes of the view or null. 99 * 100 * @type {Object} 101 * @default null 102 */ 103 this.defaultAxes = null; 104 105 /** 106 * The Tait-Bryan angles specifying the view box orientation 107 */ 108 this.angles = { 109 az: null, 110 el: null, 111 bank: null 112 }; 113 114 /** 115 * @type {Array} 116 * The view box orientation matrix 117 */ 118 this.matrix3DRot = [ 119 [1, 0, 0, 0], 120 [0, 1, 0, 0], 121 [0, 0, 1, 0], 122 [0, 0, 0, 1] 123 ]; 124 125 // Used for z-index computation 126 this.matrix3DRotShift = [ 127 [1, 0, 0, 0], 128 [0, 1, 0, 0], 129 [0, 0, 1, 0], 130 [0, 0, 0, 1] 131 ]; 132 133 /** 134 * @type {Array} 135 * @private 136 */ 137 // 3D-to-2D transformation matrix 138 this.matrix3D = [ 139 [1, 0, 0, 0], 140 [0, 1, 0, 0], 141 [0, 0, 1, 0] 142 ]; 143 144 /** 145 * The 4×4 matrix that maps box coordinates to camera coordinates. These 146 * coordinate systems fit into the View3D coordinate atlas as follows. 147 * <ul> 148 * <li><b>World coordinates.</b> The coordinates used to specify object 149 * positions in a JSXGraph scene.</li> 150 * <li><b>Box coordinates.</b> The world coordinates translated to put the 151 * center of the view box at the origin. 152 * <li><b>Camera coordinates.</b> The coordinate system where the 153 * <code>x</code>, <code>y</code> plane is the screen, the origin is the 154 * center of the screen, and the <code>z</code> axis points out of the 155 * screen, toward the viewer. 156 * <li><b>Focal coordinates.</b> The camera coordinates translated to put 157 * the origin at the focal point, which is set back from the screen by the 158 * focal distance.</li> 159 * </ul> 160 * The <code>boxToCam</code> transformation is exposed to help 3D elements 161 * manage their 2D representations in central projection mode. To map world 162 * coordinates to focal coordinates, use the 163 * {@link JXG.View3D#worldToFocal} method. 164 * @type {Array} 165 */ 166 this.boxToCam = []; 167 168 /** 169 * @type array 170 * @private 171 */ 172 // Lower left corner [x, y] of the 3D view if elevation and azimuth are set to 0. 173 this.llftCorner = parents[0]; 174 175 /** 176 * Width and height [w, h] of the 3D view if elevation and azimuth are set to 0. 177 * @type array 178 * @private 179 */ 180 this.size = parents[1]; 181 182 /** 183 * Bounding box (cube) [[x1, x2], [y1,y2], [z1,z2]] of the 3D view 184 * @type array 185 */ 186 this.bbox3D = parents[2]; 187 188 /** 189 * The distance from the camera to the origin. In other words, the 190 * radius of the sphere where the camera sits. 191 * @type Number 192 */ 193 this.r = -1; 194 195 /** 196 * The distance from the camera to the screen. Computed automatically from 197 * the `fov` property. 198 * @type Number 199 */ 200 this.focalDist = -1; 201 202 /** 203 * Type of projection. 204 * @type String 205 */ 206 // Will be set in update(). 207 this.projectionType = 'parallel'; 208 209 /** 210 * Whether trackball navigation is currently enabled. 211 * @type String 212 */ 213 this.trackballEnabled = false; 214 215 /** 216 * Store last position of pointer. 217 * This is the successor to use evt.movementX/Y which caused problems on firefox 218 * @type Object 219 * @private 220 */ 221 this._lastPos = { 222 x: 0, 223 y: 0 224 }; 225 226 this.timeoutAzimuth = null; 227 228 this.zIndexMin = Infinity; 229 this.zIndexMax = -Infinity; 230 231 this.id = this.board.setId(this, 'V'); 232 this.board.finalizeAdding(this); 233 this.elType = 'view3d'; 234 }; 235 236 JXG.View3D.prototype = new GeometryElement(); 237 Type.copyMethodMap(JXG.View3D, { 238 // TODO 239 }); 240 241 JXG.extend( 242 JXG.View3D.prototype, /** @lends JXG.View3D.prototype */ { 243 244 /** 245 * Creates a new 3D element of type elementType. 246 * @param {String} elementType Type of the element to be constructed given as a string e.g. 'point3d' or 'surface3d'. 247 * @param {Array} parents Array of parent elements needed to construct the element e.g. coordinates for a 3D point or two 248 * 3D points to construct a line. This highly depends on the elementType that is constructed. See the corresponding JXG.create* 249 * methods for a list of possible parameters. 250 * @param {Object} [attributes] An object containing the attributes to be set. This also depends on the elementType. 251 * Common attributes are name, visible, strokeColor. 252 * @returns {Object} Reference to the created element. This is usually a GeometryElement3D, but can be an array containing 253 * two or more elements. 254 */ 255 create: function (elementType, parents, attributes) { 256 var prefix = [], 257 el; 258 259 if (elementType.indexOf('3d') > 0) { 260 // is3D = true; 261 prefix.push(this); 262 } 263 el = this.board.create(elementType, prefix.concat(parents), attributes); 264 265 return el; 266 }, 267 268 /** 269 * Select a single or multiple elements at once. 270 * @param {String|Object|function} str The name, id or a reference to a JSXGraph 3D element in the 3D view. An object will 271 * be used as a filter to return multiple elements at once filtered by the properties of the object. 272 * @param {Boolean} onlyByIdOrName If true (default:false) elements are only filtered by their id, name or groupId. 273 * The advanced filters consisting of objects or functions are ignored. 274 * @returns {JXG.GeometryElement3D|JXG.Composition} 275 * @example 276 * // select the element with name A 277 * view.select('A'); 278 * 279 * // select all elements with strokecolor set to 'red' (but not '#ff0000') 280 * view.select({ 281 * strokeColor: 'red' 282 * }); 283 * 284 * // select all points on or below the x/y plane and make them black. 285 * view.select({ 286 * elType: 'point3d', 287 * Z: function (v) { 288 * return v <= 0; 289 * } 290 * }).setAttribute({color: 'black'}); 291 * 292 * // select all elements 293 * view.select(function (el) { 294 * return true; 295 * }); 296 */ 297 select: function (str, onlyByIdOrName) { 298 var flist, 299 olist, 300 i, 301 l, 302 s = str; 303 304 if (s === null) { 305 return s; 306 } 307 308 if (Type.isString(s) && s !== '') { 309 // It's a string, most likely an id or a name. 310 // Search by ID 311 if (Type.exists(this.objects[s])) { 312 s = this.objects[s]; 313 // Search by name 314 } else if (Type.exists(this.elementsByName[s])) { 315 s = this.elementsByName[s]; 316 // // Search by group ID 317 // } else if (Type.exists(this.groups[s])) { 318 // s = this.groups[s]; 319 } 320 321 } else if ( 322 !onlyByIdOrName && 323 (Type.isFunction(s) || (Type.isObject(s) && !Type.isFunction(s.setAttribute))) 324 ) { 325 // It's a function or an object, but not an element 326 flist = Type.filterElements(this.objectsList, s); 327 328 olist = {}; 329 l = flist.length; 330 for (i = 0; i < l; i++) { 331 olist[flist[i].id] = flist[i]; 332 } 333 s = new Composition(olist); 334 335 } else if ( 336 Type.isObject(s) && 337 Type.exists(s.id) && 338 !Type.exists(this.objects[s.id]) 339 ) { 340 // It's an element which has been deleted (and still hangs around, e.g. in an attractor list) 341 s = null; 342 } 343 344 return s; 345 }, 346 347 // set the Tait-Bryan angles to specify the current view rotation matrix 348 setAnglesFromRotation: function () { 349 var rem = this.matrix3DRot, // rotation remaining after angle extraction 350 rBank, cosBank, sinBank, 351 cosEl, sinEl, 352 cosAz, sinAz; 353 354 // extract bank by rotating the view box z axis onto the camera yz plane 355 rBank = Math.sqrt(rem[1][3] * rem[1][3] + rem[2][3] * rem[2][3]); 356 if (rBank > Mat.eps) { 357 cosBank = rem[2][3] / rBank; 358 sinBank = rem[1][3] / rBank; 359 } else { 360 // if the z axis is pointed almost exactly at the screen, we 361 // keep the current bank value 362 cosBank = Math.cos(this.angles.bank); 363 sinBank = Math.sin(this.angles.bank); 364 } 365 rem = Mat.matMatMult([ 366 [1, 0, 0, 0], 367 [0, cosBank, -sinBank, 0], 368 [0, sinBank, cosBank, 0], 369 [0, 0, 0, 1] 370 ], rem); 371 this.angles.bank = Math.atan2(sinBank, cosBank); 372 373 // extract elevation by rotating the view box z axis onto the camera 374 // y axis 375 cosEl = rem[2][3]; 376 sinEl = rem[3][3]; 377 rem = Mat.matMatMult([ 378 [1, 0, 0, 0], 379 [0, 1, 0, 0], 380 [0, 0, cosEl, sinEl], 381 [0, 0, -sinEl, cosEl] 382 ], rem); 383 this.angles.el = Math.atan2(sinEl, cosEl); 384 385 // extract azimuth 386 cosAz = -rem[1][1]; 387 sinAz = rem[3][1]; 388 this.angles.az = Math.atan2(sinAz, cosAz); 389 if (this.angles.az < 0) this.angles.az += 2 * Math.PI; 390 391 this.setSlidersFromAngles(); 392 }, 393 394 anglesHaveMoved: function () { 395 return ( 396 this._hasMoveAz || this._hasMoveEl || 397 Math.abs(this.angles.az - this.az_slide.Value()) > Mat.eps || 398 Math.abs(this.angles.el - this.el_slide.Value()) > Mat.eps || 399 Math.abs(this.angles.bank - this.bank_slide.Value()) > Mat.eps 400 ); 401 }, 402 403 getAnglesFromSliders: function () { 404 this.angles.az = this.az_slide.Value(); 405 this.angles.el = this.el_slide.Value(); 406 this.angles.bank = this.bank_slide.Value(); 407 }, 408 409 setSlidersFromAngles: function () { 410 this.az_slide.setValue(this.angles.az); 411 this.el_slide.setValue(this.angles.el); 412 this.bank_slide.setValue(this.angles.bank); 413 }, 414 415 // return the rotation matrix specified by the current Tait-Bryan angles 416 getRotationFromAngles: function () { 417 var a, e, b, f, 418 cosBank, sinBank, 419 mat = [ 420 [1, 0, 0, 0], 421 [0, 1, 0, 0], 422 [0, 0, 1, 0], 423 [0, 0, 0, 1] 424 ]; 425 426 // mat projects homogeneous 3D coords in View3D 427 // to homogeneous 2D coordinates in the board 428 a = this.angles.az; 429 e = this.angles.el; 430 b = this.angles.bank; 431 f = -Math.sin(e); 432 433 mat[1][1] = -Math.cos(a); 434 mat[1][2] = Math.sin(a); 435 mat[1][3] = 0; 436 437 mat[2][1] = f * Math.sin(a); 438 mat[2][2] = f * Math.cos(a); 439 mat[2][3] = Math.cos(e); 440 441 mat[3][1] = Math.cos(e) * Math.sin(a); 442 mat[3][2] = Math.cos(e) * Math.cos(a); 443 mat[3][3] = Math.sin(e); 444 445 cosBank = Math.cos(b); 446 sinBank = Math.sin(b); 447 mat = Mat.matMatMult([ 448 [1, 0, 0, 0], 449 [0, cosBank, sinBank, 0], 450 [0, -sinBank, cosBank, 0], 451 [0, 0, 0, 1] 452 ], mat); 453 454 return mat; 455 456 /* this code, originally from `_updateCentralProjection`, is an 457 * alternate implementation of the azimuth-elevation matrix 458 * computation above. using this implementation instead of the 459 * current one might lead to simpler code in a future refactoring 460 var a, e, up, 461 ax, ay, az, v, nrm, 462 eye, d, 463 func_sphere; 464 465 // finds the point on the unit sphere with the given azimuth and 466 // elevation, and returns its affine coordinates 467 func_sphere = function (az, el) { 468 return [ 469 Math.cos(az) * Math.cos(el), 470 -Math.sin(az) * Math.cos(el), 471 Math.sin(el) 472 ]; 473 }; 474 475 a = this.az_slide.Value() + (3 * Math.PI * 0.5); // Sphere 476 e = this.el_slide.Value(); 477 478 // create an up vector and an eye vector which are 90 degrees out of phase 479 up = func_sphere(a, e + Math.PI / 2); 480 eye = func_sphere(a, e); 481 d = [eye[0], eye[1], eye[2]]; 482 483 nrm = Mat.norm(d, 3); 484 az = [d[0] / nrm, d[1] / nrm, d[2] / nrm]; 485 486 nrm = Mat.norm(up, 3); 487 v = [up[0] / nrm, up[1] / nrm, up[2] / nrm]; 488 489 ax = Mat.crossProduct(v, az); 490 ay = Mat.crossProduct(az, ax); 491 492 this.matrix3DRot[1] = [0, ax[0], ax[1], ax[2]]; 493 this.matrix3DRot[2] = [0, ay[0], ay[1], ay[2]]; 494 this.matrix3DRot[3] = [0, az[0], az[1], az[2]]; 495 */ 496 }, 497 498 /** 499 * Project 2D point (x,y) to the virtual trackpad sphere, 500 * see Bell's virtual trackpad, and return z-component of the 501 * number. 502 * 503 * @param {Number} r 504 * @param {Number} x 505 * @param {Number} y 506 * @returns Number 507 * @private 508 */ 509 _projectToSphere: function (r, x, y) { 510 var d = Mat.hypot(x, y), 511 t, z; 512 513 if (d < r * 0.7071067811865475) { // Inside sphere 514 z = Math.sqrt(r * r - d * d); 515 } else { // On hyperbola 516 t = r / 1.414213562373095; 517 z = t * t / d; 518 } 519 return z; 520 }, 521 522 /** 523 * Determine 4x4 rotation matrix with Bell's virtual trackball. 524 * 525 * @returns {Array} 4x4 rotation matrix 526 * @private 527 */ 528 updateProjectionTrackball: function (Pref) { 529 var R = 100, 530 dx, dy, dr2, 531 p1, p2, x, y, theta, t, d, 532 c, s, n, 533 mat = [ 534 [1, 0, 0, 0], 535 [0, 1, 0, 0], 536 [0, 0, 1, 0], 537 [0, 0, 0, 1] 538 ]; 539 540 if (!Type.exists(this._trackball)) { 541 return this.matrix3DRot; 542 } 543 544 dx = this._trackball.dx; 545 dy = this._trackball.dy; 546 dr2 = dx * dx + dy * dy; 547 if (dr2 > Mat.eps) { 548 // // Method by Hanson, "The rolling ball", Graphics Gems III, p.51 549 // // Rotation axis: 550 // // n = (-dy/dr, dx/dr, 0) 551 // // Rotation angle around n: 552 // // theta = atan(dr / R) approx dr / R 553 // dr = Math.sqrt(dr2); 554 // c = R / Math.hypot(R, dr); // cos(theta) 555 // t = 1 - c; // 1 - cos(theta) 556 // s = dr / Math.hypot(R, dr); // sin(theta) 557 // n = [-dy / dr, dx / dr, 0]; 558 559 // Bell virtual trackpad, see 560 // https://opensource.apple.com/source/X11libs/X11libs-60/mesa/Mesa-7.8.2/progs/util/trackball.c.auto.html 561 // http://scv.bu.edu/documentation/presentations/visualizationworkshop08/materials/opengl/trackball.c. 562 // See also Henriksen, Sporring, Hornaek, "Virtual Trackballs revisited". 563 // 564 R = (this.size[0] * this.board.unitX + this.size[1] * this.board.unitY) * 0.25; 565 x = this._trackball.x; 566 y = this._trackball.y; 567 568 p2 = [x, y, this._projectToSphere(R, x, y)]; 569 x -= dx; 570 y -= dy; 571 p1 = [x, y, this._projectToSphere(R, x, y)]; 572 573 n = Mat.crossProduct(p1, p2); 574 d = Mat.hypot(n[0], n[1], n[2]); 575 n[0] /= d; 576 n[1] /= d; 577 n[2] /= d; 578 579 t = Geometry.distance(p2, p1, 3) / (2 * R); 580 t = (t > 1.0) ? 1.0 : t; 581 t = (t < -1.0) ? -1.0 : t; 582 theta = 2.0 * Math.asin(t); 583 c = Math.cos(theta); 584 t = 1 - c; 585 s = Math.sin(theta); 586 587 // Rotation by theta about the axis n. See equation 9.63 of 588 // 589 // Ian Richard Cole. "Modeling CPV" (thesis). Loughborough 590 // University. https://hdl.handle.net/2134/18050 591 // 592 mat[1][1] = c + n[0] * n[0] * t; 593 mat[2][1] = n[1] * n[0] * t + n[2] * s; 594 mat[3][1] = n[2] * n[0] * t - n[1] * s; 595 596 mat[1][2] = n[0] * n[1] * t - n[2] * s; 597 mat[2][2] = c + n[1] * n[1] * t; 598 mat[3][2] = n[2] * n[1] * t + n[0] * s; 599 600 mat[1][3] = n[0] * n[2] * t + n[1] * s; 601 mat[2][3] = n[1] * n[2] * t - n[0] * s; 602 mat[3][3] = c + n[2] * n[2] * t; 603 } 604 605 mat = Mat.matMatMult(mat, this.matrix3DRot); 606 return mat; 607 }, 608 609 updateAngleSliderBounds: function () { 610 var az_smax, az_smin, 611 el_smax, el_smin, el_cover, 612 el_smid, el_equiv, el_flip_equiv, 613 el_equiv_loss, el_flip_equiv_loss, el_interval_loss, 614 bank_smax, bank_smin; 615 616 // update stored trackball toggle 617 this.trackballEnabled = this.evalVisProp('trackball.enabled'); 618 619 // set slider bounds 620 if (this.trackballEnabled) { 621 this.az_slide.setMin(0); 622 this.az_slide.setMax(2 * Math.PI); 623 this.el_slide.setMin(-0.5 * Math.PI); 624 this.el_slide.setMax(0.5 * Math.PI); 625 this.bank_slide.setMin(-Math.PI); 626 this.bank_slide.setMax(Math.PI); 627 } else { 628 this.az_slide.setMin(this.visProp.az.slider.min); 629 this.az_slide.setMax(this.visProp.az.slider.max); 630 this.el_slide.setMin(this.visProp.el.slider.min); 631 this.el_slide.setMax(this.visProp.el.slider.max); 632 this.bank_slide.setMin(this.visProp.bank.slider.min); 633 this.bank_slide.setMax(this.visProp.bank.slider.max); 634 } 635 636 // get new slider bounds 637 az_smax = this.az_slide._smax; 638 az_smin = this.az_slide._smin; 639 el_smax = this.el_slide._smax; 640 el_smin = this.el_slide._smin; 641 bank_smax = this.bank_slide._smax; 642 bank_smin = this.bank_slide._smin; 643 644 // wrap and restore angle values 645 if (this.trackballEnabled) { 646 // if we're upside-down, flip the bank angle to reach the same 647 // orientation with an elevation between -pi/2 and pi/2 648 el_cover = Mat.mod(this.angles.el, 2 * Math.PI); 649 if (0.5 * Math.PI < el_cover && el_cover < 1.5 * Math.PI) { 650 this.angles.el = Math.PI - el_cover; 651 this.angles.az = Mat.wrap(this.angles.az + Math.PI, az_smin, az_smax); 652 this.angles.bank = Mat.wrap(this.angles.bank + Math.PI, bank_smin, bank_smax); 653 } 654 655 // wrap the azimuth and bank angle 656 this.angles.az = Mat.wrap(this.angles.az, az_smin, az_smax); 657 this.angles.el = Mat.wrap(this.angles.el, el_smin, el_smax); 658 this.angles.bank = Mat.wrap(this.angles.bank, bank_smin, bank_smax); 659 } else { 660 // wrap and clamp the elevation into the slider range. if 661 // flipping the elevation gets us closer to the slider interval, 662 // do that, inverting the azimuth and bank angle to compensate 663 el_interval_loss = function (t) { 664 if (t < el_smin) { 665 return el_smin - t; 666 } else if (el_smax < t) { 667 return t - el_smax; 668 } else { 669 return 0; 670 } 671 }; 672 el_smid = 0.5 * (el_smin + el_smax); 673 el_equiv = Mat.wrap( 674 this.angles.el, 675 el_smid - Math.PI, 676 el_smid + Math.PI 677 ); 678 el_flip_equiv = Mat.wrap( 679 Math.PI - this.angles.el, 680 el_smid - Math.PI, 681 el_smid + Math.PI 682 ); 683 el_equiv_loss = el_interval_loss(el_equiv); 684 el_flip_equiv_loss = el_interval_loss(el_flip_equiv); 685 if (el_equiv_loss <= el_flip_equiv_loss) { 686 this.angles.el = Mat.clamp(el_equiv, el_smin, el_smax); 687 } else { 688 this.angles.el = Mat.clamp(el_flip_equiv, el_smin, el_smax); 689 this.angles.az = Mat.wrap(this.angles.az + Math.PI, az_smin, az_smax); 690 this.angles.bank = Mat.wrap(this.angles.bank + Math.PI, bank_smin, bank_smax); 691 } 692 693 // wrap and clamp the azimuth and bank angle into the slider range 694 this.angles.az = Mat.wrapAndClamp(this.angles.az, az_smin, az_smax, 2 * Math.PI); 695 this.angles.bank = Mat.wrapAndClamp(this.angles.bank, bank_smin, bank_smax, 2 * Math.PI); 696 697 // since we're using `clamp`, angles may have changed 698 this.matrix3DRot = this.getRotationFromAngles(); 699 } 700 701 // restore slider positions 702 this.setSlidersFromAngles(); 703 }, 704 705 /** 706 * @private 707 * @returns {Array} 708 */ 709 _updateCentralProjection: function () { 710 var zf = 20, // near clip plane 711 zn = 8, // far clip plane 712 713 // See https://www.mathematik.uni-marburg.de/~thormae/lectures/graphics1/graphics_6_1_eng_web.html 714 // bbox3D is always at the world origin, i.e. T_obj is the unit matrix. 715 // All vectors contain affine coordinates and have length 3 716 // The matrices are of size 4x4. 717 r, A; 718 719 // set distance from view box center to camera 720 r = this.evalVisProp('r'); 721 if (r === 'auto') { 722 r = Mat.hypot( 723 this.bbox3D[0][0] - this.bbox3D[0][1], 724 this.bbox3D[1][0] - this.bbox3D[1][1], 725 this.bbox3D[2][0] - this.bbox3D[2][1] 726 ) * 1.01; 727 } 728 729 // compute camera transformation 730 // this.boxToCam = this.matrix3DRot.map((row) => row.slice()); 731 this.boxToCam = this.matrix3DRot.map(function (row) { return row.slice(); }); 732 this.boxToCam[3][0] = -r; 733 734 // compute focal distance and clip space transformation 735 this.focalDist = 1 / Math.tan(0.5 * this.evalVisProp('fov')); 736 A = [ 737 [0, 0, 0, -1], 738 [0, this.focalDist, 0, 0], 739 [0, 0, this.focalDist, 0], 740 [2 * zf * zn / (zn - zf), 0, 0, (zf + zn) / (zn - zf)] 741 ]; 742 743 return Mat.matMatMult(A, this.boxToCam); 744 }, 745 746 // Update 3D-to-2D transformation matrix with the actual azimuth and elevation angles. 747 update: function () { 748 var r = this.r, 749 stretch = [ 750 [1, 0, 0, 0], 751 [0, -r, 0, 0], 752 [0, 0, -r, 0], 753 [0, 0, 0, 1] 754 ], 755 mat2D, objectToClip, size, 756 dx, dy; 757 // objectsList; 758 759 if ( 760 !Type.exists(this.el_slide) || 761 !Type.exists(this.az_slide) || 762 !Type.exists(this.bank_slide) || 763 !this.needsUpdate 764 ) { 765 this.needsUpdate = false; 766 return this; 767 } 768 769 mat2D = [ 770 [1, 0, 0], 771 [0, 1, 0], 772 [0, 0, 1] 773 ]; 774 775 this.projectionType = this.evalVisProp('projection').toLowerCase(); 776 777 // override angle slider bounds when trackball navigation is enabled 778 if (this.trackballEnabled !== this.evalVisProp('trackball.enabled')) { 779 this.updateAngleSliderBounds(); 780 } 781 782 if (this._hasMoveTrackball) { 783 // The trackball has been moved since the last update, so we do 784 // trackball navigation. When the trackball is enabled, a drag 785 // event is interpreted as a trackball movement unless it's 786 // caught by something else, like point dragging. When the 787 // trackball is disabled, the trackball movement flag should 788 // never be set 789 this.matrix3DRot = this.updateProjectionTrackball(); 790 this.setAnglesFromRotation(); 791 } else if (this.anglesHaveMoved()) { 792 // The trackball hasn't been moved since the last up date, but 793 // the Tait-Bryan angles have been, so we do angle navigation 794 this.getAnglesFromSliders(); 795 this.matrix3DRot = this.getRotationFromAngles(); 796 } 797 798 /** 799 * The translation that moves the center of the view box to the origin. 800 */ 801 this.shift = [ 802 [1, 0, 0, 0], 803 [-0.5 * (this.bbox3D[0][0] + this.bbox3D[0][1]), 1, 0, 0], 804 [-0.5 * (this.bbox3D[1][0] + this.bbox3D[1][1]), 0, 1, 0], 805 [-0.5 * (this.bbox3D[2][0] + this.bbox3D[2][1]), 0, 0, 1] 806 ]; 807 808 switch (this.projectionType) { 809 case 'central': // Central projection 810 811 // Add a final transformation to scale and shift the projection 812 // on the board, usually called viewport. 813 size = 2 * 0.4; 814 mat2D[1][1] = this.size[0] / size; // w / d_x 815 mat2D[2][2] = this.size[1] / size; // h / d_y 816 mat2D[1][0] = this.llftCorner[0] + mat2D[1][1] * 0.5 * size; // llft_x 817 mat2D[2][0] = this.llftCorner[1] + mat2D[2][2] * 0.5 * size; // llft_y 818 // The transformations this.matrix3D and mat2D can not be combined at this point, 819 // since the projected vectors have to be normalized in between in project3DTo2D 820 this.viewPortTransform = mat2D; 821 objectToClip = this._updateCentralProjection(); 822 // this.matrix3D is a 4x4 matrix 823 this.matrix3D = Mat.matMatMult(objectToClip, this.shift); 824 break; 825 826 case 'parallel': // Parallel projection 827 default: 828 // Add a final transformation to scale and shift the projection 829 // on the board, usually called viewport. 830 dx = this.bbox3D[0][1] - this.bbox3D[0][0]; 831 dy = this.bbox3D[1][1] - this.bbox3D[1][0]; 832 mat2D[1][1] = this.size[0] / dx; // w / d_x 833 mat2D[2][2] = this.size[1] / dy; // h / d_y 834 mat2D[1][0] = this.llftCorner[0] + mat2D[1][1] * 0.5 * dx; // llft_x 835 mat2D[2][0] = this.llftCorner[1] + mat2D[2][2] * 0.5 * dy; // llft_y 836 837 // Combine all transformations, this.matrix3D is a 3x4 matrix 838 this.matrix3D = Mat.matMatMult( 839 mat2D, 840 Mat.matMatMult(Mat.matMatMult(this.matrix3DRot, stretch), this.shift).slice(0, 3) 841 ); 842 } 843 844 // Used for zIndex in dept ordering in subsequent update methods of the 845 // 3D elements and in view3d.updateRenderer 846 this.matrix3DRotShift = Mat.matMatMult(this.matrix3DRot, this.shift); 847 848 return this; 849 }, 850 851 /** 852 * Compares 3D elements according to their z-Index. 853 * @param {JXG.GeometryElement3D} a 854 * @param {JXG.GeometryElement3D} b 855 * @returns Number 856 */ 857 compareDepth: function (a, b) { 858 // return a.zIndex - b.zIndex; 859 // if (a.type !== Const.OBJECT_TYPE_PLANE3D && b.type !== Const.OBJECT_TYPE_PLANE3D) { 860 // return a.zIndex - b.zIndex; 861 // } else if (a.type === Const.OBJECT_TYPE_PLANE3D) { 862 // let bHesse = Mat.innerProduct(a.point.coords, a.normal, 4); 863 // let po = Mat.innerProduct(b.coords, a.normal, 4); 864 // let pos = Mat.innerProduct(this.boxToCam[3], a.normal, 4); 865 // console.log(this.boxToCam[3]) 866 // return pos - po; 867 // } else if (b.type === Const.OBJECT_TYPE_PLANE3D) { 868 // let bHesse = Mat.innerProduct(b.point.coords, b.normal, 4); 869 // let po = Mat.innerProduct(a.coords, a.normal, 4); 870 // let pos = Mat.innerProduct(this.boxToCam[3], b.normal, 4); 871 // console.log('b', pos, po, bHesse) 872 // return -pos; 873 // } 874 return a.zIndex - b.zIndex; 875 }, 876 877 updateZIndices: function() { 878 var id, el; 879 for (id in this.objects) { 880 if (this.objects.hasOwnProperty(id)) { 881 el = this.objects[id]; 882 // Update zIndex of less frequent objects line3d and polygon3d 883 // The other elements (point3d, face3d) do this in their update method. 884 if (( 885 el.type === Const.OBJECT_TYPE_LINE3D || 886 el.type === Const.OBJECT_TYPE_POLYGON3D 887 ) && 888 Type.exists(el.element2D) && 889 el.element2D.evalVisProp('visible') 890 ) { 891 el.updateZIndex(); 892 } 893 } 894 } 895 }, 896 897 updateShaders: function() { 898 var id, el, v; 899 for (id in this.objects) { 900 if (this.objects.hasOwnProperty(id)) { 901 el = this.objects[id]; 902 903 if (el.visPropCalc.visible && Type.exists(el.shader)) { 904 if (this.board._change3DView && el.evalVisProp('shader.fixed')) { 905 // In case, 3D view is rotated and the shader is fixed 906 // we can avoid the call of shader() 907 v = el.zIndex; 908 } else { 909 v = el.shader(); 910 } 911 if (v < this.zIndexMin) { 912 this.zIndexMin = v; 913 } else if (v > this.zIndexMax) { 914 this.zIndexMax = v; 915 } 916 } 917 } 918 } 919 }, 920 921 updateDepthOrdering: function () { 922 var id, el, 923 i, j, l, layers, lay; 924 925 // Collect elements for depth ordering layer-wise 926 layers = this.evalVisProp('depthorder.layers'); 927 for (i = 0; i < layers.length; i++) { 928 this.depthOrdered[layers[i]] = []; 929 } 930 931 for (id in this.objects) { 932 if (this.objects.hasOwnProperty(id)) { 933 el = this.objects[id]; 934 if ((el.type === Const.OBJECT_TYPE_FACE3D || 935 el.type === Const.OBJECT_TYPE_LINE3D || 936 // el.type === Const.OBJECT_TYPE_PLANE3D || 937 el.type === Const.OBJECT_TYPE_POINT3D || 938 el.type === Const.OBJECT_TYPE_POLYGON3D 939 ) && 940 Type.exists(el.element2D) && 941 el.element2D.visPropCalc.visible 942 // el.element2D.evalVisProp('visible') 943 ) { 944 lay = el.element2D.evalVisProp('layer'); 945 if (layers.indexOf(lay) >= 0) { 946 this.depthOrdered[lay].push(el); 947 } 948 } 949 } 950 } 951 952 if (this.board.renderer && this.board.renderer.type === 'svg') { 953 for (i = 0; i < layers.length; i++) { 954 lay = layers[i]; 955 this.depthOrdered[lay].sort(this.compareDepth.bind(this)); 956 // DEBUG 957 // if (this.depthOrdered[lay].length > 0) { 958 // for (let k = 0; k < this.depthOrdered[lay].length; k++) { 959 // let o = this.depthOrdered[lay][k] 960 // console.log(o.visProp.fillcolor, o.zIndex) 961 // } 962 // } 963 l = this.depthOrdered[lay]; 964 for (j = 0; j < l.length; j++) { 965 this.board.renderer.setLayer(l[j].element2D, lay); 966 } 967 // this.depthOrdered[lay].forEach((el) => this.board.renderer.setLayer(el.element2D, lay)); 968 // Attention: forEach prevents deleting an element 969 } 970 } 971 972 return this; 973 }, 974 975 updateRenderer: function () { 976 if (!this.needsUpdate) { 977 return this; 978 } 979 980 // console.time('update') 981 // Handle depth ordering 982 this.depthOrdered = {}; 983 984 if (this.shift !== undefined && this.evalVisProp('depthorder.enabled')) { 985 // Update the zIndices of certain element types. 986 // We do it here in updateRenderer, because the elements' positions 987 // are meanwhile updated. 988 this.updateZIndices(); 989 990 this.updateShaders(); 991 992 if (this.board.renderer && this.board.renderer.type === 'svg') { 993 // For SVG we update the DOM order here. 994 // In canvas we sort the elements in board.updateRendererCanvas 995 this.updateDepthOrdering(); 996 } 997 } 998 // console.timeEnd('update') 999 1000 this.needsUpdate = false; 1001 return this; 1002 }, 1003 1004 removeObject: function (object, saveMethod) { 1005 var i, el, le, o, fst, face; 1006 1007 // this.board.removeObject(object, saveMethod); 1008 if (Type.isArray(object)) { 1009 for (i = 0; i < object.length; i++) { 1010 this.removeObject(object[i]); 1011 } 1012 return this; 1013 } 1014 1015 object = this.select(object); 1016 1017 // // If the object which is about to be removed unknown or a string, do nothing. 1018 // // it is a string if a string was given and could not be resolved to an element. 1019 if (!Type.exists(object) || Type.isString(object)) { 1020 return this; 1021 } 1022 1023 try { 1024 // Remove all children. 1025 for (el in object.childElements) { 1026 if (object.childElements.hasOwnProperty(el)) { 1027 this.removeObject(object.childElements[el]); 1028 } 1029 } 1030 if (object.type === Const.OBJECT_TYPE_POLYHEDRON3D) { 1031 // Special treatment for polyhedron3d. 1032 // With this we can avoid the time consuming addChild() calls. 1033 le = object.faces.length; 1034 if (le > 0) { 1035 fst = object.faces[0]._pos; 1036 fst = (object.faces[0].element2D._pos < fst) ? object.faces[0].element2D._pos : fst; 1037 } 1038 for (i = 0; i < le; i++) { 1039 face = object.faces[i]; 1040 delete this.objects[face.id]; 1041 1042 // this.board.removeObject(face.element2D, saveMethod); 1043 delete this.board.objects[face.element2D.id]; 1044 delete this.board.elementsByName[face.element2D.name]; 1045 face.element2D.remove(); 1046 this.board.objectsList.splice(face.element2D._pos, 1); 1047 1048 delete this.board.objects[face.id]; 1049 delete this.board.elementsByName[face.name]; 1050 face.remove(); 1051 this.board.objectsList.splice(face._pos, 1); 1052 } 1053 le = this.board.objectsList.length; 1054 // Reindex the positions 1055 for (i = fst; i < this.board.objectsList.length; i++) { 1056 o = this.board.objectsList[i]; 1057 if (o._pos > -1) { o._pos = i; } 1058 } 1059 object.faces = []; 1060 } 1061 1062 delete this.objects[object.id]; 1063 } catch (e) { 1064 JXG.debug('View3D ' + object.id + ': Could not be removed: ' + e); 1065 } 1066 1067 // this.update(); 1068 1069 this.board.removeObject(object, saveMethod); 1070 1071 return this; 1072 }, 1073 1074 /** 1075 * Map world coordinates to focal coordinates. These coordinate systems 1076 * are explained in the {@link JXG.View3D#boxToCam} matrix 1077 * documentation. 1078 * 1079 * @param {Array} pWorld A world space point, in homogeneous coordinates. 1080 * @param {Boolean} [homog=true] Whether to return homogeneous coordinates. 1081 * If false, projects down to ordinary coordinates. 1082 */ 1083 worldToFocal: function (pWorld, homog = true) { 1084 var k, 1085 pView = Mat.matVecMult(this.boxToCam, Mat.matVecMult(this.shift, pWorld)); 1086 1087 pView[3] -= pView[0] * this.focalDist; 1088 if (homog) { 1089 return pView; 1090 } else { 1091 for (k = 1; k < 4; k++) { 1092 pView[k] /= pView[0]; 1093 } 1094 return pView.slice(1, 4); 1095 } 1096 }, 1097 1098 /** 1099 * Project 3D coordinates to 2D board coordinates 1100 * The 3D coordinates are provides as three numbers x, y, z or one array of length 3. 1101 * 1102 * @param {Number|Array} x 1103 * @param {Number[]} y 1104 * @param {Number[]} z 1105 * @returns {Array} Array of length 3 containing the projection on to the board 1106 * in homogeneous user coordinates. 1107 */ 1108 project3DTo2D: function (x, y, z) { 1109 var vec, w; 1110 if (arguments.length === 3) { 1111 vec = [1, x, y, z]; 1112 } else { 1113 // Argument is an array 1114 if (x.length === 3) { 1115 // vec = [1].concat(x); 1116 vec = x.slice(); 1117 vec.unshift(1); 1118 } else { 1119 vec = x; 1120 } 1121 } 1122 1123 w = Mat.matVecMult(this.matrix3D, vec); 1124 1125 switch (this.projectionType) { 1126 case 'central': 1127 w[1] /= w[0]; 1128 w[2] /= w[0]; 1129 w[3] /= w[0]; 1130 w[0] /= w[0]; 1131 return Mat.matVecMult(this.viewPortTransform, w.slice(0, 3)); 1132 1133 case 'parallel': 1134 default: 1135 return w; 1136 } 1137 }, 1138 1139 /** 1140 * We know that v2d * w0 = mat * (1, x, y, d)^T where v2d = (1, b, c, h)^T with unknowns w0, h, x, y. 1141 * Setting R = mat^(-1) gives 1142 * 1/ w0 * (1, x, y, d)^T = R * v2d. 1143 * The first and the last row of this equation allows to determine 1/w0 and h. 1144 * 1145 * @param {Array} mat 1146 * @param {Array} v2d 1147 * @param {Number} d 1148 * @returns Array 1149 * @private 1150 */ 1151 _getW0: function (mat, v2d, d) { 1152 var R = Mat.inverse(mat), 1153 R1 = R[0][0] + v2d[1] * R[0][1] + v2d[2] * R[0][2], 1154 R2 = R[3][0] + v2d[1] * R[3][1] + v2d[2] * R[3][2], 1155 w, h, det; 1156 1157 det = d * R[0][3] - R[3][3]; 1158 w = (R2 * R[0][3] - R1 * R[3][3]) / det; 1159 h = (R2 - R1 * d) / det; 1160 return [1 / w, h]; 1161 }, 1162 1163 /** 1164 * Project a 2D coordinate to the plane defined by point "foot" 1165 * and the normal vector `normal`. 1166 * 1167 * @param {JXG.Point} point2d 1168 * @param {Array} normal Normal of plane 1169 * @param {Array} foot Foot point of plane 1170 * @returns {Array} of length 4 containing the projected 1171 * point in homogeneous coordinates. 1172 */ 1173 project2DTo3DPlane: function (point2d, normal, foot) { 1174 var mat, rhs, d, le, sol, 1175 f = foot.slice(1) || [0, 0, 0], 1176 n = normal.slice(1), 1177 v2d, w0, res; 1178 1179 le = Mat.norm(n, 3); 1180 d = Mat.innerProduct(f, n, 3) / le; 1181 1182 if (this.projectionType === 'parallel') { 1183 mat = this.matrix3D.slice(0, 3); // Copy each row by reference 1184 mat.push([0, n[0], n[1], n[2]]); 1185 1186 // 2D coordinates of point 1187 rhs = point2d.coords.usrCoords.slice(); 1188 rhs.push(d); 1189 try { 1190 // Prevent singularity in case elevation angle is zero 1191 if (mat[2][3] === 1.0) { 1192 mat[2][1] = mat[2][2] = Mat.eps * 0.001; 1193 } 1194 sol = Mat.Numerics.Gauss(mat, rhs); 1195 } catch (e) { 1196 sol = [0, NaN, NaN, NaN]; 1197 } 1198 } else { 1199 mat = this.matrix3D; 1200 1201 // 2D coordinates of point: 1202 rhs = point2d.coords.usrCoords.slice(); 1203 1204 v2d = Mat.Numerics.Gauss(this.viewPortTransform, rhs); 1205 res = this._getW0(mat, v2d, d); 1206 w0 = res[0]; 1207 rhs = [ 1208 v2d[0] * w0, 1209 v2d[1] * w0, 1210 v2d[2] * w0, 1211 res[1] * w0 1212 ]; 1213 try { 1214 // Prevent singularity in case elevation angle is zero 1215 if (mat[2][3] === 1.0) { 1216 mat[2][1] = mat[2][2] = Mat.eps * 0.001; 1217 } 1218 1219 sol = Mat.Numerics.Gauss(mat, rhs); 1220 sol[1] /= sol[0]; 1221 sol[2] /= sol[0]; 1222 sol[3] /= sol[0]; 1223 // sol[3] = d; 1224 sol[0] /= sol[0]; 1225 } catch (err) { 1226 sol = [0, NaN, NaN, NaN]; 1227 } 1228 } 1229 1230 return sol; 1231 }, 1232 1233 /** 1234 * Project a point on the screen to the nearest point, in screen 1235 * distance, on a line segment in 3d space. The inputs and outputs 1236 * are in homogeneous coordinates. 1237 * <p> 1238 * Used in View3d.project2DTo3DVertical() and 1239 * Line3d.projectScreenCoords(). 1240 * 1241 * @param {Array} pScr The screen coordinates of the point to project. 1242 * @param {Array} end0 The world space coordinates of one end of the 1243 * line segment (array of length 4). 1244 * @param {Array} end1 The world space coordinates of the other end of 1245 * the line segment (array of length 4). 1246 * 1247 * @returns {Array} Homogeneous coordinates of the projection 1248 */ 1249 projectScreenToSegment: function (pScr, end0, end1) { 1250 var end0_2d = this.project3DTo2D(end0).slice(1, 3), 1251 end1_2d = this.project3DTo2D(end1).slice(1, 3), 1252 dir_2d = [ 1253 end1_2d[0] - end0_2d[0], 1254 end1_2d[1] - end0_2d[1] 1255 ], 1256 dir_2d_norm_sq = Mat.innerProduct(dir_2d, dir_2d), 1257 diff = [ 1258 pScr[0] - end0_2d[0], 1259 pScr[1] - end0_2d[1] 1260 ], 1261 s = Mat.innerProduct(diff, dir_2d) / dir_2d_norm_sq, // screen-space affine parameter 1262 mid, mid_2d, mid_diff, m, 1263 1264 t, // view-space affine parameter 1265 t_clamped, // affine parameter clamped to range 1266 t_clamped_co; 1267 1268 if (this.projectionType === 'central') { 1269 mid = [ 1270 1, 1271 0.5 * (end0[1] + end1[1]), 1272 0.5 * (end0[2] + end1[2]), 1273 0.5 * (end0[3] + end1[3]) 1274 ]; 1275 mid_2d = this.project3DTo2D(mid).slice(1, 3); 1276 mid_diff = [ 1277 mid_2d[0] - end0_2d[0], 1278 mid_2d[1] - end0_2d[1] 1279 ]; 1280 m = Mat.innerProduct(mid_diff, dir_2d) / dir_2d_norm_sq; 1281 1282 // the view-space affine parameter s is related to the 1283 // screen-space affine parameter t by a Möbius transformation, 1284 // which is determined by the following relations: 1285 // 1286 // s | t 1287 // ----- 1288 // 0 | 0 1289 // m | 1/2 1290 // 1 | 1 1291 // 1292 t = (1 - m) * s / ((1 - 2 * m) * s + m); 1293 } else { 1294 t = s; 1295 } 1296 1297 t_clamped = Math.min(Math.max(t, 0), 1); 1298 t_clamped_co = 1 - t_clamped; 1299 return [ 1300 1, 1301 t_clamped_co * end0[1] + t_clamped * end1[1], 1302 t_clamped_co * end0[2] + t_clamped * end1[2], 1303 t_clamped_co * end0[3] + t_clamped * end1[3] 1304 ]; 1305 }, 1306 1307 /** 1308 * Project a 2D coordinate to a new 3D position by keeping 1309 * the 3D x, y coordinates and changing only the z coordinate. 1310 * All horizontal moves of the 2D point are ignored. 1311 * 1312 * @param {JXG.Point} point2d 1313 * @param {Array} base_c3d 1314 * @returns {Array} of length 4 containing the projected 1315 * point in homogeneous coordinates. 1316 */ 1317 project2DTo3DVertical: function (point2d, base_c3d) { 1318 var pScr = point2d.coords.usrCoords.slice(1, 3), 1319 end0 = [1, base_c3d[1], base_c3d[2], this.bbox3D[2][0]], 1320 end1 = [1, base_c3d[1], base_c3d[2], this.bbox3D[2][1]]; 1321 1322 return this.projectScreenToSegment(pScr, end0, end1); 1323 }, 1324 1325 /** 1326 * Limit 3D coordinates to the bounding cube. 1327 * 1328 * @param {Array} c3d 3D coordinates [x,y,z] 1329 * @returns Array [Array, Boolean] containing [coords, corrected]. coords contains the updated 3D coordinates, 1330 * correct is true if the coords have been changed. 1331 */ 1332 project3DToCube: function (c3d) { 1333 var cube = this.bbox3D, 1334 isOut = false; 1335 1336 if (c3d[1] < cube[0][0]) { 1337 c3d[1] = cube[0][0]; 1338 isOut = true; 1339 } 1340 if (c3d[1] > cube[0][1]) { 1341 c3d[1] = cube[0][1]; 1342 isOut = true; 1343 } 1344 if (c3d[2] < cube[1][0]) { 1345 c3d[2] = cube[1][0]; 1346 isOut = true; 1347 } 1348 if (c3d[2] > cube[1][1]) { 1349 c3d[2] = cube[1][1]; 1350 isOut = true; 1351 } 1352 if (c3d[3] <= cube[2][0]) { 1353 c3d[3] = cube[2][0]; 1354 isOut = true; 1355 } 1356 if (c3d[3] >= cube[2][1]) { 1357 c3d[3] = cube[2][1]; 1358 isOut = true; 1359 } 1360 1361 return [c3d, isOut]; 1362 }, 1363 1364 /** 1365 * Intersect a ray with the bounding cube of the 3D view. 1366 * @param {Array} p 3D coordinates [w,x,y,z] 1367 * @param {Array} dir 3D direction vector of the line (array of length 3 or 4) 1368 * @param {Number} r direction of the ray (positive if r > 0, negative if r < 0). 1369 * @returns Affine ratio of the intersection of the line with the cube. 1370 */ 1371 intersectionLineCube: function (p, dir, r) { 1372 var r_n, i, r0, r1, d; 1373 1374 d = (dir.length === 3) ? dir : dir.slice(1); 1375 1376 r_n = r; 1377 for (i = 0; i < 3; i++) { 1378 if (d[i] !== 0) { 1379 r0 = (this.bbox3D[i][0] - p[i + 1]) / d[i]; 1380 r1 = (this.bbox3D[i][1] - p[i + 1]) / d[i]; 1381 if (r < 0) { 1382 r_n = Math.max(r_n, Math.min(r0, r1)); 1383 } else { 1384 r_n = Math.min(r_n, Math.max(r0, r1)); 1385 } 1386 } 1387 } 1388 return r_n; 1389 }, 1390 1391 /** 1392 * Test if coordinates are inside of the bounding cube. 1393 * @param {array} p 3D coordinates [[w],x,y,z] of a point. 1394 * @returns Boolean 1395 */ 1396 isInCube: function (p, polyhedron) { 1397 var q; 1398 if (p.length === 4) { 1399 if (p[0] === 0) { 1400 return false; 1401 } 1402 q = p.slice(1); 1403 } 1404 return ( 1405 q[0] > this.bbox3D[0][0] - Mat.eps && 1406 q[0] < this.bbox3D[0][1] + Mat.eps && 1407 q[1] > this.bbox3D[1][0] - Mat.eps && 1408 q[1] < this.bbox3D[1][1] + Mat.eps && 1409 q[2] > this.bbox3D[2][0] - Mat.eps && 1410 q[2] < this.bbox3D[2][1] + Mat.eps 1411 ); 1412 }, 1413 1414 /** 1415 * 1416 * @param {JXG.Plane3D} plane1 1417 * @param {JXG.Plane3D} plane2 1418 * @param {Number} d Right hand side of Hesse normal for plane2 (it can be adjusted) 1419 * @returns {Array} of length 2 containing the coordinates of the defining points of 1420 * of the intersection segment, or false if there is no intersection 1421 */ 1422 intersectionPlanePlane: function (plane1, plane2, d) { 1423 var ret = [false, false], 1424 p, q, r, w, 1425 dir; 1426 1427 d = d || plane2.d; 1428 1429 // Get one point of the intersection of the two planes 1430 w = Mat.crossProduct(plane1.normal.slice(1), plane2.normal.slice(1)); 1431 w.unshift(0); 1432 1433 p = Mat.Geometry.meet3Planes( 1434 plane1.normal, 1435 plane1.d, 1436 plane2.normal, 1437 d, 1438 w, 1439 0 1440 ); 1441 1442 // Get the direction of the intersecting line of the two planes 1443 dir = Mat.Geometry.meetPlanePlane( 1444 plane1.vec1, 1445 plane1.vec2, 1446 plane2.vec1, 1447 plane2.vec2 1448 ); 1449 1450 // Get the bounding points of the intersecting segment 1451 r = this.intersectionLineCube(p, dir, Infinity); 1452 q = Mat.axpy(r, dir, p); 1453 if (this.isInCube(q)) { 1454 ret[0] = q; 1455 } 1456 r = this.intersectionLineCube(p, dir, -Infinity); 1457 q = Mat.axpy(r, dir, p); 1458 if (this.isInCube(q)) { 1459 ret[1] = q; 1460 } 1461 1462 return ret; 1463 }, 1464 1465 intersectionPlaneFace: function (plane, face) { 1466 var ret = [], 1467 j, t, 1468 p, crds, 1469 p1, p2, c, 1470 f, le, x1, y1, x2, y2, 1471 dir, vec, w, 1472 mat = [], b = [], sol; 1473 1474 w = Mat.crossProduct(plane.normal.slice(1), face.normal.slice(1)); 1475 w.unshift(0); 1476 1477 // Get one point of the intersection of the two planes 1478 p = Geometry.meet3Planes( 1479 plane.normal, 1480 plane.d, 1481 face.normal, 1482 face.d, 1483 w, 1484 0 1485 ); 1486 1487 // Get the direction the intersecting line of the two planes 1488 dir = Geometry.meetPlanePlane( 1489 plane.vec1, 1490 plane.vec2, 1491 face.vec1, 1492 face.vec2 1493 ); 1494 1495 f = face.polyhedron.faces[face.faceNumber]; 1496 crds = face.polyhedron.coords; 1497 le = f.length; 1498 for (j = 1; j <= le; j++) { 1499 p1 = crds[f[j - 1]]; 1500 p2 = crds[f[j % le]]; 1501 vec = [0, p2[1] - p1[1], p2[2] - p1[2], p2[3] - p1[3]]; 1502 1503 x1 = Math.random(); 1504 y1 = Math.random(); 1505 x2 = Math.random(); 1506 y2 = Math.random(); 1507 mat = [ 1508 [x1 * dir[1] + y1 * dir[3], x1 * (-vec[1]) + y1 * (-vec[3])], 1509 [x2 * dir[2] + y2 * dir[3], x2 * (-vec[2]) + y2 * (-vec[3])] 1510 ]; 1511 b = [ 1512 x1 * (p1[1] - p[1]) + y1 * (p1[3] - p[3]), 1513 x2 * (p1[2] - p[2]) + y2 * (p1[3] - p[3]) 1514 ]; 1515 1516 sol = Numerics.Gauss(mat, b); 1517 t = sol[1]; 1518 if (t > -Mat.eps && t < 1 + Mat.eps) { 1519 c = [1, p1[1] + t * vec[1], p1[2] + t * vec[2], p1[3] + t * vec[3]]; 1520 ret.push(c); 1521 } 1522 } 1523 1524 return ret; 1525 }, 1526 1527 // TODO: 1528 // - handle non-closed polyhedra 1529 // - handle intersections in vertex, edge, plane 1530 intersectionPlanePolyhedron: function(plane, phdr) { 1531 var i, j, seg, 1532 p, first, pos, pos_akt, 1533 eps = 1e-12, 1534 points = [], 1535 x = [], 1536 y = [], 1537 z = []; 1538 1539 for (i = 0; i < phdr.numberFaces; i++) { 1540 if (phdr.def.faces[i].length < 3) { 1541 // We skip intersection with points or lines 1542 continue; 1543 } 1544 1545 // seg will be an array consisting of two points 1546 // that span the intersecting segment of the plane 1547 // and the face. 1548 seg = this.intersectionPlaneFace(plane, phdr.faces[i]); 1549 1550 // Plane intersects the face in less than 2 points 1551 if (seg.length < 2) { 1552 continue; 1553 } 1554 1555 if (seg[0].length === 4 && seg[1].length === 4) { 1556 // This test is necessary to filter out intersection lines which are 1557 // identical to intersections of axis planes (they would occur twice), 1558 // i.e. edges of bbox3d. 1559 for (j = 0; j < points.length; j++) { 1560 if ( 1561 (Geometry.distance(seg[0], points[j][0], 4) < eps && 1562 Geometry.distance(seg[1], points[j][1], 4) < eps) || 1563 (Geometry.distance(seg[0], points[j][1], 4) < eps && 1564 Geometry.distance(seg[1], points[j][0], 4) < eps) 1565 ) { 1566 break; 1567 } 1568 } 1569 if (j === points.length) { 1570 points.push(seg.slice()); 1571 } 1572 } 1573 } 1574 1575 // Handle the case that the intersection is the empty set. 1576 if (points.length === 0) { 1577 return { X: x, Y: y, Z: z }; 1578 } 1579 1580 // Concatenate the intersection points to a polygon. 1581 // If all went well, each intersection should appear 1582 // twice in the list. 1583 // __Attention:__ each face has to be planar!!! 1584 // Otherwise the algorithm will fail. 1585 first = 0; 1586 pos = first; 1587 i = 0; 1588 do { 1589 p = points[pos][i]; 1590 if (p.length === 4) { 1591 x.push(p[1]); 1592 y.push(p[2]); 1593 z.push(p[3]); 1594 } 1595 i = (i + 1) % 2; 1596 p = points[pos][i]; 1597 1598 pos_akt = pos; 1599 for (j = 0; j < points.length; j++) { 1600 if (j !== pos && Geometry.distance(p, points[j][0]) < eps) { 1601 pos = j; 1602 i = 0; 1603 break; 1604 } 1605 if (j !== pos && Geometry.distance(p, points[j][1]) < eps) { 1606 pos = j; 1607 i = 1; 1608 break; 1609 } 1610 } 1611 if (pos === pos_akt) { 1612 console.log('Error face3d intersection update: did not find next', pos, i); 1613 break; 1614 } 1615 } while (pos !== first); 1616 x.push(x[0]); 1617 y.push(y[0]); 1618 z.push(z[0]); 1619 1620 return { X: x, Y: y, Z: z }; 1621 }, 1622 1623 /** 1624 * Generate mesh for a surface / plane. 1625 * Returns array [dataX, dataY] for a JSXGraph curve's updateDataArray function. 1626 * @param {Array|Function} func 1627 * @param {Array} interval_u 1628 * @param {Array} interval_v 1629 * @returns Array 1630 * @private 1631 * 1632 * @example 1633 * var el = view.create('curve', [[], []]); 1634 * el.updateDataArray = function () { 1635 * var steps_u = this.evalVisProp('stepsu'), 1636 * steps_v = this.evalVisProp('stepsv'), 1637 * r_u = Type.evaluate(this.range_u), 1638 * r_v = Type.evaluate(this.range_v), 1639 * func, ret; 1640 * 1641 * if (this.F !== null) { 1642 * func = this.F; 1643 * } else { 1644 * func = [this.X, this.Y, this.Z]; 1645 * } 1646 * ret = this.view.getMesh(func, 1647 * r_u.concat([steps_u]), 1648 * r_v.concat([steps_v])); 1649 * 1650 * this.dataX = ret[0]; 1651 * this.dataY = ret[1]; 1652 * }; 1653 * 1654 */ 1655 getMesh: function (func, interval_u, interval_v) { 1656 var i_u, i_v, u, v, 1657 c2d, delta_u, delta_v, 1658 p = [0, 0, 0], 1659 steps_u = Type.evaluate(interval_u[2]), 1660 steps_v = Type.evaluate(interval_v[2]), 1661 dataX = [], 1662 dataY = []; 1663 1664 delta_u = (Type.evaluate(interval_u[1]) - Type.evaluate(interval_u[0])) / steps_u; 1665 delta_v = (Type.evaluate(interval_v[1]) - Type.evaluate(interval_v[0])) / steps_v; 1666 1667 for (i_u = 0; i_u <= steps_u; i_u++) { 1668 u = interval_u[0] + delta_u * i_u; 1669 for (i_v = 0; i_v <= steps_v; i_v++) { 1670 v = interval_v[0] + delta_v * i_v; 1671 if (Type.isFunction(func)) { 1672 p = func(u, v); 1673 } else { 1674 p = [func[0](u, v), func[1](u, v), func[2](u, v)]; 1675 } 1676 c2d = this.project3DTo2D(p); 1677 dataX.push(c2d[1]); 1678 dataY.push(c2d[2]); 1679 } 1680 dataX.push(NaN); 1681 dataY.push(NaN); 1682 } 1683 1684 for (i_v = 0; i_v <= steps_v; i_v++) { 1685 v = interval_v[0] + delta_v * i_v; 1686 for (i_u = 0; i_u <= steps_u; i_u++) { 1687 u = interval_u[0] + delta_u * i_u; 1688 if (Type.isFunction(func)) { 1689 p = func(u, v); 1690 } else { 1691 p = [func[0](u, v), func[1](u, v), func[2](u, v)]; 1692 } 1693 c2d = this.project3DTo2D(p); 1694 dataX.push(c2d[1]); 1695 dataY.push(c2d[2]); 1696 } 1697 dataX.push(NaN); 1698 dataY.push(NaN); 1699 } 1700 1701 return [dataX, dataY]; 1702 }, 1703 1704 /** 1705 * 1706 */ 1707 animateAzimuth: function () { 1708 var s = this.az_slide._smin, 1709 e = this.az_slide._smax, 1710 sdiff = e - s, 1711 newVal = this.az_slide.Value() + 0.1; 1712 1713 this.az_slide.position = (newVal - s) / sdiff; 1714 if (this.az_slide.position > 1) { 1715 this.az_slide.position = 0.0; 1716 } 1717 this.board._change3DView = true; 1718 this.board.update(); 1719 this.board._change3DView = false; 1720 1721 this.timeoutAzimuth = setTimeout(function () { 1722 this.animateAzimuth(); 1723 }.bind(this), 200); 1724 }, 1725 1726 /** 1727 * 1728 */ 1729 stopAzimuth: function () { 1730 clearTimeout(this.timeoutAzimuth); 1731 this.timeoutAzimuth = null; 1732 }, 1733 1734 /** 1735 * Check if vertical dragging is enabled and which action is needed. 1736 * Default is shiftKey. 1737 * 1738 * @returns Boolean 1739 * @private 1740 */ 1741 isVerticalDrag: function () { 1742 var b = this.board, 1743 key; 1744 if (!this.evalVisProp('verticaldrag.enabled')) { 1745 return false; 1746 } 1747 key = '_' + this.evalVisProp('verticaldrag.key') + 'Key'; 1748 return b[key]; 1749 }, 1750 1751 /** 1752 * Sets camera view to the given values. 1753 * 1754 * @param {Number} az Value of azimuth. 1755 * @param {Number} el Value of elevation. 1756 * @param {Number} [r] Value of radius. 1757 * 1758 * @returns {Object} Reference to the view. 1759 */ 1760 setView: function (az, el, r) { 1761 r = r || this.r; 1762 1763 this.az_slide.setValue(az); 1764 this.el_slide.setValue(el); 1765 this.r = r; 1766 this.board.update(); 1767 1768 return this; 1769 }, 1770 1771 /** 1772 * Changes view to the next view stored in the attribute `values`. 1773 * 1774 * @see View3D#values 1775 * 1776 * @returns {Object} Reference to the view. 1777 */ 1778 nextView: function () { 1779 var views = this.evalVisProp('values'), 1780 n = this.visProp._currentview; 1781 1782 n = (n + 1) % views.length; 1783 this.setCurrentView(n); 1784 1785 return this; 1786 }, 1787 1788 /** 1789 * Changes view to the previous view stored in the attribute `values`. 1790 * 1791 * @see View3D#values 1792 * 1793 * @returns {Object} Reference to the view. 1794 */ 1795 previousView: function () { 1796 var views = this.evalVisProp('values'), 1797 n = this.visProp._currentview; 1798 1799 n = (n + views.length - 1) % views.length; 1800 this.setCurrentView(n); 1801 1802 return this; 1803 }, 1804 1805 /** 1806 * Changes view to the determined view stored in the attribute `values`. 1807 * 1808 * @see View3D#values 1809 * 1810 * @param {Number} n Index of view in attribute `values`. 1811 * @returns {Object} Reference to the view. 1812 */ 1813 setCurrentView: function (n) { 1814 var views = this.evalVisProp('values'); 1815 1816 if (n < 0 || n >= views.length) { 1817 n = ((n % views.length) + views.length) % views.length; 1818 } 1819 1820 this.setView(views[n][0], views[n][1], views[n][2]); 1821 this.visProp._currentview = n; 1822 1823 return this; 1824 }, 1825 1826 /** 1827 * Controls 2-degree navigation in az direction using pointer. 1828 * 1829 * @private 1830 * 1831 * @param {event} evt the pointer event 1832 * @returns view 1833 */ 1834 _az_elEventHandler: function (evt) { 1835 var smax = this.az_slide._smax, 1836 smin = this.az_slide._smin, 1837 speed = (smax - smin) / this.board.canvasWidth * (this.evalVisProp('az.pointer.speed')), 1838 deltaX, // = evt.movementX, 1839 deltaY, // = evt.movementY 1840 az = this.az_slide.Value(), 1841 el = this.el_slide.Value(); 1842 1843 deltaX = evt.screenX - this._lastPos.x; 1844 this._lastPos.x = evt.screenX; 1845 deltaY = evt.screenY - this._lastPos.y; 1846 this._lastPos.y = evt.screenY; 1847 1848 // Doesn't allow navigation if another moving event is triggered 1849 if (this.board.mode === this.board.BOARD_MODE_DRAG || !this.board._change3DView) { 1850 return this; 1851 } 1852 1853 if (this.evalVisProp('az.pointer.enabled') && (deltaX !== 0) && evt.key == null) { 1854 // delta *= (Math.abs(delta) > 100) ? 0.03 : 1; 1855 az += deltaX * speed; 1856 } 1857 if (this.evalVisProp('el.pointer.enabled') && (deltaY !== 0) && evt.key == null) { 1858 el += deltaY * speed; 1859 } 1860 1861 // Project the calculated az value to a usable value in the interval [smin,smax] 1862 // Use modulo if continuous is true 1863 if (this.evalVisProp('az.continuous')) { 1864 az = Mat.wrap(az, smin, smax); 1865 } else { 1866 if (az > 0) { 1867 az = Math.min(smax, az); 1868 } else if (az < 0) { 1869 az = Math.max(smin, az); 1870 } 1871 } 1872 // Project the calculated el value to a usable value in the interval [smin,smax] 1873 // Use modulo if continuous is true and the trackball is disabled 1874 smax = this.el_slide._smax; 1875 smin = this.el_slide._smin; 1876 if (this.evalVisProp('el.continuous') && !this.trackballEnabled) { 1877 el = Mat.wrap(el, smin, smax); 1878 } else { 1879 if (el > 0) { 1880 el = Math.min(smax, el); 1881 } else if (el < 0) { 1882 el = Math.max(smin, el); 1883 } 1884 } 1885 1886 this.setView(az, el); 1887 return this; 1888 }, 1889 1890 /** 1891 * Controls the navigation in az direction using either the keyboard or a pointer. 1892 * 1893 * @private 1894 * 1895 * @param {event} evt either the keydown or the pointer event 1896 * @returns view 1897 */ 1898 _azEventHandler: function (evt) { 1899 var smax = this.az_slide._smax, 1900 smin = this.az_slide._smin, 1901 speed = (smax - smin) / this.board.canvasWidth * (this.evalVisProp('az.pointer.speed')), 1902 delta, // = evt.movementX, 1903 az = this.az_slide.Value(), 1904 el = this.el_slide.Value(); 1905 1906 delta = evt.screenX - this._lastPos.x; 1907 this._lastPos.x = evt.screenX; 1908 1909 // Doesn't allow navigation if another moving event is triggered 1910 if (this.board.mode === this.board.BOARD_MODE_DRAG || !this.board._change3DView) { 1911 return this; 1912 } 1913 1914 // Calculate new az value if keyboard events are triggered 1915 // Plus if right-button, minus if left-button 1916 if (this.evalVisProp('az.keyboard.enabled')) { 1917 if (evt.key === 'ArrowRight') { 1918 az = az + this.evalVisProp('az.keyboard.step') * Math.PI / 180; 1919 } else if (evt.key === 'ArrowLeft') { 1920 az = az - this.evalVisProp('az.keyboard.step') * Math.PI / 180; 1921 } 1922 } 1923 1924 if (this.evalVisProp('az.pointer.enabled') && (delta !== 0) && evt.key == null) { 1925 // delta *= (Math.abs(delta) > 100) ? 0.03 : 1; 1926 az += delta * speed; 1927 } 1928 1929 // Project the calculated az value to a usable value in the interval [smin,smax] 1930 // Use modulo if continuous is true 1931 if (this.evalVisProp('az.continuous')) { 1932 az = Mat.wrap(az, smin, smax); 1933 } else { 1934 if (az > 0) { 1935 az = Math.min(smax, az); 1936 } else if (az < 0) { 1937 az = Math.max(smin, az); 1938 } 1939 } 1940 1941 this.setView(az, el); 1942 return this; 1943 }, 1944 1945 /** 1946 * Controls the navigation in el direction using either the keyboard or a pointer. 1947 * 1948 * @private 1949 * 1950 * @param {event} evt either the keydown or the pointer event 1951 * @returns view 1952 */ 1953 _elEventHandler: function (evt) { 1954 var smax = this.el_slide._smax, 1955 smin = this.el_slide._smin, 1956 speed = (smax - smin) / this.board.canvasHeight * this.evalVisProp('el.pointer.speed'), 1957 delta, // = evt.movementY, 1958 az = this.az_slide.Value(), 1959 el = this.el_slide.Value(); 1960 1961 delta = evt.screenY - this._lastPos.y; 1962 this._lastPos.y = evt.screenY; 1963 1964 // Doesn't allow navigation if another moving event is triggered 1965 if (this.board.mode === this.board.BOARD_MODE_DRAG || !this.board._change3DView) { 1966 return this; 1967 } 1968 1969 // Calculate new az value if keyboard events are triggered 1970 // Plus if down-button, minus if up-button 1971 if (this.evalVisProp('el.keyboard.enabled')) { 1972 if (evt.key === 'ArrowUp') { 1973 el = el - this.evalVisProp('el.keyboard.step') * Math.PI / 180; 1974 } else if (evt.key === 'ArrowDown') { 1975 el = el + this.evalVisProp('el.keyboard.step') * Math.PI / 180; 1976 } 1977 } 1978 1979 if (this.evalVisProp('el.pointer.enabled') && (delta !== 0) && evt.key == null) { 1980 // delta *= (Math.abs(delta) > 100) ? 0.05 : 1; 1981 el += delta * speed; 1982 } 1983 1984 // Project the calculated el value to a usable value in the interval [smin,smax] 1985 // Use modulo if continuous is true and the trackball is disabled 1986 if (this.evalVisProp('el.continuous') && !this.trackballEnabled) { 1987 el = Mat.wrap(el, smin, smax); 1988 } else { 1989 if (el > 0) { 1990 el = Math.min(smax, el); 1991 } else if (el < 0) { 1992 el = Math.max(smin, el); 1993 } 1994 } 1995 1996 this.setView(az, el); 1997 1998 return this; 1999 }, 2000 2001 /** 2002 * Controls the navigation in bank direction using either the keyboard or a pointer. 2003 * 2004 * @private 2005 * 2006 * @param {event} evt either the keydown or the pointer event 2007 * @returns view 2008 */ 2009 _bankEventHandler: function (evt) { 2010 var smax = this.bank_slide._smax, 2011 smin = this.bank_slide._smin, 2012 step, speed, 2013 delta = evt.deltaY, // Wheel event 2014 bank = this.bank_slide.Value(); 2015 2016 // Doesn't allow navigation if another moving event is triggered 2017 if (this.board.mode === this.board.BOARD_MODE_DRAG || !this.board._change3DView) { 2018 return this; 2019 } 2020 2021 // Calculate new bank value if keyboard events are triggered 2022 // Plus if down-button, minus if up-button 2023 if (this.evalVisProp('bank.keyboard.enabled')) { 2024 step = this.evalVisProp('bank.keyboard.step') * Math.PI / 180; 2025 if (evt.key === '.' || evt.key === '<') { 2026 bank -= step; 2027 } else if (evt.key === ',' || evt.key === '>') { 2028 bank += step; 2029 } 2030 } 2031 2032 if (this.evalVisProp('bank.pointer.enabled') && (delta !== 0) && evt.key == null) { 2033 speed = (smax - smin) / this.board.canvasHeight * this.evalVisProp('bank.pointer.speed'); 2034 bank += delta * speed; 2035 2036 // prevent the pointer wheel from scrolling the page 2037 evt.preventDefault(); 2038 } 2039 2040 // Project the calculated bank value to a usable value in the interval [smin,smax] 2041 if (this.evalVisProp('bank.continuous')) { 2042 // in continuous mode, wrap value around slider range 2043 bank = Mat.wrap(bank, smin, smax); 2044 } else { 2045 // in non-continuous mode, clamp value to slider range 2046 bank = Mat.clamp(bank, smin, smax); 2047 } 2048 2049 this.bank_slide.setValue(bank); 2050 this.board.update(); 2051 return this; 2052 }, 2053 2054 /** 2055 * Controls the navigation using either virtual trackball. 2056 * 2057 * @private 2058 * 2059 * @param {event} evt either the keydown or the pointer event 2060 * @returns view 2061 */ 2062 _trackballHandler: function (evt) { 2063 var pos = this.board.getMousePosition(evt), 2064 x, y, dx, dy, center; 2065 2066 center = new Coords(Const.COORDS_BY_USER, [this.llftCorner[0] + this.size[0] * 0.5, this.llftCorner[1] + this.size[1] * 0.5], this.board); 2067 x = pos[0] - center.scrCoords[1]; 2068 y = pos[1] - center.scrCoords[2]; 2069 2070 dx = evt.screenX - this._lastPos.x; 2071 dy = evt.screenY - this._lastPos.y; 2072 this._lastPos.x = evt.screenX; 2073 this._lastPos.y = evt.screenY; 2074 2075 this._trackball = { 2076 dx: dx, 2077 dy: -dy, 2078 x: x, 2079 y: -y 2080 }; 2081 this.board.update(); 2082 return this; 2083 }, 2084 2085 /** 2086 * Event handler for pointer down event. Triggers handling of all 3D navigation. 2087 * 2088 * @private 2089 * @param {event} evt 2090 * @returns view 2091 */ 2092 pointerDownHandler: function (evt) { 2093 var neededButton, neededKey, target; 2094 2095 this._hasMoveAzEl = false; 2096 this._hasMoveAz = false; 2097 this._hasMoveEl = false; 2098 this._hasMoveBank = false; 2099 this._hasMoveTrackball = false; 2100 2101 if (this.board.mode !== this.board.BOARD_MODE_NONE) { 2102 return; 2103 } 2104 2105 this.board._change3DView = true; 2106 2107 this._lastPos.x = evt.screenX; 2108 this._lastPos.y = evt.screenY; 2109 2110 if (this.evalVisProp('trackball.enabled')) { 2111 neededButton = this.evalVisProp('trackball.button'); 2112 neededKey = this.evalVisProp('trackball.key'); 2113 2114 // Move events for virtual trackball 2115 if ( 2116 (neededButton === -1 || neededButton === evt.button) && 2117 (neededKey === 'none' || (neededKey.indexOf('shift') > -1 && evt.shiftKey) || (neededKey.indexOf('ctrl') > -1 && evt.ctrlKey)) 2118 ) { 2119 // If outside is true then the event listener is bound to the document, otherwise to the div 2120 target = (this.evalVisProp('trackball.outside')) ? document : this.board.containerObj; 2121 Env.addEvent(target, 'pointermove', this._trackballHandler, this); 2122 this._hasMoveTrackball = true; 2123 } 2124 } else { 2125 if (this.evalVisProp('az.pointer.enabled') && this.evalVisProp('el.pointer.enabled')) { 2126 neededButton = this.evalVisProp('az.pointer.button'); 2127 neededKey = this.evalVisProp('az.pointer.key'); 2128 if (neededButton === this.evalVisProp('el.pointer.button') && 2129 neededKey === this.evalVisProp('el.pointer.key')) { 2130 2131 // Move events for azimuth and elevation 2132 if ( 2133 (neededButton === -1 || neededButton === evt.button) && 2134 (neededKey === 'none' || (neededKey.indexOf('shift') > -1 && evt.shiftKey) || 2135 (neededKey.indexOf('ctrl') > -1 && evt.ctrlKey)) 2136 ) { 2137 // If outside is true then the event listener is bound to the document, otherwise to the div 2138 target = (this.evalVisProp('az.pointer.outside')) ? document : this.board.containerObj; 2139 2140 if (target === ((this.evalVisProp('el.pointer.outside')) ? document : this.board.containerObj)) { 2141 Env.addEvent(target, 'pointermove', this._az_elEventHandler, this); 2142 this._hasMoveAzEl = true; 2143 } 2144 } 2145 } 2146 } 2147 if (!this._hasMoveAzEl) { 2148 if (this.evalVisProp('az.pointer.enabled')) { 2149 neededButton = this.evalVisProp('az.pointer.button'); 2150 neededKey = this.evalVisProp('az.pointer.key'); 2151 2152 // Move events for azimuth 2153 if ( 2154 (neededButton === -1 || neededButton === evt.button) && 2155 (neededKey === 'none' || (neededKey.indexOf('shift') > -1 && evt.shiftKey) || (neededKey.indexOf('ctrl') > -1 && evt.ctrlKey)) 2156 ) { 2157 // If outside is true then the event listener is bound to the document, otherwise to the div 2158 target = (this.evalVisProp('az.pointer.outside')) ? document : this.board.containerObj; 2159 Env.addEvent(target, 'pointermove', this._azEventHandler, this); 2160 this._hasMoveAz = true; 2161 } 2162 } 2163 2164 if (this.evalVisProp('el.pointer.enabled')) { 2165 neededButton = this.evalVisProp('el.pointer.button'); 2166 neededKey = this.evalVisProp('el.pointer.key'); 2167 2168 // Events for elevation 2169 if ( 2170 (neededButton === -1 || neededButton === evt.button) && 2171 (neededKey === 'none' || (neededKey.indexOf('shift') > -1 && evt.shiftKey) || (neededKey.indexOf('ctrl') > -1 && evt.ctrlKey)) 2172 ) { 2173 // If outside is true then the event listener is bound to the document, otherwise to the div 2174 target = (this.evalVisProp('el.pointer.outside')) ? document : this.board.containerObj; 2175 Env.addEvent(target, 'pointermove', this._elEventHandler, this); 2176 this._hasMoveEl = true; 2177 } 2178 } 2179 } 2180 if (this.evalVisProp('bank.pointer.enabled')) { 2181 neededButton = this.evalVisProp('bank.pointer.button'); 2182 neededKey = this.evalVisProp('bank.pointer.key'); 2183 2184 // Events for bank 2185 if ( 2186 (neededButton === -1 || neededButton === evt.button) && 2187 (neededKey === 'none' || (neededKey.indexOf('shift') > -1 && evt.shiftKey) || (neededKey.indexOf('ctrl') > -1 && evt.ctrlKey)) 2188 ) { 2189 // If `outside` is true, we bind the event listener to 2190 // the document. otherwise, we bind it to the div. we 2191 // register the event listener as active so it can 2192 // prevent the pointer wheel from scrolling the page 2193 target = (this.evalVisProp('bank.pointer.outside')) ? document : this.board.containerObj; 2194 Env.addEvent(target, 'wheel', this._bankEventHandler, this, { passive: false }); 2195 this._hasMoveBank = true; 2196 } 2197 } 2198 } 2199 Env.addEvent(document, 'pointerup', this.pointerUpHandler, this); 2200 }, 2201 2202 /** 2203 * Event handler for pointer up event. Triggers handling of all 3D navigation. 2204 * 2205 * @private 2206 * @param {event} evt 2207 * @returns view 2208 */ 2209 pointerUpHandler: function (evt) { 2210 var target; 2211 2212 if (this._hasMoveAzEl) { 2213 target = (this.evalVisProp('az.pointer.outside')) ? document : this.board.containerObj; 2214 Env.removeEvent(target, 'pointermove', this._az_elEventHandler, this); 2215 this._hasMoveAzEl = false; 2216 } 2217 if (this._hasMoveAz) { 2218 target = (this.evalVisProp('az.pointer.outside')) ? document : this.board.containerObj; 2219 Env.removeEvent(target, 'pointermove', this._azEventHandler, this); 2220 this._hasMoveAz = false; 2221 } 2222 if (this._hasMoveEl) { 2223 target = (this.evalVisProp('el.pointer.outside')) ? document : this.board.containerObj; 2224 Env.removeEvent(target, 'pointermove', this._elEventHandler, this); 2225 this._hasMoveEl = false; 2226 } 2227 if (this._hasMoveBank) { 2228 target = (this.evalVisProp('bank.pointer.outside')) ? document : this.board.containerObj; 2229 Env.removeEvent(target, 'wheel', this._bankEventHandler, this); 2230 this._hasMoveBank = false; 2231 } 2232 if (this._hasMoveTrackball) { 2233 target = (this.evalVisProp('trackball.outside')) ? document : this.board.containerObj; 2234 Env.removeEvent(target, 'pointermove', this._trackballHandler, this); 2235 this._hasMoveTrackball = false; 2236 } 2237 Env.removeEvent(document, 'pointerup', this.pointerUpHandler, this); 2238 this.board._change3DView = false; 2239 this.board.mode = this.board.BOARD_MODE_NONE; 2240 } 2241 }); 2242 2243 /** 2244 * @class A View3D element provides the container and the methods to create and display 3D elements. 2245 * @pseudo 2246 * @description A View3D element provides the container and the methods to create and display 3D elements. 2247 * It is contained in a JSXGraph board. 2248 * <p> 2249 * It is advisable to disable panning of the board by setting the board attribute "pan": 2250 * <pre> 2251 * pan: {enabled: false} 2252 * </pre> 2253 * Otherwise users will not be able to rotate the scene with their fingers on a touch device. 2254 * <p> 2255 * The start position of the camera can be adjusted by the attributes {@link View3D#az}, {@link View3D#el}, and {@link View3D#bank}. 2256 * 2257 * @name View3D 2258 * @augments JXG.View3D 2259 * @constructor 2260 * @type Object 2261 * @throws {Exception} If the element cannot be constructed with the given parent objects an exception is thrown. 2262 * @param {Array_Array_Array} lower,dim,cube Here, lower is an array of the form [x, y] and 2263 * dim is an array of the form [w, h]. 2264 * The arrays [x, y] and [w, h] define the 2D frame into which the 3D cube is 2265 * (roughly) projected. If the view's azimuth=0 and elevation=0, the 3D view will cover a rectangle with lower left corner 2266 * [x,y] and side lengths [w, h] of the board. 2267 * The array 'cube' is of the form [[x1, x2], [y1, y2], [z1, z2]] 2268 * which determines the coordinate ranges of the 3D cube. 2269 * 2270 * @example 2271 * var bound = [-4, 6]; 2272 * var view = board.create('view3d', 2273 * [[-4, -3], [8, 8], 2274 * [bound, bound, bound]], 2275 * { 2276 * projection: 'parallel', 2277 * trackball: {enabled:true}, 2278 * }); 2279 * 2280 * var curve = view.create('curve3d', [ 2281 * (t) => (2 + Math.cos(3 * t)) * Math.cos(2 * t), 2282 * (t) => (2 + Math.cos(3 * t)) * Math.sin(2 * t), 2283 * (t) => Math.sin(3 * t), 2284 * [-Math.PI, Math.PI] 2285 * ], { strokeWidth: 4 }); 2286 * 2287 * </pre><div id="JXG9b327a6c-1bd6-4e40-a502-59d024dbfd1b" class="jxgbox" style="width: 300px; height: 300px;"></div> 2288 * <script type="text/javascript"> 2289 * (function() { 2290 * var board = JXG.JSXGraph.initBoard('JXG9b327a6c-1bd6-4e40-a502-59d024dbfd1b', 2291 * {boundingbox: [-8, 8, 8,-8], pan: {enabled: false}, axis: false, showcopyright: false, shownavigation: false}); 2292 * var bound = [-4, 6]; 2293 * var view = board.create('view3d', 2294 * [[-4, -3], [8, 8], 2295 * [bound, bound, bound]], 2296 * { 2297 * projection: 'parallel', 2298 * trackball: {enabled:true}, 2299 * }); 2300 * 2301 * var curve = view.create('curve3d', [ 2302 * (t) => (2 + Math.cos(3 * t)) * Math.cos(2 * t), 2303 * (t) => (2 + Math.cos(3 * t)) * Math.sin(2 * t), 2304 * (t) => Math.sin(3 * t), 2305 * [-Math.PI, Math.PI] 2306 * ], { strokeWidth: 4 }); 2307 * 2308 * })(); 2309 * 2310 * </script><pre> 2311 * 2312 * @example 2313 * var bound = [-4, 6]; 2314 * var view = board.create('view3d', 2315 * [[-4, -3], [8, 8], 2316 * [bound, bound, bound]], 2317 * { 2318 * projection: 'central', 2319 * trackball: {enabled:true}, 2320 * 2321 * xPlaneRear: { visible: false }, 2322 * yPlaneRear: { visible: false } 2323 * 2324 * }); 2325 * 2326 * var curve = view.create('curve3d', [ 2327 * (t) => (2 + Math.cos(3 * t)) * Math.cos(2 * t), 2328 * (t) => (2 + Math.cos(3 * t)) * Math.sin(2 * t), 2329 * (t) => Math.sin(3 * t), 2330 * [-Math.PI, Math.PI] 2331 * ], { strokeWidth: 4 }); 2332 * 2333 * </pre><div id="JXG0dc2493d-fb2f-40d5-bdb8-762ba0ad2007" class="jxgbox" style="width: 300px; height: 300px;"></div> 2334 * <script type="text/javascript"> 2335 * (function() { 2336 * var board = JXG.JSXGraph.initBoard('JXG0dc2493d-fb2f-40d5-bdb8-762ba0ad2007', 2337 * {boundingbox: [-8, 8, 8,-8], axis: false, pan: {enabled: false}, showcopyright: false, shownavigation: false}); 2338 * var bound = [-4, 6]; 2339 * var view = board.create('view3d', 2340 * [[-4, -3], [8, 8], 2341 * [bound, bound, bound]], 2342 * { 2343 * projection: 'central', 2344 * trackball: {enabled:true}, 2345 * 2346 * xPlaneRear: { visible: false }, 2347 * yPlaneRear: { visible: false } 2348 * 2349 * }); 2350 * 2351 * var curve = view.create('curve3d', [ 2352 * (t) => (2 + Math.cos(3 * t)) * Math.cos(2 * t), 2353 * (t) => (2 + Math.cos(3 * t)) * Math.sin(2 * t), 2354 * (t) => Math.sin(3 * t), 2355 * [-Math.PI, Math.PI] 2356 * ], { strokeWidth: 4 }); 2357 * 2358 * })(); 2359 * 2360 * </script><pre> 2361 * 2362 * @example 2363 * var bound = [-4, 6]; 2364 * var view = board.create('view3d', 2365 * [[-4, -3], [8, 8], 2366 * [bound, bound, bound]], 2367 * { 2368 * projection: 'central', 2369 * trackball: {enabled:true}, 2370 * 2371 * // Main axes 2372 * axesPosition: 'border', 2373 * 2374 * // Axes at the border 2375 * xAxisBorder: { ticks3d: { ticksDistance: 2} }, 2376 * yAxisBorder: { ticks3d: { ticksDistance: 2} }, 2377 * zAxisBorder: { ticks3d: { ticksDistance: 2} }, 2378 * 2379 * // No axes on planes 2380 * xPlaneRearYAxis: {visible: false}, 2381 * xPlaneRearZAxis: {visible: false}, 2382 * yPlaneRearXAxis: {visible: false}, 2383 * yPlaneRearZAxis: {visible: false}, 2384 * zPlaneRearXAxis: {visible: false}, 2385 * zPlaneRearYAxis: {visible: false} 2386 * }); 2387 * 2388 * var curve = view.create('curve3d', [ 2389 * (t) => (2 + Math.cos(3 * t)) * Math.cos(2 * t), 2390 * (t) => (2 + Math.cos(3 * t)) * Math.sin(2 * t), 2391 * (t) => Math.sin(3 * t), 2392 * [-Math.PI, Math.PI] 2393 * ], { strokeWidth: 4 }); 2394 * 2395 * </pre><div id="JXG586f3551-335c-47e9-8d72-835409f6a103" class="jxgbox" style="width: 300px; height: 300px;"></div> 2396 * <script type="text/javascript"> 2397 * (function() { 2398 * var board = JXG.JSXGraph.initBoard('JXG586f3551-335c-47e9-8d72-835409f6a103', 2399 * {boundingbox: [-8, 8, 8,-8], axis: false, pan: {enabled: false}, showcopyright: false, shownavigation: false}); 2400 * var bound = [-4, 6]; 2401 * var view = board.create('view3d', 2402 * [[-4, -3], [8, 8], 2403 * [bound, bound, bound]], 2404 * { 2405 * projection: 'central', 2406 * trackball: {enabled:true}, 2407 * 2408 * // Main axes 2409 * axesPosition: 'border', 2410 * 2411 * // Axes at the border 2412 * xAxisBorder: { ticks3d: { ticksDistance: 2} }, 2413 * yAxisBorder: { ticks3d: { ticksDistance: 2} }, 2414 * zAxisBorder: { ticks3d: { ticksDistance: 2} }, 2415 * 2416 * // No axes on planes 2417 * xPlaneRearYAxis: {visible: false}, 2418 * xPlaneRearZAxis: {visible: false}, 2419 * yPlaneRearXAxis: {visible: false}, 2420 * yPlaneRearZAxis: {visible: false}, 2421 * zPlaneRearXAxis: {visible: false}, 2422 * zPlaneRearYAxis: {visible: false} 2423 * }); 2424 * 2425 * var curve = view.create('curve3d', [ 2426 * (t) => (2 + Math.cos(3 * t)) * Math.cos(2 * t), 2427 * (t) => (2 + Math.cos(3 * t)) * Math.sin(2 * t), 2428 * (t) => Math.sin(3 * t), 2429 * [-Math.PI, Math.PI] 2430 * ], { strokeWidth: 4 }); 2431 * 2432 * })(); 2433 * 2434 * </script><pre> 2435 * 2436 * @example 2437 * var bound = [-4, 6]; 2438 * var view = board.create('view3d', 2439 * [[-4, -3], [8, 8], 2440 * [bound, bound, bound]], 2441 * { 2442 * projection: 'central', 2443 * trackball: {enabled:true}, 2444 * 2445 * axesPosition: 'none' 2446 * }); 2447 * 2448 * var curve = view.create('curve3d', [ 2449 * (t) => (2 + Math.cos(3 * t)) * Math.cos(2 * t), 2450 * (t) => (2 + Math.cos(3 * t)) * Math.sin(2 * t), 2451 * (t) => Math.sin(3 * t), 2452 * [-Math.PI, Math.PI] 2453 * ], { strokeWidth: 4 }); 2454 * 2455 * </pre><div id="JXG9a9467e1-f189-4c8c-adb2-d4f49bc7fa26" class="jxgbox" style="width: 300px; height: 300px;"></div> 2456 * <script type="text/javascript"> 2457 * (function() { 2458 * var board = JXG.JSXGraph.initBoard('JXG9a9467e1-f189-4c8c-adb2-d4f49bc7fa26', 2459 * {boundingbox: [-8, 8, 8,-8], axis: false, pan: {enabled: false}, showcopyright: false, shownavigation: false}); 2460 * var bound = [-4, 6]; 2461 * var view = board.create('view3d', 2462 * [[-4, -3], [8, 8], 2463 * [bound, bound, bound]], 2464 * { 2465 * projection: 'central', 2466 * trackball: {enabled:true}, 2467 * 2468 * axesPosition: 'none' 2469 * }); 2470 * 2471 * var curve = view.create('curve3d', [ 2472 * (t) => (2 + Math.cos(3 * t)) * Math.cos(2 * t), 2473 * (t) => (2 + Math.cos(3 * t)) * Math.sin(2 * t), 2474 * (t) => Math.sin(3 * t), 2475 * [-Math.PI, Math.PI] 2476 * ], { strokeWidth: 4 }); 2477 * 2478 * })(); 2479 * 2480 * </script><pre> 2481 * 2482 * @example 2483 * var bound = [-4, 6]; 2484 * var view = board.create('view3d', 2485 * [[-4, -3], [8, 8], 2486 * [bound, bound, bound]], 2487 * { 2488 * projection: 'central', 2489 * trackball: {enabled:true}, 2490 * 2491 * // Main axes 2492 * axesPosition: 'border', 2493 * 2494 * // Axes at the border 2495 * xAxisBorder: { ticks3d: { ticksDistance: 2} }, 2496 * yAxisBorder: { ticks3d: { ticksDistance: 2} }, 2497 * zAxisBorder: { ticks3d: { ticksDistance: 2} }, 2498 * 2499 * xPlaneRear: { 2500 * fillColor: '#fff', 2501 * mesh3d: {visible: false} 2502 * }, 2503 * yPlaneRear: { 2504 * fillColor: '#fff', 2505 * mesh3d: {visible: false} 2506 * }, 2507 * zPlaneRear: { 2508 * fillColor: '#fff', 2509 * mesh3d: {visible: false} 2510 * }, 2511 * xPlaneFront: { 2512 * visible: true, 2513 * fillColor: '#fff', 2514 * mesh3d: {visible: false} 2515 * }, 2516 * yPlaneFront: { 2517 * visible: true, 2518 * fillColor: '#fff', 2519 * mesh3d: {visible: false} 2520 * }, 2521 * zPlaneFront: { 2522 * visible: true, 2523 * fillColor: '#fff', 2524 * mesh3d: {visible: false} 2525 * }, 2526 * 2527 * // No axes on planes 2528 * xPlaneRearYAxis: {visible: false}, 2529 * xPlaneRearZAxis: {visible: false}, 2530 * yPlaneRearXAxis: {visible: false}, 2531 * yPlaneRearZAxis: {visible: false}, 2532 * zPlaneRearXAxis: {visible: false}, 2533 * zPlaneRearYAxis: {visible: false}, 2534 * xPlaneFrontYAxis: {visible: false}, 2535 * xPlaneFrontZAxis: {visible: false}, 2536 * yPlaneFrontXAxis: {visible: false}, 2537 * yPlaneFrontZAxis: {visible: false}, 2538 * zPlaneFrontXAxis: {visible: false}, 2539 * zPlaneFrontYAxis: {visible: false} 2540 * 2541 * }); 2542 * 2543 * var curve = view.create('curve3d', [ 2544 * (t) => (2 + Math.cos(3 * t)) * Math.cos(2 * t), 2545 * (t) => (2 + Math.cos(3 * t)) * Math.sin(2 * t), 2546 * (t) => Math.sin(3 * t), 2547 * [-Math.PI, Math.PI] 2548 * ], { strokeWidth: 4 }); 2549 * 2550 * </pre><div id="JXGbd41a4e3-1bf7-4764-b675-98b01667103b" class="jxgbox" style="width: 300px; height: 300px;"></div> 2551 * <script type="text/javascript"> 2552 * (function() { 2553 * var board = JXG.JSXGraph.initBoard('JXGbd41a4e3-1bf7-4764-b675-98b01667103b', 2554 * {boundingbox: [-8, 8, 8,-8], axis: false, pan: {enabled: false}, showcopyright: false, shownavigation: false}); 2555 * var bound = [-4, 6]; 2556 * var view = board.create('view3d', 2557 * [[-4, -3], [8, 8], 2558 * [bound, bound, bound]], 2559 * { 2560 * projection: 'central', 2561 * trackball: {enabled:true}, 2562 * 2563 * // Main axes 2564 * axesPosition: 'border', 2565 * 2566 * // Axes at the border 2567 * xAxisBorder: { ticks3d: { ticksDistance: 2} }, 2568 * yAxisBorder: { ticks3d: { ticksDistance: 2} }, 2569 * zAxisBorder: { ticks3d: { ticksDistance: 2} }, 2570 * 2571 * xPlaneRear: { 2572 * fillColor: '#fff', 2573 * mesh3d: {visible: false} 2574 * }, 2575 * yPlaneRear: { 2576 * fillColor: '#fff', 2577 * mesh3d: {visible: false} 2578 * }, 2579 * zPlaneRear: { 2580 * fillColor: '#fff', 2581 * mesh3d: {visible: false} 2582 * }, 2583 * xPlaneFront: { 2584 * visible: true, 2585 * fillColor: '#fff', 2586 * mesh3d: {visible: false} 2587 * }, 2588 * yPlaneFront: { 2589 * visible: true, 2590 * fillColor: '#fff', 2591 * mesh3d: {visible: false} 2592 * }, 2593 * zPlaneFront: { 2594 * visible: true, 2595 * fillColor: '#fff', 2596 * mesh3d: {visible: false} 2597 * }, 2598 * 2599 * // No axes on planes 2600 * xPlaneRearYAxis: {visible: false}, 2601 * xPlaneRearZAxis: {visible: false}, 2602 * yPlaneRearXAxis: {visible: false}, 2603 * yPlaneRearZAxis: {visible: false}, 2604 * zPlaneRearXAxis: {visible: false}, 2605 * zPlaneRearYAxis: {visible: false}, 2606 * xPlaneFrontYAxis: {visible: false}, 2607 * xPlaneFrontZAxis: {visible: false}, 2608 * yPlaneFrontXAxis: {visible: false}, 2609 * yPlaneFrontZAxis: {visible: false}, 2610 * zPlaneFrontXAxis: {visible: false}, 2611 * zPlaneFrontYAxis: {visible: false} 2612 * 2613 * }); 2614 * 2615 * var curve = view.create('curve3d', [ 2616 * (t) => (2 + Math.cos(3 * t)) * Math.cos(2 * t), 2617 * (t) => (2 + Math.cos(3 * t)) * Math.sin(2 * t), 2618 * (t) => Math.sin(3 * t), 2619 * [-Math.PI, Math.PI] 2620 * ], { strokeWidth: 4 }); 2621 * })(); 2622 * 2623 * </script><pre> 2624 * 2625 * @example 2626 * var bound = [-5, 5]; 2627 * var view = board.create('view3d', 2628 * [[-6, -3], 2629 * [8, 8], 2630 * [bound, bound, bound]], 2631 * { 2632 * // Main axes 2633 * axesPosition: 'center', 2634 * xAxis: { strokeColor: 'blue', strokeWidth: 3}, 2635 * 2636 * // Planes 2637 * xPlaneRear: { fillColor: 'yellow', mesh3d: {visible: false}}, 2638 * yPlaneFront: { visible: true, fillColor: 'blue'}, 2639 * 2640 * // Axes on planes 2641 * xPlaneRearYAxis: {strokeColor: 'red'}, 2642 * xPlaneRearZAxis: {strokeColor: 'red'}, 2643 * 2644 * yPlaneFrontXAxis: {strokeColor: 'blue'}, 2645 * yPlaneFrontZAxis: {strokeColor: 'blue'}, 2646 * 2647 * zPlaneFrontXAxis: {visible: false}, 2648 * zPlaneFrontYAxis: {visible: false} 2649 * }); 2650 * 2651 * </pre><div id="JXGdd06d90e-be5d-4531-8f0b-65fc30b1a7c7" class="jxgbox" style="width: 500px; height: 500px;"></div> 2652 * <script type="text/javascript"> 2653 * (function() { 2654 * var board = JXG.JSXGraph.initBoard('JXGdd06d90e-be5d-4531-8f0b-65fc30b1a7c7', 2655 * {boundingbox: [-8, 8, 8,-8], axis: false, pan: {enabled: false}, showcopyright: false, shownavigation: false}); 2656 * var bound = [-5, 5]; 2657 * var view = board.create('view3d', 2658 * [[-6, -3], [8, 8], 2659 * [bound, bound, bound]], 2660 * { 2661 * // Main axes 2662 * axesPosition: 'center', 2663 * xAxis: { strokeColor: 'blue', strokeWidth: 3}, 2664 * // Planes 2665 * xPlaneRear: { fillColor: 'yellow', mesh3d: {visible: false}}, 2666 * yPlaneFront: { visible: true, fillColor: 'blue'}, 2667 * // Axes on planes 2668 * xPlaneRearYAxis: {strokeColor: 'red'}, 2669 * xPlaneRearZAxis: {strokeColor: 'red'}, 2670 * yPlaneFrontXAxis: {strokeColor: 'blue'}, 2671 * yPlaneFrontZAxis: {strokeColor: 'blue'}, 2672 * zPlaneFrontXAxis: {visible: false}, 2673 * zPlaneFrontYAxis: {visible: false} 2674 * }); 2675 * })(); 2676 * 2677 * </script><pre> 2678 * @example 2679 * var bound = [-5, 5]; 2680 * var view = board.create('view3d', 2681 * [[-6, -3], [8, 8], 2682 * [bound, bound, bound]], 2683 * { 2684 * projection: 'central', 2685 * az: { 2686 * slider: { 2687 * visible: true, 2688 * point1: { 2689 * pos: [5, -4] 2690 * }, 2691 * point2: { 2692 * pos: [5, 4] 2693 * }, 2694 * label: {anchorX: 'middle'} 2695 * } 2696 * }, 2697 * el: { 2698 * slider: { 2699 * visible: true, 2700 * point1: { 2701 * pos: [6, -5] 2702 * }, 2703 * point2: { 2704 * pos: [6, 3] 2705 * }, 2706 * label: {anchorX: 'middle'} 2707 * } 2708 * }, 2709 * bank: { 2710 * slider: { 2711 * visible: true, 2712 * point1: { 2713 * pos: [7, -6] 2714 * }, 2715 * point2: { 2716 * pos: [7, 2] 2717 * }, 2718 * label: {anchorX: 'middle'} 2719 * } 2720 * } 2721 * }); 2722 * 2723 * 2724 * </pre><div id="JXGe181cc55-271b-419b-84fd-622326fd1d1a" class="jxgbox" style="width: 300px; height: 300px;"></div> 2725 * <script type="text/javascript"> 2726 * (function() { 2727 * var board = JXG.JSXGraph.initBoard('JXGe181cc55-271b-419b-84fd-622326fd1d1a', 2728 * {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false}); 2729 * var bound = [-5, 5]; 2730 * var view = board.create('view3d', 2731 * [[-6, -3], [8, 8], 2732 * [bound, bound, bound]], 2733 * { 2734 * projection: 'central', 2735 * az: { 2736 * slider: { 2737 * visible: true, 2738 * point1: { 2739 * pos: [5, -4] 2740 * }, 2741 * point2: { 2742 * pos: [5, 4] 2743 * }, 2744 * label: {anchorX: 'middle'} 2745 * } 2746 * }, 2747 * el: { 2748 * slider: { 2749 * visible: true, 2750 * point1: { 2751 * pos: [6, -5] 2752 * }, 2753 * point2: { 2754 * pos: [6, 3] 2755 * }, 2756 * label: {anchorX: 'middle'} 2757 * } 2758 * }, 2759 * bank: { 2760 * slider: { 2761 * visible: true, 2762 * point1: { 2763 * pos: [7, -6] 2764 * }, 2765 * point2: { 2766 * pos: [7, 2] 2767 * }, 2768 * label: {anchorX: 'middle'} 2769 * } 2770 * } 2771 * }); 2772 * 2773 * 2774 * })(); 2775 * 2776 * </script><pre> 2777 * 2778 * 2779 */ 2780 JXG.createView3D = function (board, parents, attributes) { 2781 var view, attr, attr_az, attr_el, attr_bank, 2782 x, y, w, h, 2783 p1, p2, v, 2784 coords = parents[0], // llft corner 2785 size = parents[1]; // [w, h] 2786 2787 attr = Type.copyAttributes(attributes, board.options, 'view3d'); 2788 view = new JXG.View3D(board, parents, attr); 2789 view.defaultAxes = view.create('axes3d', [], attr); 2790 2791 x = coords[0]; 2792 y = coords[1]; 2793 w = size[0]; 2794 h = size[1]; 2795 2796 attr_az = Type.copyAttributes(attr, board.options, 'view3d', 'az', 'slider'); 2797 attr_az.name = 'az'; 2798 2799 attr_el = Type.copyAttributes(attr, board.options, 'view3d', 'el', 'slider'); 2800 attr_el.name = 'el'; 2801 2802 attr_bank = Type.copyAttributes(attr, board.options, 'view3d', 'bank', 'slider'); 2803 attr_bank.name = 'bank'; 2804 2805 v = Type.evaluate(attr_az.point1.pos); 2806 if (!Type.isArray(v)) { 2807 // 'auto' 2808 p1 = [x - 1, y - 2]; 2809 } else { 2810 p1 = v; 2811 } 2812 v = Type.evaluate(attr_az.point2.pos); 2813 if (!Type.isArray(v)) { 2814 // 'auto' 2815 p2 = [x + w + 1, y - 2]; 2816 } else { 2817 p2 = v; 2818 } 2819 2820 /** 2821 * Slider to adapt azimuth angle 2822 * @name JXG.View3D#az_slide 2823 * @type {Slider} 2824 */ 2825 view.az_slide = board.create( 2826 'slider', 2827 [ 2828 p1, p2, 2829 [ 2830 Type.evaluate(attr_az.min), 2831 Type.evaluate(attr_az.start), 2832 Type.evaluate(attr_az.max) 2833 ] 2834 ], 2835 attr_az 2836 ); 2837 view.inherits.push(view.az_slide); 2838 view.az_slide.elType = 'view3d_slider'; // Used in board.prepareUpdate() 2839 2840 v = Type.evaluate(attr_el.point1.pos); 2841 if (!Type.isArray(v)) { 2842 // 'auto' 2843 p1 = [x - 1, y]; 2844 } else { 2845 p1 = v; 2846 } 2847 v = Type.evaluate(attr_el.point2.pos); 2848 if (!Type.isArray(v)) { 2849 // 'auto' 2850 p2 = [x - 1, y + h]; 2851 } else { 2852 p2 = v; 2853 } 2854 2855 /** 2856 * Slider to adapt elevation angle 2857 * 2858 * @name JXG.View3D#el_slide 2859 * @type {Slider} 2860 */ 2861 view.el_slide = board.create( 2862 'slider', 2863 [ 2864 p1, p2, 2865 [ 2866 Type.evaluate(attr_el.min), 2867 Type.evaluate(attr_el.start), 2868 Type.evaluate(attr_el.max)] 2869 ], 2870 attr_el 2871 ); 2872 view.inherits.push(view.el_slide); 2873 view.el_slide.elType = 'view3d_slider'; // Used in board.prepareUpdate() 2874 2875 v = Type.evaluate(attr_bank.point1.pos); 2876 if (!Type.isArray(v)) { 2877 // 'auto' 2878 p1 = [x - 1, y + h + 2]; 2879 } else { 2880 p1 = v; 2881 } 2882 v = Type.evaluate(attr_bank.point2.pos); 2883 if (!Type.isArray(v)) { 2884 // 'auto' 2885 p2 = [x + w + 1, y + h + 2]; 2886 } else { 2887 p2 = v; 2888 } 2889 2890 /** 2891 * Slider to adjust bank angle 2892 * 2893 * @name JXG.View3D#bank_slide 2894 * @type {Slider} 2895 */ 2896 view.bank_slide = board.create( 2897 'slider', 2898 [ 2899 p1, p2, 2900 [ 2901 Type.evaluate(attr_bank.min), 2902 Type.evaluate(attr_bank.start), 2903 Type.evaluate(attr_bank.max) 2904 ] 2905 ], 2906 attr_bank 2907 ); 2908 view.inherits.push(view.bank_slide); 2909 view.bank_slide.elType = 'view3d_slider'; // Used in board.prepareUpdate() 2910 2911 // Set special infobox attributes of view3d.infobox 2912 // Using setAttribute() is not possible here, since we have to 2913 // avoid a call of board.update(). 2914 // The drawback is that we can not use shortcuts 2915 view.board.infobox.visProp = Type.merge(view.board.infobox.visProp, attr.infobox); 2916 2917 // 3d infobox: drag direction and coordinates 2918 view.board.highlightInfobox = function (x, y, el) { 2919 var d, i, c3d, foot, 2920 pre = '', 2921 brd = el.board, 2922 arr, infobox, 2923 p = null; 2924 2925 if (this.mode === this.BOARD_MODE_DRAG) { 2926 // Drag direction is only shown during dragging 2927 if (view.isVerticalDrag()) { 2928 pre = '<span style="color:black; font-size:200%">\u21C5 </span>'; 2929 } else { 2930 pre = '<span style="color:black; font-size:200%">\u21C4 </span>'; 2931 } 2932 } 2933 2934 // Search 3D parent 2935 for (i = 0; i < el.parents.length; i++) { 2936 p = brd.objects[el.parents[i]]; 2937 if (p.is3D) { 2938 break; 2939 } 2940 } 2941 2942 if (p && Type.exists(p.element2D)) { 2943 foot = [1, 0, 0, p.coords[3]]; 2944 view._w0 = Mat.innerProduct(view.matrix3D[0], foot, 4); 2945 2946 c3d = view.project2DTo3DPlane(p.element2D, [1, 0, 0, 1], foot); 2947 if (!view.isInCube(c3d)) { 2948 view.board.highlightCustomInfobox('', p); 2949 return; 2950 } 2951 d = p.evalVisProp('infoboxdigits'); 2952 infobox = view.board.infobox; 2953 if (d === 'auto') { 2954 if (infobox.useLocale()) { 2955 arr = [pre, '(', infobox.formatNumberLocale(p.X()), ' | ', infobox.formatNumberLocale(p.Y()), ' | ', infobox.formatNumberLocale(p.Z()), ')']; 2956 } else { 2957 arr = [pre, '(', Type.autoDigits(p.X()), ' | ', Type.autoDigits(p.Y()), ' | ', Type.autoDigits(p.Z()), ')']; 2958 } 2959 2960 } else { 2961 if (infobox.useLocale()) { 2962 arr = [pre, '(', infobox.formatNumberLocale(p.X(), d), ' | ', infobox.formatNumberLocale(p.Y(), d), ' | ', infobox.formatNumberLocale(p.Z(), d), ')']; 2963 } else { 2964 arr = [pre, '(', Type.toFixed(p.X(), d), ' | ', Type.toFixed(p.Y(), d), ' | ', Type.toFixed(p.Z(), d), ')']; 2965 } 2966 } 2967 view.board.highlightCustomInfobox(arr.join(''), p); 2968 } else { 2969 view.board.highlightCustomInfobox('(' + x + ', ' + y + ')', el); 2970 } 2971 }; 2972 2973 // Hack needed to enable addEvent for view3D: 2974 view.BOARD_MODE_NONE = 0x0000; 2975 2976 // Add events for the keyboard navigation 2977 Env.addEvent(board.containerObj, 'keydown', function (event) { 2978 var neededKey, 2979 catchEvt = false; 2980 2981 // this.board._change3DView = true; 2982 if (view.evalVisProp('el.keyboard.enabled') && 2983 (event.key === 'ArrowUp' || event.key === 'ArrowDown') 2984 ) { 2985 neededKey = view.evalVisProp('el.keyboard.key'); 2986 if (neededKey === 'none' || 2987 (neededKey.indexOf('shift') > -1 && event.shiftKey) || 2988 (neededKey.indexOf('ctrl') > -1 && event.ctrlKey)) { 2989 view._elEventHandler(event); 2990 catchEvt = true; 2991 } 2992 2993 } 2994 2995 if (view.evalVisProp('az.keyboard.enabled') && 2996 (event.key === 'ArrowLeft' || event.key === 'ArrowRight') 2997 ) { 2998 neededKey = view.evalVisProp('az.keyboard.key'); 2999 if (neededKey === 'none' || 3000 (neededKey.indexOf('shift') > -1 && event.shiftKey) || 3001 (neededKey.indexOf('ctrl') > -1 && event.ctrlKey) 3002 ) { 3003 view._azEventHandler(event); 3004 catchEvt = true; 3005 } 3006 } 3007 3008 if (view.evalVisProp('bank.keyboard.enabled') && (event.key === ',' || event.key === '<' || event.key === '.' || event.key === '>')) { 3009 neededKey = view.evalVisProp('bank.keyboard.key'); 3010 if (neededKey === 'none' || (neededKey.indexOf('shift') > -1 && event.shiftKey) || (neededKey.indexOf('ctrl') > -1 && event.ctrlKey)) { 3011 view._bankEventHandler(event); 3012 catchEvt = true; 3013 } 3014 } 3015 3016 if (event.key === 'PageUp') { 3017 view.nextView(); 3018 catchEvt = true; 3019 } else if (event.key === 'PageDown') { 3020 view.previousView(); 3021 catchEvt = true; 3022 } 3023 3024 if (catchEvt) { 3025 // We stop event handling only in the case if the keypress could be 3026 // used for the 3D view. If this is not done, input fields et al 3027 // can not be used any more. 3028 event.preventDefault(); 3029 } 3030 this.board._change3DView = false; 3031 3032 }, view); 3033 3034 // Add events for the pointer navigation 3035 Env.addEvent(board.containerObj, 'pointerdown', view.pointerDownHandler, view); 3036 3037 // Initialize view rotation matrix 3038 view.getAnglesFromSliders(); 3039 view.matrix3DRot = view.getRotationFromAngles(); 3040 3041 // override angle slider bounds when trackball navigation is enabled 3042 view.updateAngleSliderBounds(); 3043 3044 view.board.update(); 3045 3046 return view; 3047 }; 3048 3049 JXG.registerElement("view3d", JXG.createView3D); 3050 3051 export default JXG.View3D; 3052