# View Space From gl_FragCoord

Trying to get the example code for CalcEyeFromWindow() (first one on the page) to work in WebGL, but having no luck.

Paired down the code to the following with some explicit values just in case something is amiss with parameter passing. Visualizing the output on a sphere of unit radius, centered in the view and 3 units from the camera. Using step() in the output to provide sharp color transitions on the sphere.

The current output is black. If I set the step to 0 for X and Y, the transitions for X and Y are centered on the sphere, so it would seem that the problem is at least in part due to the calculation of clipPos.w.

precision highp float;

attribute vec3 a_position;

uniform mat4 u_modelMatrix;
uniform mat4 u_viewMatrix;
uniform mat4 u_projectionMatrix;

void main()
{
gl_Position = u_projectionMatrix * u_viewMatrix * u_modelMatrix * vec4(a_position, 1.0);
}

precision highp float;

uniform mat4 u_inverseProjectionMatrix;
uniform mat4 u_projectionMatrix;

vec3 CalcEyeFromWindow(void)
{
vec3 ndcPos;
// Hard code window-space position at gl_FragCoord
// Hard code viewport dimensions
ndcPos.xy = (2.0 * gl_FragCoord.xy) / vec2(1000, 500) - 1.;
// Hard code clipping depths
ndcPos.z = (2.0 * gl_FragCoord.z - 1. - 4.) / (4. - 1.);

vec4 clipPos;
clipPos.w = u_projectionMatrix[3][2] /
(ndcPos.z - (u_projectionMatrix[2][2] / u_projectionMatrix[2][3]));
clipPos.xyz = ndcPos * clipPos.w;

return (u_inverseProjectionMatrix * clipPos).xyz;
}

void main() {
// Step to clarify position
gl_FragColor = vec4(step(vec3(.5, .5, 2.2), CalcEyeFromWindow() *
vec3(1,1,-1)), 1.);
}

ndcPos.z = (2.0 * gl_FragCoord.z - 0.0 - 1.0) / (1.0 - 0.0);

ndcPos.z = 2.0 * gl_FragCoord.z - 1.0;