# 3D direction to array index conversion

## Recommended Posts

spek    1240
Allright, I have some Batman riddle here. I'm planning to code some sort of low-res cubemap into a simple 1D array. Thus, 6 faces, each face 4x4 values = array with 96 elements. I'm not sure how to order yet, but that might depend on the answer on the next question.

For a certain direction, I like to find the corresponding cubemap array index. Thus:
function getSample( sourcePosition, targetPosition ) : single;	dir	= normalize( targetPosition - sourcePosition );	result	= cubemap[ directionToCubeMapIndex( dir ) ];

Now the question is, how to make such a conversion function?

By the way, I'm not doing anything graphical or with shaders. Just want to store data from all directions in a cubemap like structure, then access it in a quick & simple way. This function will be called many many times, so speed is the key.

Rick

##### Share on other sites
Zipster    2365
You could use some tests like this to see which side the direction is facing:

+X -> (v.y < v.x) && (v.y > -v.x)
-X -> (v.y > v.x) && (v.y < -v.x)
+Y -> (v.x < v.y) && (v.x > -v.y)
-Y -> (v.x > v.y) && (v.x < -v.y)
+Z -> (v.x < v.z) && (v.x > -v.z)
-Z -> (v.x > v.z) && (v.x < -v.z)

And assign each side an index. You can then extend or shrink the vector onto the unit cube:

±X -> 0.5 * v / abs(v.x)
±Y -> 0.5 * v / abs(v.y)
±Z -> 0.5 * v / abs(v.z)

The other two dimensions can then be used to index into a flattened 4x4 array. So if the direction faces the +Y face, you'd use the XZ coordinates within the unit square centered at (0,0), i.e. if v.x = 0.4 and v.z = -0.4, then i = (0.4 + 0.5) * 4 = 3 and j = (-0.4 + 0.5) * 4 = 0. The final index would be (2 * 16) + (0 * 4) + 3 = 35.

Disclaimer: Late, off the top of my head :)

##### Share on other sites
spek    1240
Thank you! I didn't have time to try it yet, but these directions can surely help me. By the way, would a videocard use a similar method when working with cubemaps
float3 direction = reflection or somethingfloat3 pixel = texCUBE( myCubeMap, direction.xyz );

I thought GPU's were bad at branching, which made me think it's using a method without if/else's... Or maybe a cubemap lookup is hardware accelerated?

Cheers,
Rick