crn_math.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // File: crn_math.cpp
  2. // See Copyright Notice and license at the end of inc/crnlib.h
  3. #include "crn_core.h"
  4. namespace crnlib
  5. {
  6. namespace math
  7. {
  8. uint g_bitmasks[32] =
  9. {
  10. 1U << 0U, 1U << 1U, 1U << 2U, 1U << 3U,
  11. 1U << 4U, 1U << 5U, 1U << 6U, 1U << 7U,
  12. 1U << 8U, 1U << 9U, 1U << 10U, 1U << 11U,
  13. 1U << 12U, 1U << 13U, 1U << 14U, 1U << 15U,
  14. 1U << 16U, 1U << 17U, 1U << 18U, 1U << 19U,
  15. 1U << 20U, 1U << 21U, 1U << 22U, 1U << 23U,
  16. 1U << 24U, 1U << 25U, 1U << 26U, 1U << 27U,
  17. 1U << 28U, 1U << 29U, 1U << 30U, 1U << 31U
  18. };
  19. double compute_entropy(const uint8* p, uint n)
  20. {
  21. uint hist[256];
  22. utils::zero_object(hist);
  23. for (uint i = 0; i < n; i++)
  24. hist[*p++]++;
  25. double entropy = 0.0f;
  26. const double invln2 = 1.0f/log(2.0f);
  27. for (uint i = 0; i < 256; i++)
  28. {
  29. if (!hist[i])
  30. continue;
  31. double prob = static_cast<double>(hist[i]) / n;
  32. entropy += (-log(prob) * invln2) * hist[i];
  33. }
  34. return entropy;
  35. }
  36. void compute_lower_pow2_dim(int& width, int& height)
  37. {
  38. const int tex_width = width;
  39. const int tex_height = height;
  40. width = 1;
  41. for ( ; ; )
  42. {
  43. if ((width * 2) > tex_width)
  44. break;
  45. width *= 2;
  46. }
  47. height = 1;
  48. for ( ; ; )
  49. {
  50. if ((height * 2) > tex_height)
  51. break;
  52. height *= 2;
  53. }
  54. }
  55. void compute_upper_pow2_dim(int& width, int& height)
  56. {
  57. if (!math::is_power_of_2((uint32)width))
  58. width = math::next_pow2((uint32)width);
  59. if (!math::is_power_of_2((uint32)height))
  60. height = math::next_pow2((uint32)height);
  61. }
  62. } // namespace math
  63. } // namespace crnlib