Math.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  1. import MersenneTwister from "mersenne-twister";
  2. import Check from "./Check.js";
  3. import defaultValue from "./defaultValue.js";
  4. import defined from "./defined.js";
  5. import DeveloperError from "./DeveloperError.js";
  6. /**
  7. * Math functions.
  8. *
  9. * @exports CesiumMath
  10. * @alias Math
  11. */
  12. const CesiumMath = {};
  13. /**
  14. * 0.1
  15. * @type {number}
  16. * @constant
  17. */
  18. CesiumMath.EPSILON1 = 0.1;
  19. /**
  20. * 0.01
  21. * @type {number}
  22. * @constant
  23. */
  24. CesiumMath.EPSILON2 = 0.01;
  25. /**
  26. * 0.001
  27. * @type {number}
  28. * @constant
  29. */
  30. CesiumMath.EPSILON3 = 0.001;
  31. /**
  32. * 0.0001
  33. * @type {number}
  34. * @constant
  35. */
  36. CesiumMath.EPSILON4 = 0.0001;
  37. /**
  38. * 0.00001
  39. * @type {number}
  40. * @constant
  41. */
  42. CesiumMath.EPSILON5 = 0.00001;
  43. /**
  44. * 0.000001
  45. * @type {number}
  46. * @constant
  47. */
  48. CesiumMath.EPSILON6 = 0.000001;
  49. /**
  50. * 0.0000001
  51. * @type {number}
  52. * @constant
  53. */
  54. CesiumMath.EPSILON7 = 0.0000001;
  55. /**
  56. * 0.00000001
  57. * @type {number}
  58. * @constant
  59. */
  60. CesiumMath.EPSILON8 = 0.00000001;
  61. /**
  62. * 0.000000001
  63. * @type {number}
  64. * @constant
  65. */
  66. CesiumMath.EPSILON9 = 0.000000001;
  67. /**
  68. * 0.0000000001
  69. * @type {number}
  70. * @constant
  71. */
  72. CesiumMath.EPSILON10 = 0.0000000001;
  73. /**
  74. * 0.00000000001
  75. * @type {number}
  76. * @constant
  77. */
  78. CesiumMath.EPSILON11 = 0.00000000001;
  79. /**
  80. * 0.000000000001
  81. * @type {number}
  82. * @constant
  83. */
  84. CesiumMath.EPSILON12 = 0.000000000001;
  85. /**
  86. * 0.0000000000001
  87. * @type {number}
  88. * @constant
  89. */
  90. CesiumMath.EPSILON13 = 0.0000000000001;
  91. /**
  92. * 0.00000000000001
  93. * @type {number}
  94. * @constant
  95. */
  96. CesiumMath.EPSILON14 = 0.00000000000001;
  97. /**
  98. * 0.000000000000001
  99. * @type {number}
  100. * @constant
  101. */
  102. CesiumMath.EPSILON15 = 0.000000000000001;
  103. /**
  104. * 0.0000000000000001
  105. * @type {number}
  106. * @constant
  107. */
  108. CesiumMath.EPSILON16 = 0.0000000000000001;
  109. /**
  110. * 0.00000000000000001
  111. * @type {number}
  112. * @constant
  113. */
  114. CesiumMath.EPSILON17 = 0.00000000000000001;
  115. /**
  116. * 0.000000000000000001
  117. * @type {number}
  118. * @constant
  119. */
  120. CesiumMath.EPSILON18 = 0.000000000000000001;
  121. /**
  122. * 0.0000000000000000001
  123. * @type {number}
  124. * @constant
  125. */
  126. CesiumMath.EPSILON19 = 0.0000000000000000001;
  127. /**
  128. * 0.00000000000000000001
  129. * @type {number}
  130. * @constant
  131. */
  132. CesiumMath.EPSILON20 = 0.00000000000000000001;
  133. /**
  134. * 0.000000000000000000001
  135. * @type {number}
  136. * @constant
  137. */
  138. CesiumMath.EPSILON21 = 0.000000000000000000001;
  139. /**
  140. * The gravitational parameter of the Earth in meters cubed
  141. * per second squared as defined by the WGS84 model: 3.986004418e14
  142. * @type {number}
  143. * @constant
  144. */
  145. CesiumMath.GRAVITATIONALPARAMETER = 3.986004418e14;
  146. /**
  147. * Radius of the sun in meters: 6.955e8
  148. * @type {number}
  149. * @constant
  150. */
  151. CesiumMath.SOLAR_RADIUS = 6.955e8;
  152. /**
  153. * The mean radius of the moon, according to the "Report of the IAU/IAG Working Group on
  154. * Cartographic Coordinates and Rotational Elements of the Planets and satellites: 2000",
  155. * Celestial Mechanics 82: 83-110, 2002.
  156. * @type {number}
  157. * @constant
  158. */
  159. CesiumMath.LUNAR_RADIUS = 1737400.0;
  160. /**
  161. * 64 * 1024
  162. * @type {number}
  163. * @constant
  164. */
  165. CesiumMath.SIXTY_FOUR_KILOBYTES = 64 * 1024;
  166. /**
  167. * 4 * 1024 * 1024 * 1024
  168. * @type {number}
  169. * @constant
  170. */
  171. CesiumMath.FOUR_GIGABYTES = 4 * 1024 * 1024 * 1024;
  172. /**
  173. * Returns the sign of the value; 1 if the value is positive, -1 if the value is
  174. * negative, or 0 if the value is 0.
  175. *
  176. * @function
  177. * @param {number} value The value to return the sign of.
  178. * @returns {number} The sign of value.
  179. */
  180. // eslint-disable-next-line es/no-math-sign
  181. CesiumMath.sign = defaultValue(Math.sign, function sign(value) {
  182. value = +value; // coerce to number
  183. if (value === 0 || value !== value) {
  184. // zero or NaN
  185. return value;
  186. }
  187. return value > 0 ? 1 : -1;
  188. });
  189. /**
  190. * Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative.
  191. * This is similar to {@link CesiumMath#sign} except that returns 1.0 instead of
  192. * 0.0 when the input value is 0.0.
  193. * @param {number} value The value to return the sign of.
  194. * @returns {number} The sign of value.
  195. */
  196. CesiumMath.signNotZero = function (value) {
  197. return value < 0.0 ? -1.0 : 1.0;
  198. };
  199. /**
  200. * Converts a scalar value in the range [-1.0, 1.0] to a SNORM in the range [0, rangeMaximum]
  201. * @param {number} value The scalar value in the range [-1.0, 1.0]
  202. * @param {number} [rangeMaximum=255] The maximum value in the mapped range, 255 by default.
  203. * @returns {number} A SNORM value, where 0 maps to -1.0 and rangeMaximum maps to 1.0.
  204. *
  205. * @see CesiumMath.fromSNorm
  206. */
  207. CesiumMath.toSNorm = function (value, rangeMaximum) {
  208. rangeMaximum = defaultValue(rangeMaximum, 255);
  209. return Math.round(
  210. (CesiumMath.clamp(value, -1.0, 1.0) * 0.5 + 0.5) * rangeMaximum
  211. );
  212. };
  213. /**
  214. * Converts a SNORM value in the range [0, rangeMaximum] to a scalar in the range [-1.0, 1.0].
  215. * @param {number} value SNORM value in the range [0, rangeMaximum]
  216. * @param {number} [rangeMaximum=255] The maximum value in the SNORM range, 255 by default.
  217. * @returns {number} Scalar in the range [-1.0, 1.0].
  218. *
  219. * @see CesiumMath.toSNorm
  220. */
  221. CesiumMath.fromSNorm = function (value, rangeMaximum) {
  222. rangeMaximum = defaultValue(rangeMaximum, 255);
  223. return (
  224. (CesiumMath.clamp(value, 0.0, rangeMaximum) / rangeMaximum) * 2.0 - 1.0
  225. );
  226. };
  227. /**
  228. * Converts a scalar value in the range [rangeMinimum, rangeMaximum] to a scalar in the range [0.0, 1.0]
  229. * @param {number} value The scalar value in the range [rangeMinimum, rangeMaximum]
  230. * @param {number} rangeMinimum The minimum value in the mapped range.
  231. * @param {number} rangeMaximum The maximum value in the mapped range.
  232. * @returns {number} A scalar value, where rangeMinimum maps to 0.0 and rangeMaximum maps to 1.0.
  233. */
  234. CesiumMath.normalize = function (value, rangeMinimum, rangeMaximum) {
  235. rangeMaximum = Math.max(rangeMaximum - rangeMinimum, 0.0);
  236. return rangeMaximum === 0.0
  237. ? 0.0
  238. : CesiumMath.clamp((value - rangeMinimum) / rangeMaximum, 0.0, 1.0);
  239. };
  240. /**
  241. * Returns the hyperbolic sine of a number.
  242. * The hyperbolic sine of <em>value</em> is defined to be
  243. * (<em>e<sup>x</sup>&nbsp;-&nbsp;e<sup>-x</sup></em>)/2.0
  244. * where <i>e</i> is Euler's number, approximately 2.71828183.
  245. *
  246. * <p>Special cases:
  247. * <ul>
  248. * <li>If the argument is NaN, then the result is NaN.</li>
  249. *
  250. * <li>If the argument is infinite, then the result is an infinity
  251. * with the same sign as the argument.</li>
  252. *
  253. * <li>If the argument is zero, then the result is a zero with the
  254. * same sign as the argument.</li>
  255. * </ul>
  256. *</p>
  257. *
  258. * @function
  259. * @param {number} value The number whose hyperbolic sine is to be returned.
  260. * @returns {number} The hyperbolic sine of <code>value</code>.
  261. */
  262. // eslint-disable-next-line es/no-math-sinh
  263. CesiumMath.sinh = defaultValue(Math.sinh, function sinh(value) {
  264. return (Math.exp(value) - Math.exp(-value)) / 2.0;
  265. });
  266. /**
  267. * Returns the hyperbolic cosine of a number.
  268. * The hyperbolic cosine of <strong>value</strong> is defined to be
  269. * (<em>e<sup>x</sup>&nbsp;+&nbsp;e<sup>-x</sup></em>)/2.0
  270. * where <i>e</i> is Euler's number, approximately 2.71828183.
  271. *
  272. * <p>Special cases:
  273. * <ul>
  274. * <li>If the argument is NaN, then the result is NaN.</li>
  275. *
  276. * <li>If the argument is infinite, then the result is positive infinity.</li>
  277. *
  278. * <li>If the argument is zero, then the result is 1.0.</li>
  279. * </ul>
  280. *</p>
  281. *
  282. * @function
  283. * @param {number} value The number whose hyperbolic cosine is to be returned.
  284. * @returns {number} The hyperbolic cosine of <code>value</code>.
  285. */
  286. // eslint-disable-next-line es/no-math-cosh
  287. CesiumMath.cosh = defaultValue(Math.cosh, function cosh(value) {
  288. return (Math.exp(value) + Math.exp(-value)) / 2.0;
  289. });
  290. /**
  291. * Computes the linear interpolation of two values.
  292. *
  293. * @param {number} p The start value to interpolate.
  294. * @param {number} q The end value to interpolate.
  295. * @param {number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
  296. * @returns {number} The linearly interpolated value.
  297. *
  298. * @example
  299. * const n = Cesium.Math.lerp(0.0, 2.0, 0.5); // returns 1.0
  300. */
  301. CesiumMath.lerp = function (p, q, time) {
  302. return (1.0 - time) * p + time * q;
  303. };
  304. /**
  305. * pi
  306. *
  307. * @type {number}
  308. * @constant
  309. */
  310. CesiumMath.PI = Math.PI;
  311. /**
  312. * 1/pi
  313. *
  314. * @type {number}
  315. * @constant
  316. */
  317. CesiumMath.ONE_OVER_PI = 1.0 / Math.PI;
  318. /**
  319. * pi/2
  320. *
  321. * @type {number}
  322. * @constant
  323. */
  324. CesiumMath.PI_OVER_TWO = Math.PI / 2.0;
  325. /**
  326. * pi/3
  327. *
  328. * @type {number}
  329. * @constant
  330. */
  331. CesiumMath.PI_OVER_THREE = Math.PI / 3.0;
  332. /**
  333. * pi/4
  334. *
  335. * @type {number}
  336. * @constant
  337. */
  338. CesiumMath.PI_OVER_FOUR = Math.PI / 4.0;
  339. /**
  340. * pi/6
  341. *
  342. * @type {number}
  343. * @constant
  344. */
  345. CesiumMath.PI_OVER_SIX = Math.PI / 6.0;
  346. /**
  347. * 3pi/2
  348. *
  349. * @type {number}
  350. * @constant
  351. */
  352. CesiumMath.THREE_PI_OVER_TWO = (3.0 * Math.PI) / 2.0;
  353. /**
  354. * 2pi
  355. *
  356. * @type {number}
  357. * @constant
  358. */
  359. CesiumMath.TWO_PI = 2.0 * Math.PI;
  360. /**
  361. * 1/2pi
  362. *
  363. * @type {number}
  364. * @constant
  365. */
  366. CesiumMath.ONE_OVER_TWO_PI = 1.0 / (2.0 * Math.PI);
  367. /**
  368. * The number of radians in a degree.
  369. *
  370. * @type {number}
  371. * @constant
  372. */
  373. CesiumMath.RADIANS_PER_DEGREE = Math.PI / 180.0;
  374. /**
  375. * The number of degrees in a radian.
  376. *
  377. * @type {number}
  378. * @constant
  379. */
  380. CesiumMath.DEGREES_PER_RADIAN = 180.0 / Math.PI;
  381. /**
  382. * The number of radians in an arc second.
  383. *
  384. * @type {number}
  385. * @constant
  386. */
  387. CesiumMath.RADIANS_PER_ARCSECOND = CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  388. /**
  389. * Converts degrees to radians.
  390. * @param {number} degrees The angle to convert in degrees.
  391. * @returns {number} The corresponding angle in radians.
  392. */
  393. CesiumMath.toRadians = function (degrees) {
  394. //>>includeStart('debug', pragmas.debug);
  395. if (!defined(degrees)) {
  396. throw new DeveloperError("degrees is required.");
  397. }
  398. //>>includeEnd('debug');
  399. return degrees * CesiumMath.RADIANS_PER_DEGREE;
  400. };
  401. /**
  402. * Converts radians to degrees.
  403. * @param {number} radians The angle to convert in radians.
  404. * @returns {number} The corresponding angle in degrees.
  405. */
  406. CesiumMath.toDegrees = function (radians) {
  407. //>>includeStart('debug', pragmas.debug);
  408. if (!defined(radians)) {
  409. throw new DeveloperError("radians is required.");
  410. }
  411. //>>includeEnd('debug');
  412. return radians * CesiumMath.DEGREES_PER_RADIAN;
  413. };
  414. /**
  415. * Converts a longitude value, in radians, to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  416. *
  417. * @param {number} angle The longitude value, in radians, to convert to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  418. * @returns {number} The equivalent longitude value in the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  419. *
  420. * @example
  421. * // Convert 270 degrees to -90 degrees longitude
  422. * const longitude = Cesium.Math.convertLongitudeRange(Cesium.Math.toRadians(270.0));
  423. */
  424. CesiumMath.convertLongitudeRange = function (angle) {
  425. //>>includeStart('debug', pragmas.debug);
  426. if (!defined(angle)) {
  427. throw new DeveloperError("angle is required.");
  428. }
  429. //>>includeEnd('debug');
  430. const twoPi = CesiumMath.TWO_PI;
  431. const simplified = angle - Math.floor(angle / twoPi) * twoPi;
  432. if (simplified < -Math.PI) {
  433. return simplified + twoPi;
  434. }
  435. if (simplified >= Math.PI) {
  436. return simplified - twoPi;
  437. }
  438. return simplified;
  439. };
  440. /**
  441. * Convenience function that clamps a latitude value, in radians, to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  442. * Useful for sanitizing data before use in objects requiring correct range.
  443. *
  444. * @param {number} angle The latitude value, in radians, to clamp to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  445. * @returns {number} The latitude value clamped to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  446. *
  447. * @example
  448. * // Clamp 108 degrees latitude to 90 degrees latitude
  449. * const latitude = Cesium.Math.clampToLatitudeRange(Cesium.Math.toRadians(108.0));
  450. */
  451. CesiumMath.clampToLatitudeRange = function (angle) {
  452. //>>includeStart('debug', pragmas.debug);
  453. if (!defined(angle)) {
  454. throw new DeveloperError("angle is required.");
  455. }
  456. //>>includeEnd('debug');
  457. return CesiumMath.clamp(
  458. angle,
  459. -1 * CesiumMath.PI_OVER_TWO,
  460. CesiumMath.PI_OVER_TWO
  461. );
  462. };
  463. /**
  464. * Produces an angle in the range -Pi <= angle <= Pi which is equivalent to the provided angle.
  465. *
  466. * @param {number} angle in radians
  467. * @returns {number} The angle in the range [<code>-CesiumMath.PI</code>, <code>CesiumMath.PI</code>].
  468. */
  469. CesiumMath.negativePiToPi = function (angle) {
  470. //>>includeStart('debug', pragmas.debug);
  471. if (!defined(angle)) {
  472. throw new DeveloperError("angle is required.");
  473. }
  474. //>>includeEnd('debug');
  475. if (angle >= -CesiumMath.PI && angle <= CesiumMath.PI) {
  476. // Early exit if the input is already inside the range. This avoids
  477. // unnecessary math which could introduce floating point error.
  478. return angle;
  479. }
  480. return CesiumMath.zeroToTwoPi(angle + CesiumMath.PI) - CesiumMath.PI;
  481. };
  482. /**
  483. * Produces an angle in the range 0 <= angle <= 2Pi which is equivalent to the provided angle.
  484. *
  485. * @param {number} angle in radians
  486. * @returns {number} The angle in the range [0, <code>CesiumMath.TWO_PI</code>].
  487. */
  488. CesiumMath.zeroToTwoPi = function (angle) {
  489. //>>includeStart('debug', pragmas.debug);
  490. if (!defined(angle)) {
  491. throw new DeveloperError("angle is required.");
  492. }
  493. //>>includeEnd('debug');
  494. if (angle >= 0 && angle <= CesiumMath.TWO_PI) {
  495. // Early exit if the input is already inside the range. This avoids
  496. // unnecessary math which could introduce floating point error.
  497. return angle;
  498. }
  499. const mod = CesiumMath.mod(angle, CesiumMath.TWO_PI);
  500. if (
  501. Math.abs(mod) < CesiumMath.EPSILON14 &&
  502. Math.abs(angle) > CesiumMath.EPSILON14
  503. ) {
  504. return CesiumMath.TWO_PI;
  505. }
  506. return mod;
  507. };
  508. /**
  509. * The modulo operation that also works for negative dividends.
  510. *
  511. * @param {number} m The dividend.
  512. * @param {number} n The divisor.
  513. * @returns {number} The remainder.
  514. */
  515. CesiumMath.mod = function (m, n) {
  516. //>>includeStart('debug', pragmas.debug);
  517. if (!defined(m)) {
  518. throw new DeveloperError("m is required.");
  519. }
  520. if (!defined(n)) {
  521. throw new DeveloperError("n is required.");
  522. }
  523. if (n === 0.0) {
  524. throw new DeveloperError("divisor cannot be 0.");
  525. }
  526. //>>includeEnd('debug');
  527. if (CesiumMath.sign(m) === CesiumMath.sign(n) && Math.abs(m) < Math.abs(n)) {
  528. // Early exit if the input does not need to be modded. This avoids
  529. // unnecessary math which could introduce floating point error.
  530. return m;
  531. }
  532. return ((m % n) + n) % n;
  533. };
  534. /**
  535. * Determines if two values are equal using an absolute or relative tolerance test. This is useful
  536. * to avoid problems due to roundoff error when comparing floating-point values directly. The values are
  537. * first compared using an absolute tolerance test. If that fails, a relative tolerance test is performed.
  538. * Use this test if you are unsure of the magnitudes of left and right.
  539. *
  540. * @param {number} left The first value to compare.
  541. * @param {number} right The other value to compare.
  542. * @param {number} [relativeEpsilon=0] The maximum inclusive delta between <code>left</code> and <code>right</code> for the relative tolerance test.
  543. * @param {number} [absoluteEpsilon=relativeEpsilon] The maximum inclusive delta between <code>left</code> and <code>right</code> for the absolute tolerance test.
  544. * @returns {boolean} <code>true</code> if the values are equal within the epsilon; otherwise, <code>false</code>.
  545. *
  546. * @example
  547. * const a = Cesium.Math.equalsEpsilon(0.0, 0.01, Cesium.Math.EPSILON2); // true
  548. * const b = Cesium.Math.equalsEpsilon(0.0, 0.1, Cesium.Math.EPSILON2); // false
  549. * const c = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON7); // true
  550. * const d = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON9); // false
  551. */
  552. CesiumMath.equalsEpsilon = function (
  553. left,
  554. right,
  555. relativeEpsilon,
  556. absoluteEpsilon
  557. ) {
  558. //>>includeStart('debug', pragmas.debug);
  559. if (!defined(left)) {
  560. throw new DeveloperError("left is required.");
  561. }
  562. if (!defined(right)) {
  563. throw new DeveloperError("right is required.");
  564. }
  565. //>>includeEnd('debug');
  566. relativeEpsilon = defaultValue(relativeEpsilon, 0.0);
  567. absoluteEpsilon = defaultValue(absoluteEpsilon, relativeEpsilon);
  568. const absDiff = Math.abs(left - right);
  569. return (
  570. absDiff <= absoluteEpsilon ||
  571. absDiff <= relativeEpsilon * Math.max(Math.abs(left), Math.abs(right))
  572. );
  573. };
  574. /**
  575. * Determines if the left value is less than the right value. If the two values are within
  576. * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns false.
  577. *
  578. * @param {number} left The first number to compare.
  579. * @param {number} right The second number to compare.
  580. * @param {number} absoluteEpsilon The absolute epsilon to use in comparison.
  581. * @returns {boolean} <code>true</code> if <code>left</code> is less than <code>right</code> by more than
  582. * <code>absoluteEpsilon<code>. <code>false</code> if <code>left</code> is greater or if the two
  583. * values are nearly equal.
  584. */
  585. CesiumMath.lessThan = function (left, right, absoluteEpsilon) {
  586. //>>includeStart('debug', pragmas.debug);
  587. if (!defined(left)) {
  588. throw new DeveloperError("first is required.");
  589. }
  590. if (!defined(right)) {
  591. throw new DeveloperError("second is required.");
  592. }
  593. if (!defined(absoluteEpsilon)) {
  594. throw new DeveloperError("absoluteEpsilon is required.");
  595. }
  596. //>>includeEnd('debug');
  597. return left - right < -absoluteEpsilon;
  598. };
  599. /**
  600. * Determines if the left value is less than or equal to the right value. If the two values are within
  601. * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns true.
  602. *
  603. * @param {number} left The first number to compare.
  604. * @param {number} right The second number to compare.
  605. * @param {number} absoluteEpsilon The absolute epsilon to use in comparison.
  606. * @returns {boolean} <code>true</code> if <code>left</code> is less than <code>right</code> or if the
  607. * the values are nearly equal.
  608. */
  609. CesiumMath.lessThanOrEquals = function (left, right, absoluteEpsilon) {
  610. //>>includeStart('debug', pragmas.debug);
  611. if (!defined(left)) {
  612. throw new DeveloperError("first is required.");
  613. }
  614. if (!defined(right)) {
  615. throw new DeveloperError("second is required.");
  616. }
  617. if (!defined(absoluteEpsilon)) {
  618. throw new DeveloperError("absoluteEpsilon is required.");
  619. }
  620. //>>includeEnd('debug');
  621. return left - right < absoluteEpsilon;
  622. };
  623. /**
  624. * Determines if the left value is greater the right value. If the two values are within
  625. * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns false.
  626. *
  627. * @param {number} left The first number to compare.
  628. * @param {number} right The second number to compare.
  629. * @param {number} absoluteEpsilon The absolute epsilon to use in comparison.
  630. * @returns {boolean} <code>true</code> if <code>left</code> is greater than <code>right</code> by more than
  631. * <code>absoluteEpsilon<code>. <code>false</code> if <code>left</code> is less or if the two
  632. * values are nearly equal.
  633. */
  634. CesiumMath.greaterThan = function (left, right, absoluteEpsilon) {
  635. //>>includeStart('debug', pragmas.debug);
  636. if (!defined(left)) {
  637. throw new DeveloperError("first is required.");
  638. }
  639. if (!defined(right)) {
  640. throw new DeveloperError("second is required.");
  641. }
  642. if (!defined(absoluteEpsilon)) {
  643. throw new DeveloperError("absoluteEpsilon is required.");
  644. }
  645. //>>includeEnd('debug');
  646. return left - right > absoluteEpsilon;
  647. };
  648. /**
  649. * Determines if the left value is greater than or equal to the right value. If the two values are within
  650. * <code>absoluteEpsilon</code> of each other, they are considered equal and this function returns true.
  651. *
  652. * @param {number} left The first number to compare.
  653. * @param {number} right The second number to compare.
  654. * @param {number} absoluteEpsilon The absolute epsilon to use in comparison.
  655. * @returns {boolean} <code>true</code> if <code>left</code> is greater than <code>right</code> or if the
  656. * the values are nearly equal.
  657. */
  658. CesiumMath.greaterThanOrEquals = function (left, right, absoluteEpsilon) {
  659. //>>includeStart('debug', pragmas.debug);
  660. if (!defined(left)) {
  661. throw new DeveloperError("first is required.");
  662. }
  663. if (!defined(right)) {
  664. throw new DeveloperError("second is required.");
  665. }
  666. if (!defined(absoluteEpsilon)) {
  667. throw new DeveloperError("absoluteEpsilon is required.");
  668. }
  669. //>>includeEnd('debug');
  670. return left - right > -absoluteEpsilon;
  671. };
  672. const factorials = [1];
  673. /**
  674. * Computes the factorial of the provided number.
  675. *
  676. * @param {number} n The number whose factorial is to be computed.
  677. * @returns {number} The factorial of the provided number or undefined if the number is less than 0.
  678. *
  679. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  680. *
  681. *
  682. * @example
  683. * //Compute 7!, which is equal to 5040
  684. * const computedFactorial = Cesium.Math.factorial(7);
  685. *
  686. * @see {@link http://en.wikipedia.org/wiki/Factorial|Factorial on Wikipedia}
  687. */
  688. CesiumMath.factorial = function (n) {
  689. //>>includeStart('debug', pragmas.debug);
  690. if (typeof n !== "number" || n < 0) {
  691. throw new DeveloperError(
  692. "A number greater than or equal to 0 is required."
  693. );
  694. }
  695. //>>includeEnd('debug');
  696. const length = factorials.length;
  697. if (n >= length) {
  698. let sum = factorials[length - 1];
  699. for (let i = length; i <= n; i++) {
  700. const next = sum * i;
  701. factorials.push(next);
  702. sum = next;
  703. }
  704. }
  705. return factorials[n];
  706. };
  707. /**
  708. * Increments a number with a wrapping to a minimum value if the number exceeds the maximum value.
  709. *
  710. * @param {number} [n] The number to be incremented.
  711. * @param {number} [maximumValue] The maximum incremented value before rolling over to the minimum value.
  712. * @param {number} [minimumValue=0.0] The number reset to after the maximum value has been exceeded.
  713. * @returns {number} The incremented number.
  714. *
  715. * @exception {DeveloperError} Maximum value must be greater than minimum value.
  716. *
  717. * @example
  718. * const n = Cesium.Math.incrementWrap(5, 10, 0); // returns 6
  719. * const m = Cesium.Math.incrementWrap(10, 10, 0); // returns 0
  720. */
  721. CesiumMath.incrementWrap = function (n, maximumValue, minimumValue) {
  722. minimumValue = defaultValue(minimumValue, 0.0);
  723. //>>includeStart('debug', pragmas.debug);
  724. if (!defined(n)) {
  725. throw new DeveloperError("n is required.");
  726. }
  727. if (maximumValue <= minimumValue) {
  728. throw new DeveloperError("maximumValue must be greater than minimumValue.");
  729. }
  730. //>>includeEnd('debug');
  731. ++n;
  732. if (n > maximumValue) {
  733. n = minimumValue;
  734. }
  735. return n;
  736. };
  737. /**
  738. * Determines if a non-negative integer is a power of two.
  739. * The maximum allowed input is (2^32)-1 due to 32-bit bitwise operator limitation in Javascript.
  740. *
  741. * @param {number} n The integer to test in the range [0, (2^32)-1].
  742. * @returns {boolean} <code>true</code> if the number if a power of two; otherwise, <code>false</code>.
  743. *
  744. * @exception {DeveloperError} A number between 0 and (2^32)-1 is required.
  745. *
  746. * @example
  747. * const t = Cesium.Math.isPowerOfTwo(16); // true
  748. * const f = Cesium.Math.isPowerOfTwo(20); // false
  749. */
  750. CesiumMath.isPowerOfTwo = function (n) {
  751. //>>includeStart('debug', pragmas.debug);
  752. if (typeof n !== "number" || n < 0 || n > 4294967295) {
  753. throw new DeveloperError("A number between 0 and (2^32)-1 is required.");
  754. }
  755. //>>includeEnd('debug');
  756. return n !== 0 && (n & (n - 1)) === 0;
  757. };
  758. /**
  759. * Computes the next power-of-two integer greater than or equal to the provided non-negative integer.
  760. * The maximum allowed input is 2^31 due to 32-bit bitwise operator limitation in Javascript.
  761. *
  762. * @param {number} n The integer to test in the range [0, 2^31].
  763. * @returns {number} The next power-of-two integer.
  764. *
  765. * @exception {DeveloperError} A number between 0 and 2^31 is required.
  766. *
  767. * @example
  768. * const n = Cesium.Math.nextPowerOfTwo(29); // 32
  769. * const m = Cesium.Math.nextPowerOfTwo(32); // 32
  770. */
  771. CesiumMath.nextPowerOfTwo = function (n) {
  772. //>>includeStart('debug', pragmas.debug);
  773. if (typeof n !== "number" || n < 0 || n > 2147483648) {
  774. throw new DeveloperError("A number between 0 and 2^31 is required.");
  775. }
  776. //>>includeEnd('debug');
  777. // From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
  778. --n;
  779. n |= n >> 1;
  780. n |= n >> 2;
  781. n |= n >> 4;
  782. n |= n >> 8;
  783. n |= n >> 16;
  784. ++n;
  785. return n;
  786. };
  787. /**
  788. * Computes the previous power-of-two integer less than or equal to the provided non-negative integer.
  789. * The maximum allowed input is (2^32)-1 due to 32-bit bitwise operator limitation in Javascript.
  790. *
  791. * @param {number} n The integer to test in the range [0, (2^32)-1].
  792. * @returns {number} The previous power-of-two integer.
  793. *
  794. * @exception {DeveloperError} A number between 0 and (2^32)-1 is required.
  795. *
  796. * @example
  797. * const n = Cesium.Math.previousPowerOfTwo(29); // 16
  798. * const m = Cesium.Math.previousPowerOfTwo(32); // 32
  799. */
  800. CesiumMath.previousPowerOfTwo = function (n) {
  801. //>>includeStart('debug', pragmas.debug);
  802. if (typeof n !== "number" || n < 0 || n > 4294967295) {
  803. throw new DeveloperError("A number between 0 and (2^32)-1 is required.");
  804. }
  805. //>>includeEnd('debug');
  806. n |= n >> 1;
  807. n |= n >> 2;
  808. n |= n >> 4;
  809. n |= n >> 8;
  810. n |= n >> 16;
  811. n |= n >> 32;
  812. // The previous bitwise operations implicitly convert to signed 32-bit. Use `>>>` to convert to unsigned
  813. n = (n >>> 0) - (n >>> 1);
  814. return n;
  815. };
  816. /**
  817. * Constraint a value to lie between two values.
  818. *
  819. * @param {number} value The value to clamp.
  820. * @param {number} min The minimum value.
  821. * @param {number} max The maximum value.
  822. * @returns {number} The clamped value such that min <= result <= max.
  823. */
  824. CesiumMath.clamp = function (value, min, max) {
  825. //>>includeStart('debug', pragmas.debug);
  826. Check.typeOf.number("value", value);
  827. Check.typeOf.number("min", min);
  828. Check.typeOf.number("max", max);
  829. //>>includeEnd('debug');
  830. return value < min ? min : value > max ? max : value;
  831. };
  832. let randomNumberGenerator = new MersenneTwister();
  833. /**
  834. * Sets the seed used by the random number generator
  835. * in {@link CesiumMath#nextRandomNumber}.
  836. *
  837. * @param {number} seed An integer used as the seed.
  838. */
  839. CesiumMath.setRandomNumberSeed = function (seed) {
  840. //>>includeStart('debug', pragmas.debug);
  841. if (!defined(seed)) {
  842. throw new DeveloperError("seed is required.");
  843. }
  844. //>>includeEnd('debug');
  845. randomNumberGenerator = new MersenneTwister(seed);
  846. };
  847. /**
  848. * Generates a random floating point number in the range of [0.0, 1.0)
  849. * using a Mersenne twister.
  850. *
  851. * @returns {number} A random number in the range of [0.0, 1.0).
  852. *
  853. * @see CesiumMath.setRandomNumberSeed
  854. * @see {@link http://en.wikipedia.org/wiki/Mersenne_twister|Mersenne twister on Wikipedia}
  855. */
  856. CesiumMath.nextRandomNumber = function () {
  857. return randomNumberGenerator.random();
  858. };
  859. /**
  860. * Generates a random number between two numbers.
  861. *
  862. * @param {number} min The minimum value.
  863. * @param {number} max The maximum value.
  864. * @returns {number} A random number between the min and max.
  865. */
  866. CesiumMath.randomBetween = function (min, max) {
  867. return CesiumMath.nextRandomNumber() * (max - min) + min;
  868. };
  869. /**
  870. * Computes <code>Math.acos(value)</code>, but first clamps <code>value</code> to the range [-1.0, 1.0]
  871. * so that the function will never return NaN.
  872. *
  873. * @param {number} value The value for which to compute acos.
  874. * @returns {number} The acos of the value if the value is in the range [-1.0, 1.0], or the acos of -1.0 or 1.0,
  875. * whichever is closer, if the value is outside the range.
  876. */
  877. CesiumMath.acosClamped = function (value) {
  878. //>>includeStart('debug', pragmas.debug);
  879. if (!defined(value)) {
  880. throw new DeveloperError("value is required.");
  881. }
  882. //>>includeEnd('debug');
  883. return Math.acos(CesiumMath.clamp(value, -1.0, 1.0));
  884. };
  885. /**
  886. * Computes <code>Math.asin(value)</code>, but first clamps <code>value</code> to the range [-1.0, 1.0]
  887. * so that the function will never return NaN.
  888. *
  889. * @param {number} value The value for which to compute asin.
  890. * @returns {number} The asin of the value if the value is in the range [-1.0, 1.0], or the asin of -1.0 or 1.0,
  891. * whichever is closer, if the value is outside the range.
  892. */
  893. CesiumMath.asinClamped = function (value) {
  894. //>>includeStart('debug', pragmas.debug);
  895. if (!defined(value)) {
  896. throw new DeveloperError("value is required.");
  897. }
  898. //>>includeEnd('debug');
  899. return Math.asin(CesiumMath.clamp(value, -1.0, 1.0));
  900. };
  901. /**
  902. * Finds the chord length between two points given the circle's radius and the angle between the points.
  903. *
  904. * @param {number} angle The angle between the two points.
  905. * @param {number} radius The radius of the circle.
  906. * @returns {number} The chord length.
  907. */
  908. CesiumMath.chordLength = function (angle, radius) {
  909. //>>includeStart('debug', pragmas.debug);
  910. if (!defined(angle)) {
  911. throw new DeveloperError("angle is required.");
  912. }
  913. if (!defined(radius)) {
  914. throw new DeveloperError("radius is required.");
  915. }
  916. //>>includeEnd('debug');
  917. return 2.0 * radius * Math.sin(angle * 0.5);
  918. };
  919. /**
  920. * Finds the logarithm of a number to a base.
  921. *
  922. * @param {number} number The number.
  923. * @param {number} base The base.
  924. * @returns {number} The result.
  925. */
  926. CesiumMath.logBase = function (number, base) {
  927. //>>includeStart('debug', pragmas.debug);
  928. if (!defined(number)) {
  929. throw new DeveloperError("number is required.");
  930. }
  931. if (!defined(base)) {
  932. throw new DeveloperError("base is required.");
  933. }
  934. //>>includeEnd('debug');
  935. return Math.log(number) / Math.log(base);
  936. };
  937. /**
  938. * Finds the cube root of a number.
  939. * Returns NaN if <code>number</code> is not provided.
  940. *
  941. * @function
  942. * @param {number} [number] The number.
  943. * @returns {number} The result.
  944. */
  945. // eslint-disable-next-line es/no-math-cbrt
  946. CesiumMath.cbrt = defaultValue(Math.cbrt, function cbrt(number) {
  947. const result = Math.pow(Math.abs(number), 1.0 / 3.0);
  948. return number < 0.0 ? -result : result;
  949. });
  950. /**
  951. * Finds the base 2 logarithm of a number.
  952. *
  953. * @function
  954. * @param {number} number The number.
  955. * @returns {number} The result.
  956. */
  957. // eslint-disable-next-line es/no-math-log2
  958. CesiumMath.log2 = defaultValue(Math.log2, function log2(number) {
  959. return Math.log(number) * Math.LOG2E;
  960. });
  961. /**
  962. * @private
  963. */
  964. CesiumMath.fog = function (distanceToCamera, density) {
  965. const scalar = distanceToCamera * density;
  966. return 1.0 - Math.exp(-(scalar * scalar));
  967. };
  968. /**
  969. * Computes a fast approximation of Atan for input in the range [-1, 1].
  970. *
  971. * Based on Michal Drobot's approximation from ShaderFastLibs,
  972. * which in turn is based on "Efficient approximations for the arctangent function,"
  973. * Rajan, S. Sichun Wang Inkol, R. Joyal, A., May 2006.
  974. * Adapted from ShaderFastLibs under MIT License.
  975. *
  976. * @param {number} x An input number in the range [-1, 1]
  977. * @returns {number} An approximation of atan(x)
  978. */
  979. CesiumMath.fastApproximateAtan = function (x) {
  980. //>>includeStart('debug', pragmas.debug);
  981. Check.typeOf.number("x", x);
  982. //>>includeEnd('debug');
  983. return x * (-0.1784 * Math.abs(x) - 0.0663 * x * x + 1.0301);
  984. };
  985. /**
  986. * Computes a fast approximation of Atan2(x, y) for arbitrary input scalars.
  987. *
  988. * Range reduction math based on nvidia's cg reference implementation: http://developer.download.nvidia.com/cg/atan2.html
  989. *
  990. * @param {number} x An input number that isn't zero if y is zero.
  991. * @param {number} y An input number that isn't zero if x is zero.
  992. * @returns {number} An approximation of atan2(x, y)
  993. */
  994. CesiumMath.fastApproximateAtan2 = function (x, y) {
  995. //>>includeStart('debug', pragmas.debug);
  996. Check.typeOf.number("x", x);
  997. Check.typeOf.number("y", y);
  998. //>>includeEnd('debug');
  999. // atan approximations are usually only reliable over [-1, 1]
  1000. // So reduce the range by flipping whether x or y is on top based on which is bigger.
  1001. let opposite;
  1002. let t = Math.abs(x); // t used as swap and atan result.
  1003. opposite = Math.abs(y);
  1004. const adjacent = Math.max(t, opposite);
  1005. opposite = Math.min(t, opposite);
  1006. const oppositeOverAdjacent = opposite / adjacent;
  1007. //>>includeStart('debug', pragmas.debug);
  1008. if (isNaN(oppositeOverAdjacent)) {
  1009. throw new DeveloperError("either x or y must be nonzero");
  1010. }
  1011. //>>includeEnd('debug');
  1012. t = CesiumMath.fastApproximateAtan(oppositeOverAdjacent);
  1013. // Undo range reduction
  1014. t = Math.abs(y) > Math.abs(x) ? CesiumMath.PI_OVER_TWO - t : t;
  1015. t = x < 0.0 ? CesiumMath.PI - t : t;
  1016. t = y < 0.0 ? -t : t;
  1017. return t;
  1018. };
  1019. export default CesiumMath;