💿🐜 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.

85 lines
2.2 KiB

  1. /*
  2. * Copyright (C) 2020 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 morton {
  21. std::uint32_t encode_2d(std::uint32_t x, std::uint32_t y)
  22. {
  23. auto interleave = [](std::uint32_t x) -> std::uint32_t
  24. {
  25. x &= 0x0000ffff;
  26. x = (x ^ (x << 8)) & 0x00ff00ff;
  27. x = (x ^ (x << 4)) & 0x0f0f0f0f;
  28. x = (x ^ (x << 2)) & 0x33333333;
  29. x = (x ^ (x << 1)) & 0x55555555;
  30. return x;
  31. };
  32. return (interleave(y) << 1) + interleave(x);
  33. }
  34. std::uint32_t encode_3d(std::uint32_t x, std::uint32_t y, std::uint32_t z)
  35. {
  36. auto interleave = [](std::uint32_t x) -> std::uint32_t
  37. {
  38. x &= 0x000003ff;
  39. x = (x ^ (x << 16)) & 0xff0000ff;
  40. x = (x ^ (x << 8)) & 0x0300f00f;
  41. x = (x ^ (x << 4)) & 0x030c30c3;
  42. x = (x ^ (x << 2)) & 0x09249249;
  43. return x;
  44. };
  45. return interleave(x) | (interleave(y) << 1) | (interleave(z) << 2);
  46. }
  47. std::array<uint32_t, 2> decode_2d(std::uint32_t code)
  48. {
  49. auto unravel = [](std::uint32_t x) -> std::uint32_t
  50. {
  51. x &= 0x55555555;
  52. x = (x ^ (x >> 1)) & 0x33333333;
  53. x = (x ^ (x >> 2)) & 0x0f0f0f0f;
  54. x = (x ^ (x >> 4)) & 0x00ff00ff;
  55. x = (x ^ (x >> 8)) & 0x0000ffff;
  56. return x;
  57. };
  58. return {unravel(code >> 0), unravel(code >> 1)};
  59. }
  60. std::array<uint32_t, 3> decode_3d(std::uint32_t code)
  61. {
  62. auto unravel = [](std::uint32_t x) -> std::uint32_t
  63. {
  64. x &= 0x09249249;
  65. x = (x ^ (x >> 2)) & 0x030c30c3;
  66. x = (x ^ (x >> 4)) & 0x0300f00f;
  67. x = (x ^ (x >> 8)) & 0xff0000ff;
  68. x = (x ^ (x >> 16)) & 0x000003ff;
  69. return x;
  70. };
  71. return {unravel(code >> 0), unravel(code >> 1), unravel(code >> 2)};
  72. }
  73. } // namespace morton