MortonCode.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Geometry/AABox.h>
  5. JPH_NAMESPACE_BEGIN
  6. class MortonCode
  7. {
  8. public:
  9. /// First converts a floating point value in the range [0, 1] to a 10 bit fixed point integer.
  10. /// Then expands a 10-bit integer into 30 bits by inserting 2 zeros after each bit.
  11. static uint32 sExpandBits(float inV)
  12. {
  13. JPH_ASSERT(inV >= 0.0f && inV <= 1.0f);
  14. uint32 v = uint32(inV * 1023.0f + 0.5f);
  15. JPH_ASSERT(v < 1024);
  16. v = (v * 0x00010001u) & 0xFF0000FFu;
  17. v = (v * 0x00000101u) & 0x0F00F00Fu;
  18. v = (v * 0x00000011u) & 0xC30C30C3u;
  19. v = (v * 0x00000005u) & 0x49249249u;
  20. return v;
  21. }
  22. /// Calculate the morton code for inVector, given that all vectors lie in inVectorBounds
  23. static uint32 sGetMortonCode(Vec3Arg inVector, const AABox &inVectorBounds)
  24. {
  25. // Convert to 10 bit fixed point
  26. Vec3 scaled = (inVector - inVectorBounds.mMin) / inVectorBounds.GetSize();
  27. uint x = sExpandBits(scaled.GetX());
  28. uint y = sExpandBits(scaled.GetY());
  29. uint z = sExpandBits(scaled.GetZ());
  30. return (x << 2) + (y << 1) + z;
  31. }
  32. };
  33. JPH_NAMESPACE_END