1#ifdef SPHERE_MAP
2#define ENVMAP sampler2D
3#define TEXENV texture2D
4#else
5#define ENVMAP samplerCube
6#define TEXENV textureCube
7#endif
8
9// converts a normalized direction vector
10// into a texture coordinate for fetching
11// texel from a sphere map
12vec2 Optics_SphereCoord(in vec3 dir){
13    float dzplus1 = dir.z + 1.0;
14
15    // compute 1/2p
16    // NOTE: this simplification only works if dir is normalized.
17    float inv_two_p = 1.414 * sqrt(dzplus1);
18    //float inv_two_p = sqrt(dir.x * dir.x + dir.y * dir.y + dzplus1 * dzplus1);
19    inv_two_p *= 2.0;
20    inv_two_p = 1.0 / inv_two_p;
21
22    // compute texcoord
23    return (dir.xy * vec2(inv_two_p)) + vec2(0.5);
24}
25
26vec4 Optics_GetEnvColor(in ENVMAP envMap, in vec3 dir){
27    #ifdef SPHERE_MAP
28    return texture2D(envMap, Optics_SphereCoord(dir));
29    #else
30    return textureCube(envMap, dir);
31    #endif
32}