tools.functions.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * Function indicating if a number is an exponent of 2
  3. * @param value defines the value to test
  4. * @returns true if the value is an exponent of 2
  5. */
  6. export function IsExponentOfTwo(value) {
  7. let count = 1;
  8. do {
  9. count *= 2;
  10. } while (count < value);
  11. return count === value;
  12. }
  13. /**
  14. * Interpolates between a and b via alpha
  15. * @param a The lower value (returned when alpha = 0)
  16. * @param b The upper value (returned when alpha = 1)
  17. * @param alpha The interpolation-factor
  18. * @returns The mixed value
  19. */
  20. export function Mix(a, b, alpha) {
  21. return a * (1 - alpha) + b * alpha;
  22. }
  23. /**
  24. * Find the nearest power of two.
  25. * @param x Number to start search from.
  26. * @returns Next nearest power of two.
  27. */
  28. export function NearestPOT(x) {
  29. const c = CeilingPOT(x);
  30. const f = FloorPOT(x);
  31. return c - x > x - f ? f : c;
  32. }
  33. /**
  34. * Find the next highest power of two.
  35. * @param x Number to start search from.
  36. * @returns Next highest power of two.
  37. */
  38. export function CeilingPOT(x) {
  39. x--;
  40. x |= x >> 1;
  41. x |= x >> 2;
  42. x |= x >> 4;
  43. x |= x >> 8;
  44. x |= x >> 16;
  45. x++;
  46. return x;
  47. }
  48. /**
  49. * Find the next lowest power of two.
  50. * @param x Number to start search from.
  51. * @returns Next lowest power of two.
  52. */
  53. export function FloorPOT(x) {
  54. x = x | (x >> 1);
  55. x = x | (x >> 2);
  56. x = x | (x >> 4);
  57. x = x | (x >> 8);
  58. x = x | (x >> 16);
  59. return x - (x >> 1);
  60. }
  61. /**
  62. * Get the closest exponent of two
  63. * @param value defines the value to approximate
  64. * @param max defines the maximum value to return
  65. * @param mode defines how to define the closest value
  66. * @returns closest exponent of two of the given value
  67. */
  68. export function GetExponentOfTwo(value, max, mode = 2) {
  69. let pot;
  70. switch (mode) {
  71. case 1:
  72. pot = FloorPOT(value);
  73. break;
  74. case 2:
  75. pot = NearestPOT(value);
  76. break;
  77. case 3:
  78. default:
  79. pot = CeilingPOT(value);
  80. break;
  81. }
  82. return Math.min(pot, max);
  83. }
  84. //# sourceMappingURL=tools.functions.js.map