All files R3DMath.js

30.79% Statements 93/302
31.96% Branches 39/122
36.53% Functions 19/52
31.03% Lines 90/290

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782            1x   1x         9x     9x   2x 7x 3x   9x                                                                                                                                                                                                                                                                                                                                                                       5x 5x 5x 5x 5x 5x 5x   5x                 3x                                                                                                                                                                                                     5x                         8x 1x     7x 2x     5x 3x 3x 6x 6x 6x 3x     3x     2x 2x 2x                                                                                                                                               3x 1x 1x 1x 1x 2x 2x 2x 2x 2x   3x 3x   3x 3x   3x               2x                                           2x                 2x                                               1x                                                                               4x 4x   4x 4x 16x 16x 16x 16x   16x 16x 4x       4x                                                                                                                                                             5x         8x         4x                   3x 1x 2x 2x                     2x 1x 1x 1x                 2x 2x               6x 3x 3x     3x 3x 1x     2x 2x         2x                       2x 2x 2x 2x                                                                                                              
/* eslint-disable camelcase */
import * as THREE from 'three';
import { RandomColor } from 'ray-visutil/lib/ColorUtils';
import tools from './tools';
import R3DTools from './R3DTools';
 
const ThreeMath = THREE.Math;
 
const R3DMath = {
  ThreeMath,
  toInteger(n) {
    // 转化为 Number, +'1', +null (0)
    // +'a', +'1a', +undefined 均为 NaN
    n = +n;
    // NaN !== NaN -> true, 可用 n !== n 来判断 NaN
    // isNaN(NaN) -> true
    if (isNaN(n)) {
      // isNaN
      n = 0;
    } else if (n !== 0 && n !== 1 / 0 && n !== -(1 / 0)) {
      n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }
    return n;
  },
  clamp(value, min, max) {
    return ThreeMath.clamp(value, min, max);
  },
  /**
   * Returns a random number between min (inclusive) and max (exclusive)
   * 获取随机浮点数值[最小值, 最大值]
   * @param {Number} min 最小值
   * @param {Number} max 最大值
   * @return {Number}
   */
  randomFloat(min, max) {
    return Math.random() * (max - min) + min;
  },
  /**
   * Returns a random integer between min (inclusive) and x (inclusive)
   * Using Math.round() will give you a non-uniform distribution!
   * 获取随机整数数值[最小值, 最大值]
   * @param {Number} min 最小值
   * @param {Number} max 最大值
   * @return {Number}
   */
  randomInt(min, max) {
    const args = arguments;
    if (args.length === 0) {
      min = 0;
      max = 10;
    } else if (args.length === 1) {
      min = 0;
      max = args[0];
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },
  randomBoolean() {
    return !!(this.randomInt() % 2);
  },
  randomColorHex(){
    return RandomColor.hexColorStr();
  },
  /** 获取随机颜色, 返回 number 类型 */
  randomColor() {
    return RandomColor.intColor();
  },
  randomTColor() {
    const color = RandomColor.intColor();
    return new THREE.Color(color);
  },
 
  /** 从数组随机挑选出任一元素 */
  randomFromArray(arr) {
    const i = R3DMath.randomInt(0, arr.length - 1);
    return arr[i];
  },
  /**
   * 产生随机下标值 [0, number - 1]
   * @param {Number} number 总数
   * @return {Number}
   */
  randomIndex(number) {
    if (!number) {
      return 0;
    }
 
    return R3DMath.randomInt(0, number - 1);
  },
  /**
   * 随机产生坐标信息
   * @param {Number} rx? x 坐标会在[-rx, rx]之间进行随机
   * @param {Number} ry? y 坐标会在[-ry, ry]之间进行随机
   * @param {Number} rz? z 坐标会在[-rz, rz]之间进行随机
   * @return {Array<Number>}
   * @example
   * // xyz 会在 [-10, 10] 之间随机
   * R3DMath.randomVector3(10, 10, 10);
   * // 也可用如下的方式调用(xyz 用同一个数值)
   * R3DMath.randomVector3(10);
   */
  randomVector3(...args) {
    if (args.length === 1) {
      const range = args[0];
      const x = ThreeMath.randFloat(-range, range);
      const y = ThreeMath.randFloat(-range, range);
      const z = ThreeMath.randFloat(-range, range);
      return new THREE.Vector3(x, y, z);
    }
    // 只有两个参数时,表示  x - z 平面,y 值默认为 0
    else if (args.length === 2) {
      const rx = args[0];
      const rz = args[1];
      const x = ThreeMath.randFloat(-rx, rx);
      const z = ThreeMath.randFloat(-rz, rz);
      return new THREE.Vector3(x, 0, z);
    } else if (args.length === 3) {
      const rx = args[0];
      const ry = args[1];
      const rz = args[2];
      const x = ThreeMath.randFloat(-rx, rx);
      const y = ThreeMath.randFloat(-ry, ry);
      const z = ThreeMath.randFloat(-rz, rz);
      return new THREE.Vector3(x, y, z);
    }
  },
  /**
   * 随机 position
   * @param {*} max
   * @param {*} radius
   * @returns {Number[]}
   */
  randomPosition(max, radius) {
    const vec3 = R3DMath.randomVector3(max);
    // 同 vec3.normalize().multiplyScalar(radius || 1);
    vec3.setLength(radius || 1);
 
    return vec3.toArray();
  },
  /**
   * 随机产生 Vector2 坐标信息
   * @param {Number} rx? x 坐标会在[-rx, rx]之间进行随机
   * @param {Number} ry? y 坐标会在[-ry, ry]之间进行随机
   * @return {Array<Number>}
   * @example
   * // xy 会在 [-10, 10] 之间随机
   * R3DMath.randomVector2(10, 10);
   * // 也可用如下的方式调用(xy 用同一个数值)
   * R3DMath.randomVector2(10);
   */
  randomVector2(...args) {
    if (args.length === 1) {
      const range = args[0];
      const x = ThreeMath.randFloat(-range, range);
      const y = ThreeMath.randFloat(-range, range);
      return new THREE.Vector2(x, y);
    } else if (args.length === 2) {
      const rx = args[0];
      const ry = args[1];
      const x = ThreeMath.randFloat(-rx, rx);
      const y = ThreeMath.randFloat(-ry, ry);
      return new THREE.Vector2(x, y);
    }
    return new THREE.Vector2(ThreeMath.randFloat(0, 1), ThreeMath.randFloat(0, 1));
  },
 
  /**
   * 获取随机的 scale
   * @param {Number} modulus 模数, 0.5 表示取值为 [0.5, 1.5] 之间的数
   * @return {Number}
   */
  randomScale(modulus = 0.5){
    return Math.random() * Math.random() + modulus;
  },
 
  /**
   * 随机生成一系列点
   * @param {number} [count=5] 点集合总数, 除去默认 [0, 0, 0]
   * @param {number} [space=10] 每个点间距最大值,用于生成 offset 系数
   * @returns array
   */
  randomPoints(count = 5, space = 10) {
    const points = [[0, 0, 0]];
    let oldType = 2;
    for (let i = 0; i < count; i++) {
      const old = points[points.length - 1];
      let type = R3DMath.randomInt(100) % 3;
      while (oldType === type) {
        type = R3DMath.randomInt(100) % 3;
      }
      oldType = type;
      const offset = R3DMath.randomInt(1, space) * (Math.random() > 0.5 ? 1 : -1);
      points.push([type === 0 ? old[0] + offset : old[0], type === 1 ? old[1] + offset : old[1], type === 2 ? old[2] + offset : old[2]]);
    }
    return points;
  },
 
  /**
   * 向上取数值的2次幂
   * @param {Number} v 数值
   * @return {Number}
   */
  roundUpPowerOf2(v) {
    v--;
    v |= v >> 1;
    v |= v >> 2;
    v |= v >> 4;
    v |= v >> 8;
    v |= v >> 16;
    v++;
 
    return v;
  },
 
  /**
   * 返回小数部分
   * @param {Number} x 数值
   * @return {Number}
   */
  fract(x) {
    return x - Math.floor(x);
  },
 
  /**
   * 抛物线路径
   * @param {*} vecStart
   * @param {*} vecEnd
   * @returns
   */
  parabolaPath(vecStart, vecEnd) {
    const pathArr = [];
    const vec1 = R3DTools.parseNumber3(vecStart);
    const vec2 = R3DTools.parseNumber3(vecEnd);
 
    let start = R3DMath.addVector(vec1, vec2);
 
    start = R3DMath.scaleVector(start, 0.5);
    start[1] = R3DMath.getDistance(vec1, vec2) * 0.6;
 
    for (let i = 0; i < 1; i += 0.001) {
      const v1 = R3DMath.scaleVector(vec1, Math.pow(1 - i, 2));
      const v2 = R3DMath.scaleVector(start, 2 * i * (1 - i));
      const v3 = R3DMath.scaleVector(vec2, Math.pow(i, 2));
 
      const v4 = R3DMath.addVector(v1, v2);
      const point = R3DMath.addVector(v4, v3);
      pathArr.push(point);
    }
 
    return pathArr;
  },
  /**
   * 创建圆 路径
   *
   * @param {number} [radius=100]
   */
  createCirclePath(radius = 100) {
    const pathArr = [];
    for (let degree = 0; degree <= 360; degree += 10) {
      const x = Math.cos((degree * 2 * Math.PI) / 360) * radius;
      const z = Math.sin((degree * 2 * Math.PI) / 360) * radius;
      pathArr.push([x, 0, z]);
    }
 
    return pathArr;
  },
 
  /**
   * 创建圆形平面点
   * @param {*} center 中心点
   * @param {Number} radius 半径
   * @param {Number} spaceDegree 每个点间隔 默认 10
   * @param {Number} raiseHeight 提高高度
   */
  circlePlanePoints(center, radius = 100, raiseHeight = 0, spaceDegree = 10){
    center = R3DTools.parseNumber3(center, [0, 0, 0]);
    const pathArr = [];
    const planeCenter = [center[0], center[1] + raiseHeight, center[2]]; // 圆心世界坐标
    // 根据圆形和半径计算坐标点
    for (let degree = 0, y = 0; degree <= 360; degree += 10) {
      const x = Math.cos((degree * 2 * Math.PI) / 360) * radius;
      const z = Math.sin((degree * 2 * Math.PI) / 360) * radius;
      const pos = R3DMath.addVector([x, y, z], planeCenter);
      pathArr.push(pos);
    }
    return pathArr;
  },
  /**
   * 创建矩形平面点
   * @param {String|Array<Number>|Object|THREE.Vector3} center 中心点 如 `x,y,z`、`[x,y,z]`、{x, y, z}、、
   * @param {Number} width 矩形长
   * @param {Number} height 矩形宽
   * @param {Number} raiseHeight 提高高度
   */
  rectPlanePoints(center, width = 100, height = 100, raiseHeight = 0){
    center = R3DTools.parseNumber3(center, [0, 0, 0]);
    const pathArr = [];
    const [x, y, z] = [center[0], center[1] + raiseHeight, center[2]]; // 中心世界坐标
    const halfW = width / 2;
    const halfH = height / 2;
    // 根据圆形和半径计算坐标点
    const v1 = [x - halfW, y, z - halfH];
    const v2 = [x + halfW, y, z - halfH];
    const v3 = [x + halfW, y, z + halfH];
    const v4 = [x - halfW, y, z + halfH];
    pathArr.push(v1, v2, v3, v4);
    return pathArr;
  },
 
  /**
   * 线性插值
   * @param {Number} start 起始值
   * @param {Number} end 终止值
   * @param {Number} percent 百分比(0~1)
   * @return {Number}
   * @example
   * R3DMath.lerp(2,10,0.5) // 6
   */
  lerp(start, end, percent) {
    return start + percent * (end - start);
  },
 
  matrixLerp($from, to, time) {
    const ret = new THREE.Matrix4();
    for (let i = 0; i < 16; i++) {
      ret[i] = $from.elements[i] + (to.elements[i] - $from.elements[i]) * time;
    }
 
    return ret;
  },
 
  getArrayIndexFromProgress(array, progress, steps) {
    if (!array.length) {
      return -1;
    }
 
    if (progress >= 1) {
      return array.length - 1;
    }
 
    if (steps) {
      let curProgress = 0;
      for (let i = 0; i < steps.length; i++) {
        const step = steps[i];
        const endProgress = curProgress + step;
        if (endProgress >= progress) {
          return i;
        }
 
        curProgress += step;
      }
    } else {
      const step = 1 / array.length;
      const index = Math.floor(progress / step);
      return Math.min(index, array.length - 1);
    }
  },
 
  getArrayProgress(array, progress, steps) {
    if (!array.length) {
      return 0;
    }
 
    if (progress >= 1) {
      return 1;
    }
 
    if (steps) {
      let curProgress = 0;
      for (let i = 0; i < steps.length; i++) {
        const step = steps[i];
        const endProgress = curProgress + step;
        const deltaProgress = endProgress - progress;
        if (deltaProgress >= 0) {
          return 1 - deltaProgress / step;
        }
 
        curProgress += step;
      }
    } else {
      const step = 1 / array.length;
      return this.fract(progress / step);
    }
  },
 
  getConsumeTime(params = {}, defaultTime) {
    const { total, from: $from, to, distance, duration, speed, defaultTime: df } = params;
    // 如果使用了速度, 用速度计算消耗时间
    if (speed) {
      let d = distance;
      if (!distance) {
        const fromPos = tools.parseVector3([$from.x, $from.y, $from.z]);
        const toPos = tools.parseVector3([to.x, to.y, to.z]);
        d = fromPos.distanceTo(toPos);
      }
      return (d / speed) * 1000;
    }
    // 直接使用时间
    else if (duration !== undefined) {
      if (total) {
        return duration / total.length;
      } else {
        return duration;
      }
    }
    // 时间和速度都没有提供,那么就返回默认时间
    else {
      return defaultTime || df;
    }
  },
 
  /**
   * return the distance between two points.
   * 获取两点间距离
   *
   * @param {number} x1		x position of first point
   * @param {number} y1		y position of first point
   * @param {number} x2		x position of second point
   * @param {number} y2		y position of second point
   * @return {number} 		distance between given points
   */
  getDistance(...args) {
    let x1;
    let y1;
    let x2;
    let y2;
    if (args.length === 2) {
      x1 = args[0][0];
      y1 = args[0][1];
      x2 = args[1][0];
      y2 = args[1][1];
    } else Eif (args.length === 4) {
      x1 = args[0];
      y1 = args[1];
      x2 = args[2];
      y2 = args[3];
    }
    let xs = x2 - x1;
    let ys = y2 - y1;
 
    xs *= xs;
    ys *= ys;
 
    return Math.sqrt(xs + ys);
  },
 
  distance(...args) {
    return R3DMath.getDistance(args);
  },
 
  degToRad(degrees) {
    return ThreeMath.degToRad(degrees);
  },
 
  radToDeg(radians) {
    return ThreeMath.radToDeg(radians);
  },
  /**
   * 生成唯一的 UUID
   * @return {String}
   */
  generateUUID(simpilfy) {
    let uuid = ThreeMath.generateUUID();
    if (simpilfy) {
      uuid = uuid.replaceAll('-', '');
    }
    return uuid;
  },
  /**
   * 交换坐标 x, y 值
   * @param {Array<Number>} v 坐标
   */
  swapXY(v) {
    return [v[1], v[0]];
  },
  /**
   * 坐标相加
   * @param {Array<Number>} v1 坐标
   * @param {Array<Number>} v2 坐标
   * @return {Array<Number>}
   */
  addVector3(v1, v2) {
    return [v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2]];
  },
 
  /**
   * 坐标相加
   * @param {Array<Number>} v1 坐标
   * @param {Array<Number> | Number} v2 坐标 或 值
   * @return {Array<Number>}
   */
  addVector(v1, v2) {
    if (tools.isArray(v2)) {
      return [v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2]];
    } else if (tools.isNumber(v2)) {
      return [v1[0] + v2, v1[1] + v2, v1[2] + v2];
    }
  },
 
  /**
   * 坐标相减
   * @param {Array<Number>} v1 坐标
   * @param {Array<Number>} v2 坐标
   * @return {Array<Number>}
   */
  subVector3(v1, v2) {
    return [v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]];
  },
 
  /**
   * 坐标相减
   * @param {Array<Number>} v1 坐标
   * @param {Array<Number> | Number} v2 坐标 或 值
   * @return {Array<Number>}
   */
  subVector(v1, v2) {
    if (tools.isArray(v2)) {
      return [v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]];
    } else if (tools.isNumber(v2)) {
      return [v1[0] - v2, v1[1] - v2, v1[2] - v2];
    }
  },
 
  /**
   * 获取面积
   * @param {Array<Number>} positions 坐标列表
   * @return {Number}
   */
  getArea(positions) {
    const points = [];
    for (let i = 0, len = positions.length; i < len; i++) {
      points.push(R3DTools.parseVector3(positions[i]));
    }
    const area = THREE.ShapeUtils.area(points);
    return Math.abs(area);
  },
 
  /**
   * 检测坐标点是否在多边形内部
   * @param {Array<Number>} point 坐标点
   * @param {Array<Array<Number>>} vs 多边形区域
   * @return {Boolean}
   */
  pointInPolygon(point, vs) {
    // ray-casting algorithm based on
    // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
    const x = point[0];
    const y = point[1];
 
    let inside = false;
    for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
      const xi = vs[i][0];
      const yi = vs[i][1];
      const xj = vs[j][0];
      const yj = vs[j][1];
 
      const intersect = yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
      if (intersect) {
        inside = !inside;
      }
    }
 
    return inside;
  },
 
  Vector3: THREE.Vector3,
 
  /**
   * Convert alpha beta rotation to direction.
   * @param {number} alpha 垂直方向上与z轴的夹角
   * @param {number} beta x-y平面上的夹角
   * @return {THREE.Vector3} new vector3 or new out
   */
  directionFromAlphaBeta(alpha, beta) {
    const theta = (alpha / 180) * Math.PI + Math.PI / 2;
    const phi = (-beta / 180) * Math.PI + Math.PI / 2;
 
    const dir = new THREE.Vector3();
    const r = Math.sin(theta);
    dir.x = r * Math.cos(phi);
    dir.y = -Math.cos(theta);
    dir.z = r * Math.sin(phi);
 
    return dir;
  },
  /**
   * 从角度获取方向 点
   * @param {number} yAngle
   * @param {number} xAngle
   * @param {number} distance
   * @returns {THREE.Vector3}
   */
  getDirectionFromAngles(yAngle, xAngle, distance) {
    const dir = R3DMath.directionFromAlphaBeta(yAngle, xAngle);
    dir.normalize();
    dir.multiplyScalar(distance);
    return dir;
  },
 
  /**
   * 获取相对于自己坐标系的位置
   *
   * @param {object} [params={}] 参数列表
   * @property {number} params.xAngle X 轴角度值
   * @property {number} params.yAngle Y 轴角度值
   * @property {number} params.distance 距离
   * @property {number} params.factor 系数
   * @returns {Array<Number>} 自身坐标系下的坐标位置
   */
  getOffsetPosition(params = {}) {
    const { xAngle = 0, yAngle = 0, distance = 10, factor } = params;
    let radius = distance;
    if (factor) {
      radius = radius * factor;
    }
    return R3DMath.getDirectionFromAngles(yAngle, xAngle, radius).toArray();
  },
 
  /**
   * 获取屏幕渲染位置
   * @param {Array<Number>} position 对齐坐标位置[0,0]~[1,1](百分比)
   * @param {Array<Number>} size 元素像素尺寸
   * @param {Array<Number>} screenSize 屏幕像素尺寸
   */
  getRenderPosition(position, size, screenSize) {
    screenSize = screenSize || [window.innerWidth, window.innerHeight];
    const halfWidth = screenSize[0] / 2;
    const halfHeight = screenSize[1] / 2;
    const center = [position[0] * halfWidth, position[1] * halfHeight];
    const halfSize = [size[0] / 2, size[1] / 2];
    center[0] = R3DMath.clamp(center[0], -halfWidth + halfSize[0], halfWidth - halfSize[0]);
    center[1] = R3DMath.clamp(center[1], -halfHeight + halfSize[1], halfHeight - halfSize[1]);
    return [center[0], -center[1]];
  },
 
  /**
   * 获取向量长度
   * @param {Array<Number>} v 坐标
   * @return {Number}
   */
  getVectorLength(v) {
    return Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
  },
 
  /** 判断数值是否2次幂 */
  isPowOf2(num) {
    return num > 0 && (num & (num - 1)) === 0;
  },
 
  /** 往大取2次幂数值 */
  floorPowOf2(value) {
    return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  },
 
  /**
   * 向量数乘
   * @param {Array<Number>} v 坐标
   * @param {Number} scale 缩放系数
   * @return {Array<Number>}
   */
  scaleVector(v, scale) {
    if (tools.isArray(scale)) {
      return [v[0] * scale[0], v[1] * scale[1], v[2] * scale[2]];
    } else Eif (tools.isNumber(scale)) {
      return [v[0] * scale, v[1] * scale, v[2] * scale];
    }
  },
 
  /**
   * 向量数除
   * @param {Array<Number>} v 坐标
   * @param {Number} scale 缩放系数
   * @return {Array<Number>}
   */
  divideVector(v, scale) {
    if (tools.isArray(scale)) {
      return [v[0] / scale[0], v[1] / scale[1], v[2] / scale[2]];
    } else Eif (tools.isNumber(scale)) {
      return [v[0] / scale, v[1] / scale, v[2] / scale];
    }
  },
  /**
   * 求单位向量
   * @param {Array<Number>} v 坐标
   * @return {Array<Number>}
   */
  normalizeVector(v) {
    const m = 1.0 / this.getVectorLength(v);
    return [v[0] * m, v[1] * m, v[2] * m];
  },
  /**
   * 四舍五入,保留位数为 digit
   * @param {Number} tarNumber
   * @param {Number} digit
   */
  roundDigit(tarNumber, digit = 0) {
    if (digit < 1) {
      const result = parseInt(tarNumber);
      return isNaN(result) ? 0 : result;
    }
    // why not Number(tarNumber)? Number('111aa') -> NaN
    tarNumber = parseFloat(tarNumber);
    if (isNaN(tarNumber)) {
      return 0;
    }
    let result;
    if (tarNumber >= 0) {
      result = parseInt(tarNumber * Math.pow(10, digit) + 0.5) / Math.pow(10, digit);
    } else E{
      const negNumber = -tarNumber;
      result = parseInt(negNumber * Math.pow(10, digit) + 0.5) / Math.pow(10, digit);
    }
    return result;
  },
  /**
   * 将极坐标(p, θ) 转化为 直角坐标 (x, y)
   * !!! 在 Math 的三角函数中,参数均为弧度
   * sin0°=0,sin90°=1,sin180°=0,sin270°=﹣1,sin360°=0;
   * cos0°=1,cos90°=0,cos180°=﹣1,cos270°=0,cos360°=1;
   * @param {Number} p 极坐标系中的 p
   * @param {Number} angle 极坐标系中的 θ 单位为 度
   */
  polarToXY(p, angle) {
    // 将度转化为弧度
    const radian = R3DMath.degToRad(angle);
    const x = p * Math.cos(radian);
    const y = p * Math.sin(radian);
    return [x, y];
  },
 
  /**
   * 将极坐标(p, θ) 转化为 坐标 (x, y, z) x:正东, z:正北,y 高度
   * @param {Number} p 极坐标系中的 p
   * @param {Number} angle 极坐标系中的 θ
   */
  polarToVector3(p, angle, high = 0) {
    // 将度转化为弧度
    const radian = R3DMath.degToRad(angle);
    const x = p * Math.cos(radian);
    const z = p * Math.sin(radian);
    return [x, high, z];
  },
  /**
   * 通过时间、和 x-y 平面夹角 获取太阳的位置,以及设置光照颜色
   * @param {Number} time
   * @param {Number} angleOnXYPlane 角度
   */
  getSunConfig(time, angleOnXYPlane) {
    const alpha = (time / 24) * 360 - 90;
    const sunPos = R3DMath.directionFromAlphaBeta(alpha, angleOnXYPlane);
    // 中午和晚上的颜色设置
    const noonColor = new THREE.Color().setHex(0xffffff);
    const earlyEveningColor = new THREE.Color().setHex(0xff8940);
    const lightColor = new THREE.Color();
 
    // 设置主光源数据
    const night = time < 6 || time > 18;
    const lerp = 1 - Math.abs(time - 12) / 6;
    const dirColor = lightColor.copy(earlyEveningColor).lerp(noonColor, lerp);
 
    // hemisphereLight 光照颜色
    const hemisphereLight = {
      intensity: Math.min(Math.max(night ? 0 : lerp + 0.3, 0.2), 0.7)
    };
 
    const mainLight = {
      color: dirColor.getHex(),
      alpha,
      beta: angleOnXYPlane
    };
 
    return {
      sunPosition: R3DTools.parseVector3(sunPos),
      hemisphereLight,
      mainLight
    };
  }
};
 
export { ThreeMath };
 
export default R3DMath;