💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.3 KiB

  1. /*
  2. * Copyright (C) 2021 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper source code.
  5. *
  6. * Antkeeper source code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper source code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "morton.hpp"
  20. namespace geom {
  21. namespace morton {
  22. std::uint32_t encode_2d(std::uint32_t x, std::uint32_t y)
  23. {
  24. auto interleave = [](std::uint32_t x) -> std::uint32_t
  25. {
  26. x &= 0x0000ffff;
  27. x = (x ^ (x << 8)) & 0x00ff00ff;
  28. x = (x ^ (x << 4)) & 0x0f0f0f0f;
  29. x = (x ^ (x << 2)) & 0x33333333;
  30. x = (x ^ (x << 1)) & 0x55555555;
  31. return x;
  32. };
  33. return (interleave(y) << 1) + interleave(x);
  34. }
  35. std::uint32_t encode_3d(std::uint32_t x, std::uint32_t y, std::uint32_t z)
  36. {
  37. auto interleave = [](std::uint32_t x) -> std::uint32_t
  38. {
  39. x &= 0x000003ff;
  40. x = (x ^ (x << 16)) & 0xff0000ff;
  41. x = (x ^ (x << 8)) & 0x0300f00f;
  42. x = (x ^ (x << 4)) & 0x030c30c3;
  43. x = (x ^ (x << 2)) & 0x09249249;
  44. return x;
  45. };
  46. return interleave(x) | (interleave(y) << 1) | (interleave(z) << 2);
  47. }
  48. std::array<uint32_t, 2> decode_2d(std::uint32_t code)
  49. {
  50. auto unravel = [](std::uint32_t x) -> std::uint32_t
  51. {
  52. x &= 0x55555555;
  53. x = (x ^ (x >> 1)) & 0x33333333;
  54. x = (x ^ (x >> 2)) & 0x0f0f0f0f;
  55. x = (x ^ (x >> 4)) & 0x00ff00ff;
  56. x = (x ^ (x >> 8)) & 0x0000ffff;
  57. return x;
  58. };
  59. return {unravel(code >> 0), unravel(code >> 1)};
  60. }
  61. std::array<uint32_t, 3> decode_3d(std::uint32_t code)
  62. {
  63. auto unravel = [](std::uint32_t x) -> std::uint32_t
  64. {
  65. x &= 0x09249249;
  66. x = (x ^ (x >> 2)) & 0x030c30c3;
  67. x = (x ^ (x >> 4)) & 0x0300f00f;
  68. x = (x ^ (x >> 8)) & 0xff0000ff;
  69. x = (x ^ (x >> 16)) & 0x000003ff;
  70. return x;
  71. };
  72. return {unravel(code >> 0), unravel(code >> 1), unravel(code >> 2)};
  73. }
  74. } // namespace morton
  75. } // namespace geom