Skip to content

Instantly share code, notes, and snippets.

@dwilliamson
Created July 30, 2015 23:50
Show Gist options
  • Save dwilliamson/efe4c2e09ad0c223be8e to your computer and use it in GitHub Desktop.
Save dwilliamson/efe4c2e09ad0c223be8e to your computer and use it in GitHub Desktop.
Faster Sphere Indexing
float3 PositionToOctahedron(float3 position)
{
// Normalize input position to unit sphere to simplify required ops
float3 P = normalize(position);
// Get octant index
float3 side = P >= 0 ? 1 : 0;
float octant_index = side.x + side.y * 2 + side.z * 4;
// Project onto octahedron face, then onto each x/y plane
float2 uv = abs(P.xy) * (1 / dot(1, abs(P)));
return float3(uv, octant_index);
}
uint GetTriangleIndex(float3 uv_face, const uint3 constants)
{
// Scale with subdivision count
float2 uv = uv_face.xy * constants.x;
// Split into integer/fractionals
uint2 uv_i = uint2(uv);
float2 uv_f = uv - uv_i;
// Triangle pairs are grouped so double and offset using diagonal sidedness
uv_i.x *= 2;
uv_i.x = (uv_f.x + uv_f.y > 1) ? uv_i.x + 1 : uv_i.x;
// Map to linear index on a grid
uint face_index = (uint)uv_face.z;
return face_index * constants.z + uv_i.y * constants.y + uv_i.x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment