MortonCode.h 1.2 KB

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